Backtestspydanticrun-20261022-024030#13661

Issue #13661 Merged fix PR #13668 Run 22 Oct 2026 · run-20261022-024030 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 B = our agent, Patch A = the merged fix.

The Rust change is byte-for-byte equivalent in both patches: InternalValidator gains by_alias/by_name fields captured from the incoming Extra and threads them into the Extra rebuilt in validate() and validate_assignment() instead of hard-coding None. That is the root cause (the wrap handler and generator item validator rebuild Extra and lost the runtime flags), so correctness is equal and all independent tests pass on both. The difference is the tests. Patch B adds a pydantic-core level test in test_function.py that exercises the wrap function validator directly against a typed_dict schema with all four by_alias/by_name combinations, plus a parametrized pydantic-level test covering TypeAdapter, model_validate, model_validate_json, a nested field-level wrap validator, and the Iterable generator path (which uses the same InternalValidator and was also affected). Patch A adds one targeted test for the wrap paths and a second test asserting strict/extra/from_attributes/context forwarding, which already worked before the change and so does not guard the fix. B's tests are more precise about the regression, cover more of the affected entry points, and test at the layer where the code changed. Scope and craft are otherwise equivalent.

Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.

Solve

5m 13s

Wall-clock time in the container

Full test suite

No new failures

491 passed · 92 skipped · 583 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

98vs 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+94 −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,pydantic-core/tests/validators/test_function.pyindex 32613812..7f423883 100644@@ -1047,3 +1047,31 @@ def test_field_name_preserved_wrap_validator() -> None:     v.validate_python({'f': 1})      assert field_names == [('val1', 'f'), ('val2', 'f')]+++@pytest.mark.parametrize(+    'by_alias,by_name,input_value,expected',+    [+        (True, False, {'field_a': 1}, {}),+        (True, False, {'FieldA': 1}, {'field_a': 1}),+        (False, True, {'field_a': 1}, {'field_a': 1}),+        (False, True, {'FieldA': 1}, {}),+    ],+)+def test_function_wrap_propagates_runtime_by_alias_by_name(by_alias, by_name, input_value, expected):+    """https://github.com/pydantic/pydantic/issues/13661"""++    def f(input_value, handler, _info):+        return handler(input_value)++    inner_schema = core_schema.typed_dict_schema(+        {+            'field_a': core_schema.typed_dict_field(core_schema.int_schema(), required=False, validation_alias='FieldA')+        },+        config=CoreConfig(validate_by_name=True, validate_by_alias=True),+    )+    plain = SchemaValidator(inner_schema)+    wrapped = SchemaValidator(core_schema.with_info_wrap_validator_function(f, inner_schema))++    assert plain.validate_python(input_value, by_alias=by_alias, by_name=by_name) == expected+    assert wrapped.validate_python(input_value, by_alias=by_alias, by_name=by_name) == expectedtests/test_aliases.pyindex c26efb28..73a9b481 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,55 @@ 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,input_key,expected',+    [+        (True, False, 'my_field', None),+        (True, False, 'my_alias', 1),+        (False, True, 'my_field', 1),+        (False, True, 'my_alias', None),+        (True, True, 'my_field', 1),+        (True, True, 'my_alias', 1),+    ],+)+def test_runtime_alias_settings_propagate_through_wrap_validators(+    runtime_by_alias: bool, runtime_by_name: bool, input_key: str, expected: int | None+) -> None:+    """https://github.com/pydantic/pydantic/issues/13661++    Runtime `by_alias`/`by_name` must be honored when validation goes through the+    handler of a wrap validator, or through a generator item validator.+    """++    class Plain(BaseModel):+        model_config = ConfigDict(validate_by_name=True)++        my_field: int | None = Field(default=None, 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)++    data = {input_key: 1}+    kwargs = {'by_alias': runtime_by_alias, 'by_name': runtime_by_name}++    assert TypeAdapter(Plain).validate_python(data, **kwargs).my_field == expected+    assert TypeAdapter(WrappedModel).validate_python(data, **kwargs).my_field == expected+    assert WrappedModel.model_validate(data, **kwargs).my_field == expected+    assert WrappedModel.model_validate_json(json.dumps(data), **kwargs).my_field == expected+    assert Outer.model_validate({'inner': data}, **kwargs).inner.my_field == expected++    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