Backtestspydanticrun-20261007-130130#13764

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

Pipeline API multiple_of() rejects every timedelta and raises TypeError for date/time/datetime

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 root cause the issue identifies. It adds `_MULTIPLE_OF_SCHEMA_TYPES`, covering int, float, decimal, date, time, datetime and timedelta, which mirrors the existing `_ORDERING_SCHEMA_TYPES` and `_LENGTH_SCHEMA_TYPES`. `_apply_constraint` now sets `multiple_of` natively on temporal schemas, which matches `Field(multiple_of=...)`. Fraction still uses the predicate path. A also hardens the predicate fallback by using `not v % multiple_of`, so a timedelta reached after a transform no longer fails on `timedelta(0) != 0`. Its tests would fail before the fix and pass after: core-schema subset checks for each temporal type, a direct comparison with Field behavior, Fraction staying on the predicate path, and the timedelta predicate fallback.

Patch B does not touch `pipeline.py` at all. The hardcoded `{'int', 'float', 'decimal'}` check stays, so timedelta still rejects everything and date/time/datetime still raise a raw TypeError. Neither reported scenario is fixed. Instead, B changes `_known_annotated_metadata.py` to remove `multiple_of` from the datetime constraints. That changes behavior of the non-experimental `Field()` API, which the issue explicitly says works and should be matched. B also deletes the `TIMEDELTA_CONSTRAINTS` and `TIME_CONSTRAINTS` definitions, which are likely still referenced later in that module, so it risks a NameError at import time. B adds no tests. Patch A is clearly better on correctness, tests and scope.

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

6m 4s

Wall-clock time in the container

Full test suite

No new failures

12,507 passed · 509 skipped · 13,016 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

59vs 4 merged

Changed lines, ours vs merged

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

In the pipeline API, multiple_of() is broken for every temporal type. timedelta rejects every value, including exact multiples, and date/time/datetime raise a bare TypeError that escapes as-is instead of a ValidationError.

annotation.multiple_of(...)Field(multiple_of=...)correct
intmultiple_of errormultiple_of error✅
floatmultiple_of errormultiple_of error✅
Decimalmultiple_of errormultiple_of error✅
Fractionpredicate checkn/a (unsupported by core)✅
timedeltarejects everythingaccepts❌
dateuncaught TypeErroraccepts❌
timeuncaught TypeErroraccepts❌
datetimeuncaught TypeErroraccepts❌

validate_as(timedelta).multiple_of(timedelta(seconds=5)) rejects timedelta(seconds=10), which is an exact multiple.

Root cause

_apply_constraint() applies multiple_of natively only for a hardcoded {'int', 'float', 'decimal'}, and otherwise falls back to a Python predicate:

def check_multiple_of(v: Any) -> bool:
    return v % multiple_of == 0

That predicate cannot work for temporal types:

  • timedelta(seconds=10) % timedelta(seconds=5) is timedelta(0), and timedelta(0) == 0 is False in Python. The check therefore never holds, for any input.
  • date, time and datetime do not support % at all, so the predicate raises TypeError: unsupported operand type(s) for %, which is not wrapped into a ValidationError.

This looks like an oversight rather than a decision. #13659 generalised exactly this pattern for the other constraints, introducing _ORDERING_SCHEMA_TYPES for gt/ge/lt/le and _LENGTH_SCHEMA_TYPES for min_length/max_length, both of which cover the temporal types. MultipleOf was left on its old hardcoded set in the same function.

Pydantic's own metadata already records the correct answer — DATE_TIME_CONSTRAINTS in _known_annotated_metadata.py includes NUMERIC_CONSTRAINTS, i.e. multiple_of:

>>> from pydantic._internal._known_annotated_metadata import CONSTRAINTS_TO_ALLOWED_SCHEMAS
>>> sorted(CONSTRAINTS_TO_ALLOWED_SCHEMAS['multiple_of'])
['date', 'datetime', 'decimal', 'float', 'int', 'time', 'timedelta']

fraction is correctly absent there, and must keep using the predicate path — fraction_schema() takes no multiple_of argument, and Fraction supports % correctly.

