Backtestspydanticrun-20261009-110034#13661

Issue #13661 Merged fix PR #13668 Run 9 Oct 2026 · run-20261009-110034 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 production fixes are functionally identical. Both add `by_alias` and `by_name` fields to `InternalValidator`, populate them from `extra` in the constructor, and forward them in both code paths that previously hard-coded `None`. That fixes the root cause: a wrap handler or generator re-entering validation through `InternalValidator` lost the runtime alias settings. The only difference is where the struct fields sit, which does not matter. So the patches differ only in their tests.

Patch B's tests are more thorough and more closely tied to the issue:
- They reproduce the issue's scenario directly: `TypeAdapter` with an `alias_generator` and `validate_by_name=True`.
- They check a `Plain` model against a `Wrapped` model for equivalence.
- They cover all three entry points: `validate_python`, `validate_json` and `validate_strings`.
- They check both directions: by_alias without by_name, and by_name without by_alias.
- They cover `model_validate`, a wrap `field_validator` on a nested model, and the generator/`Iterable` path. The generator test exercises the second modified `InternalValidator` method, which Patch A leaves untested.

Patch A's first test covers `model_validate` in both directions plus a nested wrap field validator, which is adequate but narrower. Its second test checks `strict`, `extra`, `from_attributes` and `context`. Those settings were already forwarded before the change, so that test does not guard against this regression and adds little.

Neither patch adds risky scope; Patch B's import changes are minimal. Because Patch B's tests cover more of the changed code, B is better.

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

Wall-clock time in the container

Full test suite

No new failures

12,377 passed · 500 skipped · 12,877 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

139vs 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+134 −5
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_validators.pyindex 0a5bc5f0..2dba330f 100644@@ -1,7 +1,8 @@ import contextlib+import json import re from collections import deque-from collections.abc import Callable+from collections.abc import Callable, Iterable from dataclasses import dataclass from datetime import date, datetime from enum import Enum@@ -3177,3 +3178,127 @@ 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+++_BY_NAME_BY_ALIAS_CONFIG = ConfigDict(alias_generator=lambda s: s.replace('_', '-'), validate_by_name=True)+++def _validate_with_runtime_alias_settings(+    ta: TypeAdapter[Any], data: dict[str, Any], mode: str, *, by_alias: bool, by_name: bool+) -> Any:+    if mode == 'python':+        return ta.validate_python(data, by_alias=by_alias, by_name=by_name)+    elif mode == 'json':+        return ta.validate_json(json.dumps(data), by_alias=by_alias, by_name=by_name)+    else:+        return ta.validate_strings(data, by_alias=by_alias, by_name=by_name)+++@pytest.mark.parametrize('mode', ['python', 'json', 'strings'])+@pytest.mark.parametrize(+    'by_alias,by_name,data',+    [+        (True, False, {'my_field': 'x'}),+        (False, True, {'my-field': 'x'}),+    ],+)+def test_wrap_model_validator_handler_respects_runtime_by_alias_by_name(+    mode: str, by_alias: bool, by_name: bool, data: dict[str, Any]+) -> None:+    """https://github.com/pydantic/pydantic/issues/13661"""++    class Plain(BaseModel):+        model_config = _BY_NAME_BY_ALIAS_CONFIG+        my_field: str++    class Wrapped(BaseModel):+        model_config = _BY_NAME_BY_ALIAS_CONFIG+        my_field: str++        @model_validator(mode='wrap')+        @classmethod+        def _noop(cls, data: Any, handler: ValidatorFunctionWrapHandler) -> Any:+            return handler(data)++    for model in (Plain, Wrapped):+        with pytest.raises(ValidationError) as exc_info:+            _validate_with_runtime_alias_settings(TypeAdapter(model), data, mode, by_alias=by_alias, by_name=by_name)+        assert exc_info.value.errors()[0]['type'] == 'missing'++    valid_key = 'my-field' if by_alias else 'my_field'+    m = _validate_with_runtime_alias_settings(+        TypeAdapter(Wrapped), {valid_key: 'x'}, mode, by_alias=by_alias, by_name=by_name+    )+    assert m.my_field == 'x'+++@pytest.mark.parametrize(+    'by_alias,by_name,data',+    [+        (True, False, {'my_field': 'x'}),+        (False, True, {'my-field': 'x'}),+    ],+)+def test_wrap_model_validator_handler_respects_model_validate_by_alias_by_name(+    by_alias: bool, by_name: bool, data: dict[str, Any]+) -> None:+    class Wrapped(BaseModel):+        model_config = _BY_NAME_BY_ALIAS_CONFIG+        my_field: str++        @model_validator(mode='wrap')+        @classmethod+        def _noop(cls, data: Any, handler: ValidatorFunctionWrapHandler) -> Any:+            return handler(data)++    with pytest.raises(ValidationError) as exc_info:+        Wrapped.model_validate(data, by_alias=by_alias, by_name=by_name)+    assert exc_info.value.errors()[0]['type'] == 'missing'+++@pytest.mark.parametrize(+    'by_alias,by_name,data',+    [+        (True, False, {'my_field': 'x'}),+        (False, True, {'my-field': 'x'}),+    ],+)+def test_wrap_field_validator_handler_respects_runtime_by_alias_by_name(+    by_alias: bool, by_name: bool, data: dict[str, Any]+) -> None:+    class Inner(BaseModel):+        model_config = _BY_NAME_BY_ALIAS_CONFIG+        my_field: str++    class Outer(BaseModel):+        inner: Inner++        @field_validator('inner', mode='wrap')+        @classmethod+        def _noop(cls, value: Any, handler: ValidatorFunctionWrapHandler) -> Any:+            return handler(value)++    with pytest.raises(ValidationError) as exc_info:+        Outer.model_validate({'inner': data}, by_alias=by_alias, by_name=by_name)+    assert exc_info.value.errors()[0]['type'] == 'missing'+    assert exc_info.value.errors()[0]['loc'][0] == 'inner'+++@pytest.mark.parametrize(+    'by_alias,by_name,data',+    [+        (True, False, {'my_field': 'x'}),+        (False, True, {'my-field': 'x'}),+    ],+)+def test_generator_validator_respects_runtime_by_alias_by_name(+    by_alias: bool, by_name: bool, data: dict[str, Any]+) -> None:+    class Inner(BaseModel):+        model_config = _BY_NAME_BY_ALIAS_CONFIG+        my_field: str++    items = TypeAdapter(Iterable[Inner]).validate_python([data], by_alias=by_alias, by_name=by_name)+    with pytest.raises(ValidationError) as exc_info:+        list(items)+    assert exc_info.value.errors()[0]['type'] == 'missing' 
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