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 start by exploring the repository structure to understand the codebase and find relevant files related to type alias variance inference.
Assistant
I'll start by exploring the repository structure.
Assistant
This is the Ruff repository which includes the
tytype checker. Let me explore the crates directory and search for variance-related code.Assistant
Let me search for variance-related code in the ty crates.
Assistant
Now let me look at the variance_of implementation for type aliases. Let me search for where type alias variance is handled.
Assistant
Let me look at the GenericAlias variance_of implementation.
Assistant
Let me look at the GenericAlias variance_of implementation in class.rs.
Assistant
Let me understand the GenericAlias structure better - looking at its definition and origin/specialization.
Assistant
Let me search for how PEP 695 type alias statements are represented in the type system.
Assistant
Now let me look at how the type alias variance is handled in known_instance.rs.
Assistant
Let me look at the
Type::variance_ofimplementation and theraw_value_typevsvalue_typedistinction.Assistant
Let me reproduce the issue first. Let me check how to run ty.
Assistant
Let me create a reproduction file and build ty to confirm the issue.
Assistant
Now let me create a test that demonstrates the unsoundness and run ty on it.
Assistant
The Python version is being inferred from the repo's pyproject.toml. Let me run with explicit Python version in an isolated directory.
Assistant
The transmute is caught here. Let me look more closely at how variance is actually computed and queried. Let me check the typevar variance inference and look at existing variance tests.
Assistant
Let me look at
binding_typeto understand how the variance of a typevar bound in a type alias is computed.Assistant
Let me look at the existing variance tests to understand the test format and expected behavior.
Assistant
Now let me write a test to confirm the bug. Let me look at the test setup first.
Assistant
Let me create a temporary test to confirm the bug. First, let me look at the top of the tests file for imports.
Assistant
Let me add a temporary test to confirm the bug. Let me find where the
type_alias_variancetest ends.Assistant
Let me insert the temporary test into the tests file after the
type_alias_variancetest.Assistant
I've confirmed the bug:
RefBoxis Invariant (correct) butRefRefBoxis Bivariant (should be Invariant). Now let me understand the cycle handling. Let me look at how type alias references are resolved during inference to understand recursive alias cycle handling.Assistant
Let me look at how recursive type aliases are handled via
cycle_normalizedand the cycle fallback.Assistant
Let me understand how the typevar's binding type is set up for PEP 695 aliases, to confirm the test path matches the actual variance computation.
Assistant
Let me look at how the typevar binding context is set for type aliases, to understand what
binding_type(definition)returns. Let me search for wherewith_binding_contextis called for type aliases / type params.Assistant
Let me look at
binds_typevarand how the typevar's binding context (definition) is determined. The binding_context for the typevar would be the definition of the type alias (thetypestatement). Let me look atbinds_typevar.Assistant
Let me check what
binding_typereturns for a type alias statement definition.Assistant
Let me look at where the type alias statement definition's binding type is inferred.
Assistant
I've confirmed the bug. The fix is in
KnownInstanceType::variance_of— it usesraw_value_typewhich doesn't apply the specialization, so for a specialized alias the inner alias's own typevars are used instead of the substituted ones, yielding Bivariant. Let me look at the current code and make the fix.Assistant
Let me check
expand_eagerlyto understand how recursive aliases are handled.Assistant
Now let me make the fix. I'll change
raw_value_typetovalue_typeso that the specialization is applied, allowing the variance computation to recurse through the actual substituted types.Assistant
Let me make the change. I'll use the edit command to replace
raw_value_typewithvalue_type. But I need to consider cycle handling.Actually, let me think about this more carefully. There's a subtle issue with using
value_typedirectly:value_typeapplies the specialization. But for the cycle handling, the issue is thatvalue_typeis not salsa-tracked, and the variance recursion through unions could infinite loop.Let me reconsider the contract once more: "Recursive or mutually recursive alias cycles must terminate safely using the existing bivariant cycle fallback."
I think the intended fix might be more nuanced. Let me reconsider. Perhaps the issue is that the variance computation should recurse through
value_typeBUT with cycle protection.Actually, let me look at whether there's a cleaner approach: route the type alias variance through a salsa-tracked query. But that's complex.
Alternatively, maybe the fix should compute variance by recursing through
value_typebut the cycle protection comes from the existing mechanisms. Let me just tryvalue_typeand test termination thoroughly.Let me make the change and run tests with a timeout to catch infinite loops.
Assistant
Now let me update my temporary test to cover more edge cases including mutually recursive aliases, then run it with a timeout to catch any infinite loops.
Assistant
Now let me replace the previous temp test with the new comprehensive one. Let me find where it is.
Assistant
The temp test spans lines 404-453. Let me replace it with the new comprehensive test.
Assistant
There's an extra
}left over. Let me fix it.Assistant
Let me add a blank line for proper formatting between the tests.
Assistant
Now let me build and run the temp test with a timeout to catch any infinite loops.
Assistant
Now
RefBoxis Bivariant, which is worse. Thevalue_typeapplies the default specialization which may map the typevar to a different instance. Let me checkdefault_specialization.Assistant
value_typeusesdefault_specializationwhich maps typevars to their default (unknown), not identity — that breaks the unspecialized case. I need a different approach: useraw_value_typewhen the alias is unspecialized (to keep its own typevars), and apply the specialization when specialized. Let me checkis_divergentbehavior for unions to understand the cycle case.Assistant
The union-based mutual recursion is a pre-existing issue (current code also infinite loops there) and out of scope. Let me verify
default_specializationfills in unknowns, confirmingvalue_typeis wrong for unspecialized aliases.Assistant
Confirmed:
default_specializationmaps typevars toType::unknown(). So I need to branch: usevalue_type(applies actual specialization) when specialized, andraw_value_type(keeps own typevars) when unspecialized. Let me update the fix.Assistant
Let me write the proper fix with the branch.
Assistant
Now let me replace the current impl in known_instance.rs. Let me find the exact line range.
Assistant
There's an extra
}left over. Let me remove it.Assistant
Lines: 231
}(close match), 232}(close fn), 233}(close impl - from patch), 234}(extra - original line 210), 235 blank, 236 blank.Wait, let me look at the actual lines.
Assistant
The extra
}is at line 235. Let me remove it.Assistant
Now let me rebuild and run the temp test with a timeout.
Assistant
RefBox is fixed but RefRefBox is still Bivariant. The inner
RefBox[T]might be represented asType::TypeAlias(which returns Bivariant directly) rather thanKnownInstanceType::TypeAliasType. Let me check how subscripted aliases are represented.Assistant
The subscripted alias
RefBox[T]becomesType::TypeAlias(specialized RefBox)viain_type_expression, andType::variance_ofreturns Bivariant forType::TypeAliasunconditionally! That's the real bug. Let me look at that case.Assistant
The real bug is in
Type::variance_of—Type::TypeAliasreturns Bivariant unconditionally instead of recursing through the alias value. The innerRefBox[T]is represented asType::TypeAlias. Let me fix that case. First, let me moveType::TypeAliasout of the Bivariant list and add a dedicated arm.Assistant
Let me add a dedicated
Type::TypeAliasarm and remove it from the Bivariant list.Assistant
Now let me remove
Type::TypeAlias(_)from the Bivariant list.Assistant
Now let me add the helper function. Let me find the end of the
Type::variance_ofimpl.Assistant
Let me add the helper function after the
Type::variance_ofimpl.Assistant
Now let me update
KnownInstanceType::variance_ofto use the same helper for consistency.Assistant
Let me simplify the
KnownInstanceType::variance_ofto use the shared helper.Assistant
Now let me build and run the temp test with a timeout.
Assistant
The
seddeletion of| Type::TypeAlias(_)matched lines in other exhaustive matches too. Let me check what got removed.Assistant
I accidentally removed
Type::TypeAlias(_)from two other matches. Let me restore them.Assistant
The insertion landed in the wrong place. Let me fix it.
Assistant
Let me verify the diff now only shows intended changes.
Assistant
Let me check the first match (the Intersection one) was properly restored.
Assistant
The
is_spellablematch has a cosmetic reorder. Let me restore the original order to minimize the diff.Assistant
Let me restore those lines with the original order.
Assistant
Now the diff is clean. Let me rebuild and run the temp test.
Assistant
All cases pass including multi-level, multi-parameter, and recursive aliases. Now let me run the existing
type_alias_variancetest and the broader test suite.Assistant
Now let me run the full ty_python_semantic test suite to ensure nothing is broken.
Assistant
All 204 lib tests pass. Now let me run the broader ty integration tests (mdtest) to check for regressions, especially around variance and type aliases. Let me find how to run them.
Assistant
Let me look at the existing variance mdtest files and the cyclic variance corpus.
Assistant
Let me look at the variance mdtest files and how to run mdtest.
Assistant
Let me check how to run the mdtest integration tests.
Assistant
Let me run the mdtest for the variance-related files.
Assistant
Both variance mdtests pass. Let me run the broader generics and type_properties mdtests to check for regressions.
Assistant
All pass. Let me run the full mdtest suite and corpus test to be thorough.
Assistant
A stack overflow occurred — likely a recursive alias case causing infinite recursion. Let me find which test caused it by capturing output.
Assistant
The crash is around
type_compendium. Let me run those tests specifically.Assistant
Let me run with a single test thread to find the culprit deterministically.
Assistant
The crash is after
pep613_type_aliases.md. Let me find which test comes next alphabetically.Assistant
The crash is in
pep695_type_aliases.md. Let me run it specifically.Assistant
Let me look at the
pep695_type_aliases.mdtest file for recursive alias cases.Assistant
The
Foo/Barmutually-recursive-via-union case (with typevars) causes infinite recursion because the cycle throughType::TypeAliashas no cycle detection. The fix: maketype_alias_variance_ofa salsa-tracked query with a bivariant cycle fallback (likeGenericAlias::variance_of). Let me look at howGenericAlias::variance_ofis tracked.Assistant
Let me look at how free salsa-tracked functions with cycle handling are defined, to mirror the pattern.
Assistant
Let me check the salsa version and its
cycle_initialsignature to get the param count right.Assistant
Let me verify that
cycle_initialalone (withoutcycle_fn) is valid by checking the salsa macro.Assistant
Let me confirm the
cycle_initialclosure signature (param order/count) from the salsa macro.Assistant
Let me check the macro's generated wrapper to determine the exact user closure signature for
cycle_initial.Assistant
The
cycle_initialclosure signature for my free function(db, type_alias, typevar)is|db, id, type_alias, typevar|= 4 params, matchingGenericAlias::variance_of. Let me convert the helper to a salsa-tracked function with a bivariant cycle fallback.Assistant
Let me rewrite the helper to be salsa-tracked with a bivariant cycle fallback.
Assistant
Let me find the exact end line of the function.
Assistant
Let me replace the function (lines 6883-6912) with the salsa-tracked version.
Assistant
Now let me rebuild and run the temp test plus the problematic
pep695_type_aliasesmdtest.Assistant
The stack overflow is fixed. Let me run the full mdtest suite again.
Assistant
All 338 mdtests pass. Let me also run the corpus test and the property tests.
Assistant
All tests pass. Let me also verify the actual
BoundTypeVarInstance::variance()path (used in type checking) returns correct results. Let me update my temp test to also check that.Assistant
Let me use the edit command to add the
variance()check.Assistant
Both paths are correct. Let me check the legacy variance mdtest to understand what "legacy generic type aliases" covers in the contract.
Assistant
The legacy variance test covers legacy
TypeVar/Genericclasses. My fix handles alias values regardless of representation. Let me check hover tests that might display variance, and run the ty_ide tests.Assistant
There's a hover test checking variance display. Let me run the ty_ide tests.
Assistant
There's a
hover_type_alias_typevar_variancetest. Let me look at it.Assistant
The hover tests pass. Now, per the instructions, I must remove my temporary test before submitting (no adding/modifying tests). Let me first review the full diff of my source changes, then remove the temp test.
Assistant
Let me review the full source diff (excluding tests.rs which I'll revert).
Assistant
The source diff is clean. Now let me revert
tests.rsto remove my temporary test (per instructions, no adding/modifying tests).Assistant
Let me rebuild and run the existing tests to confirm everything passes after reverting the test file.
Assistant
Let me run the full lib test suite and key mdtests once more to confirm everything is green.
Assistant
The mdtest harness only takes one filter. Let me run them separately or with a common substring. Let me just run the full mdtest again (it took 13s before).
Assistant
All 338 mdtests pass. Let me verify the "reordered multi-parameter" case and the legacy
TypeAliasTypeconstructor case work, by temporarily re-adding a focused test.Assistant
Let me re-add a focused temp test to verify the reordered multi-parameter case and other edge cases, then remove it.
Assistant
Need a blank line before
#[test]. Let me add it.Assistant
All edge cases pass including reordered multi-parameter chains. Let me also verify the trickiest case — mutually recursive aliases through unions with typevars (Foo/Bar) — yields correct variance and terminates.
Assistant
The sed failed due to delimiter conflict. Let me check the current state and use the edit command instead.
Assistant
Let me view the relevant section and use the edit command to add the Foo/Bar cases.
Assistant
All edge cases pass, including mutually recursive via list+union (Foo/Bar → Invariant, terminates via cycle fallback) and self-recursive via union (SelfOr → Bivariant). Now let me revert the test file since I must not add tests.
Assistant
Now let me do a final compile check and run the key tests to confirm everything is green after reverting the test file.
Assistant
Let me run clippy to ensure no lint issues were introduced.
Assistant
Clippy passes cleanly. Let me check the changelog convention to see if I should add an entry.
Assistant
The changelogs are release-generated and the
tychangelog lives in a separate repo. I'll skip that. Let me do a final review of the complete diff.Assistant
The diff is clean and minimal — exactly two source files modified. Let me do a final verification that there are no stray files and run the full relevant test suites one final time.
Assistant
Only the two source files are modified, no stray files. Let me run a final combined verification of the lib tests and full mdtest suite.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.