← Back to Pull requests

[ty] Fix stack overflow when forwarding generic callbacks #29971

Open
charliermarsh opened this pull request with 377 lines diff across 9 files
View on GitHub
charliermarsh charliermarsh commented on Nov 03, 2026 17:10 UTC
Author

Summary

Passing identity to itself makes ty 0.0.96 abort with a stack overflow. The outer call needs to infer P and R while the inner identity is still generic over its own P and R.

from collections.abc import Callable

def identity[**P, R](f: Callable[P, R]) -> Callable[P, R]:
    return f

identity(identity)

The same problem occurs when one ExitStack registers another stack’s callback method. Here the inner stack schedules resource.close on the outer stack, so the resource stays open until the outer stack exits.

from contextlib import ExitStack
from io import BytesIO

with ExitStack() as outer:
    with ExitStack() as inner:
        resource = BytesIO()
        inner.callback(outer.callback, resource.close)
    assert not resource.closed
assert resource.closed

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.

Diff: 377 lines (+339 / -38) across 9 files Reviewer: carljm Review duration: 38850m
All Vouch review confidence checks passed
Residual risk 0.04 = Change Risk (0.50) × (1 − Review Confidence (0.91)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.50 · 377 lines diff across 9 files
0.50
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.91 · 5 substantive comment(s)
0.91
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
91%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.355
Real PR Conversation Timeline
15 items
astral-automations-bot[bot] astral-automations-bot[bot] commented on Nov 03, 2026 17:13 UTC
Bot

<!-- 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

astral-automations-bot[bot] astral-automations-bot[bot] commented on Nov 03, 2026 17:15 UTC
Bot

<!-- 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

astral-automations-bot[bot] astral-automations-bot[bot] commented on Nov 03, 2026 17:18 UTC
Bot

<!-- 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

carljm carljm commented on code on Nov 03, 2026 18:50 UTC
Code Review
crates/ty_python_semantic/src/types/call/bind.rs:1
@@ -8870,22 +8870,36 @@ impl<'db> Binding<'db> {
             return;
         }
 
-        let inferred = CallInference {
-            db,
-            env,
-            signature: &self.signature,
-            arguments,
-            argument_matches: &self.argument_matches,
-            call_expression_tcx,
-            return_ty: self.return_ty,
-            is_partial_application: self.is_partial_application,
-            is_constructor: self.constructor_context.is_some(),
-            inferable_typevars: self
-                .signature
-                .generic_context
-                .map_or(TypeVarSet::None, |context| context.inferable_typevars(db)),
+        let infer = |binding: &Self| {
+            CallInference {
+                db,
+                env,
+                signature: &binding.signature,
+                arguments,
+                argument_matches: &binding.argument_matches,

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?

carljm carljm commented on code on Nov 03, 2026 18:50 UTC
Code Review
crates/ty_python_semantic/src/types/call/bind.rs:1
@@ -8870,22 +8870,36 @@ impl<'db> Binding<'db> {
             return;
         }
 
-        let inferred = CallInference {
-            db,
-            env,
-            signature: &self.signature,
-            arguments,
-            argument_matches: &self.argument_matches,
-            call_expression_tcx,
-            return_ty: self.return_ty,
-            is_partial_application: self.is_partial_application,
-            is_constructor: self.constructor_context.is_some(),
-            inferable_typevars: self
-                .signature
-                .generic_context
-                .map_or(TypeVarSet::None, |context| context.inferable_typevars(db)),
+        let infer = |binding: &Self| {
+            CallInference {
+                db,
+                env,
+                signature: &binding.signature,
+                arguments,

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?

carljm carljm commented on code on Nov 03, 2026 18:50 UTC
Code Review
crates/ty_python_semantic/src/types/call/bind.rs:1
@@ -8870,22 +8870,36 @@ impl<'db> Binding<'db> {
             return;
         }
 
-        let inferred = CallInference {
-            db,
-            env,
-            signature: &self.signature,
-            arguments,
-            argument_matches: &self.argument_matches,
-            call_expression_tcx,
-            return_ty: self.return_ty,
-            is_partial_application: self.is_partial_application,
-            is_constructor: self.constructor_context.is_some(),
-            inferable_typevars: self
-                .signature
-                .generic_context
-                .map_or(TypeVarSet::None, |context| context.inferable_typevars(db)),
+        let infer = |binding: &Self| {
+            CallInference {
+                db,
+                env,
+                signature: &binding.signature,
+                arguments,
+                argument_matches: &binding.argument_matches,
+                call_expression_tcx,
+                return_ty: binding.return_ty,
+                is_partial_application: binding.is_partial_application,
+                is_constructor: binding.constructor_context.is_some(),
+                inferable_typevars: binding
+                    .signature
+                    .generic_context
+                    .map_or(TypeVarSet::None, |context| context.inferable_typevars(db)),
+            }
+            .infer(constraints)
+        };
+
+        let mut inferred = infer(self);
+        if let Some(freshness) = inferred
+            .inference
+            .and_then(|inference| inference.captured_paramspec_freshness(db))
+        {
+            // If a decorator captures another occurrence of itself, its parameter list can
+            // refer to the callee's own variables. Give the callee a separate set before
+            // substituting into the captured callback.
+            self.freshen_bound_typevars(db, env, freshness.increment().value());

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?

carljm carljm commented on code on Nov 03, 2026 18:50 UTC
Code Review
crates/ty_python_semantic/src/types/call/bind.rs:1
@@ -8870,22 +8870,36 @@ impl<'db> Binding<'db> {
             return;
         }
 
-        let inferred = CallInference {
-            db,
-            env,
-            signature: &self.signature,
-            arguments,
-            argument_matches: &self.argument_matches,
-            call_expression_tcx,
-            return_ty: self.return_ty,
-            is_partial_application: self.is_partial_application,
-            is_constructor: self.constructor_context.is_some(),
-            inferable_typevars: self
-                .signature
-                .generic_context
-                .map_or(TypeVarSet::None, |context| context.inferable_typevars(db)),
+        let infer = |binding: &Self| {
+            CallInference {
+                db,
+                env,
+                signature: &binding.signature,
+                arguments,
+                argument_matches: &binding.argument_matches,
+                call_expression_tcx,
+                return_ty: binding.return_ty,
+                is_partial_application: binding.is_partial_application,
+                is_constructor: binding.constructor_context.is_some(),
+                inferable_typevars: binding
+                    .signature
+                    .generic_context
+                    .map_or(TypeVarSet::None, |context| context.inferable_typevars(db)),
+            }
+            .infer(constraints)
+        };
+
+        let mut inferred = infer(self);

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.

carljm carljm commented on code on Nov 03, 2026 18:50 UTC
Code Review
crates/ty_python_semantic/src/types/generics.rs:1
@@ -2581,6 +2581,33 @@ pub(crate) struct TypeVarInference<'db> {
 impl get_size2::GetSize for TypeVarInference<'_> {}
 
 impl<'db> TypeVarInference<'db> {
+    /// Returns the highest nonce in the captured signatures if any bind a callee type variable.
+    pub(super) fn captured_paramspec_freshness(self, db: &'db dyn Db) -> Option<TypeVarNonce> {
+        let callee = self.generic_context(db);
+        let captures = callee
+            .variables(db)
+            .zip(self.merged_types(db))
+            .filter_map(|(variable, inferred)| inferred.filter(|_| variable.is_paramspec(db)));
+        // Only type variables bound by the captured signature belong to another callable
+        // occurrence. Its parameter annotations can refer to the callee's generic class.
+        let variables = captures
+            .flat_map(|capture| match capture {
+                Type::Intersection(intersection) => Either::Left(intersection.iter_positive(db)),
+                ty => Either::Right(std::iter::once(ty)),
+            })
+            .filter_map(Type::as_callable)
+            .flat_map(|callable| callable.signatures(db))
+            .filter_map(|signature| signature.generic_context)

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?

MeGaGiGaGon MeGaGiGaGon commented on Nov 03, 2026 19:58 UTC
Contributor

Would this PR also fix astral-sh/ty#2859? Some of the examples looks similar

charliermarsh charliermarsh commented on code on Nov 03, 2026 20:40 UTC
Code Review
crates/ty_python_semantic/src/types/call/bind.rs:1
@@ -8870,22 +8870,36 @@ impl<'db> Binding<'db> {
             return;
         }
 
-        let inferred = CallInference {
-            db,
-            env,
-            signature: &self.signature,
-            arguments,
-            argument_matches: &self.argument_matches,
-            call_expression_tcx,
-            return_ty: self.return_ty,
-            is_partial_application: self.is_partial_application,
-            is_constructor: self.constructor_context.is_some(),
-            inferable_typevars: self
-                .signature
-                .generic_context
-                .map_or(TypeVarSet::None, |context| context.inferable_typevars(db)),
+        let infer = |binding: &Self| {
+            CallInference {
+                db,
+                env,
+                signature: &binding.signature,
+                arguments,
+                argument_matches: &binding.argument_matches,

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") reports invalid-argument-type on x.

Carl, could you take another look at 46b4a8799d and the keyword assertion from e4b14499a7? The revised examples are in a126aa2f21.

charliermarsh charliermarsh commented on code on Nov 03, 2026 20:40 UTC
Code Review
crates/ty_python_semantic/src/types/call/bind.rs:1
@@ -8870,22 +8870,36 @@ impl<'db> Binding<'db> {
             return;
         }
 
-        let inferred = CallInference {
-            db,
-            env,
-            signature: &self.signature,
-            arguments,
-            argument_matches: &self.argument_matches,
-            call_expression_tcx,
-            return_ty: self.return_ty,
-            is_partial_application: self.is_partial_application,
-            is_constructor: self.constructor_context.is_some(),
-            inferable_typevars: self
-                .signature
-                .generic_context
-                .map_or(TypeVarSet::None, |context| context.inferable_typevars(db)),
+        let infer = |binding: &Self| {
+            CallInference {
+                db,
+                env,
+                signature: &binding.signature,
+                arguments,

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) reports no-matching-overload on both the base and the updated PR.

charliermarsh charliermarsh commented on code on Nov 03, 2026 20:40 UTC
Code Review
crates/ty_python_semantic/src/types/call/bind.rs:1
@@ -8870,22 +8870,36 @@ impl<'db> Binding<'db> {
             return;
         }
 
-        let inferred = CallInference {
-            db,
-            env,
-            signature: &self.signature,
-            arguments,
-            argument_matches: &self.argument_matches,
-            call_expression_tcx,
-            return_ty: self.return_ty,
-            is_partial_application: self.is_partial_application,
-            is_constructor: self.constructor_context.is_some(),
-            inferable_typevars: self
-                .signature
-                .generic_context
-                .map_or(TypeVarSet::None, |context| context.inferable_typevars(db)),
+        let infer = |binding: &Self| {
+            CallInference {
+                db,
+                env,
+                signature: &binding.signature,
+                arguments,
+                argument_matches: &binding.argument_matches,
+                call_expression_tcx,
+                return_ty: binding.return_ty,
+                is_partial_application: binding.is_partial_application,
+                is_constructor: binding.constructor_context.is_some(),
+                inferable_typevars: binding
+                    .signature
+                    .generic_context
+                    .map_or(TypeVarSet::None, |context| context.inferable_typevars(db)),
+            }
+            .infer(constraints)
+        };
+
+        let mut inferred = infer(self);
+        if let Some(freshness) = inferred
+            .inference
+            .and_then(|inference| inference.captured_paramspec_freshness(db))
+        {
+            // If a decorator captures another occurrence of itself, its parameter list can
+            // refer to the callee's own variables. Give the callee a separate set before
+            // substituting into the captured callback.
+            self.freshen_bound_typevars(db, env, freshness.increment().value());

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) reveals Box[Literal[1]] on both the base and the updated PR.

charliermarsh charliermarsh commented on code on Nov 03, 2026 20:40 UTC
Code Review
crates/ty_python_semantic/src/types/call/bind.rs:1
@@ -8870,22 +8870,36 @@ impl<'db> Binding<'db> {
             return;
         }
 
-        let inferred = CallInference {
-            db,
-            env,
-            signature: &self.signature,
-            arguments,
-            argument_matches: &self.argument_matches,
-            call_expression_tcx,
-            return_ty: self.return_ty,
-            is_partial_application: self.is_partial_application,
-            is_constructor: self.constructor_context.is_some(),
-            inferable_typevars: self
-                .signature
-                .generic_context
-                .map_or(TypeVarSet::None, |context| context.inferable_typevars(db)),
+        let infer = |binding: &Self| {
+            CallInference {
+                db,
+                env,
+                signature: &binding.signature,
+                arguments,
+                argument_matches: &binding.argument_matches,
+                call_expression_tcx,
+                return_ty: binding.return_ty,
+                is_partial_application: binding.is_partial_application,
+                is_constructor: binding.constructor_context.is_some(),
+                inferable_typevars: binding
+                    .signature
+                    .generic_context
+                    .map_or(TypeVarSet::None, |context| context.inferable_typevars(db)),
+            }
+            .infer(constraints)
+        };
+
+        let mut inferred = infer(self);

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). The Ts example also passes.

charliermarsh charliermarsh commented on code on Nov 03, 2026 20:40 UTC
Code Review
crates/ty_python_semantic/src/types/generics.rs:1
@@ -2581,6 +2581,33 @@ pub(crate) struct TypeVarInference<'db> {
 impl get_size2::GetSize for TypeVarInference<'_> {}
 
 impl<'db> TypeVarInference<'db> {
+    /// Returns the highest nonce in the captured signatures if any bind a callee type variable.
+    pub(super) fn captured_paramspec_freshness(self, db: &'db dyn Db) -> Option<TypeVarNonce> {
+        let callee = self.generic_context(db);
+        let captures = callee
+            .variables(db)
+            .zip(self.merged_types(db))
+            .filter_map(|(variable, inferred)| inferred.filter(|_| variable.is_paramspec(db)));
+        // Only type variables bound by the captured signature belong to another callable
+        // occurrence. Its parameter annotations can refer to the callee's generic class.
+        let variables = captures
+            .flat_map(|capture| match capture {
+                Type::Intersection(intersection) => Either::Left(intersection.iter_positive(db)),
+                ty => Either::Right(std::iter::once(ty)),
+            })
+            .filter_map(Type::as_callable)
+            .flat_map(|callable| callable.signatures(db))
+            .filter_map(|signature| signature.generic_context)

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) -> str callback through identity(target, True) preserves its signature and rejects a string argument. A method bound to Holder[[int]] also keeps its (int, /) -> int signature.

Reviewers
Assignees
charliermarsh charliermarsh
Labels
risk: low confidence: 91.5% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 50.2% (MEDIUM) · Higher = larger blast radius
50.2%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 91.5% · Lower = rushed or shallow review
91.5%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 4.3% · Safe to merge
4.3%
Repository