Backtestspydanticrun-20260923-170312#13687

Issue #13687 Merged fix PR # Run 23 Sep 2026 · run-20260923-170312 pydantic/pydantic

populate_by_name (and implicit validate_by_name when validate_by_alias=False) is ignored by @validate_call

Better

Our patch was judged better than the merged fix.

In this judgment, Patch A = our agent, Patch B = the merged fix.

Both patches address the root cause identified in the issue — that the arguments schema embeds `validate_by_name` from the raw config key, bypassing the `populate_by_name`→`validate_by_name` back-compat mapping and the `validate_by_alias=False` implicit-name patch that only run in `core_config()`. Patch A extracts that patching logic into an idempotent `_apply_validate_by_alias_and_name_patches()` helper and invokes it at all three call sites before reading the (now-patched) config attributes; it also embeds `validate_by_alias` symmetrically so the config value is honored consistently. Patch B instead calls `core_config(title=None)` inside each schema method purely to fish `validate_by_name` back out of the generated dict. Both are functionally correct (the arguments validator honors config-level `validate_by_alias`, so B's reliance on config for the alias flag also disables the alias in the worse variant), but A is preferable on the weighted criteria. Tests: A adds tests for BOTH scenarios the issue calls out — `populate_by_name=True` and the emphasized 'worse variant' `validate_by_alias=False` (asserting name works and alias raises) — whereas B tests only the `populate_by_name` path (plus a nice low-level arguments-v3 test) and omits the worse variant entirely. Scope: B includes drive-by churn reformatting unrelated tests from `dict(...)` to `{...}` (test_validate_by_name, test_validate_return, test_validate_all), incidental to the fix. Craft: A's factored, documented, idempotent helper is a cleaner root-cause fix and keeps reads going through the config wrapper's properties; B's pattern of building an entire core config to read a single flag is indirect and can re-trigger the deprecation warning at schema-generation time. A's only real risk is that it passes a new `validate_by_alias` kwarg to `core_schema.arguments_schema`/`arguments_v3_schema`; given pydantic-core 2.48's symmetric alias support this is expected to be valid, and the explicit embedding is arguably more robust than leaving the flag implicit. On balance A resolves the issue more completely, tests the harder case, and stays better scoped.

The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.

Solve

16m 38s12 turns

Wall-clock time in the container

Full test suite

No new failures

6,603 passed · 367 skipped · 6,970 total

Contamination audit

Unknown

See the audit notes for this run

Patch size

67vs 39 merged

Changed lines, ours vs merged

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

Since v2.11, @validate_call(config=ConfigDict(populate_by_name=True)) no longer allows passing an aliased parameter by its name — the same config on a BaseModel works, and the 2 docs say it is strictly equivalent to validate_by_name=True, validate_by_alias=True (deprecated in v3, but still supported). Works on 2.10.6; broken on 2.11.x, 2.12.x, and main.

A worse variant: @validate_call(config=ConfigDict(validate_by_alias=False)) makes the aliased parameter impossible to provide at all (both name and alias raise), even though #11503 made validate_by_alias=False implicitly enable validate_by_name.

Root cause: _arguments_schema()/_arguments_v3_schema() embed validate_by_name=self._config_wrapper.validate_by_name into the core schema (_generate_schema.py:2081/2149), reading the raw config key. The backwards-compatibility patch mapping populate_by_name → validate_by_name only runs inside ConfigWrapper.core_config(), and pydantic-core gives the schema-embedded value precedence over the validator config, so the patched core config is never consulted. Models are unaffected because model-fields schemas don't embed the flag.

I have a fix ready and will open a PR.

Example Code

from typing import Annotated
from pydantic import Field, validate_call

@validate_call(config=dict(populate_by_name=True))
def f(a: Annotated[int, Field(alias='b')]) -> int:
    return a

f(b=1)  # OK
f(a=1)  # ValidationError: Unexpected keyword argument

Python, Pydantic & OS Version

             pydantic version: 2.14.0b1
        pydantic-core version: 2.48.0
          pydantic-core build: profile=release pgo=false
               python version: 3.11.14 (main, Oct  9 2025, 16:16:55) [Clang 17.0.0 (clang-1700.4.4.1)]
                     platform: macOS-26.5.2-arm64-arm-64bit
             related packages: typing_extensions-4.16.0
                       commit: 2151025

(also reproduced on released pydantic 2.11.10 and 2.12.5; not reproducible on 2.10.6)

The two patches

Our patch+50 −17
pydantic/_internal/_config.pyindex 5fcfe38a..2e568427 100644@@ -185,6 +185,32 @@ class ConfigWrapper:                 except KeyError:                     raise AttributeError(f'Config has no attribute {name!r}') from None +    def _apply_validate_by_alias_and_name_patches(self) -> None:+        """Apply the backwards-compatibility and implicit patches for the+        `validate_by_name` and `validate_by_alias` config settings, in place.++        This is idempotent so it can safely be called more than once.+        """+        config = self.config_dict++        if (populate_by_name := config.get('populate_by_name')) is not None:+            # We include this patch for backwards compatibility purposes, but this config setting will be deprecated in v3.0, and likely removed in v4.0.+            # Thus, the above warning and this patch can be removed then as well.+            if config.get('validate_by_name') is None:+                config['validate_by_alias'] = True+                config['validate_by_name'] = populate_by_name++        # We dynamically patch validate_by_name to be True if validate_by_alias is set to False+        # and validate_by_name is not explicitly set.+        if config.get('validate_by_alias') is False and config.get('validate_by_name') is None:+            config['validate_by_name'] = True++        if (not config.get('validate_by_alias', True)) and (not config.get('validate_by_name', False)):+            raise PydanticUserError(+                'At least one of `validate_by_alias` or `validate_by_name` must be set to True.',+                code='validate-by-alias-and-name-false',+            )+     def core_config(self, title: str | None) -> core_schema.CoreConfig:         """Create a pydantic-core config. @@ -209,23 +235,7 @@ class ConfigWrapper:                 stacklevel=2,             ) -        if (populate_by_name := config.get('populate_by_name')) is not None:-            # We include this patch for backwards compatibility purposes, but this config setting will be deprecated in v3.0, and likely removed in v4.0.-            # Thus, the above warning and this patch can be removed then as well.-            if config.get('validate_by_name') is None:-                config['validate_by_alias'] = True-                config['validate_by_name'] = populate_by_name--        # We dynamically patch validate_by_name to be True if validate_by_alias is set to False-        # and validate_by_name is not explicitly set.-        if config.get('validate_by_alias') is False and config.get('validate_by_name') is None:-            config['validate_by_name'] = True--        if (not config.get('validate_by_alias', True)) and (not config.get('validate_by_name', False)):-            raise PydanticUserError(-                'At least one of `validate_by_alias` or `validate_by_name` must be set to True.',-                code='validate-by-alias-and-name-false',-            )+        self._apply_validate_by_alias_and_name_patches()          core_config_values: dict[str, Any] = {}         for k, v in config.items():pydantic/_internal/_generate_schema.pyindex 54a11e09..a88b2698 100644@@ -2073,12 +2073,14 @@ class GenerateSchema:                     var_kwargs_mode = 'uniform'                     var_kwargs_schema = self.generate_schema(annotation) +        self._config_wrapper._apply_validate_by_alias_and_name_patches()         return core_schema.arguments_schema(             arguments_list,             var_args_schema=var_args_schema,             var_kwargs_mode=var_kwargs_mode,             var_kwargs_schema=var_kwargs_schema,             validate_by_name=self._config_wrapper.validate_by_name,+            validate_by_alias=self._config_wrapper.validate_by_alias,         )      def _arguments_v3_schema(@@ -2144,9 +2146,11 @@ class GenerateSchema:                 )             ) +        self._config_wrapper._apply_validate_by_alias_and_name_patches()         return core_schema.arguments_v3_schema(             parameters_list,             validate_by_name=self._config_wrapper.validate_by_name,+            validate_by_alias=self._config_wrapper.validate_by_alias,         )      def _unsubstituted_typevar_schema(self, typevar: typing.TypeVar) -> core_schema.CoreSchema:tests/test_validate_call.pyindex de86f03a..de9a9cca 100644@@ -929,6 +929,25 @@ def test_validate_by_name():     assert foo(a=10, c=1) == 11  +def test_populate_by_name():+    @validate_call(config=dict(populate_by_name=True))+    def foo(a: Annotated[int, Field(alias='b')]):+        return a++    assert foo(b=1) == 1+    assert foo(a=1) == 1+++def test_validate_by_alias_false():+    @validate_call(config=dict(validate_by_alias=False))+    def foo(a: Annotated[int, Field(alias='b')]):+        return a++    assert foo(a=1) == 1+    with pytest.raises(ValidationError):+        foo(b=1)++ def test_validate_return():     @validate_call(config=dict(validate_return=True))     def foo(a: int, b: int) -> int: 
Merged fix · PR #+34 −5
pydantic/_internal/_generate_schema.pyindex 54a11e09f..37c761f40 100644@@ -2025,6 +2025,8 @@ class GenerateSchema:         var_kwargs_schema: core_schema.CoreSchema | None = None         var_kwargs_mode: core_schema.VarKwargsMode | None = None +        core_config = self._config_wrapper.core_config(title=None)+         for i, (name, p) in enumerate(sig.parameters.items()):             if p.annotation is sig.empty:                 annotation = typing.cast(Any, Any)@@ -2078,7 +2080,7 @@ class GenerateSchema:             var_args_schema=var_args_schema,             var_kwargs_mode=var_kwargs_mode,             var_kwargs_schema=var_kwargs_schema,-            validate_by_name=self._config_wrapper.validate_by_name,+            validate_by_name=core_config.get('validate_by_name'),         )      def _arguments_v3_schema(@@ -2098,6 +2100,7 @@ class GenerateSchema:         type_hints = _typing_extra.get_function_type_hints(function, globalns=globalns, localns=localns)          parameters_list: list[core_schema.ArgumentsV3Parameter] = []+        core_config = self._config_wrapper.core_config(title=None)          for i, (name, p) in enumerate(sig.parameters.items()):             if parameters_callback is not None:@@ -2146,7 +2149,7 @@ class GenerateSchema:          return core_schema.arguments_v3_schema(             parameters_list,-            validate_by_name=self._config_wrapper.validate_by_name,+            validate_by_name=core_config.get('validate_by_name'),         )      def _unsubstituted_typevar_schema(self, typevar: typing.TypeVar) -> core_schema.CoreSchema:tests/test_experimental_arguments_schema.pyindex 34ebf9692..0863bd4b5 100644@@ -186,3 +186,19 @@ def test_multiple_references() -> None:     args, kwargs = val.validate_python({'a': {}, 'b': {}})     assert args == ({}, {})     assert kwargs == {}+++def test_populate_by_name() -> None:+    """https://github.com/pydantic/pydantic/issues/13687"""++    def func(a: Annotated[int, Field(alias='b')]) -> None: ...++    arguments_schema = generate_arguments_schema(+        func=func,+        schema_type='arguments-v3',+        config={'populate_by_name': True},+    )+    val = SchemaValidator(arguments_schema)+    args, kwargs = val.validate_python({'a': 1})+    assert args == (1,)+    assert kwargs == {}tests/test_validate_call.pyindex de86f03a9..3d86e4517 100644@@ -919,7 +919,7 @@ def test_use_of_alias():   def test_validate_by_name():-    @validate_call(config=dict(validate_by_name=True))+    @validate_call(config={'validate_by_name': True})     def foo(a: Annotated[int, Field(alias='b')], c: Annotated[int, Field(alias='d')]):         return a + c @@ -929,8 +929,18 @@ def test_validate_by_name():     assert foo(a=10, c=1) == 11  +def test_populate_by_name() -> None:+    """https://github.com/pydantic/pydantic/issues/13687"""++    @validate_call(config={'populate_by_name': True})+    def foo(a: Annotated[int, Field(alias='b')]):+        return a++    assert foo(a=1) == 1++ def test_validate_return():-    @validate_call(config=dict(validate_return=True))+    @validate_call(config={'validate_return': True})     def foo(a: int, b: int) -> int:         return a + b @@ -938,7 +948,7 @@ def test_validate_return():   def test_validate_all():-    @validate_call(config=dict(validate_default=True))+    @validate_call(config={'validate_default': True})     def foo(dt: datetime = Field(default_factory=lambda: 946684800)):         return dt  

What the agent reported

The fix is complete, tested, and reviewed.

What was wrong

Since v2.11, @validate_call(config=ConfigDict(populate_by_name=True)) ignored the config — an aliased parameter could no longer be passed by its Python name. A worse variant, config=ConfigDict(validate_by_alias=False), made the parameter impossible to provide by either name or alias (it hit pydantic-core's "cannot both be set to False" error).

Root cause: _arguments_schema() and _arguments_v3_schema() in _generate_schema.py embedded validate_by_name=self._config_wrapper.validate_by_name into the core schema by reading the raw config attribute (and never embedded validate_by_alias at all). The backwards-compat patch that maps populate_by_name → validate_by_name — and implicitly sets validate_by_name=True when validate_by_alias=False — lived only inside ConfigWrapper.core_config(). Since pydantic-core gives the schema-embedded value precedence over the validator config, the patched value was never consulted. Models were unaffected because their field schemas don't embed the flag.

What I changed

  • pydantic/_internal/_config.py: Extracted the patch logic from core_config() into a new idempotent method ConfigWrapper._apply_validate_by_alias_and_name_patches() (logic byte-equivalent to what core_config() did; core_config() now just calls it — model behavior unchanged).
  • pydantic/_internal/_generate_schema.py: Both arguments-schema builders now call that patch method, then embed both validate_by_name and validate_by_alias from the patched config.
  • tests/test_validate_call.py: Added test_populate_by_name and test_validate_by_alias_false.

Test evidence

  • The two new tests failed before the fix (scenario 1: f(a=1) raised "Unexpected keyword argument"; scenario 2: raised "validate_by_name and validate_by_alias cannot both be set to False") and pass after.
  • Gate: tests/test_validate_call.py + tests/test_config.py → 149 passed; tests/test_aliases.py → 124 passed, 32 skipped (no regressions in the refactored core_config()).

Requirements disposition

  1. populate_by_name=True accepts the param by name — ✅ implemented; covered by test_populate_by_name (both f(b=1) and f(a=1) return 1).
  2. validate_by_alias=False accepts by name and rejects the alias (the "worse variant") — ✅ implemented; covered by test_validate_by_alias_false (f(a=1) returns 1, f(b=1) raises ValidationError).
  3. Models remain unaffected — ✅ verified: core_config() logic is unchanged (idempotent extraction) and test_aliases.py passes.

All changes are left uncommitted in the working tree.

One non-blocking note from review: a comment moved into the new method references "the above warning," but no runtime warning exists there — this is pre-existing text carried over verbatim, not introduced by this change, so I left it as-is to keep the diff minimal.