Backtestspydanticrun-20261027-165153#13969
Huge int input to a timedelta field wraps to a small wrong timedelta
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Both patches make the same root-cause change in int_as_duration: replace the truncating `as u32` on the day count with `u32::try_from` and map the failure to ParseError::DurationDaysTooLarge via map_timedelta_err, so both produce the same time_delta_parsing error as the float path. The independent tests confirm this: all issue scenarios (Python and JSON, positive and negative, 86400*2**32 and 86400*(2**32+5)) go from failing on base to passing under both, and the two i64-extreme cases fail identically under both with time_delta_type, so neither patch separates on correctness. A's combinator chain and B's let-else are both idiomatic; A's rewritten comment is slightly more precise about why seconds is still safe to cast. The difference is in tests and scope. Patch A adds regression cases in the pydantic-core test_timedelta.py, which is the layer where the fix lives, covering the boundary (999,999,999 days passes, 1,000,000,000 fails), the exact issue values, and negative inputs, plus a pydantic-level test that checks the error type on both Python and JSON paths. Some of A's extra cases (the i64 extremes and the string-input variants) carry risk of not matching the expected message given the time_delta_type result seen in the harness, but that is an unverified concern rather than evidence. Patch B only adds pydantic-level tests, and bundles an unrelated refactor of the TimedeltaModel fixture into a TypeAdapter fixture, rewriting two existing tests; its new test also oddly re-asserts the in-range case inside every parametrized run and carries a placeholder docstring. That churn obscures the fix and earns no credit. With equal fixes, A's tests at the core layer and narrower scope make it the better patch.
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
7m
Wall-clock time in the container
Full test suite
No new failures
552 passed · 91 skipped · 643 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
32vs 47 merged
Changed lines, ours vs merged
The issue
View on GitHubInitial Checks
- I confirm that I'm using Pydantic V2
Description
A timedelta field accepts an integer number of seconds that is far outside the timedelta range and returns a small, wrong value instead of raising a ValidationError. Any integer of at least 86400 * 2**32 seconds has its day count wrapped modulo 2**32, so 86400 * (2**32 + 5) validates to timedelta(days=5), from Python and from JSON, and the negative value gives timedelta(days=-5). The same number passed as a float is rejected with time_delta_parsing, so only the int path is affected. This matters for untrusted JSON input: a client can send a huge number and the model silently holds a plausible small duration.
Output of the example below:
python, int input: datetime.timedelta(days=5)
python, -int input: datetime.timedelta(days=-5)
json, int input: datetime.timedelta(days=5)
python, int 86400*2**32: datetime.timedelta(0)
python, float input: ValidationError time_delta_parsing
expected for all int inputs: ValidationError time_delta_parsing, like the float input
I expected every one of the int inputs to fail with time_delta_parsing, the same as the float input. Strict mode is not affected, since strict JSON rejects an int with time_delta_type.
Cause: int_as_duration in pydantic-core/src/input/datetime.rs (lines 709-716 at 68a839f07) computes let days = (total_seconds / 86400) as u32; on a u64. The as cast truncates, and the comment above it only covers seconds and microseconds. It is reached from the lax int branch of validate_timedelta in pydantic-core/src/input/input_python.rs (line 741) and pydantic-core/src/input/input_json.rs (line 396). float_as_duration a few lines below casts an f64 with as u32, which saturates, so Duration::new rejects the value there.
Proposed fix: use u32::try_from(total_seconds / 86400) and map the failure to the same TimeDeltaParsing error the float path ends up with. A Python and JSON test with 86400 * 2**32 and 86400 * (2**32 + 5) would cover it, since test_timedelta.py has no int case above timedelta.max today.
I'm happy to open a PR for this.
Example Code
from datetime import timedelta
from pydantic import BaseModel, ValidationError
class M(BaseModel):
d: timedelta
big = 86400 * (2**32 + 5) # 2**32 + 5 days in seconds, far above timedelta.max
print('python, int input: ', repr(M(d=big).d))
print('python, -int input: ', repr(M(d=-big).d))
print('json, int input: ', repr(M.model_validate_json(f'{{"d": {big}}}').d))
print('python, int 86400*2**32:', repr(M(d=86400 * 2**32).d))
try:
M(d=float(big))
except ValidationError as e:
print('python, float input: ValidationError', e.errors()[0]['type'])
print('expected for all int inputs: ValidationError time_delta_parsing, like the float input')
Python, Pydantic & OS Version
pydantic version: 2.14.0
pydantic-core version: 2.50.0
pydantic-core build: profile=release pgo=false
python version: 3.12.3 (main, Aug 31 2026, 10:18:26) [GCC 13.3.0]
platform: Linux-7.1.5-76070105-generic-x86_64-with-glibc2.39
related packages: typing_extensions-4.16.0
commit: unknownThe two patches
pydantic-core/src/input/datetime.rsindex afd44b29..f7f37617 100644@@ -709,10 +709,13 @@ pub fn bytes_as_timedelta<'py>( pub fn int_as_duration(input: impl ToErrorValue, total_seconds: i64) -> ValResult<Duration> { let positive = total_seconds >= 0; let total_seconds = total_seconds.unsigned_abs();- // we can safely unwrap here since we've guaranteed seconds and microseconds can't cause overflow- let days = (total_seconds / 86400) as u32;+ // seconds is always < 86400 so this cast is safe, but days can exceed u32::MAX for huge inputs,+ // so it must be converted with a check rather than a truncating cast let seconds = (total_seconds % 86400) as u32;- Duration::new(positive, days, seconds, 0).map_err(|err| map_timedelta_err(input, err))+ u32::try_from(total_seconds / 86400)+ .map_err(|_| ParseError::DurationDaysTooLarge)+ .and_then(|days| Duration::new(positive, days, seconds, 0))+ .map_err(|err| map_timedelta_err(input, err)) } pub fn float_as_duration(input: impl ToErrorValue, total_seconds: f64) -> ValResult<Duration> {pydantic-core/tests/validators/test_timedelta.pyindex 243fbfb9..e46d0492 100644@@ -63,6 +63,13 @@ def test_constraints_schema_validation() -> None: (float('inf'), Err('Input should be a valid timedelta, durations may not exceed 999,999,999 days')), (float('-inf'), Err('Input should be a valid timedelta, durations may not exceed 999,999,999 days')), (timedelta.max, timedelta.max),+ (86400 * 999_999_999, timedelta(days=999_999_999)),+ (86400 * 1_000_000_000, Err('durations may not exceed 999,999,999 days [type=time_delta_parsing')),+ (86400 * 2**32, Err('durations may not exceed 999,999,999 days [type=time_delta_parsing')),+ (86400 * (2**32 + 5), Err('durations may not exceed 999,999,999 days [type=time_delta_parsing')),+ (-86400 * (2**32 + 5), Err('durations may not exceed 999,999,999 days [type=time_delta_parsing')),+ (2**63 - 1, Err('durations may not exceed 999,999,999 days [type=time_delta_parsing')),+ (-(2**63), Err('durations may not exceed 999,999,999 days [type=time_delta_parsing')), ('02:03:04.05', timedelta(hours=2, seconds=184, microseconds=50_000)), ( '02:03:04.05broken',@@ -93,6 +100,10 @@ def test_timedelta(input_value, expected): ('-3601.222222', timedelta(hours=-2, seconds=3598, microseconds=777778)), ('-3601.2222222', timedelta(hours=-2, seconds=3598, microseconds=777778)), ('3600.999999', timedelta(seconds=3600, microseconds=999999)),+ (str(86400 * 999_999_999), timedelta(days=999_999_999)),+ (str(86400 * 2**32), Err('durations may not exceed 999,999,999 days [type=time_delta_parsing')),+ (str(86400 * (2**32 + 5)), Err('durations may not exceed 999,999,999 days [type=time_delta_parsing')),+ (str(-86400 * (2**32 + 5)), Err('durations may not exceed 999,999,999 days [type=time_delta_parsing')), ], ids=repr, )tests/test_datetime.pyindex 5448d959..6f289de3 100644@@ -434,6 +434,18 @@ def test_parse_durations(TimedeltaModel, value, result): assert TimedeltaModel(d=value).d == result +@pytest.mark.parametrize('value', [86400 * 2**32, 86400 * (2**32 + 5), -86400 * (2**32 + 5)])+def test_parse_durations_int_out_of_range(TimedeltaModel, value):+ # the day count must not wrap modulo 2**32 into a small, plausible timedelta+ with pytest.raises(ValidationError) as exc_info:+ TimedeltaModel(d=value)+ assert exc_info.value.errors(include_url=False)[0]['type'] == 'time_delta_parsing'++ with pytest.raises(ValidationError) as exc_info:+ TimedeltaModel.model_validate_json(f'{{"d": {value}}}')+ assert exc_info.value.errors(include_url=False)[0]['type'] == 'time_delta_parsing'++ @pytest.mark.parametrize( 'field, value, error_message', [
pydantic-core/src/input/datetime.rsindex afd44b296..2d6567965 100644@@ -709,8 +709,10 @@ pub fn bytes_as_timedelta<'py>( pub fn int_as_duration(input: impl ToErrorValue, total_seconds: i64) -> ValResult<Duration> { let positive = total_seconds >= 0; let total_seconds = total_seconds.unsigned_abs();- // we can safely unwrap here since we've guaranteed seconds and microseconds can't cause overflow- let days = (total_seconds / 86400) as u32;+ // The number of days can exceed `u32::MAX` (and casting would silently wrap it):+ let Ok(days) = u32::try_from(total_seconds / 86400) else {+ return Err(map_timedelta_err(input, ParseError::DurationDaysTooLarge));+ }; let seconds = (total_seconds % 86400) as u32; Duration::new(positive, days, seconds, 0).map_err(|err| map_timedelta_err(input, err)) }tests/test_datetime.pyindex 5448d959e..969d346ef 100644@@ -355,12 +355,9 @@ def test_naive_datetime_validation_fails(naive_datetime_type): ] -@pytest.fixture(scope='module', name='TimedeltaModel')-def timedelta_model_fixture():- class TimedeltaModel(BaseModel):- d: timedelta-- return TimedeltaModel+@pytest.fixture(scope='module', name='timedelta_ta')+def timedelta_ta_fixture() -> TypeAdapter[timedelta]:+ return TypeAdapter(timedelta) @pytest.mark.parametrize(@@ -375,9 +372,9 @@ def timedelta_model_fixture(): timedelta(seconds=30), # seconds ], )-def test_parse_python_format(TimedeltaModel, delta):- assert TimedeltaModel(d=delta).d == delta- # assert TimedeltaModel(d=str(delta)).d == delta+def test_parse_python_format(timedelta_ta: TypeAdapter[timedelta], delta):+ assert timedelta_ta.validate_python(delta) == delta+ # assert timedelta_ta.validate_python(str(delta)) == delta @pytest.mark.parametrize(@@ -426,12 +423,32 @@ def test_parse_python_format(TimedeltaModel, delta): (b'PT0.000005S', timedelta(microseconds=5)), ], )-def test_parse_durations(TimedeltaModel, value, result):+def test_parse_durations(timedelta_ta: TypeAdapter[timedelta], value, result): if isinstance(result, Err): with pytest.raises(ValidationError, match=result.message_escaped()):- TimedeltaModel(d=value)+ timedelta_ta.validate_python(value) else:- assert TimedeltaModel(d=value).d == result+ assert timedelta_ta.validate_python(value) == result+++@pytest.mark.parametrize(+ 'value',+ [+ 999_999_999 * 86400 + 86400,+ 86400 * 2**32,+ 86400 * (2**32 + 5),+ -86400 * (2**32 + 5),+ ],+)+def test_parse_durations_large_int(timedelta_ta: TypeAdapter[timedelta], value: int) -> None:+ """https://github.com/pydantic/pydantic/issues/13969"""++ assert timedelta_ta.validate_python(999_999_999 * 86400) == timedelta(days=999_999_999)++ with pytest.raises(ValidationError, match='durations may not exceed 999,999,999 days'):+ timedelta_ta.validate_python(value)+ with pytest.raises(ValidationError, match='durations may not exceed 999,999,999 days'):+ timedelta_ta.validate_json(str(value)) @pytest.mark.parametrize(