Backtestspydanticrun-20261022-024030#13645

Issue #13645 Merged fix PR #13648 Run 22 Oct 2026 · run-20261022-024030 pydantic/pydantic

TypeError: unhashable type: 'list' in match_type for PEP 695 aliases with a ParamSpec (regression in 2.14.0b1)

Better

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 crash at the exact site the issue identifies, and all six independent tests pass on both. They differ in how they get there and in test quality.

Patch B wraps the `DEPRECATED_ALIASES.get(obj)` lookup in `try/except TypeError`, exactly one of the two fixes the issue proposes. It is self-contained, needs no dependency change, and its comment explains the unhashable case. Its tests target the reported scenario directly: a `TypeAliasType` with a `ParamSpec` parameterized as `[[], int]` (asserting the alias really is unhashable), the same alias inside an optional model field and a `TypeAdapter`, a `Callable[P, R]` alias that validates callables and rejects non-callables, and a `create_module` test using the literal PEP 695 `type Alias[**P, R] = Any` statement from the report. These would fail on base with the reported TypeError and pass after.

Patch A switches to an identity-based lookup, `DEPRECATED_ALIASES_IDS.get(id(obj))`, which depends on a new attribute from typing-inspection and so bumps the minimum dependency from 0.4.2 to 0.4.4. Functionally this is sound (the deprecated aliases are module-level singletons, so id lookup is stable), but it couples a one-line bug fix to a hard dependency floor raise that forces downstream upgrades, and I cannot verify from the diff that the attribute exists in that release. Its test (`test_unhasbable_generic_alias`, misspelled) exercises `list[Annotated[int, Meta()]]` with an unhashable metadata object. That does reach the broken lookup on base, so it is a valid regression test, but it does not cover the ParamSpec/PEP 695 alias case the issue is actually about, and it is a single assertion.

On correctness they are equivalent; on tests B is clearly stronger and closer to the issue; on scope B avoids the dependency bump; on craft B's comment and non-typo test names are better. B is the better fix.

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

6m 40s

Wall-clock time in the container

Full test suite

No new failures

952 passed · 118 skipped · 1,070 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

72vs 23 merged

Changed lines, ours vs merged

Reported downstream in Giskard-AI/giskard#2719 (breaks import giskard.checks); repro and analysis below. The report was drafted jointly with @davidberenstein1957, who invited it to be filed upstream as-is.

Description

_generate_schema.match_type added an unguarded dict lookup in 2.14 that assumes the annotation object is hashable. It is not, for a PEP 695 type alias with a ParamSpec parameterized by an empty list. Schema building for any model containing such an annotation crashes.

This is a regression: the same code builds fine on 2.13.4.

Example Code

from typing import Any
from pydantic import BaseModel

type Alias[**P, R] = Any

class M(BaseModel):
    f: Alias[[], int] | None = None

Raises immediately at class-definition time:

File ".../pydantic/_internal/_generate_schema.py", line 1127, in match_type
    if origin is not None and (aliased_obj := typing_objects.DEPRECATED_ALIASES.get(obj)):
TypeError: unhashable type: 'list'

Mechanism

Alias[[], int] is a types.GenericAlias whose __args__ is ([], int). Hashing the alias hashes that tuple, which contains a list — so it is unhashable. The line at _generate_schema.py:1127

if origin is not None and (aliased_obj := typing_objects.DEPRECATED_ALIASES.get(obj)):

calls .get(obj) without checking that obj can be hashed. dict.get propagates the TypeError rather than treating an unhashable key as absent.

Suggested fix

Guard the lookup, e.g.

if origin is not None and isinstance(obj, Hashable) and (aliased_obj := typing_objects.DEPRECATED_ALIASES.get(obj)):

or wrap it in try/except TypeError. An unhashable object cannot be a DEPRECATED_ALIASES key by construction, so skipping the lookup is always correct.

Python, Pydantic & OS Version

  • pydantic 2.14.0b1 (fails) / 2.13.4 (works)
  • Python 3.12.13
  • Reproduced on Linux and macOS

Real-world impact

Hit in giskard-oss, where type GeneratorType[**P, R, S] = ... parameterized as GeneratorType[[], InputType, None] makes import giskard.checks fail outright under 2.14.0b1. Instrumenting match_type confirms the offending object:

