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
pyfrom 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:
- Assistant
I’ll first inspect the repository structure and search for variance inference and type-alias handling. Then I’ll identify an existing focused test command or use a temporary reproduction without modifying tests.
- Assistant
rgis unavailable, so I’ll usegrepandfindto locate the relevant Rust implementation and tests. - Assistant
The focused unit tests are in
types/tests.rs, while inference implementations are spread across type variants. I’ll inspect the alias-relatedVarianceInferableimplementations and the current variance tests to understand where alias specialization is being dropped. - Assistant
Existing tests already cover one-level aliases and cycle fallback, matching the reported boundary: the likely missing arm is in the generic
Typevariance traversal. I’ll inspectvariance.rsfully aroundTypeand alias implementations, plus the alias type definitions and specialization/value APIs. - Assistant
variance.rsonly defines the lattice and trait. I’ll enumerate everyVarianceInferableimplementation to locateType,KnownInstanceType, and alias behavior, then inspecttype_alias.rsAPIs. - Assistant
Only
KnownInstanceTypehas explicit alias-related variance today;Typemay implement the trait via a macro or a differently formatted impl. I’ll inspectknown_instance.rsand search all calls/match arms involvingvariance_ofto find the dispatch layer. - Assistant
The one-level test enters through
KnownInstanceType::TypeAliasTypeand traverses its raw RHS. A nested alias RHS is represented asType::TypeAlias, so I’ll inspect that dispatch arm and nearby composite-type handling. - Assistant
The defect is explicit:
Type::TypeAlias(_)currently returns bivariant. Simply expanding it would make recursive aliases recurse forever becauseType::variance_ofis untracked, so the expansion needs a tracked alias-level query with the same bivariant cycle initial used by generic aliases/classes. Before editing, I’ll inspect how legacy aliases are represented and the repository’s existing type-check test harness so the fix covers both forms and can be reproduced externally. - Assistant
Legacy user-defined aliases are inferred in
infer_generic_alias_specialization; I’ll inspect that path and specialization mapping to determine whether nested legacy chains also eventually produceType::TypeAliasor are transparently expanded. - Assistant
A key distinction is required: top-level variance inference for an alias declaration must inspect its unspecialized RHS, but a nested alias reference must inspect the RHS with that reference’s specialization applied. I’ll verify what an absent/default specialization contains, then implement tracked variance on concrete alias ingredients and route both
KnownInstanceTypeandType::TypeAliasthrough it. - Assistant
The prior snippet missed the method body; I’ll inspect it directly and then edit based on whether default specialization preserves bound type variables.
- Assistant
Default specialization may substitute defaults/unknowns rather than identity, confirming why declaration inference uses raw RHS. I’ll inspect
specialize_partialbriefly, then add separate tracked methods: declaration/raw variance and referenced/value variance, both with bivariant cycle fallback. This also allows alias cycles to terminate regardless of entry path. - Assistant
I’ll now implement tracked variance queries on both concrete alias kinds. For PEP 695 aliases, the query expands a specialized reference with
value_type, but usesraw_value_typefor the unspecialized declaration object. The enum dispatch then becomes the common path from both variance entry representations. - Assistant
Compilation shows Salsa requires each tracked method to live in its own tracked impl block; adding it inside the existing manual alias block also caused the following
value_typecycle attributes to be associated incorrectly. I’ll inspect the exact placement and split both new queries into separate#[salsa::tracked] implblocks, following the existing GenericAlias pattern. - Assistant
The PEP alias query is correctly inside an existing tracked impl. For the manual alias, my insertion split the attributes belonging to
value_type; I’ll restorevalue_typeimmediately after its cycle attributes and placevariance_ofafterward as a separate tracked method in the same tracked impl. - Assistant
The focused unit test now passes, including its recursive-cycle cases. I’ll perform an external behavioral reproduction using a temporary Python 3.12 file: the reported three-level invariant alias must reject cross-specialization assignment, while covariant/contravariant/bivariant aliases must retain their respective behavior through reordered multi-parameter chains. This does not modify repository tests.
- Assistant
The behavioral run produced exactly the two intended variance errors; the covariant, contravariant, and bivariant paths through the reordered chain were accepted. I’ll now exercise legacy implicit and PEP 613 generic alias chains similarly, since the contract explicitly calls them out, and check that invariant behavior survives multiple levels while valid covariance remains accepted.
- Assistant
Legacy implicit and PEP 613 chains each rejected invariant widening, while the covariant legacy chain was accepted, so both legacy forms satisfy the contract through three levels. The diff is formatting-clean. I’ll now run the full
ty_python_semanticlibrary test suite to catch regressions beyond the focused variance test. - Assistant
All 203 non-ignored library tests pass. As a final edge-case check, I’ll run a temporary mutually recursive generic alias example. One cycle includes an invariant
Box[T], which should still infer invariant by joining the bivariant cycle fallback with the concrete invariant occurrence, and the command must terminate safely.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.