Backtestspydanticrun-20260930-144322#13661

Issue #13661 Merged fix PR #13668 Run 30 Sep 2026 · run-20260930-144322 pydantic/pydantic

Runtime by_name/by_alias arguments dropped by model_validator(mode="wrap")

Worse

The merged fix was judged better than our patch.

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

The Rust changes are functionally identical. Both add `by_alias`/`by_name` fields to `InternalValidator`, capture them from `extra` in `new`, and forward them in both `validate` and `validate_assignment` instead of hardcoding `None`. This fixes the root cause: the runtime alias settings were being reset when the wrap handler re-entered validation. The only difference in the Rust code is where the struct fields sit, which does not matter. The decision therefore rests on the tests.

Patch B adds a parametrized test in `test_aliases.py`. It closely mirrors the issue (alias_generator, TypeAdapter, wrap model validator) and covers all four by_alias/by_name × input combinations in both python and json modes. It is clean and well placed, and it would fail before the fix.

Patch A's first test covers the same four combinations with a wrap model validator via `model_validate`. It also exercises the nested case, where an outer model's field-level wrap validator (which also goes through `InternalValidator`) passes data to an inner model. That checks propagation through a second wrap-handler path that Patch B does not test. Patch A's second test checks context, strict, extra and from_attributes propagation through wrap handlers. These were likely already forwarded before the change, so that test is neutral hardening rather than a regression test for this issue. It adds some noise but no risk.

Neither patch tests the assignment path. On balance, Patch A's tests cover more of the code the fix touches (both model and field wrap handlers, including nesting), while Patch B adds json-mode coverage of the same path. This is a narrow edge, and I give it to A.

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

7m 20s15 turns

Wall-clock time in the container

Full test suite

No new failures

12,373 passed · 500 skipped · 12,873 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

48vs 89 merged

Changed lines, ours vs merged

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

The handler passed to a wrap-mode model validator appears to silently drop the passed-in by_name/by_alias arguments from the top-level validate_python methods.

Example Code

from typing import Self
from pydantic import BaseModel, TypeAdapter, ValidatorFunctionWrapHandler, model_validator

CFG = {"alias_generator": lambda s: s.replace("_", "-"), "validate_by_name": True}

class Plain(BaseModel):
    model_config = CFG
    build_depends: list[str] = []

class Wrapped(BaseModel):
    model_config = CFG
    build_depends: list[str] = []

    @model_validator(mode="wrap")
    @classmethod
    def _noop(cls, data, handler: ValidatorFunctionWrapHandler) -> Self:
        return handler(data)

data = {"build_depends": ["x"]}  # field name, not the alias
print(TypeAdapter(Plain).validate_python(data, by_alias=True, by_name=False))    # build_depends=[]    correct
print(TypeAdapter(Wrapped).validate_python(data, by_alias=True, by_name=False))  # build_depends=['x'] wrong

Python, Pydantic & OS Version

pydantic version: 2.13.4
        pydantic-core version: 2.46.4
          pydantic-core build: profile=release pgo=false
               python version: 3.14.6 (main, Jun 23 2026, 15:18:23) [Clang 22.1.3 ]
                     platform: Linux-6.18.33.2-microsoft-standard-WSL2-x86_64-with-glibc2.39
             related packages: typing_extensions-4.16.0
                       commit: unknown

The two patches

