Backtestspydanticrun-20261022-024030#13868

Issue #13868 Merged fix PR #13873 Run 22 Oct 2026 · run-20261022-024030 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.

The issue identifies the root cause as the Python fallback in `_validators.py` doing `x % multiple_of` without validating the divisor, and names Fraction, temporal types, and complex as affected. Patch A fixes exactly that: it adds `check_multiple_of_constraint` and invokes it wherever the fallback `multiple_of_validator` is wired up (`apply_known_metadata`) and in the experimental pipeline's non-native branch. This covers Fraction, timedelta, complex, and also int/float/Decimal when they reach the fallback via a function schema (e.g. `AfterValidator`), which A tests explicitly. It also rejects negative, NaN and infinite divisors, matching pydantic-core's message for native types. The check is tolerant of non-numeric constraint values (TypeError falls through to the existing validation-time error), and the only existing-test edit (changing `multiple_of: 0` to `1` on list/set/frozenset cases) is a necessary adjustment so those tests still exercise the 'cannot apply constraint' path rather than the new schema check. Tests are broad and would fail before the change.

Patch B instead adds native `multiple_of` support to the Rust Fraction and TimeDelta validators and routes those two types to core. That resolves the reproduction and passes the independent tests, but it does not touch the Python fallback at all, so `complex` and any int/float/Decimal constraint that lands on a function schema still raise `ZeroDivisionError` at validation time. It is also a larger, riskier change (new Rust validation logic, core schema TypedDict changes, i128 microsecond arithmetic, a new feature surface) that depends on a coordinated pydantic-core change, and its validity checks only reject <= 0, not NaN/inf for Fraction (less relevant) while leaving the generic path unguarded. B's new feature work earns no credit on its own and here it obscures that the reported root cause remains.

A is more correct against the issue as stated, better tested across the affected types, and tighter in scope.

Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.

Solve

9m 1s

Wall-clock time in the container

Full test suite

No new failures

3,942 passed · 248 skipped · 4,190 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

