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
Let me start by exploring the repository structure to understand what we're working with.
Assistant
This is the
ruffrepository, which contains bothruffandtyprojects. The issue is aboutty. Let me explore thecratesdirectory to find the relevant codeAssistant
let me look at the
type_alias.rsfile to see how type aliases handle variance.Assistant
Now let me look at how variance is computed for type aliases. Let me search for
variance_offorTypeAliasTypeorKnownInstanceType.Assistant
Now let me look at the
raw_value_typeto understand what it returns.Assistant
Let me first look at the type_alias.rs structure more, and also see how the issue can be reproduced:
Assistant
Let me look at how
Type::KnownInstancehandles variance:Assistant
Let me look at this more carefully. Let me first write a simple test to confirm the issue:
Assistant
Let me write a test to specifically reproduce the issue. First, let me modify the test file to add a check for nested type aliases:
Assistant
Let me first try modifying the test to add a check for nested type aliases:
Assistant
Now let me modify the test to add the case from the issue:
Assistant
Let me first look at the existing tests for variance and see how the issue is structured. Then I'll add a test for the nested case:
Assistant
Let me add a temporary test to verify the issue. I'll first edit the existing test to add the case from the issue:
Assistant
Now let me add a test for two-level alias variance. First, let me understand the structure:
Assistant
Let me add a test for two-level aliases and verify the issue is reproducible:
Assistant
Let me try a different approach using a simpler replacement. Let me check the file before my changes
Assistant
My patch didn't apply. Let me check what happened and try again with a different approach:
Assistant
regex matched too early. Let me use a different approach. Let me use sed:
Assistant
Now let me create the new test function in a file and use Python to insert it at line 403:
Assistant
Now let me run the test to see if it fails:
Assistant
Excellent! The test failed. Let me also check what
raw_value_typeactually returns for a nested alias:Assistant
Let me look at where
Type::TypeAliasis in the variance_of to confirm the bug:Assistant
for how
Type::TypeAliasgets created:Assistant
Let me look at how
Type::TypeAliasis created from raw_value_type:Assistant
Let me check how subscripting a
TypeAliasTypeproduces aType::TypeAlias:Assistant
me look at
infer_explicit_type_alias_type_specialization:Assistant
Let me trace
raw_value_typeforNestedCovariantAlias. Let me write a small debug print test:Assistant
Let me look at
value_typemore carefully:Assistant
Now I understand the bug. When we have:
pythontype CovariantAlias[T] = Covariant[T] # Covariant type NestedCovariantAlias[T] = CovariantAlias[T] # Should be CovariantNestedCovariantAlias.raw_value_type()returnsType::KnownInstance(KnownInstanceType::TypeAliasType(CovariantAlias_specialized_with_T)). When we then recurse into this inner type alias, we useraw_value_typewhich doesn't apply the specialization - so we getCovariant[T']whereT'is the innerCovariantAlias's typevar (not the outerNestedCovariantAlias's typevar). When we ask for the variance ofNestedTinCovariant[T'], they don't match, so we get Bivariant.The fix is to use
value_type(which applies the specialization) instead ofraw_value_type. Let me verify:Assistant
Now let me check what
value_typedoes forManualPEP695TypeAliasType:Assistant
Let me look at the combined
TypeAliasType::raw_value_type:Assistant
The
TypeAliasType::raw_value_typeforPEP695usesraw_value_type, but forManualPEP695it usesvalue_type. There's an inconsistency.Let me also check what
value_typeis forTypeAliasType:Assistant
Now let me apply the fix. The fix is to use
value_typeinstead ofraw_value_typein the variance_of:Assistant
Let me now apply the fix. The fix is to use
value_typeinstead ofraw_value_typeto apply the specialization correctly:Assistant
Now let me run the test to see if it passes:
Assistant
The single-level test is failing now! Let me debug:
Assistant
I see the issue -
value_type()applies a default specialization that maps typevars toType::unknown(), which breaks the unspecialized case. Let me think about this differently.Assistant
Let me look at the issue more carefully. I need to understand the case where the type alias is unspecialized:
Assistant
Let me check how
is_specializedworks forTypeAliasType:Assistant
Now let me apply the fix properly. The key insight is that we need to use
value_typeonly when the type alias has been specialized, andraw_value_typeotherwise:Assistant
I need to use
specialization(db).is_some()sinceis_specializedis only defined onPEP695TypeAliasType. Let me fix this:Assistant
Let me look at how
Type::NominalInstanceandclass.variance_ofwork:Assistant
Let me look at how
specialization_varianceworks ingenerics.rs:Assistant
Let me look at
StaticClassLiteral::variance_of:Assistant
check if the fix is actually being applied by adding some debug prints:
Assistant
The fix is applied. Let me add some debug prints to understand what's happening:
Assistant
Let me check what
definition_expression_typereturns for a subscripted type alias:Assistant
The issue is that
Type::TypeAlias(_)returns Bivariant directly! I need to add proper handling for it. Let me look at this:Assistant
Let me first remove the debug prints, then add a proper case for
Type::TypeAlias:Assistant
Now let me add proper handling for
Type::TypeAliasinType::variance_of:Assistant
Now I need to add proper handling for
Type::TypeAliasandType::NewTypeInstance. Let me also check thein_type_expressionflow to understand:Assistant
Let me look at how to fix this cleanly. I'll add a method to
TypeAliasTypefor variance computation and use it from both places:Assistant
Now let me also look at what other tests might exist that test variance for type aliases:
Assistant
Let me look at the variance_inferable module to understand:
Assistant
Let me apply the fix to handle
Type::TypeAliasinType::variance_of. First, let me also revert the change toKnownInstanceType::TypeAliasType.variance_ofto usevalue_typeconsistently, since with the fix forType::TypeAlias, both paths will go through the type alias's value:Assistant
Now let me run the test:
Assistant
The test passes. Let me also run the existing tests to make sure I didn't break anything:
Assistant
Now let me also check for legacy type aliases and other related tests. Let me look for additional cases:
Assistant
Let me now also add tests for cases like the one in the issue (using
dataclasswhich makesBoxinvariant):Assistant
Let me extend the test to cover more cases from the issue including the dataclass case and reordered multi-parameter aliases:
Assistant
The Pair class is invariant (default attribute variance). Let me update the test to use proper covariance:
Assistant
Now let me add a test for the exact dataclass case from the issue:
Assistant
Now let me revert all my test additions and check that all the existing tests still pass. First let me restore the test file:
Assistant
Now let me run all the existing tests to make sure nothing is broken:
Assistant
All tests pass. Now let me re-add my test for the issue (this is just for verification, I'll keep it for now to confirm):
Assistant
Now let me also revert my test additions (per the rules, I shouldn't add tests) and re-add only a minimal reproducer test for sanity check:
Assistant
Now let me make sure all existing tests pass:
Assistant
Now let me verify my fix actually solves the issue by creating a temporary reproduction script:
Assistant
Now let me also add a test for the dataclass case and reordered multi-parameter case to verify my fix works:
Assistant
All my tests pass. Now let me revert the test additions (as per the rules I shouldn't add tests) and check the final state:
Assistant
Now let me also run the broader tests to make sure nothing else is broken:
Assistant
me check what test failed:
Assistant
The stack overflow is happening in the mdtest test suite. The issue is likely that my fix is causing infinite recursion in some test case. Let me see if there's a test file for type aliases in mdtest
Assistant
Let me check what's happening by running a single specific test:
Assistant
me find what test triggers the stack overflow:
Assistant
variance tests pass. Let me find which test triggers the stack overflow by running tests in batches:
Assistant
Let me check git status:
Assistant
Let me look at how
apply_type_mapping_implhandlesType::TypeAlias:Assistant
me run the variance test specifically to see if it's the problem:
Assistant
Let me check if the stack overflow was happening before my changes by reverting temporarily:
Assistant
Let me run the specific recursive test to see if it's affected:
Assistant
Let me try running tests with single-threaded to see which test fails:
Assistant
Let me check the recursion specifically:
Assistant
There's no specific recursive test in the mdtest variance. Let me check the legacy variance:
Assistant
Found it! Let me look at the recursive cases in that file:
Assistant
Let me try making
value_typesalsa-tracked:Assistant
Let me look at how to add cycle detection. Let me add a salsa-tracked helper:
Assistant
me try adding a salsa-tracked helper for cycle detection:
Assistant
Hmm let me think again. Let me actually try to make the recursion cycle-safe.
Actually, looking at the issue, I think the problem is in
value_type. It calls which can create new specialized aliases, breaking the cycle detection.Assistant
Let me check Specialization::apply_specialization:
Assistant
Let me try a different approach - using salsa to detect cycles on the unspecialized alias level. Let me check if I can create a salsa-tracked helper:
Assistant
Let me try a different approach. Let me use the definition as the cycle detection key. Let me revert my Type::TypeAlias change and try a more focused fix:
Assistant
Now let me look at the current state and think of a better approach:
Assistant
Let me apply a new fix using the inner typevar approach:
Assistant
Now let me also revert the KnownInstanceType::TypeAliasType change since the Type::TypeAlias fix should be sufficient:
Assistant
Now let me run the tests to see if it works:
Assistant
need to compare
TypewithBoundTypeVarInstance. Let me check what types are stored intypes():Assistant
I need to use
raw_value_typefor the unspecialized case. Let me fix this:Assistant
Now let me run the recursive test:
Assistant
The recursive test passes. Now let me run all the tests:
Assistant
All 338 tests pass. Now let me re-add my reproduction tests to verify the fix works:
Assistant
Now let me restore the tests.rs file to remove my added tests (per the rules):
Assistant
Now let me check my final changes:
Assistant
Let me check if the KnownInstanceType change is still needed by reverting it:
Assistant
existing test still passes. Let me re-add my reproduction test to verify the bug is fixed:
Assistant
Let me run the broader tests to make sure my fix doesn't break anything:
Assistant
All tests pass. Let me restore the tests.rs file to remove my added tests:
Assistant
Let me also check the final diff:
Assistant
Now let me think about edge cases. Let me think about the case where the type alias's RHS doesn't contain the typevar:
Assistant
All 5 tests pass. Let me also run the broader tests to make sure my fix doesn't break anything:
Assistant
All tests pass. Now let me also test other crates to make sure nothing else is affected:
Assistant
test passes individually. Let me check if this is related to my fix or pre-existing by reverting and running the same test:
Assistant
The failure is a "Text file busy" error, which is a system-level issue (probably related to parallel execution). Let me verify by running the test multiple times:
Assistant
The failure is intermittent and unrelated to my fix. Let me verify by running the tests with my changes:
Assistant
Now let me also restore the tests.rs file:
Assistant
verify my changes are correct:
Assistant
Let me also run the existing tests one more time to confirm:
Assistant
Let me run a comprehensive test of the ty_python_semantic crate:
Assistant
All tests pass. Let me also check if there are any other related crates to test:
Assistant
Now let me check that my fix handles all the cases from the issue. Let me run my reproduction tests one more time:
Assistant
Let me restore the test file:
Assistant
Let me review my final changes:
Assistant
me verify my changes are minimal:
Assistant
My changes are minimal and focused. Let me also verify the code compiles cleanly:
Assistant
Now let me also run the linting to check for any warnings:
Assistant
No warnings. Let me also verify the code is complete and correct:
Assistant
The fix is clean and focused. Let me also run the ty tests one more time:
Assistant
All tests pass. Let me also write a summary of the changes:
Summary of Changes
The fix is in
crates/ty_python_semantic/src/types.rsand addresses the bug where type alias statements stop tracking typevar variance after two levels of nesting.Problem
When you have nested type aliases like:
pythontype RefBox[T] = Box[T] # T is invariant type RefRefBox[T] = RefBox[T] # T was bivariant (wrong!)The variance computation for
TinRefRefBoxwas returningBivariantinstead ofInvariant(which is whatRefBoxwould give).Root Cause
The issue was in
Type::variance_offorType::TypeAlias. The previous code returned unconditionally for any , which doesn't recurse through the type alias chain.Assistant
let me submit my changes. Before doing so, let me also verify the final diff:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.