Skip to content

Expand TypeVar subject in sequence and mapping pattern narrowing - #11959

Open
crypt0lith wants to merge 5 commits into
microsoft:mainfrom
crypt0lith:fix/pattern-info-unconcretized-typevar-subj
Open

crypt0lith wants to merge 5 commits into
microsoft:mainfrom
crypt0lith:fix/pattern-info-unconcretized-typevar-subj

Conversation

@crypt0lith

@crypt0lith crypt0lith commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #10689

Sequence and mapping patterns on a TypeVar subject are reported as never matched when the TypeVar has no bound, is bound to Any or to a union, or is constrained. Narrowing a TypeVar subject to a tuple also yields a tuple type that isn't assignable back to the TypeVar.

Root cause

  • getSequencePatternInfo and getMappingPatternInfo make each subtype concrete, but their fallback subtype and supertype checks against Sequence and Mapping receive the TypeVar instead of its concrete type, and reject it.
  • A union bound or constraints concretize to a union, which these functions handle as a single subtype. It isn't a class instance, so the sequence fallback runs against the TypeVar and the mapping function records nothing for it.
  • narrowTypeBasedOnSequencePattern builds the narrowed tuple and Sequence types without the TypeVar's condition.

Fix

  • Expand TypeVar subjects per subtype and run the checks against each expanded subtype.
  • Keep the TypeVar as the narrowed type when narrowing leaves its expanded subtypes unchanged; otherwise use the expanded subtypes that remain, as class patterns do, with matched NotRequired entries marked provided.
  • Add the TypeVar's condition to the narrowed tuple and Sequence types, building it from the TypeVar when its concrete type is Any.

Test

Cases added to matchUnnecessary1.py
Case Expected Description
func6 sequence and mapping patterns on unbounded TypeVar
func7 same patterns on TypeVar with union bound
func8 same patterns on constrained TypeVar
func9 same patterns on TypeVar bound to Any
func10 error same patterns on TypeVar bound to int
func11 error same patterns on TypeVar constrained to int and str
Cases added to matchSequence1.py
Case Expected Description
test_typevar_subject unbounded TypeVar narrows to conditioned Sequence, unmatched keeps TypeVar
test_any_bound_typevar_subject Any bound narrows to conditioned Sequence[Any]
test_tuple_bound_typevar_subject tuple bound keeps condition in both narrowed tuples
test_union_bound_typevar_subject union bound narrows to matching member, unmatched keeps TypeVar
test_constrained_typevar_subject constraints narrow to conditioned constraint types
Cases added to matchSequence3.py
Case Expected Description
func5 TypeVar bound to tuple subclass kept when no entry narrowed
func6 error entry narrowed, so TypeVar bound to tuple subclass loses subclass attribute
Cases added to matchMapping1.py
Case Expected Description
test_typevar_subject unbounded TypeVar kept by mapping pattern
test_union_bound_typevar_subject union bound narrows to Mapping member, unmatched keeps TypeVar
test_union_bound_typevar_subject_expand_entry **rest-only pattern leaves non-mapping member
test_union_bound_typevar_negative_narrowing unmatched removes matched TypedDict member from union bound
test_union_bound_typevar_negative_exhaustion discriminant cases exhaust TypedDict union bound
test_union_bound_typevar_not_required_narrowing matched NotRequired key accessible after narrowing union bound
test_union_bound_typevar_not_required_access error unmatched NotRequired key not accessible after narrowing union bound
Cases added to matchExhaustion1.py
Case Expected Description
func12 sequence then class pattern exhausts union-bound TypeVar
func13 sequence then class pattern exhausts constrained TypeVar

Expected error counts changed: MatchUnnecessary1 (7 -> 11), MatchSequence3 (1 -> 2)

getSequencePatternInfo and getMappingPatternInfo run their Sequence
and Mapping assignability checks against a TypeVar subject instead of
its concrete type, and treat a union bound or constraints as a single
non-class subtype, so the patterns are reported as never matched.
Expand the TypeVar per subtype, and keep its condition on narrowed
tuple and Sequence types.

