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 explore the repository structure to understand what we're working with.
Assistant
This is the ruff repository with the
tytype checker. Let me explore the crates to find variance inference logic.Assistant
Now let me look at the generics.rs file which likely handles type alias variance.
Assistant
Let me search for variance inference for type aliases specifically.
Assistant
Let me find the type alias VarianceInferable implementation. Let me look at the type_alias.rs file.
Assistant
Let me look at the typevar.rs file to understand how variance is set on typevars.
Assistant
Let me look at
binding_typeand how type alias definitions work.Assistant
Let me look at the GenericContext and how variance is computed for type aliases.
Assistant
Let me check if TypeAliasType or the alias value has a VarianceInferable impl.
Assistant
Let me check the VarianceInferable impl for the general Type.
Assistant
Let me find the variance_of impl on Type (the enum).
Assistant
Found a key clue -
Type::TypeAlias(_)returnsBivariantdirectly. Let me look at the GenericAlias variance_of impl.Assistant
Let me understand what type the alias value resolves to. Let me look at the type_alias value_type.
Assistant
Let me look at the TypeAliasType enum and its value_type method.
Assistant
Let me build ty first and write a reproduction script.
Assistant
Let me look at the KnownInstanceType variance_of impl which handles
TypeAliasType.Assistant
Let me look at how a subscripted type alias produces a Type.
Assistant
Let me look at how subscript on a type alias produces
Type::TypeAlias.Assistant
Let me look at where a subscript expression
RefBox[T]gets resolved intoType::TypeAlias. Let me look at the subscript inference and look for whereType::TypeAliasis constructed from a known instance type alias with specialization.Assistant
Let me look at known_instance.rs:313 -
Self::TypeAliasType(alias) => Some(Type::TypeAlias(alias)). This is in a method. Let me look at this context.Assistant
Let me build ty to reproduce the issue.
Assistant
Now let me write a reproduction that demonstrates the variance issue via assignability.
Assistant
I need to set the python version. Let me create a local config.
Assistant
The pyproject.toml at /ruff is being used. Let me set the python version via command line or set it in the local config differently. Let me check the CLI options.
Assistant
The relation expands aliases so direct assignability works. Let me look at where
specialization_varianceandbound_typevar.varianceare actually used.Assistant
Let me look at the subtyping path that uses
specialization_variance(lines 1280-1460).Assistant
These are used for specialization subtyping when the alias appears as a type argument. Let me write a repro showing the unsoundness via a covariant container.
Assistant
Let me look at how type aliases are compared for subtyping in relation.rs.
Assistant
Let me look at the variance test files to understand the structure of PEP 695 and legacy aliases.
Assistant
Now I understand the structure. The existing tests use single-level aliases. The bug is with multi-level aliases. Let me now look at the legacy variance test to understand what "legacy generic type aliases" means in this context.
Assistant
Let me look at the ManualPEP695 value_type and check the imports in types.rs.
Assistant
Let me check the imports and the VarianceInferable trait location to plan the implementation.
Assistant
Let me check if
Typeis salsa-interned (which would allow a tracked function taking Type).Assistant
Let me check whether salsa tracked functions can take non-interned args by searching for examples.
Assistant
Let me look at how salsa cycle_initial/cycle_fn signatures work by examining existing examples with multiple args.
Assistant
Let me check the salsa version and its cycle_initial signature to get the closure argument order right.
Assistant
Found it. The
cycle_initialsignature is:fn cycle_initial<$db_lt>(db: &$db_lt Self::DbView, id: ::salsa::Id, ($($input_id),*): ($($interned_input_ty),*)) -> Self::Output<$db_lt>So cycle_initial closure args = (db, id, inputs_tuple). So for a tracked fn with inputs (arg1, arg2), the closure is
|db, id, (arg1, arg2)|.Wait, but the closure syntax in the code is
|_, _, _, _|(flat, not a tuple). Let me look more carefully at how the macro invokes the user's cycle_initial closure.Assistant
Let me check how
VarianceInferableand related types are exported/accessible.Assistant
Let me check how types.rs references type_alias module functions.
Assistant
So types.rs imports
TypeAliasTypefromcrate::types::type_alias. And the module ismod type_alias;. To call a function, I can usecrate::types::type_alias::type_alias_value_variance_of(db, alias, typevar)ortype_alias::type_alias_value_variance_of(...). Sincemod type_alias;is declared in types.rs,type_alias::type_alias_value_variance_ofshould work within types.rs.Wait, but
mod type_alias;declares the module, and within the same file (types.rs) I can refer to it astype_alias::. Let me verify there are existing such references. The grep only found theuseimport. Let me check if any function in types.rs callstype_alias::something. Let me search more broadly.Assistant
Let me check how other private submodules' functions are called from types.rs.
Assistant
Let me check how salsa names configuration structs for tracked methods to ensure no collisions.
Assistant
The Configuration ident is based on
fn_nameonly. Let me check how#[salsa::tracked]impl blocks handle naming to avoid collisions.Assistant
Let me check the
setup_tracked_method_bodymacro to see if Configuration is namespaced by self_ty.Assistant
Let me check the
function_typelogic in salsa to understand which args are valid.Assistant
I now have a clear understanding. Let me look at the area where I'll add the tracked function in type_alias.rs.
Assistant
Now let me update the imports in type_alias.rs and add the tracked function. First, the imports:
Assistant
Now let me add the tracked function. Let me view the end of the TypeAliasType impl block.
Assistant
Now let me update the
Type::variance_ofarm in types.rs.Assistant
Now let me build to check for compilation errors.
Assistant
It compiled. Let me check for
ty_extensionshelpers that can assert variance.Assistant
Let me write a temporary unit test to verify the variance directly, mirroring the existing test. I'll add it temporarily and remove before submitting.
Assistant
Let me check the imports at the top of tests.rs.
Assistant
Let me append the temporary test to tests.rs, run it, then remove it.
Assistant
The temporary test passes. Now let me confirm the test actually catches the bug by temporarily reverting the fix.
Assistant
Let me use git to temporarily revert just the types.rs fix.
Assistant
Confirmed: without the fix,
RefRefCovariantis bivariant (the bug). Let me restore my fix.Assistant
Let me verify the git status and that types.rs has the fix.
Assistant
Good. Now let me re-run the temp test to confirm it passes with the fix restored.
Assistant
The test passes. Now let me remove the temporary test from tests.rs.
Assistant
The temp test is removed. Let me verify tests.rs is back to original state.
Assistant
tests.rs is back to original. Now let me run the existing variance-related tests to ensure nothing is broken.
Assistant
Now let me run the variance mdtest files and broader type-related tests.
Assistant
mdtest binary doesn't exist. Let me check the mdtest crate and how to run mdtests.
Assistant
mdtest is a lib, not a binary. There's a separate way to run mdtests. Let me check the scripts or how mdtests are run. Let me look for a test runner.
Assistant
That's the ruff_linter mdtest. Let me find the ty mdtest runner.
Assistant
The ty mdtests are run via
cargo test -p ty_python_semantic --test mdtest. Let me run the variance-related mdtests.Assistant
Both variance mdtests pass. Let me run a broader set of potentially-affected mdtests (generics, type aliases).
Assistant
Let me run the type_alias and protocols mdtests too.
Assistant
Let me run them with separate filters.
Assistant
All passing. Let me run the full lib test suite for ty_python_semantic to be thorough.
Assistant
All 203 lib tests pass. Let me run the full mdtest suite to be safe.
Assistant
All 338 mdtests pass. Let me also verify the actual issue scenario through a Python repro that exercises the variance path (materialization), and check the changelog conventions.
Assistant
Let me create a Python repro that demonstrates the end-to-end behavior change via a class whose typevar variance is inferred from a multi-level alias field.
Assistant
The static_asserts pass with the fix. Let me confirm that before the fix, this repro would fail (demonstrating the unsoundness).
Assistant
Confirmed: without the fix, the bivariance bug makes
is_subtype_of(C[int], C[str])true (unsound). Let me restore the fix.Assistant
The fix is verified end-to-end. Let me check the changelogs convention to see if I should add a fragment.
Assistant
Let me check if there's an unreleased/pending changelog convention for ty.
Assistant
The changelog requires PR numbers I don't have; I'll skip it to avoid inconsistency. Let me do a final review of my changes.
Assistant
The diff looks clean. Let me run rustfmt to ensure formatting is consistent.
Assistant
Let me apply rustfmt to fix the formatting.
Assistant
rustfmt is happy. Let me view the final diff.
Assistant
Let me do a final build and run the key tests to confirm everything is green after formatting.
Assistant
repro1 reports 1 diagnostic — let me confirm it's the correct invariant rejection (sound behavior), not a syntax/other error.
Assistant
repro2 (class field variance) is the real demonstration and now passes soundly. Let me run the full mdtest suite once more to confirm everything is green after the final build.
Assistant
All 338 mdtests pass. Let me run the full lib test suite once more for final confidence.
Assistant
All tests pass. Let me confirm the final git status — only the two source files should be modified.
Assistant
All checks pass. Only the two source files are modified, with no test residue. Let me do a final review of the complete change 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.