Backtestspydanticrun-20260923-170312#11922

Issue #11922 Merged fix PR # Run 23 Sep 2026 · run-20260923-170312 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 A = our agent, Patch B = the merged fix.

Patch A fixes the root cause: the code already had a FIXME acknowledging that root-field metadata was being discarded, and A reuses the existing `pydantic_js_updates` mechanism to propagate that metadata into the inner core schema. This generically restores every JS-affecting Field attribute (examples, deprecated, title, and any others) through the normal code path, and it thoughtfully excludes `description` so the existing docstring-precedence behavior (handled in `_update_class_schema`) is preserved. Its single test exercises examples, deprecated, and title together and would fail before / pass after. Patch B instead special-cases RootModel down in `GenerateJsonSchema._update_class_schema`, hand-enumerating title/examples/deprecated with duplicated logic paralleling the existing description handling. That is a symptom-level patch: it only covers the three attributes named in the issue and would silently miss any other Field metadata dropped by the same underlying gap, and it re-implements serialization (`to_jsonable_python`) and precedence rules that A gets for free. B does add broader, more granular tests (including a config-title-precedence case), which is its main merit, but that does not outweigh A's advantages on correctness (true root cause vs. mask), scope (one focused edit at the source of the bug vs. multiple hardcoded branches), and craft (removing the FIXME, deliberate description handling). Patch A is the better 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

19m 46s20 turns

Wall-clock time in the container

Full test suite

No new failures

6,390 passed · 366 skipped · 6,756 total

Contamination audit

Unknown

See the audit notes for this run

Patch size

21vs 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+19 −2
pydantic/_internal/_generate_schema.pyindex f46fcb12..8244c32f 100644@@ -840,9 +840,14 @@ class GenerateSchema:                 generic_origin: type[BaseModel] | None = getattr(cls, '__pydantic_generic_metadata__', {}).get('origin')                  if cls.__pydantic_root_model__:-                    # FIXME: should the common field metadata be used here?-                    inner_schema, _ = self._common_field_schema('root', fields['root'], decorators)+                    inner_schema, root_field_metadata = self._common_field_schema('root', fields['root'], decorators)                     inner_schema = apply_model_validators(inner_schema, model_validators, 'inner')+                    if root_field_metadata and (js_updates := root_field_metadata.get('pydantic_js_updates')):+                        # `description` is applied separately in `GenerateJsonSchema._update_class_schema`+                        # so that a class docstring takes precedence over the root field's description:+                        js_updates = {k: v for k, v in js_updates.items() if k != 'description'}+                        if js_updates:+                            update_core_metadata(inner_schema.setdefault('metadata', {}), pydantic_js_updates=js_updates)                     model_schema = core_schema.model_schema(                         cls,                         inner_schema,tests/test_root_model.pyindex 687ee17c..bb1124bb 100644@@ -708,6 +708,18 @@ def test_model_with_field_description() -> None:     assert AModel.model_json_schema() == {'title': 'AModel', 'type': 'integer', 'description': 'abc'}  +def test_model_with_field_examples_deprecated_and_title() -> None:+    class AModel(RootModel):+        root: Annotated[str, Field(examples=['foo', 'bar'], deprecated=True, title='My Title')]++    assert AModel.model_json_schema() == {+        'title': 'My Title',+        'type': 'string',+        'examples': ['foo', 'bar'],+        'deprecated': True,+    }++ 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

The review passed. Work is complete.

Summary

What was wrong: For a RootModel, the root field's JSON-schema metadata (title, examples, deprecated) was silently dropped from model_json_schema(). In pydantic/_internal/_generate_schema.py, the RootModel branch of _model_schema discarded the second element of _common_field_schema(...) — the core_metadata carrying pydantic_js_updates (marked with a # FIXME). Regular model fields attach that metadata to their field core schema so json_schema.py's generate_inner merges it in; RootModel never did. pattern/description/json_schema_extra survived only because each has a separate code path.

What I changed (pydantic/_internal/_generate_schema.py, RootModel branch): stopped discarding the field metadata and merged its pydantic_js_updates onto the inner schema so generate_inner applies them. description is explicitly excluded from the merge because it is already handled by the dedicated RootModel branch in _update_class_schema, and routing it through js_updates would break the existing docstring-over-field-description precedence. pydantic_js_extra (json_schema_extra) is deliberately not merged, since it too is handled separately — avoiding double application.

Test evidence:

  • Added tests/test_root_model.py::test_model_with_field_examples_deprecated_and_title — the exact scenario from the report. Confirmed it FAILS without the fix (title overwritten with 'AModel', examples/deprecated missing) and PASSES with it.
  • Blast-radius gate on tests/test_root_model.py + tests/test_json_schema.py: the first run surfaced a real regression in test_model_with_both_docstring_and_field_description (description precedence); after the one-time repair (excluding description), the re-run is fully green: 609 passed, 3 skipped, 1 xfailed.
  • Reviewer verdict: PASS.

Requirements disposition:

  • examples lost in RootModel schema → fixed, covered by regression test.
  • deprecated lost → fixed, covered by the same test.
  • title not applied / overwritten by class name → fixed, covered by the same test (field title 'My Title' now wins; class name still used as fallback when no field title).
  • pattern/description continue to work → preserved (verified: description precedence test and existing test_model_with_field_description still pass).
  • json_schema_extra continues to work → preserved (not double-applied; existing tests pass).

All changes are left uncommitted in the working tree.