Backtestspydanticrun-20261027-165153#13675

Issue #13675 Merged fix PR #13676 Run 27 Oct 2026 · run-20261027-165153 pydantic/pydantic

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 for the single-adapter case: pushing the TypeAdapter's config onto the JSON schema generator's config wrapper stack before `generate()`. That resolves the exact snippet in the issue, and the independent tests confirm both pass the direct bytes/list[bytes] scenarios. Patch B goes further on the same root cause in ways that matter: (1) `TypeAdapter.json_schemas()` is left untouched by Patch A, so multiple adapters passed together still ignore their configs, which is the very bug reported, just via the sibling API; B threads per-input configs through `generate_definitions()` with a length check. (2) B makes config-less TypedDicts and stdlib dataclasses nested inside the adapter inherit the adapter config during JSON schema generation, mirroring core schema generation. This is justified rather than speculative: B's test shows `dump_json` already serializes such nested bytes as base64 under the adapter config, so on Patch A the JSON schema would contradict actual serialization output. The independent tests show exactly this split: A fails the nested TypedDict, nested dataclass, and `json_schemas` cases, B passes all six. B's change of `_get_typed_dict_config` to return `None` is safe because `ConfigWrapperStack.push(None)` is a no-op, and the `config or {}` fallback preserves `_update_class_schema`'s contract. B's tests are also more thorough (several config keys, both modes, nested classes, `json_schemas`), all of which fail before and pass after. A's single test is adequate but narrow. B's extra surface (`_definitions_input_configs` attribute set externally on the generator) is slightly awkward design, but it is small, commented, and validated, and does not outweigh A leaving real instances of the reported behaviour broken.

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

6m 43s

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

92vs 11 merged

Changed lines, ours vs merged

from 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+82 −10
pydantic/json_schema.pyindex e7abcad0..b5fd6cdf 100644@@ -285,6 +285,9 @@ class GenerateJsonSchema:          self.definitions: dict[DefsRef, JsonSchemaValue] = {}         self._config_wrapper_stack = _config.ConfigWrapperStack(_config.ConfigWrapper({}))+        # Optional configs to apply for each input of `generate_definitions()`, aligned by index with the inputs+        # (used by `TypeAdapter.json_schemas()`, as each type adapter can have its own config):+        self._definitions_input_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:+        input_configs = self._definitions_input_configs+        if input_configs is not None and len(input_configs) != len(inputs):+            raise ValueError('The number of input configs must match the number of inputs.')++        for i, (_, mode, schema) in enumerate(inputs):             self._mode = mode-            self.generate_inner(schema)+            with self._config_wrapper_stack.push(input_configs[i] if input_configs is not None else None):+                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 i, (key, mode, schema) in enumerate(inputs):             self._mode = mode-            json_schema = self.generate_inner(schema)+            with self._config_wrapper_stack.push(input_configs[i] if input_configs is not None else None):+                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 dict doesn't have a config, the parent's config is used (as done during core schema generation):         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 a (plain) dataclass doesn't have a config, the parent's config is used (as in core schema generation):+        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..c8d94c04 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_ = []+        input_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))+            input_configs.append(adapter._config) +        schema_generator_instance._definitions_input_configs = input_configs         json_schemas_map, definitions = schema_generator_instance.generate_definitions(inputs_)          json_schema: dict[str, Any] = {}tests/test_type_adapter.pyindex ad746451..5dc0348f 100644@@ -1,6 +1,7 @@ import json from dataclasses import dataclass from datetime import date, datetime+from decimal import Decimal from typing import Annotated, Any, ForwardRef, Generic, NamedTuple, TypeAlias, TypeVar, Union  import pytest@@ -757,3 +758,59 @@ def test_validate_json_invalid_json():             'ctx': {'error': 'trailing comma at line 3 column 3'},         }     ]+++def test_json_schema_uses_type_adapter_config() -> None:+    ta = TypeAdapter(bytes, config={'ser_json_bytes': 'base64'})+    assert ta.json_schema() == {'type': 'string', 'format': 'base64url'}++    ta = TypeAdapter(datetime, config={'ser_json_temporal': 'seconds'})+    assert ta.json_schema(mode='serialization') == {'type': 'number'}++    ta = TypeAdapter(list[date], config={'json_schema_mode_override': 'serialization', 'ser_json_temporal': 'seconds'})+    assert ta.json_schema(mode='validation') == {'type': 'array', 'items': {'type': 'number'}}++    ta = TypeAdapter(Decimal, config={'json_schema_mode_override': 'serialization'})+    assert ta.json_schema(mode='validation') == TypeAdapter(Decimal).json_schema(mode='serialization')+    assert ta.json_schema(mode='validation') != TypeAdapter(Decimal).json_schema(mode='validation')+++def test_json_schema_type_adapter_config_used_by_nested_classes_without_config() -> None:+    class TD(TypedDict):+        b: bytes++    @dataclass+    class DC:+        b: bytes++    td_ta = TypeAdapter(list[TD], config={'ser_json_bytes': 'base64'})+    assert td_ta.dump_json([{'b': b'hi'}]) == b'[{"b":"aGk="}]'+    assert td_ta.json_schema()['$defs']['TD']['properties']['b'] == {+        'type': 'string',+        'format': 'base64url',+        'title': 'B',+    }++    dc_ta = TypeAdapter(list[DC], config={'ser_json_bytes': 'base64'})+    assert dc_ta.dump_json([DC(b=b'hi')]) == b'[{"b":"aGk="}]'+    assert dc_ta.json_schema()['$defs']['DC']['properties']['b'] == {+        'type': 'string',+        'format': 'base64url',+        'title': 'B',+    }+++def test_json_schemas_uses_type_adapter_configs() -> None:+    base64_ta = TypeAdapter(bytes, config={'ser_json_bytes': 'base64'})+    default_ta = TypeAdapter(bytes)++    schemas, _ = TypeAdapter.json_schemas(+        [+            ('base64', 'validation', base64_ta),+            ('default', 'validation', default_ta),+        ]+    )+    assert schemas == {+        ('base64', 'validation'): {'type': 'string', 'format': 'base64url'},+        ('default', 'validation'): {'type': 'string', 'format': 'binary'},+    } 
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