Backtestspydanticrun-20261013-104308#13764
Pipeline API multiple_of() rejects every timedelta and raises TypeError for date/time/datetime
Our patch was judged better than the merged fix.
In this judgment, Patch B = our agent, Patch A = the merged fix.
Patch B fixes the root cause the issue describes. In pipeline.py, `_apply_constraint` used a hardcoded `{'int','float','decimal'}` set for `multiple_of`. B replaces it with a `_MULTIPLE_OF_SCHEMA_TYPES` frozenset that includes date/time/datetime/timedelta. This mirrors the existing `_ORDERING_SCHEMA_TYPES` and `_LENGTH_SCHEMA_TYPES` conventions and matches `CONSTRAINTS_TO_ALLOWED_SCHEMAS`. It also hardens the fallback predicate to `not (v % multiple_of)`, so `timedelta(0)` counts as falsy and works when the constraint can't be applied natively (e.g. after a `not_eq` wraps the schema).
B's tests check that:
- the core schema now carries `multiple_of` for each temporal type;
- pipeline behaviour matches `Field(multiple_of=...)`;
- the Fraction function-check path still works;
- the timedelta function-check path handles exact multiples and non-multiples.
These would fail before the change.
Patch A does not touch pipeline.py at all. It changes `_known_annotated_metadata.py` to remove `multiple_of` (and other NUMERIC constraints) from date/time/timedelta constraints. It also deletes the `TIMEDELTA_CONSTRAINTS` and `TIME_CONSTRAINTS` names, which are likely referenced elsewhere in that module, so it probably breaks imports or mapping construction. It changes non-experimental `Field()` behaviour, which the issue explicitly wanted left alone. And it leaves the pipeline still using the broken `v % multiple_of == 0` predicate, so the pipeline timedelta rejection and the uncaught `TypeError` remain. A adds no tests.
B is clearly better on correctness, tests, scope and craft.
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
3m 58s
Wall-clock time in the container
Full test suite
No new failures
641 passed · 32 skipped · 673 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
52vs 4 merged
Changed lines, ours vs merged
The issue
View on GitHubInitial 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 |
|---|---|---|---|
int | multiple_of error | multiple_of error | ✅ |
float | multiple_of error | multiple_of error | ✅ |
Decimal | multiple_of error | multiple_of error | ✅ |
Fraction | predicate check | n/a (unsupported by core) | ✅ |
timedelta | rejects everything | accepts | ❌ |
date | uncaught TypeError | accepts | ❌ |
time | uncaught TypeError | accepts | ❌ |
datetime | uncaught TypeError | accepts | ❌ |
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)istimedelta(0), andtimedelta(0) == 0isFalsein Python. The check therefore never holds, for any input.date,timeanddatetimedo not support%at all, so the predicate raisesTypeError: unsupported operand type(s) for %, which is not wrapped into aValidationError.
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: c23cb86eThe two patches
pydantic/experimental/pipeline.pyindex 0fe40733..e0e1a0f0 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,13 @@ 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+ 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..8a673760 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] @@ -131,6 +131,8 @@ def test_ge_le_gt_lt( [Decimal('1.5'), Decimal('3.0'), Decimal('4.5')], [Decimal('1.4'), Decimal('2.1')], ),+ # `fraction` core schemas don't support `multiple_of`, so the constraint is applied as a function check:+ (Fraction, validate_as(Fraction).multiple_of(Fraction(1, 2)), [Fraction(1), Fraction(3, 2)], [Fraction(1, 3)]), ], ) def test_parse_multipleOf(type_: Any, pipeline: Any, valid_cases: list[Any], invalid_cases: list[Any]) -> None:@@ -293,6 +295,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 +313,40 @@ 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.timedelta, 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, value: Any) -> None:+ """The pipeline API `multiple_of()` behaves like `Field(multiple_of=...)` for temporal types."""+ 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 pipeline_ta.validate_python(value) == field_ta.validate_python(value) == value+++def test_multiple_of_function_check_timedelta() -> None:+ """When `multiple_of` can't be applied on the core schema, the function check handles `timedelta` correctly."""+ ta = TypeAdapter[datetime.timedelta](+ Annotated[+ datetime.timedelta,+ validate_as(datetime.timedelta)+ .not_eq(datetime.timedelta(seconds=20))+ .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[
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