Backtestspydanticrun-20261003-150343#13661

Issue #13661 Merged fix PR #13668 Run 3 Oct 2026 · run-20261003-150343 pydantic/pydantic

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

Better

Our patch was judged better than the merged fix.

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

Both patches make the same core fix in `pydantic-core/src/validators/generator.rs`. Each adds `by_alias`/`by_name` fields to `InternalValidator`, captures them from `Extra` in `new`, and forwards them in both `validate` and `validate_assignment` instead of hard-coding `None`. This fixes the root cause: the wrap-validator handler and the generator both go through `InternalValidator`. The Rust changes are functionally identical. The only difference is where the struct field is placed; B's spot next to `context` is marginally tidier, but this is cosmetic.

Tests are the deciding difference. Patch A's parametrized test covers four alias/name combinations across several paths:
- `model_validate`, `TypeAdapter.validate_python` and `model_validate_json`, for both a plain model and a model with a wrap `model_validator`.
- A nested field-level wrap validator, for both Python and JSON input.
- Lazy generator validation via `Iterable[...]`, which also uses `InternalValidator` and so is a second regression site fixed by the same change.

Patch B's first test covers the model-wrap and nested field-wrap cases for Python input only. It does not exercise the JSON path or the generator path. B's second test checks context, strict, extra and from_attributes forwarding. Those settings were already propagated before this change, so that test is regression hardening rather than a check that would fail before the fix. It is neutral under the scope criterion.

With the fixes equivalent, A's broader coverage of the affected code paths, including the generator and JSON validation, makes it the somewhat stronger patch.

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 58s

Wall-clock time in the container

Full test suite

No new failures

12,369 passed · 500 skipped · 12,869 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

69vs 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+65 −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..bafc1545 100644@@ -1,3 +1,5 @@+import json+from collections.abc import Iterable from contextlib import AbstractContextManager from contextlib import nullcontext as does_not_raise from inspect import signature@@ -15,8 +17,12 @@ from pydantic import (     ConfigDict,     Field,     PydanticUserError,+    TypeAdapter,     ValidationError,+    ValidatorFunctionWrapHandler,     computed_field,+    field_validator,+    model_validator, )  @@ -904,3 +910,54 @@ def test_serialization_alias_settings(config: bool | None, runtime: bool | None,      model = Model(my_field=1)     assert model.model_dump(by_alias=runtime) == expected+++@pytest.mark.parametrize(+    'runtime_by_alias,runtime_by_name,data,expected',+    [+        (True, False, {'my_field': 1}, 0),+        (True, False, {'my_alias': 1}, 1),+        (False, True, {'my_field': 1}, 1),+        (False, True, {'my_alias': 1}, 0),+    ],+)+def test_runtime_alias_settings_with_wrap_validators(+    runtime_by_alias: bool, runtime_by_name: bool, data: dict[str, int], expected: int+) -> None:+    """Runtime `by_alias`/`by_name` must propagate through wrap validator handlers.++    See https://github.com/pydantic/pydantic/issues/13661.+    """++    class Plain(BaseModel):+        model_config = ConfigDict(validate_by_name=True)++        my_field: int = Field(default=0, alias='my_alias')++    class WrappedModel(Plain):+        @model_validator(mode='wrap')+        @classmethod+        def _noop(cls, data: Any, handler: ValidatorFunctionWrapHandler) -> Any:+            return handler(data)++    class Outer(BaseModel):+        inner: Plain++        @field_validator('inner', mode='wrap')+        @classmethod+        def _noop(cls, value: Any, handler: ValidatorFunctionWrapHandler) -> Any:+            return handler(value)++    kwargs = {'by_alias': runtime_by_alias, 'by_name': runtime_by_name}++    for model in (Plain, WrappedModel):+        assert model.model_validate(data, **kwargs).my_field == expected+        assert TypeAdapter(model).validate_python(data, **kwargs).my_field == expected+        assert model.model_validate_json(json.dumps(data), **kwargs).my_field == expected++    assert Outer.model_validate({'inner': data}, **kwargs).inner.my_field == expected+    assert Outer.model_validate_json(json.dumps({'inner': data}), **kwargs).inner.my_field == expected++    # generators also validate lazily via an internal validator+    items = TypeAdapter(Iterable[Plain]).validate_python([data], **kwargs)+    assert [item.my_field for item in items] == [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