Skip to content

Fix false positive reportOverlappingOverload for recursive TypeVar lower bounds - #11579

Merged
Rich Chiodo (rchiodo) merged 6 commits into
microsoft:mainfrom
crypt0lith:fix/recursive-lowerbound-occurs-check
Oct 5, 2026
Merged

Rich Chiodo (rchiodo) merged 6 commits into
microsoft:mainfrom
crypt0lith:fix/recursive-lowerbound-occurs-check

Conversation

@crypt0lith

@crypt0lith crypt0lith commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes a regression introduced by #11415.

This caused a false positive reportOverlappingOverload on valid overloads whose return types are generic in a recursive way. The occurs check rejected an assignment when recording the lower bound would create a cyclic constraint. It did not account for the case where constraints is undefined: this is used when the caller is only testing assignability, not solving for the TypeVar, so nothing is propagated and the cyclic lower bound is satisfiable. Overload return-consistency checking uses such an assignability test, so valid overloads that the overlap check treated as overlapping were reported as returning an incompatible type.

Root cause

Overload return-consistency checking calls assignType(returnType, prevReturnType, /* constraints */ undefined, ...) (checker.ts) purely to test whether the earlier overload's return is assignable to the later one. When the two returns are generic such that this test must solve V :> C[V] (a TypeVar required to be a supertype of a type that mentions it), the assignment reaches the occurs check in assignUnconstrainedTypeVar.

The occurs check treats any such cyclic lower bound as unsatisfiable and returns false. This is correct when solving for the TypeVar, since propagating the self-reference expands without terminating. On an assignability test nothing is propagated, and the constraint is satisfiable when the source meets the TypeVar's bound. The partial-overlap check in assignFunction also treats two parameters that both have defaults as a possible match, even when the overloads overlap only when that argument is omitted. This surfaces as overloadReturnTypeMismatch under the reportOverlappingOverload rule.

Fix

Gate the rejection on constraints being defined. When constraints is undefined the caller is only testing assignability, so instead of rejecting, keep the actual source as the lower bound and let the TypeVar's bound check run against it. The constraint-solving path is unchanged and continues to reject as before, preserving the original hang fix.

Add an AssignTypeFlags.RejectCyclicLowerBound flag that keeps the rejection without a tracker. Overload return-consistency checking sets it, and the upper bound check in assignUnconstrainedTypeVar, protocol member comparisons, and assignProperty's accessor comparison pass it through. In assignFunction, don't count two defaulted parameters as a partial overlap when they overlap only through omission of the argument and the earlier overload accepts every argument list the later one accepts, with the later overload's TypeVars held fixed.

Test

Changes to overloadOverlap1:

  • func37: an overload pair where a broader argument type can select either overload and whose returns induce the V :> C[V] constraint. It is now marked as reported.
  • func38: an overload pair with the same return shape that overlaps only through an omitted defaulted parameter. It reports a false positive without the fix and is clean with it.
  • func39: the same shape as func37 in a signature with a generic parameter, which must still be reported.
  • func40: an overload pair that differs in an omitted defaulted parameter and also in another parameter the earlier overload doesn't fully accept, which must be reported.
  • func41: the keyword-only counterpart of func40, which must be reported.
  • func42: the callback protocol counterpart of func39, which must be reported.
  • func43: an overload pair whose overloads both share one constrained TypeVar across two parameters and overlap only through an omitted defaulted parameter, which must stay clean.
  • func44: the counterpart of func43 where the later overload uses independent TypeVars for those parameters, so the earlier overload doesn't accept every combination. It must be reported.
  • func45 and func46: the invariant counterparts of func43 (clean) and func44 (reported).
  • func47: the property counterpart of func42, where the protocols expose the callable through a property, which must be reported.

Adds constraintSolver.test.ts, which checks that without a tracker a recursive source is rejected when it violates the TypeVar bound and accepted when it satisfies it.

@crypt0lith

Copy link
Copy Markdown
Contributor Author

@microsoft-github-policy-service agree

@crypt0lith
crypt0lith force-pushed the fix/recursive-lowerbound-occurs-check branch from b358067 to 1416fdd Compare August 2, 2026 23:40
@rchiodo

Rich Chiodo (rchiodo) commented Aug 3, 2026 •

Copy link
Copy Markdown
Collaborator

🔒 Automated review in progress — Rich Chiodo (@rchiodo) is auto-reviewing this PR.

@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.

Approved via Review Center.

@rchiodo Rich Chiodo (rchiodo) added the review-auto:approved Automated review: no blocking findings (approval posted). label Aug 3, 2026

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.

Approved via Review Center.

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.

Approved via Review Center.

@StellaHuang95

Stella Huang (StellaHuang95) commented Aug 10, 2026 •

Copy link
Copy Markdown
Collaborator

🔒 Automated review in progress — Stella Huang (@StellaHuang95) is auto-reviewing this PR.

@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.

Approved via Review Center.

@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.

Approved via Review Center.

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.

Approved via Review Center.

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.

Approved via Review Center.

…wer bounds

