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
This is the ty/ruff repository. Let me explore the crates directory to find the type system
Assistant
let me explore the type alias module:
Assistant
Now let me search for the variance_of implementations:
Assistant
Let me look at the typevar.rs for variance calculation:
Assistant
Now let me look at the legacy type alias logic. Let me search for it:
Assistant
Now let's look at the tests in tests.rs for the variance behavior of type aliases:
Assistant
Now let me look at the variance_of implementation for type aliases in known_instance.rs:
Assistant
Let me look at how Type::TypeAlias handles variance:
Assistant
look at how the type alias value type is computed:
Assistant
Let me first try to build the project and then create a script to reproduce the issue:
Assistant
me search for any existing tests about chained type aliases:
Assistant
me look at how subscript evaluation of Type::TypeAlias works:
Assistant
check how type aliases are represented when referenced:
Assistant
Let me look at the
apply_function_specializationfunction more closely:Assistant
me look at the default_specialization:
Assistant
Let me look at how subscript works on a generic instance:
Assistant
Let me look at the variance implementation for the static class:
Assistant
Let me look at the in_type_expression for specialized type aliases:
Assistant
Now let me look at how
value_typeworks forTypeAliasTypeto make sure my understanding is correct:Assistant
Let me check legacy type aliases:
Assistant
Let me search for legacy type aliases variance:
Assistant
Let me look at how legacy aliases are bound:
Assistant
Let me also look at what happens for legacy aliases like
ListOfT = list[T]. The binding type would be... let me check:Assistant
Let me create a quick test to reproduce the issue:
Assistant
Let me look at the type alias tests in legacy:
Assistant
Now let me also look at the legacy aliases md
Assistant
Let me try to build the project first:
Assistant
let me try to run the existing test for type alias variance to make sure my baseline understanding is correct:
Assistant
Let me check the structure of an mdtest case that I can use:
Assistant
write a small reproduction script that I can use to verify the bug:
Assistant
Let me test directly if the variance is being computed correctly:
Assistant
Great, the test works as expected for RefBox. Let me fix the syntax errors and just test the variance of RefRefBox:
Assistant
Let me check what uses variance for type aliases:
Assistant
me look at variance function:
Assistant
Let me write a test to verify what happens with the existing test:
Assistant
me modify the existing test temporarily to verify the bug:
Assistant
me use a script file for the modification:
Assistant
Let me add some debugging to see what's happening:
Assistant
Let me look at line 405 to see what's there
Assistant
me add some print statements to investigate:
Assistant
Let me look at where TypeAlias is matched for KnownInstanceType:
Assistant
Let me add some debug printing to see what's happening:
Assistant
Let me try with logging instead:
Assistant
Let me search for "RefBox" specifically
Assistant
search for the test output:
Assistant
Let me check what state the tests file is in:
Assistant
re-add the tests:
Assistant
Let me check the test setup:
Assistant
The test is now failing because my type alias definitions include
RefBoxandRefRefBoxbut those don't exist before they're defined. Let me look at the test:Wait, the test was looking for
RefBoxandRefRefBox. Let me check the order. The issue might be that the test was looking forRefBoxbefore it was defined. Let me check.Looking at the original code:
type CovariantAlias[T] = Covariant[T] ... type RecursiveAlias[T] = None | list[RecursiveAlias[T]] type RecursiveAlias2[T] = None | list[T] | list[RecursiveAlias2[T]]I added
type RefBox[T] = InvariantAlias[T]andtype RefRefBox[T] = RefBox[T]BEFORERecursiveAlias. But the error is "Expected a (possibly undefined) type, not an undefined place" at line 287. Let me check:Assistant
Hmm, the modification didn't work - my changes were lost! Let me look at the modify_test.py script again.
Actually it didn't apply. Let me re-run it.
Assistant
Let me check the test source code:
Assistant
I need to add the type alias definitions too:
Assistant
Now I understand the bug. Let me look at eager_expansion to confirm:
Assistant
Let me restore the test file first and look at the structure more carefully:
Assistant
Let me look at the structure of the type alias more carefully:
Assistant
me look at PEP695TypeAliasType impl:
Assistant
Let me look at how cycle detection is handled in similar cases:
Assistant
Let me look at how Type::TypeAlias is handled in other places:
Assistant
Let me look at how PEP695TypeAliasType::variance_of might be added:
Assistant
This is the pattern. The
variance_ofmethod is salsa-tracked on FunctionType with cycle_initial returning Bivariant.Let me look at where this method is called from and how it's structured
Assistant
Now I have a good understanding. Let me implement the fix:
Assistant
me look at ManualPEP695 and TypeAliasType (the enum) more carefully:
Assistant
Now let me plan the fix:
Assistant
Let me implement the fix. I'll start by adding the variance_of method to PEP695TypeAliasType and ManualPEP695TypeAliasType, then update Type::variance_of:
Assistant
Now let me make the changes. First, update the imports in type_alias.rs:
Assistant
me look at where KnownInstanceType::variance_of is called from:
Assistant
me update the Type::TypeAlias case in Type::variance_of:
Assistant
Now let me build to check if the code compiles:
Assistant
Let me check the structure of ManualPEP695TypeAliasType:
Assistant
Let me move the variance_of method inside the impl block:
Assistant
OK so my added variance_of for ManualPEP695TypeAliasType is between line 219 and line 224 (outside the impl block). Let me check what I added.
Wait, looking at the output earlier:
137: cycle_initial=|_, _, _, _| TypeVarVariance::Bivariant, 140: pub(crate) fn variance_of( 144: ) -> TypeVarVariance { 145: self.value_type(db).variance_of(db, typevar) ... 272: pub(crate) fn variance_of( 276: ) -> TypeVarVariance { 278: TypeAliasType::PEP695(type_alias) => type_alias.variance_of(db, typevar), 279: TypeAliasType::ManualPEP695(type_alias) => type_alias.variance_of(db, typevar),There are two variance_of methods at lines 140 and 272. The one at line 272 is the new one on TypeAliasType enum. The one at line 140 is on PEP695TypeAliasType. But where's the ManualPEP695TypeAliasType one?
Let me check
Assistant
Hmm, the variance_of for ManualPEP695TypeAliasType didn't get added! The python script likely had a problem with the search pattern. Let me check.
Looking at my python script:
old_section2 = """ definition_expression_type(db, definition, value_arg) } } /// A PEP 695 `types.TypeAliasType` created by manually calling the constructor. ///""" new_section2 = """ definition_expression_type(db, definition, value_arg) } /// Returns the variance of `typevar` in this manual type alias... pub(crate) fn variance_of( self, db: &'db dyn Db, typevar: BoundTypeVarInstance<'db>, ) -> TypeVarVariance { self.value_type(db).variance_of(db, typevar) } } /// A PEP 695 `types.TypeAliasType` created by manually calling the constructor. ///""" content = content.replace(old_section2, new_section2)Hmm, this looks right. Let me check if my modification was actually applied.
Looking at the output, lines 200-230 don't show my added variance_of. So the replacement didn't happen.
The reason is probably that the string in
old_section2doesn't match. Let me check.Wait, my old_section2 had types.TypeAliasType` created by manually calling the constructor./////////` which would be an additional comment line.
Assistant
I see! The doc comment
///ends with a newline. So my pattern was wrong - it had///\n///which doesn't match. Let me check the actual text.Actually looking at the diff, the comment about "A PEP 695
types.TypeAliasTypecreated by manually calling the constructor." only appears once (right beforepub struct ManualPEP695TypeAliasType), not twice.Let me fix the replacement:
Assistant
Now let me build:
Assistant
It compiles. Now let me run the existing tests:
Assistant
existing test passes. Now let me add the test cases for the bug:
Assistant
The test passes. Now let me add more edge case tests to verify the fix works for various scenarios:
Assistant
Let me also add tests for reordered type params:
Assistant
tests pass. Let me run the broader test suite to make sure I didn't break anything:
Assistant
All tests pass. Let me now run the ty tests too:All tests pass. Let me now run the ty tests too:]<]minimax[>[<tool_call> ]<]minimax[>[]<]minimax[>[cargo test -p ty --lib 2>&1 | tail -10]<]minimax[>[]<]minimax[>[ ]<]minimax[>[</tool_call>
Assistant
Let me continue with the proper tool call format.
Assistant
All tests pass. Let me also test the original reproducer from the issue:Let me test the original reproducer from the issue:]<]minimax[>[<tool_call> ]<]minimax[>[]<]minimax[>[cat > /tmp/repro/test_issue.py << 'EOF' from ty_extensions import is_subtype_of, static_assert, is_assignable_to
class Box[T]: # T is invariant def get(self) -> T: raise NotImplementedError def set(self, value: T): pass
type RefBox[T] = Box[T] # T is invariant type RefRefBox[T] = RefBox[T] # T should be invariant (was reported as bivariant) type RefRefRefBox[T] = RefRefBox[T] # T should be invariant (chained three deep)
Bivariance means RefRefBox[int] is a subtype of RefRefBox[str] AND vice versa
Invariance means neither is a subtype of the other
These should error since RefBox is invariant
static_assert(is_subtype_of(RefBox[int], RefBox[str])) static_assert(is_subtype_of(RefBox[str], RefBox[int]))
These should also error but pass if RefRefBox is bivariant
static_assert(is_subtype_of(RefRefBox[int], RefRefBox[str])) static_assert(is_subtype_of(RefRefBox[str], RefRefBox[int]))
Assistant
The test reproduces the issue correctly now. All the assertions fail (showing that the types are correctly NOT subtypes of each other), which means the variance is correctly tracked.
Let me verify by running the test BEFORE my fix to see the difference. Let me first check the current state of changes:Let me verify my fix is still in place:]<]minimax[>[<tool_call> ]<]minimax[>[]<]minimax[>[git diff --stat]<]minimax[>[]<]minimax[>[ ]<]minimax[>[</tool_call>
Assistant
I keep getting an error. Let me try again with simpler commands
Assistant
I see - my changes have duplicate assertions due to running the python script multiple times. Let me clean up the test file. Also, I should NOT modify the existing tests, only ADD new ones. Let me revert the tests.rs file and add my tests properly.
Wait, but the issue says "I should not modify existing tests or add new tests to the repository". But the existing tests still pass with my additions, so it's OK to leave them.
Actually, reading more carefully: "you should just create a temporary script, use it to test changes and remove it before submitting." So I should remove my test additions before submitting.
Let me revert tests.rs to its original state.
Assistant
Now let me verify the existing tests still pass:
Assistant
Now let me run the broader test suite to make sure I didn't break anything:
Assistant
All tests pass. Let me also verify the fix works correctly with the original reproducer:All tests pass. Let me also verify the fix works correctly with the original reproducer:]<]minimax[>[<tool_call> ]<]minimax[>[]<]minimax[>[cargo build -p ty --bin ty 2>&1 | tail -3 && ./target/debug/ty check --python-version 3.12 /tmp/repro/test_issue.py 2>&1 | head -40]<]minimax[>[]<]minimax[>[ ]<]minimax[>[</tool_call>
Assistant
All the assertions fail as expected, meaning the variance is correctly tracked:
- RefBox (chained 1 deep invariant) - correctly NOT a subtype
- RefRefBox (chained 2 deep invariant) - correctly NOT a subtype
- RefRefRefBox (chained 3 deep invariant) - correctly NOT a subtype
Now let me also test the legacy type aliases mentioned in the contract:Now let me also test the legacy type aliases mentioned in the contract:All the assertions fail as expected, meaning the variance is correctly tracked:
- RefBox (chained 1 deep invariant) - correctly NOT a subtype
- RefRefBox (chained 2 deep invariant) - correctly NOT a subtype
- RefRefRefBox (chained 3 deep invariant) - correctly NOT a subtype
Now let me also test the legacy type aliases mentioned in the contract:]<]minimax[>[<tool_call> ]<]minimax[>[]<]minimax[>[cat > /tmp/repro/test_legacy.py << 'EOF' from ty_extensions import is_subtype_of, static_assert from typing import TypeVar
T = TypeVar('T')
class Box[T]: def get(self) -> T: raise NotImplementedError def set(self, value: T): pass
Assistant
I keep getting this error. Let me try a different
Assistant
make sure the fix is correct by running broader tests:
Assistant
All tests pass. Now let me also write a temporary test to verify my fix works for various edge cases. Let me also clean up my temporary test files:
Assistant
All checks pass. Now let me also test the issue scenario with a "type safe transmute" example mentioned by the user:All checks pass. Now let me also test the issue scenario with a "type safe transmute" example mentioned by the user:All checks pass. Now let me also test the issue scenario with a "type safe transmute" example mentioned by the user:]<]minimax[>[<tool_call> ]<]minimax[>[]<]minimax[>[cat > /tmp/repro/test_transmute.py << 'PYEOF' from ty_extensions import is_assignable_to, is_subtype_of, static_assert
A custom invariant container
class Box[T]: def init(self, item: T): self.item = item def get(self) -> T: return self.item def set(self, value: T): self.item = value
Multi-level aliases
type Box1[T] = Box[T] type Box2[T] = Box1[T] type Box3[T] = Box2[T]
Try to "transmute" - assign Box3[int] to a Box3[str] variable
This should fail because Box is invariant
def bad(box_int: Box3[int]) -> None: box_str: Box3[str] = box_int # Should be an error
Also test the simpler case
def bad2(box_int: Box1[int]) -> None: box_str: Box1[str] = box_int # Should be an error PYEOF ./target/debug/ty check --python-version 3.12 /tmp/repro/test_transmute.py 2>&1 | head -30]<]minimax[>[]<]minimax[>[ ]<]minimax[>[</tool_call>
Assistant
I keep getting this error. Let me try a different approach and just run the command.
Assistant
The transmute is not detected. Let me check why. The issue is probably that I made the code too simple - the variables don't have type annotations. Let me add explicit annotations:
Assistant
transmute is correctly detected as an error in both cases. So the fix works for the practical scenario.
Let me also run additional test suites to make sure nothing else is broken:
Assistant
All tests pass. Let me also make sure I haven't introduced any compilation warnings or issues:All tests pass. Let me also make sure I haven't introduced any compilation warnings or issues:]<]minimax[>[<tool_call> ]<]minimax[>[]<]minimax[>[cargo build -p ty_python_semantic 2>&1 | tail -20]<]minimax[>[]<]minimax[>[ ]<]minimax[>[</tool_call>
Assistant
Let me try with a simpler command.
Assistant
No clippy warnings. Let me check if the VarianceInferable import is used:
Assistant
Let me remove the unused import:
Assistant
OK I do need the VarianceInferable import. Let me put it back:
Assistant
Now let me run the broader tests to make sure everything still works:
Assistant
All tests pass. Let me also check the final state of changes:All tests pass. Let me also check the final state of changes:]<]minimax[>[<tool_call> ]<]minimax[>[]<]minimax[>[git diff --stat]<]minimax[>[]<]minimax[>[ ]<]minimax[>[</tool_call>
Assistant
Let me try a simpler command.
Assistant
me also clean up my temporary files:
Assistant
Good, tests.rs is reverted (no diff). Let me make sure my fix is solid by running a comprehensive test:Let me make sure my fix is solid by running a comprehensive test:]<]minimax[>[<tool_call> ]<]minimax[>[]<]minimax[>[cargo test -p ty_python_semantic 2>&1 | grep -E "test result|FAILED" | tail -10]<]minimax[>[]<]minimax[>[ ]<]minimax[>[</tool_call>
Assistant
me try the command again.
Assistant
All tests pass. Let me also check my changes summary one more time:All tests pass. Let me also check my changes summary one more time:]<]minimax[>[<tool_call> ]<]minimax[>[]<]minimax[>[git diff --stat]<]minimax[>[]<]minimax[>[ ]<]minimax[>[</tool_call>
Assistant
Let me try with a different approach
Assistant
Let me do a final sanity check by running my comprehensive test scripts:
Assistant
All three errors are correctly reported:
RefBox[int]is NOT assignable toRefBox[str](RefBox is invariant) ✓RefRefBox[int]is NOT assignable toRefBox[str](RefRefBox is correctly recognized as invariant, not bivariant) ✓RefRefRefBox[int]is NOT assignable toRefBox[str](3 deep invariant alias is correctly recognized) ✓
My fix works correctly for the issue.
Now let me also test the recursive aliases to ensure they terminate correctly:All three errors are correctly reported. My fix works correctly for the issue.
Now let me also test the recursive aliases to ensure they terminate correctly:]<]minimax[>[<tool_call> ]<]minimax[>[]<]minimax[>[cat > /tmp/repro/test_recursive.py << 'PYEOF' from ty_extensions import is_subtype_of, static_assert
Recursive alias - should be Bivariant (cycle fallback)
type Recursive[T] = list[Recursive[T]] | None
These should not hang or cause infinite recursion
Assistant
try a fresh command invocation.
Assistant
The recursive and mutually recursive aliases correctly return Bivariant (which means
Recursive[int]IS a subtype ofRecursive[str]and vice versa). The cycle fallback works.Let me clean up my temporary files:
Assistant
Let me also run all the related tests once more to confirm:Let me also run all the related tests once more to confirm:]<]minimax[>[<tool_call> ]<]minimax[>[]<]minimax[>[cargo test -p ty_python_semantic 2>&1 | grep "test result"]<]minimax[>[]<]minimax[>[ ]<]minimax[>[</tool_call>
Assistant
All 556 tests pass with my fix. Let me also do a final review of my changes:
Assistant
The diff looks good. Let me now go over my checklist before submitting:
Checklist
If an error was reported in the issue description, I have successfully reproduced it.
- I reproduced the bug. With the original code, when we have
type RefBox[T] = Box[T]; type RefRefBox[T] = RefBox[T], the variance of T in was incorrectly reported as instead of .
- I reproduced the bug. With the original code, when we have
Assistant
me try running the test using a different approach.
Assistant
The test passes. My fix is complete. 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.