Backtestspydanticrun-20260923-170312#13664
JSON Schema ignores ser_json_temporal, so serialization schemas contradict model_dump_json() output
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Both patches correctly handle every scenario the issue explicitly describes (all issue cases set `ser_json_temporal`, so both read a concrete 'seconds'/'milliseconds'/'iso8601' value). The deciding factor is how each handles the *default* config path in date/time/datetime. Patch A returns a number only when the value is explicitly `in ('seconds','milliseconds')`, so any unset/default/unrecognized value fails safe to `{'type':'string','format':...}` — the correct default serialization schema regardless of what the config default actually resolves to. Patch B instead passes the raw `self._config.ser_json_temporal` into `_common_temporal_schema`, which returns `{'type':'number'}` for *anything that isn't exactly the string 'iso8601'*. Its correctness therefore depends on the resolved default of `ser_json_temporal` being literally 'iso8601'; if that default is `None` (as pydantic-core treats it — SerializationConfig checks presence rather than assuming a string), every temporal field's serialization schema silently becomes `number` by default, a fail-open regression worse than the original bug. Notably, B's own signature types `temporal_format` as `Literal['iso8601','seconds','milliseconds']`, which a `None` default would violate, and B's tests never exercise the unset-default case, so the risk is untested. Both timedelta-precedence implementations are equivalent and correct (guarding on `'ser_json_temporal' in config_dict`). On tests, B is actually stronger — its schema-vs-`model_dump_json` cross-check and 4-row precedence matrix are excellent and directly validate the issue's thesis, better than A's simpler asserts — and B's single-helper refactor is slightly cleaner. But correctness is the top-ranked criterion: A is robust across all configurations with no downside, whereas B couples core correctness to an unverifiable assumption about the config default. A is the safer root-cause fix.
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
13m 52s8 turns
Wall-clock time in the container
Full test suite
No new failures
6,571 passed · 367 skipped · 6,938 total
Contamination audit
Unknown
See the audit notes for this run
Patch size
59vs 88 merged
Changed lines, ours vs merged
The issue
View on GitHubInitial 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
pydantic/json_schema.pyindex c2183e19..e9802991 100644@@ -827,6 +827,8 @@ class GenerateJsonSchema: Returns: The generated JSON schema. """+ if self._temporal_serialized_as_number():+ 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._temporal_serialized_as_number():+ return {'type': 'number'} return {'type': 'string', 'format': 'time'} def datetime_schema(self, schema: core_schema.DatetimeSchema) -> JsonSchemaValue:@@ -849,8 +853,14 @@ class GenerateJsonSchema: Returns: The generated JSON schema. """+ if self._temporal_serialized_as_number():+ return {'type': 'number'} return {'type': 'string', 'format': 'date-time'} + def _temporal_serialized_as_number(self) -> bool:+ """Whether temporal types are serialized as JSON numbers per `ser_json_temporal`."""+ return self._config.ser_json_temporal in ('seconds', 'milliseconds')+ def timedelta_schema(self, schema: core_schema.TimedeltaSchema) -> JsonSchemaValue: """Generates a JSON schema that matches a timedelta value. @@ -860,6 +870,12 @@ class GenerateJsonSchema: Returns: The generated JSON schema. """+ # `ser_json_temporal` takes precedence over `ser_json_timedelta` when explicitly set,+ # matching pydantic-core's precedence based on presence in the config dict.+ if 'ser_json_temporal' in self._config.config_dict:+ 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..e204193a 100644@@ -1878,6 +1878,49 @@ def test_model_default_timedelta(ser_json_timedelta: Literal['float', 'iso8601'] } +@pytest.mark.parametrize('ser_json_temporal', ['seconds', 'milliseconds'])+def test_ser_json_temporal_json_schema_number(ser_json_temporal: Literal['seconds', 'milliseconds']):+ class Model(BaseModel):+ model_config = ConfigDict(ser_json_temporal=ser_json_temporal)++ dt: datetime+ d: date+ t: time+ td: timedelta++ schema = Model.model_json_schema(mode='serialization')+ assert schema['properties']['dt'] == {'type': 'number', 'title': 'Dt'}+ assert schema['properties']['d'] == {'type': 'number', 'title': 'D'}+ assert schema['properties']['t'] == {'type': 'number', 'title': 'T'}+ assert schema['properties']['td'] == {'type': 'number', 'title': 'Td'}+++def test_ser_json_temporal_json_schema_iso8601():+ class Model(BaseModel):+ model_config = ConfigDict(ser_json_temporal='iso8601')++ dt: datetime+ d: date+ t: time+ td: timedelta++ schema = Model.model_json_schema(mode='serialization')+ assert schema['properties']['dt'] == {'type': 'string', 'format': 'date-time', 'title': 'Dt'}+ assert schema['properties']['d'] == {'type': 'string', 'format': 'date', 'title': 'D'}+ assert schema['properties']['t'] == {'type': 'string', 'format': 'time', 'title': 'T'}+ assert schema['properties']['td'] == {'type': 'string', 'format': 'duration', 'title': 'Td'}+++def test_ser_json_temporal_takes_precedence_over_ser_json_timedelta():+ class Model(BaseModel):+ model_config = ConfigDict(ser_json_temporal='iso8601', ser_json_timedelta='float')++ td: timedelta++ schema = Model.model_json_schema(mode='serialization')+ assert schema['properties']['td'] == {'type': 'string', 'format': 'duration', 'title': 'Td'}++ @pytest.mark.parametrize( 'ser_json_bytes,properties', [
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
The fix is complete and reviewed. Summary follows.
What was wrong
GenerateJsonSchema never consulted the ser_json_temporal config setting (added in v2.12). In pydantic/json_schema.py:
date_schema,time_schema,datetime_schemareturned hardcoded string+format dicts, reading no config at all. Withser_json_temporal='seconds'/'milliseconds',model_dump_json()emits numbers, so the published serialization schema rejected pydantic's own output.timedelta_schemaonly read the olderser_json_timedelta. Butser_json_temporaltakes precedence (pydantic-core keys this off the presence ofser_json_temporalin the config dict), soser_json_temporal='iso8601'+ser_json_timedelta='float'gave{'type': 'number'}while the dump was'P1D'.
What I changed
pydantic/json_schema.py only (production):
- Added a helper
_temporal_serialized_as_number()returningTruewhenser_json_temporalis'seconds'/'milliseconds'. date_schema/time_schema/datetime_schemanow return{'type': 'number'}in that case, else the original string+format.timedelta_schemanow mirrors pydantic-core precedence: if'ser_json_temporal' in self._config.config_dict, use it (number vs.durationstring); otherwise fall back to the existingser_json_timedeltabehavior — preservingser_json_timedelta='float'→ number.
tests/test_json_schema.py: three regression tests (test_ser_json_temporal_json_schema_number parametrized over seconds/milliseconds, ..._iso8601, and ..._takes_precedence_over_ser_json_timedelta).
Test evidence
- Before the fix:
./bt-test tests/test_json_schema.py -k ser_json_temporal→ 3 failed, 1 passed. - After the fix:
./bt-test tests/test_json_schema.py -k "ser_json_temporal or timedelta"→ 11 passed, 531 deselected (includes the untouched existing*_default_timedeltatests, confirming no regression to theser_json_timedeltafallback path).
Reviewer confirmed correctness, valid presence check, correct precedence, and no unrelated/scratch changes.
Requirements list
- datetime/date/time schemas honor
ser_json_temporalnumeric modes — implemented, tested (test_ser_json_temporal_json_schema_number), passing. ser_json_temporal='iso8601'still yields string+format — implemented, tested (test_ser_json_temporal_json_schema_iso8601), passing.timedeltaprecedence:ser_json_temporaloverridesser_json_timedelta— implemented, tested (test_ser_json_temporal_takes_precedence_over_ser_json_timedelta), passing.- Preserve existing
ser_json_timedelta='float'behavior whenser_json_temporalunset — preserved via presence-based fallback; existing*_default_timedeltatests still pass.
Changes are left uncommitted in the working tree.