Backtestspydanticrun-20261009-110034#13764

Issue #13764 Merged fix PR #13768 Run 9 Oct 2026 · run-20261009-110034 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/timedelta, mirroring `_ORDERING_SCHEMA_TYPES` and `_LENGTH_SCHEMA_TYPES`. This makes temporal types apply `multiple_of` natively, as `Field(multiple_of=...)` does. It also hardens the predicate fallback with `not (v % multiple_of)`, so `timedelta % timedelta` returning `timedelta(0)` is handled when the schema is not native, while `Fraction` keeps the predicate path. The tests check pipeline/Field agreement for all four temporal types, the core-schema output, Fraction predicate behavior, and the timedelta predicate fallback. These would fail before the change and pass after it.

Patch B does not touch `pipeline.py` at all, so neither reported bug is fixed: timedelta still rejects every value, and date/time/datetime still raise a bare `TypeError`. Instead, it changes `_known_annotated_metadata.py` to drop `multiple_of` from date/time constraints, which alters the non-experimental `Field()` behavior the issue wants to match. It also deletes the `TIMEDELTA_CONSTRAINTS` and `TIME_CONSTRAINTS` names, which the rest of that module likely references when building `CONSTRAINTS_TO_ALLOWED_SCHEMAS`, so it risks a `NameError` at import time. It 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

5m 10s

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

74vs 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+71 −3
pydantic/experimental/pipeline.pyindex 0fe40733..82ab917d 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+                # Not `== 0`: e.g. `timedelta % timedelta` returns `timedelta(0)`, which does not compare equal to `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..6b805375 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]  @@ -142,6 +142,51 @@ def test_parse_multipleOf(type_: Any, pipeline: Any, valid_cases: list[Any], inv             ta.validate_python(y)  +@pytest.mark.parametrize(+    'type_, multiple_of, values',+    [+        (+            datetime.timedelta,+            datetime.timedelta(seconds=5),+            [datetime.timedelta(seconds=10), datetime.timedelta(seconds=5), datetime.timedelta(seconds=7)],+        ),+        (datetime.date, 2, [datetime.date(2020, 1, 1)]),+        (datetime.time, 2, [datetime.time(12, 0, 1)]),+        (datetime.datetime, 2, [datetime.datetime(2020, 1, 1, 0, 0, 1)]),+    ],+)+def test_multiple_of_temporal_matches_field(type_: Any, multiple_of: Any, values: list[Any]) -> None:+    """The pipeline API should agree with `Field(multiple_of=...)` on temporal types,+    instead of rejecting every value (`timedelta`) or raising a bare `TypeError` (`date`/`time`/`datetime`).+    """+    ta_pipeline = TypeAdapter[Any](Annotated[type_, validate_as(type_).multiple_of(multiple_of)])+    ta_field = TypeAdapter[Any](Annotated[type_, Field(multiple_of=multiple_of)])+    for v in values:+        assert ta_pipeline.validate_python(v) == ta_field.validate_python(v) == v+++def test_multiple_of_fraction_uses_predicate() -> None:+    ta = TypeAdapter[Fraction](Annotated[Fraction, validate_as(Fraction).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))+++def test_multiple_of_timedelta_predicate() -> None:+    """When the schema isn't a native `timedelta` schema, the predicate fallback must handle `timedelta` remainders."""+    ta = TypeAdapter[datetime.timedelta](+        Annotated[+            datetime.timedelta,+            validate_as(int)+            .transform(lambda x: datetime.timedelta(seconds=x))+            .multiple_of(datetime.timedelta(seconds=5)),+        ]+    )+    assert ta.validate_python(10) == datetime.timedelta(seconds=10)+    with pytest.raises(ValidationError):+        ta.validate_python(7)++ @pytest.mark.parametrize(     'type_, pipeline, valid_cases, invalid_cases',     [@@ -293,6 +338,26 @@ def test_len_constraint_on_generator() -> None:             validate_as(datetime.timedelta).le(datetime.timedelta(hours=1)),             {'type': 'timedelta', 'le': datetime.timedelta(hours=1)},         ),+        (+            datetime.date,+            validate_as(datetime.date).multiple_of(2),  # pyright: ignore[reportCallIssue, reportArgumentType]+            {'type': 'date', 'multiple_of': 2},+        ),+        (+            datetime.time,+            validate_as(datetime.time).multiple_of(2),  # pyright: ignore[reportCallIssue, reportArgumentType]+            {'type': 'time', 'multiple_of': 2},+        ),+        (+            datetime.datetime,+            validate_as(datetime.datetime).multiple_of(2),  # pyright: ignore[reportCallIssue, reportArgumentType]+            {'type': 'datetime', 'multiple_of': 2},+        ),+        (+            datetime.timedelta,+            validate_as(datetime.timedelta).multiple_of(datetime.timedelta(seconds=5)),+            {'type': 'timedelta', 'multiple_of': datetime.timedelta(seconds=5)},+        ),     ], ) def test_constraints_applied_on_core_schema(type_: Any, pipeline: Any, expected_subset: dict[str, Any]) -> None: 
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