Backtestspydanticrun-20261002-175417#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 `TypeAdapter.json_schema()` the same way: they push `self._config` onto the generator's `_config_wrapper_stack` around `generate()`. That resolves the reported example, since `ser_json_bytes='base64'` now yields `format: base64url`. The issue is titled generally: TypeAdapter config is not used for JSON Schema generation. `TypeAdapter.json_schemas()` is the other public entry point that generates JSON schema from adapters, and it has the same defect. Patch A leaves it broken: adapters passed to `json_schemas` still ignore their config. Patch B fixes that path too: - It threads per-input configs through `generate_definitions` and pushes each config for both passes (definition collection and final generation). This keeps per-adapter configs isolated, which its test with a base64 adapter next to a default adapter confirms. - The new `configs` parameter is keyword-only, defaults to None, and checks that its length matches `inputs`. - To stay compatible with subclasses that override `generate_definitions()`, it only passes the new keyword when some config is non-None. This extends the public signature of `generate_definitions`, which adds some surface area. The change is backward-compatible and justified by the root cause, so the risk is low. Tests: Patch A adds one test, for `list[bytes]` via `json_schema()`. Patch B adds tests for: - the exact issue example - a timedelta serialization config - the `list[bytes]` case - the multi-adapter `json_schemas` case - the length-mismatch error All of B's behavioral tests would fail before the fix. Patch A's test also contains a placeholder docstring (`"""<link>"""`). Overall, Patch B fixes the root cause more completely and tests it more thoroughly.
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 6s
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
66vs 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+59 −7
pydantic/json_schema.pyindex e7abcad0..2803ae98 100644@@ -348,7 +348,10 @@ class GenerateJsonSchema: return mapping def generate_definitions(- self, inputs: Sequence[tuple[JsonSchemaKeyT, JsonSchemaMode, core_schema.CoreSchema]]+ self,+ inputs: Sequence[tuple[JsonSchemaKeyT, JsonSchemaMode, core_schema.CoreSchema]],+ *,+ configs: Sequence[ConfigDict | None] | None = None, ) -> tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], dict[DefsRef, JsonSchemaValue]]: """Generates JSON schema definitions from a list of core schemas, pairing the generated definitions with a mapping that links the input keys to the definition references.@@ -359,6 +362,9 @@ class GenerateJsonSchema: - The first element is a JSON schema key type. - The second element is the JSON mode: either 'validation' or 'serialization'. - The third element is a core schema.+ configs: An optional sequence of configurations (one per input, in the same order) to use+ when generating the JSON schema of the corresponding input (e.g. the config of a+ [`TypeAdapter`][pydantic.type_adapter.TypeAdapter]). Returns: A tuple where:@@ -379,16 +385,23 @@ class GenerateJsonSchema: code='json-schema-already-used', ) - for _, mode, schema in inputs:+ if configs is None:+ configs = [None] * len(inputs)+ elif len(configs) != len(inputs):+ raise ValueError('`configs` must have the same length as `inputs`.')++ for (_, mode, schema), config in zip(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, 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}pydantic/type_adapter.pyindex 447ac34b..a162266a 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_ = []+ 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,8 +795,13 @@ class TypeAdapter(Generic[T]): 'this is a bug! please report it' ) inputs_.append((key, mode, adapter.core_schema))+ configs.append(adapter._config) - json_schemas_map, definitions = schema_generator_instance.generate_definitions(inputs_)+ # Only pass `configs` when needed, to stay compatible with custom `generate_definitions()` overrides:+ if any(config is not None for config in configs):+ json_schemas_map, definitions = schema_generator_instance.generate_definitions(inputs_, configs=configs)+ else:+ json_schemas_map, definitions = schema_generator_instance.generate_definitions(inputs_) json_schema: dict[str, Any] = {} if definitions:tests/test_json_schema.pyindex f7533631..bdcff56f 100644@@ -5592,6 +5592,38 @@ def test_type_adapter_json_schemas_without_definitions(): assert 'definitions' not in json_schema +def test_type_adapter_config_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(mode='serialization') == {'type': 'number'}++ ta = TypeAdapter(list[bytes], config={'ser_json_bytes': 'base64'})+ assert ta.json_schema() == {'type': 'array', 'items': {'type': 'string', 'format': 'base64url'}}+++def test_type_adapter_config_json_schemas() -> None:+ json_schemas_map, _ = TypeAdapter.json_schemas(+ [+ ('base64', 'validation', TypeAdapter(bytes, config={'ser_json_bytes': 'base64'})),+ ('default', 'validation', TypeAdapter(bytes)),+ ]+ )+ assert json_schemas_map == {+ ('base64', 'validation'): {'type': 'string', 'format': 'base64url'},+ ('default', 'validation'): {'type': 'string', 'format': 'binary'},+ }+++def test_generate_definitions_configs_length_mismatch() -> None:+ with pytest.raises(ValueError, match='`configs` must have the same length as `inputs`'):+ GenerateJsonSchema().generate_definitions(+ [('a', 'validation', core_schema.bytes_schema())],+ configs=[None, None],+ )++ def test_custom_chain_schema(): class MySequence: @classmethod
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