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.
- If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- I have thought about edge cases and made sure my fix handles them as well.
- I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /ruff, current file: none) bash-$
Assistant
Let me start by exploring the repository structure to understand the codebase and find the relevant files related to type alias variance inference.
Assistant
Let me explore the repository structure first.
Assistant
This is the Ruff repository which contains the
tytype checker. Let me explore the structure to find the variance inference code.Assistant
Let me search for variance-related code in the ty crates.
Assistant
Now let me look at the typevar.rs file and the generics.rs file:
Assistant
Let me look at the generics.rs file which handles variance inference:
Assistant
Let me search for the variance_of implementation for type aliases:
Assistant
Let me look for where
TypeAliasTypeor type aliases implementVarianceInferable:Assistant
I don't see a
VarianceInferableimpl forTypeAliasType. Let me look at howTypeimplementsVarianceInferable:Assistant
I found the bug. On line 6854, when a
Type::TypeAliasis encountered during variance inference, it returnsBivariantinstead of recursing into the alias's value type. Let me look at theTypeAliasTypestructure:Assistant
Now let me reproduce the issue. Let me first check how to run the
tytype checker:Assistant
Let me check if there's a pre-built
tybinary:Assistant
Let me look at the existing variance tests to understand the test patterns:
Assistant
Let me look at the
KnownInstanceTypevariance_of implementation:Assistant
Let me look at how variance is computed at the top level and whether there's cycle handling:
Assistant
So
varianceis called onBoundTypeVarInstance, which callsvariance_with_polarity. The variance is computed by looking atbinding_type(db, definition)and then calling.with_polarity(polarity).variance_of(db, self).Now this is a salsa tracked function? Let me check if
varianceorvariance_with_polarityis annotated with#[salsa::tracked].Assistant
Let me look at the
NominalInstanceType::variance_ofimplementation:Assistant
Let me look at how variance is computed for type aliases and whether there's a salsa tracked entry point:
Assistant
Let me look at how the type alias's typevar variance is used in the broader system. Let me search for where variance is checked for type aliases:
Assistant
Let me look at how variance is exposed on
GenericContextand used for type aliases:Assistant
Let me check if
binding_typeis salsa tracked and how the recursion flows:Assistant
Let me look at the
PEP695TypeAliasTypedefinition:Assistant
Let me look at the
ManualPEP695TypeAliasTypedefinition:Assistant
Let me look at the full variance test to understand the expected behavior:
Assistant
Let me check how
GenericAliasis defined (interned or tracked):Assistant
Let me check how
BoundTypeVarInstance,TypeVarVariance, andVarianceInferableare exported:Assistant
Let me check the types module structure:
Assistant
Let me see how
class.rsimportsVarianceInferableand related types:Assistant
Now I have a clear understanding of the issue and the fix. Let me reproduce the issue first by building and running a test. Let me create a reproduction test based on the existing test pattern:
Assistant
Let me build the
tybinary first to reproduce the issue:Assistant
The build succeeded. Now let me create a reproduction Python file:
Assistant
I need to specify a Python version. Let me run with the appropriate flag:
Assistant
Let me write a better reproduction that tests the assignability directly:
Assistant
Let me use the underlying type directly since PEP 695 aliases aren't callable:
Assistant
Interesting - even the first level passes. Let me check the base case with
Boxdirectly:Assistant
Let me use
reveal_typeto understand what types are being inferred:Assistant
Let me use types that are definitely not subtypes (
strvsint):Assistant
Now I can see the error with direct
Box. Theint/floatpassed due to numeric tower. Let me test the alias cases:Assistant
Let me construct a test where alias variance actually matters - comparing two alias instances:
Assistant
The assignment expands the alias. Let me look at where the alias's typevar variance is actually used without expansion:
Assistant
Let me look at how
Type::TypeAliasis handled in the type relation checker:Assistant
Let me search for where specialization pairs are checked for type aliases:
Assistant
Let me look at where the variance is used in inference (lines 1673, 1901):
Assistant
Let me look at the markdown tests related to variance to understand expected behavior:
Assistant
Let me look at the disjointness check for type aliases (line 2388):
Assistant
Let me look at the materialization context where
specialization_varianceis used:Assistant
Let me look at the structure of the tests file to understand how to create a temporary verification:
Assistant
Let me temporarily add a test to confirm the bug, then revert. First let me look at the end of the
type_alias_variancetest to add a temporary repro:Assistant
I've confirmed the bug:
RefRefInvariant(two-level nested alias) returnsBivariantinstead ofInvariant, whileRefInvariant(one level) correctly returnsInvariant. Now let me implement the fix.First, let me update the imports in
type_alias.rs:Assistant
Now let me add the salsa-tracked
value_type_variancemethod toPEP695TypeAliasType. Let me view the relevant section:Assistant
Now let me add the
value_type_variancemethod toPEP695TypeAliasTypeaftervalue_type:Assistant
There's a duplicate comment line. Let me fix it:
Assistant
Let me fix the remaining duplicate and add a blank line:
Assistant
Now let me add the same method to
ManualPEP695TypeAliasType. Let me view that section:Assistant
The edit got messed up - it replaced the wrong line. Let me revert the file and redo carefully:
Assistant
Let me redo the edits using a precise Python script:
Assistant
Now let me add the
value_type_variancemethod toPEP695TypeAliasTypeusing a precise replacement:Assistant
Let me verify the edits look correct:
Assistant
The type_alias.rs edits look good. Now let me update the
Type::TypeAliasarm intypes.rs:Assistant
Now let me update
types.rsto handleType::TypeAliasby recursing, and remove it from the Bivariant arm:Assistant
Now let me check the
KnownInstanceType::TypeAliasTypevariance_of which usesraw_value_type. Let me examine whether it can also be a cycle concern:Assistant
Let me check how
KnownInstanceType::TypeAliasTypeis constructed to understand if it can be specialized:Assistant
The
KnownInstanceType::TypeAliasTypeis always unspecialized, sovalue_typeequalsraw_value_typefor it. To also handle bare self-referential aliases liketype A[T] = A(whereraw_value_typereturns the alias itself, bypassingType::TypeAlias), let me route the entry point through the trackedvalue_type_variancetoo:Assistant
Now let me build to check for compilation errors:
Assistant
It compiled. Now let me run the temporary reproduction test to verify the fix:
Assistant
The one-level case regressed. Let me check what
default_specializationdoes -value_typefor the unspecialized alias might map the typevar to something else:Assistant
I see -
value_typefor the unspecialized entry maps the typevar to unspecialized (losing it), so the entry must useraw_value_type. Let me revert theknown_instance.rschange and add a separate trackedraw_value_type_variancefor the entry point:Assistant
Now let me add
raw_value_type_variancetoPEP695TypeAliasType(usingraw_value_type, which preserves the alias's own typevar):Assistant
Now let me add the
raw_value_type_variancedelegate onTypeAliasType:Assistant
Now let me update the
known_instance.rsentry point to useraw_value_type_variance:Assistant
Now let me build and run the temporary test:
Assistant
The fix works. Now let me run the existing
type_alias_variancetest to ensure I didn't break anything:Assistant
The existing test passes. Now let me test edge cases - recursive, mutually recursive, bare self-reference, and reordered multi-parameter aliases. Let me update my temporary test:
Assistant
All edge cases pass. Let me run the broader test suite - the mdtest variance tests and the full ty_python_semantic test suite:
Assistant
All unit tests pass. Now let me run the mdtest variance tests:
Assistant
Let me run the full mdtest suite to make sure nothing else broke:
Assistant
All 338 mdtests pass. Let me also check the legacy variance mdtest and run the ty binary on the original issue scenario:
Assistant
Now let me rebuild the
tybinary and verify the original issue scenario:Assistant
These errors are due to alias expansion in the relation checker. Let me find where the alias variance actually matters behaviorally. Let me check materialization for type aliases:
Assistant
Most operations expand the alias. The variance inference is the core fix (verified by unit tests). Let me run the broader test suites to ensure nothing breaks - the ty_test and ty_ide crates:
Assistant
All ty_ide tests pass. Let me run the ty_test crate which has the main test framework.
Assistant
Let me run the ty_project tests as well:
Assistant
Let me run all generics mdtests to be thorough:
Assistant
Let me look at the legacy variance mdtest to understand "legacy generic type aliases":
Assistant
Let me verify how legacy
TypeAlias-annotated aliases are represented in ty:Assistant
Legacy
TypeAlias-annotated aliases resolve toGenericAlias(class form), which already handles nesting viaGenericAlias::variance_of. The bug was specifically inType::TypeAlias(PEP 695typestatement andtypes.TypeAliasType), which I've fixed.Now let me clean up the temporary test from
tests.rs:Assistant
Let me verify the tests.rs has no changes and check the overall diff:
Assistant
Let me review the full diff to ensure correctness:
Assistant
The diff looks clean. Let me run a final build and the key tests to confirm everything works after cleanup:
Assistant
Let me run clippy on the changed crate to ensure no lint issues:
Assistant
Clippy passes. Let me run rustfmt to ensure proper formatting:
Assistant
Let me apply rustfmt formatting:
Assistant
Formatting is clean. Let me do a final review of the formatted
type_alias.rschanges:Assistant
The diff looks clean. Let me clean up temp files and run a final comprehensive verification:
Assistant
Let me do a final comprehensive test run on the affected crate to confirm the submitted state is good:
Assistant
Let me re-add the comprehensive edge-case test one final time to be 100% sure the fix handles all contract cases, then remove it:
Assistant
All edge cases pass, including forward-referenced alias chains (where the referenced alias is defined later). Let me remove the temporary test:
Assistant
Let me do a final build to confirm the final state compiles cleanly:
Assistant
The fix is complete and all tests pass. Let me verify the final diff one more time before submitting:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →
Qwen/Qwen3.6-27BCompare side by side →