128vs 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+121 −7
pydantic/_internal/_known_annotated_metadata.pyindex 5455c8f4..12cab016 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])@@ -262,6 +262,9 @@ def apply_known_metadata(annotation: Any, schema: CoreSchema) -> CoreSchema | No             else:                 js_constraint_key = constraint +            if constraint == 'multiple_of':+                check_multiple_of_constraint(value)+             schema = cs.no_info_after_validator_function(                 partial(NUMERIC_VALIDATOR_LOOKUP[constraint], **{constraint: value}), schema             )pydantic/_internal/_validators.pyindex aecf34e4..17861725 100644@@ -16,7 +16,7 @@ from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6 from typing import Any, TypeAlias, TypeVar, cast from zoneinfo import ZoneInfo, ZoneInfoNotFoundError -from pydantic_core import PydanticCustomError, PydanticKnownError, core_schema+from pydantic_core import PydanticCustomError, PydanticKnownError, SchemaError, core_schema from typing_extensions import get_args, get_origin  # noqa: UP035 from typing_inspection import typing_objects @@ -297,6 +297,29 @@ 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 applied by a Python fallback validator is a finite value greater than zero.++    This mirrors the check performed by `pydantic-core` for the `int`, `float` and `decimal` schemas.+    The zero value is computed as `multiple_of - multiple_of`, so that non-numeric types supporting+    the modulo operation (such as `timedelta`) are also checked. Values that can't be compared that way+    are left as is: the constraint will fail to apply when validating.++    Raises:+        SchemaError: If `multiple_of` is lower than or equal to zero, or not finite.+    """+    try:+        is_valid = bool(multiple_of > multiple_of - multiple_of)+    except TypeError:+        return+    except ArithmeticError:+        # e.g. `Decimal('Infinity') - Decimal('Infinity')` or comparing a NaN `Decimal`:+        is_valid = False+    # For infinite floats, `inf - inf` is NaN, so the comparison above is already `False`.+    if not is_valid:+        raise SchemaError("'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..4cd25f62 100644@@ -561,6 +561,9 @@ def _apply_constraint(  # noqa: C901             s = s.copy()             s['multiple_of'] = multiple_of  # pyright: ignore[reportGeneralTypeIssues]         else:+            from pydantic._internal._validators import check_multiple_of_constraint++            check_multiple_of_constraint(multiple_of)              def check_multiple_of(v: Any) -> bool:                 return v % multiple_of == 0tests/test_pipeline.pyindex 8abe5cb8..ce1a175e 100644@@ -12,6 +12,7 @@ from typing import Annotated, Any import pytest import pytz from annotated_types import Interval, Len+from pydantic_core import SchemaError  from pydantic import TypeAdapter, ValidationError from pydantic.experimental.pipeline import _Pipeline, transform, validate_as  # pyright: ignore[reportPrivateUsage]@@ -142,6 +143,22 @@ def test_parse_multipleOf(type_: Any, pipeline: Any, valid_cases: list[Any], inv             ta.validate_python(y)  +@pytest.mark.parametrize(+    'type_, pipeline',+    [+        (int, validate_as(int).multiple_of(0)),+        (int, validate_as(int).transform(lambda x: x).multiple_of(0)),+        (int, validate_as(int).transform(lambda x: x).multiple_of(-5)),+        (float, validate_as(float).transform(lambda x: x).multiple_of(float('nan'))),+        (Fraction, validate_as(Fraction).multiple_of(Fraction(0))),+        (datetime.timedelta, validate_as(datetime.timedelta).multiple_of(datetime.timedelta(0))),+    ],+)+def test_parse_multipleOf_invalid_constraint(type_: Any, pipeline: Any) -> None:+    with pytest.raises(SchemaError, match="'multiple_of' must be a finite number greater than 0"):+        TypeAdapter[Any](Annotated[type_, pipeline])++ @pytest.mark.parametrize(     'type_, pipeline, valid_cases, invalid_cases',     [tests/test_types.pyindex 2d0b80ff..30e6104e 100644@@ -374,15 +374,19 @@ def test_import_string_thing_with_name() -> None:     [         ({'pattern': '^foo$'}, int, 1),         *[-            ({constraint_name: 0}, list[int], [1, 2, 3, 4, 5])+            ({constraint_name: 1 if constraint_name == 'multiple_of' else 0}, list[int], [1, 2, 3, 4, 5])             for constraint_name in ['gt', 'lt', 'ge', 'le', 'multiple_of']         ]         + [-            ({constraint_name: 0}, set[int], {1, 2, 3, 4, 5})+            ({constraint_name: 1 if constraint_name == 'multiple_of' else 0}, set[int], {1, 2, 3, 4, 5})             for constraint_name in ['gt', 'lt', 'ge', 'le', 'multiple_of']         ]         + [-            ({constraint_name: 0}, frozenset[int], frozenset({1, 2, 3, 4, 5}))+            (+                {constraint_name: 1 if constraint_name == 'multiple_of' else 0},+                frozenset[int],+                frozenset({1, 2, 3, 4, 5}),+            )             for constraint_name in ['gt', 'lt', 'ge', 'le', 'multiple_of']         ]         + [({constraint_name: 0}, Decimal, Decimal('1.0')) for constraint_name in ['max_length', 'min_length']]tests/types/test_decimal.pyindex 6711fcf8..cbfd080b 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'@@ -383,3 +383,13 @@ def test_decimal_multiple_of_invalid_constraint(multiple_of: Decimal) -> None:      with pytest.raises(SchemaError, match="'multiple_of' must be a finite number greater than 0"):         TypeAdapter(Annotated[Decimal, Field(multiple_of=multiple_of)])+++@pytest.mark.parametrize(+    'multiple_of',+    [Decimal('0'), Decimal('-0'), Decimal('-0.1'), Decimal('NaN'), Decimal('Infinity'), Decimal('-Infinity')],+)+def test_decimal_multiple_of_invalid_constraint_function_schema(multiple_of: Decimal) -> None:+    # The `AfterValidator` makes the constraint use the Python fallback validator:+    with pytest.raises(SchemaError, match="'multiple_of' must be a finite number greater than 0"):+        TypeAdapter(Annotated[Decimal, AfterValidator(lambda v: v), Field(multiple_of=multiple_of)])tests/types/test_float.pyindex 9618c3f6..c49bde5d 100644@@ -9,6 +9,7 @@ from dirty_equals import HasRepr, IsFloatNan from pydantic_core import SchemaError  from pydantic import (+    AfterValidator,     AllowInfNan,     BaseModel,     ConfigDict,@@ -250,6 +251,13 @@ def test_number_multiple_of_float_invalid_constraint(multiple_of: float) -> None         TypeAdapter(Annotated[float, annotated_types.MultipleOf(multiple_of)])  +@pytest.mark.parametrize('multiple_of', [0.0, -0.0, -0.1, math.nan, math.inf, -math.inf])+def test_number_multiple_of_float_invalid_constraint_function_schema(multiple_of: float) -> None:+    # The `AfterValidator` makes the constraint use the Python fallback validator:+    with pytest.raises(SchemaError, match="'multiple_of' must be a finite number greater than 0"):+        TypeAdapter(Annotated[float, AfterValidator(lambda v: v), annotated_types.MultipleOf(multiple_of)])++ @pytest.mark.parametrize(     'input_value,expected',     [tests/types/test_fraction.pyindex 81bd4ab2..9fcdbbda 100644@@ -4,8 +4,9 @@ from typing import Annotated  import annotated_types import pytest+from pydantic_core import SchemaError -from pydantic import Field, TypeAdapter, ValidationError+from pydantic import BaseModel, Field, TypeAdapter, ValidationError   class FractionSubclass(Fraction):@@ -225,3 +226,26 @@ 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), Fraction(-1, 2), -1, 0.0, float('nan'), float('inf'), Decimal('0'), Decimal('NaN')],+)+def test_fraction_multiple_of_invalid_constraint(multiple_of: object) -> None:+    with pytest.raises(SchemaError, match="'multiple_of' must be a finite number greater than 0"):+        TypeAdapter(Annotated[Fraction, Field(multiple_of=multiple_of)])+++def test_fraction_multiple_of_zero_model() -> None:+    with pytest.raises(SchemaError, match="'multiple_of' must be a finite number greater than 0"):++        class Model(BaseModel):+            value: Fraction = Field(multiple_of=0)+++def test_fraction_multiple_of() -> None:+    ta = TypeAdapter(Annotated[Fraction, Field(multiple_of=Fraction(1, 4))])+    assert ta.validate_python('3/4') == Fraction(3, 4)+    with pytest.raises(ValidationError):+        ta.validate_python('1/3')tests/types/test_int.pyindex e142795b..a2f845ee 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_function_schema(multiple_of: int) -> None:+    # The `AfterValidator` makes the constraint use the Python fallback validator:+    with pytest.raises(SchemaError, 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..8c2f26cf 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,16 @@ def test_strict_timedelta():             'input': '1 days',         }     ]+++@pytest.mark.parametrize('multiple_of', [timedelta(0), timedelta(seconds=-1), 0])+def test_timedelta_multiple_of_invalid_constraint(multiple_of: object) -> None:+    with pytest.raises(SchemaError, 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(minutes=30)) == timedelta(minutes=30)+    with pytest.raises(ValidationError):+        ta.validate_python(timedelta(minutes=20)) 
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)])