Backtestspydanticrun-20260930-144322#13453

Issue #13453 Merged fix PR #13456 Run 30 Sep 2026 · run-20260930-144322 pydantic/pydantic

RootModel.model_dump() typing signature rejects supported serialization arguments

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 core bug the same way. They widen `context` to `Any | None` and add `fallback: Callable[[Any], Any] | None` and `polymorphic_serialization: bool | None` in the same positions as `BaseModel.model_dump`. Both keep the `Any` return type. On correctness they are essentially equal. B also narrows `include`/`exclude` to `IncEx | None`, which is closer to the base but was not asked for.

Tests decide it for A. A adds the issue's exact example calls to `tests/typechecking/root_model.py`. That is the suite that runs mypy, pyright and pyrefly, so it directly catches this regression and fails before the fix. A also adds a runtime test that the calls work, and an AST-based sync test comparing parameter names, annotations and defaults against `BaseModel`. The sync test skips the `include`/`exclude` annotations, but it is still a useful drift guard. B adds no type-checker cases at all. B's only test sets the global `typing.TYPE_CHECKING = True` and re-executes `root_model.py` as a new module. That leaks process-global state during the run, imports TYPE_CHECKING-only symbols, and builds a duplicate `RootModel` class. It is fragile and could interfere with other tests.

Scope and craft also favour A. B replaces RootModel's explanatory docstring with a copy of BaseModel's, and its test asserts the two docstrings are identical. The copied text says 'Returns: A dictionary representation of the model', which is wrong for RootModel. That is exactly the case the original docstring explained. B also locks the two docstrings together for no real benefit. A's change is minimal and focused.

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 16s12 turns

Wall-clock time in the container

Full test suite

No new failures

12,267 passed · 501 skipped · 12,768 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

86vs 84 merged

Changed lines, ours vs merged

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

RootModel inherits the runtime implementation of BaseModel.model_dump(), but defines a separate declaration under TYPE_CHECKING to preserve its more precise return type.

That declaration has diverged from the base method:

  • context is restricted to dict[str, Any] | None instead of Any | None.
  • fallback is missing.
  • polymorphic_serialization is missing.

As a result, Mypy, Pyright, and Pyrefly reject valid calls that succeed at runtime.

All three calls in the example below succeed at runtime.

Mypy currently reports errors equivalent to:

Argument "context" to "model_dump" of "RootModel" has incompatible type "str"
Unexpected keyword argument "fallback" for "model_dump" of "RootModel"
Unexpected keyword argument "polymorphic_serialization" for "model_dump" of "RootModel"

Pyright and Pyrefly report the same signature incompatibilities.

Expected behavior

The type-checking-only RootModel.model_dump() declaration should accept the same parameters, annotations, defaults, and ordering as BaseModel.model_dump(), while preserving the more precise RootModel return annotation.

Cause

The declaration appears to have drifted as the base method evolved:

  • Serialization context originally updated both signatures.
  • BaseModel.context was later widened to Any.
  • fallback was subsequently added to BaseModel.model_dump().
  • polymorphic_serialization was later added to BaseModel.model_dump().

Those later changes were not propagated to the manually maintained RootModel declaration.

Proposed fix

Update only the static RootModel.model_dump() signature and add focused regression cases to tests/typechecking/root_model.py.

No runtime serialization behavior needs to change.

I have prepared and locally validated a focused two-file fix. The following checks pass:

  • Mypy type-checking suite
  • Pyright type-checking suite
  • Pyrefly type-checking suite
  • Focused RootModel serialization tests
  • Ruff lint and formatting checks
  • git diff --check

I would be happy to submit the PR after the issue is reviewed and assigned.

Example Code

from typing import Any

from pydantic import BaseModel, RootModel, SerializationInfo, model_serializer


class ContextRoot(RootModel[str]):
    @model_serializer
    def serialize_root(self, info: SerializationInfo) -> str:
        return f'{info.context}:{self.root}'


class Unknown:
    pass


class Base(BaseModel):
    x: int


class Sub(Base):
    y: int


ContextRoot(root='value').model_dump(context='prefix')

RootModel[Any](root=Unknown()).model_dump(
    mode='json',
    fallback=lambda _: 'fallback',
)

RootModel[list[Base]](root=[Sub(x=1, y=2)]).model_dump(
    polymorphic_serialization=True,
)

Python, Pydantic & OS Version

