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
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.
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:
- If an error was reported in the issue description, I have successfully reproduced it.
- Assistant
I'll start by exploring the repository to understand its structure and locate the issue. Let's first check the git status and see if there are any existing tests or code related to type variance.
- Assistant
Let me explore the repository structure more to understand what this project is about. The issue seems to be about a type checker (ty) and variance inference for type aliases.
- Assistant
This is the ruff repository, which includes a type checker called "ty". The issue is about variance inference for type aliases. Let me look for relevant code in the ty crate.
- Assistant
Let me look at the variance module and the generics module to understand how variance inference works:
- Assistant
Now let me look for where variance inference is done for type aliases. The issue says that "Type alias statements stop tracking typevar variance after two deep." Let me search for type alias variance handling.
- Assistant
Let me search for type alias variance inference:
- Assistant
Let me look at how variance is computed for type aliases. Let me search for the
VarianceInferableimplementation forTypeAlias: - Assistant
Let me look at the VarianceInferable implementation for Type:
- Assistant
I can see the issue! In the
VarianceInferableimplementation forType, there's a line:Type::TypeAlias(_) => TypeVarVariance::Bivariant,This means that when we encounter a
TypeAlias, we treat it as bivariant, which is incorrect. The issue states that "Type alias statements stop tracking typevar variance after two deep" because when we havetype RefBox[T] = Box[T], we correctly track variance forBox[T](which usesGenericAlias), but when we havetype RefRefBox[T] = RefBox[T], theRefBox[T]is aTypeAlias, and we returnBivariantinstead of recursing into the alias value.Let me check the
TypeAliastype to understand its structure: - Assistant
Now let me look at how
TypeAliasTypeis defined and how it's used for variance:bash_terminal - Assistant
Let me look at the type_alias.rs file to understand the TypeAliasType structure.
- Assistant
Now let me look at the
KnownInstancevariance implementation to understand how it handlesTypeAliasType: - Assistant
Let me look at the full
VarianceInferableimplementation forKnownInstanceType: - Assistant
Let me look at how
GenericAliashandles variance: - Assistant
Let me search for how GenericAlias implements VarianceInferable.
- Assistant
Let me look at how GenericAlias handles variance in class.rs.
- Assistant
Now I understand the issue. In the
VarianceInferableimplementation forType,Type::TypeAlias(_)falls into the catch-all arm that returnsBivariant. This is the problem - it doesn't recurse into the alias's value type.Let me check if there are legacy type aliases too:
- Assistant
Let me look at the existing tests for type alias variance:
- Assistant
Let me look at the type_alias_variance test:
- Assistant
Let me understand how type aliases are used in generic contexts. Let me look at how type aliases are subscripted:
- Assistant
Let me understand the flow better by examining the test file for the existing type alias variance tests:
- Assistant
Let me look at how
Type::TypeAliasis constructed and when it is used: - Assistant
Let me look at the current code in types.rs around line 6870 to see where the
Type::TypeAlias(_)case is in the match statement: - Assistant
Let me look at how type alias subscripting works (how
RefBox[T]is represented): - Assistant
Let me understand the issue better. The issue is that when you have:
type RefBox[T] = Box[T] # T is invariant type RefRefBox[T] = RefBox[T] # T is bivariant???The
RefBox[T]in the second alias's value isType::TypeAlias(RefBox)(after being subscripted with T), and when computing variance of T, it hits theType::TypeAlias(_) => Bivariantcatch-all instead of recursing through.Let me look at how
Type::TypeAliasis used in the value of other type aliases: - Assistant
Let me look more closely at how a subscripted type alias is represented. Let me check what happens when you write
RefBox[T]: - Assistant
Let me look for how type aliases are handled in subscript contexts:
- Assistant
Let me look at how type aliases are subscripted:
- Assistant
Let me look at the subscript handling code around line 5953:
- Assistant
Now I understand the issue. In the
VarianceInferableimplementation forType, theType::TypeAliasvariant falls into the catch-all arm that returnsBivariant. But forKnownInstanceType::TypeAliasType, it correctly recurses throughraw_value_type. The fix is to makeType::TypeAliasalso recurse through the alias's value type.Let me also look at how
KnownInstanceType::TypeAliasTypehandles variance and whetherType::TypeAliascan have specialization: - Assistant
Now I understand the issue. The
Type::TypeAlias(_)case inVarianceInferable::variance_ofreturnsBivariantunconditionally, instead of recursing through the alias's value type. TheKnownInstanceType::TypeAliasTypealready does this correctly, but when a type alias appears asType::TypeAlias(which happens when it's used in type expressions), the variance is lost.Let me write a reproduction script first:
- Assistant
Now let me make the fix. I need to change
Type::TypeAlias(_)from returningBivariantto recursing through the alias's value type: - Assistant
Now I need to move
Type::TypeAlias(_)out of the catch-all bivariant arm and add a proper variance computation for it. I need to usevalue_type(db)(which applies specialization) rather thanraw_value_type(db).Let me make the edit:
- Assistant
Now let me check if there are any issues with cycles. Let me look at how the existing recursive alias tests handle variance:
- Assistant
Wait, I need to be more careful here. For recursive type aliases, using
value_typedirectly could cause infinite recursion. Let me check howKnownInstanceType::TypeAliasTypehandles the recursive case - it usesraw_value_typewhich has cycle detection via salsa. ForType::TypeAlias, I need similar cycle-safe recursion.Let me look at how the variance computation interacts with recursive type aliases:
- Assistant
Let me look more at the type alias variance code and understand how it handles recursion.
- Assistant
Now I need to think about potential infinite recursion with my fix. When a type alias references itself (e.g.,
type RecursiveAlias[T] = None | list[RecursiveAlias[T]]), usingvalue_type(db)insidevariance_ofcould cause infinite recursion. However, theGenericAlias::variance_ofis a salsa tracked function with cycle detection (cycle_initial=|_, _, _, _| TypeVarVariance::Bivariant), so cycles should be detected and handled.Let me verify my fix is correct and also check if there are tests for the "legacy generic type aliases" mentioned in the evaluation contract:
- Assistant
Let me also check the known_instance.rs to see if there's already handling for legacy type aliases:
- Assistant
Now let me look at the GenericAlias variance implementation more carefully to understand how it handles type arguments:
- Assistant
Now I understand the issue. The
Type::TypeAlias(_)case in theVarianceInferableimplementation falls through to the bivariant catch-all. But for the test case oftype RefRefBox[T] = RefBox[T], the raw value type ofRefRefBoxwould beType::TypeAlias(RefBox)(with specialization), and computing variance of T should recurse through the alias.The fix I've already applied should work. However, I need to verify it handles the recursive case correctly. The
GenericAlias::variance_ofhas salsa cycle detection that returns Bivariant, which will prevent infinite recursion for self-referential aliases.Let me verify my fix compiles and run the existing tests:
- Assistant
Good, it compiles. Now let me run the existing variance tests:
- Assistant
Good, the existing test passes. Let me also run broader variance-related tests:
- Assistant
All variance-related tests pass. Now let me also run the eager_expansion test:
- Assistant
It seems the eager_expansion test didn't run with that filter. Let me check the test name.
- Assistant
Let me find the
eager_expansiontest: - Assistant
Let me search for the test:
- Assistant
Let me run the eager_expansion test:
- Assistant
Let me check the test module structure:
- Assistant
Let me check the test structure:
- Assistant
Let me run the eager_expansion test:
- Assistant
Let me try a different approach:
- Assistant
There's a stack overflow! This means my fix causes infinite recursion for recursive type aliases. The issue is that
type RecursiveAlias[T] = None | list[RecursiveAlias[T]]causes infinite recursion when trying to compute variance throughvalue_type.I need to add cycle detection for the
Type::TypeAliasvariance computation. Let me look at how to create a tracked function for this: - Assistant
I need to add salsa cycle detection for the Type::TypeAlias variance computation. Let me revert my change and create a proper tracked function instead:
- Assistant
Let me look at the
BoundTypeVarInstancedefinition: - Assistant
I need to create a salsa tracked function with cycle detection for the
Type::TypeAliasvariance computation, similar to howGenericAlias::variance_ofworks. Let me look at the existing structure more: - Assistant
Let me look at the
TypeAliasTypedefinition to see if it can be used in a salsa tracked function: - Assistant
The stack overflow confirms that my simple fix causes infinite recursion for recursive aliases. I need to add cycle detection. Let me create a salsa tracked function specifically for type alias variance:
- Assistant
I need to create a salsa tracked function with cycle detection for the type alias variance computation. Let me look at how to do this:
- Assistant
Let me understand the problem better. The issue is that
alias.value_type(db)can return the same structure that references the alias, causing infinite recursion. I need to add salsa cycle detection. Let me create a tracked function: - Assistant
Let me look at how salsa tracked functions work in this codebase with enum parameters:
- Assistant
I see the problem. My simple fix causes stack overflow because for recursive type aliases,
alias.value_type(db)can lead to the same type structure. I need to create a salsa tracked function with cycle detection. Let me revert my change and take a different approach: - Assistant
Actually, I can't define a salsa tracked function inside a closure. Let me restructure this. I need to define the tracked function at module level:
- Assistant
I see there are duplicate lines. Let me fix that first and then add the tracked function at the module level:
- Assistant
I see I accidentally removed the
NewTypeInstancearm and the ending=> TypeVarVariance::Bivariant,. Let me fix this: - Assistant
I see that I lost the
};closing brace of the match statement. Let me fix that: - Assistant
I see the
tracing::trace!call got broken. Let me fix the structure: - Assistant
Now I need to add the
type_alias_variance_oftracked function. Let me add it near the class_mro_literals function: - Assistant
Now let me check if this compiles:
- Assistant
I see two issues:
*aliasis wrong sincealiasisTypeAliasTypenot a reference- The
cycle_initialclosure needs 4 args (salsa passes additional first arg)
Let me fix both:
- Assistant
Now let me fix the
cycle_initialclosure to have4 arguments: - Assistant
Now let me try to compile again:
- Assistant
The
aliasis alreadyTypeAliasType<'db>, not a reference. Let me check the Type enum definition to see how the TypeAlias variant is defined. - Assistant
The
aliasis alreadyTypeAliasType<'db>(Copy). So no dereferencing needed: - Assistant
Now let me try to compile again:
- Assistant
It compiles! Now let me run the existing variance tests:
- Assistant
The test didn't run. Let me check why:
- Assistant
Good, the type_alias_variance test still passes. Let me also run all variance tests:
- Assistant
All tests pass. Let me run the eager_expansion test too:
- Assistant
The eager_expansion test is not found. Let me search for it:
- Assistant
The eager_expansion test is failing to be found. Let me check which test binary contains it:
- Assistant
Good, the eager_expansion test also passes. Let me now run all the mdtests related to type aliases:
- Assistant
Let me run all the tests to make sure nothing is broken:
- Assistant
Let me now run the relevant mdtests for type aliases and variance:
- Assistant
Let me now run a broader set of tests. Let me find relevant type alias test files:
- Assistant
Let me run all the type alias related tests.
- Assistant
Let me also run the implicit type aliases tests:
- Assistant
Let me run a broader set of tests:
- Assistant
All generics tests pass! Now let me look at the variance mdtest files to see if they already test multi-level alias chains:
- Assistant
Let me look at the end of the variance test files to see if they have alias variance tests:
- Assistant
Let me see what's at line 944 and the surrounding area:
- Assistant
Let me now also check the legacy variance test:
- Assistant
Let me run all the tests in the crate to make sure nothing is broken:
- Assistant
All lib tests pass. Let me now run a broader set of mdtests to make sure nothing is broken:
- Assistant
All generics tests pass. Let me now look at the final diff to make sure my changes are correct:
- Assistant
The diff looks clean and correct. Let me verify the changes one more time by looking at the final state:
- Assistant
The code looks correct. Let me also verify the tracked function:
- Assistant
Let me run a final comprehensive test to make sure everything works:
- Assistant
All338 mdtests pass. Let me now update the PEP 695 variance mdtest to add a test for the multi-level alias chain case. Actually, the instructions say "UNDER NO CIRCUMSTANCES should you modify existing tests or add new tests to the repository." So I should not add new tests. But let me verify the fix works by running a temporary test script.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.