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 understanding the repository structure and the issue. The issue is about type alias statements not properly tracking TypeVar variance after more than one level of aliasing. For example:
type RefBox[T] = Box[T] # T is invariant type RefRefBox[T] = RefBox[T] # T is bivariant???When
RefRefBox[T] = RefBox[T], the variance of T should be invariant (since it ultimately resolves toBox[T]where T is invariant), but it's being treated as bivariant.The issue is in a type checker called "ty" (or "ruff" based on the directory name). Let me explore the repository to understand its structure and find the relevant code.
Let me start by exploring the repo structure.
Assistant
This appears to be a Rust repository (likely "ty" or "ruff"). Let me explore the crate structure and search for relevant code about type alias variance.
Assistant
The
tycrate is likely the type checker. Let me search for variance-related code:Assistant
Let me look at the variance module and also search for type alias variance tracking
Assistant
Let me look at the variance.rs file first and search for type alias related variance code.
Assistant
Now let me find where
VarianceInferableis implemented for type aliases:Assistant
Let me look at the main
Typevariance implementation and also search for type alias related typesAssistant
Let me look at the type alias module and the variance implementation for type aliases:
Assistant
Let me look at the type_alias.rs file and also the variance test case.
Assistant
Let me look at the
VarianceInferableimplementation forTypein types.rs around line 6784:Assistant
I found the issue! On line 6869 (approximately),
Type::TypeAlias(_)is hardcoded to returnTypeVarVariance::Bivariant. The fix should resolve through the type alias to its underlying value type. Let me understand theType::TypeAliasstructure better:Assistant
Let me look at how
KnownInstancehandlesTypeAliasTypein variance_of to understand the full flow:Assistant
Let me look at the variance_of implementation for KnownInstanceType
Assistant
Let me look at the existing variance test for type aliases to understand the test setup:
Assistant
Now I understand the issue. Let me look at the exact line where
Type::TypeAliasreturnsBivariant:Assistant
Let me see the exact context around line 6870:
Assistant
Now I understand the issue clearly. The
Type::TypeAlias(_)variant returnsBivariantunconditionally, but it should recurse into the alias's underlying value type to determine the correct variance. Let me make the fix:Assistant
Let me navigate to line 6870 first
Assistant
Now I need to modify the code. I'll extract
Type::TypeAliasinto its own match arm that recurses into the alias's value type:Assistant
Wait, the
|prefix makes it look like a continuation of the previous arm. I need to make it a separate match arm. Let me fix thatAssistant
Let me check that
TypeAliasTypeandraw_value_typeare accessible in thetypes.rsmodule:Assistant
Good,
TypeAliasTypeis imported. Let me verify theraw_value_typemethod is accessible:Assistant
Now let me build the project to check for compilation errors:
Assistant
I see the issue. The previous match arm (
Type::TypedDict(_)) doesn't have its=>resolution. It was previously combined withType::TypeAlias(_)andType::NewTypeInstance(_)into one arm. Let me fixAssistant
I need to restructure: add
=> TypeVarVariance::Bivariant,afterTypedDict, keepNewTypeInstancein the bivariant list, and haveTypeAliasas a separate arm. Let me fix lines 6869-6871:Assistant
Now let me try building again:
Assistant
Build succeeded. Now let me run the existing tests related to type alias variance:
Assistant
The existing test passes. But the test uses
KnownInstanceType::TypeAliasTypedirectly, notType::TypeAlias. Let me check if there are any other tests that exercise this code path, and also create a reproduction script.Let me first look at all the test functions in the tests module:
Assistant
Let me create a small reproduction script to verify my fix works. First, let me understand the test infrastructure:
Assistant
Let me run the broader test suite for
ty_python_semanticto make sure nothing is broken:Assistant
There's a stack overflow - my fix causes infinite recursion for recursive type aliases. Let me investigate the cycle handling. Let me understand the issue better by looking at
cycle_normalized:Assistant
Let me look at the
Type::cycle_normalizedimplementation:Assistant
Let me understand the flow better by looking at how type alias references are resolved:
Assistant
Let me look at the
definition_expression_typefunctionAssistant
Let me search for the function
Assistant
Hmm, let me try a broader search.
Assistant
Let me look at this function
Assistant
Let me look at the
CycleDetectortype that's already used in the codeAssistant
Let me look at the
CycleDetectorto understand the cycle detection mechanism:Assistant
Let me look at the existing tests more carefully to see if multi-level aliases are tested:
Assistant
Let me check how
Type::TypeAliasis constructed in the inference system:Assistant
Let me look at the subscript handling for
TypeAliasat line 533:Assistant
Let me look at how subscript on
KnownInstanceworks, particularly forTypeAliasType:Assistant
Let me search for how type alias names are resolved in expressions:
Assistant
Let me look at the full subscript function from the beginning:
Assistant
Let me see what happens with
Type::KnownInstancein the subscript match:Assistant
Let me see the subscript handling for TypeAliasType at line 726:
Assistant
Let me find where subscript on generic type aliases is handled:
Assistant
I see the issue now. The fix needs cycle detection to prevent infinite recursion for recursive type aliases. Let me implement a solution using a thread-local set to track seen aliases during variance computation.
Assistant
Let me look at the imports at the top of types.rs:
Assistant
Let me check where
variance_ofis called from:Assistant
Let me implement a cycle-detecting fix. I'll use a thread-local to track seen aliases during variance computation. First, let me check the imports I'll need:
Assistant
Let me check if thread_local is used elsewhere in the codebase:
Assistant
Let me look at how thread_local is used in function.rs for reference:
Assistant
Let me verify the current state of my edit:
Assistant
Now I'll implement the cycle detection fix. Let me:
- Add the
ActiveRecursionDetectorimport - Add a thread_local for cycle detection
- Modify the
Type::TypeAliasarm to use cycle detection
First, let me add the import:
- Add the
Assistant
Let me add the
ActiveRecursionDetectorimport and make the fix:Assistant
Now let me find where the
VarianceInferableimpl forTypestarts:Assistant
Let me check how
RecursiveTypeNormalizationKeyworks in function.rs to understand the lifetime pattern:Assistant
Let me look at
RecursiveTypeNormalizationKey:Assistant
Let me check how salsa interned IDs work:
Assistant
Let me look at how the interned types are used:
Assistant
Let me check the salsa interned type API:
Assistant
Let me look at how salsa interned types expose their ID:
Assistant
Let me check what
last_definitionis:Assistant
Let me check what methods are available on
PEP695TypeAliasType:Assistant
Let me take a simpler approach. I'll use
salsa::Idas the key for cycle detection. Let me check if I can access the salsa ID from the interned types:Assistant
Let me write a quick test to see if I can call
.as_id()on these types:Assistant
Let me look at the
eager_expansiontest to understand type alias resolution:Assistant
Let me look at
expand_eagerlyto see how it handles resolution through type aliases:Assistant
Let me look at expand_eagerly:
Assistant
Let me implement the thread-local approach with proper cycle detection. I'll use
unsafetransmute for the lifetime since we properly manage scoping:Assistant
Let me check how to get a salsa ID from the type alias. Let me look at how
OverloadLiteral.as_id()is defined:Assistant
Let me find the OverloadLiteral definition:
Assistant
Let me check how OverloadLiteral is defined:
Assistant
Let me implement the cycle-detecting fix. I'll add a thread-local for cycle detection and modify the
Type::TypeAliasarm:Assistant
I have a duplicate line. Let me fix that:
Assistant
Now let me update the
Type::TypeAliasarm to use the cycle detection:Assistant
Now let me update the
Type::TypeAliasarm to use cycle detection:Assistant
Let me build to check for compilation errors:
Assistant
There's a warning about unsafe code. Let me check if the project denies unsafe code:
Assistant
Let me check the lib.rs file for ty_python_semantic for unsafe_code settings
Assistant
Let me check what traits salsa interned types implement:
Assistant
Let me check how salsa::Id is defined:
Assistant
Let me check the Cargo.toml for ty_python_semantic to see if unsafe is denied:
Assistant
Let me check the workspace lints:
Assistant
Let me search for lints in the root Cargo.toml:
Assistant
Let me try a cleaner approach without unsafe. Let me use the salsa interned
as_id()to create a key:Assistant
Let me use a cleaner approach with
salsa::Idas the key instead of unsafe transmute. Let me check ifas_id()is available:Assistant
Let me use a cleaner approach using
definition().as_id()as the cycle key, avoiding unsafe code:Assistant
Now update the
Type::TypeAliasarm:Assistant
Now let me build:
Assistant
I need to import
AsIdtrait. Let me add it:Assistant
Let me check how salsa is accessed:
Assistant
Let me use the full path for
AsId:Assistant
Let me build again
Assistant
Let me check how
as_id()is imported in function.rs:Assistant
Let me see the imports in function.rs:
Assistant
I need to use
salsa::plumbing::AsId. Let me update:Assistant
Let me build
Assistant
It compiles! Now let me run the tests:
Assistant
Let me try a different filter:
Assistant
Let me now run the broader test suite to make sure nothing is broken:
Assistant
All tests pass! Let me also run the broader test suite for
ruffto make sure nothing else is broken:Assistant
All tests pass. Let me check the final diff to review my changes:
Assistant
The diff looks correct and clean. Let me verify the changes once more by running all tests one final time:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.