Skip to content

fix(chat): hard-stop runaway tool loops per turn - #1752

Merged
dcramer merged 6 commits into
mainfrom
fix/turn-tool-call-execution-limit
Sep 1, 2026
Merged

dcramer merged 6 commits into
mainfrom
fix/turn-tool-call-execution-limit

Conversation

@sentry-junior

@sentry-junior sentry-junior Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Event-task CI watches (notably getsentry/sentry#121448) kept thrashing bash polls for hours as system-actor dispatches. Soft-yield progress bypassed the existing slice budget, so unattributed spend spiked (~5.68B input tokens / multi-hour loops on that path).

Root cause

One turn already has a 100-slice resume budget, but soft yield with progress can keep advancing without hitting that stop. There was no hard tool-call budget, so a single turn could execute hundreds of tool calls. A first pass counted tool calls from the live turn message slice; compaction and handoff rewrite history and reset turnStartMessageIndex to 0, so that recount undercounted and the hard cap could reset mid-turn.

Fix

  • Add maxToolCallsPerTurn (150) on bot config, set from production dispatch tool-call distributions.
  • Keep a durable cumulativeToolCallCount on the Redis turn cursor and charge +1 on each admitted beforeToolCall.
  • Checkpoint that total on running/paused/failed writes so resume, compaction, and handoff keep the same absolute count.
  • Fail closed through pendingPiHookError + block/terminate so Pi does not swallow the limit into a recoverable tool error.
  • Share user-facing limit replies via the turn execution-limit path (slice + tool-call).

Residual risk

This stops one runaway turn, including after history replacement. Separate event-task fires still each get a fresh budget; follow-up could add task/dispatch-level spend or duration caps if needed.

Requested by Junior system actor resource-event.

--

View Junior Session [Sentry]

Event-task CI watches thrashing through hundreds of bash polls burned multi-hour
system-actor spend because soft-yield progress bypassed the slice budget. Cap
tool calls per turn and fail closed with the shared execution-limit path.

Co-Authored-By: David Cramer <[email protected]>
@vercel

vercel Bot commented Sep 1, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
junior-docs Ready Ready Preview Sep 1, 2026 6:28pm UTC

Request Review

@dcramer
dcramer marked this pull request as ready for review September 1, 2026 17:18
@github-actions github-actions Bot added the risk: high PR risk score: high label Sep 1, 2026
Drop the base-error class hierarchy for a type guard, strip thrash/budget
jargon, and set the limit from production dispatch tool-call distributions.

Co-Authored-By: David Cramer <[email protected]>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit c64b64b. Configure here.

Comment thread packages/junior/src/chat/agent/index.ts Resolved
Recounting tool calls from live history undercounts after compaction or
handoff rewrites the transcript. Store a durable cumulative total on the
turn cursor and charge against it before each tool admission.
Put admit/check/charge on resume state, drop the unused message recount
helper, and keep checkpoint writes on one shared base path.

Co-Authored-By: David Cramer <[email protected]>
Hard stops already had the right copy on resume, but first-turn mention
and subscribed-message catch paths always posted the generic internal
error. Share one reply picker and pass the failure cause through.

Co-Authored-By: David Cramer <[email protected]>
Import the generic failure reply directly, read the tool-call limit from
bot config inside admitToolCall, and keep cause matching to one wrap.

Co-Authored-By: David Cramer <[email protected]>
@dcramer
dcramer merged commit b294776 into main Sep 1, 2026
39 checks passed
@dcramer
dcramer deleted the fix/turn-tool-call-execution-limit branch September 1, 2026 18:32
dcramer added a commit that referenced this pull request Sep 7, 2026
## Summary
`MAX_TOOL_CALLS_PER_TURN` (added in #1752, shipped 2026-09-01) is a
single global cap that fires for both runaway automation and legitimate
long-form human turns. This turn hit it:
[JUNIOR-96](https://sentry.sentry.io/issues/7709966903/),
`event_id=dbb4dd6a38b64357b739f12e5cdd1499`.

## Evidence
- `JUNIOR-96` fired 4 times in the 7 days since the cap shipped, all on
human-initiated turns (`app.actor.type:user`), none on
automated/resource-event turns — the case #1752 targeted.
- ~241 sampled human-run traces in that window (~1,129 total
invoke_agent traces incl. sub-agents), so this is a low but real tax on
legitimate work.
- 30d `gen_ai.execute_tool` span counts per trace show p90 ≈ 192, p95 ≈
192, p99 ≈ 256 — 250 sits just under the p99 tail instead of at the
p50-adjacent 150.

## Change
Raise `MAX_TOOL_CALLS_PER_TURN` from 150 to 250 (config + tests only).
Left the mechanism (durable `cumulativeToolCallCount`, fail-closed
behavior) untouched from #1752.

## Residual risk
Same global cap for automated and human turns — doesn't distinguish
runaway CI-watch loops from long-form human work. A follow-up could
split limits by actor if this keeps firing.

<!-- junior-request-attribution:start -->
Requested by **David Cramer**.
<!-- junior-request-attribution:end -->

<!-- junior-session-footer:start -->
<!-- junior-conversation-id:slack%3AC0B595QDZLL%3A1788803900.539279 -->

--

[View Junior
Session](https://junior-prod.sentry.dev/conversations/slack%3AC0B595QDZLL%3A1788803900.539279)
[[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AC0B595QDZLL%3A1788803900.539279/?project=4510944073809921)

<!-- junior-session-footer:end -->

Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
Co-authored-by: David Cramer <[email protected]>
dcramer added a commit that referenced this pull request Oct 15, 2026
Child agents doing real work keep hitting the 250 tool-call cap from
#1752. The turn fails, the parent sees "model failed", and the child's
work is lost. The cap was meant to stop runaway loops, and what those
loops really cost was model spend.

- **Spend limit:** each turn can spend `maxTurnCostUsd` of model cost,
$100 by default, across all its execution slices. Retries that Junior
throws away count too. The tool-call cap goes from 250 to 1,000 and only
matters for models without cost data.
- **Wrap up instead of failing:** the first model step past a limit has
its tool calls blocked with the same message as a tool that
`disableTools` (#2148) disabled. The tool list stays the same, so the
provider cache stays valid. The model replies with what it finished,
what is left, and how to continue, and a child agent sends that reply to
its parent as a normal result. Any later tool call in the turn fails it.
The turn checkpoint saves the wrap-up, so a later slice does not wrap up
again.
- **Child limit failures are final:** a non-final attempt used to
rethrow the limit error. The retry then marked the child's Turn as "lost
its worker before it could pause", so the parent never saw the limit.

The $100 default comes from Sentry span cost estimates: one child agent
that made 250 tool calls cost about $50.

Not in this PR:
- One budget shared by the root conversation and its child agents. Each
child agent gets its own budget.
- The root and scheduler path in `task-execution/conversation-turn.ts`,
which still retries limit failures.

The new subagent eval uses a 3-call limit to stand in for a spent
budget.

Context: JUNIOR-96, event `49c00ccc6e12485e9f4b18a97c3010d6`.

<!-- junior-request-attribution:start -->
via **David Cramer**.
<!-- junior-request-attribution:end -->

<!-- junior-session-footer:start -->
<!-- junior-conversation-id:slack%3AC0B595QDZLL%3A1792078672.880799 -->

--

[View Junior
Session](https://junior-prod.sentry.dev/conversations/slack%3AC0B595QDZLL%3A1792078672.880799)
[[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AC0B595QDZLL%3A1792078672.880799/?project=4510944073809921)

<!-- junior-session-footer:end -->

---------

Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com>
Co-authored-by: David Cramer <[email protected]>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>

This branch was successfully deployed

1 active deployment
Preview – junior-docs — e0e6f7de Deployed Sep 1, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk: high PR risk score: high

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant