[ty] Fix stack overflow when forwarding generic callbacks #29971
<!-- generated-comment typing-conformance -->
<!-- report-run:41738703620:1 -->
Typing conformance results
No changes detected ✅
<details>
<summary>Current numbers</summary>
<br>
The percentage of diagnostics emitted that were expected errors held steady at <b>98.60%</b>. The percentage of expected errors that received a diagnostic held steady at <b>98.86%</b>. The number of fully passing files held steady at <b>137/146</b>.
</details>
---
Results for 1023cf9 · Workflow run
<!-- generated-comment memory -->
<!-- report-run:41738703510:1 -->
Memory usage report
Summary
| Project | Old | New | Diff | Outcome |
|---------|-----|-----|------|---------|
| prefect | 455.25MB | 455.27MB | +0.01% (25.55kB) | ⏫ |
| trio | 91.97MB | 91.97MB | +0.00% (408.00B) | ⏫ |
| flake8 | 38.07MB | 38.07MB | - | ✅ |
| sphinx | 185.37MB | 185.37MB | - | ✅ |
Significant changes
<details>
<summary>Click to expand detailed breakdown</summary>
prefect
| Name | Old | New | Diff | Outcome |
|------|-----|-----|------|---------|
| Type<'db>::apply_specialization_inner_::interned_arguments | 3.08MB | 3.09MB | +0.47% (14.92kB) |⏫ |
| Type<'db>::apply_specialization_inner_ | 2.44MB | 2.45MB | +0.36% (9.00kB) |⏫ |
| infer_definition_types | 36.17MB | 36.17MB | +0.00% (896.00B) |⏫ |
| infer_scope_types_impl | 19.11MB | 19.11MB | +0.00% (640.00B) |⏫ |
| infer_expression_types_impl | 22.42MB | 22.42MB | +0.00% (184.00B) |⏫ |
| Type<'db>::class_member_with_policy_inner_ | 7.92MB | 7.92MB | -0.00% (48.00B) |⬇️ |
| infer_statement_types_impl | 565.65kB | 565.70kB | +0.01% (48.00B) |⏫ |
| member_lookup_with_policy_inner | 5.74MB | 5.74MB | -0.00% (40.00B) |⬇️ |
| effective_superclass_variable_kind | 155.29kB | 155.27kB | -0.02% (24.00B) |⬇️ |
| FunctionType<'db>::literal_signature_ | 2.50MB | 2.50MB | +0.00% (8.00B) |⏫ |
trio
| Name | Old | New | Diff | Outcome |
|------|-----|-----|------|---------|
| Type<'db>::apply_specialization_inner_::interned_arguments | 689.53kB | 689.77kB | +0.03% (240.00B) |⏫ |
| Type<'db>::apply_specialization_inner_ | 530.71kB | 530.85kB | +0.03% (144.00B) |⏫ |
| infer_expression_types_impl | 5.56MB | 5.56MB | +0.00% (16.00B) |⏫ |
| infer_scope_types_impl | 2.73MB | 2.73MB | +0.00% (8.00B) |⏫ |
</details>
---
Results for 1023cf9 · Workflow run
<!-- generated-comment ty-ecosystem -->
<!-- report-run:41738703507:1 -->
ecosystem-analyzer results
No diagnostic changes detected ✅
Full report with detailed diff · Timing results
---
Results for 1023cf9 · Workflow run
The retry can panic when freshening changes the number of parameters. This call produces an ordinary argument diagnostic on the base revision and an index-out-of-bounds panic on this branch.
from collections.abc import Callable
def f[**P](cb: Callable[P, None], *args: *tuple[()], x: int) -> None:
pass
f(f, x=1)
Argument matching records x at index 2. Freshening expands the empty tuple and moves x to index 1, but the retry reuses the original match. Could we freshen before matching, or rebuild the matches and per-parameter state for the fresh signature?
invoke([invoke], 1) now passes type checking. The outer call forwards 1 to the inner invoke as its cbs argument. Both overloads require a list there, and the implementation tries to iterate over the integer. Main rejects the call.
from collections.abc import Callable
from typing import overload
@overload
def invoke[**P](cbs: list[Callable[P, object]], /, *args: P.args, **kwargs: P.kwargs) -> None: ...
@overload
def invoke(cbs: list[object], /, flag: None) -> None: ...
def invoke(cbs, *args, **kwargs):
for cb in cbs:
cb(*args, **kwargs)
invoke([invoke], 1)
The list literal has a different inferred type for each overload. Those types are keyed by the original parameter annotations, so looking up the fresh annotation can miss and drop the list from inference. Could we carry the corresponding argument type into the retry or infer it again with the fresh annotation?
Freshening the constructor signature here loses the type inferred from 1. Main reveals Box[Literal[1]] for this call. On this branch the class type variable escapes into the result as Box[T@Box].
from collections.abc import Callable
from typing import overload, reveal_type
class Box[T]:
@overload
def __init__[**P](self, fn: Callable[P, object], value: T): ...
@overload
def __init__(self, fn: object, value: T): ...
def __init__(self, fn, value):
self.value = value
reveal_type(Box(Box, 1))
The synthetic receiver and constructor_context.instance_type still refer to the original T after the signature gets its fresh variables. Could we keep all three in sync, as ConstructorBinding::freshen_class_typevars does?
The standalone self-call from the issue now works, but wrapping that same expression in reveal_type still aborts ty check with a stack overflow.
from collections.abc import Callable
from typing import reveal_type
def identity[**P, R](f: Callable[P, R]) -> Callable[P, R]:
return f
reveal_type(identity(identity))
Here argument_type_context_specialization reaches GenericContext::specialize_recursive while collecting the argument context, before this check runs. With a TypeVarTuple, the first infer(self) can also build a merged specialization before it returns.
from collections.abc import Callable
def identity[**P, R, *Ts](f: Callable[P, R], *args: *Ts) -> Callable[P, R]:
return f
identity(identity)
Both examples also overflow on main, so we could consider this a separate follow-up if it's not easy to fix.
A callback can refer to the enclosing function’s P and R even when it has no generic context of its own. This recursive call still aborts ty check on both the base revision and this branch.
from collections.abc import Callable
def identity[**P, R](f: Callable[P, R], flag: bool = False) -> Callable[P, R]:
def wrap(cb: Callable[P, R]) -> Callable[P, R]:
return cb
if flag:
return identity(wrap)(f)
return f
This filter skips wrap, whose annotations use the outer invocation’s variables. The recursive invocation of identity needs its own P and R before we substitute into those annotations. Could we account for variables captured from an enclosing function here while preserving references to a generic class’s parameters?
Would this PR also fix astral-sh/ty#2859? Some of the examples looks similar
46b4a8799d removes the retry and freshens the signature before matching arguments. e4b14499a7 adds the invalid keyword next to the valid call and checks the column of enabled. Regression test
Codex replay:f(f, x=1)passes.f(f, x="wrong")reportsinvalid-argument-typeonx.
Carl, could you take another look at 46b4a8799d and the keyword assertion from e4b14499a7? The revised examples are in a126aa2f21.
Removing the retry also removes the second lookup with a fresh annotation. Each overload uses the argument type inferred with its own parameter annotation. Regression test
Codex replay:invoke([invoke], 1)reportsno-matching-overloadon both the base and the updated PR.
Removing the retry leaves class-variable freshening with ConstructorBinding::freshen_class_typevars, which updates the signature, synthetic receiver, and per-overload instance type together. Regression test
Codex replay:Box(Box, 1)revealsBox[Literal[1]]on both the base and the updated PR.
Both cases are covered in 46b4a8799d. The callable relation separates the callback’s bound variables before capturing P or constraining R, so this also applies during argument-context inference. Generic identity test · TypeVarTuple test
Codex replay:reveal_type(identity(identity))yields[P, R](f: (P) -> R) -> ((*P) -> R). TheTsexample also passes.
The recursive invocation gets fresh P and R before argument matching. That lets wrap retain the variables it captures from the enclosing invocation. Closure test · Class parameter test
Codex replay: passing a(number: int) -> strcallback throughidentity(target, True)preserves its signature and rejects a string argument. A method bound toHolder[[int]]also keeps its(int, /) -> intsignature.
carljm
charliermarsh
Summary
Passing
identityto itself makes ty 0.0.96 abort with a stack overflow. The outer call needs to inferPandRwhile the inneridentityis still generic over its ownPandR.The same problem occurs when one
ExitStackregisters another stack’scallbackmethod. Here the inner stack schedulesresource.closeon the outer stack, so the resource stays open until the outer stack exits.Both callbacks come from the same generic declaration. Substituting the callee’s variables into the callback’s own signature can keep expanding that signature. We now give a recursive callee fresh variables before matching arguments to parameters. When capturing the callback’s signature, we keep its own bound variables independent of the callee’s. The final argument check preserves those bindings when it applies the callee’s specialization.
Closes https://github.com/astral-sh/ty/issues/4898.