Backtestspydanticrun-20260929-204949#13661
Runtime by_name/by_alias arguments dropped by model_validator(mode="wrap")
The merged fix was judged better than our patch.
In this judgment, Patch A = our agent, Patch B = the merged fix.
The Rust source fix is byte-for-byte equivalent in both patches (add by_alias/by_name to InternalValidator, populate from extra, and forward them instead of hardcoding None). Both resolve the root cause correctly, so the decision rests on tests. Patch A's test faithfully reproduces the issue via TypeAdapter and checks both by_alias/by_name combinations plus positive alias/name cases — solid and well-documented. Patch B's first test covers the same by_alias/by_name matrix but additionally exercises a nested Outer->Inner wrap-validator chain, which is a genuinely broader regression scenario that would also fail before the fix and pass after. That extra nested coverage is a real, relevant edge. B's second test (strict/extra/from_attributes/context) is largely tautological relative to this specific fix since those fields were already forwarded, and its docstring is a leftover '<link>' placeholder — minor craft dings but neutral risk. On balance B's stronger, more directly relevant regression coverage of nested wrap validators tips the decision, given identical fixes.
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
9m 5s19 turns
Wall-clock time in the container
Full test suite
No new failures
12,366 passed · 500 skipped · 12,866 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
53vs 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
pydantic-core/src/validators/generator.rsindex 7529248d..332abf89 100644@@ -224,6 +224,8 @@ pub struct InternalValidator { strict: Option<bool>, extra_behavior: Option<ExtraBehavior>, from_attributes: Option<bool>,+ by_alias: Option<bool>,+ by_name: Option<bool>, context: Option<Py<PyAny>>, field_name: Option<Py<PyString>>, self_instance: Option<Py<PyAny>>,@@ -258,6 +260,8 @@ impl InternalValidator { strict: extra.strict, extra_behavior: extra.extra_behavior, from_attributes: extra.from_attributes,+ by_alias: extra.by_alias,+ by_name: extra.by_name, context: extra.context.map(|d| d.clone().unbind()), field_name: state.field_name().map(|d| d.clone().unbind()), self_instance: state.self_instance.map(|d| d.clone().unbind()),@@ -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..18b6cfe8 100644@@ -15,8 +15,10 @@ from pydantic import ( ConfigDict, Field, PydanticUserError,+ TypeAdapter, ValidationError, computed_field,+ model_validator, ) @@ -862,6 +864,45 @@ def test_validation_alias_settings( assert Model.model_validate({'my_field': 1}, by_alias=runtime_by_alias, by_name=runtime_by_name).my_field == 1 +def test_by_name_and_by_alias_honored_with_wrap_model_validator() -> None:+ """`by_alias`/`by_name` runtime args must be honored even with a `mode='wrap'` model validator.++ Regression test: a wrap validator calling `handler(data)` used to silently drop the+ runtime `by_name`/`by_alias` args passed to `validate_python`.+ """+ config = ConfigDict(alias_generator=lambda s: s.replace('_', '-'), validate_by_name=True)++ class Plain(BaseModel):+ model_config = config++ build_depends: list[str] = []++ class Wrapped(BaseModel):+ model_config = config++ build_depends: list[str] = []++ @model_validator(mode='wrap')+ @classmethod+ def _noop(cls, data, handler):+ return handler(data)++ data = {'build_depends': ['x']} # field name, not the alias 'build-depends'++ # by_alias=True, by_name=False => field name should NOT match, value stays default.+ assert TypeAdapter(Plain).validate_python(data, by_alias=True, by_name=False).build_depends == []+ assert TypeAdapter(Wrapped).validate_python(data, by_alias=True, by_name=False).build_depends == []++ # Positive case: matching by name works for both models.+ assert TypeAdapter(Plain).validate_python(data, by_alias=True, by_name=True).build_depends == ['x']+ assert TypeAdapter(Wrapped).validate_python(data, by_alias=True, by_name=True).build_depends == ['x']++ # Positive case: matching by the alias works for both models.+ alias_data = {'build-depends': ['x']}+ assert TypeAdapter(Plain).validate_python(alias_data, by_alias=True, by_name=False).build_depends == ['x']+ assert TypeAdapter(Wrapped).validate_python(alias_data, by_alias=True, by_name=False).build_depends == ['x']++ def test_user_error_on_validation_methods() -> None: class Model(BaseModel): my_field: int = Field(alias='my_alias')
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
Review confirms the fix is correct, minimal, and complete. Done.
Summary
What was wrong: In the vendored Rust pydantic-core, InternalValidator — the struct backing the handler object passed to a model_validator(mode="wrap") — did not carry the by_alias/by_name validation settings. When a wrap validator called handler(data), the nested validation was reconstructed with by_alias: None, by_name: None hardcoded, so those values fell back to defaults (by_alias=True, by_name=False) and silently discarded whatever was passed to the top-level validate_python(..., by_alias=..., by_name=...).
What I changed (pydantic-core/src/validators/generator.rs):
- Added
by_alias: Option<bool>andby_name: Option<bool>fields toInternalValidator. - Captured them from the incoming
ExtrainInternalValidator::new(mirroringstrict,from_attributes, etc.). - Propagated
self.by_alias/self.by_name(instead ofNone) in bothvalidateandvalidate_assignment.
Then rebuilt the extension with maturin develop --uv --release.
Test evidence:
- Added regression test
tests/test_aliases.py::test_by_name_and_by_alias_honored_with_wrap_model_validator, using the public API from the report. It failed before the fix (assert ['x'] == []) and passes after. - Direct reproduction now returns the correct
build_depends=[]for the wrapped model, while positive cases (match by alias, orby_name=True) still populate the field. - Gate:
./bt-test tests/test_aliases.py tests/test_validators.py→ 301 passed, 32 skipped, 2 xfailed, 1 failed. The single failure,test_v1_validator_deprecated, is unrelated to this change: it asserts a deprecation warning'sfilename == __file__and fails only on the/work→/workspacesymlink path mismatch in the bt-test environment (/work/tests/...vs/workspace/tests/...). It does not exercise pydantic_core validation behavior at all and fails independently of this fix. - Reviewer confirmed the fix is correct, minimal, consistent with sibling fields, and the
validate_assignmentpropagation is a symmetric correct improvement with no regression risk.
Requirements disposition:
- Honor
by_name/by_aliaspassed tovalidate_pythonwhen amode="wrap"model validator is present — implemented, with a regression test that fails before and passes after, and a live reproduction confirming the reported example now yields the correct result.
Changes are left uncommitted in the working tree (pydantic-core/src/validators/generator.rs, tests/test_aliases.py); the rebuilt .so is gitignored. No scratch files.