Backtestspydanticrun-20261013-104308#11025

Issue #11025 Merged fix PR #13442 Run 13 Oct 2026 · run-20261013-104308 pydantic/pydantic

Mypy internal error when subclassing a generic model with a recursive type variable

Better

Our patch was judged better than the merged fix.

In this judgment, Patch B = our agent, Patch A = the merged fix.

The two code fixes are functionally the same. Each imports `has_placeholder` from `mypy.semanal_shared`. When any collected field type still contains a placeholder, each calls `self._api.defer()` (unless on the final iteration) and returns False. This stops the plugin from serializing an unresolved PlaceholderType into metadata, which is the root cause of the AssertionError. Patch A puts the check in the existing `field.type is None` condition; Patch B adds a separate branch. That is a cosmetic difference, and both comments explain the reason clearly. On correctness and scope they are tied.

Tests are where they differ. Patch A appends a reproduction to the existing `generics.py` module. It only checks that mypy no longer crashes and that `child.children` is `list[Child]`. It also uses a string bound (`bound='Element'`), which is slightly different from the issue's `bound=Element`, and has an odd placeholder docstring (`"""<link>"""`). Patch B adds a dedicated `recursive_generic_model.py` module, registers it in `test_mypy.py` under the strict plugin config, and commits the expected output file. Its scenario is broader: the exact pattern from the issue, a second field (`Optional[ElementT]`), a further subclass (`GrandChild`) inheriting the resolved fields, and negative cases. Those negative cases check that the synthesized `__init__` really carries the resolved `Child` types, by expecting `list-item` and `arg-type` errors when `Other` is passed. That confirms the deferred pass produces correct signatures, not just the absence of a crash. Patch B's test coverage is clearly more thorough and more meaningful, so B wins.

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

13m 17s

Wall-clock time in the container

Full test suite

No new failures

0 passed · 54 skipped · 54 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

91vs 27 merged

Changed lines, ours vs merged

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

When using mypy with the pydantic.mypy plugin and a pydantic model that:

  • inherits from a generic model with a TypeVar bound to a BaseModel subclass,
  • has a self-referential type hint (e.g., Child referencing itself through Generic[_T]).

mypy crashes with the following output:

/home/reznak/Documents/Projects/svglab/svglab/bug.py:17: error: INTERNAL ERROR -- Please try using mypy master on GitHub:
https://mypy.readthedocs.io/en/stable/common_issues.html#using-a-development-mypy-build
Please report a bug at https://github.com/python/mypy/issues
version: 1.13.0
Traceback (most recent call last):
  File "mypy/semanal.py", line 7113, in accept
  File "mypy/nodes.py", line 1183, in accept
  File "mypy/semanal.py", line 1705, in visit_class_def
  File "mypy/semanal.py", line 1898, in analyze_class
  File "mypy/semanal.py", line 1945, in analyze_class_body_common
  File "mypy/semanal.py", line 2030, in apply_class_plugin_hooks
  File "/home/reznak/.cache/pypoetry/virtualenvs/svglab-Gw7jsKfD-py3.12/lib/python3.12/site-packages/pydantic/mypy.py", line 159, in _pydantic_model_class_maker_callback
    transformer.transform()
  File "/home/reznak/.cache/pypoetry/virtualenvs/svglab-Gw7jsKfD-py3.12/lib/python3.12/site-packages/pydantic/mypy.py", line 462, in transform
    'fields': {field.name: field.serialize() for field in fields},
                           ^^^^^^^^^^^^^^^^^
  File "/home/reznak/.cache/pypoetry/virtualenvs/svglab-Gw7jsKfD-py3.12/lib/python3.12/site-packages/pydantic/mypy.py", line 360, in serialize
    'type': self.type.serialize(),
            ^^^^^^^^^^^^^^^^^^^^^
  File "mypy/types.py", line 1498, in serialize
  File "mypy/types.py", line 3160, in serialize
AssertionError: Internal error: unresolved placeholder type svglab.bug.Child
/home/reznak/Documents/Projects/svglab/svglab/bug.py:17: : note: use --pdb to drop into pdb

The validation seems to work correctly at run-time. Removing BaseModel from the hierarchy fixes the crash, as does disabling the pydantic.mypy plugin or instantiating the type variable with any other (hypothetical) subclass of Element other than Child.

Example Code

from typing import Generic, TypeVar

from pydantic import BaseModel


class Element(BaseModel):
    pass


_T = TypeVar("_T", bound=Element)


class ElementWithChildren(Element, Generic[_T]):
    children: list[_T] = []


class Child(ElementWithChildren["Child"]):
    pass


Child()

Python, Pydantic & OS Version

pydantic version: 2.10.2
pydantic-core version: 2.27.1
pydantic-core build: profile=release pgo=false
install path: /home/reznak/.cache/pypoetry/virtualenvs/svglab-Gw7jsKfD-py3.12/lib/python3.12/site-packages/pydantic
python version: 3.12.7 (main, Oct  3 2024, 14:05:50) [GCC 13.2.0]
platform: Linux-6.6.63_1-x86_64-with-glibc2.39
related packages: pydantic-extra-types-2.10.0 mypy-1.13.0 typing_extensions-4.12.2
commit: unknown

The two patches

