Backtestspydanticrun-20260930-183947#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 core bug: RootModel now carries the root field's examples, deprecated flag and title into the model-level JSON schema. Patch B handles the edge cases more carefully. 1. **Title from `field_title_generator`.** Pydantic can fill in `FieldInfo.title` from a `field_title_generator`. Patch A reads `root_field.title` without checking where it came from, so a generated root title (e.g. 'ROOT') would silently replace the class-name title. Patch B only uses a title the user set explicitly (checked via `_attributes_set`), and it has a test proving generated titles don't leak. 2. **Title precedence.** In Patch A the root title applies only when neither the config title nor `model_title_generator` produced one. So an explicit `Field(title=...)` loses to a model-wide generator. Patch B gives the explicit field title precedence over the generator but not over an explicit config title, which is more sensible, and tests both orderings. 3. **Empty deprecation message.** Patch A uses `if root_field.deprecated:`, so `deprecated=''` (a valid empty-message form) is dropped. Patch B handles it and parametrizes a test for it. 4. **Placement of `deprecated`.** Patch B puts the flag in the existing `__deprecated__` block, consistent with how class-level deprecation is emitted. 5. **Tests.** Patch B also covers the nested `$defs` case, which confirms the metadata appears where RootModels are actually referenced. Patch A's tests cover the basic scenarios but miss these edges. Both are similar in scope, and Patch B also lightly refactors `root_field` into one variable, which reads cleanly.
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
11m 34s
Wall-clock time in the container
Full test suite
No new failures
12,246 passed · 503 skipped · 12,749 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
96vs 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..d77faa42 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 'title' in root_field._attributes_set and root_field.title is not None:+ # Only use an explicitly set title, not one 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,9 +1672,12 @@ 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 and root_field.examples is not None:+ json_schema.setdefault('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()` if extra == 'allow':@@ -1706,7 +1714,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..6e710967 100644@@ -708,6 +708,88 @@ 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,+ }+++@pytest.mark.parametrize('deprecated', ['use something else', ''])+def test_model_with_field_deprecated_message(deprecated: str) -> None:+ class AModel(RootModel):+ root: int = Field(deprecated=deprecated)++ 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='Root title')++ assert AModel.model_json_schema() == {'title': 'Root title', 'type': 'integer'}+++def test_model_with_field_title_and_config_title() -> None:+ """Check if the config title takes precedence over the root field title."""++ 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_title_and_model_title_generator() -> None:+ """Check if the root field title takes precedence over the `model_title_generator`."""++ class AModel(RootModel):+ model_config = ConfigDict(model_title_generator=lambda cls: f'Generated {cls.__name__}')++ root: int = Field(title='Root title')++ assert AModel.model_json_schema() == {'title': 'Root title', 'type': 'integer'}+++def test_model_with_field_title_generator() -> None:+ """Check that a title generated by `field_title_generator` does not override the model title."""++ class AModel(RootModel):+ model_config = ConfigDict(field_title_generator=lambda name, info: name.upper())++ root: int++ class BModel(RootModel):+ model_config = ConfigDict(field_title_generator=lambda name, info: name.upper())++ root: int = Field(title='Root title')++ assert AModel.model_json_schema() == {'title': 'AModel', 'type': 'integer'}+ assert BModel.model_json_schema() == {'title': 'Root title', 'type': 'integer'}+++def test_model_with_field_metadata_nested() -> None:+ class AModel(RootModel):+ root: int = Field(title='Root title', examples=[1, 2], deprecated=True)++ class Model(BaseModel):+ a: AModel++ assert Model.model_json_schema() == {+ '$defs': {'AModel': {'title': 'Root title', 'type': 'integer', 'examples': [1, 2], 'deprecated': True}},+ 'properties': {'a': {'$ref': '#/$defs/AModel'}},+ 'required': ['a'],+ 'title': 'Model',+ '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."""
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,+ }