Backtestspydanticrun-20261009-110034#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 apply the same core fix in `TypeAdapter.json_schema()`: they push `self._config` onto the generator's config stack. That resolves the issue's literal example (`TypeAdapter(bytes, config=...)`).
Patch A stops there, which leaves real gaps:
- **Nested types.** In `json_schema.py`, `typed_dict_schema` and `dataclass_schema` push `{}` (via `_get_typed_dict_config` / `getattr(cls, '__pydantic_config__', {})`) when the class has no config of its own. Pushing an empty config overrides the parent config. So `TypeAdapter(list[SomeTypedDict], config={'ser_json_bytes': 'base64'})` would still emit `format: binary` inside the TypedDict. That disagrees with the core schema, where config-less TypedDicts and plain dataclasses inherit the parent config. The same mismatch already exists for a BaseModel containing such types.
- **`TypeAdapter.json_schemas()`.** Patch A leaves this static method untouched, so per-adapter configs are still ignored there.
- **Test coverage.** Its single test uses `list[bytes]`, which sidesteps the nested-class problem.
Patch B addresses the root cause more completely:
- It returns `None` instead of `{}` for missing TypedDict/dataclass configs. The stack's `push(None)` is a no-op, so the parent config now carries through, matching core-schema behavior.
- It still passes `config or {}` to `_update_class_schema`, preserving the existing title and extra handling.
- It threads per-input configs into `generate_definitions` so `json_schemas()` respects each adapter's config.
Patch B's tests are substantially stronger:
- multiple config keys (`ser_json_bytes`, `ser_json_timedelta`, `json_schema_mode_override`)
- default behavior when no config is given
- nested TypedDict and dataclass under both a TypeAdapter and a BaseModel
- a TypedDict with its own config keeping that config
- the multi-adapter `json_schemas()` case
These would fail before the change.
The `_inputs_configs` attribute is a slightly awkward side channel, but it is documented, length-checked, and low-risk.
Overall, B is more correct and better tested.
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
7m 21s
Wall-clock time in the container
Full test suite
No new failures
1,545 passed · 16 skipped · 1,561 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
106vs 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+95 −11
pydantic/json_schema.pyindex e7abcad0..00bd1e82 100644@@ -285,6 +285,9 @@ class GenerateJsonSchema: self.definitions: dict[DefsRef, JsonSchemaValue] = {} self._config_wrapper_stack = _config.ConfigWrapperStack(_config.ConfigWrapper({}))+ # Optional per-input configs used by `generate_definitions()` (one entry per input, `None` meaning no config).+ # This is set by `TypeAdapter.json_schemas()` so that each adapter's config is taken into account.+ self._inputs_configs: Sequence[ConfigDict | None] | None = None self._mode: JsonSchemaMode = 'validation' @@ -379,16 +382,22 @@ class GenerateJsonSchema: code='json-schema-already-used', ) - for _, mode, schema in inputs:+ inputs_configs = self._inputs_configs or [None] * len(inputs)+ if len(inputs_configs) != len(inputs):+ raise ValueError('The number of input configs must match the number of inputs.')++ for (_, mode, schema), config in zip(inputs, inputs_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, inputs_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,6 +1541,7 @@ class GenerateJsonSchema: if self.mode == 'serialization': named_required_fields.extend(self._name_required_computed_fields(schema.get('computed_fields', []))) cls = schema.get('cls')+ # if the typed dictionary class doesn't have config, we use the parent's config (see `_generate_schema.py`): config = _get_typed_dict_config(cls) with self._config_wrapper_stack.push(config): json_schema = self._named_required_fields_schema(named_required_fields)@@ -1555,7 +1565,7 @@ class GenerateJsonSchema: if cls is not None: # `_update_class_schema()` will not override # `additionalProperties` if already present:- self._update_class_schema(json_schema, cls, config)+ self._update_class_schema(json_schema, cls, config or {}) elif 'additionalProperties' not in json_schema: extra = schema.get('config', {}).get('extra_fields_behavior') if extra == 'forbid':@@ -1886,12 +1896,13 @@ class GenerateJsonSchema: """ cls = schema['cls']- config = cast('ConfigDict', getattr(cls, '__pydantic_config__', {}))+ # if (plain) dataclass doesn't have config, we use the parent's config (see `_generate_schema.py`):+ config = cast('ConfigDict | None', getattr(cls, '__pydantic_config__', None)) with self._config_wrapper_stack.push(config): json_schema = self.generate_inner(schema['schema']).copy() - self._update_class_schema(json_schema, cls, config)+ self._update_class_schema(json_schema, cls, config or {}) return json_schema @@ -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..0869572f 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[ConfigDict | 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,9 @@ class TypeAdapter(Generic[T]): 'this is a bug! please report it' ) inputs_.append((key, mode, adapter.core_schema))+ inputs_configs.append(adapter._config) + schema_generator_instance._inputs_configs = inputs_configs json_schemas_map, definitions = schema_generator_instance.generate_definitions(inputs_) json_schema: dict[str, Any] = {}tests/test_json_schema.pyindex f7533631..f4c085e8 100644@@ -57,7 +57,7 @@ from pydantic import ( field_validator, ) from pydantic.color import Color-from pydantic.config import ConfigDict+from pydantic.config import ConfigDict, with_config from pydantic.dataclasses import dataclass from pydantic.errors import PydanticInvalidForJsonSchema from pydantic.json_schema import (@@ -2063,6 +2063,75 @@ def test_model_subclass_metadata(): assert B.model_json_schema() == {'title': 'B', 'type': 'object', 'properties': {}} +def test_type_adapter_config_used_for_json_schema() -> None:+ ta = TypeAdapter(bytes, config={'ser_json_bytes': 'base64'})+ assert ta.json_schema() == {'type': 'string', 'format': 'base64url'}++ ta = TypeAdapter(timedelta, config={'ser_json_timedelta': 'float'})+ assert ta.json_schema() == {'type': 'number'}++ int_to_str = Annotated[int, PlainSerializer(str, return_type=str)]+ ta = TypeAdapter(int_to_str, config={'json_schema_mode_override': 'serialization'})+ assert ta.json_schema(mode='validation') == {'type': 'string'}++ # Without config, the defaults are used:+ assert TypeAdapter(bytes).json_schema() == {'type': 'string', 'format': 'binary'}+ assert TypeAdapter(int_to_str).json_schema(mode='validation') == {'type': 'integer'}+++def test_type_adapter_config_used_for_nested_json_schema() -> None:+ class TD(TypedDict):+ b: bytes++ @dataclasses.dataclass+ class DC:+ b: bytes++ ta = TypeAdapter(list[TD], config={'ser_json_bytes': 'base64'})+ assert ta.json_schema()['$defs']['TD']['properties']['b'] == {+ 'type': 'string',+ 'format': 'base64url',+ 'title': 'B',+ }++ ta = TypeAdapter(list[DC], config={'ser_json_bytes': 'base64'})+ assert ta.json_schema()['$defs']['DC']['properties']['b'] == {+ 'type': 'string',+ 'format': 'base64url',+ 'title': 'B',+ }++ class Model(BaseModel, ser_json_bytes='base64'):+ td: TD+ dc: DC++ defs = Model.model_json_schema()['$defs']+ assert defs['TD']['properties']['b']['format'] == 'base64url'+ assert defs['DC']['properties']['b']['format'] == 'base64url'++ # A TypedDict with its own config does not use the parent config:+ @with_config({'ser_json_bytes': 'utf8'})+ class TDWithConfig(TypedDict):+ b: bytes++ ta = TypeAdapter(list[TDWithConfig], config={'ser_json_bytes': 'base64'})+ assert ta.json_schema()['$defs']['TDWithConfig']['properties']['b']['format'] == 'binary'+++def test_type_adapter_config_used_for_json_schemas() -> None:+ base64_ta = TypeAdapter(bytes, config={'ser_json_bytes': 'base64'})+ default_ta = TypeAdapter(bytes)++ json_schemas_map, definitions = TypeAdapter.json_schemas(+ [('base64', 'validation', base64_ta), ('default', 'validation', default_ta)]+ )+ assert json_schemas_map == {+ ('base64', 'validation'): {'type': 'string', 'format': 'base64url'},+ ('default', 'validation'): {'type': 'string', 'format': 'binary'},+ }+ assert definitions == {}++ @pytest.mark.parametrize( 'docstring,description', [
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