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 the structure and locate relevant files. Let's first get an overview.
- Assistant
Let me understand the issue. The problem is with type alias variance tracking. When we have:
@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???The second level type alias (
RefRefBox) loses track of variance and becomes bivariant instead of invariant.This is in the
typroject (ruff's type checker). Let me explore the codebase to find where variance inference happens. - Assistant
The main file to look at is
crates/ty_python_semantic/src/types/variance.rs. - Assistant
Now let's look at where variance inference is computed. Let me search for "variance_of" implementations and where type aliases are handled.
- Assistant
Let me search for type alias variance inference code.
- Assistant
Let me search for type alias related types and variance inference:
- Assistant
Let me look at the type_alias.rs file in the ty_python_semantic crate.
- Assistant
Now let me search for where variance inference is implemented for type aliases:
- Assistant
Let me search for where variance inference is implemented for TypeAliasType.
- Assistant
Now let me look at the
VarianceInferableimplementation forType: - Assistant
Let me continue reading the variance_of implementation for Type to see how TypeAliasType is handled:
- Assistant
I found the issue! Looking at line 6873,
Type::TypeAlias(_)is matched and returnsTypeVarVariance::Bivariant. This means when we havetype RefRefBox[T] = RefBox[T], the variance inference forTinRefRefBox[T]stops at the type alias and returnsBivariantinstead of recursing through the alias value.Let me look at how
TypeAliasTypeworks to understand how to properly recurse: - Assistant
Let me look at the
TypeAliasTypein more detail to understand how it handles type parameters: - Assistant
Now let me look at how
TypeAliasTypeprovides access to its value type: - Assistant
Now let me look at how variance inference is done for
GenericAlias: - Assistant
Let me look at the
Specializationtype and how it works with type aliases: - Assistant
Let me look at the
Specializationstruct to understand its fields. - Assistant
Let me look at how type aliases are applied when subscripted (e.g.,
RefBox[T]): - Assistant
Let me look at the subscript handling for TypeAlias:
- Assistant
Let me look at how the generic context works:
- Assistant
Let me look at the GenericContext variables:
- Assistant
Let me look at how the
variablesmethod works on GenericContext: - Assistant
Let me search for how variance inference is done for type variables in a generic context:
- Assistant
Let me look at how variance inference is done for type variables in the TypeVar module:
- Assistant
Let me search for the
variancemethod onBoundTypeVarInstance: - Assistant
Let me look at the
variancemethod onBoundTypeVarInstance. - Assistant
Now I understand the flow. When computing variance of a
BoundTypeVarInstance, it callsbinding_type(db, definition).variance_of(db, self). Let me look at whatbinding_typereturns for a type alias definition: - Assistant
Let me search for how type aliases are handled in the known instances:
- Assistant
Let me look at the KnownInstanceType variance implementation:
- Assistant
Let me look at the subscript handling for KnownInstanceType::TypeAliasType:
- Assistant
Let me look at the full subscript function to see how
Type::TypeAliasis handled: - Assistant
Let me look at how
definition_expression_typehandles expressions, especially subscript expressions: - Assistant
Let me check what
definition_expression_typedoes - it's the function that computes the value type of a type alias. - Assistant
Let me look at how the type inference for type expressions (like
RefBox[T]) handles type aliases: - Assistant
Let me look at how TypeAlias is handled in subscripting:
- Assistant
Let me look at the infer_subscript_load function, which handles subscript expressions in type context:
- Assistant
Let me look at the infer_subscript_expression_types method:
- Assistant
Let me look at the
infer_subscript_expression_typesmethod to understand how type aliases are handled in subscript expressions. - Assistant
Now let me look at the subscript method for Type, particularly the TypeAlias case:
- Assistant
Let me look at the
infer_explicit_type_alias_specializationmethod: - Assistant
Let me search for where
infer_explicit_type_alias_specializationis defined: - Assistant
Now let me understand the core issue. Let me look at the test file for variance to understand what behavior is expected:
- Assistant
Let me look at the full test:
- Assistant
Now let me understand the flow. Let me look at how a subscript on a TypeAlias evaluates:
- Assistant
Let me look at how
Type::TypeAliasandKnownInstanceType::TypeAliasTypediffer: - Assistant
Let me look at how
RefBox[T]is evaluated when RefBox is a generic type alias. Let me check how known instances handle subscript: - Assistant
- Assistant
Now let me look at the
infer_explicit_type_alias_type_specializationmethod to understand how RefBox[T] is evaluated: - Assistant
Let me understand the whole flow by tracing how variance is computed for a type alias typevar. Let me look at the binding_type for a type alias definition:
- Assistant
Let me look at the binding_type for a type alias definition to understand what type is returned.
- Assistant
Let me look at the
infer_type_alias_definitionfunction: - Assistant
Let me look at that function:
- Assistant
Now I understand the issue completely. Let me trace through the flow:
type RefRefBox[T] = RefBox[T]- the RHSRefBox[T]evaluates to a specialized type alias viainfer_explicit_type_alias_type_specialization- The raw_value_type of
RefRefBoxisKnownInstance(KnownInstanceType::TypeAliasType(refbox_specialized_with_T)) - When computing variance of
Tin this type, theKnownInstanceType::TypeAliasTypecase doestype_alias.raw_value_type(db).variance_of(db, typevar)which ignores the specialization - So it computes
Box[T_refbox].variance_of(db, T_refrefbox)which isBivariantbecauseT_refrefbox != T_refbox
The fix needs to handle specialized type aliases properly, similar to how
GenericAliasdoes it. Let me now implement this.First, let me write a reproduce script to confirm the issue:
- Assistant
Let me look at the existing variance tests and write a reproduce test:
- Assistant
Now I have a clear picture of the issue. Let me look at how the
Type::TypeAliasvariant relates to theKnownInstanceType::TypeAliasType: - Assistant
Now I fully understand the issue. Let me trace through the exact flow:
type RefRefBox[T] = RefBox[T]- the raw_value_type of RefRefBox isKnownInstance(TypeAliasType(RefBox))specialized with[T_refrefbox]- When computing variance of T_refrefbox in this, it calls
KnownInstanceType::TypeAliasType(RefBox_specialized).variance_of(db, T_refrefbox) - But the current implementation:
type_alias.raw_value_type(db).variance_of(db, typevar)ignores the specialization - So it computes
Box[T_refbox].variance_of(db, T_refrefbox)= Bivariant since T_refbox ≠ T_refrefbox
The fix: for specialized type aliases, compute variance like
GenericAliasdoes - compose the variance of the substituted types with the variance in the raw value type.Let me implement
VarianceInferableforTypeAliasType: - Assistant
Let me now look at the variance computation flow more carefully. Let me check how the raw_value_type relates to the specialization:
- Assistant
Now I fully understand the issue. Let me trace through the flow:
type RefRefBox[T] = RefBox[T]- raw_value_type evaluatesRefBox[T]which becomes a specializedKnownInstanceType::TypeAliasType(RefBox_specialized_with_T_refrefbox)- When computing variance:
KnownInstanceType::TypeAliasType(RefBox_specialized).variance_of(db, T_refrefbox)callstype_alias.raw_value_type(db).variance_of(db, typevar) raw_value_typereturns the unspecialized RHSBox[T_refbox](using RefBox's own T)Box[T_refbox].variance_of(db, T_refrefbox)= Bivariant since T_refrefbox ≠ T_refbox
The fix: for specialized type aliases, we need to compose variances through the specialization (like
GenericAliasdoes). ForType::TypeAlias, we also need to handle this instead of returning Bivariant.Let me implement
VarianceInferableforTypeAliasType: - Assistant
Now I understand the full flow. Let me implement the fix. I need to add a
VarianceInferableimplementation forTypeAliasTypethat handles specialization properly. - Assistant
Now I have a clear picture. Let me implement the fix. I'll add a
VarianceInferableimpl forTypeAliasTypeand update the variance computation in bothTypeandKnownInstanceType. - Assistant
First, let me add the necessary imports and the
VarianceInferableimplementation forTypeAliasType: - Assistant
Let me verify the file was updated correctly:
- Assistant
Let me check the VarianceInferable implementation was added correctly:
- Assistant
Good. Now let me update the
KnownInstanceType::TypeAliasTypevariance computation inknown_instance.rs: - Assistant
Now let me update the
KnownInstanceType::TypeAliasTypevariance computation: - Assistant
Now let me update
Type::TypeAliasintypes.rs: - Assistant
Now let me update
Type::TypeAliasin the variance computation: - Assistant
Now let me check if the code compiles:
- Assistant
The
VarianceInferabletrait is implemented intype_alias.rsbut it's not being seen whereTypeAliasTypeis used. Let me check the full error: - Assistant
There's an issue with the placement. Let me check the file structure:
- Assistant
The impl was probably placed inside another impl block. Let me check:
- Assistant
I see - the
VarianceInferableimpl was placed inside theTypeAliasTypeimpl block. Let me look at the exact location: - Assistant
The impl was placed inside the TypeAliasType impl block. I need to move it outside. Let me fix this:
- Assistant
I need to fix the file structure - the impl was placed inside the TypeAliasType impl block. Let me fix it:
- Assistant
Let me verify the file structure is correct:
- Assistant
Good. Now let me try to compile again:
- Assistant
It compiles. Now let me run the existing tests to make sure I haven't broken anything:
- Assistant
Let me check the test name more carefully:
- Assistant
Good, the existing test passes. Now let me run the broader test suite:
- Assistant
All tests pass. Now let me also run the mdtests related to variance:
- Assistant
Let me look at the variance mdtest files:
- Assistant
I can see there are already variance tests for type aliases. Let me run the mdtests for variance:
- Assistant
All variance mdtests pass. Now let me write a test to verify the fix works for the issue described. Let me first look at the issue more carefully and add a test to the existing variance.md file:
- Assistant
Let me look at the end of the type aliases section:
- Assistant
I see there are tests for single-level type aliases but not for multi-level ones. Let me also check the legacy variance file:
- Assistant
Now let me create a test to verify the fix works for the specific issue described. I'll write a temporary test script:
- Assistant
Now let me run this test to verify the fix works. Let me find how to run the ty tool:
- Assistant
Let me find the ty binary and run it:
- Assistant
Let me run the ty tool on my test file to verify the fix works.
- Assistant
The test passes. Now let me also verify that the full test suite still passes:
- Assistant
Good, all 203 tests pass. Let me also run the full mdtest suite:
- Assistant
All 338 mdtests pass! Now let me also run a broader test to make sure nothing else is broken.
- Assistant
Everything passes. Let me also run the ruff_linter tests to make sure nothing is broken:
- Assistant
Let me also run the type_bivariance test from ruff_linter:
- Assistant
Let me also run the type_name_incorrect_variance test:
- Assistant
Let me now test some more edge cases to ensure robustness:
- Assistant
Excellent! All edge case tests pass. Let me also run the exact example from the issue description:
- Assistant
Let me run the full test suite one more time to make sure everything is clean:
- Assistant
All tests pass. Let me verify the exact changes I made:
- Assistant
Let me review the exact changes I made:
- Assistant
Let me now verify my changes look correct by reviewing the diff again and running a final comprehensive test:
- Assistant
All 338 mdtests pass. Let me run the full lib tests one more time to confirm:
- Assistant
Let me now verify the final state of my changes:
- Assistant
Let me clean up the temporary test files:
- Assistant
Now let me do a final verification of the changes and submit:
- Assistant
Let me run the full test suite one final time to confirm everything passes:
- Assistant
All tests pass. Let me submit the changes:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.