Backtestspydanticrun-20260923-170312#13422

Issue #13422 Merged fix PR # Run 23 Sep 2026 · run-20260923-170312 pydantic/pydantic

to_json: timedelta_mode and temporal_mode break documented behavior

Better

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 identified in the issue (regression from #1743 collapsing the dedicated timedelta field into temporal_mode). It reintroduces a distinct `timedelta_mode: TemporalMode` on `SerializationConfig`, routes all three timedelta serialization paths (to_python, serialize, json_key) through it, and derives it correctly in both `from_config` and the positional constructor: when `temporal_mode`/`ser_json_temporal` is explicitly set it governs timedelta too (preserving prior unified behavior), otherwise the legacy timedelta alias applies to timedelta only. This delivers exactly the documented/desired outcome — `to_json(..., timedelta_mode='float', temporal_mode='iso8601')` yields ISO datetimes with float-second timedeltas — which the issue author states is impossible today and explicitly prefers as the fix. Patch B also adds a targeted test covering both to_json and to_jsonable_python that would fail before and pass after, matching the issue's repro. Patch A changes only the .pyi docstrings and a config.py comment; it neither fixes the behavior nor lets the user set timedelta independently, so the reported bug persists. Worse, Patch A's new prose asserts 'temporal_mode takes precedence over timedelta_mode', which contradicts the actual reported behavior (timedelta_mode='float' silently overrides temporal_mode='iso8601'), so it documents something untrue and still leaves no parameter combination producing the desired result. On correctness and tests Patch B wins decisively; its scope is somewhat larger but appropriately so for a root-cause fix, and its comments clearly explain the precedence logic. The one minor concern is Patch B does not update the docs/.pyi to reflect the now-independent timedelta semantics, but a correct behavioral fix far outweighs A's docs-only relabeling of a bug as intended.

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

15m 5s32 turns

Wall-clock time in the container

Full test suite

No new failures

6,413 passed · 368 skipped · 6,781 total

Contamination audit

Unknown

See the audit notes for this run

Patch size

47vs 55 merged

Changed lines, ours vs merged

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

pydantic_core.to_json (and to_jsonable_python) documents timedelta_mode and temporal_mode as independent parameters governing disjoint type sets:

  • timedelta_mode: How to serialize timedelta objects, either 'iso8601' or 'float'.
  • temporal_mode: How to serialize datetime-like objects (datetime, date, time), either 'iso8601', 'seconds', or 'milliseconds'.

(This is what both the API docs and the shipped _pydantic_core.pyi type stub say.)

Given that contract, to_json(..., timedelta_mode="float", temporal_mode="iso8601") should serialize datetime/date/time as ISO 8601 strings and timedelta as a float. Instead, datetime/date/time are also coerced to unix-timestamp floats, timedelta_mode="float" silently overrides temporal_mode="iso8601" for all temporal types.

There is no combination of the two parameters that yields ISO datetimes with float-second timedeltas, even though the documented parameters imply there should be.

Root cause / regression. This regressed in #1743. Before that PR, SerializationConfig had a dedicated timedelta_mode: TimedeltaMode field and to_json had no temporal_mode parameter, so timedelta_mode was genuinely independent. #1743 replaced the dedicated field with a single unified temporal_mode and retrofitted timedelta_mode as a legacy alias that maps into it.

Either the docs/.pyi should be corrected to state that timedelta_mode is a deprecated alias that affects all temporal types, or (preferably) timedelta should retain an independent setting so the documented behavior holds. Personally I have a requirement to be able to set the timedelta format independent of the other datetime types.

Example Code

import datetime
import pydantic_core

payload = {
    "dt": datetime.datetime(2026, 7, 9, 12, 0, 0),
    "d": datetime.date(2026, 7, 9),
    "t": datetime.time(12, 0, 0),
    "td": datetime.timedelta(hours=1, minutes=30),
}

# Per the docs: temporal_mode governs dt/d/t; timedelta_mode governs td.
actual = pydantic_core.to_json(
    payload, timedelta_mode="float", temporal_mode="iso8601"
).decode()

expected = '{"dt":"2026-07-09T12:00:00","d":"2026-07-09","t":"12:00:00","td":5400.0}'

print("actual  :", actual)
print("expected:", expected)
assert actual == expected, "timedelta_mode='float' wrongly coerced datetime/date/time to floats"
# AssertionError: actual == {"dt":1783598400.0,"d":1783555200.0,"t":43200.0,"td":5400.0}

Python, Pydantic & OS Version

pydantic version: 2.13.4
        pydantic-core version: 2.46.4
          pydantic-core build: profile=release pgo=false
               python version: 3.11.14 (main, Oct 10 2025, 12:48:11) [Clang 20.1.4 ]
                     platform: Linux-6.17.0-35-generic-x86_64-with-glibc2.39
             related packages: typing_extensions-4.16.0 mypy-2.2.0 email-validator-2.3.0 pydantic-settings-2.14.2 pydantic-extra-types-2.11.1
                       commit: unknown

The two patches

Our patch+40 −7
pydantic-core/src/serializers/config.rsindex 9a1377c6..f90ce9b0 100644@@ -22,6 +22,7 @@ use super::errors::py_err_se_err; #[allow(clippy::struct_field_names)] pub(crate) struct SerializationConfig {     pub temporal_mode: TemporalMode,+    pub timedelta_mode: TemporalMode,     pub bytes_mode: BytesMode,     pub inf_nan_mode: InfNanMode, }@@ -30,6 +31,7 @@ impl Default for SerializationConfig {     fn default() -> Self {         Self {             temporal_mode: TemporalMode::default(),+            timedelta_mode: TemporalMode::default(),             bytes_mode: BytesMode::default(),             inf_nan_mode: InfNanMode::Constants,         }@@ -41,8 +43,13 @@ impl SerializationConfig {         let temporal_set = config             .and_then(|cfg| cfg.contains(intern!(cfg.py(), "ser_json_temporal")).ok())             .unwrap_or(false);-        let temporal_mode = if temporal_set {-            TemporalMode::from_config(config)?+        // `temporal_mode` governs datetime/date/time; the legacy `ser_json_timedelta` alias+        // must not leak onto them.+        let temporal_mode = TemporalMode::from_config(config)?;+        // `timedelta` follows `ser_json_temporal` when it is explicitly set (so that setting+        // e.g. `seconds` also applies to timedelta), otherwise the dedicated timedelta alias.+        let timedelta_mode = if temporal_set {+            temporal_mode         } else {             TimedeltaMode::from_config(config)?.into()         };@@ -50,6 +57,7 @@ impl SerializationConfig {         let inf_nan_mode = InfNanMode::from_config(config)?;         Ok(Self {             temporal_mode,+            timedelta_mode,             bytes_mode,             inf_nan_mode,         })@@ -61,13 +69,17 @@ impl SerializationConfig {         bytes_mode: &str,         inf_nan_mode: &str,     ) -> PyResult<Self> {-        let resolved_temporal_mode = if temporal_mode != "iso8601" {-            TemporalMode::from_str(temporal_mode)?+        let resolved_temporal_mode = TemporalMode::from_str(temporal_mode)?;+        // As in `from_config`, an explicit `temporal_mode` also governs timedelta; when it is+        // left at the default the dedicated `timedelta_mode` alias takes over for timedelta only.+        let resolved_timedelta_mode = if temporal_mode != "iso8601" {+            resolved_temporal_mode         } else {             TimedeltaMode::from_str(timedelta_mode)?.into()         };         Ok(Self {             temporal_mode: resolved_temporal_mode,+            timedelta_mode: resolved_timedelta_mode,             bytes_mode: BytesMode::from_str(bytes_mode)?,             inf_nan_mode: InfNanMode::from_str(inf_nan_mode)?,         })pydantic-core/src/serializers/infer.rsindex 141a4d5f..f8aaccf9 100644@@ -164,7 +164,7 @@ pub(crate) fn infer_to_python_known<'py>(             }             ObType::Timedelta => {                 let either_delta = EitherTimedelta::try_from(value)?;-                state.config.temporal_mode.timedelta_to_json(value.py(), either_delta)?+                state.config.timedelta_mode.timedelta_to_json(value.py(), either_delta)?             }             ObType::Url             | ObType::MultiHostUrl@@ -412,7 +412,7 @@ pub(crate) fn infer_serialize_known<'py, S: Serializer>(         }         ObType::Timedelta => {             let either_delta = EitherTimedelta::try_from(value).map_err(py_err_se_err)?;-            state.config.temporal_mode.timedelta_serialize(either_delta, serializer)+            state.config.timedelta_mode.timedelta_serialize(either_delta, serializer)         }         ObType::Url         | ObType::MultiHostUrl@@ -538,7 +538,7 @@ pub(crate) fn infer_json_key_known<'a, 'py>(         }         ObType::Timedelta => {             let either_delta = EitherTimedelta::try_from(key)?;-            state.config.temporal_mode.timedelta_json_key(&either_delta)+            state.config.timedelta_mode.timedelta_json_key(&either_delta)         }         ObType::Url         | ObType::MultiHostUrlpydantic-core/tests/serializers/test_any.pyindex 3d2ca39f..8f644e9b 100644@@ -773,3 +773,24 @@ def test_ipaddress_type_inference(any_serializer, value, expected_json):     assert any_serializer.to_python(value) == value     assert any_serializer.to_python(value, mode='json') == expected_json     assert any_serializer.to_json(value) == f'"{expected_json}"'.encode()+++def test_timedelta_mode_independent_of_temporal_mode():+    payload = {+        'dt': datetime(2026, 7, 9, 12, 0, 0),+        'd': date(2026, 7, 9),+        't': time(12, 0, 0),+        'td': timedelta(hours=1, minutes=30),+    }++    # timedelta_mode governs only timedelta; temporal_mode governs datetime/date/time.+    result = pydantic_core.to_json(payload, timedelta_mode='float', temporal_mode='iso8601').decode()+    assert result == '{"dt":"2026-07-09T12:00:00","d":"2026-07-09","t":"12:00:00","td":5400.0}'++    jsonable = pydantic_core.to_jsonable_python(payload, timedelta_mode='float', temporal_mode='iso8601')+    assert jsonable == {+        'dt': '2026-07-09T12:00:00',+        'd': '2026-07-09',+        't': '12:00:00',+        'td': 5400.0,+    } 
Merged fix · PR #+49 −6
pydantic-core/python/pydantic_core/_pydantic_core.pyiindex c13dd4d21..12b8e4d49 100644@@ -449,10 +449,31 @@ def to_json(         by_alias: Whether to use the alias names of fields.         exclude_none: Whether to exclude fields that have a value of `None`.         round_trip: Whether to enable serialization and validation round-trip support.-        timedelta_mode: How to serialize `timedelta` objects, either `'iso8601'` or `'float'`.-        temporal_mode: How to serialize datetime-like objects (`datetime`, `date`, `time`), either `'iso8601'`, `'seconds'`, or `'milliseconds'`.-            `iso8601` returns an ISO 8601 string; `seconds` returns the Unix timestamp in seconds as a float; `milliseconds` returns the Unix timestamp in milliseconds as a float.+        timedelta_mode: The format of serialized timedeltas. Accepts the string values of `'iso8601'` and `'float'`. +            - `'iso8601'` will serialize timedeltas to [ISO 8601 text format](https://en.wikipedia.org/wiki/ISO_8601#Durations).+            - `'float'` will serialize timedeltas to the total number of seconds.++            /// version-changed | v2.12+            It is now recommended to use the `temporal_mode` argument. `timedelta_mode` will be deprecated in v3.+            ///+        temporal_mode: The format of serialized temporal types from the [`datetime`][] module. This includes:++            - [`datetime.datetime`][]+            - [`datetime.date`][]+            - [`datetime.time`][]+            - [`datetime.timedelta`][]++            Can be one of:++            - `'iso8601'` will serialize date-like types to [ISO 8601 text format](https://en.wikipedia.org/wiki/ISO_8601#Durations).+            - `'milliseconds'` will serialize date-like types to a floating point number of milliseconds since the epoch.+            - `'seconds'` will serialize date-like types to a floating point number of seconds since the epoch.++            /// version-added | v2.12+            This argument replaces `timedelta_mode`, which will be deprecated in v3. `temporal_mode` adds more+            configurability for the other temporal types. It takes precedence over `timedelta_mode`.+            ///         bytes_mode: How to serialize `bytes` objects, either `'utf8'`, `'base64'`, or `'hex'`.         inf_nan_mode: How to serialize `Infinity`, `-Infinity` and `NaN` values, either `'null'`, `'constants'`, or `'strings'`.         serialize_unknown: Attempt to serialize unknown types, `str(value)` will be used, if that fails@@ -534,10 +555,31 @@ def to_jsonable_python(         by_alias: Whether to use the alias names of fields.         exclude_none: Whether to exclude fields that have a value of `None`.         round_trip: Whether to enable serialization and validation round-trip support.-        timedelta_mode: How to serialize `timedelta` objects, either `'iso8601'` or `'float'`.-        temporal_mode: How to serialize datetime-like objects (`datetime`, `date`, `time`), either `'iso8601'`, `'seconds'`, or `'milliseconds'`.-            `iso8601` returns an ISO 8601 string; `seconds` returns the Unix timestamp in seconds as a float; `milliseconds` returns the Unix timestamp in milliseconds as a float.+        timedelta_mode: The format of serialized timedeltas. Accepts the string values of `'iso8601'` and `'float'`.++            - `'iso8601'` will serialize timedeltas to [ISO 8601 text format](https://en.wikipedia.org/wiki/ISO_8601#Durations).+            - `'float'` will serialize timedeltas to the total number of seconds.++            /// version-changed | v2.12+            It is now recommended to use the `temporal_mode` argument. `timedelta_mode` will be deprecated in v3.+            ///+        temporal_mode: The format of serialized temporal types from the [`datetime`][] module. This includes:++            - [`datetime.datetime`][]+            - [`datetime.date`][]+            - [`datetime.time`][]+            - [`datetime.timedelta`][]++            Can be one of:++            - `'iso8601'` will serialize date-like types to [ISO 8601 text format](https://en.wikipedia.org/wiki/ISO_8601#Durations).+            - `'milliseconds'` will serialize date-like types to a floating point number of milliseconds since the epoch.+            - `'seconds'` will serialize date-like types to a floating point number of seconds since the epoch. +            /// version-added | v2.12+            This argument replaces `timedelta_mode`, which will be deprecated in v3. `temporal_mode` adds more+            configurability for the other temporal types. It takes precedence over `timedelta_mode`.+            ///         bytes_mode: How to serialize `bytes` objects, either `'utf8'`, `'base64'`, or `'hex'`.         inf_nan_mode: How to serialize `Infinity`, `-Infinity` and `NaN` values, either `'null'`, `'constants'`, or `'strings'`.         serialize_unknown: Attempt to serialize unknown types, `str(value)` will be used, if that failspydantic/config.pyindex 5211aae83..e61029bdf 100644@@ -595,6 +595,7 @@ class ConfigDict(TypedDict, total=False):     /// version-added | v2.12     This setting replaces [`ser_json_timedelta`][pydantic.config.ConfigDict.ser_json_timedelta],     which will be deprecated in v3. `ser_json_temporal` adds more configurability for the other temporal types.+    It takes precedence over `ser_json_timedelta`.     ///     """  

What the agent reported

The fix is complete and verified. Here is my final report.

What was wrong

pydantic_core.to_json / to_jsonable_python document timedelta_mode (governs only timedelta) and temporal_mode (governs datetime/date/time) as independent, but PR #1743 collapsed them into a single temporal_mode field, retrofitting timedelta_mode as a lossy alias (float → Seconds). Because the shared SerializationConfig stored only one temporal_mode, setting timedelta_mode='float' silently coerced datetime/date/time to unix-timestamp floats too. There was no combination yielding ISO datetimes with float-second timedeltas.

What I changed

  • pydantic-core/src/serializers/config.rs — Added a separate timedelta_mode: TemporalMode field to SerializationConfig. temporal_mode (datetime/date/time) is now resolved purely from ser_json_temporal/temporal_mode, so the legacy timedelta alias no longer leaks onto them. timedelta_mode follows the explicit temporal setting when one is present (preserving the ser_json_temporal-priority behavior), otherwise the dedicated timedelta alias. Applied symmetrically in both from_config and from_args.
  • pydantic-core/src/serializers/infer.rs — Switched the three timedelta serialization sites (to_python, serde_serialize, json_key) from config.temporal_mode to config.timedelta_mode. Datetime/date/time sites unchanged.
  • pydantic-core/tests/serializers/test_any.py — Added regression test test_timedelta_mode_independent_of_temporal_mode asserting the exact reported scenario for both to_json and to_jsonable_python.

No .pyi change was needed — the docstrings already describe the now-correct behavior.

Test evidence

  • Regression test failed before the Rust change (datetime/date/time came back as 1783598400.0 etc.) and passes after ({"dt":"2026-07-09T12:00:00","d":"2026-07-09","t":"12:00:00","td":5400.0}).
  • I rebuilt the Rust extension in the test container (maturin develop), then ran the gate: ./bt-test on the serializers directory → 802 passed, 5 skipped, 1 xfailed. Notably test_config_timedelta_timedelta_ser_flag_prioritised (which asserts ser_json_temporal priority over ser_json_timedelta) still passes, confirming backward compatibility.
  • Reviewer confirmed the fix resolves the report, preserves backward compat, touches nothing unrelated, and leaves no scratch files.

Requirements disposition

  1. timedelta_mode='float', temporal_mode='iso8601' must give ISO datetimes + float timedelta — ✅ Implemented; covered by the new regression test (was failing, now passes).
  2. Preferred fix: timedelta retains an independent setting — ✅ Implemented via the separate timedelta_mode field, rather than the alternative "just fix the docs."
  3. Alternative offered (correct docs/.pyi to say timedelta_mode is a deprecated alias affecting all temporal types) — ⏭️ Skipped in favor of the report's stated preference; the existing .pyi docstrings (_pydantic_core.pyi:452-453, 537-538) already describe the independent contract and now match actual behavior, so no doc change was needed. Evidence: reviewer confirmed the docstrings match post-fix behavior.
  4. Don't break existing ser_json_temporal-priority behavior — ✅ Preserved; test_config_timedelta_timedelta_ser_flag_prioritised and all other serializer tests pass.

One non-blocking note from review: from_config detects an explicit temporal setting by key presence while from_args uses temporal_mode != "iso8601". This asymmetry is inherent to the args API (a default and an explicit "iso8601" are indistinguishable) and preserves prior config behavior, so it is not a regression.