Backtestspydanticrun-20261007-130130#13868

Issue #13868 Merged fix PR #13873 Run 7 Oct 2026 · run-20261007-130130 pydantic/pydantic

multiple_of=0 still raises ZeroDivisionError for non-native numeric types

Better

Our patch was judged better than the merged fix.

In this judgment, Patch A = our agent, Patch B = the merged fix.

Patch A fixes the cause the issue names: the Python fallback in `_validators.py` divides by `multiple_of` without checking it. A adds `check_multiple_of_constraint`, which runs at schema-build time whenever `multiple_of` falls back to the Python validator. That covers Fraction, timedelta, complex, any other type using `%`, and native types where the constraint can't be pushed down (e.g. `int` with an `AfterValidator`, which A tests). It also guards the same unchecked path in the experimental pipeline. Its edge handling is careful: values not comparable to `0` are compared to their own zero (timedelta), unordered values are checked for `!= zero` (complex), and NaN/inf are rejected. Tests cover Fraction (0, negatives, NaN, inf, Decimal NaN), timedelta, complex, the after-validator int case and the pipeline, plus positive cases confirming valid constraints still work. One minor weakness is that A raises `ValueError` with a slightly different message rather than core's `SchemaError`, but model definition still fails at schema generation as the issue asks. Patch B instead adds native `multiple_of` support for Fraction and timedelta in pydantic-core (Rust validators, `core_schema` types and constraint pairings). That is consistent with how int/float/Decimal raise `SchemaError`, but it is a much broader redesign spanning the Rust core. It also leaves the actual root cause untouched: the Python fallback still performs `x % 0` unchecked, so complex, wrapped/function schemas and other fallback types can still reach it. B's Rust changes add risk and churn, and its tests cover only Fraction and timedelta. On correctness at the root cause and breadth of coverage, A is the better fix.

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

12m 12s

Wall-clock time in the container

Full test suite

No new failures

12,867 passed · 526 skipped · 13,393 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

98vs 139 merged

Changed lines, ours vs merged

Description

Field(multiple_of=0) is rejected during schema generation for int, float, and Decimal, but equivalent non-native numeric types still pass schema generation and raise an uncaught ZeroDivisionError during validation.

Reproduction

from fractions import Fraction
from pydantic import BaseModel, Field

class Model(BaseModel):
    value: Fraction = Field(multiple_of=0)

Model(value=Fraction(1, 2))

Actual: validation raises ZeroDivisionError rather than ValidationError.

Expected: model definition fails with a schema-generation error stating that multiple_of must be greater than zero, consistently with native numeric types.

The Python fallback in pydantic/_internal/_validators.py performs x % multiple_of without validating the divisor. Fraction, temporal types, and complex use this fallback. I found no existing report for the remaining types after the native numeric fix.

The two patches

