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
Let me start by exploring the repository structure to understand what we're working with.
Assistant
Now let me search for where type aliases are handled in terms of variance:
Assistant
Now let me look at the type_alias.rs file:
Assistant
Now let me check how variance is computed for type aliases (if at all):
Assistant
Now let me look at how the type aliases relate to types and how variance is computed:
Assistant
Let me look at the test for variance inference with type aliases:
Assistant
Now let me find where variance_of is implemented for TypeAliasType. Let me search for KnownInstanceType:
Assistant
So the existing implementation looks at
type_alias.raw_value_type(db). Let me understand the flow better. Let me reproduce the issue first to understand it:Assistant
Now let me look at the aliases.md file:
Assistant
Now let me look at how the variance of Type::TypeAlias (vs KnownInstanceType::TypeAliasType) is computed. Let me also look at where the Type alias goes through specialization:
Assistant
Let me look at the KnownInstanceType definition:
Assistant
Now let me find what the type alias is used in
Type::TypeAliasvsKnownInstanceType::TypeAliasType. The issue states that type aliases are tracking variance two levels deep. Let me understand the problem:Assistant
Let me first reproduce the issue. I'll create a small test:
Assistant
Let me check the existing tests around type alias variance. Look at the test that already exists for variance inference:
Assistant
Let me check the test that we already have for this to understand what test framework to use:
Assistant
Now I know the test exists and passes. Let me look at this test and understand the issue better. The existing test
type_alias_varianceusestype MyInvariant[T] = Invariant[T]. Let me modify the test to also add atype RefRefBox[T] = RefBox[T]case:Assistant
Let me write a test case first to reproduce the issue. Let me create a quick mdtest:
Assistant
Now let me look at the tests in instance.rs and known_instance.rs more carefully:
Assistant
Let me look at the issue more carefully. First, let me understand the flow of
Type::TypeAlias:Assistant
Let me check what
Type::TypeAliasis - looking at the union variants:Assistant
Now let me check how the variance of
Type::TypeAliasis computed. Looking at the existing logic:Assistant
Now I see!
Type::TypeAliasis being treated as bivariant. So when the type alias has nested type aliases, this might be the problem.Let me think about this. When the type alias is used, the value type is computed. Looking at the existing test for type alias variance:
The test uses
KnownInstanceType::TypeAliasTypedirectly. This is fine because the variance check onKnownInstanceType::TypeAliasTypedirectly recurses into the value type. The issue is when something else wraps aType::TypeAlias. Let me check the actual problem in the issue:Assistant
Let me trace through what happens:
For
RefBox[T] = Invariant[T]:KnownInstanceType::TypeAliasType(RefBox).variance_of(T) = Invariant[T].variance_of(T) = Invariant
For
RefRefBox[T] = RefBox[T]:- When we ask
KnownInstanceType::TypeAliasType(RefRefBox).variance_of(T), it callstype_alias.raw_value_type(db).variance_of(db, typevar). - The
raw_value_type(db)ofRefRefBoxshould return... what? Let me check:
Assistant
Let me look at raw_value_type more carefully:
Assistant
Now I need to understand what
definition_expression_typereturns forRefRefBox[T] = RefBox[T]. It probably returns aType::TypeAliasforRefBox[T]. Let me trace the value:Assistant
Let me look at how the Type::TypeAlias is constructed during expression evaluation:
Assistant
Now let me find where the Type::TypeAlias gets created when an alias references another alias. Let me trace this:
Assistant
Now let me check the type_expression.rs at line 1469 to see how the type alias is created:
Assistant
Now let me look at how
Type::TypeAliasis created:Assistant
Let me find where Type::TypeAlias is created (not just matched):
Assistant
Now I understand.
KnownInstanceType::TypeAliasType(alias)becomesType::TypeAlias(alias)when in a type expression. So:- For
RefBox[T] = Invariant[T], when we resolveRefBox[T], the value type becomesInvariant[T]. - For
RefRefBox[T] = RefBox[T], when we resolveRefRefBox[T], the value type becomes...Type::TypeAlias(RefBox[T])orInvariant[T]?
Let me trace this.
RefRefBox[T]RHS isRefBox[T]. When evaluated as a type expression,RefBox[T]becomesType::TypeAlias(RefBox)(via the in_type_expression) - but wait,RefBox[T]is specialized!Let me look more carefully:
- For
Assistant
Let me look at where the actual value_type of a type alias is being computed when one alias references another. Let me look at how the type alias gets its value type when the RHS uses another alias:
Assistant
Now I need to understand what
value_tyis when we haveRefRefBox[T] = RefBox[T]. Let me write a quick test to see the issue:Actually, let me look at the issue more carefully. The bug states that with
RefRefBox[T] = RefBox[T], the type variance is bivariant. Let me check this with the existing test:Looking at the existing test:
type MyInvariant[T] = Invariant[T]For this,
KnownInstanceType::TypeAliasType(MyInvariant).variance_of(T) = Invariant[T].variance_of(T) = InvariantBut for
type RefRefBox[T] = RefBox[T], the value type ofRefRefBoxis...RefBox[T]which would be...Type::TypeAlias(RefBox[T])orType::TypeAlias(RefBox).apply_specialization(...)which would resolve toType::TypeAlias(RefBox). Hmm.Let me look at how
value_typeis computed for the type alias:Assistant
OK so when we call
KnownInstanceType::TypeAliasType(RefRefBox).variance_of(T):- It calls
type_alias.raw_value_type(db) - This returns
definition_expression_type(db, definition, &node.value) - For
RefRefBox[T] = RefBox[T], the value isRefBox[T], which after type inference becomesType::TypeAlias(RefBox).with_specialization(...)
But the variance check just calls
.variance_ofon this, andType::TypeAliasis treated asTypeVarVariance::Bivariant!Wait, looking back at the code:
impl<'db> VarianceInferable<'db> for KnownInstanceType<'db> { fn variance_of(self, db: &'db dyn Db, typevar: BoundTypeVarInstance<'db>) -> TypeVarVariance { match self { KnownInstanceType::TypeAliasType(type_alias) => { type_alias.raw_value_type(db).variance_of(db, typevar) } _ => TypeVarVariance::Bivariant, } } }- It calls
Assistant
Now let me look at how
Type::TypeAliasis used in similar contexts. Let me look at how recursion is normally done for type aliases elsewhere:Assistant
Now let me look at how
visit_type_alias_typeis implemented for the visitor:Assistant
Now let me think about the proper way to handle this. Looking at how
KnownInstanceType::TypeAliasTypedoes it:KnownInstanceType::TypeAliasType(type_alias) => { type_alias.raw_value_type(db).variance_of(db, typevar) }The fix is to do the same for
Type::TypeAlias. Let me look at the issue again carefully:The issue says:
type RefBox[T] = Box[T](Box is invariant): T is invariant in RefBoxtype RefRefBox[T] = RefBox[T]: T should be invariant (but is bivariant)
Let me trace through:
When we ask
KnownInstanceType::TypeAliasType(RefRefBox).variance_of(T):- We get
type_alias.raw_value_type(db)which returns the RHS of RefRefBox. The RHS is the type expressionRefBox[T]. Let me find what type this resolves to.
Looking at the type_expr handling, when
RefBox[T]is evaluated in a type context, it gets the value type of RefBox which isBox[T]. But wait, it might still beType::TypeAlias(RefBox)if specialization is not applied.Let me find what value_type returns for RefBox[T]:
Assistant
Let me look at where
definition_expression_typeresolves a type alias. Let me look at the type_expression.rs:Assistant
Now let me look at how
infer_definition_typeshandles atype RefRefBox[T] = RefBox[T]statement. The RHS expression isRefBox[T], which is a subscript. Let me find the path:Assistant
Assistant
Let me look at how the type alias value gets created in builder.rs to better understand what
RefBox[T]becomes:Assistant
So
infer_type_aliascallsinfer_type_expressionon the RHS. Theinfer_type_expressionreturns aType. ForRefRefBox[T] = RefBox[T], the RHS isRefBox[T]. Looking atinfer_explicit_type_alias_type_specialization:When we evaluate
RefBox[T], we get aType::TypeAlias(RefBox_specialized_with_T)fromin_type_expression. Sovalue_tyisType::TypeAlias(...).Let me trace this more carefully:
Assistant
So when we evaluate
RefBox[T], we get a specialized type alias. Then.in_type_expression()on it returnsType::TypeAlias(specialized_refbox).Wait, let me look at
infer_explicit_type_alias_type_specialization:Assistant
Assistant
Assistant
Interesting!
GenericAlias::variance_ofissalsa::trackedand hascycle_initial=|_, _, _, _| TypeVarVariance::Bivariant. So for cyclic variance computations, it returns Bivariant.We should do something similar for type aliases. But type aliases are not salsa-tracked (they're in an enum). Let me think about this.
Actually, since
value_typeis salsa tracked and has cycle handling, when we recurse intovalue_typeand there's a cycle, we'll get aDivergenttype. AndType::Divergent.variance_ofreturns Bivariant.Wait, let me check:
Assistant
Assistant
Now I need to think about whether to use
value_typeorraw_value_type. Theraw_value_typereturns the RHS as-is. Thevalue_typeapplies the specialization.For
type RefBox[T] = Invariant[T]:RefBox.raw_value_typereturnsGenericAlias(Invariant, [T@RefBox]). T in this is bound to RefBox.RefBox.value_typereturnsGenericAlias(Invariant, [T@RefBox])(no specialization).
For
RefBox[int](specialized):RefBox.specializationis[int].RefBox.value_typeapplies the specialization:GenericAlias(Invariant, [int]).RefBox.raw_value_typereturnsGenericAlias(Invariant, [T@RefBox]).
For variance:
- If we call
variance_of(T@RefBox)onRefBox(non-specialized): use raw_value_type to getInvariant[T]. - If we call
variance_of(T@outer)onType::TypeAlias(RefBox_specialized_with_T@outer): use value_type to get .
Assistant
Let me first understand the test framework. Let me look at existing mdtest tests:
Assistant
Now let me look at how mdtest runs:
Assistant
Let me look at how mdtest runs:
Assistant
Now let me look at how the existing variance test in variance.md is structured:
Assistant
Now I have enough context. Let me first reproduce the issue:
Assistant
Let me run a more direct test by modifying the existing test:
Assistant
Let me look at where the legacy type aliases handle variance too:
Assistant
Let me also look at legacy type aliases (the ones defined with
TypeAliasType(...)):Assistant
Now let me look at the issue more comprehensively. The issue mentions "Preserve covariant, contravariant, invariant, and bivariant results through multi-level and reordered multi-parameter alias chains." So we need to handle:
- Multi-level alias chains (RefRefBox[T] = RefBox[T] = Invariant[T])
- Reordered multi-parameter alias chains
Let me think about reordered multi-parameter. For example:
type Alias1[T, U] = tuple[T, U] type Alias2[U, T] = tuple[U, T] type Alias12[V, W] = Alias1[V, W] # V->T, W->U type Alias21[X, Y] = Alias2[X, Y] # X->U, Y->TFor variance:
Alias1.variance_of(T)= Covariant (T is in covariant position in tuple[T, U])
Assistant
Assistant
Now let me make the fix. I'll need to remove
Type::TypeAlias(_)from the bivariant list and add a separate case for it that recurses:Assistant
Now I'll make the fix. The key change is to remove
Type::TypeAlias(_)from the bivariant list and add a new case that recurses:Assistant
Let me apply the fix:
Assistant
Now let me verify the change:
Assistant
Now let me build to make sure my change compiles:
Assistant
Build is successful. Now let me run the existing tests:
Assistant
Now let me run the full test suite for the semantic crate to see if my changes break anything:
Assistant
Hmm, but I see there are many mdtests. Let me check the test counts:
Assistant
Only 2 test results shown but there should be more. Let me see all of them:
Assistant
Hmm only 203 + 14 = 217 tests run, but there are 338 mdtest tests. Let me see:
Assistant
Hmm, mdtest results are not showing. Let me check:
Assistant
Stack overflow! My fix causes infinite recursion. Let me think about why.
Looking at the issue: when
value_typeis called recursively, it eventually reaches a cycle. But the cycle detection might not work correctly becausevariance_ofis not salsa tracked.Let me check the value_type cycle handling more carefully:
Assistant
Looking at this,
value_typecallsapply_function_specializationandraw_value_type.raw_value_typeis#[salsa::tracked(...)]and has cycle handling.So when there's a cycle:
raw_value_type(A)is called.- If we're already in a cycle (computing
raw_value_type(A)), it returns Divergent. - But the cycle detection in salsa works on the SAME query.
Wait,
value_typeis also#[salsa::tracked]indirectly. Let me check ifvalue_typeis salsa tracked:Looking at the code,
value_typeis not explicitly#[salsa::tracked]. But it callsraw_value_typewhich IS tracked. So:A.value_type()->apply_function_specialization(A.raw_value_type())->raw_value_type()returns the value (salsa handles cycles here).
Assistant
Let me check where the stack overflow could be happening. The issue is that
variance_ofis called inside a salsa query, and within that, it callsvalue_typewhich is a salsa query, and within that, it can recurse infinitely.Actually wait,
variance_ofis not salsa tracked (it's a regular fn). But it's called from salsa queries. So the salsa cycle detection invalue_typeshould work.Let me check the actual stack overflow trace by running a specific test:
Assistant
Assistant
OK so the specialize function returns
Type::KnownInstance(KnownInstanceType::TypeAliasType(specialized)). Thenin_type_expressionon this returnsType::TypeAlias(specialized).So
A[T]evaluates toType::TypeAlias(A_specialized_with_T). No cycle yet.Now
raw_value_type(A)is called bydefinition_expression_typeforA's RHSA[T]. This returnsType::TypeAlias(A_specialized_with_T).Now
KnownInstanceType::TypeAliasType(A).variance_of(T):- Calls
A.raw_value_type(db).variance_of(T).
- Calls
Assistant
Looking at this more carefully:
Assistant
So
ManualPEP695TypeAliasType::value_typeis#[salsa::tracked]with cycle handling. Good.For
PEP695TypeAliasType,value_typeis not#[salsa::tracked]. But it callsraw_value_typewhich is#[salsa::tracked]with cycle handling.Wait,
raw_value_typefor PEP695 is salsa tracked. Let me look:Assistant
OK so:
PEP695TypeAliasType::value_type- NOT salsa tracked.PEP695TypeAliasType::raw_value_type- IS salsa tracked with cycle handling.
For
type A[T] = A[T]:- We call
A.value_type(). - This calls
A.raw_value_type()(salsa tracked). The salsa key isA. - The first time, salsa computes it. It evaluates the RHS
A[T]. The T here isT@A(bound to A's scope). - Evaluating
A[T]doesn't directly callA.value_type(). It calls something else...
Let me look at the type expression evaluation for
A[T]:Assistant
OK this is getting complex. Let me trace more carefully. The evaluation of
A[T]in the RHS ofA[T] = A[T]:- We're in the type expression inference for
A's RHS, which isA[T]. - The lookup of
AreturnsKnownInstanceType::TypeAliasType(A). - The subscript
A[T]triggersinfer_explicit_type_alias_type_specialization. - This creates a new specialized alias
A_specialized_with_T(where T isT@A). - Calls
.in_type_expression()on it which returnsType::TypeAlias(A_specialized_with_T).
Now
A_specialized_with_Tis a NEW salsa interned value. When we callvalue_typeon it:A_specialized_with_T.value_type()callsapply_function_specialization(A_specialized_with_T.raw_value_type()).A_specialized_with_T.raw_value_type()is salsa tracked with key .
- We're in the type expression inference for
Assistant
Assistant
Assistant
Let me look at the TypeCollector usage:
Assistant
Let me look at the TypeCollector class:
Assistant
OK so there's a
TypeCollectorthat can be used as a recursion guard. But this is for visitors, not forvariance_of.Let me think about this differently. The issue is that
Type::variance_ofis not salsa tracked, so we need to add cycle detection.Assistant
OK so when we apply the specialization, the type mapping replaces typevars in the type. For
Type::TypeAlias(A_specialized_with_T), applying the type alias specialization[T@A -> T@A]would look for T@A inside the inner alias and replace. But the inner alias's specialization is[T@A], not the type variables themselves.Actually, let me look at how
apply_type_mapping_implworks forType::TypeAlias:Assistant
Interesting! In
infer_map_impl, when the formal isType::TypeAlias, it expands to the value type and continues. There's aseenparameter for cycle detection! Let me look:Assistant
Assistant
Let me look at the trait definition:
Assistant
Assistant
Assistant
Good, both
PEP695TypeAliasTypeandManualPEP695TypeAliasTypehave#[salsa::tracked]impl blocks. So I can addvariance_ofas a salsa tracked method.Actually, let me re-think. The cycle detection for
variance_ofneeds to detect the cycle in the type alias chain. Fortype A[T] = A[T]:A.value_type() = Type::TypeAlias(A_specialized_with_T).- If we call
variance_ofon this, we recurse. - We need to detect that we're in a cycle.
If
variance_ofis salsa tracked onTypeAliasType, the salsa key is(TypeAliasType, typevar). ForType::TypeAlias(A_specialized_with_T).variance_of(T):Assistant
I think the simplest approach is to add a
variance_ofmethod on each variant separately. Or add a helper function.Actually wait, the simplest approach is to just add the method on
TypeAliasTypedirectly (as a regular method) that handles both variants. The salsa cycle detection won't work directly, but we can manually detect cycles using a seen set.Hmm. Let me look at the existing approach more carefully.
Actually, I just realized: there's a different way to fix this. We can make
Type::TypeAlias.variance_ofonly recurse if the value type is not the same alias. This handles direct self-recursion ().Assistant
Assistant
So
GenericAlias::variance_ofis salsa tracked, withcycle_initial=|_, _, _, _| TypeVarVariance::Bivariant. The signature is(self, db, typevar). The salsa key is(db, self, typevar).For type aliases, I'd want a similar approach. Let me try adding
variance_ofas a salsa tracked method onTypeAliasType:Assistant
Let me try adding a salsa tracked method on each variant. Actually wait, let me reconsider.
Looking at
GenericAlias::variance_of:- Salsa key:
(db, GenericAlias, typevar). - Cycle detected when we recursively call with the same key.
For type aliases, we want similar behavior:
- Salsa key:
(db, TypeAliasType, typevar). - Cycle detected when we recursively call with the same key.
Let me check if salsa supports tracked methods on enums. Looking at the salsa docs, salsa tracked methods can be on any type that implements the necessary traits. Enums are typically fine.
But the implementation might require
#[salsa::tracked]on the impl block, which requires the type to be salsa-interned or salsa-tracked.Looking at
TypeAliasType, it's not salsa-interned. So I can't directly add salsa tracked methods.Workaround: I can add the salsa tracked method on each variant (
PEP695TypeAliasTypeandManualPEP695TypeAliasType) and dispatch inType::TypeAlias.variance_of.Let me try this:
- Salsa key:
Assistant
Assistant
Wait,
value_typeis implemented as a regular method onTypeAliasType(not salsa tracked). Andraw_value_typefor PEP695 is salsa tracked, for ManualPEP695 it'svalue_typewhich is salsa tracked.Let me try adding salsa tracked
variance_ofon the enum. Let me see if this works:Assistant
Let me try a different approach: add salsa tracked
variance_ofon each variant separately.Actually, wait. The simpler approach: I'll make
Type::TypeAlias.variance_ofjust check if we're in a cycle by comparing the type aliases. I'll use a depth limit or comparison-based detection.Let me think... for , we recurse into . This returns . We can detect this is the same and return Bivariant.
Assistant
The
variance_ofis called from many places. Let me see what's the actual approach.Actually, the cleanest approach is to just modify the trait signature. Let me think about this.
Alternative idea: Instead of using
variance_offor recursion, I'll do the recursion manually withinType::TypeAlias.variance_ofusing a different approach.Actually wait. Let me think again. The issue is that for cyclic cases, the recursion doesn't terminate. The solution is to detect cycles.
For
type A[T] = A[T], the cycle is at the level of(A_specialized_with_T, T). If I makeType::TypeAlias.variance_ofuse a salsa-tracked helper, the salsa tracking handles this.Let me try to add salsa tracked method on each variant of
TypeAliasType:Assistant
OK so
PEP695TypeAliasTypehas salsa tracked methods. Let me add avariance_ofmethod to it:Actually wait, let me try a completely different approach. Let me revert my change to use the
value_typeapproach, but add a salsa tracked helper:Actually, I just thought of something simpler. The variance recursion uses salsa tracked queries indirectly (through
value_type->raw_value_type). The cycle detection inraw_value_typeworks for the same salsa key.What if I make the cycle detection at the
Type::TypeAlias.variance_oflevel use the salsa interned value as a key, by using a salsa tracked query?Let me try:
impl<'db> TypeAliasType<'db> { pub fn variance_of(self, db: &'db dyn Db, typevar: BoundTypeVarInstance<'db>) -> TypeVarVariance { self.variance_of_salsa(db, typevar) } #[salsa::tracked( cycle_initial=|_, _, _, _| TypeVarVariance::Bivariant, heap_size=ruff_memory_usage::heap_size )] fn variance_of_salsa(self, db: &'db dyn Db, typevar: BoundTypeVarInstance<'db>) -> TypeVarVariance { self.value_type(db).variance_of(db, typevar) } }Assistant
The
#[salsa::tracked]is on impl blocks for the variants (PEP695TypeAliasType and ManualPEP695TypeAliasType). Let me add avariance_ofmethod to each.But actually, this adds complexity. Let me try a different approach.
Let me just add cycle detection using a
seenset, and pass it through the trait. I'll modify the trait signature.Wait, there's an even simpler approach. Let me check what happens if I just compare the type alias directly. For the cyclic case
A[T] = A[T], the value type IS the same Type::TypeAlias. For mutual recursionA[T] = B[T]; B[T] = A[T], we have two different aliases but they refer to each other.Actually for
A[T] = B[T]; B[T] = A[T]:A.value_type()=Type::TypeAlias(B_specialized_with_T).B.value_type()=Type::TypeAlias(A_specialized_with_T).
When we call
A.variance_of(T):A.value_type()=Type::TypeAlias(B_specialized_with_T).
Assistant
Let me revert my fix first, then approach this differently:
Assistant
OK my current change causes infinite recursion. Let me try a different approach.
I'll make
Type::TypeAlias.variance_ofuse a salsa tracked helper. Let me try addingvariance_oftoTypeAliasType:Actually, looking at this more carefully, I realized that I need to add cycle detection. Let me try adding the cycle detection using a
seenset passed through a thread-local. Actually, let me just look at how theRawValueTypeis structured for the cyclic case more carefully.Wait, I think there's a simpler approach. Let me look at the existing code for
KnownInstanceType::TypeAliasType.variance_of:KnownInstanceType::TypeAliasType(type_alias) => { type_alias.raw_value_type(db).variance_of(db, typevar) }Assistant
Assistant
OK let me revert my change and try a different approach: make the
Type::TypeAlias.variance_ofuse a salsa tracked helper. Let me revert and try again.Assistant
Now let me think about this. The issue is that
Type::TypeAlias.variance_ofcurrently returns Bivariant. The fix is to recurse intovalue_type. But this can cause infinite recursion for cyclic cases.Approach: Add a salsa tracked
variance_ofmethod onTypeAliasType(or its variants).Let me try this. First, let me add
variance_ofonTypeAliasType:Assistant
Now let me add a salsa tracked
variance_ofmethod toTypeAliasType. I'll add it as a regular fn that delegates to a salsa tracked inner fn.Actually, since
TypeAliasTypeis an enum (not salsa interned), I'd need to add the salsa tracked method on each variant. Let me try.Wait, let me think. Salsa tracked functions need to take salsa inputs. For a method on a salsa struct, the receiver is the salsa input.
For an enum like
TypeAliasType, the enum value itself could be the salsa input. But the enum is not salsa-tracked.Looking at the code,
KnownInstanceTypeis also an enum and has methods. Let me see if it has salsa tracked methods:Assistant
No salsa tracked methods on
KnownInstanceType. OK.Let me try a different approach. Let me add a helper method to
TypeAliasTypethat's NOT salsa tracked, but uses the salsa interned values inside:Assistant
OK let me try a different approach. I'll just add a cycle detection check inline.
Here's the plan:
- In
Type::TypeAlias.variance_of, check if the value type is the sameType::TypeAlias. If yes, return Bivariant. Otherwise, recurse. - For mutual recursion, track visited type aliases via a thread-local or some other mechanism.
Actually, the simplest robust solution: use a
seenset that's passed through. Let me modify the trait.But that's invasive. Let me try the salsa tracked approach instead.
Actually, let me try yet another approach. I'll add a
seenparameter tovariance_ofas an optional argument. Or maybe just add a separate method.Hmm. Let me try yet another approach: use salsa tracked function on
TypeAliasType. Let me see if I can add#[salsa::tracked]to a method on the enum:Looking at the
#[salsa::tracked]macro, it generates code that wraps the function with salsa tracking. The receiver is the salsa input. For an enum, the enum value would be the salsa input.Salsa should support this if the enum implements the necessary traits. Let me try:
- In
Assistant
Let me just try it and see.
Assistant
Let me check the error:
Assistant
First error:
#[salsa::tracked] must also be applied to the impl block for tracked methods. So I need to add#[salsa::tracked]to the impl block.Let me also check the type alias.rs file for the imports:
Assistant
I need to add the missing imports:
Assistant
Hmm, it says finished, but did anything actually compile? Let me try a clean build:
Assistant
Now let me check the file:
Assistant
Good, it compiles. Now let me update
Type::TypeAlias.variance_ofto call this method:Assistant
Now let me run the existing tests:
Assistant
Now let me run more tests:
Assistant
All mdtest tests pass! Let me also run the unit tests:
Assistant
All tests pass. Now let me write a test to verify the fix works for the issue:
Assistant
Let me look at the existing tests for variance and create a temporary file to verify the fix:
Assistant
Actually let me create a temporary test in the test file to verify the fix. But first let me verify by running the existing tests:
Assistant
The existing test passes. Now let me add a test case for the nested type alias scenario. Let me look at the existing test:
Assistant
I should not modify existing tests. Let me create a separate test file to verify my fix. Actually, let me write a small standalone script to verify the fix works:
Assistant
Let me think about how to write a test that demonstrates the fix without modifying existing tests. Let me look at how the test structure works:
Assistant
Let me create a temporary test in the file to verify, but since I'm not supposed to modify tests, let me do this differently. Let me create a temporary test file:
Assistant
Let me create a temporary mdtest file:
Assistant
Let me copy this file into the mdtest directory and run it:
Assistant
Let me write a better test:
Assistant
The test passes! That means:
RefRefBox[bool] = x(wherex: RefRefBox[bool]) - OK (assignable).RefRefBox[int] = x(wherex: RefRefBox[bool]) - ERROR (invalid-assignment, because T is invariant in RefRefBox).
This shows the fix works correctly! Without the fix,
RefRefBoxwould be Bivariant and no error would be raised.Let me also verify with a test that should NOT error (covariant case):
Assistant
The test passes. Let me also verify with a more comprehensive test:
Assistant
Let me now also test some more edge cases:
Assistant
There are some test issues but I see:
RecursiveAlias[int]is revealed correctly.RecursiveAlias2[int]is revealed correctly.DirectSelfRefcorrectly produces a cyclic error.
So the recursive cases are working. Let me simplify the test:
Assistant
Recursive cases work! Let me also test more complex scenarios:
Assistant
Let me clean up the temp test file:
Assistant
Now let me look at the variance.md test to make sure I understand the existing semantics, and also add some tests there to verify the fix:
Assistant
Let me check the snapshot directory:
Assistant
OK there are no snapshot tests for variance. Now let me also run the corpus tests:
Assistant
All corpus tests pass. Now let me check the existing tests for the type alias and look at what else might be affected:
Assistant
All tests pass. Now let me also run the tests for the linter and other crates to make sure nothing else is affected:
Assistant
All ty tests pass. Let me also check the warning logs:
Assistant
No warnings or errors. Let me look at the diff I've made:
Assistant
Good. Let me look at the broader picture to ensure my fix is correct. Let me look at the variance_inferable trait:
Assistant
Now let me think about whether
VarianceInferableimport is needed. Let me check:Assistant
It's imported but I'm not sure if it's used. Let me check:
Assistant
We use
variance_of(which is fromVarianceInferabletrait). Let me verify the import is necessary:Assistant
Build succeeds. Now let me think about edge cases more carefully. Let me look at what
value_typereturns forTypeAliasType::PEP695andTypeAliasType::ManualPEP695:For
PEP695:value_type = apply_function_specialization(raw_value_type).raw_value_typeis salsa tracked with cycle detection.
For
ManualPEP695:value_typeis salsa tracked with cycle detection.
Both handle cycles at the salsa level. But the cycle detection is only for the SAME salsa key.
Hmm, my
variance_ofsalsa tracked function has key(TypeAliasType, typevar). The cycle detection returns Bivariant when the same key is recursively called.Let me trace for the cyclic case:
Type::TypeAlias(A_specialized_with_T).variance_of(T).- ->
A_specialized_with_T.variance_of(T)(the salsa tracked function). - This is a new salsa query. Compute it.
A_specialized_with_T.value_type()returnsType::TypeAlias(A_specialized_with_T).Type::TypeAlias(A_specialized_with_T).variance_of(T)- same call!
Assistant
The tests show that these direct cyclic definitions produce cyclic errors (which is expected). They don't crash or infinite loop. Let me update the test:
Assistant
All cycle cases work without infinite recursion! Let me clean up and look at the snapshots more carefully:
Assistant
Let me also check if there are any cycle tests in the existing variance test:
Assistant
Good, the existing tests for RecursiveAlias (Bivariant) and RecursiveAlias2 (Invariant) still pass. Let me make sure these tests still pass:
Assistant
Now let me check if the
VarianceInferableimport is actually needed. Let me try removing it to see:Assistant
OK let me revert that and check if
VarianceInferableis really needed:Assistant
Hmm wait, the sed command didn't actually replace anything because of how I used the multi-line pattern. The diff is unchanged. Let me just check if
VarianceInferableis needed:In the new code:
self.value_type(db).variance_of(db, typevar)variance_ofis from theVarianceInferabletrait. So the trait needs to be in scope.Let me make sure the test compiles:
Assistant
Assistant
No infinite recursion. The cyclic error is correctly produced.
Assistant
Now let me also verify by running the recursive alias test (which doesn't directly self-reference but is cyclic):
Assistant
Assistant
All tests pass: 203 + 14 + 338 + 1 + 0 = 556 tests, 0 failed.
Let me also run the ty crate tests:
Assistant
There's one failure in ty. Let me check:
Assistant
Wait, all tests pass now. Let me run again to see:
Assistant
All tests pass. The earlier failure might have been due to incremental compilation. Let me run the test again:
Assistant
All 4 + 0 + 128 + 40 = 172 tests pass. Let me also run the linter tests to make sure nothing else is broken:
Assistant
There's a failure in the ruff tests. But the ruff tests shouldn't be affected by my change. Let me check:
Assistant
This is an unrelated test about file permissions that's failing because we're running as root. This is not related to my changes. Let me verify by checking the test before my changes:
Assistant
Yes, this test fails before my changes too. It's an unrelated environment issue (running as root). Let me restore my changes:
Assistant
Good. Now let me verify my changes are still in place:
Assistant
Now let me also add a test to the variance.md file (since it's an existing file I can edit):
Assistant
Wait, the issue says:
UNDER NO CIRCUMSTANCES should you modify existing tests or add new tests to the repository. This will lead to an error in the system that evaluates your performance.
So I shouldn't modify the test file. Let me re-read the instruction...
OK so I should NOT add new tests to the repository. Let me check the test file:
Assistant
Good, I haven't modified any test files. Let me re-read the issue to make sure I understand the requirements:
Looking at the issue again:
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.
So:
- Variance inference for PEP 695 type aliases must recurse through the alias value - ✓ (handled by my fix)
- Variance inference for legacy generic type aliases must recurse - need to verify
- Multi-level alias chains must work - ✓
- Reordered multi-parameter alias chains must work - ✓
- Recursive or mutually recursive alias cycles must terminate safely using the bivariant cycle fallback - ✓ (salsa cycle detection returns Bivariant)
Let me verify the legacy type alias case. Looking at my code:
- matches both and variants.
Assistant
The
MyInvariantis a manual type alias. Manual type aliases don't have generic contexts. Let me think about this.MyInvariant = TypeAliasType("MyInvariant", Invariant)creates a manual type alias withvalue_type = Invariant. But since Invariant is a class,MyInvariantis essentially an alias for the Invariant class.Hmm, let me think about what variance should be inferred for a manual type alias that aliases a generic class.
Assistant
Let me look at what
ManualPEP695TypeAliasTypeis. It doesn't have a generic context. So the type aliases usingTypeAliasType(...)are non-generic.Wait, but the issue mentions "legacy generic type aliases". Let me look at this:
Assistant
The "legacy generic type aliases" probably refers to legacy
TypeVar-based type aliases like:from typing import TypeVar, Generic T = TypeVar('T') MyList = List[T] # legacy type alias using TypeVarThese are different from PEP 695 type aliases. Let me look at how legacy type aliases are handled:
Assistant
Let me look at how legacy type aliases are handled. Let me search for "implicit_type_alias":
Assistant
Let me check for legacy type aliases test:
Assistant
OK so legacy type aliases are different from PEP 695. Let me look at PEP 613 and implicit type aliases:
Assistant
OK so "legacy generic type aliases" probably means
MyList = List[T]style. Let me look for tests like this:Assistant
Let me look at the implicit type alias test for variance:
Assistant
Let me search for variance-related tests in implicit/PEP 613 type aliases:
Assistant
OK so PEP 613 type aliases can be generic. Let me look at how they're handled in the code:
Assistant
Let me check what a PEP 613 type alias is treated as internally:
Assistant
Let me look at how PEP 613 type aliases are treated in terms of TypeAliasType:
Assistant
So PEP 613 type aliases (and manual PEP 695 type aliases using
TypeAliasType(...)) are represented asManualPEP695TypeAliasType. Both PEP 613 and explicitTypeAliasType(...)use this variant.For PEP 613 generic aliases like
MyList: TypeAlias = list[T], they are stored asManualPEP695TypeAliasType. The value type is the type expressionlist[T].Let me see what my fix does for
ManualPEP695TypeAliasType:TypeAliasType::variance_ofdispatches tovalue_type(db).variance_of(db, typevar).- For
ManualPEP695,value_typeis salsa tracked with cycle handling. - So my fix should work for
ManualPEP695too.
Let me verify with a test:
Assistant
PEP 613 type aliases work correctly with my fix. The Invariant test errors (correctly, since Invariant is invariant in T), and the Covariant test passes (correctly, since Covariant is covariant in T).
Let me also test nested PEP 613 aliases:
Assistant
Nested PEP 613 aliases work. Let me clean up:
Assistant
Let me also look at the broader picture. The issue mentions:
Variance inference for both PEP 695 and legacy generic type aliases must recurse through the alias value rather than treating every alias as bivariant.
So we need to handle both. My fix does this:
- For
TypeAliasType::PEP695(PEP 695 type aliases),value_type()is computed viaraw_value_type()which is salsa tracked. - For
TypeAliasType::ManualPEP695(legacy / manual PEP 695 type aliases, including PEP 613 andTypeAliasType(...)),value_type()is salsa tracked with cycle handling.
Both should work with my fix.
Let me also verify the reorder multi-parameter case:
- For
Assistant
Reordered multi-parameter aliases work correctly. Let me clean up:
Assistant
Now let me also test the recursive case from the issue:
Assistant
The issue is resolved. Both
RefBox[bool] = RefBox[int]andRefRefBox[bool] = RefRefBox[int]correctly produce errors.Let me clean up:
Assistant
Now let me also verify that the second issue example (with combined #3517) doesn't have a problem:
Assistant
Both cases work correctly. Let me clean up:
Assistant
Now let me also do a final review of my fix:
Assistant
Now let me also run the full test suite one more time to make sure all tests still pass:
Assistant
All 203 + 14 + 338 + 1 + 0 = 556 tests pass.
Let me also think about potential edge cases I might have missed:
- Self-referential alias:
type A[T] = A[T]- should be Bivariant (cycle detected). - Mutually recursive aliases:
type A[T] = B[T]; type B[T] = A[T]- should be Bivariant. - Recursive through union:
type A[T] = None | list[A[T]]- existing test expects Bivariant. - Multi-level alias chain:
type A[T] = ...; type B[T] = A[T]; type C[T] = B[T]- should preserve variance. - Reordered multi-parameter:
type A[T, U] = tuple[T, U]; type B[U, T] = A[T, U]- should preserve variance. - Manual PEP 695 alias:
MyInvariant = TypeAliasType("MyInvariant", Invariant[T])- should preserve variance. - Nested manual PEP 695:
MyInvariant = TypeAliasType("MyInvariant", Invariant[T]); MyRefBox = TypeAliasType("MyRefBox", MyInvariant)- should preserve variance.
I've tested cases 1, 2, 3, 4, 5, 6, 7. Let me double-check case 1 (self-referential):
- Self-referential alias:
Assistant
Good, self-referential alias correctly produces a cyclic error. Let me clean up:
Assistant
Now let me look at the variance.md file to understand the existing tests more carefully:
Assistant
Looking at the existing test, it tests
KnownInstanceType::TypeAliasType(...).variance_of(...). This goes through the existing path inknown_instance.rswhich usesraw_value_type. With my fix:- For single-level aliases (e.g.,
InvariantAlias[T] = Invariant[T]): raw_value_type returnsGenericAlias(Invariant, [T]), variance is Invariant. ✓ - For recursive aliases (RecursiveAlias, RecursiveAlias2): behavior depends on my fix.
Wait, the existing test for
RecursiveAliasexpects Bivariant. Let me verify this still works:- For single-level aliases (e.g.,
Assistant
Assistant
Yes,
VarianceInferableis needed because we call.variance_of(...)on aTypevalue. Let me verify by removing it:Assistant
Yes, we need the import. Let me restore it:
Assistant
Let me also look at how the existing
variance_offor KnownInstanceType handles the type alias. Maybe I should also update that for consistency:Assistant
Assistant
Good, ParamSpec cases work.
Let me also check what happens when we have a complex case like ParamSpec with Concatenate:
Assistant
Hmm, the ParamSpecContravariantAliasNested test fails. The error says it's not assignable. Let me think about this.
For ParamSpec, the variance is contravariant. So
Callable[[int, str], None]should be a subtype ofCallable[[int, object], None]because str <: object and Callable is contravariant in its parameters.Wait, that's wrong. If Callable is contravariant in P, then
Callable[P, R]is a subtype ofCallable[Q, R]if Q <: P (because the contravariant direction is flipped).Hmm let me think about this. If we have:
- f: Callable[[int, str], None] (takes int and str)
- g: Callable[[int, object], None] (takes int and object)
Can we pass f where g is expected? f takes (int, str). g expects (int, object). When we call g, we pass (int, object). But f expects str, not object. So we can't pass an arbitrary object.
So
Callable[[int, str], None]is NOT a subtype ofCallable[[int, object], None].Wait, that's actually covariant!
Callable[[int, str], None]<: (same). But not assignable to .Assistant
The ParamSpec variance is correctly preserved. Let me clean up:
Assistant
All edge cases work correctly. Let me now look at the final diff:
Assistant
The diff is clean and minimal. Let me also verify by running the complete test suite one more time:
Assistant
All 556 tests pass. Now let me also think about the original test in
tests.rsfortype_alias_variance. The test usesKnownInstanceType::TypeAliasType(...).variance_of(...). This goes throughknown_instance.rs:KnownInstanceType::TypeAliasType(type_alias) => { type_alias.raw_value_type(db).variance_of(db, typevar) }This calls
raw_value_typefirst. If the RHS contains aType::TypeAlias, my fix makes it recurse properly.But wait, this test was passing before my fix because
Type::TypeAlias.variance_ofreturned Bivariant. Now it returns the correct variance. Let me verify the test still passes with the correct expected values:The test expects:
CovariantAlias-> CovariantContravariantAlias-> ContravariantInvariantAlias-> Invariant
Assistant
Test passes. Let me look at the VarianceInferable usage to make sure I have a clean solution. Let me check if my fix introduces any new dependencies:
Assistant
Let me clean up the imports to be more compact:
Assistant
Let me check if
VarianceInferableis actually used intype_alias.rs:Assistant
Only the import, but
VarianceInferableis needed because we use.variance_of(...)method. Let me check if it's properly used:Assistant
Yes,
VarianceInferableis used to call.variance_of().Let me run all the tests one final time:
Assistant
All 556 tests pass.
Let me also think about what happens for
TypeAliasType::ManualPEP695. Looking at the implementation:Assistant
For
ManualPEP695,value_typeis salsa tracked with cycle handling. So my fix should work for it.Let me also check the case where the
value_typeof a manual PEP 695 type alias returns a Type::TypeAlias. The recursion should work properly.Now let me also think about whether to add the VarianceInferable import via different path to make it cleaner. Actually, the current import is fine.
Let me also think about the visibility of
variance_of. I made itpub(crate). Let me check if this is correct:Assistant
pub(crate)is appropriate since it's only used internally.Let me also verify the final diff one more time:
Assistant
The diff is clean and minimal. Let me also look at the rust documentation comment style to match:
Assistant
Let me add a doc comment to my new method:
Assistant
Let me verify the final diff:
Assistant
The diff is clean and well-documented. Let me run the tests one final time:
Assistant
All 556 tests pass!
Let me also double-check that the fix correctly handles the issue described in the issue:
Assistant
The fix correctly resolves the issue.
Let me now go through the checklist:
Checklist:
-
If an error was reported in the issue description, I have successfully reproduced it.
- Yes, I reproduced the issue where
type RefRefBox[T] = RefBox[T]had T as bivariant instead of invariant. My fix correctly resolves this.
- Yes, I reproduced the issue where
-
If an error was reported in the issue description, I have confirmed that my fix resolves the error.
-
Assistant
Only 2 files modified, 26 insertions, 3 deletions. A minimal and focused fix.
Let me also make sure I'm not missing any pre-existing test files that should be modified. Let me look at the existing test for type alias variance:
Assistant
The existing test in tests.rs is what we have. My fix doesn't break it.
Let me look at the changes I made one more time:
Assistant
The fix is minimal and focused:
-
In
types.rs:- Added a new case for
Type::TypeAlias(alias)in theVarianceInferableimpl. - This case calls
alias.variance_of(db, typevar)to recurse into the type alias. - Removed
Type::TypeAlias(_)from the bivariant catchall since it's now handled explicitly.
- Added a new case for
-
In
type_alias.rs:- Added the missing imports for
BoundTypeVarInstance,TypeVarVariance, andVarianceInferable. - Added a new salsa tracked
variance_ofmethod onTypeAliasType(which dispatches to bothPEP695andManualPEP695variants). - The salsa tracking with
cycle_initial=|_, _, _, _| TypeVarVariance::Bivariantensures safe termination for recursive or mutually recursive alias cycles.
- Added the missing imports for
Let me submit the changes:
-
Assistant
All 556 tests pass. Let me also run the build for the whole workspace to make sure nothing is broken:
Assistant
The release build is taking too long. Let me skip it and just verify with the dev build:
Assistant
Build is successful.
Let me also verify my fix works with the example from the issue's #3517 reference:
Assistant
The transmute-like test correctly produces an
[invalid-assignment]error after my fix.Let me also do one more sanity check - look at the complete fix:
Assistant
Let me submit:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.