pydantic version: 2.14.0a1
        pydantic-core version: 2.47.0
          pydantic-core build: profile=debug pgo=false
               python version: 3.13.5 | packaged by Anaconda, Inc. | (main, Jun 12 2025, 11:23:37) [Clang 14.0.6 ]
                     platform: macOS-15.7.3-arm64-arm-64bit-Mach-O
             related packages: mypy-1.18.2 typing_extensions-4.15.0 pydantic-settings-2.7.1 pyright-1.1.407
                       commit: b281d5aed

The two patches

Our patch+84 −2
pydantic/root_model.pyindex d2900433..5d40d8d5 100644@@ -2,6 +2,7 @@  from __future__ import annotations as _annotations +from collections.abc import Callable from copy import copy, deepcopy from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar @@ -123,7 +124,7 @@ class RootModel(BaseModel, Generic[RootModelRootType], metaclass=_RootModelMetac             mode: Literal['json', 'python'] | str = 'python',             include: Any = None,             exclude: Any = None,-            context: dict[str, Any] | None = None,+            context: Any | None = None,             by_alias: bool | None = None,             exclude_unset: bool = False,             exclude_defaults: bool = False,@@ -131,7 +132,9 @@ class RootModel(BaseModel, Generic[RootModelRootType], metaclass=_RootModelMetac             exclude_computed_fields: bool = False,             round_trip: bool = False,             warnings: bool | Literal['none', 'warn', 'error'] = True,+            fallback: Callable[[Any], Any] | None = None,             serialize_as_any: bool = False,+            polymorphic_serialization: bool | None = None,         ) -> Any:             """This method is included just to get a more accurate return type for type checkers.             It is included in this `if TYPE_CHECKING:` block since no override is actually necessary.tests/test_root_model.pyindex fa2ca461..6e207454 100644@@ -1,5 +1,7 @@+import ast import pickle from datetime import date, datetime+from pathlib import Path from typing import Annotated, Any, Generic, Literal, TypeVar  import pytest@@ -15,8 +17,10 @@ from pydantic import (     PydanticDeprecatedSince20,     PydanticUserError,     RootModel,+    SerializationInfo,     ValidationError,     field_serializer,+    model_serializer,     model_validator, ) @@ -721,3 +725,50 @@ def test_model_with_both_docstring_and_field_description() -> None:         'type': 'integer',         'description': 'More detailed description',     }+++def _model_dump_signature(module_file: str, class_name: str) -> list[tuple[str, str | None, str | None]]:+    tree = ast.parse(Path(module_file).read_text(encoding='utf-8'))+    cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == class_name)+    # `RootModel.model_dump` only exists under `if TYPE_CHECKING:`, so search the whole class body:+    func = next(n for n in ast.walk(cls) if isinstance(n, ast.FunctionDef) and n.name == 'model_dump')+    args = func.args+    assert not args.defaults and not args.posonlyargs and args.vararg is None and args.kwarg is None+    return [('self', None, None)] + [+        (+            arg.arg,+            None if arg.arg in ('include', 'exclude') else ast.unparse(arg.annotation),+            None if default is None else ast.unparse(default),+        )+        for arg, default in zip(args.kwonlyargs, args.kw_defaults)+    ]+++def test_root_model_model_dump_signature_matches_base_model() -> None:+    """The `TYPE_CHECKING`-only `RootModel.model_dump` declaration must stay in sync with `BaseModel.model_dump`."""+    import pydantic.main+    import pydantic.root_model++    assert _model_dump_signature(pydantic.root_model.__file__, 'RootModel') == _model_dump_signature(+        pydantic.main.__file__, 'BaseModel'+    )+++def test_root_model_model_dump_accepts_base_model_arguments() -> None:+    class ContextRoot(RootModel[str]):+        @model_serializer+        def serialize_root(self, info: SerializationInfo) -> str:+            return f'{info.context}:{self.root}'++    class Unknown:+        pass++    class Base(BaseModel):+        x: int++    class Sub(Base):+        y: int++    assert ContextRoot(root='value').model_dump(context='prefix') == 'prefix:value'+    assert RootModel[Any](root=Unknown()).model_dump(mode='json', fallback=lambda _: 'fallback') == 'fallback'+    assert RootModel[list[Base]](root=[Sub(x=1, y=2)]).model_dump(polymorphic_serialization=True) == [{'x': 1, 'y': 2}]tests/typechecking/root_model.pyindex 1149472b..524c6113 100644@@ -1,6 +1,8 @@+from typing import Any+ from typing_extensions import assert_type -from pydantic import RootModel+from pydantic import BaseModel, RootModel, SerializationInfo, model_serializer  IntRootModel = RootModel[int] @@ -17,3 +19,29 @@ class StrRootModel(RootModel[str]): str_root_model = StrRootModel(root='a')  assert_type(str_root_model.root, str)+++# `RootModel.model_dump` should accept the same arguments as `BaseModel.model_dump`:+++class ContextRoot(RootModel[str]):+    @model_serializer+    def serialize_root(self, info: SerializationInfo) -> str:+        return f'{info.context}:{self.root}'+++class Unknown:+    pass+++class Base(BaseModel):+    x: int+++class Sub(Base):+    y: int+++ContextRoot(root='value').model_dump(context='prefix')+RootModel[Any](root=Unknown()).model_dump(mode='json', fallback=lambda _: 'fallback')+RootModel[list[Base]](root=[Sub(x=1, y=2)]).model_dump(polymorphic_serialization=True) 
Merged fix · PR #13456+71 −13
pydantic/root_model.pyindex d2900433e..4548bd326 100644@@ -2,6 +2,7 @@  from __future__ import annotations as _annotations +from collections.abc import Callable from copy import copy, deepcopy from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar @@ -15,6 +16,7 @@ from .main import BaseModel, _object_setattr if TYPE_CHECKING:     from .fields import Field as PydanticModelField     from .fields import PrivateAttr as PydanticModelPrivateAttr+    from .main import IncEx      # dataclass_transform could be applied to RootModel directly, but `ModelMetaclass`'s dataclass_transform     # takes priority (at least with pyright). We trick type checkers into thinking we apply dataclass_transform@@ -116,14 +118,20 @@ class RootModel(BaseModel, Generic[RootModelRootType], metaclass=_RootModelMetac         return m      if TYPE_CHECKING:+        # This `model_dump()` definition is only provided to get a more accurate return type for type checkers+        # (no override is actually necessary at runtime). Generally, the return type will be `RootModelRootType`,+        # assuming that `RootModelRootType` is not a `BaseModel` subclass. If `RootModelRootType` is a `BaseModel`+        # subclass, then the return type will likely be `dict[str, Any]`, as `model_dump()` calls are recursive.+        # The return type could even be something different, in the case of a custom serializer. Thus, `Any` is+        # used here to catch all of these cases.          def model_dump(  # type: ignore             self,             *,             mode: Literal['json', 'python'] | str = 'python',-            include: Any = None,-            exclude: Any = None,-            context: dict[str, Any] | None = None,+            include: IncEx | None = None,+            exclude: IncEx | None = None,+            context: Any | None = None,             by_alias: bool | None = None,             exclude_unset: bool = False,             exclude_defaults: bool = False,@@ -131,18 +139,39 @@ class RootModel(BaseModel, Generic[RootModelRootType], metaclass=_RootModelMetac             exclude_computed_fields: bool = False,             round_trip: bool = False,             warnings: bool | Literal['none', 'warn', 'error'] = True,+            fallback: Callable[[Any], Any] | None = None,             serialize_as_any: bool = False,+            polymorphic_serialization: bool | None = None,         ) -> Any:-            """This method is included just to get a more accurate return type for type checkers.-            It is included in this `if TYPE_CHECKING:` block since no override is actually necessary.--            See the documentation of `BaseModel.model_dump` for more details about the arguments.--            Generally, this method will have a return type of `RootModelRootType`, assuming that `RootModelRootType` is-            not a `BaseModel` subclass. If `RootModelRootType` is a `BaseModel` subclass, then the return-            type will likely be `dict[str, Any]`, as `model_dump` calls are recursive. The return type could-            even be something different, in the case of a custom serializer.-            Thus, `Any` is used here to catch all of these cases.+            """!!! abstract "Usage Documentation"+                [`model_dump`](../concepts/serialization.md#python-mode)++            Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.++            Args:+                mode: The mode in which `to_python` should run.+                    If mode is 'json', the output will only contain JSON serializable types.+                    If mode is 'python', the output may contain non-JSON-serializable Python objects.+                include: A set of fields to include in the output.+                exclude: A set of fields to exclude from the output.+                context: Additional context to pass to the serializer.+                by_alias: Whether to use the field's alias in the dictionary key if defined.+                exclude_unset: Whether to exclude fields that have not been explicitly set.+                exclude_defaults: Whether to exclude fields that are set to their default value.+                exclude_none: Whether to exclude fields that have a value of `None`.+                exclude_computed_fields: Whether to exclude computed fields.+                    While this can be useful for round-tripping, it is usually recommended to use the dedicated+                    `round_trip` parameter instead.+                round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].+                warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,+                    "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].+                fallback: A function to call when an unknown value is encountered. If not provided,+                    a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.+                serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.+                polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.++            Returns:+                A dictionary representation of the model.             """             ... tests/test_root_model.pyindex fa2ca4612..ce97fca28 100644@@ -1,4 +1,7 @@+import importlib.util+import inspect import pickle+import typing from datetime import date, datetime from typing import Annotated, Any, Generic, Literal, TypeVar @@ -721,3 +724,29 @@ def test_model_with_both_docstring_and_field_description() -> None:         'type': 'integer',         'description': 'More detailed description',     }+++def test_type_checking_model_dump_signature_in_sync_with_base_model() -> None:++    import pydantic.root_model++    spec = importlib.util.spec_from_file_location('pydantic._root_model_type_checking', pydantic.root_model.__file__)+    assert spec is not None and spec.loader is not None+    module = importlib.util.module_from_spec(spec)++    typing.TYPE_CHECKING = True+    try:+        spec.loader.exec_module(module)+    finally:+        typing.TYPE_CHECKING = False++    base_sig = inspect.signature(BaseModel.model_dump)+    root_sig = inspect.signature(module.RootModel.model_dump)++    # The return annotation intentionally differs (`Any` instead of `dict[str, Any]`),+    # but the parameters must match exactly:+    assert list(root_sig.parameters.values()) == list(base_sig.parameters.values())++    assert module.RootModel.model_dump.__doc__ is not None+    assert BaseModel.model_dump.__doc__ is not None+    assert inspect.cleandoc(module.RootModel.model_dump.__doc__) == inspect.cleandoc(BaseModel.model_dump.__doc__) 

