Backtestspydanticrun-20261027-165153#13645

Issue #13645 Merged fix PR #13648 Run 27 Oct 2026 · run-20261027-165153 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 reported crash and pass all six independent tests. Patch B guards the `DEPRECATED_ALIASES.get(obj)` lookup with `try/except TypeError`, which is exactly one of the fixes the issue suggests, is self-contained, and carries a clear comment. Its tests reproduce the issue's scenario directly (a `TypeAliasType` with a `ParamSpec` parameterized as `Alias[[], int]`, both optional and non-optional fields, plus a `TypeAdapter`), so they would fail on base and pass after. It also fixes a second hashing site in `_path_schema` (`{str, bytes}` set membership) with a dedicated test; this is adjacent but low risk and covered. Patch A instead switches to an identity-keyed `DEPRECATED_ALIASES_IDS` table, which is a reasonable design but requires bumping the `typing-inspection` minimum to a new release, adding dependency friction and risk outside the issue's ask. Its single test uses an unrelated construction (`list[Annotated[int, Meta()]]` with `__hash__ = None`) rather than the ParamSpec alias from the issue, and the test name contains a typo. On correctness they are equivalent; on tests and scope B is stronger.

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

6m 25s

Wall-clock time in the container

Full test suite

No new failures

983 passed · 118 skipped · 1,101 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

53vs 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+46 −7
pydantic/_internal/_generate_schema.pyindex 53971d20..d3aac01a 100644@@ -586,7 +586,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 +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` is unhashable (e.g. a parametrized PEP 695 type alias with a `ParamSpec`,+                # such as `Alias[[], int]`), and thus 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..ba06f99f 100644@@ -1,11 +1,11 @@ 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 typing_extensions import ParamSpec, TypeAliasType  from pydantic import BaseModel, PlainSerializer, PydanticUserError, TypeAdapter, ValidationError, WithJsonSchema @@ -488,3 +488,24 @@ def test_type_alias_type_with_metadata() -> None:      ta = TypeAdapter(B)     assert ta.json_schema() == {'type': 'int', 'extra': 1}+++def test_type_alias_type_with_param_spec_unhashable_args() -> None:+    """Parametrizing a type alias with a `ParamSpec` using a list results in an unhashable generic alias.++    Such annotations should still be usable (the equivalent PEP 695 syntax is `type Alias[**P, R] = Any`).+    """++    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] = 1++    assert Model(f='a', g=2).model_dump() == {'f': 'a', 'g': 2}+    assert Model().model_dump() == {'f': None, 'g': 1}++    ta = TypeAdapter(Alias[[], int])+    assert ta.validate_python([1]) == [1]tests/types/test_path.pyindex 866436e5..c57c9bc7 100644@@ -5,6 +5,7 @@ from pathlib import Path from typing import Any  import pytest+from typing_extensions import ParamSpec, TypeAliasType, TypeVar  from pydantic import (     BaseModel,@@ -13,6 +14,7 @@ from pydantic import (     Field,     FilePath,     NewPath,+    PydanticUserError,     SocketPath,     TypeAdapter,     ValidationError,@@ -312,3 +314,12 @@ def test_ser_path_incorrect() -> None:     ta = TypeAdapter(Path)     with pytest.warns(UserWarning, match='serialized value may not be as expected.'):         ta.dump_python(123)+++def test_pathlike_unsupported_unhashable_type_param() -> None:+    P = ParamSpec('P')+    R = TypeVar('R')+    Alias = TypeAliasType('Alias', Any, type_params=(P, R))++    with pytest.raises(PydanticUserError, match='`os.PathLike` can only be used with `str`, `bytes` or `Any`'):+        TypeAdapter(os.PathLike[Alias[[], int]]) 
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]]