Backtestspydanticrun-20261022-024030#13664

Issue #13664 Merged fix PR #13665 Run 22 Oct 2026 · run-20261022-024030 pydantic/pydantic

JSON Schema ignores ser_json_temporal, so serialization schemas contradict model_dump_json() output

Better

Our patch was judged better than the merged fix.

In this judgment, Patch B = our agent, Patch A = the merged fix.

Both patches fix the root cause the same way: date/time/datetime schemas now consult `ser_json_temporal`, and `timedelta_schema` mirrors pydantic-core by checking for the key's presence in `config_dict` before falling back to `ser_json_timedelta`. All independent tests pass on both, so they are equivalent on the issue's core scenarios. Patch A is slightly cleaner (one `_common_temporal_schema` helper, explicit Literal typing), while B repeats the `in ('seconds', 'milliseconds')` check four times. B pulls ahead on completeness and tests: it also updates `encode_default` so the `to_jsonable_python` fallback (used for stdlib dataclass defaults that bypass the TypeAdapter path) honors `ser_json_temporal` precedence, which is the same schema-vs-dump contradiction the issue describes applied to `default` values, and it adds a test proving the default equals the actual `model_dump_json()` output. B's test matrix is also broader and more discriminating: it covers unset config, `ser_json_temporal` alone, both precedence directions, `ser_json_timedelta` alone (confirming it still only affects timedelta), nested-model config isolation via `$defs`, and defaults under each temporal mode, each asserting against the real dump. A's tests cover the main cases and precedence but not nested config or the default-encoding path. The extra `encode_default` change in B is low risk (it only triggers when `ser_json_temporal` is explicitly set and passes the mode pydantic-core already supports). Net: B is the more thorough fix with stronger tests; A's helper refactor is a minor craft advantage that does not outweigh that.

Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.

Solve

7m 18s

Wall-clock time in the container

Full test suite

No new failures

1,232 passed · 15 skipped · 1,247 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

169vs 88 merged

Changed lines, ours vs merged

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

ser_json_temporal landed in v2.12 and controls how datetime, date, time and timedelta are serialized to JSON. GenerateJsonSchema was never told about it, so a mode='serialization' schema still says these fields are strings even when model_dump_json() writes numbers.

With ser_json_temporal='seconds' (same with 'milliseconds'), every temporal field is affected:

schema:  {'dt': {'type': 'string', 'format': 'date-time'}, 'td': {'type': 'string', 'format': 'duration'}}
dump:    {'dt': 1577836800.0, 'td': 86400.0}

Running that payload through a JSON Schema validator fails with 1577836800.0 is not of type 'string', so the schema pydantic publishes rejects the output pydantic itself just produced. date_schema, time_schema and datetime_schema read no config at all right now.

There is a second mismatch that goes the other way, on timedelta. timedelta_schema only looks at the older ser_json_timedelta setting. The docs for ser_json_temporal say it takes precedence over ser_json_timedelta, and pydantic-core implements exactly that: SerializationConfig::from_config and TimeDeltaSerializer::build both check whether ser_json_temporal is present in the config before falling back to ser_json_timedelta. The JSON schema layer does not, so setting ser_json_temporal='iso8601' together with ser_json_timedelta='float' gives you the reverse problem:

schema:  {'td': {'type': 'number'}}
dump:    {'td': 'P1D'}

For anyone generating an OpenAPI document from a model this is a silent wrong answer rather than a crash, which is probably why it has gone unnoticed since the setting was added.

I have a patch that mirrors the pydantic-core resolution in the four temporal schema methods, plus tests. Happy to open a PR if you want to assign this to me.

Example Code

import json
from datetime import date, datetime, time, timedelta

from pydantic import BaseModel, ConfigDict


class Numeric(BaseModel):
    model_config = ConfigDict(ser_json_temporal='seconds')

    dt: datetime
    d: date
    t: time
    td: timedelta


model = Numeric(dt=datetime(2020, 1, 1), d=date(2020, 1, 1), t=time(12, 0), td=timedelta(days=1))

print(Numeric.model_json_schema(mode='serialization')['properties'])
#> {'dt': {'format': 'date-time', 'title': 'Dt', 'type': 'string'},
#>  'd': {'format': 'date', 'title': 'D', 'type': 'string'},
#>  't': {'format': 'time', 'title': 'T', 'type': 'string'},
#>  'td': {'format': 'duration', 'title': 'Td', 'type': 'string'}}

print(json.loads(model.model_dump_json()))
#> {'dt': 1577836800.0, 'd': 1577836800.0, 't': 43200.0, 'td': 86400.0}


# The timedelta precedence case, wrong in the opposite direction:
class Precedence(BaseModel):
    model_config = ConfigDict(ser_json_temporal='iso8601', ser_json_timedelta='float')

    td: timedelta


