Backtestspydanticrun-20261027-165153#13965
max_digits whole-digit limit not enforced when a validator precedes Field on Decimal
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
The production changes in both patches are functionally identical: both thread `max_digits` into `decimal_places_validator` from `apply_known_metadata` when both constraints are present, and both replicate pydantic-core's whole-digits rule (max(max_digits - decimal_places, 0), checked against both raw and normalized digit counts). Independent tests confirm both fix every failing scenario. Patch A's inline comments are slightly clearer and it names intermediate variables (`whole_digits`, `normalized_whole_digits`), but that is marginal. The meaningful difference is test coverage. Patch A parametrizes over After/Before/Wrap validators, covers string inputs, negatives, integer input ('12'), exponent notation ('1E1'), trailing zeros ('1.000' must still pass, exercising the normalized-digit path), and distinguishes `decimal_whole_digits` from `decimal_max_digits` for '1234' and '1.234'. It also checks the full error dict matches the core's output and adds a BaseModel test covering both `Annotated[..., Field(...)]` and `= Field(...)` forms. Patch B only tests AfterValidator with four Decimal inputs and never exercises Before/Wrap validators, string inputs, or the trailing-zero/normalization edge. Patch A's tests would catch regressions in more of the paths the issue implies. Both patches are in scope with no churn; A is better on tests, equal elsewhere.
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
8m 17s
Wall-clock time in the container
Full test suite
No new failures
1,124 passed · 34 skipped · 1,158 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
91vs 51 merged
Changed lines, ours vs merged
The issue
View on GitHubInitial Checks
- I confirm that I'm using Pydantic V2
Description
When a validator comes before Field(max_digits=..., decimal_places=...) in Annotated, the constraints are applied by the Python fallback in _validators.py instead of pydantic-core. That fallback never checks the number of digits before the decimal point, so values that the core rejects with decimal_whole_digits are accepted.
Expected: the same decimal_whole_digits error in both cases.
I have a small fix with tests (pass max_digits to decimal_places_validator and apply the core's whole-digits rule there) and would be happy to open a PR if this can be assigned to me.
Example Code
from decimal import Decimal
from typing import Annotated
from pydantic import AfterValidator, Field, TypeAdapter
plain = TypeAdapter(Annotated[Decimal, Field(max_digits=3, decimal_places=2)])
after = TypeAdapter(Annotated[Decimal, AfterValidator(lambda v: v), Field(max_digits=3, decimal_places=2)])
plain.validate_python('12.3') # ValidationError: decimal_whole_digits
after.validate_python('12.3') # Decimal('12.3'), no error
Python, Pydantic & OS Version
pydantic version: 2.14.0
pydantic-core version: 2.50.0
pydantic-core build: profile=release pgo=false
python version: 3.12.15 (main, Oct 6 2026, 02:02:22) [GCC 14.2.0]
platform: Linux-6.18.40.1-microsoft-standard-WSL2-x86_64-with-glibc2.41
related packages: typing_extensions-4.16.0
commit: unknownThe two patches
pydantic/_internal/_known_annotated_metadata.pyindex 6245b429..0c131adb 100644@@ -264,8 +264,12 @@ def apply_known_metadata(annotation: Any, schema: CoreSchema) -> CoreSchema | No else: js_constraint_key = constraint + validator_kwargs = {constraint: value}+ if constraint == 'decimal_places' and schema_update.get('max_digits') is not None:+ # the whole digits check depends on both constraints, see `decimal_places_validator()`+ validator_kwargs['max_digits'] = schema_update['max_digits'] schema = cs.no_info_after_validator_function(- partial(NUMERIC_VALIDATOR_LOOKUP[constraint], **{constraint: value}), schema+ partial(NUMERIC_VALIDATOR_LOOKUP[constraint], **validator_kwargs), schema ) metadata = schema.get('metadata', {}) if (existing_json_schema_updates := metadata.get('pydantic_js_updates')) is not None:pydantic/_internal/_validators.pyindex a63b8db1..1067dcea 100644@@ -395,14 +395,27 @@ def max_digits_validator(x: Any, max_digits: Any) -> Any: raise TypeError(f"Unable to apply constraint 'max_digits' to supplied value {x}") -def decimal_places_validator(x: Any, decimal_places: Any) -> Any:+def decimal_places_validator(x: Any, decimal_places: Any, max_digits: Any = None) -> Any: try:- (decimal_places_, _), (normalized_decimal_places, _) = _extract_decimal_digits_info(x)+ (decimal_places_, num_digits), (normalized_decimal_places, normalized_num_digits) = (+ _extract_decimal_digits_info(x)+ ) if (decimal_places_ > decimal_places) and (normalized_decimal_places > decimal_places): raise PydanticKnownError( 'decimal_max_places', {'decimal_places': decimal_places}, )+ if max_digits is not None:+ # Same rule as in pydantic-core: when both constraints are set,+ # at most `max_digits - decimal_places` digits are allowed before the decimal point.+ max_whole_digits = max(max_digits - decimal_places, 0)+ whole_digits = num_digits - decimal_places_+ normalized_whole_digits = normalized_num_digits - normalized_decimal_places+ if (whole_digits > max_whole_digits) and (normalized_whole_digits > max_whole_digits):+ raise PydanticKnownError(+ 'decimal_whole_digits',+ {'whole_digits': max_whole_digits},+ ) return x except TypeError: raise TypeError(f"Unable to apply constraint 'decimal_places' to supplied value {x}")tests/test_annotated.pyindex 65b8d435..7f9f5f97 100644@@ -18,6 +18,7 @@ from pydantic import ( PydanticUserError, TypeAdapter, ValidationError,+ WrapValidator, ) from pydantic.errors import PydanticSchemaGenerationError from pydantic.fields import PrivateAttr@@ -662,3 +663,70 @@ def test_decimal_constraints_after_annotation( with pytest.raises(ValidationError) as exc_info: ta.validate_python(Decimal(input_value)) assert exc_info.value.errors()[0]['type'] == error_type+++@pytest.mark.parametrize(+ 'validator',+ [AfterValidator(lambda v: v), BeforeValidator(lambda v: v), WrapValidator(lambda v, h: h(v))],+ ids=['after', 'before', 'wrap'],+)+@pytest.mark.parametrize(+ ['input_value', 'error'],+ [+ ('1.23', None),+ ('0.12', None),+ ('9', None),+ # Trailing zeros should not count towards the whole digits:+ ('1.000', None),+ ('12.3', {'type': 'decimal_whole_digits', 'ctx': {'whole_digits': 1}}),+ ('12', {'type': 'decimal_whole_digits', 'ctx': {'whole_digits': 1}}),+ ('1E1', {'type': 'decimal_whole_digits', 'ctx': {'whole_digits': 1}}),+ ('-12.3', {'type': 'decimal_whole_digits', 'ctx': {'whole_digits': 1}}),+ ('1234', {'type': 'decimal_max_digits', 'ctx': {'max_digits': 3}}),+ ('1.234', {'type': 'decimal_max_digits', 'ctx': {'max_digits': 3}}),+ ],+)+def test_decimal_whole_digits_after_annotation(validator: Any, input_value: str, error: Any) -> None:+ """Constraints applied after a validator must behave like the ones enforced by pydantic-core."""+ expected_ta = TypeAdapter(Annotated[Decimal, Field(max_digits=3, decimal_places=2)])+ ta = TypeAdapter(Annotated[Decimal, validator, Field(max_digits=3, decimal_places=2)])++ if error is None:+ assert expected_ta.validate_python(input_value) == Decimal(input_value)+ assert ta.validate_python(input_value) == Decimal(input_value)+ else:+ with pytest.raises(ValidationError) as expected_exc_info:+ expected_ta.validate_python(input_value)+ with pytest.raises(ValidationError) as exc_info:+ ta.validate_python(input_value)+ expected_errors = expected_exc_info.value.errors(include_url=False)+ assert exc_info.value.errors(include_url=False) == expected_errors+ assert len(expected_errors) == 1+ assert expected_errors[0]['type'] == error['type']+ assert expected_errors[0]['ctx'] == error['ctx']+++def test_decimal_whole_digits_after_annotation_model_field() -> None:+ class Model(BaseModel):+ x: Annotated[Decimal, AfterValidator(lambda v: v), Field(max_digits=3, decimal_places=2)]+ y: Annotated[Decimal, AfterValidator(lambda v: v)] = Field(max_digits=3, decimal_places=2)++ with pytest.raises(ValidationError) as exc_info:+ Model(x='12.3', y='12.3')+ assert exc_info.value.errors(include_url=False) == [+ {+ 'type': 'decimal_whole_digits',+ 'loc': ('x',),+ 'msg': 'Decimal input should have no more than 1 digit before the decimal point',+ 'input': '12.3',+ 'ctx': {'whole_digits': 1},+ },+ {+ 'type': 'decimal_whole_digits',+ 'loc': ('y',),+ 'msg': 'Decimal input should have no more than 1 digit before the decimal point',+ 'input': '12.3',+ 'ctx': {'whole_digits': 1},+ },+ ]+ assert Model(x='1.23', y='1.23').y == Decimal('1.23')
pydantic/_internal/_known_annotated_metadata.pyindex 6245b4290..95dc0213f 100644@@ -264,8 +264,12 @@ def apply_known_metadata(annotation: Any, schema: CoreSchema) -> CoreSchema | No else: js_constraint_key = constraint + validator_kwargs = {constraint: value}+ if constraint == 'decimal_places' and schema_update.get('max_digits') is not None:+ # The whole digits limit depends on both constraints, and is checked alongside `decimal_places`:+ validator_kwargs['max_digits'] = schema_update['max_digits'] schema = cs.no_info_after_validator_function(- partial(NUMERIC_VALIDATOR_LOOKUP[constraint], **{constraint: value}), schema+ partial(NUMERIC_VALIDATOR_LOOKUP[constraint], **validator_kwargs), schema ) metadata = schema.get('metadata', {}) if (existing_json_schema_updates := metadata.get('pydantic_js_updates')) is not None:pydantic/_internal/_validators.pyindex a63b8db1b..d9d7b20e8 100644@@ -395,14 +395,25 @@ def max_digits_validator(x: Any, max_digits: Any) -> Any: raise TypeError(f"Unable to apply constraint 'max_digits' to supplied value {x}") -def decimal_places_validator(x: Any, decimal_places: Any) -> Any:+def decimal_places_validator(x: Any, decimal_places: Any, max_digits: Any = None) -> Any: try:- (decimal_places_, _), (normalized_decimal_places, _) = _extract_decimal_digits_info(x)+ (decimal_places_, num_digits), (normalized_decimal_places, normalized_num_digits) = (+ _extract_decimal_digits_info(x)+ ) if (decimal_places_ > decimal_places) and (normalized_decimal_places > decimal_places): raise PydanticKnownError( 'decimal_max_places', {'decimal_places': decimal_places}, )+ if max_digits is not None:+ max_whole_digits = max(max_digits - decimal_places, 0)+ if (num_digits - decimal_places_ > max_whole_digits) and (+ normalized_num_digits - normalized_decimal_places > max_whole_digits+ ):+ raise PydanticKnownError(+ 'decimal_whole_digits',+ {'whole_digits': max_whole_digits},+ ) return x except TypeError: raise TypeError(f"Unable to apply constraint 'decimal_places' to supplied value {x}")tests/types/test_decimal.pyindex 6711fcf8a..33f9ad306 100644@@ -4,7 +4,7 @@ from typing import Annotated import pytest from pydantic_core import SchemaError -from pydantic import AllowInfNan, BaseModel, Field, TypeAdapter, ValidationError+from pydantic import AfterValidator, AllowInfNan, BaseModel, Field, TypeAdapter, ValidationError pos_int_values = 'Inf', '+Inf', 'Infinity', '+Infinity' neg_int_values = '-Inf', '-Infinity'@@ -345,6 +345,34 @@ def test_decimal_validation(mode, type_args, value, result): assert Model(foo=value).foo == result +@pytest.mark.parametrize(+ ['value', 'result'],+ [+ (Decimal('1.23'), Decimal('1.23')),+ (Decimal('12.3'), 'decimal_whole_digits'),+ (Decimal('0.123'), 'decimal_max_places'),+ (Decimal('1234'), 'decimal_max_digits'),+ ],+)+def test_decimal_constraints_python_validators(value: Decimal, result: Decimal | str) -> None:+ """https://github.com/pydantic/pydantic/issues/13965"""++ ta = TypeAdapter(Annotated[Decimal, AfterValidator(lambda v: v), Field(max_digits=3, decimal_places=2)])+ core_ta = TypeAdapter(Annotated[Decimal, Field(max_digits=3, decimal_places=2)])++ if isinstance(result, Decimal):+ assert ta.validate_python(value) == result+ else:+ with pytest.raises(ValidationError) as exc_info:+ ta.validate_python(value)+ with pytest.raises(ValidationError) as core_exc_info:+ core_ta.validate_python(value)++ errors = exc_info.value.errors(include_url=False)+ assert errors[0]['type'] == result+ assert errors == core_exc_info.value.errors(include_url=False)++ @pytest.mark.parametrize( 'value,result', [