Backtestspydanticrun-20260930-144322#13664

Issue #13664 Merged fix PR #13665 Run 30 Sep 2026 · run-20260930-144322 pydantic/pydantic

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

Worse

The merged fix was judged better than our patch.

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

Both patches fix the root cause the same way. They make `date_schema`, `time_schema` and `datetime_schema` emit `{'type': 'number'}` for `'seconds'` and `'milliseconds'`. They also make `timedelta_schema` prefer `ser_json_temporal` over `ser_json_timedelta` only when the former is explicitly set, which matches pydantic-core.

A checks precedence with `'ser_json_temporal' in config_dict`, which mirrors pydantic-core's presence check exactly. B uses `.get(...) is not None`, which is equivalent for any valid config. So on correctness they are effectively equal.

Tests are strong on both sides, and each checks the generated schema against real `model_dump_json()` output. A's precedence test is somewhat more complete. It covers both explicit-override directions plus the two legacy fallback cases where only `ser_json_timedelta` is set, which guards against regressions in the fallback path. B covers only the two override combinations, though it also checks them against the dump. B's full-schema equality assertions are slightly stricter per case.

On craft, A factors the repeated logic into a small `_common_temporal_schema` helper, so all four methods share one resolution rule. B repeats the same three-line check four times and duplicates the duration branch inside `timedelta_schema`. A's parameter named `format` shadows a builtin, which is minor.

Overall the difference is small. A wins narrowly on DRYness and more complete precedence and fallback coverage.

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

2m 59s9 turns

Wall-clock time in the container

Full test suite

No new failures

12,351 passed · 500 skipped · 12,851 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