What the agent reported

I fixed the RootModel.model_dump() signature so type checkers accept the three calls from the report. I couldn't run Mypy, Pyright or Pyrefly: none are installed and there's no network access to install them. The evidence is a new pytest test that compares the two signatures. It failed before the fix and passes after.

What was wrong: RootModel declares its own model_dump() signature (only visible to type checkers) so it can return Any. That copy had fallen behind BaseModel.model_dump() in pydantic/main.py:

  • context only accepted a dict[str, Any] | None, not Any | None.
  • fallback was missing.
  • polymorphic_serialization was missing.

The calls already worked at runtime; only type checking rejected them.

What I changed:

  • Fix, in pydantic/root_model.py: context is now Any | None. I added fallback: Callable[[Any], Any] | None = None between warnings and serialize_as_any, and polymorphic_serialization: bool | None = None last. Callable comes from collections.abc, which Ruff requires. The return type stays -> Any, and runtime behaviour is unchanged.
  • Not changed: include/exclude stay annotated Any, where the base method uses IncEx | None. The report asks for identical annotations, but narrowing these would make type checkers reject calls they accept today, and the report didn't raise them. They are the only remaining difference besides the return type.
  • Tests, in tests/typechecking/root_model.py: the report's three example calls. These are only checked by the type-checker suites, so they haven't been run as type checks here.
  • Tests, in tests/test_root_model.py:
  • test_root_model_model_dump_signature_matches_base_model reads both source files and checks that the two model_dump signatures have the same parameter names, order, annotations and defaults (ignoring the return type and the include/exclude annotations). It will also catch any future drift.
  • test_root_model_model_dump_accepts_base_model_arguments runs the three example calls and checks their results: 'prefix:value', 'fallback' and [{'x': 1, 'y': 2}].

Test evidence:

  • Before the fix: the signature test failed on the context annotation ('dict[str, Any] | None' != 'Any | None'), and the other list had 2 extra parameters.
  • After the fix: ./bt-test tests/test_root_model.py tests/test_serialize.py gives 168 passed, 1 skipped.
  • Lint: ruff check, ruff format --check and git diff --check are clean.
  • Review: a read-only review found nothing blocking and no unrelated edits.

Requirements:

RequirementStatus
context accepts Any \| NoneDone; covered by the signature test, the runtime context='prefix' call and the type-check case
Add fallbackDone; same coverage
Add polymorphic_serializationDone; same coverage
Same parameters, defaults and order as BaseModel, keeping the RootModel return typeDone; covered by the signature test. The one exception is include/exclude, explained above
Add regression cases to tests/typechecking/root_model.pyAdded, but not run through a type checker
No runtime behaviour changeOnly the type-checking-only declaration and an import changed, and the existing root-model and serialization tests pass
Mypy, Pyright and Pyrefly accept the callsNot verified here; please run make test-typechecking-mypy, make test-typechecking-pyright and make test-typechecking-pyrefly where those tools are installed

All changes are uncommitted in the working tree, with no scratch files.