print(Precedence.model_json_schema(mode='serialization')['properties'])
#> {'td': {'title': 'Td', 'type': 'number'}}

print(json.loads(Precedence(td=timedelta(days=1)).model_dump_json()))
#> {'td': 'P1D'}

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.12.13 (main, May 10 2026, 19:20:41) [Clang 22.1.3 ]
                     platform: macOS-15.7.4-arm64-arm-64bit
             related packages: typing_extensions-4.16.0
                       commit: unknown

Also reproduces on main (2.14.0b1 / pydantic-core 2.48.0).

The two patches

Our patch+168 −1
pydantic/json_schema.pyindex c2183e19..dfc66f4a 100644@@ -827,6 +827,8 @@ class GenerateJsonSchema:         Returns:             The generated JSON schema.         """+        if self._config.ser_json_temporal in ('seconds', 'milliseconds'):+            return {'type': 'number'}         return {'type': 'string', 'format': 'date'}      def time_schema(self, schema: core_schema.TimeSchema) -> JsonSchemaValue:@@ -838,6 +840,8 @@ class GenerateJsonSchema:         Returns:             The generated JSON schema.         """+        if self._config.ser_json_temporal in ('seconds', 'milliseconds'):+            return {'type': 'number'}         return {'type': 'string', 'format': 'time'}      def datetime_schema(self, schema: core_schema.DatetimeSchema) -> JsonSchemaValue:@@ -849,6 +853,8 @@ class GenerateJsonSchema:         Returns:             The generated JSON schema.         """+        if self._config.ser_json_temporal in ('seconds', 'milliseconds'):+            return {'type': 'number'}         return {'type': 'string', 'format': 'date-time'}      def timedelta_schema(self, schema: core_schema.TimedeltaSchema) -> JsonSchemaValue:@@ -860,7 +866,12 @@ class GenerateJsonSchema:         Returns:             The generated JSON schema.         """-        if self._config.ser_json_timedelta == 'float':+        # Mirror pydantic-core: `ser_json_temporal` takes precedence over `ser_json_timedelta` when it is set:+        if self._config.config_dict.get('ser_json_temporal') is not None:+            is_number = self._config.ser_json_temporal in ('seconds', 'milliseconds')+        else:+            is_number = self._config.ser_json_timedelta == 'float'+        if is_number:             return {'type': 'number'}         return {'type': 'string', 'format': 'duration'} @@ -2451,6 +2462,14 @@ class GenerateJsonSchema:         except PydanticSchemaGenerationError:             raise pydantic_core.PydanticSerializationError(f'Unable to encode default value {dft}') +        # Mirror pydantic-core: `ser_json_temporal` takes precedence over `ser_json_timedelta` when it is set:+        if config.config_dict.get('ser_json_temporal') is not None:+            return pydantic_core.to_jsonable_python(+                default,+                temporal_mode=config.ser_json_temporal,+                bytes_mode=config.ser_json_bytes,+                by_alias=self.by_alias,+            )         return pydantic_core.to_jsonable_python(             default, timedelta_mode=config.ser_json_timedelta, bytes_mode=config.ser_json_bytes, by_alias=self.by_alias         )tests/test_json_schema.pyindex 9cca3292..196a5ea6 100644@@ -1878,6 +1878,154 @@ def test_model_default_timedelta(ser_json_timedelta: Literal['float', 'iso8601']     }  +@pytest.mark.parametrize(+    'config,dt_schema,d_schema,t_schema,td_schema',+    [+        (+            {},+            {'type': 'string', 'format': 'date-time'},+            {'type': 'string', 'format': 'date'},+            {'type': 'string', 'format': 'time'},+            {'type': 'string', 'format': 'duration'},+        ),+        (+            {'ser_json_temporal': 'iso8601'},+            {'type': 'string', 'format': 'date-time'},+            {'type': 'string', 'format': 'date'},+            {'type': 'string', 'format': 'time'},+            {'type': 'string', 'format': 'duration'},+        ),+        (+            {'ser_json_temporal': 'seconds'},+            {'type': 'number'},+            {'type': 'number'},+            {'type': 'number'},+            {'type': 'number'},+        ),+        (+            {'ser_json_temporal': 'milliseconds'},+            {'type': 'number'},+            {'type': 'number'},+            {'type': 'number'},+            {'type': 'number'},+        ),+        # `ser_json_temporal` takes precedence over `ser_json_timedelta`:+        (+            {'ser_json_temporal': 'iso8601', 'ser_json_timedelta': 'float'},+            {'type': 'string', 'format': 'date-time'},+            {'type': 'string', 'format': 'date'},+            {'type': 'string', 'format': 'time'},+            {'type': 'string', 'format': 'duration'},+        ),+        (+            {'ser_json_temporal': 'seconds', 'ser_json_timedelta': 'iso8601'},+            {'type': 'number'},+            {'type': 'number'},+            {'type': 'number'},+            {'type': 'number'},+        ),+        # `ser_json_timedelta` alone only affects `timedelta`:+        (+            {'ser_json_timedelta': 'float'},+            {'type': 'string', 'format': 'date-time'},+            {'type': 'string', 'format': 'date'},+            {'type': 'string', 'format': 'time'},+            {'type': 'number'},+        ),+    ],+)+def test_ser_json_temporal_schema_matches_dump(+    config: ConfigDict,+    dt_schema: dict[str, Any],+    d_schema: dict[str, Any],+    t_schema: dict[str, Any],+    td_schema: dict[str, Any],+) -> None:+    class Model(BaseModel):+        model_config = config++        dt: datetime+        d: date+        t: time+        td: timedelta++    expected = {'dt': dt_schema, 'd': d_schema, 't': t_schema, 'td': td_schema}+    properties = Model.model_json_schema(mode='serialization')['properties']+    assert {name: {k: v for k, v in prop.items() if k != 'title'} for name, prop in properties.items()} == expected++    # The published schema type must agree with what `model_dump_json()` actually produces:+    dumped = json.loads(+        Model(dt=datetime(2020, 1, 1), d=date(2020, 1, 1), t=time(12, 0), td=timedelta(days=1)).model_dump_json()+    )+    for name, value in dumped.items():+        expected_type = (int, float) if expected[name]['type'] == 'number' else str+        assert isinstance(value, expected_type), (name, value)+++def test_ser_json_temporal_nested_model_config() -> None:+    class Inner(BaseModel):+        model_config = ConfigDict(ser_json_temporal='milliseconds')++        dt: datetime++    class Outer(BaseModel):+        inner: Inner+        dt: datetime++    schema = Outer.model_json_schema(mode='serialization')+    assert schema['$defs']['Inner']['properties']['dt'] == {'title': 'Dt', 'type': 'number'}+    assert schema['properties']['dt'] == {'title': 'Dt', 'type': 'string', 'format': 'date-time'}+++@pytest.mark.parametrize(+    'ser_json_temporal,properties',+    [+        ('seconds', {'duration': {'default': 300.0, 'title': 'Duration', 'type': 'number'}}),+        ('milliseconds', {'duration': {'default': 300000.0, 'title': 'Duration', 'type': 'number'}}),+        ('iso8601', {'duration': {'default': 'PT5M', 'format': 'duration', 'title': 'Duration', 'type': 'string'}}),+    ],+)+def test_model_default_timedelta_ser_json_temporal(+    ser_json_temporal: Literal['seconds', 'milliseconds', 'iso8601'], properties: dict[str, Any]+):+    class Model(BaseModel):+        model_config = ConfigDict(ser_json_temporal=ser_json_temporal, ser_json_timedelta='float')++        duration: timedelta = timedelta(minutes=5)++    assert Model.model_json_schema(mode='serialization') == {+        'properties': properties,+        'title': 'Model',+        'type': 'object',+    }+++@pytest.mark.parametrize(+    'config,expected_default',+    [+        ({'ser_json_temporal': 'seconds'}, {'dt': 1577836800.0, 'td': 86400.0}),+        ({'ser_json_temporal': 'milliseconds'}, {'dt': 1577836800000.0, 'td': 86400000.0}),+        ({'ser_json_temporal': 'iso8601', 'ser_json_timedelta': 'float'}, {'dt': '2020-01-01T00:00:00', 'td': 'P1D'}),+    ],+)+def test_model_default_stdlib_dataclass_ser_json_temporal(config: ConfigDict, expected_default: dict[str, Any]):+    """Defaults that bypass the `TypeAdapter` dump in `encode_default` must also honor `ser_json_temporal`."""++    @dataclasses.dataclass+    class Plain:+        dt: datetime+        td: timedelta++    class Model(BaseModel):+        model_config = config++        plain: Plain = Plain(dt=datetime(2020, 1, 1), td=timedelta(days=1))++    default = Model.model_json_schema(mode='serialization')['properties']['plain']['default']+    assert default == expected_default+    assert default == json.loads(Model().model_dump_json())['plain']++ @pytest.mark.parametrize(     'ser_json_bytes,properties',     [ 
Merged fix · PR #13665+83 −5
pydantic/json_schema.pyindex c2183e193..aa330bc66 100644@@ -827,7 +827,7 @@ class GenerateJsonSchema:         Returns:             The generated JSON schema.         """-        return {'type': 'string', 'format': 'date'}+        return self._common_temporal_schema('date', self._config.ser_json_temporal)      def time_schema(self, schema: core_schema.TimeSchema) -> JsonSchemaValue:         """Generates a JSON schema that matches a time value.@@ -838,7 +838,7 @@ class GenerateJsonSchema:         Returns:             The generated JSON schema.         """-        return {'type': 'string', 'format': 'time'}+        return self._common_temporal_schema('time', self._config.ser_json_temporal)      def datetime_schema(self, schema: core_schema.DatetimeSchema) -> JsonSchemaValue:         """Generates a JSON schema that matches a datetime value.@@ -849,7 +849,7 @@ class GenerateJsonSchema:         Returns:             The generated JSON schema.         """-        return {'type': 'string', 'format': 'date-time'}+        return self._common_temporal_schema('date-time', self._config.ser_json_temporal)      def timedelta_schema(self, schema: core_schema.TimedeltaSchema) -> JsonSchemaValue:         """Generates a JSON schema that matches a timedelta value.@@ -860,9 +860,21 @@ class GenerateJsonSchema:         Returns:             The generated JSON schema.         """-        if self._config.ser_json_timedelta == 'float':+        if 'ser_json_temporal' in self._config.config_dict:+            temporal_format = self._config.ser_json_temporal+        else:+            # `ser_json_temporal` supersedes `ser_json_timedelta`, which only applies when the former isn't+            # explicitly set.+            temporal_format = 'seconds' if self._config.ser_json_timedelta == 'float' else 'iso8601'+        return self._common_temporal_schema('duration', temporal_format)++    def _common_temporal_schema(+        self, format: str, temporal_format: Literal['iso8601', 'seconds', 'milliseconds']+    ) -> JsonSchemaValue:+        if temporal_format != 'iso8601':+            # Both `'seconds'` and `'milliseconds'` serialize to a number:             return {'type': 'number'}-        return {'type': 'string', 'format': 'duration'}+        return {'type': 'string', 'format': format}      def literal_schema(self, schema: core_schema.LiteralSchema) -> JsonSchemaValue:         """Generates a JSON schema that matches a literal value.tests/test_json_schema.pyindex 9cca32928..5157bdb80 100644@@ -830,6 +830,72 @@ def test_date_types(field_type, expected_schema):     assert Model.model_json_schema() == base_schema  +@pytest.mark.parametrize('ser_json_temporal', ['iso8601', 'seconds', 'milliseconds'])+@pytest.mark.parametrize(+    'field_type,iso8601_format',+    [+        (datetime, 'date-time'),+        (date, 'date'),+        (time, 'time'),+        (timedelta, 'duration'),+    ],+)+def test_date_types_ser_json_temporal(field_type, iso8601_format, ser_json_temporal):+    """https://github.com/pydantic/pydantic/issues/13664"""++    class Model(BaseModel):+        model_config = ConfigDict(ser_json_temporal=ser_json_temporal)++        a: field_type++    if ser_json_temporal == 'iso8601':+        expected_schema = {'title': 'A', 'type': 'string', 'format': iso8601_format}+    else:+        expected_schema = {'title': 'A', 'type': 'number'}++    assert Model.model_json_schema(mode='serialization')['properties']['a'] == expected_schema+++@pytest.mark.parametrize('ser_json_temporal', ['iso8601', 'seconds', 'milliseconds'])+def test_date_types_ser_json_temporal_matches_serialized_output(ser_json_temporal):+    class Model(BaseModel):+        model_config = ConfigDict(ser_json_temporal=ser_json_temporal)++        dt: datetime+        d: date+        t: time+        td: timedelta++    model = Model(dt=datetime(2020, 1, 1), d=date(2020, 1, 1), t=time(12, 0), td=timedelta(days=1))+    properties = Model.model_json_schema(mode='serialization')['properties']+    expected_type = 'string' if ser_json_temporal == 'iso8601' else 'number'++    for field_name, value in json.loads(model.model_dump_json()).items():+        assert properties[field_name]['type'] == expected_type+        if ser_json_temporal == 'iso8601':+            assert isinstance(value, str)+        else:+            assert isinstance(value, float)+++@pytest.mark.parametrize(+    'config,expected_schema',+    [+        ({'ser_json_timedelta': 'float'}, {'type': 'number'}),+        ({'ser_json_timedelta': 'iso8601'}, {'type': 'string', 'format': 'duration'}),+        ({'ser_json_temporal': 'seconds', 'ser_json_timedelta': 'iso8601'}, {'type': 'number'}),+        ({'ser_json_temporal': 'iso8601', 'ser_json_timedelta': 'float'}, {'type': 'string', 'format': 'duration'}),+    ],+)+def test_timedelta_ser_json_temporal_takes_precedence(config, expected_schema):+    class Model(BaseModel):+        model_config = config++        a: timedelta++    assert Model.model_json_schema(mode='serialization')['properties']['a'] == {'title': 'A', **expected_schema}++ @pytest.mark.parametrize(     'interval',     [