94vs 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+94 −0
pydantic/json_schema.pyindex c2183e19..c320f067 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,6 +866,10 @@ class GenerateJsonSchema:         Returns:             The generated JSON schema.         """+        if self._config.config_dict.get('ser_json_temporal') is not None:+            if self._config.ser_json_temporal in ('seconds', 'milliseconds'):+                return {'type': 'number'}+            return {'type': 'string', 'format': 'duration'}         if self._config.ser_json_timedelta == 'float':             return {'type': 'number'}         return {'type': 'string', 'format': 'duration'}tests/test_json_schema.pyindex 9cca3292..f7ff56ce 100644@@ -1960,6 +1960,90 @@ def test_typeddict_default_timedelta(ser_json_timedelta: Literal['float', 'iso86     }  +@pytest.mark.parametrize(+    'ser_json_temporal,properties',+    [+        (+            'iso8601',+            {+                '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'},+            },+        ),+        (+            'seconds',+            {+                'dt': {'title': 'Dt', 'type': 'number'},+                'd': {'title': 'D', 'type': 'number'},+                't': {'title': 'T', 'type': 'number'},+                'td': {'title': 'Td', 'type': 'number'},+            },+        ),+        (+            'milliseconds',+            {+                'dt': {'title': 'Dt', 'type': 'number'},+                'd': {'title': 'D', 'type': 'number'},+                't': {'title': 'T', 'type': 'number'},+                'td': {'title': 'Td', 'type': 'number'},+            },+        ),+    ],+)+def test_model_ser_json_temporal(+    ser_json_temporal: Literal['iso8601', 'seconds', 'milliseconds'], properties: dict[str, Any]+):+    class Model(BaseModel):+        model_config = ConfigDict(ser_json_temporal=ser_json_temporal)++        dt: datetime+        d: date+        t: time+        td: timedelta++    schema_properties = Model.model_json_schema(mode='serialization')['properties']+    assert schema_properties == properties++    # the JSON schema must agree with the actual JSON serialization output+    model = Model(dt=datetime(2032, 1, 1, 12, 30), d=date(2032, 1, 1), t=time(12, 30), td=timedelta(minutes=5))+    dumped = json.loads(model.model_dump_json())+    for name, value in dumped.items():+        is_number = isinstance(value, (int, float)) and not isinstance(value, bool)+        assert is_number == (schema_properties[name]['type'] == 'number'), name+++@pytest.mark.parametrize(+    'ser_json_temporal,ser_json_timedelta,td_schema',+    [+        ('iso8601', 'float', {'format': 'duration', 'title': 'Td', 'type': 'string'}),+        ('seconds', 'iso8601', {'title': 'Td', 'type': 'number'}),+    ],+)+def test_model_ser_json_temporal_precedence_over_timedelta(+    ser_json_temporal: Literal['iso8601', 'seconds', 'milliseconds'],+    ser_json_timedelta: Literal['float', 'iso8601'],+    td_schema: dict[str, Any],+):+    class Model(BaseModel):+        model_config = ConfigDict(ser_json_temporal=ser_json_temporal, ser_json_timedelta=ser_json_timedelta)++        td: timedelta++    assert Model.model_json_schema(mode='serialization') == {+        'properties': {'td': td_schema},+        'required': ['td'],+        'title': 'Model',+        'type': 'object',+    }++    # the JSON schema must agree with the actual JSON serialization output+    dumped = json.loads(Model(td=timedelta(minutes=5)).model_dump_json())+    is_number = isinstance(dumped['td'], (int, float)) and not isinstance(dumped['td'], bool)+    assert is_number == (td_schema['type'] == 'number')++ @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',     [ 

What the agent reported

I fixed both schema mismatches from the report, and the tests pass. The changes are uncommitted in the working tree.

What was wrong

In pydantic/json_schema.py, GenerateJsonSchema never read ser_json_temporal:

  • date_schema, time_schema and datetime_schema always returned string schemas. With 'seconds' or 'milliseconds', model_dump_json() writes numbers, so the published schema rejected pydantic's own output.
  • timedelta_schema only looked at ser_json_timedelta. pydantic-core lets an explicitly set ser_json_temporal take precedence, so ser_json_temporal='iso8601' with ser_json_timedelta='float' produced {'type': 'number'} while the dump was 'P1D'.

What I changed

  • pydantic/json_schema.py: date_schema, time_schema and datetime_schema return {'type': 'number'} when ser_json_temporal is 'seconds' or 'milliseconds'. Otherwise they return the same strings as before.
  • timedelta_schema: if ser_json_temporal is set in the config and isn't None, it decides the result (number or duration string). Otherwise the old ser_json_timedelta logic applies, so existing configs behave the same.
  • It has to check whether the key is set: the config object fills in 'iso8601' for an unset ser_json_temporal, which would otherwise always override ser_json_timedelta.
  • It also ignores a None value, because pydantic-core never sees None-valued keys. The reviewer flagged this and I applied it.
  • The new behaviour applies in both validation and serialization mode, the same way ser_json_timedelta and ser_json_bytes already work. One side effect: in validation mode these fields are now described as numbers, even though pydantic also accepts strings on input.
  • tests/test_json_schema.py has two new tests:
  • test_model_ser_json_temporal: checks iso8601, seconds and milliseconds for all four types.
  • test_model_ser_json_temporal_precedence_over_timedelta: checks iso8601 with float, and seconds with iso8601.

Both assert the exact schema and also check that each value in model_dump_json() is a number exactly when the schema says number.

Test evidence

  • Before the fix: 4 of the 5 new cases failed (seconds, milliseconds and both precedence cases). The iso8601 case passed, as expected.
  • After the fix: ./bt-test tests/test_json_schema.py tests/test_datetime.py tests/test_types.py tests/test_config.py gave 1135 passed, 6 skipped, 2 xfailed, 0 failed. That run includes the existing ser_json_timedelta tests for models, dataclasses and TypedDicts.
  • No existing test was changed, and no scratch files were left behind.

Requirements

  1. ser_json_temporal='seconds' makes the schema say number for datetime, date, time and timedelta: done, covered by test_model_ser_json_temporal[seconds].
  2. Same for 'milliseconds': done, covered by [milliseconds].
  3. iso8601 still gives string schemas: unchanged, covered by [iso8601].
  4. ser_json_temporal takes precedence over ser_json_timedelta for timedelta: done, covered by both precedence cases.
  5. The report's example, where the schema contradicted the dump: covered. Both tests check the dumped JSON types against the schema.
  6. Default values in the schema: I changed nothing here. The reviewer checked encode_default: defaults are dumped with the model's own config first, so ser_json_temporal already applies to them. No test covers this case specifically.

The new tests only cover BaseModel. Dataclasses and TypedDicts go through the same config lookup, and their existing ser_json_timedelta tests still pass, but there's no new test with ser_json_temporal for them.