Backtestspydanticrun-20261009-110034#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 `TypeError` at the `match_type` lookup, but B is the better fix.
**Patch A**
- It swaps the hash-based lookup for `typing_objects.DEPRECATED_ALIASES_IDS.get(id(obj))` and bumps `typing-inspection` to >=0.4.4.
- The diff does not show that `DEPRECATED_ALIASES_IDS` exists, so the fix rests on an outside dependency. If that attribute is missing, every schema build fails with `AttributeError`.
- The idea itself is sound: the deprecated aliases are singletons, so looking them up by `id` avoids hashing.
- Its test uses `list[Annotated[int, Meta()]]` with unhashable metadata. That likely fails before the change, since hashing an `Annotated` alias hashes its metadata. It does not cover the reported PEP 695 / ParamSpec `Alias[[], int]` case, and it carries a typo in the name (`unhasbable`).
**Patch B**
- It wraps the `DEPRECATED_ALIASES.get(obj)` call in `try/except TypeError`, which is the issue's own suggestion. This is self-contained and correct, because an unhashable object can never be a dict key.
- It also hardens two nearby places where the same unhashable object would be hashed later in the pipeline:
- the `json_encoders.get(base)` loop;
- the `path_type not in {str, bytes}` set check, now a tuple.
- These extras are small, low-risk and on topic, since the same reported annotation would otherwise crash further along.
- Its tests rebuild the exact scenario from the issue: a `TypeAliasType` with a `ParamSpec`, parameterized as `[[], int]`. They assert the alias is unhashable, then check model creation, validation, the JSON schema, `TypeAdapter`, `json_encoders` and `os.PathLike`. All of these would fail before the change.
**Verdict**
B is more robust, needs no dependency change, and tests the reported case directly.
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
12m 26s
Wall-clock time in the container
Full test suite
No new failures
12,329 passed · 500 skipped · 12,829 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
90vs 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..c2c95089 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:+ # `tp` can be unhashable (e.g. a PEP 695 alias parameterized with a list,+ # such as `Alias[[], int]`), in which case it can't be a key of `json_encoders`.+ continue if encoder is None: continue @@ -586,7 +591,7 @@ class GenerateSchema: ) def _path_schema(self, tp: Any, path_type: Any) -> CoreSchema:- if tp is os.PathLike and (path_type not in {str, bytes} and not typing_objects.is_any(path_type)):+ if tp is os.PathLike and (path_type not in (str, bytes) and not typing_objects.is_any(path_type)): raise PydanticUserError( '`os.PathLike` can only be used with `str`, `bytes` or `Any`', code='schema-for-unknown-type' )@@ -1124,10 +1129,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 parameterized with+ # a list, such as `Alias[[], int]`), 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..d23a063b 100644@@ -1,13 +1,22 @@ import datetime+import os 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 +497,52 @@ def test_type_alias_type_with_metadata() -> None: ta = TypeAdapter(B) assert ta.json_schema() == {'type': 'int', 'extra': 1}+++P = ParamSpec('P')+R = TypeVar('R')+ParamSpecAlias = TypeAliasType('ParamSpecAlias', Any, type_params=(P, R))+++def test_type_alias_type_param_spec_list_arg_unhashable() -> None:+ """https://github.com/pydantic/pydantic/issues/13645++ Equivalent to `type ParamSpecAlias[**P, R] = Any`, parameterized with an (unhashable) list.+ """+ alias = ParamSpecAlias[[], int]+ with pytest.raises(TypeError):+ hash(alias)++ class Model(BaseModel):+ f: ParamSpecAlias[[], int] | None = None++ assert Model().f is None+ assert Model(f='anything').f == 'anything'+ assert Model.model_json_schema() == {+ '$defs': {'ParamSpecAlias_list_int_': {}},+ 'properties': {+ 'f': {'anyOf': [{'$ref': '#/$defs/ParamSpecAlias_list_int_'}, {'type': 'null'}], 'default': None}+ },+ 'title': 'Model',+ 'type': 'object',+ }++ ta = TypeAdapter(ParamSpecAlias[[], int])+ assert ta.validate_python([1, 'a']) == [1, 'a']+++def test_type_alias_type_param_spec_list_arg_with_json_encoders() -> None:+ with pytest.warns(DeprecationWarning, match='json_encoders'):++ class Model(BaseModel):+ model_config = ConfigDict(json_encoders={int: str})++ f: ParamSpecAlias[[], int]+ g: int++ assert Model(f=1, g=2).model_dump_json() == '{"f":1,"g":"2"}'+++def test_type_alias_type_param_spec_list_arg_in_path_like() -> None:+ with pytest.raises(PydanticUserError, match='`os.PathLike` can only be used with `str`, `bytes` or `Any`'):+ TypeAdapter(os.PathLike[ParamSpecAlias[[], int]])
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]]