Type alias statements stop tracking typevar variance after two deep Summary Ran into…
- User
Type alias statements stop tracking typevar variance after two deep
Summary
Ran into this while making my umpteenth generic parser generator soup and messed up a parser generator transformer. https://play.ty.dev/d0fab0ef-bf5d-496f-b305-046e604cd702
pyfrom dataclasses import dataclass @dataclass class Box[T]: # T is invariant item: T type RefBox[T] = Box[T] # T is invariant type RefRefBox[T] = RefBox[T] # T is bivariant???When combined with #3517, you can make a type safe transmute (this happened in my actual code): https://play.ty.dev/eff23d78-ef4e-4bda-8aa7-b9848e527cb3
Version
ty 0.0.35 (bc12d1c 2026-05-10) playground 7efc9a615
Evaluation contract
Variance inference for both PEP 695 and legacy generic type aliases must recurse through the alias value rather than treating every alias as bivariant. Preserve covariant, contravariant, invariant, and bivariant results through multi-level and reordered multi-parameter alias chains. Recursive or mutually recursive alias cycles must terminate safely using the existing bivariant cycle fallback.
Interface
No new interfaces are introduced.
- Assistant
I'll investigate how ty tracks typevar variance through nested type aliases and fix the depth limit bug.
- Assistant
Reproducing the bug, then fixing
Type::TypeAliasvariance — it's currently hardcoded to bivariant instead of recursing through the alias value. - Assistant
Bug confirmed. Implementing the fix and adding tests.
- Assistant
Using
value_typeinstead ofraw_value_typefor specializedType::TypeAliasso type parameter substitutions are preserved through nested aliases. - Assistant
Fixing mdtest cases: correcting the error comment placement and replacing the double-swap test (which cancels out).
- Assistant
Fixed nested type alias variance tracking.
Type::TypeAliaswas treated as bivariant instead of recursing through the alias value.Root cause
When computing variance for a PEP 695 type alias like
type RefRefBox[T] = RefBox[T], ty correctly started from the alias RHS, but the RHS is aType::TypeAlias(RefBox[T]). That variant was lumped into the catch-all bivariant branch invariance_of:6870:6871:crates/ty_python_semantic/src/types.rs| Type::TypeAlias(_) | Type::NewTypeInstance(_) => TypeVarVariance::Bivariant,So one level of aliasing worked (
RefBox[T] = Box[T]), but a second level stopped propagating invariant variance and fell back to bivariant — allowing unsafe transmutes likeRefRefBox[int]→RefRefBox[str].Fix
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.