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
Now let's make the fix:
Assistant
Now let's implement the tracked variance_of for PEP695TypeAliasType and ManualPEP695TypeAliasType, plus dispatch on TypeAliasType enum.
Assistant
Now let's do the same for ManualPEP695TypeAliasType, and add the dispatch impl for TypeAliasType.
Assistant
Now let's add the
VarianceInferabledispatch impl forTypeAliasTypeenum:Assistant
Insert the trait impl right after line 341 (end of
impl<'db> TypeAliasType<'db>block).Assistant
Now update the
Type::TypeAlias(_)arm in types.rs to dispatch through this trait impl:Assistant
Now let's build to catch compile errors.
Assistant
Compiles cleanly. Now let's run the existing variance test and write a reproduction test for the issue.
Assistant
Existing test passes. Now let's write a small script to reproduce the exact issue scenario (2-level type alias chain) and verify with a temporary test binary.
Assistant
Good, imports already available (super::* brings TypeAliasType, KnownInstanceType, VarianceInferable, etc.). Let's run the test.
Assistant
We need python-version set. Let's create pyproject.toml or pass --python-version flag.
Assistant
The fix now correctly reports the invariance violation for
RefRefBox. Let's confirm this error was NOT reported before the fix (i.e., verify the bug existed) by checking out the original code temporarily.Assistant
Good, tests.rs is restored to original. Now let's run the full relevant test suite to make sure nothing broke.
Assistant
All lib tests pass. Now let's run the mdtest suite (which includes pep695_type_aliases.md and other alias-related tests) to make sure nothing regressed.
Assistant
All 338 mdtests pass. Let's also run the broader workspace test suite briefly (at least ty crate tests) to be safe, and check for clippy warnings on the changed files.
Assistant
No warnings. Let's view the final diff to review the change set.
Assistant
Let's verify legacy
TypeAliasType(...)generic aliases work correctly too with a temporary check, and multi-level chains combining both PEP 695 and manual.Assistant
With the fix, correctly
(Never, /) -> objectand(object, /) -> Never. Now let's check pre-fix (original code) behavior to see if it was wrong (bivariant would ignore contravariance, and materialize both as covariant perhaps).Assistant
Let's specifically test mutual recursion without an intervening generic container (the riskiest case for infinite recursion) to make sure it terminates safely.
Assistant
No hang this time — matches pre-fix behavior. The earlier timeout was likely due to concurrent build contention (cargo build + cargo run running near-simultaneously). Let's re-run a couple more times to be safe, and also re-run the original repro to confirm everything still works correctly.
Assistant
Good, consistent and correct (exit code 1 just reflects errors present, which is expected/unrelated). No hangs across multiple runs. Let's run a stress test with a longer mutual recursion chain and deeper nested reordering to be extra sure about termination and correctness.
Assistant
Build is fine and fast now. Let's retry the generic_class.py repro directly (already built).
Assistant
Excellent! This confirms the bug precisely: pre-fix,
Container[int]was (incorrectly) bidirectionally assignable toContainer[object](bivariant treatment), and post-fix it's correctly rejected both ways (proper invariance). Let's rebuild with the fix and do a final full confirmation plus a stress-retest for stability (no flaky hangs).Assistant
Stable and consistent. Now let's also test covariant/contravariant/bivariant multi-level chains end-to-end similarly, and reordered multi-param, and mutual recursion once more for stability (already confirmed no hang).
Assistant
All checks pass now, confirming correct variance propagation across covariant, contravariant, invariant, bivariant, multi-level chains, and reordered multi-parameter aliases. Let's re-run the full test suite one more time as a final sanity check.
Assistant
All tests pass. Let's do a final review of the diff and ensure the repository is clean of temporary artifacts.
Assistant
Clean diff, no leftover test modifications. Let's clean up temp repro files (outside repo, not tracked) - not necessary but let's tidy up anyway.
Assistant
Now let's go through the checklist explicitly.
Assistant
Everything compiles cleanly and passes lint. Now the checklist:
-
If an error was reported in the issue description, I have successfully reproduced it. Yes — I reproduced the exact "variance forgotten after two levels of
typealiasing" bug using aContainer[T]generic class whose method returns a two-level alias chain (RefRefBox[T] = RefBox[T] = Box[T], whereBoxis invariant). With the original code,is_assignable_to(Container[int], Container[object])and its reverse were bothTrue(i.e., treated as bivariant), which is wrong since is invariant.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.