Fixes microsoft#10689
@bschnurr

Copy link
Copy Markdown
Member

Looks good. The TypeVar condition is now retained, and the merge with main (including #11785) builds and passes the Match tests.

Non-blocking follow-up (pre-existing on main, not a regression from this PR): a TypeVar bound to a tuple subclass still loses the subclass after a sequence pattern that doesn't narrow it, unlike the concrete-class case fixed in #11785:

class Pair(tuple[int, int]):
    def marker(self) -> None: ...

TPair = TypeVar("TPair", bound=Pair)

def generic_pair(value: TPair) -> TPair:
    match value:
        case (first, second):
            value.marker()  # still reportAttributeAccessIssue; narrowed to tuple[int, int]*
            return value
        case _:
            return value

If it's easy to preserve the bound subclass here, adding it to this PR would be nice. Otherwise it can be a follow-up.

🤖 AI-assisted review posted on behalf of Bill Schnurr (@bschnurr).

@rchiodo Rich Chiodo (rchiodo) left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's a pre-existing negative-path case that the new positive narrowing exposes:

from typing import Literal, TypedDict, TypeVar, assert_never
class A(TypedDict):
    kind: Literal['a']
    x: int
class B(TypedDict):
    kind: Literal['b']
    y: str
TAB = TypeVar('TAB', bound=A | B)
def generic(x: TAB) -> TAB:
    match x:
        case {'kind': 'a'}: return x
        case {'kind': 'b'}: return x
        case _: assert_never(x)
def concrete(x: A | B) -> A | B:
    match x:
        case {'kind': 'a'}: return x
        case {'kind': 'b'}: return x
        case _: assert_never(x)

Both revisions report an error at assert_never in generic because the wildcard retains TAB. The concrete union is exhaustive. On 72bb148, the positive cases narrow to A* and B*; base treated them as unreachable. Could the negative matching path expand the bound too, with an exhaustiveness test? I haven't tested that change.

There's also a possible scaling issue in getNarrowedSubtypes. It filters and recombines all entries and concretizes the whole TypeVar again for each entry of the same TypeVar. With N conditioned literal subtypes, the literal-map fast path is bypassed, so repeated union construction looks like it can do roughly cubic work. The tuple-expansion cap comes later.

The stress case used a TypeVar bound to 100 distinct string literals, with tuple, starred-list and one-element sequence cases plus a wildcard. Shared-host runs looked substantially slower, but they were contended. The performance impact is inconclusive, and there's no clean benchmark or defensible number. Would grouping or caching entries once per TypeVar help, or could we run an uncontended scaling test? I haven't tested the grouping or caching idea.

The existing tests already cover constrained int/str and other sequence-plus-class exhaustion, but a few additional controls might be useful:

  • Returning an unrelated T where U is expected should still error after narrowing.
  • Standalone TypeVars bounded to str or bytes should still never match sequence patterns.
  • Exhaustion across different tuple arities, or a starred-list case followed by a str case.

@crypt0lith
crypt0lith force-pushed the fix/pattern-info-unconcretized-typevar-subj branch from 7c98fe9 to d4e5506 Compare November 23, 2026 14:08
@crypt0lith

Copy link
Copy Markdown
Contributor Author

The repeated union construction in #11959 (review) is cached per TypeVar in 16a90cb.

The exhaustiveness case in #11959 (review) and the tuple subclass case in #11959 (comment) are fixed in d4e5506.

@heejaechang

Heejae Chang (heejaechang) commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

🟢 Pyright CLI QA — c5c7e810 — verdict: green

Automated CLI checks compared this change with its base revision.
10 focused check(s) completed.

No new behavior difference was detected.

@bschnurr Bill Schnurr (bschnurr) left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current per-TypeVar cache addresses the repeated recombination in my earlier review. One remaining performance question is that getNarrowedSubtypes still filters all entries once per distinct TypeVar, so grouping costs O(k*n) for k TypeVars and n expanded entries.

I compared the base and this head with five alternating runs of a single TypeVar bound to 512 literals. Median checker time was 0.84s versus 0.88s; the shared host had substantial wall-time outliers. This does not establish a performance regression or measure the distinct-TypeVar case. Could we check that scaling, alongside the pending benchmark, before deciding whether one-pass grouping is needed?

I also replayed the earlier NotRequired QA cases: the matched-key false positives are gone, and the missing-key negative control still reports an error. The evaluator suite passed on this head.

@github-actions

Copy link
Copy Markdown
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

@github-actions

Copy link
Copy Markdown
Contributor

Compared candidate 6836f883cf56addc84cc54c6ce087b7b0298dcee against its first parent 2981f9f1ce41be5c15667da1f7a3cfda4f245089.

Release history charts were not rendered for this run. See the workflow run for details.

Type checker benchmark

🟢 No performance regressions detected.

Regression threshold: 20.0%
Statistic: median
Variance guard: >1.0s time and >100.0 MB memory

Package Checker Files checked Time Time delta Peak memory Memory delta Status
ansible pyright 583 16.285s +1.6% 1075.1 MB -0.4% 🟢 Pass
click pyright 17 2.974s -0.6% 358.0 MB -0.3% 🟢 Pass
homeassistant pyright 9850 115.056s +0.7% 5999.4 MB +0.1% 🟢 Pass
numpy pyright 356 34.518s +0.5% 1299.0 MB -1.2% 🟢 Pass
pandas pyright 1459 138.124s +3.2% 3599.0 MB -0.9% 🟢 Pass
pytest pyright 243 9.914s -0.5% 865.5 MB -0.1% 🟢 Pass
requests pyright 19 1.862s +0.3% 343.0 MB -0.9% 🟢 Pass
torch pyright 2400 105.502s +1.7% 4616.1 MB -0.3% 🟢 Pass
transformers pyright 2901 83.069s +0.2% 5193.2 MB +0.0% 🟢 Pass

Pyright stats

Package Parsed/bound Checked Find Read Tokenize Parse Imports Bind Check Cycles
ansible 988 583 0.030s 0.067s 0.293s 0.563s 0.177s 0.753s 13.603s 0.000s
click 111 17 0.000s 0.013s 0.107s 0.190s 0.030s 0.250s 2.077s 0.000s
homeassistant 11154 9850 0.530s 0.643s 2.440s 4.340s 1.683s 5.630s 96.450s 0.000s
numpy 606 356 0.010s 0.063s 0.333s 0.557s 0.223s 0.760s 32.143s 0.000s
pandas 1899 1459 0.070s 0.220s 1.263s 2.530s 0.267s 2.687s 129.477s 0.000s
pytest 545 243 0.013s 0.050s 0.287s 0.413s 0.093s 0.550s 8.137s 0.000s
requests 167 19 0.000s 0.013s 0.087s 0.167s 0.043s 0.210s 1.080s 0.000s
torch 3078 2400 0.120s 0.387s 1.573s 3.143s 0.567s 4.070s 92.810s 0.000s
transformers 3546 2901 0.097s 0.323s 1.537s 2.537s 0.763s 6.693s 72.957s 0.000s

@crypt0lith

Copy link
Copy Markdown
Contributor Author

Bill Schnurr (@bschnurr) Each distinct TypeVar contributes at least one expanded entry, so $k \le n$ and the grouping is $O(n^2)$ at worst. Expanded entries carry the TypeVar's condition, and _addTypeIfUnique skips the literal maps for conditioned types, so combineTypes already costs $O(n^2)$ on those entries, both per group and for the narrowed union the caller builds:

// Handle the addition of a string literal in a special manner to
// avoid n^2 behavior in unions that contain hundreds of string
// literal types. Skip this for constrained types.
if (isClass(typeToAdd) && !typeToAdd.props?.condition) {

Grouping in one pass wouldn't change the overall bound.

The benchmark on c5c7e81 found no regressions; every time delta is within +3.2%: #11959 (comment)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

sequence or mapping pattern on generic variables makes case unreachable

4 participants