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
from 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
The repro passed — the subtype check must resolve through the alias value. Let me find where the alias typevar's variance actually matters.
- Assistant
The static asserts pass since relations unwrap alias values. Let me find where the alias typevar variance is user-observable — likely hover/display and the referenced issue.
- Assistant
Now let me understand how legacy type aliases bind typevars:
- Assistant
Let me look at the
GenericAliasvariance implementation to mirror the pattern: - Assistant
Now I'll implement. First check imports in
known_instance.rsand the top oftype_alias.rs: - Assistant
Now implement the fix in
type_alias.rs: - Assistant
Now add the
ManualPEP695TypeAliasTypeandTypeAliasTypeimpls: - Assistant
Now update the
KnownInstanceTypearm and theType::variance_ofarm: - Assistant
The test catches the bug. Restore the fix:
- Assistant
Now the legacy alias case. Let me check how legacy typevar variance flags are inferred:
- Assistant
Unit tests pass. Now add hover tests in ty_ide for the two-deep case (the issue's observable):
- Assistant
The hover now shows the correct variance. Fill in the inline snapshots:
- Assistant
Now run the broader test suites to check for regressions:
- Assistant
Now verify the original issue scenario end-to-end, including recursion termination:
- Assistant
All green. Let me review the complete diff:
- Assistant
The diff is complete. Now run
prekon the changed files per repo guidelines: - Assistant
uvx/prekaren't available in this environment — falling back tocargo fmtfor the Rust formatting hook: - Assistant
These are artifacts of the earlier resource-exhausted parallel run (thread-pool creation failed), not real diffs — the same tests passed with
--test-threads=4. Cleaning them up: - Assistant
Done. Variance inference now recurses through type alias values instead of treating alias uses as bivariant.
The bug
BoundTypeVarInstance::variance_ofrecursion had two holes for type aliases:Type::TypeAlias(_)was in the "always bivariant" bucket inType::variance_of(crates/ty_python_semantic/src/types.rs). Since a PEP 695 alias's RHS referencing another alias (type RefRefBox[T] = RefBox[T]) infers toType::TypeAlias(RefBox[T@RefRefBox]), the typevar was never found — hence "bivariant after two deep."KnownInstanceType::TypeAliasTypeonly looked atraw_value_type, ignoring the specialization. This broke even one level deep for legacy implicit aliases (ImplicitAlias = CovariantAlias[LegacyT]), whose binding type is a specializedTypeAliasType— the queried typevar lives in the specialization, not the raw RHS.
The fix (
crates/ty_python_semantic/src/types/type_alias.rs)- Added a salsa-tracked
VarianceInferableimpl forPEP695TypeAliasTypewith the existingcycle_initial = Bivariantfallback (same pattern asGenericAlias/StaticClassLiteral/FunctionType):- unspecialized → recurse into
raw_value_type(where the alias's own typevars still occur); - specialized → compose each alias typevar's definition-site variance with the use-site variance of the queried typevar in the corresponding specialized type, mirroring
GenericAlias::variance_of.
- unspecialized → recurse into
- Added a tracked impl for
ManualPEP695TypeAliasType(recurses intovalue_type) and a dispatching impl for theTypeAliasTypeenum. Type::TypeAlias(alias)andKnownInstanceType::TypeAliasTypenow both route through it.
Recursive/mutually recursive aliases terminate via salsa cycle recovery with the bivariant fallback (verified: direct cycles, and lazy cycles like
type A[T] = list[B[T]] | None; type B[T] = list[A[T]] | None).Tests
types::tests::type_alias_varianceextended with: 2- and 3-deep chains for all four variances, a reordered two-parameter chain (type Swapped[T, U] = CoContraAlias[U, T]→ contravariant/covariant correctly swapped), direct and lazy mutual recursion (bivariant, terminates), and legacy implicit aliases of a generic PEP 695 alias. I verified the new assertions fail (Bivariantinstead ofCovariant) on the unfixed code.- Hover tests in
ty_idefor the issue's observable:T@ListAlias (invariant)andT@TupleAliasAlias (covariant)through 2- and 3-level chains. - Full
ty_python_semantic(338 mdtests + lib),ty_ide(1487),ty_project,tyCLI, andty_serversuites pass;cargo clippy --workspace --all-targets --all-features -- -D warningsandcargo fmt --checkare clean. (uvx prekisn't available in this environment, so I ran rustfmt/clippy directly.)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
- composer-2.5Compare side by side →
- composer-2.5Compare side by side →
- composer-2.5Compare side by side →
- composer-2.5Compare side by side →
- composer-2.5Compare side by side →
- gpt-5.6-solCompare side by side →
- gpt-5.6-solCompare side by side →
- gpt-5.6-solCompare side by side →
- gpt-5.6-solCompare side by side →
- gpt-5.6-solCompare side by side →
- fable-5Compare side by side →