Backtestspydanticrun-20260929-204949#11922

Issue #11922 Merged fix PR # Run 29 Sep 2026 · run-20260929-204949 pydantic/pydantic

Some Field attributes lost in JSON schema when using RootModel

Better

Our patch was judged better than the merged fix.

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

The two patches share the identical core fix for title and examples. The meaningful differences are in the `deprecated` handling. Patch B uses `json_schema.setdefault('deprecated', True)`, which is consistent with how `examples`, `description`, and `title` are all handled in the surrounding code and avoids clobbering a `deprecated` value that may already be present from earlier model-level processing. Patch A instead does an unconditional `json_schema['deprecated'] = True`, which overrides rather than defers, an inconsistency with the rest of the method. Patch B also handles the edge case of an empty-string deprecation message (`root_field.deprecated == ''`, which is falsy) that Patch A's plain truthiness check would silently drop, and it updates the method docstring to list `examples` alongside `deprecated`, matching the documentation convention already there. Both patch's tests would fail before and pass after; Patch A adds a nice config-title-override test while Patch B adds a combined-all-attributes test, so test quality is roughly even. B edges ahead on correctness robustness (setdefault, empty-string handling) and craft (consistency with surrounding idioms, docstring update).

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

8m 25s28 turns

Wall-clock time in the container

Full test suite

No new failures

12,242 passed · 503 skipped · 12,745 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

48vs 53 merged

Changed lines, ours vs merged

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

When declaring a RootModel and adding a Field annotation to the root property that includes examples, those examples are not part of the generated JSON schema. This also applies to the deprecated attribute. The title attribute is also not applied or it is overwritten by the class name of the root model class.

Most other attributes, such as pattern or description are exposed as expected. Furthermore, placing examples in json_schema_extra also works as expected.

Example Code

from typing import Annotated
from pydantic import RootModel, Field

class Foo(RootModel):
    root: Annotated[str, Field(examples=["foo", "bar"], deprecated=True)]

print(Foo.model_json_schema())  # does not include examples or deprecated.

Python, Pydantic & OS Version

pydantic version: 2.11.4
        pydantic-core version: 2.33.2
          pydantic-core build: profile=release pgo=false
               python version: 3.13.3 (main, May 22 2025, 01:38:47) [Clang 20.1.4 ]
                     platform: macOS-15.5-arm64-arm-64bit-Mach-O
             related packages: pydantic-settings-2.9.1 mypy-1.15.0 typing_extensions-4.13.2 fastapi-0.115.12
                       commit: unknown

The two patches

Our patch+47 −1
pydantic/json_schema.pyindex 10d2f972..fd07458d 100644@@ -1633,6 +1633,7 @@ class GenerateJsonSchema:         * additional properties         * json_schema_extra         * deprecated+        * examples          Done in place, hence there's no return value as the original json_schema is mutated.         No ref resolving is involved here, as that's not appropriate for simple updates.@@ -1649,7 +1650,10 @@ class GenerateJsonSchema:                 raise TypeError(f'model_title_generator {model_title_generator} must return str, not {title.__class__}')             json_schema.setdefault('title', title)         if 'title' not in json_schema:-            json_schema['title'] = cls.__name__+            if issubclass(cls, RootModel) and (root_title := cls.__pydantic_fields__['root'].title):+                json_schema['title'] = root_title+            else:+                json_schema['title'] = cls.__name__          # BaseModel and dataclasses; don't use cls.__doc__ as it will contain the verbose class signature by default         if cls is BaseModel:@@ -1670,6 +1674,13 @@ class GenerateJsonSchema:         elif issubclass(cls, RootModel) and (root_description := cls.__pydantic_fields__['root'].description):             json_schema.setdefault('description', root_description) +        if issubclass(cls, RootModel):+            root_field = cls.__pydantic_fields__['root']+            if root_field.examples is not None:+                json_schema.setdefault('examples', to_jsonable_python(root_field.examples))+            if bool(root_field.deprecated) or root_field.deprecated == '':+                json_schema.setdefault('deprecated', True)+         extra = config.get('extra')         if 'additionalProperties' not in json_schema:  # This check is particularly important for `typed_dict_schema()`             if extra == 'allow':tests/test_root_model.pyindex 687ee17c..ca5c3157 100644@@ -708,6 +708,41 @@ def test_model_with_field_description() -> None:     assert AModel.model_json_schema() == {'title': 'AModel', 'type': 'integer', 'description': 'abc'}  +def test_root_model_field_examples() -> None:+    class AModel(RootModel):+        root: Annotated[str, Field(examples=['foo', 'bar'])]++    assert AModel.model_json_schema() == {'title': 'AModel', 'type': 'string', 'examples': ['foo', 'bar']}+++def test_root_model_field_deprecated() -> None:+    class AModel(RootModel):+        root: Annotated[str, Field(deprecated=True)]++    assert AModel.model_json_schema() == {'title': 'AModel', 'type': 'string', 'deprecated': True}+++def test_root_model_field_title() -> None:+    class AModel(RootModel):+        root: Annotated[str, Field(title='MyTitle')]++    assert AModel.model_json_schema() == {'title': 'MyTitle', 'type': 'string'}+++def test_root_model_field_all_attributes() -> None:+    class AModel(RootModel):+        root: Annotated[str, Field(examples=['foo', 'bar'], deprecated=True, title='MyTitle', description='desc', pattern='^f')]++    assert AModel.model_json_schema() == {+        'title': 'MyTitle',+        'description': 'desc',+        'pattern': '^f',+        'examples': ['foo', 'bar'],+        'deprecated': True,+        'type': 'string',+    }++ def test_model_with_both_docstring_and_field_description() -> None:     """Check if the docstring is used as the description when both are present."""  
Merged fix · PR #+52 −1
pydantic/json_schema.pyindex 10d2f972e..1f76e861d 100644@@ -1649,7 +1649,10 @@ class GenerateJsonSchema:                 raise TypeError(f'model_title_generator {model_title_generator} must return str, not {title.__class__}')             json_schema.setdefault('title', title)         if 'title' not in json_schema:-            json_schema['title'] = cls.__name__+            if issubclass(cls, RootModel) and (root_title := cls.__pydantic_fields__['root'].title):+                json_schema['title'] = root_title+            else:+                json_schema['title'] = cls.__name__          # BaseModel and dataclasses; don't use cls.__doc__ as it will contain the verbose class signature by default         if cls is BaseModel:@@ -1670,6 +1673,13 @@ class GenerateJsonSchema:         elif issubclass(cls, RootModel) and (root_description := cls.__pydantic_fields__['root'].description):             json_schema.setdefault('description', root_description) +        if issubclass(cls, RootModel):+            root_field = cls.__pydantic_fields__['root']+            if root_field.examples is not None:+                json_schema.setdefault('examples', to_jsonable_python(root_field.examples))+            if root_field.deprecated:+                json_schema['deprecated'] = True+         extra = config.get('extra')         if 'additionalProperties' not in json_schema:  # This check is particularly important for `typed_dict_schema()`             if extra == 'allow':tests/test_root_model.pyindex 687ee17c8..60e36c338 100644@@ -721,3 +721,44 @@ def test_model_with_both_docstring_and_field_description() -> None:         'type': 'integer',         'description': 'More detailed description',     }+++def test_model_json_schema_field_examples() -> None:+    class AModel(RootModel):+        root: str = Field(examples=['foo', 'bar'])++    assert AModel.model_json_schema() == {'title': 'AModel', 'type': 'string', 'examples': ['foo', 'bar']}+++def test_model_json_schema_field_deprecated() -> None:+    class AModel(RootModel):+        root: str = Field(deprecated=True)++    assert AModel.model_json_schema() == {'title': 'AModel', 'type': 'string', 'deprecated': True}+++def test_model_json_schema_field_title() -> None:+    class AModel(RootModel):+        root: str = Field(title='My Title')++    assert AModel.model_json_schema() == {'title': 'My Title', 'type': 'string'}+++def test_model_json_schema_field_title_overridden_by_config() -> None:+    class AModel(RootModel):+        model_config = ConfigDict(title='Config Title')+        root: str = Field(title='Field Title')++    assert AModel.model_json_schema() == {'title': 'Config Title', 'type': 'string'}+++def test_model_json_schema_field_examples_and_deprecated_together() -> None:+    class AModel(RootModel):+        root: Annotated[str, Field(examples=['foo'], deprecated=True)]++    assert AModel.model_json_schema() == {+        'title': 'AModel',+        'type': 'string',+        'examples': ['foo'],+        'deprecated': True,+    } 

