Backtestspydanticrun-20261022-024030#11922
Some Field attributes lost in JSON schema when using RootModel
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 three reported gaps (examples, deprecated, title) and pass every independent test. The difference is at the edges. Patch A reads `cls.__pydantic_fields__['root'].title` without distinguishing an explicitly set title from one injected by `field_title_generator` (pydantic writes generated titles back onto FieldInfo during core schema generation), so a RootModel configured with a field title generator would get e.g. 'ROOT' as its model title. Patch B guards this via `_attributes_set` and adds a test for it. Patch B also folds the root field's `deprecated` into the existing `__deprecated__` branch (handling the message-string and empty-string forms) rather than adding a separate block, and reuses the `__pydantic_root_model__` check already used later in the same function, removing the ad-hoc RootModel import. Its title precedence (config title > root field title > model_title_generator) is explicit and tested, whereas Patch A's ordering makes model_title_generator silently beat an explicit Field(title=...). Tests: B covers nested $defs usage, deprecated-as-message, title generator interactions, and config override; A's tests are reasonable but narrower. Scope and churn are comparable; B's small refactor is low-risk and clarifies the fix. B is the better fix.
Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.
Solve
7m 22s
Wall-clock time in the container
Full test suite
No new failures
1,251 passed · 15 skipped · 1,266 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
102vs 53 merged
Changed lines, ours vs merged
The issue
View on GitHubInitial 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: unknownThe two patches
pydantic/json_schema.pyindex 10d2f972..ea3f0c7a 100644@@ -63,6 +63,7 @@ if TYPE_CHECKING: from ._internal._core_utils import CoreSchemaField, CoreSchemaOrField from ._internal._dataclasses import PydanticDataclass from ._internal._schema_generation_shared import GetJsonSchemaFunction+ from .fields import FieldInfo from .main import BaseModel @@ -1639,10 +1640,16 @@ class GenerateJsonSchema: """ from ._internal._dataclasses import is_stdlib_dataclass from .main import BaseModel- from .root_model import RootModel++ root_field: FieldInfo | None = None+ if issubclass(cls, BaseModel) and cls.__pydantic_root_model__:+ root_field = cls.__pydantic_fields__['root'] 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 and 'title' in root_field._attributes_set:+ # Titles produced by a `field_title_generator` are not in `_attributes_set` and are ignored here+ 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 +1674,11 @@ 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 and root_field.examples is not None:+ json_schema['examples'] = to_jsonable_python(root_field.examples) extra = config.get('extra') if 'additionalProperties' not in json_schema: # This check is particularly important for `typed_dict_schema()`@@ -1678,8 +1688,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"'@@ -1706,7 +1716,9 @@ class GenerateJsonSchema: f"model_config['json_schema_extra']={json_schema_extra} should be a dict, callable, or None" ) - if hasattr(cls, '__deprecated__'):+ if hasattr(cls, '__deprecated__') or (+ root_field is not None and (bool(root_field.deprecated) or root_field.deprecated == '')+ ): json_schema['deprecated'] = True def resolve_ref_schema(self, json_schema: JsonSchemaValue) -> JsonSchemaValue:tests/test_root_model.pyindex 687ee17c..d5b23a66 100644@@ -721,3 +721,81 @@ def test_model_with_both_docstring_and_field_description() -> None: 'type': 'integer', 'description': 'More detailed description', }+++def test_model_with_field_examples_and_deprecated() -> None:+ """https://github.com/pydantic/pydantic/issues/11922"""++ 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_title() -> None:+ class AModel(RootModel):+ root: int = Field(title='Custom Title')++ assert AModel.model_json_schema() == {'title': 'Custom Title', 'type': 'integer'}+++def test_model_with_both_config_title_and_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_with_field_title_and_title_generator() -> None:+ 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_model_with_field_title_generator_does_not_override_class_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_nested_model_with_root_field_metadata() -> None:+ class AModel(RootModel):+ root: Annotated[str, Field(title='A Title', examples=['foo'], deprecated=True)]++ class Model(BaseModel):+ a: AModel++ assert Model.model_json_schema() == {+ '$defs': {+ 'AModel': {+ 'title': 'A Title',+ 'type': 'string',+ 'examples': ['foo'],+ 'deprecated': True,+ }+ },+ 'properties': {'a': {'$ref': '#/$defs/AModel'}},+ 'required': ['a'],+ 'title': 'Model',+ 'type': 'object',+ }
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,+ }