Backtestspydanticrun-20261009-110034#13868
multiple_of=0 still raises ZeroDivisionError for non-native numeric types
Our patch was judged better than the merged fix.
In this judgment, Patch B = our agent, Patch A = the merged fix.
The issue's root cause is that the Python fallback `multiple_of_validator` divides by `multiple_of` without checking it first. The issue names three affected families: Fraction, temporal types, and complex. Patch B fixes this where the fallback is wired in. It adds `check_multiple_of_constraint`, which runs at schema-build time in `apply_known_metadata` and in the experimental pipeline's fallback path. It unwraps function-before/after/wrap schemas and rejects zero, negative and NaN divisors. That covers fraction, timedelta, complex (comparison raises TypeError, so it falls back to a falsiness check) and bool. The result is a SchemaError at model definition, which is the behaviour the issue expects. Its tests reproduce the issue's BaseModel case directly. They also cover TypeAdapter with Fraction(0), negative and NaN values, a wrapped AfterValidator schema, timedelta zero and negative, complex 0/0j, bool and pipeline. A valid-constraint sanity test confirms normal validation still works. All of these would fail before the change. Patch A instead redesigns two types. It moves `multiple_of` for fraction and timedelta into pydantic-core, adding new Rust validator fields, TypedDict keys and schema-builder arguments, and changes the constraint routing tables. The Rust checks do reject non-positive divisors for those two types. However, complex is not handled at all: it still goes through the Python fallback and would still raise ZeroDivisionError, so one of the cases the issue lists remains broken. The redesign is also much riskier. It changes which layer enforces timedelta and fraction constraints, alters the error-message format, requires a core rebuild, and adds a new microsecond-arithmetic path. That is more surface than the bug needs. Its tests are reasonable for fraction and timedelta but say nothing about complex or the pipeline path. On correctness, B fully covers the reported scenarios while A leaves complex unfixed. On scope and risk, B is a focused fix while A is a broader redesign. B wins.
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 7s
Wall-clock time in the container
Full test suite
No new failures
12,864 passed · 526 skipped · 13,390 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
113vs 139 merged
Changed lines, ours vs merged
The issue
View on GitHubDescription
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
pydantic/_internal/_known_annotated_metadata.pyindex 5455c8f4..121850c9 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,8 @@ 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':+ check_multiple_of_constraint(value, schema) schema = cs.no_info_after_validator_function( partial(NUMERIC_VALIDATOR_LOOKUP[constraint], **{constraint: value}), schemapydantic/_internal/_validators.pyindex aecf34e4..7b4bf678 100644@@ -11,12 +11,13 @@ import re import sys import typing from collections.abc import Callable, Sequence+from datetime import timedelta from decimal import Decimal from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network 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 +298,39 @@ def less_than_or_equal_validator(x: Any, le: Any) -> Any: raise TypeError(f"Unable to apply constraint 'le' to supplied value {x}") +_MULTIPLE_OF_FALLBACK_NUMERIC_SCHEMA_TYPES = {'fraction', 'timedelta', 'complex', 'bool'}+"""Numeric core schema types for which the `multiple_of` constraint is enforced by `multiple_of_validator`."""+++def check_multiple_of_constraint(multiple_of: Any, schema: core_schema.CoreSchema | None) -> None:+ """Reject, at schema build time, a `multiple_of` value that is not greater than zero for numeric schemas+ validated by the Python fallback `multiple_of_validator`.++ Mirrors the check performed by pydantic-core for `int`, `float` and `decimal` schemas, so that+ e.g. `Fraction` or `timedelta` don't raise a `ZeroDivisionError` during validation.++ Raises:+ SchemaError: If `multiple_of` is zero, or compares as less than zero.+ """+ while schema is not None and schema['type'] in {'function-before', 'function-wrap', 'function-after'}:+ schema = schema['schema'] # type: ignore[typeddict-item]+ if schema is None or schema['type'] not in _MULTIPLE_OF_FALLBACK_NUMERIC_SCHEMA_TYPES:+ return++ zero = timedelta(0) if isinstance(multiple_of, timedelta) else 0+ try:+ # Written as `not >` (rather than `<=`) so that NaN values are rejected as well:+ invalid = not multiple_of > zero+ except TypeError:+ # Not comparable to `0` (e.g. `complex`), fall back to the zero value being falsy:+ invalid = not multiple_of+ except ArithmeticError:+ # e.g. `Decimal('nan')`, which can't be ordered:+ invalid = True+ if invalid:+ 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..723ff751 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, s) def check_multiple_of(v: Any) -> bool: return v % multiple_of == 0tests/test_pipeline.pyindex 8abe5cb8..60961237 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]@@ -662,3 +663,15 @@ 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(+ 'pipeline',+ [+ validate_as(Fraction).multiple_of(Fraction(0)), # pyright: ignore[reportArgumentType]+ validate_as(datetime.timedelta).multiple_of(datetime.timedelta(0)), # pyright: ignore[reportArgumentType]+ ],+)+def test_multiple_of_zero_non_native(pipeline: _Pipeline[Any, Any]) -> None:+ with pytest.raises(SchemaError, match="'multiple_of' must be a finite number greater than 0"):+ TypeAdapter(Annotated[Any, pipeline])tests/types/test_bool.pyindex 7afced63..c1c4c64e 100644@@ -1,8 +1,10 @@ from decimal import Decimal+from typing import Annotated import pytest+from pydantic_core import SchemaError -from pydantic import StrictBool, TypeAdapter, ValidationError+from pydantic import Field, StrictBool, TypeAdapter, ValidationError class BoolCastable:@@ -110,3 +112,8 @@ def test_bool_validate_json(input_value, output_value): ta = TypeAdapter(bool) assert ta.validate_json(input_value) is output_value+++def test_bool_multiple_of_zero_constraint() -> None:+ with pytest.raises(SchemaError, match="'multiple_of' must be a finite number greater than 0"):+ TypeAdapter(Annotated[bool, Field(multiple_of=0)])tests/types/test_complex.pyindex e810a585..799e69c8 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])+def test_complex_multiple_of_zero_constraint(multiple_of: complex) -> None:+ with pytest.raises(SchemaError, match="'multiple_of' must be a finite number greater than 0"):+ TypeAdapter(Annotated[complex, Field(multiple_of=multiple_of)]) # pyright: ignore[reportArgumentType]tests/types/test_fraction.pyindex 81bd4ab2..8e9a7b10 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 @@ -225,3 +226,32 @@ 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', [Fraction(0), Fraction(-1, 2), 0, float('nan'), Decimal('nan')])+def test_fraction_multiple_of_invalid_constraint(multiple_of: Fraction) -> 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:+ from pydantic import BaseModel++ 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_zero_wrapped_schema() -> None:+ from pydantic import AfterValidator++ with pytest.raises(SchemaError, match="'multiple_of' must be a finite number greater than 0"):+ TypeAdapter(Annotated[Fraction, AfterValidator(lambda v: v), Field(multiple_of=0)])+++def test_fraction_multiple_of_valid_constraint() -> 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, match=r'Input should be a multiple of Fraction\(1, 2\)'):+ ta.validate_python(Fraction(1, 3))tests/types/test_timedelta.pyindex fe633e20..09823596 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,13 @@ def test_strict_timedelta(): 'input': '1 days', } ]+++def test_timedelta_multiple_of_zero_constraint() -> None:+ with pytest.raises(SchemaError, match="'multiple_of' must be a finite number greater than 0"):+ TypeAdapter(Annotated[timedelta, Field(multiple_of=timedelta(0))]) # pyright: ignore[reportArgumentType]+++def test_timedelta_multiple_of_negative_constraint() -> None:+ with pytest.raises(SchemaError, match="'multiple_of' must be a finite number greater than 0"):+ TypeAdapter(Annotated[timedelta, Field(multiple_of=timedelta(seconds=-1))]) # pyright: ignore[reportArgumentType]
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)])