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 layout and locate variance inference and type-alias handling. Then I’ll reproduce the reported behavior with the project’s existing test/CLI conventions before making a focused fix.
- Assistant
rgis unavailable in the environment, so I’ll usegrep/findto identify the relevant Rust modules and tests. - Assistant
There is already a concentrated
type_alias_varianceunit test, suggesting the implementation has explicit cycle behavior and likely exposes the bug directly. I’ll inspect that test and theVarianceInferableimplementations for aliases/types. - Assistant
The existing tests cover one-level aliases and self-recursion, but not alias chains. I’ll read the core dispatch and alias representations to determine why the second alias loses variance, including how legacy aliases are represented.
- Assistant
I need the exact
KnownInstanceType::variance_ofbranch andType::variance_ofdispatch. I’ll also locate legacy alias structures, since the evaluation explicitly requires both PEP 695 and legacy generic aliases. - Assistant
The one-level branch traverses
raw_value_type, but a specialized alias value appears asType::TypeAlias, whose genericTypevariance dispatch likely defaults to bivariant. I’ll inspect that dispatch and legacy specialization logic to verify the representation and formulate a cycle-safe recursion approach. - Assistant
Confirmed:
Type::TypeAliasis absent from the shown recursive cases and therefore likely falls into the bivariant default. The right fix is to recurse into alias values atTypedispatch, where specialized PEP 695 aliases and any alias-valued path are handled, while retaining Salsa’s existing cycle fallback. I’ll inspect the rest of the match and existing markdown variance expectations before editing. - Assistant
The implementation change should be a single dispatch branch: for
Type::TypeAlias(alias), infer variance fromalias.raw_value_type(db). This preserves specialization mappings and allows arbitrary/reordered chains; recursive calls eventually re-enter trackedGenericAlias::variance_of, whose declaredcycle_initialis already bivariant as required. Before changing it, I’ll reproduce the public symptom using a temporary file and thetyCLI (outside the repository, so no tests are added). - Assistant
The CLI inherited the repository’s Python 3.7 setting, so that run only established a configuration issue rather than the bug. I’ll check the CLI flag and rerun under Python 3.12.
- Assistant
I’ll now rerun the temporary repro with
--python-version 3.12; the expected pre-fix failure is that the assertions claiming invariance are rejected because the twice-referenced alias is incorrectly bivariant. - Assistant
The plain class did not reproduce the report—its attribute semantics differ from the dataclass example and/or the alias was eagerly normalized in this path. I’ll use the exact dataclass shape and test direct assignment/subtyping across the two-level alias.
- Assistant
Direct alias subtyping expands alias values during relation checking, so it bypasses variance inference and cannot expose this bug. The defect affects variance inferred for a generic class whose members/bases mention the alias. I’ll wrap each alias level in a return annotation; an invariant alias should make the enclosing generic invariant, while the current
Type::TypeAliasdefault can incorrectly infer bivariance. - Assistant
The temporary repro now demonstrates the variance defect (the invariant assertions fail; unrelated empty-body diagnostics can be removed later). It also confirms that alias occurrences represented as
Type::TypeAliasare treated bivariantly even at one wrapper level, while the alias object’s own one-level unit test takes the separateKnownInstanceTypepath.I’ll add the recursive alias branch and remove
TypeAliasfrom the bivariant leaf alternatives. - Assistant
I’ll rerun the reproduction with valid method bodies. This checks that both one- and two-level PEP 695 alias uses now preserve invariance through enclosing generic variance inference.
- Assistant
The direct dispatch alone is insufficient: the specialized
Type::TypeAliasbranch is reached, butraw_value_typelikely intentionally omits applying the alias specialization, so the queried outer type variable does not occur in the returned value. I’ll inspectPEP695TypeAliasType::{value_type,raw_value_type}and specialization mapping to recurse through the correctly substituted RHS. - Assistant
raw_value_typeis correct for the unspecialized runtime alias object (KnownInstanceType), where inference asks about the alias’s own bound variable. ForType::TypeAlias, however, it is an alias occurrence with a specialization, so variance must recurse throughvalue_type, which applies that specialization. I’ll correct this distinction and rerun. - Assistant
The PEP 695 repro now passes. Next I’ll verify the existing focused unit test, especially its recursive and self-recursive cycle expectations; this is important because the new recursion must retain the bivariant cycle fallback and still detect direct invariant occurrences alongside a cycle.
- Assistant
The focused self-recursive tests pass, but a direct mutually recursive alias chain (
A[T] = B[T],B[T] = A[T]) may recurse without ever enteringGenericAlias::variance_of. The contract explicitly requires safe mutual-cycle termination, so I’ll inspect established tracked variance-query patterns and test that case with a timeout before deciding whether alias variance itself needs a tracked cycle boundary. - Assistant
The mutually recursive case terminates safely (the alias-value queries normalize the invalid direct cycle to divergent/bivariant), and the existing valid recursive tests remain green. I’ll now exercise legacy implicit/PEP 613 generic alias chains in a temporary file, since the evaluation contract explicitly includes them.
- Assistant
Legacy invariant chains pass. To validate composition rather than only recursion, I’ll use a temporary PEP 695 scenario covering covariant, contravariant, bivariant, invariant, and reordered two-parameter chains. This specifically tests that
value_typeapplies each alias specialization in the right parameter order. - Assistant
All four variance modes and reordered multi-parameter chains pass. I’ll run the repository’s variance markdown tests (or identify the exact generated test target), then run the crate’s full library tests to catch broader regressions.
- Assistant
The dedicated variance markdown suite passes. I’ll now run all
ty_python_semanticlibrary unit tests, then inspect the final diff/status and ensure no temporary or generated repository files were introduced.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.