Our patch+91 −0
pydantic/mypy.pyindex 40aee062..6517de95 100644@@ -58,6 +58,7 @@ from mypy.plugins.common import (     deserialize_and_fixup_type, ) from mypy.semanal import set_callable_name+from mypy.semanal_shared import has_placeholder from mypy.server.trigger import make_wildcard_trigger from mypy.state import state from mypy.type_visitor import TypeTranslator@@ -534,6 +535,13 @@ class PydanticModelTransformer:         for field in fields:             if field.type is None:                 return False+            if has_placeholder(field.type):+                # The field type references a class that is not fully defined yet, e.g. a model+                # subclassing a generic model parametrized with itself (`class Child(Parent['Child'])`).+                # Placeholder types can't be serialized into the metadata, so we need another pass.+                if not self._api.final_iteration:+                    self._api.defer()+                return False          is_settings = info.has_base(BASESETTINGS_FULLNAME)         self.add_initializer(fields, config, is_settings, is_a_root_model)tests/mypy/modules/recursive_generic_model.pynew file mode 100644index 00000000..7e39b6b3@@ -0,0 +1,40 @@+from typing import Generic, Optional, TypeVar++from typing_extensions import assert_type++from pydantic import BaseModel+++class Element(BaseModel):+    pass+++ElementT = TypeVar('ElementT', bound=Element)+++class ElementWithChildren(Element, Generic[ElementT]):+    children: list[ElementT] = []+    parent: Optional[ElementT] = None+++class Child(ElementWithChildren['Child']):+    pass+++class GrandChild(Child):+    pass+++class Other(Element):+    pass+++child = Child(children=[Child(), GrandChild()], parent=Child())+assert_type(child.children, list[Child])+assert_type(child.parent, Optional[Child])++grand_child = GrandChild(children=[Child()])+assert_type(grand_child.children, list[Child])++Child(children=[Other()])+GrandChild(parent=Other())tests/mypy/outputs/mypy-plugin-strict_ini/recursive_generic_model.pynew file mode 100644index 00000000..7df64fc8@@ -0,0 +1,42 @@+from typing import Generic, Optional, TypeVar++from typing_extensions import assert_type++from pydantic import BaseModel+++class Element(BaseModel):+    pass+++ElementT = TypeVar('ElementT', bound=Element)+++class ElementWithChildren(Element, Generic[ElementT]):+    children: list[ElementT] = []+    parent: Optional[ElementT] = None+++class Child(ElementWithChildren['Child']):+    pass+++class GrandChild(Child):+    pass+++class Other(Element):+    pass+++child = Child(children=[Child(), GrandChild()], parent=Child())+assert_type(child.children, list[Child])+assert_type(child.parent, Optional[Child])++grand_child = GrandChild(children=[Child()])+assert_type(grand_child.children, list[Child])++Child(children=[Other()])+# MYPY: error: List item 0 has incompatible type "Other"; expected "Child"  [list-item]+GrandChild(parent=Other())+# MYPY: error: Argument "parent" to "GrandChild" has incompatible type "Other"; expected "Child | None"  [arg-type]tests/mypy/test_mypy.pyindex c66f1964..6bb8ccb0 100644@@ -106,6 +106,7 @@ cases: list[ParameterSet | tuple[str, str]] = [         ('mypy-plugin.ini', 'frozen_field.py'),         ('mypy-plugin.ini', 'plugin_optional_inheritance.py'),         ('mypy-plugin.ini', 'generics.py'),+        ('mypy-plugin-strict.ini', 'recursive_generic_model.py'),         ('mypy-plugin.ini', 'root_models.py'),         ('mypy-plugin.ini', 'plugin_strict_fields.py'),         ('mypy-plugin.ini', 'final_with_default.py'), 
Merged fix · PR #13442+26 −1
pydantic/mypy.pyindex 40aee0627..475aa3e55 100644@@ -58,6 +58,7 @@ from mypy.plugins.common import (     deserialize_and_fixup_type, ) from mypy.semanal import set_callable_name+from mypy.semanal_shared import has_placeholder from mypy.server.trigger import make_wildcard_trigger from mypy.state import state from mypy.type_visitor import TypeTranslator@@ -532,7 +533,12 @@ class PydanticModelTransformer:             # Some definitions are not ready. We need another pass.             return False         for field in fields:-            if field.type is None:+            if field.type is None or has_placeholder(field.type):+                # The field type may contain placeholders, e.g. when inheriting from a generic+                # model parametrized with a forward reference to the class being defined.+                # Request another pass so that they can be resolved:+                if not self._api.final_iteration:+                    self._api.defer()                 return False          is_settings = info.has_base(BASESETTINGS_FULLNAME)tests/mypy/modules/generics.pyindex ecf5dea2c..aec77397d 100644@@ -53,3 +53,22 @@ class DomainType(HistoryField[int]):  thing = DomainType(value=None) assert_type(thing.value, Optional[int])+++TElement = TypeVar('TElement', bound='Element')+++class Element(BaseModel):+    pass+++class ElementWithChildren(Element, Generic[TElement]):+    children: list[TElement] = []+++class Child(ElementWithChildren['Child']):+    """https://github.com/pydantic/pydantic/issues/11025"""+++child = Child(children=[Child()])+assert_type(child.children, list[Child])