Our patch+96 −2
pydantic/_internal/_known_annotated_metadata.pyindex 5455c8f4..4f7827b3 100644@@ -184,7 +184,7 @@ def apply_known_metadata(annotation: Any, schema: CoreSchema) -> CoreSchema | No     """     import annotated_types as at -    from ._validators import NUMERIC_VALIDATOR_LOOKUP, forbid_inf_nan_check+    from ._validators import NUMERIC_VALIDATOR_LOOKUP, check_multiple_of_constraint, forbid_inf_nan_check      schema = schema.copy()     schema_update, other_metadata = collect_known_metadata([annotation])@@ -261,6 +261,15 @@ def apply_known_metadata(annotation: Any, schema: CoreSchema) -> CoreSchema | No                     js_constraint_key = 'minLength' if constraint == 'min_length' else 'maxLength'             else:                 js_constraint_key = constraint+                if constraint == 'multiple_of':+                    inner_schema = schema+                    while inner_schema['type'] in {'function-before', 'function-wrap', 'function-after'}:+                        inner_schema = inner_schema['schema']  # type: ignore+                    # Sized types (strings, collections) never support `multiple_of`, and are reported as+                    # incompatible during validation. For other types (e.g. `Fraction`, `timedelta`), the+                    # constraint is enforced with `%`, so the divisor is checked like pydantic-core does for `int`:+                    if inner_schema['type'] not in CONSTRAINTS_TO_ALLOWED_SCHEMAS['min_length']:+                        check_multiple_of_constraint(value)              schema = cs.no_info_after_validator_function(                 partial(NUMERIC_VALIDATOR_LOOKUP[constraint], **{constraint: value}), schemapydantic/_internal/_validators.pyindex aecf34e4..44f0ad23 100644@@ -297,6 +297,37 @@ def less_than_or_equal_validator(x: Any, le: Any) -> Any:         raise TypeError(f"Unable to apply constraint 'le' to supplied value {x}")  +def check_multiple_of_constraint(multiple_of: Any) -> None:+    """Ensure a `multiple_of` constraint value is usable as a divisor, at schema-build time.++    Mirrors the check pydantic-core performs for `int`, `float` and `decimal` schemas,+    for the types (e.g. `Fraction`, `timedelta`) where `multiple_of` is enforced in Python.++    Raises:+        ValueError: If `multiple_of` is not a finite value greater than zero.+    """+    try:+        try:+            valid = multiple_of > 0 and multiple_of != math.inf+        except TypeError:+            # Not comparable with `0` (e.g. `timedelta`), compare with the value's own zero instead:+            try:+                zero = multiple_of * 0+            except TypeError:+                # No zero value can be derived, leave any incompatibility to be reported during validation:+                return+            try:+                valid = multiple_of > zero+            except TypeError:+                # Values that can't be ordered (e.g. `complex`) can still be checked against zero:+                valid = multiple_of != zero+    except ArithmeticError:+        # e.g. `Decimal('NaN')`, which can't be ordered:+        valid = False+    if not valid:+        raise ValueError("'multiple_of' must be a finite number greater than 0")++ def multiple_of_validator(x: Any, multiple_of: Any) -> Any:     try:         if x % multiple_of:pydantic/experimental/pipeline.pyindex fb1da8b2..fc79d316 100644@@ -23,6 +23,7 @@ from pydantic_core import PydanticCustomError from pydantic_core import core_schema as cs  from pydantic import Strict+from pydantic._internal import _validators  __all__ = ['validate_as', 'validate_as_deferred', 'transform'] @@ -561,6 +562,7 @@ def _apply_constraint(  # noqa: C901             s = s.copy()             s['multiple_of'] = multiple_of  # pyright: ignore[reportGeneralTypeIssues]         else:+            _validators.check_multiple_of_constraint(multiple_of)              def check_multiple_of(v: Any) -> bool:                 return v % multiple_of == 0tests/test_pipeline.pyindex 8abe5cb8..2b07e51c 100644@@ -662,3 +662,9 @@ def test_validate_as_ellipsis_preserves_other_steps() -> None:     ta = TypeAdapter[float](Annotated[float, validate_as(str).transform(lambda v: v.split()[0]).validate_as(...)])      assert ta.validate_python('12 ab') == 12.0+++@pytest.mark.parametrize('multiple_of', [0, -1, Fraction(0)])+def test_multiple_of_invalid_constraint_python_check(multiple_of: Any) -> None:+    with pytest.raises(ValueError, match="'multiple_of' must be a finite number greater than 0"):+        TypeAdapter(Annotated[Fraction, validate_as(Fraction).multiple_of(multiple_of)])tests/types/test_complex.pyindex e810a585..003bdf56 100644@@ -65,3 +65,9 @@ def test_strict_complex():         ta.validate_python(1.0)     with pytest.raises(ValidationError):         ta.validate_python(5)+++@pytest.mark.parametrize('multiple_of', [0, 0j])+def test_complex_multiple_of_invalid_constraint(multiple_of) -> None:+    with pytest.raises(ValueError, match="'multiple_of' must be a finite number greater than 0"):+        TypeAdapter(Annotated[complex, Field(multiple_of=multiple_of)])tests/types/test_fraction.pyindex 81bd4ab2..61665014 100644@@ -5,7 +5,7 @@ from typing import Annotated import annotated_types import pytest -from pydantic import Field, TypeAdapter, ValidationError+from pydantic import BaseModel, Field, TypeAdapter, ValidationError   class FractionSubclass(Fraction):@@ -225,3 +225,21 @@ def test_fraction_json_schema():     ta = TypeAdapter(Annotated[Fraction, Field(ge=Fraction(1))])      assert ta.json_schema() == {'anyOf': [{'minimum': 1.0, 'type': 'number'}, {'format': 'fraction', 'type': 'string'}]}+++@pytest.mark.parametrize(+    'multiple_of', [0, Fraction(0), -1, Fraction(-1, 2), float('nan'), float('inf'), Decimal('NaN')]+)+def test_fraction_multiple_of_invalid_constraint(multiple_of) -> None:+    with pytest.raises(ValueError, match="'multiple_of' must be a finite number greater than 0"):++        class Model(BaseModel):+            value: Fraction = Field(multiple_of=multiple_of)+++def test_fraction_multiple_of() -> None:+    ta = TypeAdapter(Annotated[Fraction, Field(multiple_of=Fraction(1, 2))])+    assert ta.validate_python('3/2') == Fraction(3, 2)+    with pytest.raises(ValidationError) as exc_info:+        ta.validate_python('1/3')+    assert exc_info.value.errors()[0]['type'] == 'multiple_of'tests/types/test_int.pyindex e142795b..6fae9508 100644@@ -7,6 +7,7 @@ import pytest from pydantic_core import SchemaError  from pydantic import (+    AfterValidator,     BaseModel,     NegativeInt,     NonNegativeInt,@@ -292,6 +293,13 @@ def test_number_multiple_of_int_invalid_constraint(multiple_of: int) -> None:         TypeAdapter(Annotated[int, annotated_types.MultipleOf(multiple_of)])  +@pytest.mark.parametrize('multiple_of', [0, -5])+def test_number_multiple_of_int_invalid_constraint_after_validator(multiple_of: int) -> None:+    # The constraint can't be pushed down to the `int` core schema, and is enforced in Python:+    with pytest.raises(ValueError, match="'multiple_of' must be a finite number greater than 0"):+        TypeAdapter(Annotated[int, AfterValidator(lambda v: v), annotated_types.MultipleOf(multiple_of)])++ # A number well outside of i64 range _BIG_NUMBER_STR = '1' + ('0' * 40) tests/types/test_timedelta.pyindex fe633e20..c5da8546 100644@@ -63,3 +63,17 @@ def test_strict_timedelta():             'input': '1 days',         }     ]+++@pytest.mark.parametrize('multiple_of', [timedelta(0), timedelta(seconds=-1)])+def test_timedelta_multiple_of_invalid_constraint(multiple_of: timedelta) -> None:+    with pytest.raises(ValueError, match="'multiple_of' must be a finite number greater than 0"):+        TypeAdapter(Annotated[timedelta, Field(multiple_of=multiple_of)])+++def test_timedelta_multiple_of() -> None:+    ta = TypeAdapter(Annotated[timedelta, Field(multiple_of=timedelta(minutes=15))])+    assert ta.validate_python(timedelta(hours=1)) == timedelta(hours=1)+    with pytest.raises(ValidationError) as exc_info:+        ta.validate_python(timedelta(minutes=10))+    assert exc_info.value.errors()[0]['type'] == 'multiple_of' 
Merged fix · PR #13873+135 −4
pydantic-core/python/pydantic_core/core_schema.pyindex f7abea6cf..a280e26d8 100644@@ -842,6 +842,7 @@ def decimal_schema(  class FractionSchema(TypedDict, total=False):     type: Required[Literal['fraction']]+    multiple_of: Fraction     le: Fraction     ge: Fraction     lt: Fraction@@ -854,6 +855,7 @@ class FractionSchema(TypedDict, total=False):  def fraction_schema(     *,+    multiple_of: Fraction | None = None,     le: Fraction | None = None,     ge: Fraction | None = None,     lt: Fraction | None = None,@@ -876,6 +878,7 @@ def fraction_schema(     ```      Args:+        multiple_of: The value must be a multiple of this number         le: The value must be less than or equal to this number         ge: The value must be greater than or equal to this number         lt: The value must be strictly less than this number@@ -887,6 +890,7 @@ def fraction_schema(     """     return _dict_not_none(         type='fraction',+        multiple_of=multiple_of,         gt=gt,         ge=ge,         lt=lt,@@ -1286,6 +1290,7 @@ def datetime_schema( class TimedeltaSchema(TypedDict, total=False):     type: Required[Literal['timedelta']]     strict: bool+    multiple_of: timedelta     le: timedelta     ge: timedelta     lt: timedelta@@ -1299,6 +1304,7 @@ class TimedeltaSchema(TypedDict, total=False): def timedelta_schema(     *,     strict: bool | None = None,+    multiple_of: timedelta | None = None,     le: timedelta | None = None,     ge: timedelta | None = None,     lt: timedelta | None = None,@@ -1322,6 +1328,7 @@ def timedelta_schema(      Args:         strict: Whether the value should be a timedelta or a value that can be converted to a timedelta+        multiple_of: The value must be a multiple of this timedelta         le: The value must be less than or equal to this timedelta         ge: The value must be greater than or equal to this timedelta         lt: The value must be strictly less than this timedelta@@ -1334,6 +1341,7 @@ def timedelta_schema(     return _dict_not_none(         type='timedelta',         strict=strict,+        multiple_of=multiple_of,         le=le,         ge=ge,         lt=lt,pydantic-core/src/validators/fraction.rsindex 795fd9586..83ca27f90 100644@@ -47,6 +47,7 @@ fn validate_as_fraction( #[derive(Debug, Clone)] pub struct FractionValidator {     strict: bool,+    multiple_of: Option<Py<PyAny>>,     le: Option<Py<PyAny>>,     lt: Option<Py<PyAny>>,     ge: Option<Py<PyAny>>,@@ -62,8 +63,16 @@ impl BuildValidator for FractionValidator {     ) -> PyResult<Arc<CombinedValidator>> {         let py = schema.py(); +        let multiple_of = validate_as_fraction(py, schema, intern!(py, "multiple_of"))?;+        if let Some(ref m) = multiple_of+            && !m.bind(py).gt(0)?+        {+            return Err(PyValueError::new_err("'multiple_of' must be greater than 0"));+        }+         Ok(CombinedValidator::Fraction(Self {             strict: is_strict(schema, config)?,+            multiple_of,             le: validate_as_fraction(py, schema, intern!(py, "le"))?,             lt: validate_as_fraction(py, schema, intern!(py, "lt"))?,             ge: validate_as_fraction(py, schema, intern!(py, "ge"))?,@@ -73,7 +82,13 @@ impl BuildValidator for FractionValidator {     } } -impl_py_gc_traverse!(FractionValidator { le, lt, ge, gt });+impl_py_gc_traverse!(FractionValidator {+    multiple_of,+    le,+    lt,+    ge,+    gt+});  impl Validator for FractionValidator {     fn validate<'py>(@@ -84,6 +99,18 @@ impl Validator for FractionValidator {     ) -> ValResult<Py<PyAny>> {         let fraction = input.validate_fraction(state.strict_or(self.strict), py)?.unpack(state); +        if let Some(multiple_of) = &self.multiple_of+            && !fraction.rem(multiple_of)?.eq(0)?+        {+            return Err(ValError::new(+                ErrorType::MultipleOf {+                    multiple_of: Number::String(multiple_of.to_string()),+                    context: Some([("multiple_of", multiple_of)].into_py_dict(py)?.into()),+                },+                input,+            ));+        }+         if let Some(le) = &self.le             && !fraction.le(le)?         {pydantic-core/src/validators/timedelta.rsindex c607af8ea..294b32f26 100644@@ -22,6 +22,7 @@ pub struct TimeDeltaValidator {  #[derive(Debug, Clone)] struct TimedeltaConstraints {+    multiple_of: Option<Duration>,     le: Option<Duration>,     lt: Option<Duration>,     ge: Option<Duration>,@@ -40,6 +41,10 @@ fn get_constraint(schema: &Bound<'_, PyDict>, key: &Bound<'_, PyString>) -> PyRe     } } +fn total_microseconds(duration: &Duration) -> i128 {+    i128::from(duration.signed_total_seconds()) * 1_000_000 + i128::from(duration.signed_microseconds())+}+ impl BuildValidator for TimeDeltaValidator {     const EXPECTED_TYPE: &'static str = "timedelta"; @@ -49,7 +54,14 @@ impl BuildValidator for TimeDeltaValidator {         _definitions: &mut DefinitionsBuilder<Arc<CombinedValidator>>,     ) -> PyResult<Arc<CombinedValidator>> {         let py = schema.py();+        let multiple_of = get_constraint(schema, intern!(py, "multiple_of"))?;+        if let Some(ref m) = multiple_of+            && total_microseconds(m) <= 0+        {+            return Err(PyValueError::new_err("'multiple_of' must be greater than 0"));+        }         let constraints = TimedeltaConstraints {+            multiple_of,             le: get_constraint(schema, intern!(py, "le"))?,             lt: get_constraint(schema, intern!(py, "lt"))?,             ge: get_constraint(schema, intern!(py, "ge"))?,@@ -58,7 +70,8 @@ impl BuildValidator for TimeDeltaValidator {          Ok(CombinedValidator::Timedelta(Self {             strict: is_strict(schema, config)?,-            constraints: (constraints.le.is_some()+            constraints: (constraints.multiple_of.is_some()+                || constraints.le.is_some()                 || constraints.lt.is_some()                 || constraints.ge.is_some()                 || constraints.gt.is_some())@@ -85,6 +98,18 @@ impl Validator for TimeDeltaValidator {         if let Some(constraints) = &self.constraints {             let raw_timedelta = timedelta.to_duration()?; +            if let Some(multiple_of) = &constraints.multiple_of+                && total_microseconds(&raw_timedelta) % total_microseconds(multiple_of) != 0+            {+                return Err(ValError::new(+                    ErrorType::MultipleOf {+                        context: None,+                        multiple_of: pydelta_to_human_readable(duration_as_pytimedelta(py, multiple_of)?).into(),+                    },+                    py_timedelta.as_any(),+                ));+            }+             macro_rules! check_constraint {                 ($constraint:ident, $error:ident) => {                     if let Some(constraint) = &constraints.$constraint {pydantic/_internal/_known_annotated_metadata.pyindex 5455c8f4d..6245b4290 100644@@ -43,12 +43,13 @@ SEQUENCE_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *FAIL_FAST}  FLOAT_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *ALLOW_INF_NAN, *STRICT} DECIMAL_CONSTRAINTS = {'max_digits', 'decimal_places', *FLOAT_CONSTRAINTS}-FRACTION_CONSTRAINTS = {*INEQUALITY, *STRICT}+FRACTION_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT} INT_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT} BOOL_CONSTRAINTS = STRICT UUID_CONSTRAINTS = STRICT  DATE_TIME_CONSTRAINTS = {*INEQUALITY, *STRICT}+TIMEDELTA_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT} LAX_OR_STRICT_CONSTRAINTS = STRICT ENUM_CONSTRAINTS = STRICT COMPLEX_CONSTRAINTS = STRICT@@ -76,7 +77,8 @@ constraint_schema_pairings: list[tuple[set[str], tuple[str, ...]]] = [     (GENERATOR_CONSTRAINTS, ('generator',)),     (FLOAT_CONSTRAINTS, ('float',)),     (INT_CONSTRAINTS, ('int',)),-    (DATE_TIME_CONSTRAINTS, ('date', 'time', 'datetime', 'timedelta')),+    (DATE_TIME_CONSTRAINTS, ('date', 'time', 'datetime')),+    (TIMEDELTA_CONSTRAINTS, ('timedelta',)),     (STRICT, ('typed-dict', 'model')),     (UNION_CONSTRAINTS, ('union',)),     (URL_CONSTRAINTS, ('url', 'multi-host-url')),tests/types/test_fraction.pyindex 81bd4ab25..5ea43b119 100644@@ -4,6 +4,7 @@ from typing import Annotated  import annotated_types import pytest+from pydantic_core import SchemaError  from pydantic import Field, TypeAdapter, ValidationError @@ -190,6 +191,9 @@ def test_fraction_dump_json(input_value, expected):         (annotated_types.Lt(1), '1/3', Fraction(1, 3)),         (annotated_types.Le(1), 1, Fraction(1)),         (annotated_types.Le(1), '1/3', Fraction(1, 3)),+        (annotated_types.MultipleOf(Fraction(1, 3)), '2/3', Fraction(2, 3)),+        (annotated_types.MultipleOf(Fraction(1, 3)), -1, Fraction(-1)),+        (annotated_types.MultipleOf(Fraction(1, 3)), 0, Fraction(0)),         # float bound         (annotated_types.Gt(0.5), 1, Fraction(1)),     ],@@ -208,6 +212,8 @@ def test_fraction_constraints(constraint, input_value, expected):         (annotated_types.Lt(1), 1),         (annotated_types.Lt(1), 2),         (annotated_types.Le(1), 2),+        (annotated_types.MultipleOf(Fraction(1, 3)), '1/2'),+        (annotated_types.MultipleOf(Fraction(1, 3)), 0.5),         # float bound         (annotated_types.Gt(0.5), '1/3'),     ],@@ -218,6 +224,33 @@ def test_fraction_constraints_error(constraint, input_value):         ta.validate_python(input_value)  +def test_fraction_multiple_of_error() -> None:+    """https://github.com/pydantic/pydantic/issues/13868"""++    ta = TypeAdapter(Annotated[Fraction, Field(multiple_of=Fraction(1, 3))])++    with pytest.raises(ValidationError) as exc_info:+        ta.validate_python(Fraction(1, 2))+    # insert_assert(exc_info.value.errors(include_url=False))+    assert exc_info.value.errors(include_url=False) == [+        {+            'type': 'multiple_of',+            'loc': (),+            'msg': 'Input should be a multiple of 1/3',+            'input': Fraction(1, 2),+            'ctx': {'multiple_of': Fraction(1, 3)},+        }+    ]+++@pytest.mark.parametrize('multiple_of', [0, Fraction(0), Fraction(-1, 3)])+def test_fraction_multiple_of_invalid_constraint(multiple_of: Fraction) -> None:+    """https://github.com/pydantic/pydantic/issues/13868"""++    with pytest.raises(SchemaError, match="'multiple_of' must be greater than 0"):+        TypeAdapter(Annotated[Fraction, Field(multiple_of=multiple_of)])++ def test_fraction_json_schema():     ta = TypeAdapter(Fraction)     assert ta.json_schema(mode='serialization') == {'type': 'string', 'format': 'fraction'}tests/types/test_timedelta.pyindex fe633e208..53b64a764 100644@@ -3,6 +3,7 @@ from decimal import Decimal from typing import Annotated  import pytest+from pydantic_core import SchemaError  from pydantic import Field, TypeAdapter, ValidationError @@ -63,3 +64,38 @@ def test_strict_timedelta():             'input': '1 days',         }     ]+++@pytest.mark.parametrize(+    'value',+    [timedelta(0), timedelta(minutes=45), timedelta(minutes=-30), timedelta(days=3), 'PT1H', 900],+)+def test_timedelta_multiple_of(value: object) -> None:++    ta = TypeAdapter(Annotated[timedelta, Field(multiple_of=timedelta(minutes=15))])+    assert ta.validate_python(value) % timedelta(minutes=15) == timedelta(0)+++def test_timedelta_multiple_of_error() -> None:+    ta = TypeAdapter(Annotated[timedelta, Field(multiple_of=timedelta(minutes=15))])++    with pytest.raises(ValidationError) as exc_info:+        ta.validate_python(timedelta(minutes=50))+    # insert_assert(exc_info.value.errors(include_url=False))+    assert exc_info.value.errors(include_url=False) == [+        {+            'type': 'multiple_of',+            'loc': (),+            'msg': 'Input should be a multiple of 15 minutes',+            'input': timedelta(minutes=50),+            'ctx': {'multiple_of': '15 minutes'},+        }+    ]+++@pytest.mark.parametrize('multiple_of', [timedelta(0), timedelta(minutes=-15)])+def test_timedelta_multiple_of_invalid_constraint(multiple_of: timedelta) -> None:+    """https://github.com/pydantic/pydantic/issues/13868"""++    with pytest.raises(SchemaError, match="'multiple_of' must be greater than 0"):+        TypeAdapter(Annotated[timedelta, Field(multiple_of=multiple_of)])