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 first to understand what we're working with.
Assistant
This is the ruff repository with the "ty" type checker. The issue is about type alias statements not tracking typevar variance after two deep. Let me find the relevant code about variance inference and type aliases.
Assistant
Now let me look at the generics.rs file which probably contains the variance inference for type aliases.
Assistant
Let me search for the variance inference logic for type aliases specifically.
Assistant
Let me look at how variance is computed for type aliases. Let me search for where
varianceis computed/stored for type aliases, and theVarianceInferableimplementations.Assistant
Now let me find the
VarianceInferableimplementation forType(the main type enum) and forTypeAliasType.Assistant
No matches found. Let me find where the
VarianceInferablefor theTypeenum is implemented.Assistant
Let me look at where variance is computed for type aliases. Let me search more broadly.
Assistant
So
variance_with_polaritycallsbinding_type(db, definition).with_polarity(polarity).variance_of(db, self). Thebinding_typeis what the typevar is bound to (the value of the generic). For a class generic likeBox[T], the binding type is... the class itself? Let me understand.Actually,
binding_typeis the type the typevar is bound to. Forclass Box[T], what is thebinding_type? Let me look.Assistant
So
binding_typereturns the type that the typevar is bound to. For a type aliastype RefBox[T] = Box[T], the typevarT's binding context is the definition ofRefBoxand the binding type is the value type of the alias (i.e.Box[T]). ForBox[T](a class), the binding type is the class type.Now
variance_with_polaritycallsbinding_type(db, definition).with_polarity(polarity).variance_of(db, self). So the variance ofTinRefBoxis computed by looking at the variance ofTin the value typeBox[T]. The value type isBox[T], aNominalInstanceofBoxwithTas type arg. Thevariance_offorNominalInstanceTypewould look at the variance ofTinBox's specialization. That should work for one level.But for
type RefRefBox[T] = RefBox[T], the value type isRefBox[T]. What isRefBox[T]? It's aTypeAliasspecialization. Let me look at how the value type of a PEP 695 alias is represented.Let me look at the
VarianceInferableimplementation for - the main enum. Actually let me find the .Assistant
I found the issue! Look at the
Type::TypeAlias(_)arm in the list of types that returnTypeVarVariance::Bivariant. When computing the variance of a typevar in aTypeAliasvalue type, thevariance_ofreturnsBivariantimmediately, without recursing into the alias value. Let me verify the structure of type aliases.Assistant
Now let me look at the
TypeAliasTypeenum and theType::TypeAliasvariant.Assistant
I found the issue. In the
VarianceInferableimpl forType, theType::TypeAlias(_)arm returnsBivariantwithout recursing into the alias value. Let me first reproduce the issue. Let me check how to run ty.Assistant
Let me look at how to build and run ty, and find relevant test patterns for type alias variance.
Assistant
Let me check if there's a way to run ty. Let me try building the ty binary (might take a while).
Assistant
Let me look at the existing variance tests to understand the test format.
Assistant
Now let me look at the
KnownInstanceType::TypeAliasTypevariance_of implementation, since that's what the tests call.Assistant
Let me look at how the cycle handling works and the
eager_expansiontest.Assistant
So
expand_eagerlyuses the Salsa cycle handling (raw_value_typewithcycle_fn) and returnsDivergentfor recursive aliases. Let me look atexpand_eagerlyandcycle_normalized.Assistant
Let me look at the
cycle_normalizedfunction and understand how cycles are handled.Assistant
Let me look at how
GenericAlias::variance_ofhandles recursion, since classes can also be recursive.Assistant
GenericAlias::variance_ofis a Salsa tracked function withcycle_initial=TypeVarVariance::Bivariant. This is the "existing bivariant cycle fallback"! Let me checkClassLiteral::variance_ofandClassType::variance_of.Assistant
Now let me look at
StaticClassLiteral::variance_ofwhich is Salsa-tracked.Assistant
Let me look at the
ManualPEP695TypeAliasTypestructure.Assistant
Let me look at the imports and structure of
type_alias.rsto understand where to add the impls.Assistant
Let me look at the legacy variance test file to understand legacy generic type aliases.
Assistant
Let me look at the legacy variance test for type aliases section.
Assistant
Let me understand how legacy
TypeAlias-annotated assignments are represented. Let me search.Assistant
So PEP 695
type X = ...statements createTypeAliasType::PEP695. Thex: TypeAlias = ...annotation - let me check how that's handled. Let me look at line 4049 (TypeAliasType call) and howTypeAliasannotation is handled.Actually, the legacy
InvariantAlias: TypeAlias = Invariant[T_co]- the: TypeAliasannotation marks it as a type alias. Let me check how this is represented. Let me search forTypeAliasspecial form handling.Actually, this is a side concern. Let me check: is
InvariantAliasaType::TypeAlias? When used asInvariantAlias[T_co](subscript), the result would be... Let me just check by looking at how the legacy variance test currently passes. The key question: does my change toType::TypeAliasaffect the legacy variance test?If
InvariantAliasis aType::TypeAlias(ManualPEP695 or some legacy form), then my change affects it. If it's just a binding to aNominalInstance(not aType::TypeAlias), then my change doesn't affect it.Let me check. . The RHS is a subscript → . The annotation... Let me search how -annotated bindings are treated.
Assistant
Let me look at how
: TypeAliasannotations are handled.Assistant
A PEP-613 type alias (
x: TypeAlias = ...) is just a binding to the inferred RHS type, NOT aType::TypeAlias. So the fix in theType::TypeAliasarm handles PEP695 and ManualPEP695 aliases. Let me first write a reproduction test mirroringtype_alias_variance. Let me check the test setup helper.Assistant
Let me check how mdtest is run so I can create a temporary reproduction.
Assistant
Let me create a temporary reproduction mdtest file based on the issue, then build and run it to confirm the bug.
Assistant
Now let me build and run the mdtest for this reproduction file. This will compile everything needed.
Assistant
The mdtest passed because alias-to-alias subtyping expands the alias value rather than using the alias's own variance. The bug is in the variance inference itself, checked directly by the
type_alias_varianceunit test. Let me look at where alias variance (not expansion) is actually used.Assistant
Let me look at how
Type::TypeAliassubtyping is handled - via expansion or via variance.Assistant
Let me find where subtyping of two
Type::TypeAliasof the same alias is handled.Assistant
Let me check where
check_specialization_pairis called and whether aliases go through it.Assistant
Let me look at the base-class variance validation (
invalid-generic-classlint).Assistant
The alias's own typevar variance is checked directly by the
type_alias_varianceunit test. The bug is in the variance inference. Let me add a temporary unit test to reproduce it directly, mirroringtype_alias_variancewith a two-level chain.Assistant
I've reproduced the bug:
RefRefBoxis bivariant instead of invariant (andRefBoxis correctly invariant). Now let me implement the fix.Let me look at the exact
Type::TypeAliasarm location.Assistant
Now let me make the edit. First, remove
Type::TypeAlias(_)from the bivariant group and add a separate recursing arm.Assistant
Now let me add the
VarianceInferableimpls intype_alias.rs. First, let me check howVarianceInferableandTypeVarVarianceare imported elsewhere.Assistant
VarianceInferableis accessible viacrate::types::VarianceInferable(it'spub(crate)and re-exported, sincemod varianceis private butVarianceInferableispub(crate)). Wait,mod variance;is private (nopub), socrate::types::variance::VarianceInferableisn't accessible outside. ButVarianceInferableis referenced ascrate::types::...VarianceInferablein class.rs imports (use crate::types::{... VarianceInferable}). So it must be re-exported. Let me check.Actually
class.rsusesuse crate::types::{... VarianceInferable}. Andmod varianceis intypes.rs(thetypesmodule). Socrate::types::VarianceInferableworks ifVarianceInferableis re-exported fromtypes.rs. Let me check.pub use crate::types::variance::TypeVarVariance;is there. IsVarianceInferablere-exported? Let me search.Assistant
VarianceInferableand the variance module are accessible fromtype_alias.rs(sibling module). Let me verifyGenericAliasis interned with a separate tracked trait impl, to mirror the pattern.Assistant
GenericAliasis interned with a separate tracked trait impl. I'll mirror this pattern. Let me update the imports intype_alias.rsand add the impls.Assistant
Let me verify
VarianceInferableis accessible ascrate::types::VarianceInferable(check for re-export).Assistant
The import paths work since
type_aliasis a descendant oftypes. Now let me find a good place to add theVarianceInferableimpls intype_alias.rs.Assistant
Now let me add the
VarianceInferableimpls after theTypeAliasTypeimpl block.Assistant
Now let me update the
KnownInstanceType::TypeAliasTypeentry to route through the Salsa-tracked impl for cycle safety (bare self-references).Assistant
Now let me check if
raw_value_typeis still used elsewhere to avoid unused warnings.Assistant
raw_value_typeis still used elsewhere. Now let me build and run the reproduction test.Assistant
Even
RefBox(one level) became bivariant - a regression. The issue is that routing the entry throughvalue_typeapplies the default specialization. Let me check whatdefault_specializationdoes.Assistant
The
default_specializationmaps typevars to their bounds (viaspecialize_partialwithNone), not to themselves. So routing the entry throughvalue_typeis wrong for the unspecialized alias (where the typevar is the alias's OWN typevar). The entry must keep usingraw_value_type. Let me revert the entry change.Assistant
The reproduction test now passes. Let me run the existing
type_alias_variancetest and the variance mdtests.Assistant
All variance tests pass. Now let me thoroughly test edge cases per the contract: multi-level chains with all four variances, reordered multi-parameter chains, recursive/mutually recursive cycles, and bare self-references.
Assistant
I referenced
CoContrawithout defining it. Let me rewrite the edge test properly with a two-parameter class and reordered chains.Assistant
Excellent! All edge cases pass, including the bare self-reference (it terminates via the Salsa cycle). Now let me test the legacy (ManualPEP695 /
TypeAliasTypeconstructor) case, since the contract mentions "legacy generic type aliases". Let me create a temporary mdtest for manual aliases.Assistant
Manual aliases (ManualPEP695) don't have own typevars, but they can appear inside other types' variance computations. Let me write a quick mdtest to verify the manual alias path recurses and terminates.
Assistant
The manual alias path works. Now let me run the broader test suite to ensure nothing is broken. First, the full library tests.
Assistant
All library tests pass. Now let me run the full mdtest suite to ensure no regressions in type checking behavior.
Assistant
All 340 mdtests pass. Now let me clean up the temporary test files before submitting.
Assistant
There's a residual diff in tests.rs. Let me check and clean it up.
Assistant
Now the diff is clean - only the two intended source files. Let me verify the known_instance.rs was fully reverted and review the complete diff.
Assistant
The diff is clean and minimal. Let me run clippy to ensure the code meets the project's lint standards.
Assistant
Clippy passes cleanly. Let me run a few more test crates that depend on the semantic layer to ensure no regressions.
Assistant
All tests pass. Let me do a final
cargo checkon thetyCLI crate to ensure the whole workspace still compiles with my changes.Assistant
Let me double-check whether ManualPEP695 (
TypeAliasTypeconstructor) aliases can be generic in ty, since the contract mentions "legacy generic type aliases".Assistant
Let me verify the manual (legacy) generic alias variance with a focused temporary unit test, mirroring
type_alias_variancebut usingTypeAliasTypeconstructor.Assistant
ManualInvresolved to Unknown - likelyTypeVarisn't imported. Let me fix the test imports.Assistant
Let me check how
TypeAliasTypeconstructor is used in existing tests to set it up correctly.Assistant
Manual generic aliases use
type_params=(T,). Let me look at the existing examples for the correct setup.Assistant
Let me check
setup_db's default Python version and retry the manual alias test withtype_params.Assistant
The default Python version is 3.10, where
TypeAliasTypeisn't intyping. Let me retry the manual alias test with Python 3.12 andtype_params, to confirm the manualvalue_typepath works.Assistant
The manual (legacy) generic alias test passes:
ManualInv→ invariant,ManualCo→ covariant, andManualRefInvterminates (recurses through the manual alias value). Now let me clean up the temporary test and do a final verification run.Assistant
The diff is now clean (only the two intended source files). Let me do a final comprehensive test run to confirm everything passes after cleanup.
Assistant
All tests pass (203 lib, 338 mdtest). Let me do a final review of the complete diff.
Assistant
The diff is clean and minimal. Let me run a final clippy check with tests included to be thorough.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.