Backtestspydanticrun-20260930-144322#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 issue in the same place, `GenerateJsonSchema`'s model-level schema handling. For RootModel they add the root field's `examples` (made JSON-safe with `to_jsonable_python`) and `deprecated`, and apply the root field's `title` instead of the class name. The differences are in edge cases. 1. **How the title is detected.** Patch A reads `root_field.title` whenever it is set. In pydantic, `field_title_generator` can fill in `FieldInfo.title` during schema building. With Patch A, a generated field title could then replace the model's class-name title, which was never asked for. Patch B only uses the title if the user set it explicitly (`'title' in root_field._attributes_set`), and its test checks exactly this case: `Gen` with `field_title_generator` still gets the title 'Gen'. 2. **Title priority.** Patch B places the explicit field title after the config `title` but before `model_title_generator`. That is reasonable: something the user wrote on the field should beat a generic generator. In Patch A, the field title only applies when no generator is configured. 3. **Deprecated values.** Patch B also treats `deprecated=''` as deprecated, which is a small extra edge case. 4. **Tests.** Patch B's single test covers more ground: - title, description, examples and deprecated together; - the schema is the same when the model is nested under `$defs`; - a config title overrides the field title; - `field_title_generator` does not leak into the title; - a string deprecation message. Patch A's tests are clean and separate but only cover the basic cases and the config override. 5. **Craft.** Patch B computes `root_field` once and reuses it, including in the existing description branch. This is tidier than Patch A's repeated `issubclass` checks. Overall, Patch B is more robust 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
4m 29s17 turns
Wall-clock time in the container
Full test suite
No new failures
12,239 passed · 503 skipped · 12,742 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
46vs 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..5ab9bc06 100644@@ -1641,8 +1641,12 @@ 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 'title' in root_field._attributes_set:+ 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,9 +1671,15 @@ class GenerateJsonSchema: if docstring: json_schema.setdefault('description', inspect.cleandoc(docstring))- elif issubclass(cls, RootModel) and (root_description := cls.__pydantic_fields__['root'].description):+ elif root_field is not None and (root_description := root_field.description): json_schema.setdefault('description', root_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['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 687ee17c..60db3a2d 100644@@ -721,3 +721,37 @@ def test_model_with_both_docstring_and_field_description() -> None: 'type': 'integer', 'description': 'More detailed description', }+++def test_model_with_field_examples_deprecated_title() -> None:+ class Foo(RootModel[str]):+ root: Annotated[str, Field(examples=['foo', 'bar'], deprecated=True, title='Foo title', description='d')]++ assert Foo.model_json_schema() == {+ 'type': 'string',+ 'title': 'Foo title',+ 'description': 'd',+ 'examples': ['foo', 'bar'],+ 'deprecated': True,+ }++ class Bar(BaseModel):+ foo: Foo++ assert Bar.model_json_schema()['$defs']['Foo'] == Foo.model_json_schema()++ class FooCfg(Foo):+ model_config = ConfigDict(title='Cfg')++ assert FooCfg.model_json_schema()['title'] == 'Cfg'++ class Gen(RootModel[int]):+ model_config = ConfigDict(field_title_generator=lambda name, info: name.upper())+ root: int++ assert Gen.model_json_schema()['title'] == 'Gen'++ class DepMsg(RootModel[int]):+ root: Annotated[int, Field(deprecated='some message')]++ assert DepMsg.model_json_schema()['deprecated'] is True
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,+ }
What the agent reported
RootModel.model_json_schema() now includes the root field's examples and deprecated, and uses its explicit title instead of the class name. The final test run passed: 1217 passed, 101 skipped, 1 xfailed, 0 failed.
What was wrong: Field(...) settings on a normal model field are attached to that field's schema. A RootModel's root field is handled differently: those settings are thrown away. The only compensation was in _update_class_schema (pydantic/json_schema.py), which copied the root field's description and json_schema_extra onto the model schema. That is why description, pattern and json_schema_extra worked. title, examples and deprecated had no such handling, and the title always fell back to the class name.
What I changed (all in _update_class_schema, pydantic/json_schema.py:1644-1681):
- Lookup: the root field is looked up once, and the existing description branch now uses that lookup.
- Title order: config
title, then the root field's title, thenmodel_title_generator, then the class name. The root field's title only counts if it was set explicitly withField(title=...). The reviewer caught that a configfield_title_generatoralso writes into the field's title; without this check, a RootModel using one would have gone from"Foo"to e.g."ROOT"as its title. - Examples: the root field's
examplesare added to the schema. - Deprecated:
deprecatedis set toTruewhen the root field is deprecated, using the same rule as normal fields, so a message string also counts. json_schema_extra: still applied last, so it can still override all of the above.
Test evidence: I added test_model_with_field_examples_deprecated_title to tests/test_root_model.py. It uses the exact example from the report, adding title and description, and compares the whole schema. It also checks:
- a model that contains
Fooas a field gets the same schema forFoounder$defs; - a config title still wins over the root field title;
field_title_generatordoes not change the model title;deprecated='some message'givesdeprecated: True.
Before the fix it failed with {'title': 'Foo'} != {'title': 'Foo title'} and examples/deprecated missing. After the fix it passes. The final run covered tests/test_root_model.py, tests/test_json_schema.py and tests/test_docs.py.
Requirements:
examplesonrootmissing from the schema: fixed and tested.deprecatedonrootmissing: fixed and tested, including the message-string form.titleonrootignored or replaced by the class name: fixed and tested, with config title andfield_title_generatorbehaving as before.description,patternandjson_schema_extraalready worked: still the same. The description branch was only refactored to share the lookup, and the existing tests pass.
One limitation: like the existing description handling, root-field title and examples only fill in values the inner type's schema hasn't already set. So if the inner type brings its own examples, those win. I kept this for consistency with the existing code; ordinary model fields behave the other way round.
The changes are uncommitted in pydantic/json_schema.py and tests/test_root_model.py, with no scratch files.