Backtestspydanticrun-20261022-024030#13845

Issue #13845 Merged fix PR #13899 Run 22 Oct 2026 · run-20261022-024030 pydantic/pydantic

JSON schema ignores propagated config for stdlib dataclasses (extra='forbid' validates but no additionalProperties: false)

Tie

The judges split evenly between our patch and the merged fix.

In this judgment, Patch B = our agent, Patch A = the merged fix.

Both patches make the same core change: when a stdlib dataclass has no config of its own, `dataclass_schema` reads the propagated `extra_fields_behavior` from the dataclass's core-schema `config` (the same value validation uses) and feeds it to `_update_class_schema`. For every scenario in the issue (nested dataclass under a forbid model, `TypeAdapter(list[DC], config=...)`, allow/forbid/ignore) they behave identically, and the independent tests confirm both go from FAIL-ASSERT to PASS across all nine failing cases, including recursive, deeply nested, and shared-definition scenarios. Patch A's variant (merge `extra` into an existing config only if absent) is functionally equivalent to Patch B's `config is None` branch, since a dataclass with its own config never receives a propagated `extra_fields_behavior`. Neither is a symptom mask; both fix the root cause at the right place. The difference is in tests and clarity. Patch B adds three tests covering the model case parametrized over forbid/allow/ignore, the TypeAdapter and `TypeAdapter.json_schemas` paths, and a dedicated test for a dataclass reused in two fields plus a self-recursive dataclass, which directly exercises the definition-reuse concern its code comment explains (the dataclass schema may be a definition generated outside the current config-stack context). Patch A's parametrized test is also solid (covers DC with non-extra config, DC with its own extra, and pydantic dataclass) and it usefully repairs an existing test that was asserting `extra='ignore'` under a name claiming forbid. But A's test lacks the reuse/recursion/json_schemas coverage that matters most for the 'definition generated elsewhere' path. Patch B's explanatory comment is also clearer about why the core config is consulted rather than the current config wrapper. Scope and craft are otherwise comparable (A's long walrus line is slightly denser). On balance B edges out A on test coverage of the issue's implied scenarios.

Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.

Solve

7m 13s

Wall-clock time in the container

Full test suite

No new failures

1,367 passed · 16 skipped · 1,383 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

104vs 64 merged

Changed lines, ours vs merged

Initial 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

Our patch+103 −1
pydantic/json_schema.pyindex 9a6e0e78..24b60677 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 propagated `extra` behavior is stored in the core config (as used during validation). We don't+            # rely on the current config, as the dataclass schema may be a definition generated in another context:+            extra = schema.get('config', {}).get('extra_fields_behavior')+            class_config: ConfigDict = {'extra': extra} if extra is not None else {}+        else:+            class_config = config++        self._update_class_schema(json_schema, cls, class_config)          return json_schema tests/test_json_schema.pyindex 84460192..fddbe555 100644@@ -2196,6 +2196,100 @@ 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: str, additional_properties: bool | None) -> None:+    """The propagated `extra` config is reflected in `additionalProperties` for stdlib dataclasses and typed dicts."""++    @dataclasses.dataclass+    class DCWithoutConfig:+        qty: int++    @dataclasses.dataclass+    @with_config(extra='ignore')+    class DCWithConfig:+        qty: int++    class TDWithoutConfig(TypedDict):+        qty: int++    @with_config(extra='ignore')+    class TDWithConfig(TypedDict):+        qty: int++    class Parent(BaseModel):+        model_config = ConfigDict(extra=extra)++        dc_1: DCWithoutConfig+        dc_2: DCWithConfig+        td_1: TDWithoutConfig+        td_2: TDWithConfig++    schema = Parent.model_json_schema()+    defs = schema['$defs']+    assert schema.get('additionalProperties') == additional_properties+    for name in ('DCWithoutConfig', 'TDWithoutConfig'):+        assert defs[name].get('additionalProperties') == additional_properties+    for name in ('DCWithConfig', 'TDWithConfig'):+        assert 'additionalProperties' not in defs[name]++    # Consistent with validation:+    data = {name: {'qty': 1, 'x': 1} for name in ('dc_1', 'dc_2', 'td_1', 'td_2')}+    if extra == 'forbid':+        with pytest.raises(ValidationError) as exc_info:+            Parent.model_validate(data)+        assert {err['loc'][0] for err in exc_info.value.errors()} == {'dc_1', 'td_1'}+    else:+        Parent.model_validate(data)+++def test_stdlib_dataclass_extra_config_propagation_type_adapter() -> None:+    @dataclasses.dataclass+    class Line:+        qty: int++    class LineTD(TypedDict):+        qty: int++    adapter = TypeAdapter(list[Line], config=ConfigDict(extra='forbid'))+    with pytest.raises(ValidationError):+        adapter.validate_python([{'qty': 1, 'typo': 2}])+    assert adapter.json_schema()['$defs']['Line']['additionalProperties'] is False++    td_adapter = TypeAdapter(list[LineTD], config=ConfigDict(extra='forbid'))+    with pytest.raises(ValidationError):+        td_adapter.validate_python([{'qty': 1, 'typo': 2}])+    assert td_adapter.json_schema()['$defs']['LineTD']['additionalProperties'] is False++    _, top_level_schema = TypeAdapter.json_schemas([((), 'validation', adapter)])+    assert top_level_schema['$defs']['Line']['additionalProperties'] is False+++def test_stdlib_dataclass_extra_config_propagation_reused_and_recursive() -> None:+    @dataclasses.dataclass+    class Line:+        qty: int++    @dataclasses.dataclass+    class Node:+        children: 'list[Node]'++    class Order(BaseModel):+        model_config = ConfigDict(extra='forbid')++        line_1: Line+        line_2: Line+        node: Node++    with pytest.raises(ValidationError):+        Order.model_validate({'line_1': {'qty': 1}, 'line_2': {'qty': 1, 'typo': 2}, 'node': {'children': []}})+    with pytest.raises(ValidationError):+        Order.model_validate({'line_1': {'qty': 1}, 'line_2': {'qty': 1}, 'node': {'children': [], 'typo': 2}})++    defs = Order.model_json_schema()['$defs']+    assert defs['Line']['additionalProperties'] is False+    assert defs['Node']['additionalProperties'] is False++ def test_str_length_config() -> None:     class Model(BaseModel):         model_config = ConfigDict(str_min_length=3, str_max_length=5) 
Merged fix · PR #13899+61 −3
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,     }