The occurs check in assignUnconstrainedTypeVar (added in microsoft#11415) rejects
an assignment when recording the lower bound would create a cyclic
constraint. It does not account for the case where constraints is
undefined: this is used when the caller is only testing assignability,
not solving for the TypeVar, so nothing is propagated and the cyclic
lower bound is satisfiable. Overload return-consistency checking uses
such an assignability test, so rejecting in that scenario reported valid
overloads as overlapping with an incompatible return type.

Add a check for whether constraints is defined before rejecting the
assignment; when it is undefined, widen the lower bound to 'Unknown'
(a valid solution) to escape infinite recursion and proceed with the
assignability test as normal.

Adds a regression test case func37 in overloadOverlap1 that reports a
false positive without the fix.
@crypt0lith
crypt0lith force-pushed the fix/recursive-lowerbound-occurs-check branch from 1416fdd to 979506c Compare August 26, 2026 18:58
@crypt0lith

Copy link
Copy Markdown
Contributor Author

Rebased onto main to resolve merge conflict in packages/pyright-internal/src/tests/samples/overloadOverlap1.py (renamed func35 to func37)

@heejaechang

Heejae Chang (heejaechang) commented Sep 22, 2026 •

Copy link
Copy Markdown
Collaborator

🔴 Pyright CLI QA — 67e187ef — verdict: red

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

Needs review: reportOverlappingOverload no longer reported

The base reports reportOverlappingOverload for this example; the PR does not. Is this change intended?

Reproduction and observed results

Create these files in an empty directory:

README.md

# Defaulted overloads with enum aliases

Python Enum members initialized with the same value are aliases: `Mode.PRIMARY is Mode.ALIAS` is true. Consequently, the two overloads accept the same explicit argument, not merely a shared omitted argument. They promise incompatible return types for that argument.

The base reports `reportOverlappingOverload`. The candidate reports no error. Both reveal `str` for the alias call, even though this implementation returns `int` for the shared enum member. The inference of separate literal names already exists in the base; the regression being checked is the loss of its unsafe-overlap diagnostic when defaults are present.

main.py

from enum import Enum
from typing import Literal, overload, reveal_type

class Mode(Enum):
    PRIMARY = "same"
    ALIAS = "same"

# The two names denote the same enum member, not disjoint modes.

@overload
def convert(mode: Literal[Mode.PRIMARY] = Mode.PRIMARY) -> int: ...
@overload
def convert(mode: Literal[Mode.ALIAS] = ...) -> str: ...
def convert(mode: Mode = Mode.PRIMARY) -> int | str:
    if mode is Mode.PRIMARY:
        return 0
    return "other"

# Both calls return int at runtime; the conflicting overloads should be flagged.
reveal_type(convert())
reveal_type(convert(Mode.ALIAS))

pyrightconfig.json

{
  "include": [
    "*.py"
  ],
  "pythonVersion": "3.13",
  "typeCheckingMode": "standard"
}

From that directory, run each built Pyright revision:

node <pyright-cli-entrypoint> --outputjson -p .

Base 37c03866d7929e4745e802c37e7e9bcabeda080b

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "main.py",
      "severity": "error",
      "rule": "reportOverlappingOverload",
      "message": "Overload 1 for \"convert\" overlaps overload 2 and returns an incompatible type",
      "range": {
        "start": [
          10,
          4
        ],
        "end": [
          10,
          11
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"convert()\" is \"int\"",
      "range": {
        "start": [
          19,
          12
        ],
        "end": [
          19,
          21
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"convert(Mode.ALIAS)\" is \"str\"",
      "range": {
        "start": [
          20,
          12
        ],
        "end": [
          20,
          31
        ]
      }
    }
  ]
}

PR 67e187ef49c212fd6ac6146aba712f5e2232fd56

{
  "exit_code": 0,
  "diagnostics": [
    {
      "file": "main.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"convert()\" is \"int\"",
      "range": {
        "start": [
          19,
          12
        ],
        "end": [
          19,
          21
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"convert(Mode.ALIAS)\" is \"str\"",
      "range": {
        "start": [
          20,
          12
        ],
        "end": [
          20,
          31
        ]
      }
    }
  ]
}

Diagnostic ranges use zero-based line and character positions.

@crypt0lith

Copy link
Copy Markdown
Contributor Author

The base reports reportOverlappingOverload for this example; the PR does not. Is this change intended?

That false positive reportOverlappingOverload is precisely what this PR exists to address, so yes the change is intended.

@heejaechang

Copy link
Copy Markdown
Collaborator

I understand the false-positive argument when a recursive TypeVar constraint shows up during assignability testing rather than actual type solving.

What I'm struggling with is the tradeoff. For concrete incompatible types, we still report an error. With this change, it seems like recursive TypeVar cases go from "can't satisfy this constraint" to "don't report an error".

In a case like T :> list[T], there doesn't seem to be any obvious finite solution. Wouldn't this change suppress what could be a legitimate reportOverlappingOverload diagnostic?

Put another way, why is it better to assume this is a false positive rather than a real overlap issue? Have you seen many examples where the current behavior reports an error incorrectly, versus catching a genuinely problematic overload?

@crypt0lith

Copy link
Copy Markdown
Contributor Author

In your repro you used this:

@overload
def factory[T](tag: str, value: T) -> Callable[[T], list[T]]: ...
@overload
def factory[T](tag: object, value: T) -> Callable[[T], T]: ...
def factory[T](tag: object, value: T) -> Callable[[T], T | list[T]]:
    def callback(x: T) -> T | list[T]:
        return [x] if isinstance(tag, str) else x
    return callback

This is legitimate Python and correctly typed. On the base, this produced a false-positive diagnostic; on the PR, this does not produce that same diagnostic. Pre-regression, that would also not have produced the same diagnostic.

During overlapping overload validation, we are not looking for a finite solution, we are looking for a finite least solution. When one does not exist, as in the recursive generic case, that lower bound can be safely widened to Unknown to allow the assignability test to continue as before. It is not changing assignability test semantics. It is simply not failing at the occurs check, to preserve pre-regression behavior as well as the hang fix which the occurs check was implemented to address.

@heejaechang

Copy link
Copy Markdown
Collaborator

This used to pass, but was that intentional behavior, or did the old check miss an unsafe overlap that the hang fix happened to expose?

In the repro, use("wrap") is typed as returning int, but actually returns [1]. Isn't that what this diagnostic is meant to catch?

My question is whether reporting the diagnostic is correct for this example, rather than whether this restores the previous behavior.

@crypt0lith

crypt0lith commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor Author

#11415 added the occurs check to fix a hang in the constraint solver. It wasn't meant to change how overload overlaps are evaluated, but it did: overload pairs that were never reported before now get reportOverlappingOverload. This PR undoes that side effect and keeps the hang fix. Rejection still happens whenever constraints are being solved.

I compared the behavior across a range of overload shapes. This PR gives the same results as 1.1.409 (before #11415) on all of them, so it restores the previous behavior without changing anything else. mypy also leaves the example from the QA comment unreported.

Whether Pyright should report overlaps like this one is a fair question, but it's a policy change and should be proposed and reviewed on its own, not inherited as a side effect of a hang fix. That's outside this PR's scope.

@github-actions

This comment has been minimized.

@heejaechang

Copy link
Copy Markdown
Collaborator

Regardless of how the behavior changed, my question is whether the diagnostic is correct. Restoring the previous behavior doesn't by itself mean we're fixing a false positive.

You said this is a false positive, so can you give us an example where the diagnostic is incorrect? Then we can see whether we can remove it for that class of false positives while keeping it for cases where it correctly catches an unsafe overlap.

I don't think debating the process helps here. Let's focus on the examples and what the product should report.

@github-actions

This comment has been minimized.

@crypt0lith

crypt0lith commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor Author

The occurs check from #11415 treats R :> R | Awaitable[R] as having "no finite solution" (see its code comment), but object satisfies it. In assignability-only checks any solution suffices, so rejecting it produces false positives: e.g. sympy rings.py:907–908, where PolyElement[Er] is reported as violating its RingElement bound, which the same file uses without error at lines 340/499/543/686, and which 1.1.409 didn't report.

I'd appreciate a maintainer's call explicitly on whether this approach is acceptable or should be narrowed.

@heejaechang

Copy link
Copy Markdown
Collaborator

The SymPy example you gave doesn't show reportOverlappingOverload, even before this PR. It shows reportInvalidTypeArguments. That diagnostic serves a different purpose, although both can be affected by the same code path.

I think we should handle the cases like this:

Case Assessment Desired outcome
SymPy's two reported bound errors False positives Fix those reportInvalidTypeArguments errors
factory and func37 unsafe overloads Correct diagnostics Keep reportOverlappingOverload
Original recursive-inference hang Real bug Keep the hang fix

We should fix the SymPy false positives without losing the diagnostics that correctly catch unsafe overloads.

@crypt0lith

Copy link
Copy Markdown
Contributor Author

To evaluate the plan in your table, I prototyped a principled version of the second row (reporting reportOverlappingOverload for unsafe overlaps) on top of this PR: crypt0lith/pyright@a7eb5f6. I'm not proposing it for merge. It's here so the policy can be judged on its results.

Main's behavior doesn't implement that row. I tested nine overload pairs with the same hazard as factory: a runtime value selects the narrow overload while the static type selects the wide one. Main flags three of them, func37, factory and d (factory with overload 2's TypeVar renamed), and only because #11415's occurs check fires inside the upper-bound consistency probe in assignUnconstrainedTypeVar. That probe is reached only when overload 2's returned Callable takes the TypeVar as a parameter. factory without the Callable (r2: list[T] → T) isn't flagged on main.

Repro: the nine unsafe pairs and three safe controls
from typing import Any, Callable, overload

# func37: this PR's regression sample
@overload
def func37[V](x: str) -> Callable[[V], list[V]]: ...
@overload
def func37[V](x: Any) -> Callable[[V], V]: ...
def func37(x: Any) -> Any: ...

# factory: the QA bot's repro
@overload
def factory[T](tag: str, value: T) -> Callable[[T], list[T]]: ...
@overload
def factory[T](tag: object, value: T) -> Callable[[T], T]: ...
def factory(tag: object, value: object) -> Any: ...

# d: factory with overload 2's TypeVar renamed
@overload
def d[T](tag: str, value: T) -> Callable[[T], list[T]]: ...
@overload
def d[U](tag: object, value: U) -> Callable[[U], U]: ...
def d(tag: object, value: object) -> Any: ...

# r2: factory without the Callable
@overload
def r2[T](tag: str, value: T) -> list[T]: ...
@overload
def r2[T](tag: object, value: T) -> T: ...
def r2(tag: object, value: object) -> Any: ...

@overload
def n1[V](x: str, y: V) -> Callable[[V], list[int]]: ...
@overload
def n1[V](x: object, y: V) -> Callable[[V], V]: ...
def n1(x: object, y: object) -> Any: ...

@overload
def n2(tag: str, value: int) -> list[int]: ...
@overload
def n2[T](tag: object, value: T) -> T: ...
def n2(tag: object, value: object) -> Any: ...

@overload
def k1[T](tag: str, value: T) -> Callable[[], list[T]]: ...
@overload
def k1[U](tag: object, value: U) -> Callable[[], U]: ...
def k1(tag: object, value: object) -> Any: ...

@overload
def k2[T](tag: str, value: T) -> Callable[[int], list[T]]: ...
@overload
def k2[U](tag: object, value: U) -> Callable[[int], U]: ...
def k2(tag: object, value: object) -> Any: ...

@overload
def k3[T](tag: str, value: T) -> tuple[T, list[T]]: ...
@overload
def k3[U](tag: object, value: U) -> tuple[U, U]: ...
def k3(tag: object, value: object) -> Any: ...

# Safe controls
@overload
def s1(x: int) -> int: ...
@overload
def s1(x: object) -> object: ...
def s1(x: object) -> object: ...

@overload
def s2[T](x: list[T]) -> list[T]: ...
@overload
def s2[T](x: T) -> T: ...
def s2(x: object) -> object: ...

@overload
def s3[T](x: int, y: T) -> list[T]: ...
@overload
def s3[T](x: str, y: T) -> T: ...
def s3(x: object, y: object) -> object: ...

reportOverlappingOverload results:

Pairs 1.1.409 1.1.410 (main) this PR prototype mypy 2.3.1
func37, factory, d — error — error —
r2, n1, n2, k1, k2, k3 — — — error —
s1, s2, s3 — — — — —

The prototype changes only the return check in _validateOverloadConsistency:

  • Overload 1's TypeVars are bound in the return comparison, the same way _isOverlappingOverload already binds them for the parameter check. list[T] vs T then fails by ordinary assignability, without the occurs check.
  • The parameter-overlap check's constraint solutions are applied to overload 2's return type, so its TypeVars reflect the overlapping arguments instead of being solved freely.

It flags all nine unsafe pairs and leaves the safe controls alone. It also reports these new errors:

Where New errors mypy on the same pairs
Pyright's test samples 6, in 5 overload sets (incl. func37) none flagged
typeshed builtins.sum 1 none flagged
prefect 8 none flagged
xarray 5 none flagged
sympy, jax, home-assistant 0 —

The builtins.sum error is on overloads typeshed ordered deliberately (builtins.pyi):

# In general, the return type of `x + x` is *not* guaranteed to be the same type as x.
# However, we can't express that in the stub for `sum()`
# without creating many false-positive errors (see #7578).
# Instead, we special-case the most common examples of this: bool and literal integers.

The first overload is typeshed's fix for the second overload's known unsoundness, and it's the one the prototype flags.

Two of the new errors are wrong even by the runtime-soundness standard: prefect's run_task and xarray's NamedArray._new. In each, the overloads differ in a defaulted parameter with disjoint types (Literal["state"] vs Literal["result"], or duckarray vs a Default sentinel). The only calls that match both omit that parameter, and omission selects overload 1 both statically and at runtime.

So a correct version of the second row is a policy change in its own right. It needs decisions on Any (mypy exempts it, and func37 depends on that), on narrow-before-wide into an identity TypeVar (the sum shape), on sync/async dispatch (Callable[..., Awaitable[T]] before Callable[..., T]), and on overlap only through omitted defaults. None of this depends on the occurs check, and none of it touches the constraints === undefined path this PR relaxes. The two can be evaluated independently.

Method and details
  • Prototype: crypt0lith/pyright@a7eb5f6, stacked on this PR's head (979506c), which is the baseline for every comparison.
  • Primer: mypy_primer run locally against each project's current HEAD, not the bot's snapshot. The projects are the ones in this PR's and Fix hang in constraint solver for cyclic TypeVar lower bounds (#11413) #11415's primer results.
  • mypy 2.3.1: prefect was checked with follow_imports=silent, since its configured skip would make every prefect-internal type Any. xarray was checked with its own config. Neither run had the projects' full dependencies installed.
  • Typeshed: Pyright doesn't report diagnostics in files under the typeshed path, so I checked the sum overloads in a standalone stub.

New project errors:

Location Overloads Shape
prefect task_engine.py:1846 run_task 1 vs 2 return_type: Literal["state"] = "state" vs return_type: Literal["result"] = "result"
prefect task_runners.py and prefect_dask/task_runners.py submit, map (4) 1 vs 2 coroutine-returning task vs plain task: Task[P, Coroutine[Any, Any, R]] (or CoroutineType) vs Task[Any, R] (or Task[P, R])
prefect flows.py:1781, :2432 __call__ 1 vs 3 self: Flow[P, NoReturn] -> None vs self: Flow[P, T] -> T
prefect tasks.py:1154 __call__ 5 vs 7 self: Task[..., Coroutine[Any, Any, T]] vs self: Task[..., T]
xarray backends/common.py:57 _normalize_path 1 vs 3 (PathLike) -> str vs (T) -> T
xarray backends/scipy_.py:55 _decode_string 1 vs 2 (bytes) -> str vs (T) -> T
xarray namedarray/core.py:274 _new, plus 2 test subclasses 1 vs 2 data: duckarray[...] = ... vs data: Default = ...

@bschnurr

Copy link
Copy Markdown
Member

/benchmark

@github-actions

This comment has been minimized.

@crypt0lith

Copy link
Copy Markdown
Contributor Author

can you give us an example where the diagnostic is incorrect?

from typing import Any, Callable, Literal, overload

@overload
def g1[T](value: T, mode: Literal["wrap"] = "wrap") -> Callable[[T], list[T]]: ...
@overload
def g1[T](value: T, mode: Literal["id"] = ...) -> Callable[[T], T]: ...
def g1(value: object, mode: str = "wrap") -> Any: ...

When a caller omits mode, overload 1 is selected as the default both statically and at runtime.

On current main (1.1.410-1.1.414) this reports the reportOverlappingOverload diagnostic, which is incorrect even by the runtime-safety standard.

@rchiodo

Copy link
Copy Markdown
Collaborator

I think a narrower fix would be preferable here: address the demonstrated default-only overlap false positive in overlap checking, rather than making recursive assignability succeed globally by substituting Unknown.

The g1 example is a useful positive case. I verified that the patch removes its false positive while preserving the precise return types and matching runtime behavior. However, the factory counterexample still loses a useful diagnostic: its callback remains typed as (int) -> int, while use("wrap") returns [1]; using that result with + 1 raises TypeError. These comparisons used this patch rebased onto fe14a8e051c63f1ea1b76ac08227f73aa923032f, not a new published PR revision.

Suggested direction:

  1. Preserve the occurs-check protection against storing cyclic bounds and the existing checks against the actual source type. An absent ConstraintTracker means this particular call does not retain a solution; it does not remove its compatibility obligations.
  2. Handle the g1 case in the partial-overlap/default-argument logic used by _validateOverloadConsistency. For demonstrably disjoint explicit discriminants, distinguish overlap only through omission of a defaulted parameter, where the first overload also determines the omitted-argument result. This should not exempt cases like factory, where a broader static argument type can select a different return contract. Failure of assignability in both directions alone is not sufficient proof of disjointness.
  3. Add paired coverage: g1 should be accepted, factory should retain reportOverlappingOverload, and ParamSpec56 should continue to terminate. Include a bounded recursive-source rejection control if the shared solver is changed.

There is also a solver-contract reason to avoid the Unknown fallback: direct public-evaluator probes with T bounded by an unrelated nominal class reject Box[T] on the baseline but accept it with this patch. A nested no-tracker check can then authorize an enclosing tracked assignment to record the incompatible lower bound. This is confirmed at the evaluator API; I have not established an additional Python-source reproducer for that bound case.

Simply retaining adjSrcType instead of substituting Unknown is worth considering for preserving bound validation, but it is not a complete fix for the unsafe-overlap case. The localized overlap approach above is a proposed repair direction, not an implemented or validated replacement, and should not require adopting the broader overload-policy prototype.

Setting the lower bound to Unknown when the occurs check runs without
a constraint tracker skips the TypeVar bound check, since Unknown
satisfies any bound, so a recursive source that violates the bound
is accepted. It also hides unsafe overload overlaps whose return type
comparison reaches the occurs check.

Keep the actual source as the lower bound so the bound check still
runs against it. Add a RejectCyclicLowerBound flag that makes the
occurs check reject a recursive source without a tracker, set it in
the overload return type check, and pass it through the upper bound
check in assignUnconstrainedTypeVar. In assignFunction, don't count
two defaulted parameters as a partial overlap when they overlap only
through omission of the argument.

Adds func38 (clean) and func39 (reported) to overloadOverlap1 and
marks func37 as reported, since it has the same shape as func39. Adds
constraintSolver.test.ts, which checks that without a tracker a
recursive source is rejected when it violates the TypeVar bound and
accepted when it satisfies it.
@crypt0lith

Copy link
Copy Markdown
Contributor Author

Thank you for the feedback Rich Chiodo (@rchiodo).
Addressed in 53ba392:

  1. The occurs check keeps its protection, and the no-tracker lower bound is adjSrcType again instead of Unknown.
  2. The partial-overlap default-argument logic now exempts overlap only through omission, limited to disjoint literals where the first overload's default decides the omitted-argument result.
  3. func38 (g1) is accepted, func39 (factory) is reported, ParamSpec56 still terminates, and constraintSolver.test.ts adds the bounded recursive-source rejection control.

The unsafe-overlap case is handled by a new RejectCyclicLowerBound flag, which the overload return check sets so that cyclic lower bounds are still rejected there without a tracker.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@rchiodo

Copy link
Copy Markdown
Collaborator

This is an improvement over the previous version. The Unknown substitution is gone, and retaining adjSrcType keeps the actual source/bound validation in place. I checked 53ba3922e: the intended g1 is accepted, the ordinary unsafe Callable factory is flagged, and ParamSpec56 still terminates.

There are still two cases where the base reports an unsafe overlap and this version doesn't.

1. The default-omission exception needs to account for the other parameters.

At this assignment, and the corresponding keyword-only path, we set canAssign = false based on one defaulted parameter. The helper establishes that the explicit literal domains are disjoint and that the destination default belongs to its domain. That doesn't establish that omitting the parameter is safe for the whole signature.

For example:

from typing import Literal, overload

@overload
def f(x: int, mode: Literal["a"] = "a") -> int: ...
@overload
def f(x: object, mode: Literal["b"] = ...) -> str: ...
def f(x: object, mode: str = "a") -> int | str:
    return 1 if isinstance(x, int) and mode == "a" else "b"

def use(x: object) -> str:
    return f(x)

With Python 3.12 configuration, standard checking, and reportOverlappingOverload: error, the base reports the overlapping-return error. Head reports no errors. Running use(1) returns the integer 1, although f(x) is statically str. The keyword-only version has the same result.

The other argument matters here. x: object filters out the first overload statically, but the runtime value can still be an int. The spec's step 6 selects the first remaining candidate after filtering, not necessarily the first declaration. That doesn't dictate the exact overlap-diagnostic policy, but declaration order alone doesn't make this case safe.

Could we restrict the omission exception to cases where the earlier signature accepts the later signature's remaining argument combinations? A conservative equivalence check on the other parameters might be enough as a starting point. I haven't implemented or validated that remedy. I'd keep g1 as the positive case and add this differing-other-parameter case to both paths.

2. The cyclic-lower-bound flag gets dropped when checking protocol members.

The mask in protocols.ts retains only OverloadOverlap | PartialOverloadOverlap, losing RejectCyclicLowerBound. The nested member comparison does have a tracker, but the upper-bound probe runs without one, so it still needs that bit.

This shows up with class-generic callback protocols:

from typing import Protocol, overload

class Identity[T](Protocol):
    def __call__(self, value: T, /) -> T: ...

class Wrap[T](Protocol):
    def __call__(self, value: T, /) -> list[T]: ...

@overload
def factory[T](tag: str, value: T) -> Wrap[T]: ...
@overload
def factory[T](tag: object, value: T) -> Identity[T]: ...

In the full tested repro, the implementation returns a callback that wraps its input in a list when tag is a string. A caller with tag: object gets Identity[int] from factory(tag, 0), and both that assertion and callback(1): int pass. At runtime, use("wrap") returns [1].

The base flags this factory and the plain Callable control. Head flags only the control.

I'd start by preserving RejectCyclicLowerBound through protocol member checking and adding paired protocol/Callable coverage. That repair still needs validation too, but both changes look local to these exceptions rather than requiring a broader redesign.

The omission exemption in assignFunction looks only at the defaulted
parameter, so it hides an unsafe overlap when the later overload
accepts arguments for its other parameters that the earlier overload
rejects. Protocol assignment also drops RejectCyclicLowerBound from
the flags it passes to member comparisons, so the overload return check
accepts a recursive source when the return types are callback protocols.

Apply the exemption only when the earlier overload accepts every
argument list the later overload accepts, apart from parameters that
overlap only when omitted. Keep RejectCyclicLowerBound in the flags
that protocol assignment passes through.

Adds func40 and func41 to overloadOverlap1, covering a differing
other parameter in the positional and keyword-only paths, and func42,
the callback protocol counterpart of func39. All three are reported.
@crypt0lith

Copy link
Copy Markdown
Contributor Author

Addressed in 4952364:

  1. The omission exemption now also requires the earlier overload to accept every argument the later overload accepts for its other parameters. Your example is func40, and its keyword-only version is func41.
  2. protocols.ts now keeps RejectCyclicLowerBound in its mask. Your factory is func42, paired with the Callable version, func39.

@rchiodo

Copy link
Copy Markdown
Collaborator

The original examples are fixed in 4952364bc. The Unknown fallback is still gone, and the bound validation is doing meaningful work. I'd keep this localized approach rather than revert it or turn it into a broader overload-policy change.

There are still two cases where it removes an existing unsafe-overlap warning, though. Both reproduce against the PR's base/head and with the PR integrated into current main (e73e6c2).

The first is in the whole-signature omission check. These comparisons pass srcParam.type through unchanged, so the later overload's independent TypeVars can be solved while we're trying to prove that the earlier overload accepts every combination.

from typing import Literal, overload, reveal_type

@overload
def f[T: (int, str)](x: T, y: T, mode: Literal["a"] = "a") -> int: ...
@overload
def f[S: (int, str), U: (int, str)](x: S, y: U, mode: Literal["b"] = ...) -> str: ...
def f(x: int | str, y: int | str, mode: str = "a") -> int | str:
    if mode == "a" and isinstance(x, int) == isinstance(y, int):
        return 1
    return "result"

def proxy[S: (int, str), U: (int, str)](x: S, y: U) -> str:
    return f(x, y)

reveal_type(f(1, 1))
reveal_type(f(1, "s"))
reveal_type(proxy(1, 1))
print(type(proxy(1, 1)).__name__)

With Python target 3.13, standard mode, and reportOverlappingOverload set to error, the base and current main report one unsafe-overlap error on f. The PR and its current-main integration report none. All retain the same revealed types: int, str, str. Running this on Python 3.14.3, proxy(1, 1) returns 1, an int.

The call inference isn't newly broken here. The regression is losing the declaration warning that exposed it.

The first overload requires x and y to use the same constrained choice. The second allows them to vary independently. Wouldn't proving coverage need to preserve that independence rather than solve it away? A shared ConstraintTracker doesn't do that on its own.

A helper-level probe of the two parameter comparisons returned [true, true] with the raw source variables, but [true, false] with bound/rigid source variables. I'd investigate using the existing makeTypeVarsBound for the later overload's function-local TypeVars, while leaving the earlier overload's variables inferable. That may mean passing the source function or scope IDs into the helper. The probe supports that distinction, but it isn't an implemented or validated production fix yet.

Can you add paired correlated/independent generic cases here, keeping g1 as a positive control? An invariant list variant also exposed this family. The constrained-TypeVar rules and callable assignability rules explain the coverage distinction. They don't, by themselves, prescribe the exact overlap diagnostic or occurs-check policy.

There's a separate flag-loss path through protocol properties. The ordinary-member mask change works, but the property branch in protocols.ts calls assignProperty without the policy flag, and the accessor comparison explicitly uses AssignTypeFlags.Default.

This reproduces without any Any:

from typing import Callable, Protocol, assert_type, overload

class Identity[T](Protocol):
    @property
    def call(self) -> Callable[[T], T]: ...

class Wrap[T](Protocol):
    @property
    def call(self) -> Callable[[T], list[T]]: ...

class IdentityResult[T]:
    @property
    def call(self) -> Callable[[T], T]:
        return lambda value: value

class WrapResult[T]:
    @property
    def call(self) -> Callable[[T], list[T]]:
        return lambda value: [value]

@overload
def factory[T](tag: str, value: T) -> Wrap[T]: ...
@overload
def factory[T](tag: object, value: T) -> Identity[T]: ...
def factory[T](tag: object, value: T) -> Wrap[T] | Identity[T]:
    if isinstance(tag, str):
        return WrapResult[T]()
    return IdentityResult[T]()

def use(tag: object) -> int:
    result = factory(tag, 0).call(1)
    assert_type(result, int)
    return result

result = use("wrap")
print(result + 1)

Under the same settings, the base and current main report one overlap error on factory. The PR and integrated PR produce no diagnostics, including at assert_type. At runtime, use("wrap") returns [1], and the addition raises TypeError.

I'd thread RejectCyclicLowerBound through assignProperty and its accessor comparisons, preserving the default behavior for other callers. Then add this property-wrapped case alongside the ordinary protocol and Callable controls. That's also a proposed fix, not a production patch that's been validated. The existing OverloadOverlap1, ParamSpec56, Protocol44, and bound tests pass at both head and integration, so they don't currently catch these two gaps.

One smaller performance opportunity: isParamListOverlapOnlyByOmission rescans the same full parameter details and creates a fresh tracker for each qualifying default. Since those inputs are fixed within an assignFunction invocation, can we lazily compute it once and reuse both true and false results across the positional and keyword-only call sites? No global cache needed, and the whole-signature safety check should stay. On the raw base/head comparison, a synthetic file with four function names, eight overloads each, and one required tuple[T, ...] payload plus 64 defaulted literal discriminators per overload went from a 79.5 ms to 254.5 ms median incremental whole-file check over four completed alternating pairs. The normal sample stayed at 54 ms. That's a narrow synthetic result, not a one-function cost or an ecosystem benchmark, and no memoization change has been implemented or timed.

The next changes look fairly contained: preserve the later overload's generic independence in the omission proof, and carry the cycle-rejection policy through properties. The local memoization is secondary; those two missing warnings are the correctness issues to fix.

@github-actions

This comment has been minimized.

The omission check lets the solver pick the later overload's
TypeVars, so it can treat independent TypeVars as the same type and
wrongly conclude that the earlier overload covers every argument
list. assignProperty also drops RejectCyclicLowerBound when comparing
accessors.

Treat the later overload's TypeVars as bound in the omission check,
and pass the flags from protocol assignment through assignProperty
to the accessor comparison.

Adds func43 through func47 to overloadOverlap1: paired constrained and
invariant cases with shared TypeVars (clean) and independent TypeVars
(reported), and func47, the property counterpart of func42 (reported).
Reuse the result of isParamListOverlapOnlyByOmission at the positional
and keyword-only call sites instead of rescanning for each default.
@crypt0lith

Copy link
Copy Markdown
Contributor Author

Addressed in ce29a63:

  1. The omission proof binds the later overload's TypeVars with makeTypeVarsBound, leaving the earlier overload's free. Added correlated (clean) and independent (reported) pairs to overloadOverlap1: func43/func44 constrained, func45/func46 invariant list. func38 (g1) stays as the positive control.
  2. assignProperty takes flags and passes RejectCyclicLowerBound to the accessor comparison. Protocols pass their mask; the variance caller passes Default. Added func47, the property-wrapped factory, alongside func42 and func39.

Addressed in 67e187e:

  • isParamListOverlapOnlyByOmission is computed lazily once per assignFunction call, and the result (true or false) is reused at both call sites.

On your synthetic shape, the median CLI check time over seven alternating rounds was 0.48 s at base, 0.82 s at ce29a63, and 0.48 s at 67e187e. overloadOverlap1.py stayed at 0.35–0.37 s across all three. These are cold CLI runs, not incremental checks, so the numbers aren't directly comparable to yours.

@github-actions

github-actions Bot commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Diff from mypy_primer, showing the effect of this PR on open source code:

jinja (https://github.com/pallets/jinja)
-   .../projects/jinja/src/jinja2/environment.py:711:9 - error: Overload 1 for "compile" overlaps overload 2 and returns an incompatible type (reportOverlappingOverload)
- 46 errors, 15 warnings, 0 informations
+ 45 errors, 15 warnings, 0 informations

sympy (https://github.com/sympy/sympy)
-   .../projects/sympy/sympy/polys/rings.py:907:34 - error: Type "PolyElement[Er@PolyElement]" cannot be assigned to type variable "Er@PolyElement"
-     Type "PolyElement[Er@PolyElement]" is not assignable to upper bound "RingElement" for type variable "Er@PolyElement"
-       "PolyElement[Er@PolyElement]" is incompatible with protocol "RingElement"
-         "__add__" is an incompatible type
-           Type "(other: PolyElement[Er@PolyElement] | Er@PolyElement | int | PolyElement[PolyElement[Er@PolyElement]], /) -> (PolyElement[Er@PolyElement] | PolyElement[PolyElement[Er@PolyElement]])" is not assignable to type "(other: PolyElement[Er@PolyElement] | int, /) -> PolyElement[Er@PolyElement]"
-             Function return type "PolyElement[Er@PolyElement] | PolyElement[PolyElement[Er@PolyElement]]" is incompatible with type "PolyElement[Er@PolyElement]" (reportInvalidTypeArguments)
-   .../projects/sympy/sympy/polys/rings.py:908:22 - error: Type "PolyElement[Er@PolyElement]" cannot be assigned to type variable "Er@PolyElement"
-     Type "PolyElement[Er@PolyElement]" is not assignable to upper bound "RingElement" for type variable "Er@PolyElement"
-       "PolyElement[Er@PolyElement]" is incompatible with protocol "RingElement"
-         "__add__" is an incompatible type
-           Type "(other: PolyElement[Er@PolyElement] | Er@PolyElement | int | PolyElement[PolyElement[Er@PolyElement]], /) -> (PolyElement[Er@PolyElement] | PolyElement[PolyElement[Er@PolyElement]])" is not assignable to type "(other: PolyElement[Er@PolyElement] | int, /) -> PolyElement[Er@PolyElement]"
-             Function return type "PolyElement[Er@PolyElement] | PolyElement[PolyElement[Er@PolyElement]]" is incompatible with type "PolyElement[Er@PolyElement]" (reportInvalidTypeArguments)
-   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:176:44 - error: Cannot access attribute "expand" for class "Basic"
-     Attribute "expand" is unknown (reportAttributeAccessIssue)
-   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:423:38 - error: Argument of type "Unknown | Expr | Literal[0]" cannot be assigned to parameter "expr" of type "Expr" in function "make_args"
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:423:38 - error: Argument of type "int | Expr" cannot be assigned to parameter "expr" of type "Expr" in function "make_args"
-     Type "Unknown | Expr | Literal[0]" is not assignable to type "Expr"
+     Type "int | Expr" is not assignable to type "Expr"
-       "Literal[0]" is not assignable to "Expr" (reportArgumentType)
+       "int" is not assignable to "Expr" (reportArgumentType)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:504:19 - error: Operator "**" not supported for types "Unknown | Basic" and "Literal[2]"
+     Operator "**" not supported for types "Basic" and "Literal[2]" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:505:19 - error: Operator "*" not supported for types "Unknown | Basic" and "Unknown | Basic"
+     Operator "*" not supported for types "Basic" and "Basic" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:506:19 - error: Operator "**" not supported for types "Unknown | Basic" and "Literal[2]"
+     Operator "**" not supported for types "Basic" and "Literal[2]" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:569:42 - error: Operator "*" not supported for types "int" and "Unknown | Basic"
+     Operator "*" not supported for types "int" and "Basic" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:569:50 - error: Operator "*" not supported for types "Expr" and "Unknown | Basic"
+     Operator "*" not supported for types "Expr" and "Basic" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:725:42 - error: Operator "**" not supported for types "Unknown | Basic" and "Literal[2]"
+     Operator "**" not supported for types "Basic" and "Literal[2]" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:735:19 - error: Operator "**" not supported for types "Unknown | Basic" and "Literal[2]"
+     Operator "**" not supported for types "Basic" and "Literal[2]" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:736:19 - error: Operator "**" not supported for types "Unknown | Basic" and "Literal[2]"
+     Operator "**" not supported for types "Basic" and "Literal[2]" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:737:19 - error: Operator "**" not supported for types "Unknown | Basic" and "Literal[2]"
+     Operator "**" not supported for types "Basic" and "Literal[2]" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:814:47 - error: Operator "**" not supported for types "Unknown | Basic" and "Literal[2]"
+     Operator "**" not supported for types "Basic" and "Literal[2]" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:841:26 - error: Operator "**" not supported for types "Unknown | Basic" and "Literal[2]"
+     Operator "**" not supported for types "Basic" and "Literal[2]" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:842:22 - error: Operator "*" not supported for types "Unknown | Basic" and "Unknown | Basic"
+     Operator "*" not supported for types "Basic" and "Basic" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:843:36 - error: Operator "*" not supported for types "int" and "Unknown | Basic"
+     Operator "*" not supported for types "int" and "Basic" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:843:42 - error: Operator "*" not supported for types "Unknown | Basic" and "Unknown | Basic"
+     Operator "*" not supported for types "Basic" and "Basic" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:843:51 - error: Operator "*" not supported for types "int" and "Unknown | Basic"
+     Operator "*" not supported for types "int" and "Basic" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:843:57 - error: Operator "*" not supported for types "Unknown | Basic" and "Unknown | Basic"
+     Operator "*" not supported for types "Basic" and "Basic" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:843:66 - error: Operator "*" not supported for types "Unknown | Basic" and "Unknown | Basic"
+     Operator "*" not supported for types "Basic" and "Basic" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:845:53 - error: Operator "*" not supported for types "Unknown | Basic" and "Unknown | Basic"
+     Operator "*" not supported for types "Basic" and "Basic" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:854:18 - error: Operator "**" not supported for types "Unknown | Basic" and "Literal[2]"
+     Operator "**" not supported for types "Basic" and "Literal[2]" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:856:22 - error: Operator "**" not supported for types "Unknown | Basic" and "Literal[2]"
+     Operator "**" not supported for types "Basic" and "Literal[2]" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:865:22 - error: Operator "*" not supported for types "Unknown | Basic" and "Unknown | Basic"
+     Operator "*" not supported for types "Basic" and "Basic" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:865:36 - error: Operator "*" not supported for types "Unknown | Basic" and "Unknown | Basic"
+     Operator "*" not supported for types "Basic" and "Basic" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:867:27 - error: Operator "**" not supported for types "Unknown | Basic" and "Literal[2]"
+     Operator "**" not supported for types "Basic" and "Literal[2]" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:868:27 - error: Operator "*" not supported for types "Unknown | Basic" and "Unknown | Basic"
+     Operator "*" not supported for types "Basic" and "Basic" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:869:27 - error: Operator "*" not supported for types "Unknown | Basic" and "Unknown | Basic"
+     Operator "*" not supported for types "Basic" and "Basic" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:870:27 - error: Operator "**" not supported for types "Unknown | Basic" and "Literal[2]"
+     Operator "**" not supported for types "Basic" and "Literal[2]" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:871:27 - error: Operator "*" not supported for types "Unknown | Basic" and "Unknown | Basic"
+     Operator "*" not supported for types "Basic" and "Basic" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:872:27 - error: Operator "**" not supported for types "Unknown | Basic" and "Literal[2]"
+     Operator "**" not supported for types "Basic" and "Literal[2]" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:876:24 - error: Operator "**" not supported for types "Unknown | Basic" and "Literal[2]"
+     Operator "**" not supported for types "Basic" and "Literal[2]" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/diophantine/diophantine.py:877:24 - error: Operator "**" not supported for types "Unknown | Basic" and "Literal[2]"
+     Operator "**" not supported for types "Basic" and "Literal[2]" (reportOperatorIssue)

... (truncated 315 lines) ...

prefect (https://github.com/PrefectHQ/prefect)
-     Parameter 1 type mismatch: base parameter is type "_SyncOrAsyncCallable[(), T@wait_for_call_in_new_thread] | Call[T@wait_for_call_in_new_thread]", override parameter is type "(() -> T@wait_for_call_in_new_thread) | Call[T@wait_for_call_in_new_thread]"
-     Return type mismatch: base method returns type "T@wait_for_call_in_new_thread", override returns type "CoroutineType[Any, Any, T@wait_for_call_in_new_thread]"
+     Return type mismatch: base method returns type "T@wait_for_call_in_new_thread", override returns type "CoroutineType[Any, Any, T@wait_for_call_in_new_thread | Awaitable[T@wait_for_call_in_new_thread]]"
-       Type "_SyncOrAsyncCallable[(), T@wait_for_call_in_new_thread] | Call[T@wait_for_call_in_new_thread]" is not assignable to type "(() -> T@wait_for_call_in_new_thread) | Call[T@wait_for_call_in_new_thread]"
-         Type "_SyncOrAsyncCallable[(), T@wait_for_call_in_new_thread]" is not assignable to type "(() -> T@wait_for_call_in_new_thread) | Call[T@wait_for_call_in_new_thread]"
-           "FunctionType" is not assignable to "Call[T@wait_for_call_in_new_thread]"
-           Type "_SyncOrAsyncCallable[(), T@wait_for_call_in_new_thread]" is not assignable to type "() -> T@wait_for_call_in_new_thread"
-             Function return type "T@wait_for_call_in_new_thread | Awaitable[T@wait_for_call_in_new_thread]" is incompatible with type "T@wait_for_call_in_new_thread"
-       Type "CoroutineType[Any, Any, T@wait_for_call_in_new_thread]" is not assignable to type "T@wait_for_call_in_new_thread" (reportIncompatibleMethodOverride)
+       Type "CoroutineType[Any, Any, T@wait_for_call_in_new_thread | Awaitable[T@wait_for_call_in_new_thread]]" is not assignable to type "T@wait_for_call_in_new_thread" (reportIncompatibleMethodOverride)
-   .../projects/prefect/src/prefect/_internal/concurrency/api.py:201:9 - error: Method "wait_for_call_in_new_thread" overrides class "_base" in an incompatible manner
-     Parameter 1 type mismatch: base parameter is type "_SyncOrAsyncCallable[(), T@wait_for_call_in_new_thread] | Call[T@wait_for_call_in_new_thread]", override parameter is type "(() -> T@wait_for_call_in_new_thread) | Call[T@wait_for_call_in_new_thread]"
-       Type "_SyncOrAsyncCallable[(), T@wait_for_call_in_new_thread] | Call[T@wait_for_call_in_new_thread]" is not assignable to type "(() -> T@wait_for_call_in_new_thread) | Call[T@wait_for_call_in_new_thread]"
-         Type "_SyncOrAsyncCallable[(), T@wait_for_call_in_new_thread]" is not assignable to type "(() -> T@wait_for_call_in_new_thread) | Call[T@wait_for_call_in_new_thread]"
-           "FunctionType" is not assignable to "Call[T@wait_for_call_in_new_thread]"
-           Type "_SyncOrAsyncCallable[(), T@wait_for_call_in_new_thread]" is not assignable to type "() -> T@wait_for_call_in_new_thread"
-             Function return type "T@wait_for_call_in_new_thread | Awaitable[T@wait_for_call_in_new_thread]" is incompatible with type "T@wait_for_call_in_new_thread" (reportIncompatibleMethodOverride)
- 6321 errors, 201 warnings, 0 informations
+ 6320 errors, 201 warnings, 0 informations

streamlit (https://github.com/streamlit/streamlit)
-   .../projects/streamlit/lib/streamlit/elements/widgets/multiselect.py:231:9 - error: Overload 1 for "multiselect" overlaps overload 2 and returns an incompatible type (reportOverlappingOverload)
- 7384 errors, 140 warnings, 0 informations
+ 7383 errors, 140 warnings, 0 informations

core (https://github.com/home-assistant/core)
-   .../projects/core/homeassistant/helpers/template/__init__.py:900:9 - error: Overload 1 for "compile" overlaps overload 2 and returns an incompatible type (reportOverlappingOverload)
- 41901 errors, 76 warnings, 0 informations
+ 41900 errors, 76 warnings, 0 informations

werkzeug (https://github.com/pallets/werkzeug)
-   .../projects/werkzeug/src/werkzeug/wrappers/request.py:577:9 - error: Overload 1 for "get_data" overlaps overload 2 and returns an incompatible type (reportOverlappingOverload)
- 327 errors, 22 warnings, 0 informations
+ 326 errors, 22 warnings, 0 informations

pandas-stubs (https://github.com/pandas-dev/pandas-stubs)
+ .../projects/pandas-stubs/pandas-stubs/core/frame.pyi
+   .../projects/pandas-stubs/pandas-stubs/core/frame.pyi:1206:37 - error: Unnecessary "# pyright: ignore" rule: "reportOverlappingOverload" (reportUnnecessaryTypeIgnoreComment)
+   .../projects/pandas-stubs/pandas-stubs/core/frame.pyi:1254:37 - error: Unnecessary "# pyright: ignore" rule: "reportOverlappingOverload" (reportUnnecessaryTypeIgnoreComment)
+   .../projects/pandas-stubs/pandas-stubs/core/frame.pyi:1278:37 - error: Unnecessary "# pyright: ignore" rule: "reportOverlappingOverload" (reportUnnecessaryTypeIgnoreComment)
+   .../projects/pandas-stubs/pandas-stubs/core/frame.pyi:1302:37 - error: Unnecessary "# pyright: ignore" rule: "reportOverlappingOverload" (reportUnnecessaryTypeIgnoreComment)
+   .../projects/pandas-stubs/pandas-stubs/core/frame.pyi:1326:54 - error: Unnecessary "# type: ignore" comment (reportUnnecessaryTypeIgnoreComment)
+   .../projects/pandas-stubs/pandas-stubs/core/frame.pyi:1350:37 - error: Unnecessary "# pyright: ignore" rule: "reportOverlappingOverload" (reportUnnecessaryTypeIgnoreComment)
- 202 errors, 3 warnings, 0 informations
+ 208 errors, 3 warnings, 0 informations

jax (https://github.com/google/jax)
-   .../projects/jax/jax/_src/scipy/linalg.py:981:5 - error: Overload 1 for "qr" overlaps overload 2 and returns an incompatible type (reportOverlappingOverload)
-   .../projects/jax/jax/_src/scipy/linalg.py:997:5 - error: Overload 4 for "qr" overlaps overload 5 and returns an incompatible type (reportOverlappingOverload)
-   .../projects/jax/jax/_src/scipy/linalg.py:1102:5 - error: Overload 1 for "qr_multiply" overlaps overload 2 and returns an incompatible type (reportOverlappingOverload)
- 3715 errors, 72 warnings, 0 informations
+ 3712 errors, 72 warnings, 0 informations

@rchiodo

Copy link
Copy Markdown
Collaborator

I pushed ef17dc0 to address the remaining performance concern.

The partial-overlap/default-omission proof can do a lot of literal-union work. We were doing that work even when the overload return types were already compatible, but compatible returns can't produce the incompatible-return diagnostic from this checker loop anyway.

The change is pretty localized: compare the return types first, and skip partial-overlap analysis when they're compatible or unavailable. When the returns are incompatible, the existing overlap check still runs exactly as before. This doesn't linearize the literal-union helper or remove its worst-case cost. It just avoids paying that cost in cases where it can't affect the result.

The compatible-return stress cases improved by roughly 43-49%. The normal sample was effectively unchanged, and the incompatible-return sample stayed within measurement noise. Diagnostic counts were identical before and after.

I also reran the full 1,219 evaluator and constraint-solver tests, the four adversarial overlap repros, the build, and Prettier. Everything passed, and the overlap repro diagnostics were unchanged.

I pushed this rather than just suggesting it because it's a small checker-only reorder, it's fully validated, and it removes the performance blocker without changing the PR's intended behavior.

@github-actions

github-actions Bot commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Diff from mypy_primer, showing the effect of this PR on open source code:

jinja (https://github.com/pallets/jinja)
-   .../projects/jinja/src/jinja2/environment.py:711:9 - error: Overload 1 for "compile" overlaps overload 2 and returns an incompatible type (reportOverlappingOverload)
- 46 errors, 15 warnings, 0 informations
+ 45 errors, 15 warnings, 0 informations

sympy (https://github.com/sympy/sympy)
-   .../projects/sympy/sympy/polys/rings.py:907:34 - error: Type "PolyElement[Er@PolyElement]" cannot be assigned to type variable "Er@PolyElement"
-     Type "PolyElement[Er@PolyElement]" is not assignable to upper bound "RingElement" for type variable "Er@PolyElement"
-       "PolyElement[Er@PolyElement]" is incompatible with protocol "RingElement"
-         "__add__" is an incompatible type
-           Type "(other: PolyElement[Er@PolyElement] | Er@PolyElement | int | PolyElement[PolyElement[Er@PolyElement]], /) -> (PolyElement[Er@PolyElement] | PolyElement[PolyElement[Er@PolyElement]])" is not assignable to type "(other: PolyElement[Er@PolyElement] | int, /) -> PolyElement[Er@PolyElement]"
-             Function return type "PolyElement[Er@PolyElement] | PolyElement[PolyElement[Er@PolyElement]]" is incompatible with type "PolyElement[Er@PolyElement]" (reportInvalidTypeArguments)
-   .../projects/sympy/sympy/polys/rings.py:908:22 - error: Type "PolyElement[Er@PolyElement]" cannot be assigned to type variable "Er@PolyElement"
-     Type "PolyElement[Er@PolyElement]" is not assignable to upper bound "RingElement" for type variable "Er@PolyElement"
-       "PolyElement[Er@PolyElement]" is incompatible with protocol "RingElement"
-         "__add__" is an incompatible type
-           Type "(other: PolyElement[Er@PolyElement] | Er@PolyElement | int | PolyElement[PolyElement[Er@PolyElement]], /) -> (PolyElement[Er@PolyElement] | PolyElement[PolyElement[Er@PolyElement]])" is not assignable to type "(other: PolyElement[Er@PolyElement] | int, /) -> PolyElement[Er@PolyElement]"
-             Function return type "PolyElement[Er@PolyElement] | PolyElement[PolyElement[Er@PolyElement]]" is incompatible with type "PolyElement[Er@PolyElement]" (reportInvalidTypeArguments)
+   .../projects/sympy/sympy/solvers/bivariate.py:135:15 - error: Operator "-" not supported for "None" (reportOptionalOperand)
+   .../projects/sympy/sympy/solvers/bivariate.py:139:17 - error: Operator "-" not supported for type "Basic | Unknown" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/bivariate.py:144:23 - error: Operator "-" not supported for "None" (reportOptionalOperand)
+   .../projects/sympy/sympy/solvers/deutils.py:234:14 - error: Operator "not in" not supported for types "str" and "Unknown | int"
+     Operator "not in" not supported for types "str" and "int" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/ode/lie_group.py:619:61 - error: Operator "-" not supported for type "Unknown | Basic" (reportOperatorIssue)
+   .../projects/sympy/sympy/solvers/ode/riccati.py:702:43 - error: Cannot access attribute "free_symbols" for class "str"
+     Attribute "free_symbols" is unknown (reportAttributeAccessIssue)
-   .../projects/sympy/sympy/solvers/ode/riccati.py:869:30 - error: Argument of type "dict[Unknown, Unknown] | Unknown | Poly" cannot be assigned to parameter "obj" of type "Sized" in function "len"
+   .../projects/sympy/sympy/solvers/ode/riccati.py:869:30 - error: Argument of type "dict[Unknown, Unknown] | dict[str, str] | Unknown | Poly" cannot be assigned to parameter "obj" of type "Sized" in function "len"
-     Type "dict[Unknown, Unknown] | Unknown | Poly" is not assignable to type "Sized"
+     Type "dict[Unknown, Unknown] | dict[str, str] | Unknown | Poly" is not assignable to type "Sized"
+   .../projects/sympy/sympy/solvers/ode/single.py:2652:9 - error: Operator "+=" not supported for types "One | NegativeOne | Zero | Integer | NaN | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | Number | Expr | Any | Unknown" and "Basic"
+     Operator "+" not supported for types "ComplexInfinity" and "Basic"
+     Operator "+" not supported for types "Number" and "Basic"
+     Operator "+" not supported for types "Expr" and "Basic" (reportOperatorIssue)
-   .../projects/sympy/sympy/solvers/pde.py:173:18 - error: Cannot access attribute "pop" for class "tuple[()]"
-     Attribute "pop" is unknown (reportAttributeAccessIssue)
-   .../projects/sympy/sympy/solvers/pde.py:173:18 - error: Cannot access attribute "pop" for class "tuple[str, ...]"
-     Attribute "pop" is unknown (reportAttributeAccessIssue)
-   .../projects/sympy/sympy/solvers/recurr.py:424:16 - error: Cannot access attribute "is_polynomial" for class "tuple[Unknown, list[Unknown]]"
+   .../projects/sympy/sympy/solvers/recurr.py:424:16 - error: Cannot access attribute "is_polynomial" for class "tuple[Unknown, list[Expr | Unknown]]"
-   .../projects/sympy/sympy/solvers/recurr.py:424:16 - error: Cannot access attribute "is_polynomial" for class "tuple[Unknown, Unknown | Unbound]"
+   .../projects/sympy/sympy/solvers/recurr.py:424:16 - error: Cannot access attribute "is_polynomial" for class "tuple[Unknown | tuple[Unknown, list[Poly]], list[Poly] | Unknown | Unbound]"
+   .../projects/sympy/sympy/solvers/recurr.py:424:16 - error: Cannot access attribute "is_polynomial" for class "tuple[Unknown, list[Poly]]"
+     Attribute "is_polynomial" is unknown (reportAttributeAccessIssue)
-   .../projects/sympy/sympy/solvers/recurr.py:425:20 - error: Cannot access attribute "as_numer_denom" for class "tuple[Unknown, list[Unknown]]"
+   .../projects/sympy/sympy/solvers/recurr.py:425:20 - error: Cannot access attribute "as_numer_denom" for class "tuple[Unknown, list[Expr | Unknown]]"
+   .../projects/sympy/sympy/solvers/recurr.py:425:20 - error: Cannot access attribute "as_numer_denom" for class "tuple[Unknown | tuple[Unknown, list[Poly]], list[Poly] | Unknown | Unbound]"
+     Attribute "as_numer_denom" is unknown (reportAttributeAccessIssue)
-   .../projects/sympy/sympy/solvers/recurr.py:425:20 - error: Cannot access attribute "as_numer_denom" for class "tuple[Unknown, Unknown | Unbound]"
+   .../projects/sympy/sympy/solvers/recurr.py:425:20 - error: Cannot access attribute "as_numer_denom" for class "tuple[Unknown, list[Poly]]"
+   .../projects/sympy/sympy/solvers/recurr.py:449:13 - error: No overloads for "__setitem__" match the provided arguments (reportCallIssue)
+   .../projects/sympy/sympy/solvers/recurr.py:449:13 - error: Argument of type "Expr | Unknown | Poly" cannot be assigned to parameter "value" of type "Zero" in function "__setitem__"
+     Type "Expr | Unknown | Poly" is not assignable to type "Zero"
+       "Expr" is not assignable to "Zero" (reportArgumentType)
+   .../projects/sympy/sympy/solvers/solvers.py:3121:17 - error: No overloads for "__init__" match the provided arguments (reportCallIssue)
+   .../projects/sympy/sympy/solvers/solvers.py:3121:22 - error: Argument of type "zip[Unknown]" cannot be assigned to parameter "iterable" of type "Iterable[list[bytes]]" in function "__init__"
+     "zip[Unknown]" is incompatible with protocol "Iterable[list[bytes]]"
+       "__iter__" is an incompatible type
+         Type "() -> zip[Unknown]" is not assignable to type "() -> Iterator[_T_co@Iterable]"
+           Function return type "zip[Unknown]" is incompatible with type "Iterator[_T_co@Iterable]"
+             "zip[Unknown]" is incompatible with protocol "Iterator[_T_co@Iterable]" (reportArgumentType)
+   .../projects/sympy/sympy/solvers/solveset.py:4182:23 - error: No overloads for "__init__" match the provided arguments (reportCallIssue)
+   .../projects/sympy/sympy/solvers/solveset.py:4182:28 - error: Argument of type "zip[Unknown]" cannot be assigned to parameter "iterable" of type "Iterable[list[bytes]]" in function "__init__"
+     "zip[Unknown]" is incompatible with protocol "Iterable[list[bytes]]"
+       "__iter__" is an incompatible type
+         Type "() -> zip[Unknown]" is not assignable to type "() -> Iterator[_T_co@Iterable]"
+           Function return type "zip[Unknown]" is incompatible with type "Iterator[_T_co@Iterable]"
+             "zip[Unknown]" is incompatible with protocol "Iterator[_T_co@Iterable]" (reportArgumentType)
-   .../projects/sympy/sympy/solvers/tests/test_numeric.py:24:12 - error: Operator ">" not supported for types "list[dict[Unknown, Unknown]] | Unknown | list[dict[str, str]] | MutableDenseMatrix" and "float"
+   .../projects/sympy/sympy/solvers/tests/test_numeric.py:24:12 - error: Operator ">" not supported for types "list[dict[Unknown, Unknown]] | Unknown | list[dict[bytes, bytes]] | MutableDenseMatrix" and "float"
-     Operator ">" not supported for types "list[dict[str, str]]" and "float"
+     Operator ">" not supported for types "list[dict[bytes, bytes]]" and "float"
-   .../projects/sympy/sympy/solvers/tests/test_numeric.py:24:27 - error: Operator "<" not supported for types "list[dict[Unknown, Unknown]] | Unknown | list[dict[str, str]] | MutableDenseMatrix" and "float"
+   .../projects/sympy/sympy/solvers/tests/test_numeric.py:24:27 - error: Operator "<" not supported for types "list[dict[Unknown, Unknown]] | Unknown | list[dict[bytes, bytes]] | MutableDenseMatrix" and "float"
-     Operator "<" not supported for types "list[dict[str, str]]" and "float"
+     Operator "<" not supported for types "list[dict[bytes, bytes]]" and "float"
-   .../projects/sympy/sympy/solvers/tests/test_numeric.py:37:12 - error: Operator "-" not supported for types "list[dict[Unknown, Unknown]] | Unknown | list[dict[str, str]] | MutableDenseMatrix" and "Expr"
+   .../projects/sympy/sympy/solvers/tests/test_numeric.py:37:12 - error: Operator "-" not supported for types "list[dict[Unknown, Unknown]] | Unknown | list[dict[bytes, bytes]] | MutableDenseMatrix" and "Expr"
-     Operator "-" not supported for types "list[dict[str, str]]" and "Expr"
+     Operator "-" not supported for types "list[dict[bytes, bytes]]" and "Expr"
-   .../projects/sympy/sympy/solvers/tests/test_numeric.py:67:28 - error: Argument of type "list[dict[Unknown, Unknown]] | Unknown | list[dict[str, str]] | MutableDenseMatrix" cannot be assigned to parameter "iterable" of type "Iterable[_T1@__new__]" in function "__new__"

... (truncated 197 lines) ...

prefect (https://github.com/PrefectHQ/prefect)
-     Parameter 1 type mismatch: base parameter is type "_SyncOrAsyncCallable[(), T@wait_for_call_in_new_thread] | Call[T@wait_for_call_in_new_thread]", override parameter is type "(() -> T@wait_for_call_in_new_thread) | Call[T@wait_for_call_in_new_thread]"
-     Return type mismatch: base method returns type "T@wait_for_call_in_new_thread", override returns type "CoroutineType[Any, Any, T@wait_for_call_in_new_thread]"
+     Return type mismatch: base method returns type "T@wait_for_call_in_new_thread", override returns type "CoroutineType[Any, Any, T@wait_for_call_in_new_thread | Awaitable[T@wait_for_call_in_new_thread]]"
-       Type "_SyncOrAsyncCallable[(), T@wait_for_call_in_new_thread] | Call[T@wait_for_call_in_new_thread]" is not assignable to type "(() -> T@wait_for_call_in_new_thread) | Call[T@wait_for_call_in_new_thread]"
-         Type "_SyncOrAsyncCallable[(), T@wait_for_call_in_new_thread]" is not assignable to type "(() -> T@wait_for_call_in_new_thread) | Call[T@wait_for_call_in_new_thread]"
-           "FunctionType" is not assignable to "Call[T@wait_for_call_in_new_thread]"
-           Type "_SyncOrAsyncCallable[(), T@wait_for_call_in_new_thread]" is not assignable to type "() -> T@wait_for_call_in_new_thread"
-             Function return type "T@wait_for_call_in_new_thread | Awaitable[T@wait_for_call_in_new_thread]" is incompatible with type "T@wait_for_call_in_new_thread"
-       Type "CoroutineType[Any, Any, T@wait_for_call_in_new_thread]" is not assignable to type "T@wait_for_call_in_new_thread" (reportIncompatibleMethodOverride)
+       Type "CoroutineType[Any, Any, T@wait_for_call_in_new_thread | Awaitable[T@wait_for_call_in_new_thread]]" is not assignable to type "T@wait_for_call_in_new_thread" (reportIncompatibleMethodOverride)
-   .../projects/prefect/src/prefect/_internal/concurrency/api.py:201:9 - error: Method "wait_for_call_in_new_thread" overrides class "_base" in an incompatible manner
-     Parameter 1 type mismatch: base parameter is type "_SyncOrAsyncCallable[(), T@wait_for_call_in_new_thread] | Call[T@wait_for_call_in_new_thread]", override parameter is type "(() -> T@wait_for_call_in_new_thread) | Call[T@wait_for_call_in_new_thread]"
-       Type "_SyncOrAsyncCallable[(), T@wait_for_call_in_new_thread] | Call[T@wait_for_call_in_new_thread]" is not assignable to type "(() -> T@wait_for_call_in_new_thread) | Call[T@wait_for_call_in_new_thread]"
-         Type "_SyncOrAsyncCallable[(), T@wait_for_call_in_new_thread]" is not assignable to type "(() -> T@wait_for_call_in_new_thread) | Call[T@wait_for_call_in_new_thread]"
-           "FunctionType" is not assignable to "Call[T@wait_for_call_in_new_thread]"
-           Type "_SyncOrAsyncCallable[(), T@wait_for_call_in_new_thread]" is not assignable to type "() -> T@wait_for_call_in_new_thread"
-             Function return type "T@wait_for_call_in_new_thread | Awaitable[T@wait_for_call_in_new_thread]" is incompatible with type "T@wait_for_call_in_new_thread" (reportIncompatibleMethodOverride)
- 6315 errors, 201 warnings, 0 informations
+ 6314 errors, 201 warnings, 0 informations

streamlit (https://github.com/streamlit/streamlit)
-   .../projects/streamlit/lib/streamlit/elements/widgets/multiselect.py:231:9 - error: Overload 1 for "multiselect" overlaps overload 2 and returns an incompatible type (reportOverlappingOverload)
- 7384 errors, 140 warnings, 0 informations
+ 7383 errors, 140 warnings, 0 informations

core (https://github.com/home-assistant/core)
-   .../projects/core/homeassistant/helpers/template/__init__.py:900:9 - error: Overload 1 for "compile" overlaps overload 2 and returns an incompatible type (reportOverlappingOverload)
- 41898 errors, 76 warnings, 0 informations
+ 41897 errors, 76 warnings, 0 informations

werkzeug (https://github.com/pallets/werkzeug)
-   .../projects/werkzeug/src/werkzeug/wrappers/request.py:577:9 - error: Overload 1 for "get_data" overlaps overload 2 and returns an incompatible type (reportOverlappingOverload)
- 327 errors, 22 warnings, 0 informations
+ 326 errors, 22 warnings, 0 informations

pandas-stubs (https://github.com/pandas-dev/pandas-stubs)
+ .../projects/pandas-stubs/pandas-stubs/core/frame.pyi
+   .../projects/pandas-stubs/pandas-stubs/core/frame.pyi:1206:37 - error: Unnecessary "# pyright: ignore" rule: "reportOverlappingOverload" (reportUnnecessaryTypeIgnoreComment)
+   .../projects/pandas-stubs/pandas-stubs/core/frame.pyi:1254:37 - error: Unnecessary "# pyright: ignore" rule: "reportOverlappingOverload" (reportUnnecessaryTypeIgnoreComment)
+   .../projects/pandas-stubs/pandas-stubs/core/frame.pyi:1278:37 - error: Unnecessary "# pyright: ignore" rule: "reportOverlappingOverload" (reportUnnecessaryTypeIgnoreComment)
+   .../projects/pandas-stubs/pandas-stubs/core/frame.pyi:1302:37 - error: Unnecessary "# pyright: ignore" rule: "reportOverlappingOverload" (reportUnnecessaryTypeIgnoreComment)
+   .../projects/pandas-stubs/pandas-stubs/core/frame.pyi:1326:54 - error: Unnecessary "# type: ignore" comment (reportUnnecessaryTypeIgnoreComment)
+   .../projects/pandas-stubs/pandas-stubs/core/frame.pyi:1350:37 - error: Unnecessary "# pyright: ignore" rule: "reportOverlappingOverload" (reportUnnecessaryTypeIgnoreComment)
- 202 errors, 3 warnings, 0 informations
+ 208 errors, 3 warnings, 0 informations

jax (https://github.com/google/jax)
-   .../projects/jax/jax/_src/scipy/linalg.py:981:5 - error: Overload 1 for "qr" overlaps overload 2 and returns an incompatible type (reportOverlappingOverload)
-   .../projects/jax/jax/_src/scipy/linalg.py:997:5 - error: Overload 4 for "qr" overlaps overload 5 and returns an incompatible type (reportOverlappingOverload)
-   .../projects/jax/jax/_src/scipy/linalg.py:1102:5 - error: Overload 1 for "qr_multiply" overlaps overload 2 and returns an incompatible type (reportOverlappingOverload)
- 3711 errors, 72 warnings, 0 informations
+ 3708 errors, 72 warnings, 0 informations

@rchiodo

Copy link
Copy Markdown
Collaborator

The mypy_primer differences look good to me. The current-head run completed after ef17dc0a, and it shows the same expected diagnostic changes.

The removed overlap diagnostics in jinja, streamlit, Home Assistant, werkzeug, and jax are the intended product change. They're all defaulted disjoint-literal selector cases where the overloads were previously reported as overlapping. Nothing in the primer output indicates a corresponding call-site type regression.

The new pandas-stubs diagnostics are reportUnnecessaryTypeIgnoreComment. That's expected cleanup from the underlying overlap errors disappearing, not a type or API regression.

Prefect is the more interesting one. The override still fails with reportIncompatibleMethodOverride, but the old parameter mismatch goes away and the effective override return becomes Coroutine[..., T | Awaitable[T]]. That's correct because the base and override method TypeVars are independently scoped. The override parameter Callable[[], U] can accept the base Callable[[], T | Awaitable[T]] with the finite substitution U = T | Awaitable[T].

The actual incompatibility is then the return type: Coroutine[..., T | Awaitable[T]] isn't assignable to T. Applying RejectCyclicLowerBound to the parameter inference would reject that valid generic substitution and bring the false positive back. So the remaining error is in the right place now.

For SymPy, removing the two recursive-bound PolyElement reportInvalidTypeArguments diagnostics is intended and is the motivating case here. The rest is fairly broad and noisy inference churn across SymPy. I'm comfortable not treating that as actionable signal for this PR, though I wouldn't claim every individual SymPy difference is necessarily correct.

Based on that classification, I don't see a mypy_primer blocker here.

@github-actions

github-actions Bot commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

mypy_primer analysis

Advisory AI analysis of primer run 37384842100, attempt 2
for commit ef17dc0a60ca1357f0831a9f65f5871f50f3902d. This is not an approval or proof of correctness.

Regression review required. Potential regressions or recorded warning signals are listed first; causation must be established separately.

Potential regressions

sympy: Recursive lower-bound inference reshapes broad SymPy unions, adds new operator/member failures, and removes three simplify argument checks; the net change is not safely dismissible as noise.

Regression warning signals require review, regardless of the AI assessment:

  • Type-checking diagnostics disappear without replacements at the same locations.

AI assessment: Possible regression (medium confidence). PR attribution: Likely caused by the PR.

Before / baseline evidence: Baseline rejected recursive PolyElement bounds at rings.py:907-908 and diagnosed simplify calls at test_continuous_rv.py:1568, 1570, and 1575 because the inferred argument union included int, which is not Basic. Other locations carried unions without the newly retained Add member.

After / PR evidence: The bound errors disappear, many inferred unions gain Add or change members (including NotImplementedType), and new errors appear at bivariate.py:135/139/144, deutils.py:234, lie_group.py:619, riccati.py:702, single.py:2652, recurr.py:449, solvers.py:3121, and solveset.py:4182. The three simplify call/argument diagnostics vanish entirely.

Why this matters: Users may get newly rejected symbolic operations while losing checks that prevent non-Basic values from reaching simplify. The changed unions also alter attribute, operator, constructor, and override checking across solver/stats code. This is static precision/checking impact, not evidence of a Python runtime defect.

Causal analysis:

The solver now rejects T occurring in its own lower bound only when constraints are being tracked or RejectCyclicLowerBound is explicitly propagated. In ordinary inference, recursive symbolic protocols can therefore contribute nested/concrete members instead of failing the candidate: the removed PolyElement bound diagnostics and widespread Add/member substitutions follow that mechanism. The three removed simplify checks are a warning signal because int was previously the concrete incompatible member; the raw diff does not reveal whether the new path selected Any, a different overload, or removed int through a sound solution. SymPy is noisy and several lines are message rewrites at unchanged locations, but the coherent recursive-type shifts and removed checks justify regression review rather than blanket noise classification.

Uncertainty / next check: Pin the recorded SymPy commit and reveal the expressions passed at 1568/1570/1575 plus the bivariate operands. A solver control should compare T:=Container[T] with and without ConstraintTracker, then test Basic-only argument and operator/member checks. Not run.

  • Exact-head occurs-check is conditional, allowing recursive lower bounds in ordinary untracked inference.:
    // `T := T | int` arising from protocol matching against `T | int`)
    // are *not* considered cyclic - the original `adjSrcType` is
    // recorded as the lower bound and existing logic resolves it.
    if (
    (constraints || (flags & AssignTypeFlags.RejectCyclicLowerBound) !== 0) &&
    typeVarOccursIn(destType, adjSrcType)
    ) {
    diag?.addMessage(
    LocAddendum.typeAssignmentMismatch().format(evaluator.printSrcDestTypes(adjSrcType, destType))
    );
    return false;
    }
    newLowerBound = adjSrcType;
    } else if (isTypeSame(curLowerBound, adjSrcType, {}, recursionCount)) {
  • Exact-head recursive assignment propagates only RejectCyclicLowerBound, affecting nested protocol/type-variable comparisons.:
    if (
    !evaluator.assignType(
    curUpperBound,
    newLowerBound,
    diag?.createAddendum(),
    /* constraints */ undefined,
    flags & AssignTypeFlags.RejectCyclicLowerBound,
    recursionCount
    )
    ) {
    if (diag && diagAddendum) {
    diag.addMessage(
    LocAddendum.typeAssignmentMismatch().format(
    evaluator.printSrcDestTypes(newLowerBound, curUpperBound)
    )
  • Exact-head overload consistency explicitly requests cyclic-lower-bound rejection, contrasting with ordinary inference paths behind the ecosystem type shifts.:
    for (let i = 0; i < prevOverloads.length; i++) {
    const prevOverload = prevOverloads[i];
    const prevReturnType = FunctionType.getEffectiveReturnType(prevOverload);
    const returnType = FunctionType.getEffectiveReturnType(functionType);
    if (
    !prevReturnType ||
    !returnType ||
    this._evaluator.assignType(
    returnType,
    prevReturnType,
    /* diag */ undefined,
    /* constraints */ undefined,
    AssignTypeFlags.RejectCyclicLowerBound
    )
    ) {
    continue;
    }
    if (this._isOverlappingOverload(prevOverload, functionType, /* partialOverlap */ true)) {
    const altNode = this._findNodeForOverload(node, prevOverload);
    this._evaluator.addDiagnostic(
    DiagnosticRule.reportOverlappingOverload,
    LocMessage.overloadReturnTypeMismatch().format({
    name: node.d.name.d.value,
    newIndex: prevOverloads.length + 1,
    prevIndex: i + 1,
    }),
    (altNode || node).d.name
    );
    break;
    }
    }
    }

prefect: Recursive TypeVar acceptance widens an async override's coroutine result to T | Awaitable[T] and removes a parameter incompatibility, reducing the guarantee of one await yielding T.

AI assessment: Possible regression (medium confidence). PR attribution: Likely caused by the PR.

Before / baseline evidence: The concise baseline detail for wait_for_call_in_new_thread reported a narrower CoroutineType[Any, Any,T] return plus a parameter mismatch: the base accepts a callable returning T | Awaitable[T], while the override accepts only () -> T. A header was present at api.py:201 for an incompatible override.

After / PR evidence: The changed detail reports CoroutineType[Any,Any,T | Awaitable[T]]. The parameter-mismatch detail and the api.py:201 override header disappear, although a return incompatibility remains elsewhere. Because detail lines lack independent locations, the widened return cannot safely be assigned to the removed header.

Why this matters: Static users can no longer rely on one await of this async method producing T; it may still be Awaitable[T]. The removed contravariance check can also hide that an override rejects async-producing callables admitted by the base. This is a checker regression risk even if runtime behavior is unchanged.

Causal analysis:

The PR changes assignUnconstrainedTypeVar so a recursive lower bound is rejected only when a constraint tracker exists or RejectCyclicLowerBound is set. Ordinary inference without either can therefore retain a self-referential solution such as T including Awaitable[T]. That matches the observed coroutine payload widening and can make callable assignability appear acceptable, suppressing the parameter mismatch. Counterevidence: Prefect's abstract/override annotations may themselves model async behavior inconsistently, but that does not explain why the same declarations lose a check and precision under the new solver. Exact tested Prefect revision was not recovered.

Uncertainty / next check: Minimal control: generic base accepts Callable[[],T|Awaitable[T]], async override accepts Callable[[],T]; instantiate with Callable[[],Awaitable[int]]. Verify override rejection and reveal await override(...) as int, not int|Awaitable[int]. Not run.

Other project assessments

jinja: The compile overload warning disappeared because raw's default-selected return and its disjoint literal alternative overlap only through omission, not through one explicit call shape.

AI assessment: Expected improvement (medium confidence). PR attribution: Likely caused by the PR.

Before / baseline evidence: At src/jinja2/environment.py:711, baseline reported that compile overload 1 overlapped overload 2 with an incompatible return. This was a declaration-consistency diagnostic; the artifact does not show a changed inferred type at any call site.

After / PR evidence: The warning is absent. The PR recognizes defaulted literal parameters whose explicit accepted values are disjoint and whose omitted value selects the destination overload; it therefore does not count omission alone as unsafe overlap.

Why this matters: Jinja maintainers no longer need to suppress or restructure a useful overload set that distinguishes compiled code from raw source. Callers should retain the selected return for omitted raw and explicit literal raw values; no lost argument or member checking is evidenced.

Causal analysis:

Pyright's new isOverlapOnlyByOmission helper requires literal/None parameter types, verifies that the destination default belongs to its declared type, and requires no explicit type member shared with the source. assignFunction then rejects partial-overlap only when all corresponding parameters satisfy the omission-specific comparison. That directly explains this default-controlled compile overload warning disappearing without making the return types compatible or erasing them. The recorded ecosystem checkout was not resolved from the available log tail, so the exact Jinja declaration revision was not independently pinned; classification rests on the diagnostic shape and exact-head checker path.

Uncertainty / next check: Minimal control: reveal compile(...), compile(..., raw=False), compile(..., raw=True), and a call with raw: bool; verify the first three preserve their intended returns and the nonliteral call is rejected or safely unioned. This control was not run.

streamlit: multiselect's default-controlled overloads are no longer considered unsafe merely because omitting the literal selector reaches the default overload.

AI assessment: Expected improvement (medium confidence). PR attribution: Likely caused by the PR.

Before / baseline evidence: At lib/streamlit/elements/widgets/multiselect.py:231, baseline emitted reportOverlappingOverload for overload 1 versus overload 2 with incompatible returns. No call-site reveal changed in the artifact.

After / PR evidence: The declaration warning is gone under the new rule that excludes overlap caused solely by omitting a defaulted disjoint literal parameter.

Why this matters: Streamlit can describe return precision for its default behavior and alternate literal-selected behavior without a false declaration error. The evidence does not show that callers lost the list/container API or element checking.

Causal analysis:

The PR does not broadly permit incompatible overlapping overloads. isOverlapOnlyByOmission requires disjoint literal/None parameter domains and a destination default contained in the destination domain; the callable comparison additionally checks the full corresponding parameter list. This matches a selector-driven widget overload where omission deterministically chooses the default behavior. The exact Streamlit revision used by primer was unavailable, so this remains medium rather than high confidence.

Uncertainty / next check: Control with omitted selector, each explicit literal selector, and a nonliteral bool should confirm precise intended returns and that unsupported operations on each result are still rejected. It was not run.

core: Template.compile's incompatible-return overload warning was removed by the narrow default-omission exception, with no observed loss of call-result precision.

AI assessment: Expected improvement (medium confidence). PR attribution: Likely caused by the PR.

Before / baseline evidence: At homeassistant/helpers/template/__init__.py:900, baseline diagnosed overload 1 as overlapping overload 2 with an incompatible return. This checked the overload declaration, not a runtime call.

After / PR evidence: The warning is absent because the revised overlap comparison can distinguish explicit disjoint literal selector values from the single omitted/default call shape.

Why this matters: Home Assistant can retain a useful overload API for default versus alternate compilation modes without a suppression. The artifact contains no evidence that invalid arguments, attributes, or operators on compile results stopped being checked.

Causal analysis:

The exact-head helper only recognizes an omission-only collision when all participating types are literal/None, the destination default is included in its own parameter type, and destination/source parameter types share no explicit member. assignFunction consults that result during partial overload comparison. That mechanism is specific enough to explain this single compile warning and does not imply Any/Unknown widening. The recorded Home Assistant checkout was not recoverable, so its overload body was not pinned to the run.

Uncertainty / next check: Check omitted mode, each literal mode, and a widened bool variable. Expected control: precise returns for literals/default and no unsound acceptance of operations common to neither return. Not run.

werkzeug: get_data's as_text=False default and as_text=True alternative no longer form an unsafe overlap solely because the argument can be omitted.

AI assessment: Expected improvement (high confidence). PR attribution: Likely caused by the PR.

Before / baseline evidence: At src/werkzeug/wrappers/request.py:577, baseline reported that get_data overload 1 overlapped overload 2 and returned an incompatible type. The familiar overload distinction is bytes for the false/default branch versus str for true.

After / PR evidence: The declaration diagnostic is removed. Explicit Literal[False] and Literal[True] domains are disjoint; omission selects the false default, so there is no ambiguous explicit call that can choose incompatible returns.

Why this matters: Werkzeug users retain precise bytes versus str results and maintainers no longer need an ignore for a sound default-controlled overload. This is useful type information preservation, not reduced downstream checking.

Causal analysis:

isOverlapOnlyByOmission checks exactly this pattern: literal/None types only, the destination default belongs to its declared type, and no explicit member is shared with the source. The callable overlap logic then treats omission as non-overlap when corresponding parameters all pass. Since as_text=False deterministically yields bytes and as_text=True yields str, removing the declaration warning is consistent with overload semantics; there is no artifact evidence of result erasure.

Uncertainty / next check: Positive control: reveal get_data() and get_data(as_text=True) as bytes and str. Negative control: bytes-only and str-only operations should fail on the opposite result, and a nonliteral bool should not receive an unjustified single return. Not run.

pandas-stubs: Existing overlap suppressions became unnecessary because selector overloads now exclude default-only collisions; this is cleanup evidence, not new call-site errors.

AI assessment: Expected improvement (medium confidence). PR attribution: Likely caused by the PR.

Before / baseline evidence: The affected frame.pyi overload declarations carried pyright/type ignores for reportOverlappingOverload, so baseline accepted the file without reporting those comments as unnecessary.

After / PR evidence: At frame.pyi:1206, 1254, 1278, 1302, 1326, and 1350, Pyright reports the ignores as unnecessary after the underlying overlap diagnostics cease to be produced.

Why this matters: Stub maintainers can remove obsolete checker-specific suppressions while preserving overload-based DataFrame return precision. Downstream users do not gain six semantic errors; these diagnostics only flag dead comments in the stub package's strict configuration.

Causal analysis:

The PR's omission-only logic changes declaration validation, and the unnecessary-ignore rule then exposes comments that no longer suppress anything. This causal chain explains why the only new headers are reportUnnecessaryTypeIgnoreComment. It does not establish that every ignored overload is correct: the concise artifact lacks each overload set, and the exact pandas-stubs revision was not resolved. However, the helper's disjoint-literal guards make broad suppression unlikely.

Uncertainty / next check: Remove each ignore in a control checkout, inspect every adjacent overload pair, and test omitted, literal-selected, and widened-selector calls for precise outer DataFrame/Series APIs. This was not performed.

jax: qr and qr_multiply mode overloads stopped warning where incompatible tuple returns are selected by disjoint literals and the omitted default, rather than an ambiguous explicit call.

AI assessment: Expected improvement (medium confidence). PR attribution: Likely caused by the PR.

Before / baseline evidence: Baseline reported unsafe overlaps at linalg.py:981 and 997 for qr and at 1102 for qr_multiply. These APIs use mode-dependent return shapes; the artifact shows declaration warnings, not erased inferred call results.

After / PR evidence: The three overlap diagnostics are absent under the new omission-only exception for defaulted literal selectors.

Why this matters: JAX can retain shape/tuple-sensitive overloads without false diagnostics. This matters because collapsing these returns would lose tuple arity and array operations; the observed change instead removes declaration warnings and does not show such collapse.

Causal analysis:

The PR first checks whether corresponding parameters differ only through omission of a default whose literal belongs to the destination domain, while explicit destination/source literals have no common member. It then excludes that case from partial overlap. This matches mode-dispatched qr APIs whose omitted mode has one documented return and explicit modes have others. Exact ecosystem source was not pinned, so all overload pairs and retained array types remain to be checked.

Uncertainty / next check: Reveal qr/qr_multiply results for omitted mode and every accepted literal mode, then use tuple indexing/unpacking and array members as positive controls; pass a widened str as a negative control. Not run.

Full evidence and limitations: download mypy-primer-analysis-report from this analysis run.
The original raw primer comment is unchanged. Treat uncertainty and possible regressions as requests for human review.

@rchiodo
Rich Chiodo (rchiodo) merged commit fbaf3dd into microsoft:main Oct 5, 2026
17 checks passed
@crypt0lith
crypt0lith deleted the fix/recursive-lowerbound-occurs-check branch October 6, 2026 05:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

review-auto:approved Automated review: no blocking findings (approval posted).

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants