Backtestspydanticrun-20261007-130130#13645

Issue #13645 Merged fix PR #13648 Run 7 Oct 2026 · run-20261007-130130 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 stop the `TypeError` at `match_type`, but Patch B is the more reliable and better-tested fix.

Correctness: Patch B wraps the `DEPRECATED_ALIASES.get(obj)` lookup in `try/except TypeError` and treats an unhashable `obj` as 'not a deprecated alias'. The issue itself explains why this is always right: an unhashable object can never be a dict key. The change is local, needs no new dependencies, and keeps the original semantics for hashable objects. Patch A switches to `DEPRECATED_ALIASES_IDS.get(id(obj))` and raises the minimum `typing-inspection` version to 0.4.4. Avoiding hashing entirely is a reasonable idea, since the deprecated aliases are singletons. However, the fix only works if that new attribute exists in the bumped dependency, which cannot be verified from the diff. It also forces a dependency bump onto a regression fix. Patch B additionally hardens `_path_schema`, where `path_type not in {str, bytes}` would hit the same unhashable problem for `os.PathLike[[]]`. This adjacent fix is low-risk and tested.

Tests: Patch B's new test reproduces the reported scenario directly: a TypeAliasType with a ParamSpec, parameterized with `[]`, used in a model field with `| None`, plus a TypeAdapter and JSON schema check. It also adds a parametrized path test. Patch A's test uses a different route to the same problem, `list[Annotated[int, Meta()]]` with unhashable metadata. It would likely fail before the change, but it does not exercise the reported ParamSpec case. It also has a typo in its name (`unhasbable`) and a placeholder `<link>` docstring.

Craft: Patch B's comment explains why the exception is caught. Patch A is terser, but its test is sloppy. Overall, B has the safer fix, the more direct regression test, and no new dependency requirement.

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

8m 50s

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

45vs 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+38 −7
pydantic/_internal/_generate_schema.pyindex 53971d20..14eeed19 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 is not str and path_type is not 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 PEP 695 alias parameterized with a list, such as `Alias[[], int]`+                # when `Alias` has a `ParamSpec`), so 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..854a5c11 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,20 @@ def test_type_alias_type_with_metadata() -> None:      ta = TypeAdapter(B)     assert ta.json_schema() == {'type': 'int', 'extra': 1}+++def test_type_alias_with_param_spec_parameterized_with_list() -> None:+    """Parameterizing a type alias having a `ParamSpec` with a list results in an unhashable object."""+    P = ParamSpec('P')+    R = TypeVar('R')+    Alias = TypeAliasType('Alias', Any, type_params=(P, R))++    class Model(BaseModel):+        f: Alias[[], int] | None = None++    assert Model(f=1).f == 1+    assert Model().f is None++    ta = TypeAdapter(Alias[[], int])+    assert ta.validate_python('a') == 'a'+    assert ta.json_schema() == {}tests/types/test_path.pyindex 866436e5..d0873ae5 100644@@ -13,6 +13,7 @@ from pydantic import (     Field,     FilePath,     NewPath,+    PydanticUserError,     SocketPath,     TypeAdapter,     ValidationError,@@ -105,6 +106,12 @@ def test_path_like_extra_subtype():     ]  +@pytest.mark.parametrize('path_type', [int, []])+def test_path_like_invalid_subtype(path_type):+    with pytest.raises(PydanticUserError, match='`os.PathLike` can only be used with `str`, `bytes` or `Any`'):+        TypeAdapter(os.PathLike[path_type])++ def test_path_like_strict():     class Model(BaseModel):         model_config = dict(strict=True) 
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]]