Backtestspydanticrun-20261027-165153#14064
typing.Self in a parametrized generic dataclass now fails schema generation
Our patch was judged better than the merged fix.
In this judgment, Patch B = our agent, Patch A = the merged fix.
Both patches apply the same root-cause fix: after `_resolve_self_type` replaces `Self` with the resolved (possibly parametrized) class, they recompute `origin` from the new `obj` instead of using the stale origin computed on `Self`. The independent tests confirm both make all failing cases pass with no regressions, so correctness is equal. The differences are in craft and tests. Patch A keeps the original `origin = origin if ... else get_origin(obj)` line after unconditionally reassigning `origin`, leaving a redundant no-op for the Self branch; Patch B restructures into an if/elif so each path computes origin exactly once, which reads cleaner. On tests, A nicely reuses the `dataclass_decorators` helper and adds a NamedTuple case, while B adds an Annotated-wrapped `Self` case and, importantly, negative assertions (`ValidationError` on `'not an int'`) that verify the type argument actually propagates into the nested Self schema rather than falling back to an unparametrized/Any schema. Both sets would fail on base and pass after. The margin is small, but B's cleaner control flow and stronger behavioural assertions give it the edge.
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
3m 43s
Wall-clock time in the container
Full test suite
No new failures
542 passed · 32 skipped · 574 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
75vs 44 merged
Changed lines, ours vs merged
The issue
View on GitHubInitial Checks
- I confirm that I'm using Pydantic V2
Description
It looks like in 2.14.x a generic dataclass with a Self-annotated field cannot be used with type arguments. The example below shows a minimal example. This did work in 2.13.x, and I walked it back as far as 2.11.7, all of which seem to handle this fine. It's kinda of a weird use case, but I have code where we are building pydantic models that store graph-like information (hence my example) and the bump to 2.14.x broke everything.
I think the root cause originates in #13614. generate_schema() now calls get_origin() before _generate_schema_inner(), which is where Self gets replaced by the type being built via _resolve_self_type. That causes the origin to now be stale and not match the new obj which could be a generic, so its origin of None is wrong.
Pretty sure it's a one line fix to regenerate the origin after _resolve_self_type is called. Seemed to work for me
Example Code
from dataclasses import dataclass
from typing import Generic, Self, TypeVar
from dataclasses import dataclass
from typing import Generic, Self, TypeVar
import pydantic
from pydantic import TypeAdapter
T = TypeVar('T')
@dataclass
class StdNode(Generic[T]):
value: T
parent: Self | None = None
@pydantic.dataclasses.dataclass
class PydNode(Generic[T]):
value: T
parent: Self | None = None
print('pydantic', pydantic.VERSION)
for tp in (StdNode, PydNode, StdNode[int], PydNode[int]):
try:
ta = TypeAdapter(tp)
print(f' OK {tp!r:28} ->', ta.validate_python({'value': 1, 'parent': {'value': 0}}))
except pydantic.errors.PydanticSchemaGenerationError as e:
print(f' FAIL {tp!r:28} -> PydanticSchemaGenerationError: {str(e).splitlines()[0][:70]}')
Python, Pydantic & OS Version
pydantic version: 2.14.1
pydantic-core version: 2.50.1
pydantic-core build: profile=release pgo=false
python version: 3.13.12 (main, Feb 3 2026, 17:53:27) [Clang 17.0.0 (clang-1700.6.3.2)]
platform: macOS-26.7.1-arm64-arm-64bit-Mach-O
related packages: typing_extensions-4.16.0
commit: unknownThe two patches
pydantic/_internal/_generate_schema.pyindex 866db4e9..1fea5435 100644@@ -1098,8 +1098,11 @@ class GenerateSchema: def _generate_schema_inner(self, obj: Any, origin: Any | None = PydanticUndefined) -> core_schema.CoreSchema: if typing_objects.is_self(obj): obj = self._resolve_self_type(obj)-- origin = origin if origin is not PydanticUndefined else get_origin(obj)+ # The origin (if provided) was computed on `Self`, and is stale now that `obj` was resolved+ # (it could e.g. be a parametrized generic class):+ origin = get_origin(obj)+ elif origin is PydanticUndefined:+ origin = get_origin(obj) if is_union_origin(origin): return self._union_schema(obj)tests/test_types_self.pyindex d15367ed..f07c7a69 100644@@ -8,6 +8,7 @@ import typing_extensions from typing_extensions import NamedTuple, TypedDict, TypeForm from pydantic import BaseModel, Field, PydanticUserError, TypeAdapter, ValidationError, computed_field, validate_call+from pydantic.dataclasses import dataclass as pydantic_dataclass self_types: list[TypeForm] = [] ids: list[str] = []@@ -173,6 +174,73 @@ def test_self_type_in_dataclass(Self): m.item.ref.x = 3 +def test_self_type_in_parametrized_generic_stdlib_dataclass(Self):+ T = typing.TypeVar('T')++ @dataclasses.dataclass+ class Node(typing.Generic[T]):+ value: T+ parent: Self | None = None++ ta = TypeAdapter(Node[int])+ node = ta.validate_python({'value': '1', 'parent': {'value': '0'}})+ assert node == Node(value=1, parent=Node(value=0, parent=None))++ with pytest.raises(ValidationError):+ ta.validate_python({'value': 1, 'parent': {'value': 'not an int'}})+++def test_self_type_in_parametrized_generic_pydantic_dataclass(Self):+ T = typing.TypeVar('T')++ @pydantic_dataclass+ class Node(typing.Generic[T]):+ value: T+ parent: Self | None = None++ ta = TypeAdapter(Node[int])+ node = ta.validate_python({'value': '1', 'parent': {'value': '0'}})+ assert node.value == 1+ assert node.parent.value == 0+ assert node.parent.parent is None++ with pytest.raises(ValidationError):+ ta.validate_python({'value': 1, 'parent': {'value': 'not an int'}})+++def test_self_type_in_parametrized_generic_typed_dict(Self):+ T = typing.TypeVar('T')++ class Node(TypedDict, typing.Generic[T]):+ value: T+ parent: Self | None++ ta = TypeAdapter(Node[int])+ assert ta.validate_python({'value': '1', 'parent': {'value': '0', 'parent': None}}) == {+ 'value': 1,+ 'parent': {'value': 0, 'parent': None},+ }++ with pytest.raises(ValidationError):+ ta.validate_python({'value': 1, 'parent': {'value': 'not an int', 'parent': None}})+++def test_annotated_self_type_in_parametrized_generic_dataclass(Self):+ T = typing.TypeVar('T')++ @dataclasses.dataclass+ class Node(typing.Generic[T]):+ value: T+ parent: typing.Annotated[Self, Field(description='parent')] | None = None++ ta = TypeAdapter(Node[int])+ node = ta.validate_python({'value': '1', 'parent': {'value': '0'}})+ assert node == Node(value=1, parent=Node(value=0, parent=None))++ with pytest.raises(ValidationError):+ ta.validate_python({'value': 1, 'parent': {'value': 'not an int'}})++ def test_invalid_validate_call(Self): with pytest.raises(PydanticUserError, match='`typing.Self` is invalid in this context'):
pydantic/_internal/_generate_schema.pyindex 866db4e9a..037774ba0 100644@@ -1098,6 +1098,9 @@ class GenerateSchema: def _generate_schema_inner(self, obj: Any, origin: Any | None = PydanticUndefined) -> core_schema.CoreSchema: if typing_objects.is_self(obj): obj = self._resolve_self_type(obj)+ # The resolved type can be a parametrized generic (e.g. `GenericDataclass[int]`),+ # so the origin provided by the caller (computed on `Self`) is stale:+ origin = get_origin(obj) origin = origin if origin is not PydanticUndefined else get_origin(obj) tests/test_types_self.pyindex d15367ed8..a8e6e6520 100644@@ -2,6 +2,7 @@ import dataclasses import re import sys import typing+from typing import Generic, TypeVar import pytest import typing_extensions@@ -9,6 +10,8 @@ from typing_extensions import NamedTuple, TypedDict, TypeForm from pydantic import BaseModel, Field, PydanticUserError, TypeAdapter, ValidationError, computed_field, validate_call +from .utils import dataclass_decorators+ self_types: list[TypeForm] = [] ids: list[str] = [] if sys.version_info >= (3, 11):@@ -173,6 +176,44 @@ def test_self_type_in_dataclass(Self): m.item.ref.x = 3 +@pytest.mark.parametrize('dataclass_decorator', **dataclass_decorators())+def test_self_type_in_parametrized_generic_dataclass(Self, dataclass_decorator):+ T = TypeVar('T')++ @dataclass_decorator+ class SelfRef(Generic[T]):+ x: T+ ref: Self | None = None++ ta = TypeAdapter(SelfRef[int])+ item = ta.validate_python({'x': '1', 'ref': {'x': '2'}})+ assert item.x == 1+ assert item.ref.x == 2+ assert item.ref.ref is None+++def test_self_type_in_parametrized_generic_typed_dict(Self):+ T = TypeVar('T')++ class SelfRefTypedDict(TypedDict, Generic[T]):+ x: T+ ref: Self | None++ ta = TypeAdapter(SelfRefTypedDict[int])+ assert ta.validate_python({'x': '1', 'ref': {'x': '2', 'ref': None}}) == {'x': 1, 'ref': {'x': 2, 'ref': None}}+++def test_self_type_in_parametrized_generic_named_tuple(Self):+ T = TypeVar('T')++ class SelfRefNamedTuple(NamedTuple, Generic[T]):+ x: T+ ref: Self | None = None++ ta = TypeAdapter(SelfRefNamedTuple[int])+ assert ta.validate_python(('1', ('2',))) == (1, (2, None))++ def test_invalid_validate_call(Self): with pytest.raises(PydanticUserError, match='`typing.Self` is invalid in this context'):