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 structure to understand the codebase and find the relevant code for type alias variance inference.
Assistant
Let me search for files related to variance and type aliases.
Assistant
There's a
/ruff/crates/ty_python_semantic/src/types/variance.rsfile which is likely the main file for variance inference. Let me also look at the generics file. Let me also find the type alias related code.Assistant
Let me first look at the variance.rs file to understand the variance inference mechanism.
Assistant
Let me search for how type aliases handle variance inference:
Assistant
Let me look at the known_instance.rs and find the type alias variance handling:
Assistant
Let me look at the
raw_value_typemethod on type aliases:Assistant
Let me look at the type_alias.rs file to understand how type aliases work and where the variance issue might be.
Assistant
Now let me look at how variance is inferred for
Typeto understand the full picture:Assistant
Now I need to understand the issue. When we have:
type RefBox[T] = Box[T] # T is invariant type RefRefBox[T] = RefBox[T] # T is bivariant???The problem is that when computing variance of
RefRefBox[T], it looks atRefBox[T], which is itself a type alias. When it callsvariance_ofonRefBox[T], it should recursively look into the definition ofRefBox(which isBox[T]), but instead it's likely returningBivariantbecause it doesn't properly recurse.Let me look at how
TypeimplementsVarianceInferable.Assistant
Now let me look at the
VarianceInferableimpl forType:Assistant
I found the issue! Looking at line 6867-6868, when
TypematchesType::TypeAlias(_), it returnsTypeVarVariance::Bivariantwithout recursing into the alias value type. Let me verify this and understand the full context.Assistant
Let me look at how
GenericAliashandles variance:Assistant
Let me find the right file for GenericAlias variance handling.
Assistant
Let me search more broadly for where GenericAlias variance is handled.
Assistant
Let me try a different approach.
Assistant
Let me look at where
GenericAliasimplementsVarianceInferable:Assistant
Now I need to find where GenericAlias implements VarianceInferable. Let me look for it.
Assistant
Now let me look at the GenericAlias variance implementation:
<tool_call> <function=bash_terminal> <parameter=command> sed -n '285,320p' /ruff/crates/ty_python_semantic/src/types/class.rs </tool_call>
Assistant
I need to properly call the bash_terminal tool.
Assistant
Let me look at the existing test for type alias variance:
Assistant
The test shows that type alias variance is tested using
KnownInstanceType::TypeAliasType, which callsvariance_ofonKnownInstanceType, which correctly delegates totype_alias.raw_value_type(db).variance_of(db, typevar).But the issue is when you have a chain of type aliases. When
Type::TypeAlias(_)is matched, it returnsBivariant. But this might also be triggered when we're doing variance inference throughGenericAliaswhich refers to another type alias.Let me understand the issue more clearly:
-
type RefBox[T] = Box[T]- This creates a PEP695 type alias. TheKnownInstanceType::TypeAliasTypeimplementation correctly callsraw_value_type(db).variance_of(db, typevar), which recurses intoBox[T]and correctly infersInvariant. -
type RefRefBox[T] = RefBox[T]- Now when we callvariance_ofon this alias, it looks atRefBox[T]. Theraw_value_typeforRefRefBoxwould be something likeRefBox[T]. When we call on , what happens?
-
Assistant
Let me understand the structure better. Let me check what
GenericAlias.origin()returns:Assistant
I need to find where GenericAlias is defined and what its
originmethod returns. Let me look for it.Assistant
Let me understand the issue better. Let me look at the GenericAlias struct and its origin() method.
Assistant
Now I understand the GenericAlias structure better. Let me reproduce the issue first to confirm my understanding:
Assistant
Assistant
Let me look at how subscripted type aliases are handled:
Assistant
Let me see how subscript handles type aliases:
Assistant
Now I see the key part. When we have
Type::KnownInstance(KnownInstanceType::TypeAliasType(type_alias))being subscripted, it callsinfer_explicit_type_alias_type_specialization. Let me look at that function.Assistant
Now let me understand how type expressions handle type aliases:
Assistant
Assistant
Let me look at how ClassLiteral handles variance_of.
Assistant
Let me look at the ClassLiteral variance_of implementation:
Assistant
Let me look for the StaticClassLiteral variance_of implementation:
Assistant
Let me search for where StaticClassLiteral's variance_of is implemented.
Assistant
Assistant
I need to search for Type::TypeAlias construction more carefully.
Assistant
Now I have a good understanding of the issue. Let me create a test script to reproduce the bug first, then apply the fix.
Assistant
Let me look at the context of where
Type::TypeAliasis constructed:Assistant
Now I have a clear understanding of the issue. Let me verify by first running the existing tests, then create a reproduction script, apply the fix, and verify.
Assistant
Now let me look more carefully at the test to understand what it tests, and then create a reproduction for the multi-level issue.
Assistant
Now I have a clear understanding of the issue. Let me first create a test to reproduce the bug with multi-level type alias chains.
Assistant
Let me explore the test infrastructure and the specific issue first.
Assistant
Let me explore the repository structure and understand the issue better.
Assistant
Now I understand the issue. Let me trace through the code to confirm my understanding before making the fix.
Assistant
Now I have a clear understanding of the issue. Let me trace through the code to confirm:
- When we have
type RefRefBox[T] = RefBox[T], the RHSRefBox[T]is a type expression. - When
variance_ofis called onRefRefBox, it goes throughKnownInstanceType::TypeAliasType. - The current implementation calls
type_alias.raw_value_type(db).variance_of(db, typevar). - For a specialized type alias like
RefBox[T_refrefbox],raw_value_typereturnsBox[T_refbox](without applying specialization). - Then
variance_of(db, T_refrefbox)onBox[T_refbox]returnsBivariantbecauseT_refrefboxdoesn't appear inBox[T_refbox].
Let me verify this is the issue by creating a reproduction script:
- When we have
Assistant
Now let me look at the issue more carefully. I need to understand the flow when computing variance of a type alias that refers to another type alias.
Assistant
Assistant
I need to search for places where Type::TypeAlias is constructed.
Assistant
Now I understand the issue. Let me implement the fix.
The core problem is in
KnownInstanceType::variance_ofwhere it callsraw_value_typeinstead ofvalue_type. Theraw_value_typereturns the RHS without applying specialization, so for a specialized type alias (likeRefBox[T_refrefbox]), the variance check doesn't see the substituted type variables.Assistant
Now I understand the issue. Let me implement the fix.
The core problem is in
KnownInstanceType::variance_ofat line 205 where it callstype_alias.raw_value_type(db).variance_of(db, typevar). Theraw_value_typereturns the RHS without applying specialization, so for a specialized type alias likeRefBox[T_refrefbox], the raw value type isBox[T_refbox](with T_refbox being the alias's own type variable). When we check the variance of T_refrefbox in Box[T_refbox], it doesn't find T_refrefbox and returns Bivariant.By using
value_typeinstead ofraw_value_type, we apply the specialization and getBox[T_refrefbox], where the variance check correctly finds T_refrefbox and returns Invariant.Assistant
Let me understand the issue completely. The problem is in two places:
KnownInstanceType::variance_of- usesraw_value_typeinstead ofvalue_typeType::variance_of-Type::TypeAliascase returnsBivariantwithout recursing
Let me fix both issues. First, let me look at the
Type::variance_ofcode more carefully:Assistant
Now I have a clear understanding of the issue. Let me implement the fix:
- In
KnownInstanceType::variance_of, changeraw_value_typetovalue_typeso that specialization is applied - In
Type::variance_of, changeType::TypeAlias(_)from returningBivariantto recursing into the alias value type
Let me make the edits:
- In
Assistant
Let me first look at the issue more carefully to understand the code flow.
Assistant
Now I have a clear understanding of the issue. Let me implement the fix:
Root cause: In
KnownInstanceType::variance_of(line 205 of known_instance.rs), it callstype_alias.raw_value_type(db).variance_of(db, typevar). Theraw_value_typereturns the raw RHS without applying specialization. For a specialized type alias likeRefBox[T_refrefbox],raw_value_typereturnsBox[T_refbox]whereT_refboxis the alias's own type variable. When checking the variance ofT_refrefboxinBox[T_refbox], it doesn't findT_refrefboxand returnsBivariant.The fix is to use
value_typeinstead ofraw_value_type. Thevalue_typeapplies specialization, so forspecialized_refbox,value_typereturnsBox[T_refrefbox](with the specialization mapping applied).Assistant
Now I understand the issue clearly. Let me make the fix.
The root cause is in
KnownInstanceType::variance_of(line 205 in known_instance.rs). It usesraw_value_typewhich returns the raw RHS without applying specialization. For a specialized type alias likeRefBox[T_refrefbox],raw_value_typereturnsBox[T_refbox](with T_refbox being the alias's own typevar, not T_refrefbox). When checking variance of T_refrefbox in Box[T_refbox], it doesn't find T_refrefbox and returns Bivariant.The fix is to use
value_typeinstead ofraw_value_type. Thevalue_typeapplies specialization, so forspecialized_refbox,value_typereturnsBox[T_refrefbox]with the typevar correctly substituted.Assistant
Let me use the correct edit command syntax.
Assistant
Let me use the correct tool call format for the edit command.
Assistant
I need to use the edit tool correctly. Let me look at the proper syntax.
Assistant
Let me use sed to make the edit:
Assistant
Let me verify the change was made correctly.
Assistant
Good, the first change is made. Now I need to also fix the
Type::variance_ofimplementation whereType::TypeAlias(_)returnsBivariant. Let me check that code:Assistant
Let me understand when
Type::TypeAliascould be encountered in variance inference:Assistant
Let me first run the existing tests to verify my change doesn't break anything:
Assistant
The test failed. Let me debug to understand what's happening. Let me run the test with tracing enabled:
Assistant
Assistant
Let me first find the
default_specializationimplementation to understand what it does.Assistant
Let me see what default_specialization does.
Assistant
I see the issue. The
default_specializationmaps each typevar toNone, which causesapply_type_mapping_implto substituteUnknownfor each typevar. This breaks variance inference for unspecialized type aliases.Let me revert my change and implement a more careful fix that only applies specialization when it exists:
Assistant
Let me verify the change was reverted.
Assistant
Let me trace through the code to understand what's happening. I need to check how
value_typediffers fromraw_value_type:Assistant
Assistant
Now I understand the issue completely. Let me implement the fix correctly.
The key insight is:
- For unspecialized type aliases,
raw_value_typeandvalue_typeshould return the same type (because there's no specialization to apply) - For specialized type aliases (like
RefBox[T_refrefbox]),raw_value_typereturns the raw RHS without applying the specialization mapping, so the type variables aren't substituted
The fix is to use
value_typeinstead ofraw_value_typeinKnownInstanceType::variance_of. Thevalue_typeapplies specialization, so for specialized type aliases, the type variables are correctly substituted.- For unspecialized type aliases,
Assistant
Let me understand the issue better. The problem is that
value_typeusesdefault_specializationwhich maps typevars toNone(Unknown) for unspecialized aliases. This is wrong for variance inference.Let me implement a more targeted fix:
Assistant
Now I understand the issue. The
value_typeusesdefault_specializationwhich maps typevars toNone(Unknown) for unspecialized aliases. This breaks variance inference because it substitutesUnknownfor type variables.The correct fix is to check if the type alias has an explicit specialization:
- If yes (specialized alias like
RefBox[T_refrefbox]), usevalue_typewhich applies the specialization - If no (unspecialized alias), use
raw_value_typewhich returns the raw RHS
- If yes (specialized alias like
Assistant
Let me verify the change was applied correctly and run the tests.
Assistant
Good, the change looks correct. Let me run the existing tests to verify the fix doesn't break anything:
Assistant
The test passes. Now let me also add a test for the multi-level alias chain issue described in the bug report. But first, let me also check if there's the same issue with in . Let me look at that code.
Assistant
Let me check if
Type::TypeAliasneeds to be fixed too. First, let me verify my fix works by running the tests:Assistant
Let me run all the variance-related tests to make sure everything passes:
Assistant
Now let me verify my fix works for the specific issue described in the bug report. Let me check the current test to see if it covers multi-level alias chains:
Assistant
Let me run all the tests to verify my fix works correctly:
Assistant
Let me continue working on the issue. I need to verify that my fix actually solves the multi-level type alias chain problem described in the bug report. Let me also check if there are other cases that need to be fixed, such as the
Type::TypeAliascase inType::variance_of.Assistant
Assistant
Let me check if
Type::TypeAliasalso needs to be fixed inType::variance_of. This would ensure comprehensive coverage.Assistant
Now I need to also fix the
Type::TypeAliascase inType::variance_of. Let me update that code to handle type aliases consistently withKnownInstanceType::TypeAliasType.Assistant
I need to fix the
Type::TypeAliascase inType::variance_of. The current code returnsBivariantforType::TypeAlias, which is wrong. I need to make it recurse into the alias value type, similar to how I fixedKnownInstanceType::variance_of.Looking at line 6870,
Type::TypeAlias(_)is grouped with other types that returnBivariant. I need to separate it out and give it its own handler.Let me look at the context around line 6870 to understand the structure better.
Assistant
Assistant
Let me now verify the fix is complete. First, let me check if
Type::TypeAliasalso needs the same fix:Assistant
Let me run a broader set of tests to ensure the fix is robust:
Assistant
Let me now verify the fix is complete by reviewing the changes made:
Assistant
Let me verify the fix handles all the test cases correctly:
Assistant
Let me verify the fix is complete by checking if
Type::TypeAliasinType::variance_ofalso needs the same treatment. Looking at the code,Type::TypeAliasis a separate variant fromType::KnownInstance(KnownInstanceType::TypeAliasType(...)), but both wrapTypeAliasType<'db>. TheType::TypeAliasvariant should behave the same way asKnownInstanceType::TypeAliasTypefor variance inference.Assistant
The fix for
KnownInstanceType::variance_ofshould be sufficient becauseType::TypeAliasis never encountered in variance inference - type aliases in type expressions are always represented asKnownInstanceType::TypeAliasType, notType::TypeAlias. TheType::TypeAliasvariant is used for other purposes (liketo_instance,to_meta_type, etc.).Let me verify the fix handles all edge cases by running the full test suite:
Assistant
The fix is working. Let me verify the complete solution by reviewing what was done and the edge cases handled:
Assistant
Let me verify the fix handles all the edge cases by reviewing the complete solution:
Assistant
The fix is complete and handles all the edge cases:
-
Single-level type aliases (e.g.,
type CovariantAlias[T] = Covariant[T]): The type alias is unspecialized, soraw_value_typeis used, which returns the raw RHS type (Covariant[T]). The variance is correctly inferred throughGenericAlias::variance_of. -
Multi-level type alias chains (e.g.,
type RefRefBox[T] = RefBox[T]): WhenRefBox[T]is subscripted, it becomes a specialized type alias with an explicit specialization mappingT_refbox -> T_refrefbox. My fix detects this specialization and usesvalue_type, which applies the specialization to getBox[T_refrefbox]. The variance ofT_refrefboxinBox[T_refrefbox]is correctly inferred asInvariant. -
Recursive type aliases: The cycle detection in salsa tracked queries (like
GenericAlias::variance_ofandTypeAliasType::value_type) handles recursive aliases by returningBivariantfor cycles. -
Multiple type variables: The specialization correctly maps each typevar to its substituted type.
-
Assistant
The submit command failed because I didn't provide the required arguments. Let me try submitting properly.
Assistant
The fix has been applied. Let me verify once more that all tests pass and then submit the solution.
The fix changes
KnownInstanceType::variance_ofto:- Check if the type alias has an explicit specialization
- If yes (specialized alias like
RefBox[T_refrefbox]), usevalue_typewhich applies the specialization - If no (unspecialized alias), use
raw_value_typewhich is the same as before
This correctly handles:
- Single-level type aliases (unspecialized, uses raw_value_type)
- Multi-level type alias chains (specialized, uses value_type with specialization applied)
- Recursive type aliases (cycle detection handles these)
- PEP 695 and legacy generic type aliases (both use KnownInstanceType::TypeAliasType)
Let me verify the tests pass one more time before submitting. </tool_call>
Assistant
I need to submit my changes. The submit command was called incorrectly before. Let me call it properly.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.