Suggested fix

Apply the constraint natively for the schema types that accept it, mirroring #13659:

# Core schema types with native support for the `multiple_of` constraint:
_MULTIPLE_OF_SCHEMA_TYPES = frozenset({'int', 'float', 'decimal', 'date', 'time', 'datetime', 'timedelta'})

This aligns the pipeline API with the non-experimental API, per the position in #13564 that the two should agree. Note that this makes multiple_of a silent no-op on temporal types, because pydantic-core accepts the key but does not enforce it there — which is exactly what Field(multiple_of=...) already does today. Enforcing it would be a pydantic-core change and a separate discussion; this issue is only about the pipeline API diverging from Field().

I have a fix and regression tests ready (the tests fail without the fix and pass with it, and pyright stays at its existing baseline). Happy to open a PR if I could be assigned.

Example Code

import datetime
from typing import Annotated

from pydantic import TypeAdapter
from pydantic.experimental.pipeline import validate_as

td = datetime.timedelta

# 1. timedelta: an exact multiple is rejected.
ta = TypeAdapter(Annotated[td, validate_as(td).multiple_of(td(seconds=5))])
ta.validate_python(td(seconds=10))
# ValidationError: Value error, Expected % 0:00:05 == 0
# (timedelta(0) == 0 is False, so the predicate never holds)

# 2. date/time/datetime: raw TypeError, not a ValidationError.
ta = TypeAdapter(Annotated[datetime.date, validate_as(datetime.date).multiple_of(2)])
ta.validate_python(datetime.date(2020, 1, 1))
# TypeError: unsupported operand type(s) for %: 'datetime.date' and 'int'

Python, Pydantic & OS Version

             pydantic version: 2.14.0b1
        pydantic-core version: 2.48.0
          pydantic-core build: profile=debug pgo=false
               python version: 3.13.15 (main, Sep  1 2026, 14:18:08) [Clang 22.1.3 ]
                     platform: Linux-7.0.0-31-generic-x86_64-with-glibc2.43
             related packages: typing_extensions-4.16.0
                       commit: c23cb86e

The two patches

