[py] generate loop recursion silently caps max_turns below the configured value
What
The Python generate loop is implemented as recursion. generate_turn ends by calling run_wrap_generate with current_turn + 1:
# _generate.py:1450
return await run_wrap_generate(
registry=registry,
options=after_tools.options,
mw_pipeline=mw_pipeline,
current_turn=current_turn + 1,
message_index=after_tools.message_index,
call=call,
resolved=resolved,
)
Each tool round is a stack frame, and each frame also nests through the full wrap_generate middleware chain. DEFAULT_MAX_TURNS = 50 against Python's default recursion limit of 1000 leaves less headroom than it appears.
Impact: max_turns is not the real ceiling
Measured with a model that always requests a tool, varying only the number of registered wrap_generate middleware:
| middleware | max_turns |
result | model calls | peak frames |
|---|---|---|---|---|
| 0 | 50 | aborted — correct |
51 | — |
| 1 | 50 | aborted — correct |
51 | 499 |
| 5 | 50 | failed / internal error |
36 | 940 |
| 10 | 50 | failed / internal error |
— | 940 |
| 5 | 30 | aborted — correct |
31 | — |
| 5 | 20 | aborted — correct |
21 | — |
With five wrap_generate middleware the effective ceiling drops to roughly 35 turns. The configured max_turns=50 is never reached.
Two problems with that:
- Silent: the caller gets
finish_reason=failed,finish_message='internal error',status=INTERNAL. Nothing indicates a stack limit was hit, or thatmax_turnswas not honored. - Coupled to unrelated config: the real turn ceiling depends on how many middleware an application happens to register. Adding an observability middleware can reduce the usable turn budget.
Why Go does not have this problem
Go uses the same recursive shape:
// go/ai/generate.go:770
return generate(ctx, newReq, currentTurn+1, currentIndex+1)
Goroutine stacks grow dynamically into the hundreds of MB. 50 frames is free. Python's limit is fixed at 1000 frames. The design ported; the assumption underneath it did not.
Suggested fix
Drive the loop with a while in run_generate, using the existing ContinueTurn as the loop condition. ContinueTurn already carries exactly the state the next iteration needs (options, messages, message_index), so the change is mostly mechanical.
This keeps every current abstraction and fixes three things at once:
- Removes the ceiling.
max_turnsbecomes the only limit, independent of middleware count. - Collapses four error-boxing sites into one. Today
run_wrap_generate,generate_turn, andrun_tools_or_stopeach box failures independently, and each must separately remember to attach the turn's request. Three of the four forgot, which was the bug fixed in #6255 — seee6c2f17ec,a83f06b65,bd156fffc. - Makes
wrap_generatefiring once per turn an explicit choice. Today it is a consequence of where the hook dispatch sits relative to the recursion. The name suggests it wraps the whole generate call; it wraps a single turn. This surprises middleware authors who count invocations or cache per-call.
Interim mitigation
If the refactor is not wanted now, the failure should at least be legible: catch RecursionError in run_generate and surface a distinct status and message rather than internal error, so a user can tell the difference between "my tool threw" and "the framework ran out of stack".
Repro
Register N no-op wrap_generate middleware, point at a model that always returns a tool request, set max_turns=50, and compare finish_reason for N=1 vs N=5.
Hi — thanks for the detailed write-up; the measured table makes the impact easy to
reason about. I traced the same path on current main and can confirm the code shape:
DEFAULT_MAX_TURNS = 50 (py/packages/genkit/src/genkit/_ai/_generate.py, L106),
run_wrap_generate re-enters with current_turn + 1 (L1475), and the turn ceiling
check (L1621) counts turns while every middleware frame still consumes Python stack.
Before writing code I'd like to align on scope, since the two options differ a lot in review cost:
- Full fix — drive the turn loop with a
whileinrun_generate, usingContinueTurnas the loop condition as suggested. As a side effect the four error-boxing sites collapse into one, and "wrap_generate fires once per turn" becomes a documented contract instead of an accident of where the hook dispatch sits. This is the change I would prefer to make, but it touches the core loop, so I'd rather have a maintainer's nod first. - Interim mitigation — catch
RecursionErrorinrun_generateand surface a distinct status/message instead ofinternal error, so callers can tell "stack exhausted, max_turns was never reached" from a tool failure.
Which direction would you prefer? If (1): should wrap_generate keep firing once per
turn (current behavior) or once per generate call (what the name suggests)?
Disclosure: drafted with a coding agent; the line references above were checked
against current main.
Looks like the recursion limit is causing issues when there are multiple middleware layers. I’d check how the recursion depth is affecting the max_turns setting.
Thanks @modelpath-dev — that matches the trace: each middleware layer adds Python stack frames per turn, so the effective turn budget is roughly recursion_limit / frames_per_turn and max_turns can never be reached before the stack is exhausted.
The two scope questions above are still open though, and I'd rather not touch the core loop without a maintainer's call:
- Full fix — drive the loop with a
whileinrun_generate(collapses the four error-boxing sites, makes "wrap_generate fires once per turn" a documented contract), or - Interim mitigation — catch
RecursionErrorand surface a distinct status instead ofinternal error.
Happy to start with (2) as a small standalone PR if (1) needs more discussion.
I'd lean towards starting with the interim mitigation to address the immediate issue. It provides a clearer error message without altering the core loop, which seems like a safer first step. We can then discuss the full fix in more depth.