Backtestspydanticrun-20261005-183002#13675
TypeAdapter config not used for JSON Schema generation
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 reported case the same way: `TypeAdapter.json_schema()` now pushes `self._config` onto the generator's config stack. `TypeAdapter(bytes, config={'ser_json_bytes': 'base64'}).json_schema()` will therefore yield `format: base64url` under either patch.
Patch A stops there. It leaves the sibling API `TypeAdapter.json_schemas()` broken: adapters passed to it still have their config ignored. That is the same root cause, reached through the other public entry point for adapter JSON schema generation.
Patch B also fixes `json_schemas()`. It records a per-input config and pushes it around both `generate_inner` passes in `generate_definitions`. Setting a private `_inputs_configs` attribute after construction is a little awkward, but it is contained and defaults to no-op behavior.
B also fixes a closely related inconsistency. Stdlib dataclasses and TypedDicts without their own config used to push `{}`, which reset to default config. They now push `None`, so they inherit the parent config. This matches how core schema generation treats them. Without it, `TypeAdapter(list[SomeTypedDict], config=...)` would still emit the wrong schema for nested fields, so the config fix would not hold for those types. B is careful here: it keeps `{}` for the `_update_class_schema` / extra-behavior uses, so only the config-stack semantics change.
Tests: A has one test (`list[bytes]`), which would fail before the fix. B tests more:
- the exact issue case and the default case;
- `ser_json_temporal`;
- `json_schema_mode_override`;
- `json_schemas` with mixed configs, which checks that config does not leak between inputs;
- nested dataclass/TypedDict inheritance, for both TypeAdapter and BaseModel.
These are meaningful regression tests. B's extra changes stay within the issue's theme (config honored in JSON schema) and add little risk. B is the more complete and better-tested 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
9m 51s
Wall-clock time in the container
Full test suite
No new failures
12,373 passed · 500 skipped · 12,873 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
96vs 11 merged
Changed lines, ours vs merged
The issue
View on GitHubfrom pydantic import BaseModel, TypeAdapter
class Model(BaseModel, ser_json_bytes='base64'):
b: bytes
Model.model_json_schema()['properties']['b']
#> {'format': 'base64url', 'title': 'B', 'type': 'string'}
ta = TypeAdapter(bytes, config={'ser_json_bytes': 'base64'})
ta.json_schema()
#> {'format': 'binary', 'type': 'string'}The two patches
Our patch+83 −13
pydantic/json_schema.pyindex e7abcad0..cb2ed1ac 100644@@ -285,6 +285,9 @@ class GenerateJsonSchema: self.definitions: dict[DefsRef, JsonSchemaValue] = {} self._config_wrapper_stack = _config.ConfigWrapperStack(_config.ConfigWrapper({}))+ # Configs (e.g. from a `TypeAdapter`) that apply to the input at the same index in `generate_definitions()`,+ # as such configs are not carried by the core schema itself:+ self._inputs_configs: Sequence[_config.ConfigWrapper | None] | None = None self._mode: JsonSchemaMode = 'validation' @@ -379,16 +382,20 @@ class GenerateJsonSchema: code='json-schema-already-used', ) - for _, mode, schema in inputs:+ input_configs = self._inputs_configs if self._inputs_configs is not None else [None] * len(inputs)++ for (_, mode, schema), config in zip(inputs, input_configs): self._mode = mode- self.generate_inner(schema)+ with self._config_wrapper_stack.push(config):+ self.generate_inner(schema) definitions_remapping = self._build_definitions_remapping() json_schemas_map: dict[tuple[JsonSchemaKeyT, JsonSchemaMode], DefsRef] = {}- for key, mode, schema in inputs:+ for (key, mode, schema), config in zip(inputs, input_configs): self._mode = mode- json_schema = self.generate_inner(schema)+ with self._config_wrapper_stack.push(config):+ json_schema = self.generate_inner(schema) json_schemas_map[(key, mode)] = definitions_remapping.remap_json_schema(json_schema) json_schema = {'$defs': self.definitions}@@ -1532,8 +1539,10 @@ class GenerateJsonSchema: if self.mode == 'serialization': named_required_fields.extend(self._name_required_computed_fields(schema.get('computed_fields', []))) cls = schema.get('cls')- config = _get_typed_dict_config(cls)- with self._config_wrapper_stack.push(config):+ # if a typed dict doesn't have config, the parent's config is used (as in core schema generation):+ pushed_config = _get_typed_dict_config(cls)+ config = pushed_config if pushed_config is not None else {}+ with self._config_wrapper_stack.push(pushed_config): json_schema = self._named_required_fields_schema(named_required_fields) # There's some duplication between `extra_behavior` and@@ -1886,9 +1895,11 @@ class GenerateJsonSchema: """ cls = schema['cls']- config = cast('ConfigDict', getattr(cls, '__pydantic_config__', {}))+ # if a (plain) dataclass doesn't have config, the parent's config is used (as in core schema generation):+ pushed_config = cast('ConfigDict | None', getattr(cls, '__pydantic_config__', None))+ config = pushed_config if pushed_config is not None else {} - with self._config_wrapper_stack.push(config):+ with self._config_wrapper_stack.push(pushed_config): json_schema = self.generate_inner(schema['schema']).copy() self._update_class_schema(json_schema, cls, config)@@ -2997,13 +3008,13 @@ else: return hash(type(self)) -def _get_typed_dict_config(cls: type[Any] | None) -> ConfigDict:+def _get_typed_dict_config(cls: type[Any] | None) -> ConfigDict | None: if cls is not None: try: return _decorators.get_attribute_from_bases(cls, '__pydantic_config__') except AttributeError: pass- return {}+ return None def _get_ser_schema_for_default_value(schema: CoreSchema) -> core_schema.PlainSerializerFunctionSerSchema | None:pydantic/type_adapter.pyindex 447ac34b..fa52ae06 100644@@ -736,7 +736,8 @@ class TypeAdapter(Generic[T]): if isinstance(self.core_schema, _mock_val_ser.MockCoreSchema): self.core_schema.rebuild() assert not isinstance(self.core_schema, _mock_val_ser.MockCoreSchema), 'this is a bug! please report it'- return schema_generator_instance.generate(self.core_schema, mode=mode)+ with schema_generator_instance._config_wrapper_stack.push(self._config):+ return schema_generator_instance.generate(self.core_schema, mode=mode) @staticmethod def json_schemas(@@ -785,6 +786,7 @@ class TypeAdapter(Generic[T]): ) inputs_ = []+ inputs_configs: list[_config.ConfigWrapper | None] = [] for key, mode, adapter in inputs: # This is the same pattern we follow for model json schemas - we attempt a core schema rebuild if we detect a mock if isinstance(adapter.core_schema, _mock_val_ser.MockCoreSchema):@@ -793,7 +795,11 @@ class TypeAdapter(Generic[T]): 'this is a bug! please report it' ) inputs_.append((key, mode, adapter.core_schema))+ inputs_configs.append(+ _config.ConfigWrapper(adapter._config, check=False) if adapter._config is not None else None+ ) + schema_generator_instance._inputs_configs = inputs_configs json_schemas_map, definitions = schema_generator_instance.generate_definitions(inputs_) json_schema: dict[str, Any] = {}tests/test_type_adapter.pyindex ad746451..d6f8b7a7 100644@@ -1,13 +1,13 @@ import json from dataclasses import dataclass-from datetime import date, datetime+from datetime import date, datetime, timedelta from typing import Annotated, Any, ForwardRef, Generic, NamedTuple, TypeAlias, TypeVar, Union import pytest from pydantic_core import ValidationError from typing_extensions import TypedDict -from pydantic import BaseModel, Field, TypeAdapter, ValidationInfo, create_model, field_validator+from pydantic import BaseModel, Field, PlainSerializer, TypeAdapter, ValidationInfo, create_model, field_validator from pydantic._internal import _mock_val_ser from pydantic._internal._typing_extra import annotated_type from pydantic.config import ConfigDict@@ -757,3 +757,56 @@ def test_validate_json_invalid_json(): 'ctx': {'error': 'trailing comma at line 3 column 3'}, } ]+++def test_json_schema_uses_type_adapter_config() -> None:+ """https://github.com/pydantic/pydantic/issues/13675"""+ assert TypeAdapter(bytes).json_schema() == {'type': 'string', 'format': 'binary'}+ assert TypeAdapter(bytes, config={'ser_json_bytes': 'base64'}).json_schema() == {+ 'type': 'string',+ 'format': 'base64url',+ }++ ta_timedelta = TypeAdapter(timedelta, config={'ser_json_temporal': 'milliseconds'})+ assert ta_timedelta.json_schema(mode='serialization') == {'type': 'number'}++ ta_mode_override = TypeAdapter(+ Annotated[int, PlainSerializer(str, return_type=str)], config={'json_schema_mode_override': 'serialization'}+ )+ assert ta_mode_override.json_schema(mode='validation') == {'type': 'string'}+++def test_json_schemas_uses_each_type_adapter_config() -> None:+ json_schemas_map, top_level_schema = TypeAdapter.json_schemas(+ [+ ('default', 'validation', TypeAdapter(bytes)),+ ('base64', 'validation', TypeAdapter(bytes, config={'ser_json_bytes': 'base64'})),+ ('default_again', 'validation', TypeAdapter(list[bytes])),+ ]+ )+ assert top_level_schema == {}+ assert json_schemas_map == {+ ('default', 'validation'): {'type': 'string', 'format': 'binary'},+ ('base64', 'validation'): {'type': 'string', 'format': 'base64url'},+ ('default_again', 'validation'): {'type': 'array', 'items': {'type': 'string', 'format': 'binary'}},+ }+++def test_json_schema_parent_config_used_for_nested_types_without_config() -> None:+ """Stdlib dataclasses and typed dicts without config use the parent config, as during validation/serialization."""++ @dataclass+ class StdDC:+ b: bytes++ class TD(TypedDict):+ b: bytes++ for tp in (StdDC, TD):+ ta = TypeAdapter(list[tp], config={'ser_json_bytes': 'base64'})+ assert ta.json_schema()['$defs'][tp.__name__]['properties']['b']['format'] == 'base64url'++ class Model(BaseModel, ser_json_bytes='base64'):+ x: tp++ assert Model.model_json_schema()['$defs'][tp.__name__]['properties']['b']['format'] == 'base64url'
Merged fix · PR #13676+10 −1
pydantic/type_adapter.pyindex 447ac34bc..1c6824acb 100644@@ -736,7 +736,10 @@ class TypeAdapter(Generic[T]): if isinstance(self.core_schema, _mock_val_ser.MockCoreSchema): self.core_schema.rebuild() assert not isinstance(self.core_schema, _mock_val_ser.MockCoreSchema), 'this is a bug! please report it'- return schema_generator_instance.generate(self.core_schema, mode=mode)+ # The configuration provided to the type adapter (if any) is not part of the core schema,+ # so we need to explicitly make it available to the JSON Schema generator:+ with schema_generator_instance._config_wrapper_stack.push(self._config):+ return schema_generator_instance.generate(self.core_schema, mode=mode) @staticmethod def json_schemas(tests/test_type_adapter.pyindex ad7464513..1038a8291 100644@@ -555,6 +555,12 @@ def test_ta_config_with_annotated_type() -> None: ] +def test_ta_config_used_for_json_schema() -> None:+ """https://github.com/pydantic/pydantic/issues/13675"""+ ta = TypeAdapter(list[bytes], config=ConfigDict(ser_json_bytes='base64'))+ assert ta.json_schema() == {'type': 'array', 'items': {'type': 'string', 'format': 'base64url'}}++ def defer_build_test_models(config: ConfigDict) -> list[Any]: class Model(BaseModel): model_config = config