Backtestspydanticrun-20261027-165153#13868

Issue #13868 Merged fix PR #13873 Run 27 Oct 2026 · run-20261027-165153 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 users of that fallback. Patch A fixes exactly that: it adds `check_multiple_of_constraint` and calls it at the fallback site in `apply_known_metadata` (and in the experimental pipeline's Python path), so every type routed through `multiple_of_validator` now fails at schema generation with the same message pydantic-core uses for int/float/Decimal. That covers Fraction, timedelta, complex, and also int/Decimal wrapped in function schemas (AfterValidator), with careful handling of Decimal('1e400'), huge ints, NaN/inf, and non-float types. Its tests are broad and would fail before the change (Fraction, timedelta, complex, int/Decimal function-schema, pipeline), and the test_types.py edit preserves the original intent of that test now that a 0 divisor is rejected earlier.

Patch B instead adds native `multiple_of` support to the Rust Fraction and Timedelta validators and reroutes those two types to core. That is a larger cross-repo feature (pydantic-core Rust + schema TypedDicts + a required core release) rather than a fix of the stated root cause. The unvalidated fallback remains: `complex` (explicitly named in the issue), int/Decimal under function schemas, and the pipeline still raise ZeroDivisionError. Its tests only cover Fraction and timedelta. Both patches pass the independent tests, but those tests only probe Fraction and timedelta, so they do not expose B's remaining gap.

A resolves the issue at its root with narrower, lower-risk scope and stronger tests; B masks the symptom for two types via a redesign and leaves the reported fallback problem in place for others.

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 46s

Wall-clock time in the container

Full test suite

No new failures

3,894 passed · 248 skipped · 4,142 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

149vs 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+142 −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..7166121a 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 @@ -306,6 +306,49 @@ def multiple_of_validator(x: Any, multiple_of: Any) -> Any:         raise TypeError(f"Unable to apply constraint 'multiple_of' to supplied value {x}")  +def _is_valid_multiple_of(multiple_of: Any) -> bool:+    if isinstance(multiple_of, Decimal):+        # `math.isfinite()` would convert large decimals (e.g. `Decimal('1e400')`) to infinity:+        return multiple_of.is_finite() and multiple_of > 0+    try:+        return math.isfinite(multiple_of) and multiple_of > 0+    except OverflowError:+        # Finite values too large to be converted to a float (e.g. `10**400`):+        return multiple_of > 0+    except (ValueError, ArithmeticError):+        # e.g. signaling NaN decimals:+        return False+    except TypeError:+        # Types not convertible to a float (e.g. `timedelta`, `complex`):+        pass++    if multiple_of != multiple_of:+        # NaN values (e.g. `complex('nan')`):+        return False++    try:+        zero = multiple_of * 0+    except TypeError:+        return bool(multiple_of)+    try:+        return multiple_of > zero+    except TypeError:+        # Types not supporting ordering (e.g. `complex`):+        return multiple_of != zero+++def check_multiple_of_constraint(multiple_of: Any) -> None:+    """Check that a `multiple_of` constraint enforced by `multiple_of_validator()` is valid.++    This mirrors the checks performed by the core int, float and decimal validators.++    Raises:+        SchemaError: If `multiple_of` isn't a finite number greater than 0.+    """+    if not _is_valid_multiple_of(multiple_of):+        raise SchemaError("'multiple_of' must be a finite number greater than 0")++ def min_length_validator(x: Any, min_length: Any) -> Any:     try:         if not (len(x) >= min_length):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..958e3c4f 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,21 @@ 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)),+        (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_complex.pyindex e810a585..e34e340e 100644@@ -3,6 +3,7 @@ import platform from typing import Annotated  import pytest+from pydantic_core import SchemaError  from pydantic import Field, TypeAdapter, ValidationError @@ -65,3 +66,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, complex(math.nan, 0)])+def test_complex_multiple_of_invalid_constraint(multiple_of) -> None:+    with pytest.raises(SchemaError, match="'multiple_of' must be a finite number greater than 0"):+        TypeAdapter(Annotated[complex, Field(multiple_of=multiple_of)])tests/types/test_decimal.pyindex 6711fcf8..a84fe229 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,15 @@ 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('-1'), Decimal('NaN'), Decimal('sNaN'), Decimal('Infinity')])+def test_decimal_multiple_of_invalid_constraint_function_schema(multiple_of: Decimal) -> None:+    # The after validator results in a function schema, meaning the constraint is enforced in Python:+    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)])+++def test_decimal_multiple_of_function_schema_large_constraint() -> None:+    ta = TypeAdapter(Annotated[Decimal, AfterValidator(lambda v: v), Field(multiple_of=Decimal('1e400'))])+    assert ta.validate_python(Decimal('2e400')) == Decimal('2e400')tests/types/test_fraction.pyindex 81bd4ab2..332b848c 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,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'}]}+++def test_fraction_multiple_of() -> None:+    ta = TypeAdapter(Annotated[Fraction, Field(multiple_of=Fraction(1, 2))])+    assert ta.validate_python(Fraction(3, 2)) == Fraction(3, 2)+    with pytest.raises(ValidationError):+        ta.validate_python(Fraction(1, 3))+++@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) -> None:+    with pytest.raises(SchemaError, match="'multiple_of' must be a finite number greater than 0"):++        class Model(BaseModel):+            value: Fraction = Field(multiple_of=multiple_of)tests/types/test_int.pyindex e142795b..626a5d33 100644@@ -7,7 +7,9 @@ import pytest from pydantic_core import SchemaError  from pydantic import (+    AfterValidator,     BaseModel,+    Field,     NegativeInt,     NonNegativeInt,     NonPositiveInt,@@ -317,3 +319,15 @@ def test_int_validate_json(input_value, expected):             ta.validate_json(input_value)     else:         assert ta.validate_json(input_value) == expected+++@pytest.mark.parametrize('multiple_of', [0, -5, 2**1100 * -1])+def test_number_multiple_of_int_invalid_constraint_function_schema(multiple_of: int) -> None:+    # The after validator results in a function schema, meaning the constraint is enforced in Python:+    with pytest.raises(SchemaError, match="'multiple_of' must be a finite number greater than 0"):+        TypeAdapter(Annotated[int, AfterValidator(lambda v: v), Field(multiple_of=multiple_of)])+++def test_number_multiple_of_int_function_schema_large_constraint() -> None:+    ta = TypeAdapter(Annotated[int, AfterValidator(lambda v: v), Field(multiple_of=2**1100)])+    assert ta.validate_python(2**1101) == 2**1101tests/types/test_timedelta.pyindex fe633e20..0ea69e46 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',         }     ]+++def test_timedelta_multiple_of() -> None:+    ta = TypeAdapter(Annotated[timedelta, Field(multiple_of=timedelta(minutes=15))])+    assert ta.validate_python(timedelta(minutes=45)) == timedelta(minutes=45)+    with pytest.raises(ValidationError):+        ta.validate_python(timedelta(minutes=10))+++@pytest.mark.parametrize('multiple_of', [timedelta(0), timedelta(minutes=-15)])+def test_timedelta_multiple_of_invalid_constraint(multiple_of: timedelta) -> None:+    with pytest.raises(SchemaError, match="'multiple_of' must be a finite number greater than 0"):+        TypeAdapter(Annotated[timedelta, Field(multiple_of=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)])