Backtestspydanticrun-20261027-165153#11922
Some Field attributes lost in JSON schema when using RootModel
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Both patches add examples, deprecated, and title from the root field in `model_schema` and pass all independent tests. Patch A is more correct at the edges. It uses `root_field._attributes_set` to apply only an explicitly set field title, so a config `field_title_generator` (which mutates `FieldInfo.title` during schema generation) does not replace the model's class name with 'ROOT'; Patch B reads `.title` directly and would regress that case, and A adds a test for it. A also handles `deprecated=''` like the existing field-level code (`bool(deprecated) or deprecated == ''`) and uses `setdefault` for `deprecated`, while B unconditionally assigns. A's precedence (config title > explicit field title > model_title_generator > class name) is defensible and tested; B puts model_title_generator above field title, also defensible, but untested. A's tests are broader: Annotated and assigned forms, deprecation message string, deprecated=False, nested `$defs` consistency, config-title precedence, and title-generator interaction. B's tests cover the basic cases only. Scope and craft are comparable, with A slightly cleaner by hoisting `root_field` once and reusing it for the description branch.
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
6m 57s
Wall-clock time in the container
Full test suite
No new failures
1,247 passed · 15 skipped · 1,262 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
73vs 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..c01efe2e 100644@@ -1641,8 +1641,13 @@ class GenerateJsonSchema: from .main import BaseModel from .root_model import RootModel + root_field = 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 is not None and root_field._attributes_set.get('title') is not None:+ # Only an explicitly set title (not one produced by a `field_title_generator`) is used for the model:+ 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 +1672,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 bool(root_field.deprecated) or root_field.deprecated == '':+ json_schema.setdefault('deprecated', True) extra = config.get('extra') if 'additionalProperties' not in json_schema: # This check is particularly important for `typed_dict_schema()`tests/test_json_schema.pyindex ff6bc3c3..67768ca8 100644@@ -5391,6 +5391,64 @@ def test_root_model(): } +def test_root_model_field_json_schema_attributes() -> None:+ """https://github.com/pydantic/pydantic/issues/11922"""++ class Annotated_(RootModel):+ root: Annotated[str, Field(title='Root Title', examples=['foo', 'bar'], deprecated=True, pattern='^f')]++ assert Annotated_.model_json_schema() == {+ 'title': 'Root Title',+ 'examples': ['foo', 'bar'],+ 'deprecated': True,+ 'pattern': '^f',+ 'type': 'string',+ }++ class Assigned(RootModel[str]):+ root: str = Field(title='Root Title', examples=['foo'], deprecated='Use something else')++ assert Assigned.model_json_schema() == {+ 'title': 'Root Title',+ 'examples': ['foo'],+ 'deprecated': True,+ 'type': 'string',+ }++ class Parent(BaseModel):+ child: Annotated_++ assert Parent.model_json_schema()['$defs']['Annotated_'] == Annotated_.model_json_schema()++ class NotDeprecated(RootModel[int]):+ root: int = Field(deprecated=False)++ assert NotDeprecated.model_json_schema() == {'title': 'NotDeprecated', 'type': 'integer'}+++def test_root_model_config_title_takes_precedence_over_field_title() -> None:+ class Model(RootModel[int]):+ model_config = ConfigDict(title='Config Title')++ root: int = Field(title='Field Title')++ assert Model.model_json_schema() == {'title': 'Config Title', 'type': 'integer'}+++def test_root_model_field_title_generator_does_not_override_model_title() -> None:+ class Model(RootModel[int]):+ model_config = ConfigDict(field_title_generator=lambda name, _: name.upper())++ assert Model.model_json_schema() == {'title': 'Model', 'type': 'integer'}++ class Generated(RootModel[int]):+ model_config = ConfigDict(+ field_title_generator=lambda name, _: name.upper(), model_title_generator=lambda cls: 'Generated Title'+ )++ assert Generated.model_json_schema() == {'title': 'Generated Title', 'type': 'integer'}++ def test_type_adapter_json_schemas_title_description(): class Model(BaseModel): a: str
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,+ }