ISSUE DESCRIPTION Type alias statements stop tracking typevar variance after two deep…
- User
ISSUE DESCRIPTION
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.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use
git checkout <file>to restore the file to its original state. You can also reset all changes in the repository usinggit reset --hardcommand. Additionally, you can usegit stashandgit stash popto temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you callsubmit) usinggit statusorgit diffcommands. However you don't need to usegit addorgit commitbefore submitting your changes. In fact,submitonly submits currently unstaged changes because it usesgit diffto get the changes that need to be submitted.CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
Assistant
Let me start by understanding the repository structure and the issue at hand.
The issue is about type alias statements in what appears to be a Python type checker (ty, which seems to be a type checking tool). The problem is that type variable variance tracking stops after two levels of type aliases. Specifically:
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???RefRefBox[T]should have T as invariant (inheriting fromBox[T]), but it's being treated as bivariant.Let me explore the repository structure first.
Assistant
Let me explore the crates directory and understand the codebase better
Assistant
The
tycrate is likely where the type checker lives. Let me explore it for variance-related code.Assistant
Let me look for variance-related files in the ty crates.
Assistant
Let me search more specifically for the variance inference logic in type aliases.
Assistant
Let me find where TypeVarVariance is defined and the variance computation logic.
Assistant
Let me find where
TypeVarVarianceis defined and thevariancefunction/method.Assistant
Let me look at the variance.rs file.
Assistant
Now I need to find where
VarianceInferableis implemented for Type or the type alias representation. Let me search forvariance_ofimplementations.Assistant
Let me look at the typevar.rs file, particularly where variance is computed for type variables.
Assistant
Let me look at the relevant sections in typevar.rs:
Assistant
Let me try again.
Assistant
Let me find the
binding_typefunctionAssistant
Let me look at
binding_typeintypes.rs:Assistant
Let me look at
infer.rs:Assistant
Let me look at
known_instance.rsfor theVarianceInferableimplementation:Assistant
Let me understand how type alias definitions are handled. Let me search for where type alias definitions get their binding types:
Assistant
Let me look for the TypeAliasType definition:
Assistant
Let me look at the type_alias module:
Assistant
Let me look at the TypeAliasType enum and its raw_value_type method:
Assistant
Let me look at the TypeAliasType enum and its raw_value_type:
Assistant
Let me look at
PEP695TypeAliasTypeto understand `raw_value_typeAssistant
Let me look at how binding types are inferred for type alias definitions:
Assistant
Let me look at the
infer_type_alias_definitionmethodAssistant
Let me look at how
GenericAliascomputes variance - this is crucial for understanding howBox[T]knows about its type variable TAssistant
Let me look at how type alias subscription is handled in the type inference
Assistant
Let me look at the subscript handling for type aliases:
Assistant
Let me look at the rest of the subscript logic, especially for generic type aliases:
Assistant
Let me look at how a generic PEP 695 type alias is subscripted. Let me check the
__class_getitem__implementation:Assistant
Let me look at the test file for variance to understand the expected behavior
Assistant
Let me see the rest of the test
Assistant
Let me look at how type alias definitions get their binding types:
Assistant
Let me look at that section:
Assistant
Let me search for how
__class_getitem__works for TypeAliasType:Assistant
Let me look at these sections in bound_super.rs:
Assistant
Let me look at the
__class_getitem__handling for TypeAlias:Assistant
Let me look at the Type enum to understand the
TypeAliasvariant:Assistant
Let me search for where subscripting of TypeAliasType creates a result:
Assistant
Let me look at
try_call_dunder_on_classto understand how TypeAliasType handles__class_getitem__:Assistant
Let me search for
try_call_dunder_on_class:Assistant
Let me look at
try_call_dunder_on_class:Assistant
Let me first try to reproduce the issue by creating a test:
Assistant
Let me search for how TypeAliasType defines
__class_getitem__Assistant
Let me look at the full subscript logic for type aliases:
Assistant
Let me look at how
KnownInstanceTyperesolves members:Assistant
Let me look at how Type resolves members for KnownInstance:
Assistant
Let me look at the
memberfunction:Assistant
Let me write a small Rust test to reproduce the issue:
Assistant
Let me look at how
find_name_in_mroworks for `KnownInstanceTypeAssistant
Let me look at
classfor KnownInstanceType:Assistant
Let me search for how subscripting of a TypeAliasType creates the resulting type:
Assistant
Let me look at
infer_parameterized_legacy_typing_aliasand nearby code:Assistant
Let me search for how a bare type alias name is handled in type expressions:
Assistant
Let me look at this section more closely:
Assistant
Let me look at
infer_explicit_type_alias_type_specialization:Assistant
Let me look at
infer_explicit_type_alias_type_specialization:Assistant
Let me find and look at
infer_explicit_type_alias_type_specializationAssistant
Let me search more broadly
Assistant
Let me look at
infer_explicit_type_alias_type_specializationAssistant
Let me look at
in_type_expressionforKnownInstanceTypeAssistant
Let me search for
in_type_expressionon Type:Assistant
Let me look at
in_type_expression:Assistant
Let me look at the
variance_ofimplementation forTypeAssistant
Let me see the end of the match statement:
Assistant
Now I found the bug! On line 6870 of
types.rs:rustType::TypeAlias(_) => TypeVarVariance::Bivariant,Type::TypeAliasis unconditionally treated as bivariant. When theraw_value_typeof a PEP 695 type alias returnsType::TypeAlias(...)(which happens when the RHS is another type alias likeRefBox[T]), the variance computation just returnsBivariantinstead of recursing into the alias's value type.The fix should delegate to the alias's value type. Let me verify my understanding and then make the fix.
Let me also check what
NewTypeInstanceshould do, and whether any other types are also affectedAssistant
Let me look at the Type enum definition:
Assistant
Let me look at the remaining variants
Assistant
Now I've identified the bug. In the
variance_ofimplementation forType(line 6870 oftypes.rs),Type::TypeAlias(_)unconditionally returnsTypeVarVariance::Bivariantinstead of recursing into the alias's value type. This means two-level type alias chains liketype RefRefBox[T] = RefBox[T]always get bivariant variance.The fix is to delegate to the alias's
value_type:Assistant
Now let me check if the Type::variance_of already has cycle handling (salsa::tracked):
Assistant
Now let me run the existing tests to make sure the change works correctly
Assistant
The syntax is wrong - I need to remove
Type::TypeAliasfrom the multi-arm pattern and add it as a separate arm. Let me fix this:Assistant
Now I need to add the
Type::TypeAliasas a separate arm. Let me add it right before the catch-all:Assistant
Now let me compile and test
Assistant
Now let me add test cases for multi-level type aliases. Let me first look at the existing test to understand the structure and then add additional test cases:
Assistant
Let me look at the end of the test function to see where to add new test cases:
Assistant
Now I need to add multi-level alias test cases. Let me add them to the existing test:
Assistant
I need to fix the test - the closing
"#,got broken. Let me check the current state:Assistant
I need to fix the broken raw string closing. Let me restore it:
Assistant
I need to fix the closing properly. There's a duplicate line and the closing is wrong
Assistant
Now let me add the test assertions for the multi-level aliases at the end of the test function:
Assistant
The test file is quite corrupted now. Let me revert and start fresh:
Assistant
Right, the instructions say I should NOT modify existing tests. Let me restore my changes to the main code and verify it compiles and passes existing tests:
Assistant
Let me now run a broader set of tests to ensure nothing is broken:
Assistant
There's a stack overflow! My change creates infinite recursion when there are alias cycles. Let me look at which test causes it:
Assistant
I see a stack overflow - my change introduces infinite recursion for non-generic type aliases that reference themselves (like
type Itself = Itself). I need to add cycle detection. Let me look at howKnownInstanceType::TypeAliasTypehandles this and use a similar approach but with cycle protection.The key insight: for
Type::TypeAlias(alias), if the alias has no specialization (i.e., no type parameters), we can safely returnBivariantsince there are no type variables to track. If it has a specialization, we need to recurse.Let me adjust the
Assistant
Let me fix the approach - I need to handle the cycle case. The fix should only recurse into the alias value if the alias has a generic context (type parameters), and use
raw_value_typewhich is already salsa-tracked with cycle detection:Assistant
The approach still has a problem with self-referential non-generic aliases. Let me look at how
CycleDetectorworks in this codebase:Assistant
Let me look at the
CycleDetectorincyclic.rs:Assistant
Let me create a salsa-tracked function for computing variance of TypeAliasType, which will provide cycle detection via salsa:
Assistant
Let me add a salsa-tracked function for type alias variance. I'll place it after the
VarianceInferableimpl forType:Assistant
Let me create a salsa-tracked function with cycle detection for type alias variance. I'll add it right after the
VarianceInferableimpl block:Assistant
Now update the
Type::TypeAliasarm to use the new tracked function:Assistant
Now let me compile and test:
Assistant
Now let me run the full test suite:
Assistant
All 338 tests pass including the stack overflow fix. Let me check if there are broader tests that might be affected:
Assistant
Let me also run the other ty-related packages
Assistant
All tests pass. Let me now verify the fix works for the specific issue by creating a temporary test script:
Assistant
Let me review all my changes:
Assistant
The changes look clean and correct. Let me summarize:
Summary of Changes
Problem:
Type::TypeAliaswas unconditionally treated asBivariantin thevariance_ofmethod, which meant variance tracking stopped at the first type alias boundary. For multi-level type alias chains liketype RefRefBox[T] = RefBox[T](whereRefBox[T] = Box[T]), the variance of T would incorrectly beBivariantinstead ofInvariant.Fix (in
crates/ty_python_semantic/src/types.rs):-
Removed
Type::TypeAliasfrom the catch-all Bivariant arm - It was incorrectly lumped with other types that don't contain type variables.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.