ISSUE DESCRIPTION Type alias statements stop tracking typevar variance after two deep…
- User
ISSUE DESCRIPTION
Type alias statements stop tracking typevar variance after two deep
Summary
Ran into this while making my umpteenth generic parser generator soup and messed up a parser generator transformer. https://play.ty.dev/d0fab0ef-bf5d-496f-b305-046e604cd702
pyfrom dataclasses import dataclass @dataclass class Box[T]: # T is invariant item: T type RefBox[T] = Box[T] # T is invariant type RefRefBox[T] = RefBox[T] # T is bivariant???When combined with #3517, you can make a type safe transmute (this happened in my actual code): https://play.ty.dev/eff23d78-ef4e-4bda-8aa7-b9848e527cb3
Version
ty 0.0.35 (bc12d1c 2026-05-10) playground 7efc9a615
Evaluation contract
Variance inference for both PEP 695 and legacy generic type aliases must recurse through the alias value rather than treating every alias as bivariant. Preserve covariant, contravariant, invariant, and bivariant results through multi-level and reordered multi-parameter alias chains. Recursive or mutually recursive alias cycles must terminate safely using the existing bivariant cycle fallback.
Interface
No new interfaces are introduced.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use
git checkout <file>to restore the file to its original state. You can also reset all changes in the repository usinggit reset --hardcommand. Additionally, you can usegit stashandgit stash popto temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you callsubmit) usinggit statusorgit diffcommands. However you don't need to usegit addorgit commitbefore submitting your changes. In fact,submitonly submits currently unstaged changes because it usesgit diffto get the changes that need to be submitted.CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
- Assistant
I'll start by exploring the repository structure to understand what we're dealing with.
- Assistant
This is a large Rust repository (likely ruff, the Python linter). The issue is about variance inference for type aliases in Python's type system. Let me search for relevant code related to type aliases and variance.
- Assistant
This appears to be the ruff repository. The issue mentions "ty" which is a type checker. Let me look for the ty crate.
- Assistant
Let me explore the repository structure, particularly the
ty_python_semanticcrate which likely handles type checking and variance inference. - Assistant
Let me look at the variance.rs file first, as that's likely where the variance inference logic is.
- Assistant
Let me look at the variance.rs file to understand how variance inference works.
- Assistant
Now let me search for how variance inference is done for type aliases:
- Assistant
Let me look at the type_alias module:
- Assistant
Now let me look for where
VarianceInferableis implemented, especially for type aliases: - Assistant
Now let me look at how
VarianceInferableis implemented forType: - Assistant
Let me look at the
VarianceInferableimplementation forType: - Assistant
Let me look at the VarianceInferable implementation for Type to see how it handles TypeAlias:
- Assistant
Found it! The issue is on line 6860 (or around there):
rust| Type::TypeAlias(_) => TypeVarVariance::Bivariant,This is treating
TypeAliasas bivariant, which means it's not recursing through the type alias to determine the variance. Let me look at the issue more carefully.The issue states:
python@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???So when we have
RefRefBox[T], the type parameter T should be invariant (same asBox[T]), but it's being treated as bivariant because the variance inference isn't recursing through the type alias.The fix should be to recurse into the type alias's value type when computing variance. Let me look at how to implement this properly.
First, let me understand the current code:
Type::TypeAlias(_) => TypeVarVariance::Bivariant- This is treating ALL type aliases as bivariant- But we should recurse into the type alias's value type to determine variance
Let me look at how to access the value type from a TypeAlias:
- Assistant
Now I understand the issue. The
VarianceInferableimplementation forTypehasType::TypeAlias(_)returningTypeVarVariance::Bivariant. This means variance doesn't recurse into type alias values. Let me check the structure more carefully: - Assistant
Now let me understand how type aliases store their type parameters and how the mapping works. Let me look at how
GenericAliashandles variance: - Assistant
Let me look at the GenericAlias VarianceInferable implementation:
- Assistant
Now let me understand how the type alias's generic context and value_type relate. Let me look at the
Specializationstructure: - Assistant
Let me look at how a type alias with parameters is represented in the type system. Let me check how type aliases are used in type expressions:
- Assistant
Let me look at how PEP695 type aliases are used in subscript expressions:
- Assistant
Let me look at how TypeAlias is specialized/subscripted. Let me look at the
apply_type_mapping_implmethod: - Assistant
- Assistant
Let me look at the Specialization struct and its methods.
- Assistant
Now let me look at the test files for variance:
- Assistant
There's already a test function called
type_alias_variance. Let me look at it. - Assistant
Let me look at the test and the surrounding code.
- Assistant
Let me see the rest of this test and understand how variance is computed for type aliases.
- Assistant
Now let me look at where the variance is computed for
KnownInstanceType::TypeAliasType: - Assistant
Let me look at the KnownInstanceType VarianceInferable implementation.
- Assistant
Now I see the issue! The
KnownInstanceType::TypeAliasTypeimplementation correctly recurses throughraw_value_type, but when the raw value type itself contains aType::TypeAlias, it falls into theType::TypeAlias(_) => TypeVarVariance::Bivariantbranch in the mainType::variance_ofimplementation.Let me understand what the raw value type of
RefRefBox[T] = RefBox[T]looks like: - Assistant
Let me look at how subscript expressions work for type aliases:
- Assistant
Now I understand the full picture. Let me trace through the issue step by step. The key is:
KnownInstanceType::TypeAliasTypecorrectly delegates toraw_value_type().variance_of()- For
RefRefBox, the raw value type isRefBox[T], which is itself aType::TypeAlias(...)(specialized alias) Type::TypeAlias(_)returnsBivariantinstead of recursing
I need to implement proper variance computation for
Type::TypeAlias. Let me first understand howRefBox[T](in the RHS ofRefRefBox) is represented in the type system: - Assistant
Let me search more broadly for how subscript expressions are handled.
- Assistant
Let me look at the subscript builder to understand how
RefBox[T]is resolved: - Assistant
Let me look at how type alias subscripting is handled:
- Assistant
Let me search for where
Type::TypeAliasis created in the codebase: - Assistant
Let me look at how
Type::TypeAliasandKnownInstanceType::TypeAliasTyperelate and understand the complete flow: - Assistant
Let me look at the explicit specialization code:
- Assistant
Now I understand the complete picture. The issue is in the variance computation for type aliases. When computing variance of
KnownInstanceType::TypeAliasType, it delegates toraw_value_type().variance_of(), butraw_value_typeis the unspecialized RHS type. For a specialized alias likeRefBox[T_outer], we need to account for the specialization mapping.Let me also check how the variance is computed in the
Type::TypeAliascase vs theKnownInstanceType::TypeAliasTypecase: - Assistant
Now let me also look at how
TypeAliasType::raw_value_typeis used vsvalue_type: - Assistant
Let me look at the
value_typeandraw_value_typemethods more carefully to understand the difference: - Assistant
Now I have a clear understanding of the issue. Let me implement the fix. The issue is that:
-
KnownInstanceType::TypeAliasType::variance_ofusesraw_value_typedirectly, ignoring any specialization. For a specialized alias likeRefBox[T_outer], this means the typevar mapping is lost. -
Type::TypeAlias(_)inType::variance_ofreturnsBivariantinstead of recursing.
Let me fix both. First, let me fix the
KnownInstanceType::TypeAliasTypecase: -
- Assistant
Now let me look at the
GenericAlias::variance_ofimplementation more carefully for the pattern to follow: - Assistant
Now I have a thorough understanding. Let me trace through the exact issue:
type RefBox[T] = Box[T]—RefBoxis aPEP695TypeAliasTypewhoseraw_value_typeisBox[T](aGenericAlias)type RefRefBox[T] = RefBox[T]—RefRefBox'sraw_value_typeisRefBox[T]which isKnownInstance(TypeAliasType(RefBox specialized with T_refrefbox))- When computing variance of
T_refrefboxinRefRefBox, it goes throughKnownInstanceType::TypeAliasType::variance_ofwhich callsRefBox.raw_value_type(db).variance_of(db, T_refrefbox) RefBox.raw_value_typeisBox[T_refbox](unspecialized, withT_refboxnotT_refrefbox)- So
T_refrefboxdoesn't appear inBox[T_refbox]→ returnsBivariant!
The fix: For a specialized type alias, we need to account for the specialization mapping, similar to how
GenericAlias::variance_ofworks.Let me first write a reproduction test:
- Assistant
Now let me look at the existing test infrastructure and run the variance test:
- Assistant
Let me look at how
Type::TypeAliasis actually used in different contexts to understand its full impact: - Assistant
Let me now look at how the specialization works and understand the relationship between the alias typevar and the target typevar. Let me look at how
GenericAlias::variance_ofworks, because we need to replicate that pattern for type aliases: - Assistant
Now I have a thorough understanding of the issue. Let me trace through the problem:
For
type RefRefBox[T] = RefBox[T]:KnownInstanceType::TypeAliasType(RefRefBox).variance_of(db, T)callsRefRefBox.raw_value_type(db).variance_of(db, T)RefRefBox.raw_value_type()returnsRefBox[T_refrefbox], which isKnownInstance(TypeAliasType(RefBox with specialization [T_refrefbox]))- This calls
KnownInstanceType::TypeAliasType(RefBox.specialized).variance_of(db, T_refrefbox) - Which calls
RefBox.raw_value_type(db).variance_of(db, T_refrefbox) RefBox.raw_value_type()returnsBox[T_refbox](unspecialized, using RefBox's OWN typevar)Box[T_refbox].variance_of(db, T_refrefbox)→ Bivariant becauseT_refrefboxdoesn't appear inBox[T_refbox]
The fix: for a specialized type alias, we need to handle it like
GenericAlias::variance_ofdoes - composing the variance from the specialization mapping with the variance in the raw value type.Let me now implement the fix. First, let me look at what methods TypeAliasType provides:
- Assistant
Let me look at the specialization method on PEP695TypeAliasType:
- Assistant
Now I have a complete understanding. Let me implement the fix. The approach for both
KnownInstanceType::TypeAliasTypeandType::TypeAliasshould mirrorGenericAlias::variance_of: for specialized aliases, compose the variance from the specialization mapping with the variance in the raw value type.Let me first fix
KnownInstanceType::TypeAliasType::variance_of: - Assistant
Now let me implement the fix. I'll modify both
KnownInstanceType::TypeAliasType::variance_ofinknown_instance.rsandType::TypeAliasintypes.rs: - Assistant
I notice there's an extra
}on line 232. Let me fix that: - Assistant
I see the extra
}on line 232. Let me remove it: - Assistant
Good, the extra
}is removed. Now let me fix theType::TypeAliascase intypes.rs. Let me look at the current code: - Assistant
Now I need to also fix the
Type::TypeAliascase. Even though the direct path to the issue is throughKnownInstanceType::TypeAliasType, the evaluation contract says variance inference should recurse through alias values. Let me removeType::TypeAliasfrom the bivariant fallback and add proper handling: - Assistant
Wait, I need to check the syntax. The
Type::TypeAliasarm needs to be inside thematch selfexpression properly. Let me check: - Assistant
I see there's a missing
};to close thematch selfexpression. Let me check: - Assistant
I see the problem - the
matchexpression needs a closing};. The original code had it on the line after the bivariant arm, but my replacement removed it. Let me add it: - Assistant
Let me use a different approach:
- Assistant
Wait, I need to check the structure more carefully. The
};on line 6891 closes the innermatch type_alias.specialization(db)but the outermatch selfexpression also needs to be closed. Let me fix the structure: - Assistant
I still need a
};to close the outermatch selfexpression. Let me add it: - Assistant
Good, the structure looks correct now. Let me verify the full structure of the match expression:
- Assistant
Good, the structure looks correct. Now let me try to compile and run the existing test:
- Assistant
The existing test passes. Now let me check if there are existing mdtest files related to this:
- Assistant
Let me look at the variance mdtest:
- Assistant
Let me look at the variance mdtest to understand the test structure and check for existing two-deep alias tests:
- Assistant
Let me search for related tests more broadly:
- Assistant
Let me see the broader section of the mdtest with type alias tests:
- Assistant
Good, I can see the existing tests. Now let me run the existing variance mdtest to make sure my changes don't break anything:
- Assistant
Let me try running the mdtest from the correct package:
- Assistant
The existing variance mdtest passes. Now let me create a temporary script to verify the two-deep alias case works. Let me first check if ty is available:
- Assistant
Let me look for existing integration tests for variance:
- Assistant
Let me run a broader set of tests to make sure nothing is broken:
- Assistant
All PEP695 tests pass. Let me also run broader tests:
- Assistant
All generics tests pass. Now let me create a temporary test to verify the two-deep alias case works:
- Assistant
Let me run ty on this test file to check if the variance is now correctly inferred.
- Assistant
I need to configure the Python version. Let me create a proper test:
- Assistant
The pyproject.toml from the ruff repo is being picked up. Let me try a different approach:
- Assistant
The fix is working! The key diagnostic line:
codeerror[invalid-assignment]: Object of type `RefRefBox @ /tmp/test_variance/test.py:8:6[int]` is not assignable to `RefRefBox @ /tmp/test_variance/test.py:8:6[str]`This confirms that
RefRefBoxnow correctly tracks invariant variance. Before the fix, it would have been bivariant, allowing any assignment. Let me also test the transmute case from the issue: - Assistant
All the variance behaviors are correct:
- RefRefBox (invariant):
RefRefBox[int]is NOT assignable toRefRefBox[str]✓ - MyMyCov (covariant):
MyMyCov[int]IS assignable toMyMyCov[object]✓ - MyMyContra (contravariant):
MyMyContra[object]IS assignable toMyMyContra[int]✓ - MyMyBi (bivariant):
MyMyBi[int]IS assignable toMyMyBi[str]✓
Now let me run a broader test suite to make sure nothing is broken:
- RefRefBox (invariant):
- Assistant
All 203 tests pass. Let me also run the full mdtest suite:
- Assistant
All 338 mdtests pass. Let me now also run the full test suite to make sure nothing is broken:
- Assistant
Let me see the full summary:
- Assistant
All tests pass. Let me now review the final state of my changes:
- Assistant
The diff looks correct. Let me clean up the temporary test files:
- Assistant
Let me do a final check on the changes:
- Assistant
Now let me verify one more edge case - let me make sure the existing test still works and also think about whether I need to handle any edge cases in the
Type::TypeAliaspath that might not have aspecializationmethod: - Assistant
Let me verify the test runs:
- Assistant
All tests pass. Let me now run a final comprehensive test to make sure nothing is broken:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.