What the agent reported

Done. Two files changed, both intentional.

What was wrong

For a RootModel, the root field's core-schema metadata (which normally carries title, examples, deprecated) is deliberately discarded during core-schema generation (_generate_schema.py:842-844), and only description was re-added afterward in _update_class_schema. As a result:

  • examples and deprecated from Field(...) on root were silently dropped from model_json_schema().
  • title from the field was overwritten by the unconditional class-name fallback (json_schema['title'] = cls.__name__).

pattern survived because it's baked into the inner str core schema; description survived via its own re-add special-case.

What I changed (pydantic/json_schema.py, _update_class_schema)

Extended the existing RootModel re-add pattern (localized here rather than touching core-schema generation, to avoid disturbing docstring/description precedence and json_schema_extra handling):

  • title: before falling back to the class name, use the root field's .title if set (still after config-title / model_title_generator, which take precedence).
  • examples: json_schema.setdefault('examples', to_jsonable_python(root_field.examples)).
  • deprecated: setdefault('deprecated', True) using the same normalization (bool(...) or ... == '') that normal fields use in _extract_json_schema_info_from_field_info.

All additions are gated on issubclass(cls, RootModel), so BaseModels, dataclasses, and TypedDicts are unaffected. Also updated the method docstring to list examples.

Test evidence

Added 4 regression tests to tests/test_root_model.py (test_root_model_field_examples, _deprecated, _title, _all_attributes — the last reproduces the report exactly). They failed on the unfixed code (examples/deprecated missing, title = AModel) and pass after the fix.

Gate: ./bt-test tests/test_root_model.py tests/test_json_schema.py → 612 passed, 3 skipped, 1 xfailed, no failures. Existing precedence tests (test_root_model_json_schema_meta expecting RootModel[int], test_model_with_both_docstring_and_field_description expecting docstring wins) still pass.

Review: reviewer confirmed correct gating, matching deprecated/examples normalization, preserved title/description precedence, and no unrelated changes or scratch files.

Requirements disposition

  1. examples lost on root field — Implemented; covered by test_root_model_field_examples and _all_attributes (failed before, pass after).
  2. deprecated lost on root field — Implemented; covered by test_root_model_field_deprecated and _all_attributes.
  3. title not applied / overwritten by class name — Implemented; covered by test_root_model_field_title and _all_attributes.
  4. pattern/description still work; json_schema_extra still works — Verified unchanged: pattern/description asserted in _all_attributes; the full test_json_schema.py and json_schema_extra root-model tests pass. No change to those code paths.

All changes are left uncommitted in the working tree.