Our patch+44 −4
pydantic-core/src/validators/generator.rsindex 7529248d..702825c4 100644@@ -234,6 +234,8 @@ pub struct InternalValidator {     hide_input_in_errors: bool,     validation_error_cause: bool,     cache_str: jiter::StringCacheMode,+    by_alias: Option<bool>,+    by_name: Option<bool>, }  impl fmt::Debug for InternalValidator {@@ -268,6 +270,8 @@ impl InternalValidator {             hide_input_in_errors,             validation_error_cause,             cache_str: extra.cache_str,+            by_alias: extra.by_alias,+            by_name: extra.by_name,         }     } @@ -286,8 +290,8 @@ impl InternalValidator {             from_attributes: self.from_attributes,             context: self.context.as_ref().map(|data| data.bind(py)),             cache_str: self.cache_str,-            by_alias: None,-            by_name: None,+            by_alias: self.by_alias,+            by_name: self.by_name,         };         let mut state = ValidationState::new(             extra,@@ -329,8 +333,8 @@ impl InternalValidator {             from_attributes: self.from_attributes,             context: self.context.as_ref().map(|data| data.bind(py)),             cache_str: self.cache_str,-            by_alias: None,-            by_name: None,+            by_alias: self.by_alias,+            by_name: self.by_name,         };         let mut state = ValidationState::new(             extra,tests/test_aliases.pyindex c26efb28..c1b63f75 100644@@ -1,3 +1,4 @@+import json from contextlib import AbstractContextManager from contextlib import nullcontext as does_not_raise from inspect import signature@@ -15,8 +16,10 @@ from pydantic import (     ConfigDict,     Field,     PydanticUserError,+    TypeAdapter,     ValidationError,     computed_field,+    model_validator, )  @@ -876,6 +879,39 @@ def test_user_error_on_validation_methods() -> None:         Model.model_validate_strings("{'my_alias': 1}", by_alias=False, by_name=False)  +@pytest.mark.parametrize(+    'by_alias,by_name,data,expected',+    [+        (True, False, {'build_depends': ['x']}, []),+        (True, False, {'build-depends': ['x']}, ['x']),+        (False, True, {'build-depends': ['x']}, []),+        (False, True, {'build_depends': ['x']}, ['x']),+    ],+)+@pytest.mark.parametrize('mode', ['python', 'json'])+def test_runtime_alias_settings_with_wrap_model_validator(+    by_alias: bool, by_name: bool, data: dict[str, Any], expected: list[str], mode: str+) -> None:+    """Runtime `by_alias`/`by_name` must be propagated through the handler of a wrap model validator."""++    class Model(BaseModel):+        model_config = ConfigDict(alias_generator=lambda s: s.replace('_', '-'), validate_by_name=True)++        build_depends: list[str] = []++        @model_validator(mode='wrap')+        @classmethod+        def _noop(cls, data: Any, handler: Any) -> Any:+            return handler(data)++    ta = TypeAdapter(Model)+    if mode == 'python':+        m = ta.validate_python(data, by_alias=by_alias, by_name=by_name)+    else:+        m = ta.validate_json(json.dumps(data), by_alias=by_alias, by_name=by_name)+    assert m.build_depends == expected++ @pytest.mark.parametrize(     'config,runtime,expected',     [ 
Merged fix · PR #13668+85 −4
pydantic-core/src/validators/generator.rsindex 7529248d3..a83527dfe 100644@@ -225,6 +225,8 @@ pub struct InternalValidator {     extra_behavior: Option<ExtraBehavior>,     from_attributes: Option<bool>,     context: Option<Py<PyAny>>,+    by_alias: Option<bool>,+    by_name: Option<bool>,     field_name: Option<Py<PyString>>,     self_instance: Option<Py<PyAny>>,     recursion_guard: RecursionState,@@ -259,6 +261,8 @@ impl InternalValidator {             extra_behavior: extra.extra_behavior,             from_attributes: extra.from_attributes,             context: extra.context.map(|d| d.clone().unbind()),+            by_alias: extra.by_alias,+            by_name: extra.by_name,             field_name: state.field_name().map(|d| d.clone().unbind()),             self_instance: state.self_instance.map(|d| d.clone().unbind()),             recursion_guard: state.recursion_guard.clone(),@@ -286,8 +290,8 @@ impl InternalValidator {             from_attributes: self.from_attributes,             context: self.context.as_ref().map(|data| data.bind(py)),             cache_str: self.cache_str,-            by_alias: None,-            by_name: None,+            by_alias: self.by_alias,+            by_name: self.by_name,         };         let mut state = ValidationState::new(             extra,@@ -329,8 +333,8 @@ impl InternalValidator {             from_attributes: self.from_attributes,             context: self.context.as_ref().map(|data| data.bind(py)),             cache_str: self.cache_str,-            by_alias: None,-            by_name: None,+            by_alias: self.by_alias,+            by_name: self.by_name,         };         let mut state = ValidationState::new(             extra,tests/test_validators.pyindex 0a5bc5f04..7e9f47137 100644@@ -3177,3 +3177,80 @@ def test_model_validate_json_default_value_validator_with_validation_info() -> N     f2 = Foo.model_validate_json('{"field1": 1}', context='context')      assert f1.field == f2.field == 2+++def test_wrap_validator_forwards_by_alias_by_name() -> None:+    """https://github.com/pydantic/pydantic/issues/13661"""++    class Inner(BaseModel):+        model_config = ConfigDict(validate_by_name=True)++        build_depends: list[str] = Field(default=[], alias='build-depends')++        @model_validator(mode='wrap')+        @classmethod+        def _wrap(cls, data: Any, handler: ValidatorFunctionWrapHandler) -> Any:+            return handler(data)++    class Outer(BaseModel):+        inner: Inner++        @field_validator('inner', mode='wrap')+        @classmethod+        def _wrap(cls, v: Any, handler: ValidatorFunctionWrapHandler) -> Any:+            return handler(v)++    by_name = {'build_depends': ['x']}+    by_alias = {'build-depends': ['x']}++    assert Inner.model_validate(by_name, by_alias=True, by_name=False).build_depends == []+    assert Inner.model_validate(by_alias, by_alias=True, by_name=False).build_depends == ['x']+    assert Inner.model_validate(by_name, by_alias=False, by_name=True).build_depends == ['x']+    assert Inner.model_validate(by_alias, by_alias=False, by_name=True).build_depends == []++    assert Outer.model_validate({'inner': by_name}, by_alias=True, by_name=False).inner.build_depends == []+    assert Outer.model_validate({'inner': by_alias}, by_alias=False, by_name=True).inner.build_depends == []+++def test_wrap_validator_forwards_runtime_settings() -> None:+    class Inner(BaseModel):+        a: int++        @model_validator(mode='wrap')+        @classmethod+        def _wrap(cls, data: Any, handler: ValidatorFunctionWrapHandler, info: ValidationInfo) -> Any:+            assert info.context == 'ctx'+            return handler(data)++        @field_validator('a', mode='wrap')+        @classmethod+        def _wrap_a(cls, v: Any, handler: ValidatorFunctionWrapHandler, info: ValidationInfo) -> Any:+            assert info.context == 'ctx'+            return handler(v)++    class Outer(BaseModel):+        inner: Inner++        @field_validator('inner', mode='wrap')+        @classmethod+        def _wrap(cls, v: Any, handler: ValidatorFunctionWrapHandler) -> Any:+            return handler(v)++    # strict:+    assert Outer.model_validate({'inner': {'a': '1'}}, context='ctx').inner.a == 1+    with pytest.raises(ValidationError, match='Input should be a valid integer'):+        Outer.model_validate({'inner': {'a': '1'}}, strict=True, context='ctx')++    # extra:+    m = Outer.model_validate({'inner': {'a': 1, 'b': 2}}, extra='allow', context='ctx')+    assert m.inner.model_extra == {'b': 2}+    with pytest.raises(ValidationError, match='Extra inputs are not permitted'):+        Outer.model_validate({'inner': {'a': 1, 'b': 2}}, extra='forbid', context='ctx')++    # from_attributes:+    class InnerObj:+        a = 1++    with pytest.raises(ValidationError, match='Input should be a valid dictionary'):+        Outer.model_validate({'inner': InnerObj()}, context='ctx')+    assert Outer.model_validate({'inner': InnerObj()}, from_attributes=True, context='ctx').inner.a == 1 

What the agent reported

Fixed: a @model_validator(mode="wrap") handler now keeps the by_alias/by_name values you pass to validate_python/validate_json. The new regression test passes with the change, and 4 of its 8 cases failed before it.

What was wrong: when a wrap validator calls handler(data), pydantic-core validates again through an internal object called InternalValidator (in pydantic-core/src/validators/generator.rs). That object copied settings like strict, context and from_attributes from the current run, but always set by_alias and by_name to None. So the handler fell back to the model config (validate_by_name=True), and {"build_depends": ["x"]} was accepted even with by_alias=True, by_name=False.

What I changed:

  • The fix (pydantic-core/src/validators/generator.rs): InternalValidator now stores by_alias and by_name when it is created and passes them on in both validate() and validate_assignment(). Nothing else changed in production code.
  • Side effect: generator validators use the same object, so items validated lazily inside a generator now also respect these settings. That is the expected behavior.
  • Other places: the reviewer checked every other spot that sets these values to None. They are entry points or URL helpers that never receive runtime values, so nothing else drops them.
  • Build: I rebuilt the extension with maturin develop --release. uv.lock, pyproject.toml and Cargo.lock are unchanged. cargo fmt and cargo clippy aren't installed for the toolchain here, so neither was run; the code compiled cleanly.

Regression test: test_runtime_alias_settings_with_wrap_model_validator in tests/test_aliases.py uses the report's model, with validate_python and validate_json, and four cases:

  • the reported case (by_alias=True, by_name=False with the field name gives []);
  • the reverse settings (by_alias=False, by_name=True with the alias gives []);
  • two cases with allowed input that fill the field, to check the fix doesn't reject too much.

Test results:

  • Before the fix: 4 of the 8 cases failed with assert ['x'] == [].
  • After the fix: ./bt-test tests/test_aliases.py tests/test_validators.py tests/test_model_validator.py tests/test_main.py tests/test_types.py gave 852 passed, 60 skipped, 4 xfailed and 1 failed.
  • The failure is test_validators.py::test_v1_validator_deprecated, which expects the warning's file path to be /workspace/tests/test_validators.py but gets /work/tests/test_validators.py. /work is a symlink to /workspace in this container, so this comes from the environment, not the fix. I didn't run it without the fix to confirm.
  • pydantic-core tests: test_function.py, test_generator.py, test_model_fields.py and test_model.py gave 448 passed and 2 skipped.
  • Your example: now prints build_depends=[] for both Plain and Wrapped.

Requirements:

  1. handler in a wrap model validator must respect runtime by_alias/by_name from validate_python: fixed, and covered by the new test.
  2. The report's example should give build_depends=[] for Wrapped, like Plain: fixed; that exact case is in the test and the script output confirms it.
  3. "The top-level validate_python methods": the fix is in the shared handler, so it also applies to validate_json (tested) and validate_strings (not tested).

Both changes are left uncommitted and no scratch files were added.