Backtestspydanticrun-20261013-104308#13845
JSON schema ignores propagated config for stdlib dataclasses (extra='forbid' validates but no additionalProperties: false)
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Both patches fix the root cause the same way. In `dataclass_schema`, when the class's own config doesn't settle `extra`, they read `extra_fields_behavior` from the core schema config. That is the config validation actually uses after the earlier core-schema fix, so the JSON schema now agrees with the validator for both the nested-model and the `TypeAdapter(list[DC], config=...)` scenarios. Neither patch leaks the parent's title or `json_schema_extra` into the nested schema. Patch A matches the issue's stated expectation exactly: it applies the propagated `extra` only when the dataclass has no `__pydantic_config__`. It builds a fresh config containing only `extra`, with a comment explaining why the other parent keys are skipped. Patch B applies the fallback whenever `'extra'` is missing from the class config. In practice this is equivalent, because a class with its own config produces a core config without the parent's extra. But the condition is less direct, and readers must reason about that interaction to see it is safe. On tests, both add parametrized forbid/allow/ignore cases that fail before the fix and pass after it, and both check consistency with validation. Patch A additionally asserts that the parent's title and `json_schema_extra` do not leak into the nested schema, and it covers a TypedDict alongside the dataclass. Patch B covers more dataclass variants, including one with its own `extra` and a pydantic dataclass. B also rewrites the unrelated `test_dataclass_with_extra_forbid`, which is a reasonable correction of a mislabeled test but is churn outside the issue's ask. Overall the correctness is effectively equal. Patch A is slightly tighter in scope and clearer in intent, and its tests directly guard against the over-propagation risk.
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
5m 51s
Wall-clock time in the container
Full test suite
No new failures
1,365 passed · 16 skipped · 1,381 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
59vs 64 merged
Changed lines, ours vs merged
The issue
View on GitHubInitial Checks
- I confirm that I'm using Pydantic V2
Description
The docs (Configuration propagation) say that configuration is propagated to stdlib dataclasses that don't set their own. Validation does this. JSON schema generation doesn't.
#10928 fixed this in the core-schema generator (_internal/_generate_schema.py) by changing the default so the parent's config is used:
- config = getattr(dataclass, '__pydantic_config__', ConfigDict())
+ config = getattr(dataclass, '__pydantic_config__', None)
The JSON-schema generator still has the same pattern. GenerateJsonSchema.dataclass_schema in json_schema.py, unchanged on main:
config = cast('ConfigDict', getattr(cls, '__pydantic_config__', {}))
with self._config_wrapper_stack.push(config):
json_schema = self.generate_inner(schema['schema']).copy()
self._update_class_schema(json_schema, cls, config)
_update_class_schema then decides additionalProperties from that config, which for a stdlib dataclass without its own config is always {}, whatever the parent says.
So with a parent extra='forbid':
- the nested stdlib dataclass rejects unknown keys (
unexpected_keyword_argument); - its JSON schema doesn't say
additionalProperties: false. Under JSON Schema rules, that means extra keys are allowed.
The schema and the validator disagree. This matters most where the schema is handed to a client that fills it in, such as LLM tool calling. The model is told extra keys are fine, then its answer is refused.
The same applies to TypeAdapter(list[SomeStdlibDataclass], config=ConfigDict(extra='forbid')).
Expected: for a stdlib dataclass with no __pydantic_config__, dataclass_schema uses the propagated config (the one validation uses) when deciding additionalProperties, so extra='forbid' produces additionalProperties: false.
Example Code
import dataclasses
from pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationError
@dataclasses.dataclass
class Line:
qty: int
class Order(BaseModel):
model_config = ConfigDict(extra='forbid')
line: Line
try:
Order.model_validate({'line': {'qty': 1, 'typo': 2}})
except ValidationError as e:
print(e.errors()[0]['type'], e.errors()[0]['loc'])
#> unexpected_keyword_argument ('line', 'typo') <- propagated: forbid
schema = Order.model_json_schema()
print(schema.get('additionalProperties'))
#> False
print(schema['$defs']['Line'].get('additionalProperties'))
#> None <- expected False
adapter = TypeAdapter(list[Line], config=ConfigDict(extra='forbid'))
try:
adapter.validate_python([{'qty': 1, 'typo': 2}])
except ValidationError as e:
print(e.errors()[0]['type'])
#> unexpected_keyword_argument
print(adapter.json_schema()['$defs']['Line'].get('additionalProperties'))
#> None <- expected False
Python, Pydantic & OS Version
pydantic version: 2.13.5
pydantic-core version: 2.46.5
pydantic-core build: profile=release pgo=false
python version: 3.14.7 (main, Aug 10 2026, 00:00:00) [GCC 16.1.1 20260515 (Red Hat 16.1.1-2)]
platform: Linux-7.1.3-200.fc44.x86_64-x86_64-with-glibc2.43
The snippet above reproduces on 2.12.5 and 2.13.5. 2.10.x and 2.11.x don't install on Python 3.14 here, but dataclass_schema has the same getattr(cls, '__pydantic_config__', {}) default at v2.10.1 and v2.11.0, and on main. So the split (validator inherits, JSON schema doesn't) looks present in every release since #10928 shipped in 2.10.1.
Related: #10917 / #10928 (the same fix, applied to the core schema only), #10785 (default extra for dataclasses/TypedDicts in JSON schema), #8326 (config can't be passed to TypeAdapter for a stdlib dataclass directly).
The two patches
pydantic/json_schema.pyindex 9a6e0e78..e01e4132 100644@@ -1986,7 +1986,15 @@ class GenerateJsonSchema: with self._config_wrapper_stack.push(config): json_schema = self.generate_inner(schema['schema']).copy() - self._update_class_schema(json_schema, cls, config or {})+ if config is None:+ # The parent's `extra` setting applies during validation, so reflect it in `additionalProperties`+ # (the parent's title, `json_schema_extra`, etc. are class-specific and aren't applied):+ config = cast('ConfigDict', {})+ extra = schema.get('config', {}).get('extra_fields_behavior')+ if extra is not None:+ config['extra'] = extra++ self._update_class_schema(json_schema, cls, config) return json_schema tests/test_json_schema.pyindex 84460192..3d2c1adc 100644@@ -2196,6 +2196,55 @@ def test_stdlib_types_config_propagation() -> None: Parent(dc_1={'name': 'x'}, dc_2={'name': 'long name'}, td_1={'name': 'x'}, td_2={'name': 'long name'}) +@pytest.mark.parametrize('extra,additional_properties', [('forbid', False), ('allow', True), ('ignore', None)])+def test_stdlib_types_extra_config_propagation(extra, additional_properties) -> None:+ """The propagated `extra` config is reflected in `additionalProperties`, consistent with validation."""++ @dataclasses.dataclass+ class DCWithoutConfig:+ qty: int++ @dataclasses.dataclass+ @with_config(extra='ignore')+ class DCWithConfig:+ qty: int++ class TDWithoutConfig(TypedDict):+ qty: int++ class Parent(BaseModel):+ model_config = ConfigDict(extra=extra, title='ParentTitle', json_schema_extra={'examples': [{}]})++ dc_1: DCWithoutConfig+ dc_2: DCWithConfig+ td_1: TDWithoutConfig++ defs = Parent.model_json_schema()['$defs']+ for name in ('DCWithoutConfig', 'TDWithoutConfig'):+ assert defs[name].get('additionalProperties') == additional_properties+ # Only `extra` affects the nested class schema; the parent's title and `json_schema_extra` don't:+ assert defs[name]['title'] == name+ assert 'examples' not in defs[name]+ assert 'additionalProperties' not in defs['DCWithConfig']++ data = {'dc_1': {'qty': 1, 'typo': 2}, 'dc_2': {'qty': 1, 'typo': 2}, 'td_1': {'qty': 1}}+ if extra == 'forbid':+ with pytest.raises(ValidationError) as exc_info:+ Parent.model_validate(data)+ assert [(e['type'], e['loc']) for e in exc_info.value.errors()] == [+ ('unexpected_keyword_argument', ('dc_1', 'typo'))+ ]+ else:+ Parent.model_validate(data)++ adapter = TypeAdapter(list[DCWithoutConfig], config=ConfigDict(extra=extra))+ assert adapter.json_schema()['$defs']['DCWithoutConfig'].get('additionalProperties') == additional_properties+ if extra == 'forbid':+ with pytest.raises(ValidationError) as exc_info:+ adapter.validate_python([{'qty': 1, 'typo': 2}])+ assert exc_info.value.errors()[0]['type'] == 'unexpected_keyword_argument'++ def test_str_length_config() -> None: class Model(BaseModel): model_config = ConfigDict(str_min_length=3, str_max_length=5)
pydantic/json_schema.pyindex 9a6e0e788..1a9728c6b 100644@@ -1986,7 +1986,13 @@ class GenerateJsonSchema: with self._config_wrapper_stack.push(config): json_schema = self.generate_inner(schema['schema']).copy() - self._update_class_schema(json_schema, cls, config or {})+ # Only the parent's `extra` config value is relevant to the class schema. It is propagated+ # to the core config (and used for validation), so we reuse it:+ class_config = config or {}+ if 'extra' not in class_config and (extra := schema.get('config', {}).get('extra_fields_behavior')) is not None:+ class_config = cast('ConfigDict', {**class_config, 'extra': extra})++ self._update_class_schema(json_schema, cls, class_config) return json_schema tests/test_json_schema.pyindex 844601923..b5d212a47 100644@@ -59,7 +59,7 @@ from pydantic import ( with_config, ) from pydantic.color import Color-from pydantic.config import ConfigDict+from pydantic.config import ConfigDict, ExtraValues from pydantic.dataclasses import dataclass from pydantic.errors import PydanticInvalidForJsonSchema from pydantic.json_schema import (@@ -2196,6 +2196,57 @@ def test_stdlib_types_config_propagation() -> None: Parent(dc_1={'name': 'x'}, dc_2={'name': 'long name'}, td_1={'name': 'x'}, td_2={'name': 'long name'}) +@pytest.mark.parametrize(+ ['extra', 'additional_properties'],+ [('forbid', False), ('allow', True), ('ignore', None)],+)+def test_stdlib_dataclass_extra_config_propagation(extra: ExtraValues, additional_properties: bool | None) -> None:+ """https://github.com/pydantic/pydantic/issues/13845"""++ @dataclasses.dataclass+ class DCWithoutConfig:+ a: int++ @dataclasses.dataclass+ @with_config(str_to_lower=True)+ class DCWithConfig:+ a: int++ @dataclasses.dataclass+ @with_config(extra='allow')+ class DCWithExtraConfig:+ a: int++ @pydantic.dataclasses.dataclass+ class PydanticDC:+ a: int++ class Model(BaseModel):+ model_config = ConfigDict(extra=extra)++ dc_1: DCWithoutConfig+ dc_2: DCWithConfig+ dc_3: DCWithExtraConfig+ dc_4: PydanticDC++ defs = Model.model_json_schema()['$defs']+ assert defs['DCWithoutConfig'].get('additionalProperties') == additional_properties+ assert 'additionalProperties' not in defs['DCWithConfig']+ assert defs['DCWithExtraConfig']['additionalProperties'] is True+ assert 'additionalProperties' not in defs['PydanticDC']++ ta = TypeAdapter(list[DCWithoutConfig], config=ConfigDict(extra=extra))+ assert ta.json_schema()['$defs']['DCWithoutConfig'].get('additionalProperties') == additional_properties++ # Consistent with validation:+ if extra == 'forbid':+ with pytest.raises(ValidationError):+ Model(dc_1={'a': 1, 'b': 2}, dc_2={'a': 1}, dc_3={'a': 1}, dc_4={'a': 1})+ with pytest.raises(ValidationError):+ ta.validate_python([{'a': 1, 'b': 2}])+ Model(dc_1={'a': 1}, dc_2={'a': 1, 'b': 2}, dc_3={'a': 1, 'b': 2}, dc_4={'a': 1, 'b': 2})++ def test_str_length_config() -> None: class Model(BaseModel): model_config = ConfigDict(str_min_length=3, str_max_length=5)@@ -2911,7 +2962,7 @@ def test_dataclass_with_extra_ignore(): def test_dataclass_with_extra_forbid(): @pydantic.dataclasses.dataclass class Model:- __pydantic_config__ = ConfigDict(extra='ignore')+ __pydantic_config__ = ConfigDict(extra='forbid') a: str assert TypeAdapter(Model).json_schema() == {@@ -2919,6 +2970,7 @@ def test_dataclass_with_extra_forbid(): 'type': 'object', 'properties': {'a': {'title': 'A', 'type': 'string'}}, 'required': ['a'],+ 'additionalProperties': False, }