Backtestspydanticrun-20261007-130130#13661
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.
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`. The only difference is where the struct fields sit. That fixes the root cause: the wrap handler (and generator item validation) was rebuilding `Extra` with `by_alias: None, by_name: None`. Correctness is therefore a wash, and the decision rests on the tests. Patch A's tests follow the issue closely. They reproduce the alias_generator + `validate_by_name=True` setup and go through `TypeAdapter.validate_python`, `validate_json` and `model_validate`. They are parametrized over a plain model and a wrapped model, so the plain model acts as a control. They also cover a WrapValidator on a field and the generator/Iterable path, which is the other user of `InternalValidator` in `generator.rs`. All of these fail before the fix. Patch B's first test also checks by_alias/by_name for a wrap model validator and a wrap field validator, so it is valid regression coverage, though it omits the JSON path and the generator path. Its second test checks strict, extra, from_attributes and context forwarding. Those settings were already forwarded before the patch, so that test would pass on the old code and adds little evidence about this fix. Patch A's tests cover the fix more fully, including the generator code path the change also touches, so A is slightly 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
5m 40s
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
67vs 89 merged
Changed lines, ours vs merged
The issue
View on GitHubInitial 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: unknownThe two patches
Our patch+63 −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_validators.pyindex 0a5bc5f0..a3585a4e 100644@@ -3177,3 +3177,58 @@ 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+++class _AliasedModel(BaseModel):+ model_config = ConfigDict(alias_generator=lambda s: s.replace('_', '-'), validate_by_name=True)++ build_depends: list[str] = []+++class _WrappedAliasedModel(_AliasedModel):+ @model_validator(mode='wrap')+ @classmethod+ def _noop(cls, data: Any, handler: ValidatorFunctionWrapHandler) -> Any:+ return handler(data)+++@pytest.mark.parametrize('model', [_AliasedModel, _WrappedAliasedModel])+def test_wrap_model_validator_respects_runtime_by_alias_by_name(model: type[_AliasedModel]) -> None:+ """https://github.com/pydantic/pydantic/issues/13661"""+ ta = TypeAdapter(model)++ # Field name is ignored when only validating by alias:+ assert ta.validate_python({'build_depends': ['x']}, by_alias=True, by_name=False).build_depends == []+ assert ta.validate_json('{"build_depends": ["x"]}', by_alias=True, by_name=False).build_depends == []+ assert model.model_validate({'build_depends': ['x']}, by_alias=True, by_name=False).build_depends == []+ assert ta.validate_python({'build-depends': ['x']}, by_alias=True, by_name=False).build_depends == ['x']++ # Alias is ignored when only validating by name:+ assert ta.validate_python({'build-depends': ['x']}, by_alias=False, by_name=True).build_depends == []+ assert ta.validate_json('{"build-depends": ["x"]}', by_alias=False, by_name=True).build_depends == []+ assert ta.validate_python({'build_depends': ['x']}, by_alias=False, by_name=True).build_depends == ['x']+++def test_wrap_field_validator_respects_runtime_by_alias_by_name() -> None:+ def noop(value: Any, handler: ValidatorFunctionWrapHandler) -> Any:+ return handler(value)++ class Outer(BaseModel):+ inner: Annotated[_AliasedModel, WrapValidator(noop)]++ data = {'inner': {'build_depends': ['x']}}+ assert Outer.model_validate(data, by_alias=True, by_name=False).inner.build_depends == []+ assert Outer.model_validate(data, by_alias=False, by_name=True).inner.build_depends == ['x']+++def test_generator_items_respect_runtime_by_alias_by_name() -> None:+ from collections.abc import Iterable++ ta = TypeAdapter(Iterable[_AliasedModel])++ items = list(ta.validate_python([{'build_depends': ['x']}], by_alias=True, by_name=False))+ assert items[0].build_depends == []+ items = list(ta.validate_python([{'build-depends': ['x']}], by_alias=False, by_name=True))+ assert items[0].build_depends == []+ items = list(ta.validate_python([{'build_depends': ['x']}], by_alias=False, by_name=True))+ assert items[0].build_depends == ['x']
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