Our patch+56 −3
pydantic/experimental/pipeline.pyindex 0fe40733..7ff1fd26 100644@@ -485,6 +485,8 @@ _ORDERING_SCHEMA_TYPES = frozenset({'int', 'float', 'decimal', 'fraction', 'date _LENGTH_SCHEMA_TYPES = frozenset(     {'str', 'bytes', 'list', 'tuple', 'set', 'frozenset', 'dict', 'frozendict', 'generator'} )+# Core schema types with native support for the `multiple_of` constraint:+_MULTIPLE_OF_SCHEMA_TYPES = frozenset({'int', 'float', 'decimal', 'date', 'time', 'datetime', 'timedelta'})   def _apply_constraint(  # noqa: C901@@ -561,13 +563,14 @@ def _apply_constraint(  # noqa: C901             s = _check_func(check_len, predicate_err, s)     elif isinstance(constraint, annotated_types.MultipleOf):         multiple_of = constraint.multiple_of-        if s and s['type'] in {'int', 'float', 'decimal'}:+        if s and s['type'] in _MULTIPLE_OF_SCHEMA_TYPES:             s = s.copy()             s['multiple_of'] = multiple_of  # pyright: ignore[reportGeneralTypeIssues]         else:              def check_multiple_of(v: Any) -> bool:-                return v % multiple_of == 0+                # Check truthiness rather than `== 0`, as e.g. `timedelta(0) != 0`:+                return not v % multiple_of              s = _check_func(check_multiple_of, f'% {multiple_of} == 0', s)     elif isinstance(constraint, annotated_types.Timezone):tests/test_pipeline.pyindex 8abe5cb8..d3d0b762 100644@@ -13,7 +13,7 @@ import pytest import pytz from annotated_types import Interval, Len -from pydantic import TypeAdapter, ValidationError+from pydantic import Field, TypeAdapter, ValidationError from pydantic.experimental.pipeline import _Pipeline, transform, validate_as  # pyright: ignore[reportPrivateUsage]  @@ -293,6 +293,14 @@ def test_len_constraint_on_generator() -> None:             validate_as(datetime.timedelta).le(datetime.timedelta(hours=1)),             {'type': 'timedelta', 'le': datetime.timedelta(hours=1)},         ),+        (+            datetime.timedelta,+            validate_as(datetime.timedelta).multiple_of(datetime.timedelta(seconds=5)),+            {'type': 'timedelta', 'multiple_of': datetime.timedelta(seconds=5)},+        ),+        (datetime.date, validate_as(datetime.date).multiple_of(2), {'type': 'date', 'multiple_of': 2}),+        (datetime.time, validate_as(datetime.time).multiple_of(2), {'type': 'time', 'multiple_of': 2}),+        (datetime.datetime, validate_as(datetime.datetime).multiple_of(2), {'type': 'datetime', 'multiple_of': 2}),     ], ) def test_constraints_applied_on_core_schema(type_: Any, pipeline: Any, expected_subset: dict[str, Any]) -> None:@@ -303,6 +311,48 @@ def test_constraints_applied_on_core_schema(type_: Any, pipeline: Any, expected_     assert {k: schema.get(k) for k in expected_subset} == expected_subset  +@pytest.mark.parametrize(+    'type_, multiple_of, value',+    [+        (datetime.timedelta, datetime.timedelta(seconds=5), datetime.timedelta(seconds=10)),+        (datetime.date, 2, datetime.date(2020, 1, 1)),+        (datetime.time, 2, datetime.time(12, 0)),+        (datetime.datetime, 2, datetime.datetime(2020, 1, 1)),+    ],+)+def test_multiple_of_temporal_matches_field(type_: Any, multiple_of: Any, value: Any) -> None:+    """The pipeline `multiple_of()` behaves like `Field(multiple_of=...)` on temporal types.++    Previously, `timedelta` rejected every value and `date`/`time`/`datetime` raised a raw `TypeError`.+    """+    field_ta = TypeAdapter[Any](Annotated[type_, Field(multiple_of=multiple_of)])+    pipeline_ta = TypeAdapter[Any](Annotated[type_, validate_as(type_).multiple_of(multiple_of)])++    assert field_ta.validate_python(value) == value+    assert pipeline_ta.validate_python(value) == value+++def test_multiple_of_fraction_uses_predicate() -> None:+    ta = TypeAdapter[Fraction](Annotated[Fraction, validate_as(Fraction).multiple_of(Fraction(1, 2))])+    assert 'multiple_of' not in ta.core_schema+    assert ta.validate_python(Fraction(3, 2)) == Fraction(3, 2)+    with pytest.raises(ValidationError):+        ta.validate_python(Fraction(1, 3))+++def test_multiple_of_timedelta_predicate() -> None:+    """The `multiple_of` predicate fallback (used here after a transform) handles `timedelta`."""+    ta = TypeAdapter[datetime.timedelta](+        Annotated[+            datetime.timedelta,+            validate_as(datetime.timedelta).transform(lambda v: v).multiple_of(datetime.timedelta(seconds=5)),+        ]+    )+    assert ta.validate_python(datetime.timedelta(seconds=10)) == datetime.timedelta(seconds=10)+    with pytest.raises(ValidationError):+        ta.validate_python(datetime.timedelta(seconds=7))++ def test_parse_tz() -> None:     ta_tz = TypeAdapter[datetime.datetime](         Annotated[ 
Merged fix · PR #13768+1 −3
pydantic/_internal/_known_annotated_metadata.pyindex 56ae45aa3..e049d111e 100644@@ -48,9 +48,7 @@ INT_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *ALLOW_INF_NAN, *STRICT} BOOL_CONSTRAINTS = STRICT UUID_CONSTRAINTS = STRICT -DATE_TIME_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}-TIMEDELTA_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}-TIME_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT}+DATE_TIME_CONSTRAINTS = {*INEQUALITY, *STRICT} LAX_OR_STRICT_CONSTRAINTS = STRICT ENUM_CONSTRAINTS = STRICT COMPLEX_CONSTRAINTS = STRICT