Backtestspydanticrun-20261013-104308#11922

Issue #11922 Merged fix PR # Run 13 Oct 2026 · run-20261013-104308 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 issue in the same place, `GenerateJsonSchema._update_class_schema`. Each one reads the RootModel's `root` FieldInfo and emits `examples` (via `to_jsonable_python`), `deprecated: True`, and the root field's title. Both let an explicit `config['title']` take precedence over the field title.

Correctness differences are minor:
- **Title precedence:** Patch A puts the root field title ahead of `model_title_generator`. Patch B applies it only when neither config title nor generator set one. An explicit field title is arguably more specific than a generic generator, so A's ordering is reasonable, but neither choice is clearly wrong.
- **Examples:** Patch A overwrites `examples`, while Patch B uses `setdefault`. The inner schema rarely has its own examples here, so this is roughly equivalent.
- **Deprecated:** Patch A checks `is not None and is not False`, which handles deprecation-message strings and `deprecated` instances. Patch B uses truthiness, which is equivalent except for an empty-string message.
- **Description:** Patch A also refactors the existing description branch to reuse the cached `root_field_info`. This is a small clarity improvement with no added risk.

Tests are the main differentiator. Both cover examples, deprecated, title, and config-title override. Patch A goes further:
- It checks that a non-JSON-native example (a `date`) is serialized to `'2020-01-02'`, exercising the `to_jsonable_python` path.
- It checks that a string deprecation message yields `deprecated: True`.
- It checks the nested-in-model case, where the RootModel appears under `$defs` with the title and examples intact. This is the realistic usage scenario.

Patch B's tests are narrower and miss these paths. Overall the fixes are equivalent in substance, and A has stronger test coverage and slightly cleaner code.

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

5m 30s

Wall-clock time in the container

Full test suite

No new failures

1,250 passed · 15 skipped · 1,265 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

77vs 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+75 −2
pydantic/json_schema.pyindex 10d2f972..4b9d6e82 100644@@ -1641,8 +1641,12 @@ class GenerateJsonSchema:         from .main import BaseModel         from .root_model import RootModel +        root_field_info = cls.__pydantic_fields__['root'] if issubclass(cls, RootModel) else None+         if (config_title := config.get('title')) is not None:             json_schema.setdefault('title', config_title)+        elif root_field_info is not None and root_field_info.title is not None:+            json_schema.setdefault('title', root_field_info.title)         elif model_title_generator := config.get('model_title_generator'):             title = model_title_generator(cls)             if not isinstance(title, str):@@ -1667,8 +1671,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_info is not None and root_field_info.description:+            json_schema.setdefault('description', root_field_info.description)++        if root_field_info is not None:+            if root_field_info.examples is not None:+                json_schema['examples'] = to_jsonable_python(root_field_info.examples)+            if root_field_info.deprecated is not None and root_field_info.deprecated is not False:+                json_schema['deprecated'] = True          extra = config.get('extra')         if 'additionalProperties' not in json_schema:  # This check is particularly important for `typed_dict_schema()`tests/test_root_model.pyindex 687ee17c..e7e1fe8a 100644@@ -708,6 +708,69 @@ def test_model_with_field_description() -> None:     assert AModel.model_json_schema() == {'title': 'AModel', 'type': 'integer', 'description': 'abc'}  +def test_model_with_field_examples_and_deprecated() -> None:+    class AModel(RootModel):+        root: Annotated[str, Field(examples=['foo', 'bar'], deprecated=True)]++    assert AModel.model_json_schema() == {+        'title': 'AModel',+        '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_jsonable() -> None:+    class AModel(RootModel):+        root: date = Field(examples=[date(2020, 1, 2)])++    assert AModel.model_json_schema() == {+        'title': 'AModel',+        'type': 'string',+        'format': 'date',+        'examples': ['2020-01-02'],+    }+++def test_model_with_field_title() -> None:+    class AModel(RootModel):+        root: int = Field(title='Root Title')++    assert AModel.model_json_schema() == {'title': 'Root Title', 'type': 'integer'}+++def test_model_with_field_title_and_config_title() -> None:+    class AModel(RootModel):+        model_config = ConfigDict(title='Config Title')++        root: int = Field(title='Root Title')++    assert AModel.model_json_schema() == {'title': 'Config Title', 'type': 'integer'}+++def test_model_with_field_examples_nested_in_model() -> None:+    class AModel(RootModel):+        root: Annotated[str, Field(title='Root Title', examples=['foo'])]++    class Outer(BaseModel):+        a: AModel++    assert Outer.model_json_schema() == {+        '$defs': {'AModel': {'title': 'Root Title', 'type': 'string', 'examples': ['foo']}},+        'properties': {'a': {'$ref': '#/$defs/AModel'}},+        'required': ['a'],+        'title': 'Outer',+        'type': 'object',+    }++ 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,+    }