Backtestspydanticrun-20261003-150343#13675

Issue #13675 Merged fix PR #13676 Run 3 Oct 2026 · run-20261003-150343 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 fix the reported root cause the same way. Each wraps `GenerateJsonSchema.generate()` in `TypeAdapter.json_schema()` with `_config_wrapper_stack.push(self._config)`. Pushing `None` is a no-op, so adapters without config are unaffected. Either patch therefore makes the issue's example produce `base64url`.

Patch B goes further, in ways that are closely tied to the issue rather than unrelated churn:

1. It applies the same fix to the static `TypeAdapter.json_schemas()` path, which has the identical bug. It stores per-input configs and pushes them around both `generate_inner` passes in `generate_definitions()`. Without this, A still ignores adapter config when multiple adapters' schemas are generated together.
2. It stops TypedDicts and plain dataclasses without their own config from resetting to an empty config during JSON schema generation. Instead they inherit the parent config, which matches core-schema generation. B's test asserts that `dump_json` really emits base64 for these nested types. Under A, `TypeAdapter(list[TD], config={'ser_json_bytes': 'base64'}).json_schema()` would still report `binary` for the nested field, so the schema would disagree with actual serialization. That is the same class of inconsistency the issue complains about.

The edits are small and careful: `config or {}` keeps `_update_class_schema` safe, and `_get_typed_dict_config` now returns `None`.

Tests: A adds one test, `list[bytes]`, which fails before and passes after. B adds broader tests that also fail before the change: the bytes case, `ser_json_temporal` in serialization mode, base64 defaults, no config leakage to later adapters, `json_schemas()` with mixed configs, and nested TypedDict/dataclass inheritance.

B carries slightly more change surface, but the added behavior aligns JSON schema with real validation/serialization semantics and is well tested. Overall B is the more complete and correct 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

10m 37s

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

74vs 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+66 −8
pydantic/json_schema.pyindex e7abcad0..149b0e0a 100644@@ -285,6 +285,9 @@ class GenerateJsonSchema:          self.definitions: dict[DefsRef, JsonSchemaValue] = {}         self._config_wrapper_stack = _config.ConfigWrapperStack(_config.ConfigWrapper({}))+        # Configs to apply when generating the JSON Schema of specific inputs of `generate_definitions()`+        # (e.g. the `config` of each `TypeAdapter` in `TypeAdapter.json_schemas()`):+        self._inputs_configs: dict[tuple[Any, JsonSchemaMode], ConfigDict] = {}          self._mode: JsonSchemaMode = 'validation' @@ -379,16 +382,18 @@ class GenerateJsonSchema:                 code='json-schema-already-used',             ) -        for _, mode, schema in inputs:+        for key, mode, schema in inputs:             self._mode = mode-            self.generate_inner(schema)+            with self._config_wrapper_stack.push(self._inputs_configs.get((key, mode))):+                self.generate_inner(schema)          definitions_remapping = self._build_definitions_remapping()          json_schemas_map: dict[tuple[JsonSchemaKeyT, JsonSchemaMode], DefsRef] = {}         for key, mode, schema in inputs:             self._mode = mode-            json_schema = self.generate_inner(schema)+            with self._config_wrapper_stack.push(self._inputs_configs.get((key, mode))):+                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 +1537,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, the parent's config is used (as 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 +1561,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':@@ -1888,7 +1894,8 @@ class GenerateJsonSchema:         cls = schema['cls']         config = cast('ConfigDict', getattr(cls, '__pydantic_config__', {})) -        with self._config_wrapper_stack.push(config):+        # If a (plain) dataclass doesn't have config, the parent's config is used (as during core schema generation):+        with self._config_wrapper_stack.push(getattr(cls, '__pydantic_config__', None)):             json_schema = self.generate_inner(schema['schema']).copy()          self._update_class_schema(json_schema, cls, config)@@ -2997,13 +3004,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..88e601b4 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(@@ -793,6 +794,8 @@ class TypeAdapter(Generic[T]):                     'this is a bug! please report it'                 )             inputs_.append((key, mode, adapter.core_schema))+            if adapter._config is not None:+                schema_generator_instance._inputs_configs[(key, mode)] = adapter._config          json_schemas_map, definitions = schema_generator_instance.generate_definitions(inputs_) tests/test_type_adapter.pyindex ad746451..32efc37a 100644@@ -757,3 +757,51 @@ def test_validate_json_invalid_json():             'ctx': {'error': 'trailing comma at line 3 column 3'},         }     ]+++def test_json_schema_uses_config() -> None:+    """https://github.com/pydantic/pydantic/issues/13675"""+    ta = TypeAdapter(bytes, config={'ser_json_bytes': 'base64'})+    assert ta.json_schema() == {'type': 'string', 'format': 'base64url'}++    ta_temporal = TypeAdapter(datetime, config={'ser_json_temporal': 'seconds'})+    assert ta_temporal.json_schema(mode='serialization') == {'type': 'number'}++    ta_default = TypeAdapter(Annotated[bytes, Field(default=b'\xff')], config={'ser_json_bytes': 'base64'})+    assert ta_default.json_schema() == {'type': 'string', 'format': 'base64url', 'default': '_w=='}++    # The config is not leaked into subsequent generation:+    assert TypeAdapter(bytes).json_schema() == {'type': 'string', 'format': 'binary'}+++def test_json_schemas_uses_config() -> None:+    ta_base64 = TypeAdapter(bytes, config={'ser_json_bytes': 'base64'})+    ta_utf8 = TypeAdapter(bytes)++    json_schemas_map, _ = TypeAdapter.json_schemas(+        [('base64', 'validation', ta_base64), ('utf8', 'validation', ta_utf8)]+    )+    assert json_schemas_map == {+        ('base64', 'validation'): {'type': 'string', 'format': 'base64url'},+        ('utf8', 'validation'): {'type': 'string', 'format': 'binary'},+    }+++def test_json_schema_uses_config_nested_typed_dict_and_dataclass() -> None:+    """Typed dicts and plain dataclasses without config use the parent config, as during validation/serialization."""++    class TD(TypedDict):+        b: bytes++    @dataclass+    class DC:+        b: bytes++    for tp in (TD, DC):+        ta = TypeAdapter(list[tp], config={'ser_json_bytes': 'base64'})+        assert ta.dump_json([tp(b=b'\xff')]) == b'[{"b":"_w=="}]'+        assert ta.json_schema()['$defs'][tp.__name__]['properties']['b'] == {+            'type': 'string',+            'format': 'base64url',+            'title': 'B',+        } 
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