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
I’ll first map the repository and locate variance inference and alias handling. Then I’ll reproduce the behavior with the project’s existing test/CLI infrastructure, patch the recursive alias traversal while preserving cycle handling, and run focused plus broader tests.
- Assistant
ripgrepis unavailable, so I’ll use recursivegrepand narrow searches to identify the relevant crate and symbols. - Assistant
The focused unit tests already include direct aliases and recursive cases. I’ll inspect those expectations alongside the
VarianceInferableimplementations, especiallyType,GenericAlias, and type-alias representations, to find where a specialized alias loses its mapping. - Assistant
I’ll now read the complete variance dispatch and alias data model. The likely defect is a match arm classifying
Type::TypeAliasas always bivariant, but legacy and PEP 695 aliases may require different value/specialization access paths. - Assistant
The alias model exposes
value_type, which already applies PEP 695 specialization. Next I’ll locate everyVarianceInferableimplementation and theType/KnownInstanceTypematch arms to see exactly which alias forms currently recurse and which return the fallback. - Assistant
I found dedicated dispatch in
known_instance.rsandtypes.rs; I’ll inspect these plus the alias specialization code. This should reveal whether only the alias object (KnownInstance) recurses while the alias value produced by subscription (Type::TypeAlias) does not. - Assistant
The direct alias object uses
raw_value_type, which explains why one level works. A nested alias RHS is likely represented as a specialized alias object;KnownInstanceType::variance_ofagain callsraw_value_type, discarding that specialization. I’ll confirm this against the remaining dispatch and specialization construction before changing it to recurse through the specializedvalue_type. - Assistant
Two relevant gaps are visible:
KnownInstanceType::TypeAliasTypetraverses the unspecialized raw RHS, andType::TypeAliasis unconditionally bivariant. The evaluation explicitly requires both PEP 695 and legacy aliases, so I’ll inspectType::TypeAlias’s representation and expansion semantics to implement both without introducing a separate cycle mechanism. - Assistant
Type::TypeAliasis also PEP 695’s instance-level wrapper, not a distinct legacy structure. Legacy assignment aliases appear to resolve directly to their RHS types, but chains can still include PEP-style wrappers or specialized alias objects. I’ll reproduce the reported subtype behavior through ty’s mdtest framework and inspect existing variance diagnostic tests to choose the fastest reliable validation route. - Assistant
The minimal semantic correction is to recurse through
value_typein both alias dispatch arms. This preserves substitutions (including parameter reordering), while existing tracked variance queries on enclosing generic aliases/classes retain the bivariant Salsa cycle seed. I’ll apply that focused change first, then run the existing alias variance unit test and create external temporary source cases for deep/reordered/recursive chains rather than modifying repository tests. - Assistant
The focused unit exposed an important distinction: an unspecialized alias object must inspect its raw RHS so its own bound type variable remains visible; applying the default specialization erases it. A specialized alias must inspect
value_type. I’ll make that branch explicit.Type::TypeAliasrepresents an alias used as a type and should continue through its specialized value. - Assistant
The existing direct and recursive unit expectations now pass. I’ll validate the reported observable bug with
/tmpsources using the builttyCLI: invariant deep PEP 695 and legacy chains must reject widening, while reordered covariant/contravariant chains must preserve direction. I’ll also include recursive and mutually recursive aliases to verify termination. - Assistant
The CLI source parsed and recursive aliases terminated, but bare module annotations are considered undefined values, obscuring assignability. I’ll switch to functions whose typed parameters are returned under another specialization, and use raising method bodies. This directly exercises subtype/assignability and cleanly distinguishes expected invariant errors from valid reordered covariance/contravariance.
- Assistant
The patched CLI produces exactly the two expected errors: both deep PEP 695 and legacy invariant chains reject widening, while the reordered mixed-variance chain is accepted and recursive/mutual aliases terminate. To satisfy explicit reproduction, I’ll temporarily save the patch, rebuild the baseline versions of the two source files, run the same fixture to show the missing PEP 695 error, then restore and rebuild the fix.
- Assistant
That first black-box fixture exercised relation expansion, which independently sees the underlying
Box, so it did not reproduce variance inference. I’ll refine it to put each deep alias inside a PEP 695 generic class attribute; assignability between specializations then depends on inferred variance. This matches the original failure mechanism. I’ll compare baseline and patched diagnostics again, keeping all temporary fixtures outside the repository. - Assistant
The refined fixture successfully reproduces the defect: baseline reports three errors while patched reports four; the missing baseline error is the class whose variance depends on the twice-deep PEP alias. Legacy assignment aliases already normalize more eagerly in this fixture, but the
Type::TypeAliasarm is still required for aliases encountered as retained type values and is explicitly part of the contract. I’ll inspect the final diff, add concise comments explaining raw-vs-specialized traversal, and then run formatting, focused tests, and the semantic crate’s full library suite. - Assistant
I’ll document why unspecialized alias objects use the raw RHS but specialized aliases and
Type::TypeAliasuse the mapped RHS. This guards against regressing the direct unit test by naively always applying defaults, and makes the multi-level behavior explicit. - Assistant
All 203 active semantic library tests pass (34 intentionally ignored), including the focused alias and recursive-cycle test. I’ll now run the existing PEP 695 and legacy variance mdtests, then rerun the external black-box fixture to ensure the final commented/formatted build still yields four expected errors and no recursion failure. Finally I’ll inspect status/diff for accidental files.
- Assistant
The mdtest harness accepts only one filter per invocation; the attempted combined command was a CLI-usage failure, not a test failure. I’ll run each variance document separately. The final black-box check reports all four expected invalid returns, and only the two intended source files are modified with a clean diff.
- Assistant
Before submission I’ll stress the edge cases most relevant to the contract: variance inference through reordered two-parameter chains (not merely direct relation expansion), and pure mutually recursive aliases used in a generic class. The command will use a short timeout so any missed cycle fallback is detected safely.
- Assistant
Edge validation succeeded: the valid reordered direction is accepted, the reverse is rejected, and a pure mutual cycle terminates promptly using existing cycle recovery (with the expected cyclic-definition diagnostics). I’ll perform one final diff/status review, then submit. Checklist assessment:
- Reproduced: yes—the baseline generic wrapper over a twice-deep PEP alias missed one invalid return (3 diagnostics vs. fixed 4).
- Fix confirmed: yes—the refined fixture now rejects that return; direct, legacy, reordered, and recursive scenarios were also checked.
- Edge cases: yes—multi-parameter reorderings preserve covariance/contravariance, unspecialized direct aliases retain their typevars, and recursive/mutual cycles terminate.
- Existing tests: yes—203 active semantic library tests pass, plus focused PEP 695 and legacy variance mdtests.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.