OFFENDING obj  = GeneratorType[[], InputType, None]
OFFENDING type = <class 'types.GenericAlias'>
OFFENDING args = ([], InputType, None)

There is no workaround on the library side short of pinning pydantic<2.14 (done in Giskard-AI/giskard#2752), which is what downstream has had to do.

The two patches

Our patch+65 −7
pydantic/_internal/_generate_schema.pyindex 53971d20..dddfdc29 100644@@ -1124,10 +1124,17 @@ class GenerateSchema:             # early for model-like fields, which handles it already.             return core_schema.any_schema() -        if origin is not None and (aliased_obj := typing_objects.DEPRECATED_ALIASES.get(obj)):-            # See https://typing-inspection.pydantic.dev/dev/usage/#inspecting-the-type-expression:-            obj = aliased_obj-            origin = None+        if origin is not None:+            try:+                aliased_obj = typing_objects.DEPRECATED_ALIASES.get(obj)+            except TypeError:+                # `obj` can be unhashable (e.g. a PEP 695 alias with a `ParamSpec`, parameterized with a list),+                # in which case it can't be a deprecated alias.+                aliased_obj = None+            if aliased_obj is not None:+                # See https://typing-inspection.pydantic.dev/dev/usage/#inspecting-the-type-expression:+                obj = aliased_obj+                origin = None          if origin is None:             # Thanks to the checks before this point, no origin means `obj` is atests/test_type_alias_type.pyindex 13b56cbc..8cdf5dcf 100644@@ -1,11 +1,12 @@ import datetime-from collections.abc import Sequence+import sys+from collections.abc import Callable, Sequence from dataclasses import dataclass-from typing import Annotated, Generic, Literal, TypeVar, Union+from typing import Annotated, Any, Generic, Literal, TypeVar, Union  import pytest from annotated_types import MaxLen-from typing_extensions import TypeAliasType+from typing_extensions import ParamSpec, TypeAliasType  from pydantic import BaseModel, PlainSerializer, PydanticUserError, TypeAdapter, ValidationError, WithJsonSchema @@ -488,3 +489,53 @@ def test_type_alias_type_with_metadata() -> None:      ta = TypeAdapter(B)     assert ta.json_schema() == {'type': 'int', 'extra': 1}+++@pytest.mark.skipif(sys.version_info < (3, 12), reason='Requires `typing.TypeAliasType` ParamSpec support.')+def test_type_alias_type_param_spec_parameterized_with_list() -> None:+    """https://github.com/pydantic/pydantic/issues/13645: `Alias[[], int]` is unhashable, as its args contain a list."""++    P = ParamSpec('P')+    R = TypeVar('R')+    AnyAlias = TypeAliasType('AnyAlias', Any, type_params=(P, R))++    with pytest.raises(TypeError):+        hash(AnyAlias[[], int])++    class Model(BaseModel):+        f: AnyAlias[[], int] | None = None++    assert Model().f is None+    assert Model(f='anything').f == 'anything'+    assert TypeAdapter(AnyAlias[[], int]).validate_python(1) == 1++    CallableAlias = TypeAliasType('CallableAlias', Callable[P, R], type_params=(P, R))++    def func() -> int:+        return 1++    ta = TypeAdapter(CallableAlias[[], int])+    assert ta.validate_python(func) is func+    with pytest.raises(ValidationError):+        ta.validate_python(1)+++@pytest.mark.skipif(sys.version_info < (3, 12), reason='Requires PEP 695 syntax')+def test_pep695_type_alias_param_spec_parameterized_with_list(create_module) -> None:+    """https://github.com/pydantic/pydantic/issues/13645, using the PEP 695 `type` statement."""++    module = create_module(+        """+from typing import Any++from pydantic import BaseModel++type Alias[**P, R] = Any++class Model(BaseModel):+    f: Alias[[], int] | None = None+        """+    )++    assert module.Model().f is None+    assert module.Model(f='anything').f == 'anything' 
Merged fix · PR #13648+17 −6
pydantic/_internal/_generate_schema.pyindex 53971d205..815766b37 100644@@ -1124,7 +1124,7 @@ class GenerateSchema:             # early for model-like fields, which handles it already.             return core_schema.any_schema() -        if origin is not None and (aliased_obj := typing_objects.DEPRECATED_ALIASES.get(obj)):+        if origin is not None and (aliased_obj := typing_objects.DEPRECATED_ALIASES_IDS.get(id(obj))):             # See https://typing-inspection.pydantic.dev/dev/usage/#inspecting-the-type-expression:             obj = aliased_obj             origin = Nonepyproject.tomlindex dcd9d1464..27f62269f 100644@@ -48,7 +48,7 @@ dependencies = [     'annotated-types>=0.6.0',     # Keep this in sync with the version in the `check_pydantic_core_version()` function:     'pydantic-core==2.48.0',-    'typing-inspection>=0.4.2',+    'typing-inspection>=0.4.4', ] dynamic = ['version', 'readme'] tests/test_edge_cases.pyindex 3649fb3d7..699a49da0 100644@@ -3198,3 +3198,14 @@ def test_interconnected_models_build_in_linear_time() -> None:     instance = last.model_validate({'value': 1, 'ref2': {'value': 2, 'ref2': {'value': 3}}})     assert instance.ref2.ref2.value == 3     assert instance.model_dump(exclude_none=True) == {'value': 1, 'ref2': {'value': 2, 'ref2': {'value': 3}}}+++def test_unhasbable_generic_alias() -> None:+    """https://github.com/pydantic/pydantic/issues/13645"""++    class Meta:+        __hash__ = None++    ta = TypeAdapter(list[Annotated[int, Meta()]])++    assert ta.validate_python(['1']) == [1]uv.lockindex be6b53763..ef8660538 100644@@ -2551,7 +2551,7 @@ requires-dist = [     { name = "email-validator", marker = "extra == 'email'", specifier = ">=2.0.0" },     { name = "pydantic-core", editable = "pydantic-core" },     { name = "typing-extensions", specifier = ">=4.15.0" },-    { name = "typing-inspection", specifier = ">=0.4.2" },+    { name = "typing-inspection", specifier = ">=0.4.4" },     { name = "tzdata", marker = "sys_platform == 'win32' and extra == 'timezone'" }, ] provides-extras = ["email", "timezone"]@@ -3949,14 +3949,14 @@ wheels = [  [[package]] name = "typing-inspection"-version = "0.4.3"+version = "0.4.4" source = { registry = "https://pypi.org/simple" } dependencies = [     { name = "typing-extensions" }, ]-sdist = { url = "https://files.pythonhosted.org/packages/6d/bc/4eae18cd40c65798a16267572ba346c11f599d44b01603dbd843342042bc/typing_inspection-0.4.3.tar.gz", hash = "sha256:c5f9ec1530b5c1e2c9bc34a84d9a3466ed1b2f3f2fa9f901368d9c5596210e4d", size = 76711, upload-time = "2026-08-10T09:39:18.063Z" }+sdist = { url = "https://files.pythonhosted.org/packages/a3/26/b09b8010994eccc3c09092e6b34058f36a460eea2d4c3e8b910c695975a0/typing_inspection-0.4.4.tar.gz", hash = "sha256:547274fa6b0a561ccf549cc9524b999a578e737d015d8709d021f9d0d13bea47", size = 76928, upload-time = "2026-08-12T12:37:25.997Z" } wheels = [-    { url = "https://files.pythonhosted.org/packages/42/f7/7a3935abdebd5cf18705a5f0335dd6a3a18bef3baa7cb9edc3b6b9922cc8/typing_inspection-0.4.3-py3-none-any.whl", hash = "sha256:5f42b23858a91e0b4ef521f5418f03a0da3c9216fd2995ef5e73463100e676cd", size = 14693, upload-time = "2026-08-10T09:39:16.693Z" },+    { url = "https://files.pythonhosted.org/packages/67/81/4add07e5172b7ac40d8ed5ff580409a7801a4fe26d529bdd915401dabfbe/typing_inspection-0.4.4-py3-none-any.whl", hash = "sha256:65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147", size = 14750, upload-time = "2026-08-12T12:37:24.648Z" }, ]  [[package]]