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 "ty" project (a type checker from the ruff/astral team). Let me explore the structure more, particularly looking for variance inference related code.
Assistant
Now let me look at how variance inference is implemented for type aliases. Let me search for the alias type handling.
Assistant
Let me look at the type_alias.rs file and how the
Type::Aliasis handled for variance inference.Assistant
Found it! The issue is in the
VarianceInferableimpl forType<'db>. When the type isType::TypeAlias(_), it returnsTypeVarVariance::Bivariant. This means variance is lost when a type alias references another type alias because it doesn't recurse into the alias's value type.Let me look at
TypeAliasTypeto understand its structure.Assistant
Now let me understand how cycles are handled for type aliases. Let me look at the cyclic handling.
Assistant
Let me look at how variance inference is invoked, particularly where
variance_ofis called from.Assistant
Let me look at the typevar.rs in types/ to see how
variance_ofis used and where the cycle detection might be needed.Assistant
So
variance_with_polarityis called, and it callsbinding_type(db, definition).variance_of(db, self). Thebinding_typeis the type of the definition where the typevar is bound (the generic alias value type, or the class definition).Let me look at
binding_typefunction.Assistant
Let me understand how the value type of a PEP 695 type alias that references another generic alias is inferred. Let me look at how subscripting works on type aliases.
Assistant
Let me see how a PEP 695 type alias is subscripted when it has a generic context. Let me look earlier in subscript.rs.
Assistant
Let me find how a generic PEP 695 type alias gets subscripted (i.e.,
RefBox[T]). It's likely handled via the general subscript forKnownInstance-> theTypeAliasTypecase for generic aliases. Let me look at the generic handling.Assistant
Let me look at how subscripting is handled for generic aliases - the actual subscript of
RefBox[T]. Let me look at theKnownInstanceTypeAliasType subscript handling. The case at line 732 only handles non-generic. For generic, it must be handled elsewhere. Let me look for the__getitem__ofTypeAliasType.Let me search how
TypeAliasTypesubscript creates a specialized alias.Assistant
Let me look at how a generic
TypeAliasTypegets subscripted. Let me check the general subscript logic forKnownInstance.Assistant
The issue is becoming clearer. Let me look at the full type_alias.rs to understand
value_typevsraw_value_type.Assistant
Now let me look at
GenericAlias::variance_ofandClassType::variance_of.Assistant
Let me verify how subscripting a generic
TypeAliasTypeproduces a specialized alias.Assistant
Let me find where the generic
TypeAliasTypesubscript is handled in subscript.rs.Assistant
Let me look at the
infer_subscript_expressionandinfer_subscript_loadmethods.Assistant
Let me look at
infer_explicit_type_alias_type_specializationandin_type_expression.Assistant
Let me look at
in_type_expressionforKnownInstanceType::TypeAliasType.Assistant
Let me check what
infer_type_expressionreturns vsin_type_expression.Assistant
Let me just build and run ty on the example to confirm the behavior. First, let me create the reproduction file.
Assistant
Let me look at the existing variance tests to understand the testing pattern.
Assistant
I'm having trouble reasoning about the exact behavior. Let me build and run the existing variance test to confirm the current behavior.
Assistant
Let me add a temporary test to confirm the bug and understand the RecursiveAlias2 case.
Assistant
Let me add a temporary test to debug the issue. Let me view the end of the
type_alias_variancetest.Assistant
Let me add a temporary debugging test after the
type_alias_variancefunction.Assistant
Confirmed:
RefRefBox: Bivariant(should be Invariant). Now let me understand howRecursiveAlias2gives Invariant. Let me extend the debug test to inspect the raw value type.Assistant
I need to add
use crate::types::TypeAliasType;anduse crate::types::Type;etc. ActuallyTypeAliasTypeis already imported in tests.rs? Let me check the imports at the top of the debug test. Theget_type_aliasusesKnownInstanceType,TypeAliasType,PEP695TypeAliasType. These are already imported at the file level. Let me check what's imported. The existingtype_alias_variancetest uses them without local imports, so they're imported at the file level.For my new code I use
TypeAliasType::PEP695(r1).raw_value_type(&db)and.value_type(&db)and.display(&db).TypeAliasTypeanddisplayshould be available. Let me check ifraw_value_typeis accessible — it'spub(super). From tests.rs (in the same moduletypes),pub(super)would be visible since tests.rs is intypesmodule andtype_aliasis a submodule of . Actually in (which is ) means visible to module. tests.rs is . So (visible to ) — is able to see it? = visible in parent module = . Submodules of (like ) can access items that are visible in ? Actually no — makes it visible to the parent module and its descendants. Yes, descendants can access. So can access items of . Good.Assistant
Excellent! Now I understand the mechanism. Key findings:
RefRefBox: Bivariant(bug - should be Invariant)listis invariant, which is whyRecursiveAlias2(containinglist[T]) is Invariantraw_value_typeuses the alias's own typevar;value_typeapplies specialization (mapping to Unknown for non-specialized)
The bug:
Type::TypeAlias(_)returnsBivariantwithout recursing into the alias's value type. Let me look at the exact code to fix.Assistant
Now let me make the fix. First, let me remove
Type::TypeAlias(_)from the bivariant list and add a separate arm.Assistant
RefRefBoxis now Invariant (fixed!), and recursive cases still pass. Let me run the full existing variance test suite.Assistant
The fix works for PEP 695. Now let me check the contract mentions "both PEP 695 and legacy generic type aliases." Let me search for how legacy generic type aliases are represented and tested.
Assistant
Let me look at the
ManualPEP695TypeAliasTypeto understand legacy generic aliases viatypes.TypeAliasType(...).Assistant
Let me run the existing variance mdtest tests to ensure nothing breaks.
Assistant
My simple fix may not handle mutually recursive aliases that reference each other directly (not through a generic alias). Let me test this edge case.
Assistant
Interesting — it returned
Bivariantwithout overflowing. Let me instrument with a recursion counter to understand how the cycle terminates.Assistant
The depth never exceeded 40, so something IS terminating the recursion. Let me track max depth and entry count more precisely.
Assistant
Let me add display output in the TypeAlias arm to see what value_type returns.
Assistant
The
TypeAliasarm was never entered for MutRec1, suggestingraw_value_typereturned Divergent. Let me directly inspectraw_value_typeandvalue_typefor MutRec1.Assistant
raw_value_typereturnsDivergentfor mutually recursive aliases (salsa cycle recovery → Bivariant). Let me test more recursive variants to ensure no stack overflow in the Rust-level recursion. Let me test cycles through unions and covariant wrappers.Assistant
No output for those grep terms? Let me run without grep to see the full output.
Assistant
I have a brace mismatch. Let me view and fix the debug test region.
Assistant
There's an extra
}at the end. Let me fix it.Assistant
Only partial output — likely a crash on UnionA. Let me check the full output and exit code.
Assistant
Confirmed: cycles through unions cause a stack overflow. My simple fix is insufficient — I need cycle detection. The cleanest approach, mirroring
GenericAlias::variance_of(which is salsa-tracked withcycle_initial=Bivariant), is to make the type-alias variance recursion go through a salsa-tracked query. Let me look at howGenericAliasis defined.Assistant
Confirmed: cycles through unions cause a stack overflow with my simple fix. I need cycle detection. The robust approach, mirroring
GenericAlias::variance_of(salsa-tracked withcycle_initial=Bivariant), is to route the type-alias variance through a salsa-tracked query. Let me first revert the instrumentation, then look at type_alias.rs imports.Assistant
I need to add imports for
BoundTypeVarInstance,TypeVarVariance, andVarianceInferable(the trait, for calling.variance_ofonType). Let me check where these are defined.BoundTypeVarInstance- in types/typevar.rs probably.TypeVarVariance- types/variance.rs.VarianceInferable- types/variance.rs.Let me check the path. In types.rs,
pub use crate::types::variance::TypeVarVariance;anduse crate::types::variance::VarianceInferable;. And BoundTypeVarInstance — let me find.Assistant
BoundTypeVarInstanceis re-exported fromtypes::typevar(used in types.rs line 87 viacrate::types::typevar?). Let me check line 87 context.Assistant
Now let me revert the instrumentation in types.rs and implement the proper fix. First, revert the
Type::TypeAliasarm.Assistant
Now let me check if
TypeAliasTypealready implementsVarianceInferableanywhere.Assistant
No existing impl. Let me update the imports in type_alias.rs and add the salsa-tracked methods.
Assistant
Now let me add the salsa-tracked
variance_oftoPEP695TypeAliasType. Let me view the end of its tracked impl block.Assistant
Now let me add the salsa-tracked
variance_oftoManualPEP695TypeAliasTypeand a dispatch method onTypeAliasType.Assistant
Now let me add the dispatch method on
TypeAliasType. Let me view its impl block.Assistant
Now let me build and run the debug test to verify the fix and cycle safety.
Assistant
All recursive cases terminate safely with Bivariant, and
RefRefBoxis now Invariant (fixed!). Let me run the existing variance tests to confirm no regressions.Assistant
The fix works at the unit level. Now let me verify end-to-end behavior using
ty checkon the issue's reproduction. Let me build thetybinary.Assistant
Both directions are now
Literal[False](invariant preserved through the two-level chain). Let me verify covariant and contravariant multi-level chains are also preserved.Assistant
The repo's pyproject sets Python 3.7. Let me specify the Python version explicitly.
Assistant
It's picking up the
/ruff/pyproject.toml. Let me run from within/tmp/repro.Assistant
All variance kinds are preserved through multi-level chains. Now let me test reordered multi-parameter alias chains (from the contract).
Assistant
My test assertion was self-contradictory. Let me fix it.
Assistant
Excellent! All reordered multi-parameter cases pass. Now let me test legacy generic type aliases (the contract mentions "both PEP 695 and legacy"). Let me check how legacy aliases are represented.
Assistant
Let me check whether this legacy behavior is pre-existing (unrelated to my change) by revealing the types.
Assistant
Let me test
is_assignable_todirectly onCo[B]/Co[A]to isolate whether this is a pre-existing legacy-alias limitation.Assistant
My legacy test was wrong —
TypeVar("T")is invariant by default (legacy). That's correct pre-existing behavior, unrelated to my change (legacyTypeAlias-annotated assignments areGenericAlias, notType::TypeAlias). My fix handles PEP 695 andManualPEP695(TypeAliasType).Now let me remove the temporary debug test and run the broader test suite.
Assistant
Good. Let me build and run the variance tests plus broader related tests.
Assistant
All generics mdtests pass. Let me run the full
ty_python_semanticlib test suite to check for regressions.Assistant
All 203 lib tests pass. Let me run the full mdtest suite and property tests to ensure no regressions in variance-dependent areas.
Assistant
All 338 mdtests pass. Let me run the property tests for ty_python_semantic.
Assistant
Property tests are ignored by default. Let me check if they need a feature flag to run.
Assistant
Let me run a few stable property tests briefly to ensure no variance-related regressions in type relations.
Assistant
Let me review the final diff to ensure it's clean.
Assistant
The diff is clean, but there's an extra blank line in tests.rs. Let me clean it up.
Assistant
The tests.rs diff is now clean. Let me run clippy on the changed crate to catch any lint issues with my new code.
Assistant
Clippy passes with no warnings. Let me check the existing PEP 695 variance mdtest to see if it covers aliases used as class bases (variance validation), and add a quick end-to-end check for that.
Assistant
Let me check the rest of the file for alias-as-base variance validation tests.
Assistant
The existing tests cover single-level aliases. I'll not add tests per the instructions. Let me rebuild the
tybinary with the final fix and re-verify the end-to-end behavior.Assistant
Let me re-run the end-to-end tests with the rebuilt binary.
Assistant
Let me re-run the transmute test directly to confirm the invariant behavior.
Assistant
Both directions are
Literal[False]— the transmute is prevented. Let me verify there are no leftover debug artifacts in the repo and the diff is final.Assistant
The diff is clean — only
types.rsandtype_alias.rsare modified (tests.rs reverted). Let me confirm there are no leftover debug statements.Assistant
No leftover debug statements. Let me do a final confirmation run of the variance-related tests.
Assistant
All tests pass. Let me do a final review of the complete diff before submitting.
Assistant
The diff is clean and complete. Let me test one more edge case: a recursive alias where the recursive reference uses a non-identity specialization (e.g.,
A[int]insideA's definition).
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.