Backtestspydanticrun-20261003-150343#11922

Issue #11922 Merged fix PR # Run 3 Oct 2026 · run-20261003-150343 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.

Both patches fix the reported symptoms in `GenerateJsonSchema` for root models: `examples` and `deprecated` from the root `Field` now appear in the schema, and a root field `title` can replace the class name. The deciding differences are at the edges.

**Correctness**
- **Title source.** Patch A uses the root field title only when it is in `_attributes_set`, meaning the user set it explicitly. A comment explains this excludes titles produced by `field_title_generator`. Patch B reads `root_field.title` whenever it is truthy. Pydantic fills `FieldInfo.title` from `field_title_generator` while building the schema, so a config like `field_title_generator=lambda n, i: n.upper()` would wrongly turn the model title into 'ROOT' under Patch B. Patch A guards against this and tests it.
- **Title precedence.** Patch A puts an explicit field title ahead of `model_title_generator`. Patch B puts it behind. Either order is defensible.
- **Deprecated message.** Patch A also treats `deprecated=''` as deprecated. Patch B relies on truthiness, so an empty message is silently dropped.
- **Refactor.** Patch A computes `root_field` once via `__pydantic_root_model__` and reuses it, consolidating the existing checks.

**Tests**
Patch A's tests are broader. They cover:
- the Annotated form and the assigned-default form;
- non-JSON example values, with `date` serialized to '2020-01-01';
- a deprecated message string;
- the root model nested inside `$defs`;
- config title precedence;
- the `field_title_generator` regression;
- `deprecated=False`.

Patch B's tests cover only the basic cases plus config precedence.

**Scope and craft**
Both patches stay in scope. Patch A's consolidation is clean and fits the surrounding code. Overall, Patch A is more correct at the edges and better tested.

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

9m 3s

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

82vs 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+77 −5
pydantic/json_schema.pyindex 10d2f972..e091a3a3 100644@@ -1639,10 +1639,16 @@ class GenerateJsonSchema:         """         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 'title' in root_field._attributes_set:+            # Only use explicitly set titles, not those produced by a `field_title_generator`:+            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['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..7b5bb56c 100644@@ -708,6 +708,66 @@ 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:+    """https://github.com/pydantic/pydantic/issues/11922"""++    class AnnotatedModel(RootModel):+        root: Annotated[str, Field(examples=['foo', 'bar'], deprecated=True, title='Custom Title')]++    assert AnnotatedModel.model_json_schema() == {+        'title': 'Custom Title',+        'type': 'string',+        'examples': ['foo', 'bar'],+        'deprecated': True,+    }++    class AssignedModel(RootModel[date]):+        root: date = Field(examples=[date(2020, 1, 1)], deprecated='Use something else', title='Custom Title')++    assert AssignedModel.model_json_schema() == {+        'title': 'Custom Title',+        'type': 'string',+        'format': 'date',+        'examples': ['2020-01-01'],+        'deprecated': True,+    }++    class Outer(BaseModel):+        value: AnnotatedModel++    assert Outer.model_json_schema()['$defs']['AnnotatedModel'] == {+        'title': 'Custom Title',+        'type': 'string',+        'examples': ['foo', 'bar'],+        'deprecated': True,+    }+++def test_model_config_title_takes_precedence_over_field_title() -> None:+    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_field_title_generator_does_not_override_model_title() -> None:+    class AModel(RootModel):+        model_config = ConfigDict(field_title_generator=lambda name, info: name.upper())++        root: int++    assert AModel.model_json_schema() == {'title': 'AModel', 'type': 'integer'}+++def test_model_field_not_deprecated() -> None:+    class AModel(RootModel):+        root: int = Field(deprecated=False)++    assert AModel.model_json_schema() == {'title': 'AModel', 'type': 'integer'}++ 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,+    }