Backtestspydanticrun-20261013-104308#13645
TypeError: unhashable type: 'list' in match_type for PEP 695 aliases with a ParamSpec (regression in 2.14.0b1)
Our patch was judged better than the merged fix.
In this judgment, Patch B = our agent, Patch A = the merged fix.
Both patches stop the crash at `match_type`, but B is the safer, more complete, and better-tested fix. Correctness: Patch A swaps the lookup to `typing_objects.DEPRECATED_ALIASES_IDS.get(id(obj))`. Deprecated aliases such as `typing.List` are singletons, so an identity lookup is sound in principle and avoids hashing. However, the fix depends on an attribute that only exists in a newer typing-inspection, which A handles by bumping the minimum to >=0.4.4. That attribute cannot be verified from the diff. The bump also widens the change's blast radius: if the attribute or version is wrong, every `match_type` call breaks. Patch B wraps the existing `.get(obj)` in `try/except TypeError`, which is self-contained and directly implements the issue's suggestion; an unhashable object can never be a key, so skipping it is correct. B also guards the `json_encoders.get(base)` lookup in `_add_custom_serialization_from_json_encoders`. The same unhashable `Alias[[], int]` would raise there when `json_encoders` is configured, so this is a real latent crash on the issue's scenario, not unrelated churn. Tests: B's tests reproduce the reported case exactly: a `TypeAliasType` with a `ParamSpec`, parameterized with `[]` and `[int, str]`, inside a `BaseModel` with `| None`. They also exercise `TypeAdapter` and the json_encoders path. All of these would fail before the fix. A's test (`test_unhasbable_generic_alias`, which is also misspelled) uses `list[Annotated[int, Meta()]]` with unhashable metadata. That is the same mechanism but not the reported ParamSpec scenario. Scope and craft: A adds a dependency floor bump, which carries upgrade risk. B's changes are local, commented, and consistent with the surrounding code. B is more verbose, but its control flow is clear.
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
7m 1s
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
77vs 23 merged
Changed lines, ours vs merged
The issue
View on GitHubReported 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
pydantic/_internal/_generate_schema.pyindex 53971d20..73864d78 100644@@ -287,7 +287,12 @@ def _add_custom_serialization_from_json_encoders( # Decimal.__class__.__mro__ (and probably other cases) doesn't include Decimal itself # if the type is a GenericAlias (e.g. from list[int]) we need to use __class__ instead of .__mro__ for base in (tp, *getattr(tp, '__mro__', tp.__class__.__mro__)[:-1]):- encoder = json_encoders.get(base)+ try:+ encoder = json_encoders.get(base)+ except TypeError:+ # `base` can be unhashable, e.g. a PEP 695 type alias with a `ParamSpec`+ # parameterized with a list (`Alias[[], int]`):+ continue if encoder is None: continue @@ -1124,10 +1129,18 @@ 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 type alias with a `ParamSpec`+ # parameterized with a list (`Alias[[], int]`):+ pass+ else:+ 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..29b15def 100644@@ -1,13 +1,21 @@ import datetime from collections.abc import 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 pydantic import BaseModel, PlainSerializer, PydanticUserError, TypeAdapter, ValidationError, WithJsonSchema+from typing_extensions import ParamSpec, TypeAliasType++from pydantic import (+ BaseModel,+ ConfigDict,+ PlainSerializer,+ PydanticUserError,+ TypeAdapter,+ ValidationError,+ WithJsonSchema,+) T = TypeVar('T') @@ -488,3 +496,41 @@ def test_type_alias_type_with_metadata() -> None: ta = TypeAdapter(B) assert ta.json_schema() == {'type': 'int', 'extra': 1}+++def test_type_alias_with_paramspec_parameterized_with_list() -> None:+ """https://github.com/pydantic/pydantic/issues/13645.++ Parameterizing a `ParamSpec` with a list creates an unhashable generic alias.+ """+ P = ParamSpec('P')+ R = TypeVar('R')+ Alias = TypeAliasType('Alias', Any, type_params=(P, R))++ class Model(BaseModel):+ f: Alias[[], int] | None = None+ g: Alias[[int, str], int] = 1++ assert Model().f is None+ assert Model(f='anything', g=[1]).model_dump() == {'f': 'anything', 'g': [1]}++ ta = TypeAdapter(Alias[[], int])+ assert ta.validate_python({'a': 1}) == {'a': 1}+ assert ta.json_schema() == {}+++def test_type_alias_with_paramspec_parameterized_with_list_and_json_encoders() -> None:+ """https://github.com/pydantic/pydantic/issues/13645."""+ P = ParamSpec('P')+ R = TypeVar('R')+ Alias = TypeAliasType('Alias', Any, type_params=(P, R))++ class Model(BaseModel):+ model_config = ConfigDict(json_encoders={int: str})++ f: Alias[[], int] | None = None++ assert Model(f=1).model_dump() == {'f': 1}++ ta = TypeAdapter(Alias[[], int], config=ConfigDict(json_encoders={int: str}))+ assert ta.validate_python(1) == 1
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]]