Backtestspydanticrun-20261002-175417#11922

Issue #11922 Merged fix PR # Run 2 Oct 2026 · run-20261002-175417 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.

Both patches fix the issue the same basic way: in the model-level schema update, they copy the `root` field's examples, deprecated flag and title into the RootModel's JSON schema, and both serialize examples with `to_jsonable_python`. For the issue's example (examples plus deprecated, and title no longer overwritten by the class name), both work.

Patch B is the cleaner and more complete version:
- It computes `root_field` once, using the existing `__pydantic_root_model__` convention. It then reuses it for the title, the description, the new examples/deprecated handling, and the existing `json_schema_extra` branch, so all root-field metadata goes through one path.
- Title precedence is principled: config title first, then field title, then `model_title_generator`, then the class name. An explicit field title is more specific than a generic generator, so it should win. In Patch A, the generator would silently override an explicit `Field(title=...)`, which partly reproduces the reported "title overwritten" problem.
- Patch B also handles the `deprecated=''` edge case, which Patch A's truthiness check misses.

Tests: both add tests that fail before the change and pass after it. Patch B's are more meaningful:
- `deprecated` given as a message string.
- Non-JSON example values (`date`), which exercises the `to_jsonable_python` serialization.
- Precedence between config title and generator title.
- A nested RootModel appearing in `$defs`.

Patch A's tests cover only the basic cases plus config-title precedence.

Scope is comparable, and Patch B's refactor of the existing branches is small and low-risk. Overall, B wins on correctness at the edges and on test quality.

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 32s

Wall-clock time in the container

Full test suite

No new failures

12,244 passed · 503 skipped · 12,747 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

91vs 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+86 −5
pydantic/json_schema.pyindex 10d2f972..5e0ce4a4 100644@@ -1633,16 +1633,22 @@ class GenerateJsonSchema:         * additional properties         * json_schema_extra         * deprecated+        * examples (for `RootModel`, from the `root` field)          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.         """         from ._internal._dataclasses import is_stdlib_dataclass         from .main import BaseModel-        from .root_model import RootModel++        root_field = (+            cls.__pydantic_fields__['root'] if issubclass(cls, BaseModel) and cls.__pydantic_root_model__ else None+        )          if (config_title := config.get('title')) is not None:             json_schema.setdefault('title', config_title)+        elif root_field is not None and root_field.title is not None:+            json_schema.setdefault('title', root_field.title)         elif model_title_generator := config.get('model_title_generator'):             title = model_title_generator(cls)             if not isinstance(title, str):@@ -1667,8 +1673,14 @@ class GenerateJsonSchema:          if docstring:             json_schema.setdefault('description', inspect.cleandoc(docstring))-        elif issubclass(cls, RootModel) and (root_description := cls.__pydantic_fields__['root'].description):-            json_schema.setdefault('description', root_description)+        elif root_field is not None and root_field.description:+            json_schema.setdefault('description', root_field.description)++        if root_field is not None:+            if root_field.examples is not None:+                json_schema.setdefault('examples', to_jsonable_python(root_field.examples))+            if root_field.deprecated or 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()`@@ -1678,8 +1690,8 @@ class GenerateJsonSchema:                 json_schema['additionalProperties'] = False          json_schema_extra = config.get('json_schema_extra')-        if issubclass(cls, BaseModel) and cls.__pydantic_root_model__:-            root_json_schema_extra = cls.model_fields['root'].json_schema_extra+        if root_field is not None:+            root_json_schema_extra = root_field.json_schema_extra             if json_schema_extra and root_json_schema_extra:                 raise ValueError(                     '"model_config[\'json_schema_extra\']" and "Field.json_schema_extra" on "RootModel.root"'tests/test_root_model.pyindex 687ee17c..aa046509 100644@@ -721,3 +721,72 @@ def test_model_with_both_docstring_and_field_description() -> None:         'type': 'integer',         'description': 'More detailed description',     }+++def test_model_with_field_examples_title_and_deprecated() -> None:+    class AModel(RootModel):+        root: Annotated[str, Field(title='Root Title', examples=['foo', 'bar'], deprecated=True)]++    assert AModel.model_json_schema() == {+        'title': 'Root Title',+        'type': 'string',+        'examples': ['foo', 'bar'],+        'deprecated': True,+    }+++def test_model_with_field_deprecated_message() -> None:+    class AModel(RootModel):+        root: int = Field(deprecated='Use something else')++    assert AModel.model_json_schema() == {'title': 'AModel', 'type': 'integer', 'deprecated': True}+++def test_model_with_field_examples_non_json_values() -> None:+    class AModel(RootModel):+        root: date = Field(examples=[date(2020, 1, 1)])++    assert AModel.model_json_schema() == {+        'title': 'AModel',+        'type': 'string',+        'format': 'date',+        'examples': ['2020-01-01'],+    }+++def test_model_with_field_title_and_config_title() -> None:+    """Check that the config title takes precedence over the field title."""++    class AModel(RootModel):+        model_config = ConfigDict(title='Config Title')++        root: int = Field(title='Field Title')++    assert AModel.model_json_schema() == {'title': 'Config Title', 'type': 'integer'}+++def test_model_with_field_title_and_title_generator() -> None:+    """Check that the field title takes precedence over the `model_title_generator`."""++    class AModel(RootModel):+        model_config = ConfigDict(model_title_generator=lambda cls: f'Generated {cls.__name__}')++        root: int = Field(title='Field Title')++    assert AModel.model_json_schema() == {'title': 'Field Title', 'type': 'integer'}+++def test_nested_model_with_field_examples() -> None:+    class AModel(RootModel):+        root: int = Field(examples=[1, 2], title='Root Title')++    class Model(BaseModel):+        a: AModel++    assert Model.model_json_schema() == {+        '$defs': {'AModel': {'title': 'Root Title', 'type': 'integer', 'examples': [1, 2]}},+        'properties': {'a': {'$ref': '#/$defs/AModel'}},+        'required': ['a'],+        'title': 'Model',+        'type': 'object',+    } 
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,+    }