Backtestspydanticrun-20261022-024030#11025

Issue #11025 Merged fix PR #13442 Run 22 Oct 2026 · run-20261022-024030 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 production change is functionally identical in both patches: import `has_placeholder`, and in `transform()` return False (deferring unless on the final iteration) when any collected field type still contains a placeholder. Both also guard against infinite deferral with `final_iteration`. Patch B's split of the `None` check and placeholder check is marginally clearer but not materially different. The independent tests confirm both fix the crash and preserve correct field typing.

The difference is in tests. Patch B adds a dedicated module `generics_recursive.py`, registers it in `test_mypy.py`, and supplies the corresponding expected-output file under `outputs/mypy-plugin_ini/`, which is how pydantic's mypy test harness works. It covers the exact issue scenario, a forward reference to a later-defined subclass, and negative cases that verify mypy still reports real list-item type errors rather than silently accepting anything. Patch A only appends to the existing `generics.py` module without updating its corresponding expected-output file; since the harness compares module source against the stored output, that existing case would likely fail or be out of sync. Patch A's test also includes a stray `"""<link>"""` docstring that is noise, and it lacks any negative assertion. B's tests are complete, correctly wired, and more rigorous, so B is the better patch.

Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.

Solve

5m 50s

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

95vs 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+95 −0
pydantic/mypy.pyindex 40aee062..b3c8e41d 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 analyzed yet (e.g. a recursive+                # generic model such as `class Child(Parent['Child'])`). Placeholder types can't be+                # serialized nor used in signatures, 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/generics_recursive.pynew file mode 100644index 00000000..0e8682f1@@ -0,0 +1,42 @@+from typing import Generic, TypeVar++from typing_extensions import assert_type++from pydantic import BaseModel+++class Element(BaseModel):+    pass+++T = TypeVar('T', bound=Element)+++class ElementWithChildren(Element, Generic[T]):+    children: list[T] = []+++# Parametrized with itself: the type is not fully analyzed when the plugin first processes the class.+class Child(ElementWithChildren['Child']):+    pass+++child = Child()+assert_type(child.children, list[Child])+Child.model_construct(children=[Child()])+Child.model_construct(children=[Element()])+++# Parametrized with a class defined later in the module.+class Branch(ElementWithChildren['Leaf']):+    name: str+++class Leaf(Element):+    value: int+++branch = Branch(name='b', children=[Leaf(value=1)])+assert_type(branch.children, list[Leaf])+Branch.model_construct(name='b', children=[Leaf(value=1)])+Branch.model_construct(name='b', children=[Branch(name='c')])tests/mypy/outputs/mypy-plugin_ini/generics_recursive.pynew file mode 100644index 00000000..4ef97df8@@ -0,0 +1,44 @@+from typing import Generic, TypeVar++from typing_extensions import assert_type++from pydantic import BaseModel+++class Element(BaseModel):+    pass+++T = TypeVar('T', bound=Element)+++class ElementWithChildren(Element, Generic[T]):+    children: list[T] = []+++# Parametrized with itself: the type is not fully analyzed when the plugin first processes the class.+class Child(ElementWithChildren['Child']):+    pass+++child = Child()+assert_type(child.children, list[Child])+Child.model_construct(children=[Child()])+Child.model_construct(children=[Element()])+# MYPY: error: List item 0 has incompatible type "Element"; expected "Child"  [list-item]+++# Parametrized with a class defined later in the module.+class Branch(ElementWithChildren['Leaf']):+    name: str+++class Leaf(Element):+    value: int+++branch = Branch(name='b', children=[Leaf(value=1)])+assert_type(branch.children, list[Leaf])+Branch.model_construct(name='b', children=[Leaf(value=1)])+Branch.model_construct(name='b', children=[Branch(name='c')])+# MYPY: error: List item 0 has incompatible type "Branch"; expected "Leaf"  [list-item]tests/mypy/test_mypy.pyindex c66f1964..225df427 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.ini', 'generics_recursive.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])