Skip to content

fix(agents): bound runaway tool-call loops and subagent runs - #230

Merged
insomnius merged 5 commits into
boonfrom
ariefrahman/eng-20206-loop-bound
Sep 18, 2026
Merged

insomnius merged 5 commits into
boonfrom
ariefrahman/eng-20206-loop-bound

Conversation

@insomnius

@insomnius insomnius commented Sep 18, 2026 •

Copy link
Copy Markdown

Summary

Three independent containment gaps let a single agent run repeat one failing tool call 1,146 times over 86 minutes without anything stopping it. Each is small; together they meant nothing bounded the run.

Measured end to end, same stub and prompt, before vs after: 1,231 HTTP turns → 23. Wall clock 155s → 6s.

The three gaps

1. A subagent run had no wall-clock bound at all.

resolveConfiguredSubagentRunTimeoutSeconds read only agents.defaults.subagents.runTimeoutSeconds and fell back to 0. resolveAgentTimeoutMs treats 0 as the explicit no timeout sentinel (MAX_TIMER_TIMEOUT_MS, ≈24.85 days), so the abort timer was armed correctly — just 24 days out.

Any deployment setting agents.defaults.timeoutSeconds and expecting it to bound subagents was wrong. It never applied to them. The fallback is documented as deliberate legacy behaviour (subagent-spawn.ts), which is exactly why it went unnoticed.

Fixed in the shared resolver rather than at the call site, because acp-spawn.ts is a sibling caller with the identical defect — patching only the observed path would have left ACP subagents unbounded. An explicit subagents.runTimeoutSeconds: 0 still means no timeout.

2. A tool call that never executed was invisible to loop detection.

The detector wraps tool.execute. A schema-validation failure means execute never runs, so both detectToolCallLoop and recordToolCall are skipped — the call is recorded nowhere. No detector could ever count it. The same blind spot swallowed unknown-tool-name and tool-resolution failures.

prepareToolCall's immediate outcomes also bypassed finalizeExecutedToolCall, the sole caller of config.afterToolCall, so a never-executed call reached neither hook.

Fixed by routing immediate outcomes through the existing finalizeExecutedToolCall (finalizeImmediateToolCall), plus a new AfterToolCallContext.executionStarted flag. That flag is load-bearing, not cosmetic: without it a consumer cannot distinguish a never-executed outcome from an executed one and would double-record every successful call, corrupting the detector's own history.

Detection is force-enabled on the never-executed path only, following this repo's existing precedent — resolveUnknownToolGuardThreshold keeps the provider unknown-tool guard on regardless of tools.loopDetection.enabled, because an unregistered tool "is an objective dead end". A call that never executed made objectively zero progress by the same argument. Adding a knob that defaults off is precisely what let this through.

3. Blocking a call did not end the run — and this is the one that mattered.

Gaps 1 and 2 alone were measured as a placebo on the cost axis. With the detector firing correctly at its critical threshold and blocking 1,211 calls, the run still spent 1,231 HTTP turns versus 1,231 unfixed. A blocked call is still a model turn. Request bodies grew faster with the fix, because the block message is longer than the validation error it replaced.

So: after a bounded streak of consecutive blocked, never-executed calls, the run now terminates via the existing terminate mechanism.

Test plan

Every behaviour was red first; verbatim failures are in the commits.

1,231 turns / 155s  →  23 turns / 6.0s

23 = the detector's existing criticalThreshold (20) + a streak bound of 3.

The 3 is not the dominant number. Twenty of those 23 turns are the pre-existing threshold and move with tools.loopDetection.criticalThreshold. If 23 turns is still too expensive at large context sizes, that 20 is the lever, not the 3.

A recoverable session is not killed, proven rather than argued. A dedicated E2E scenario emits the invalid call 22 times — 20 validation failures, then 2 blocks — then answers normally on turn 23. The run delivered its answer and was not cut. The streak resets on any progress: a call that actually executed, a non-error outcome, or a different call. You must already be 20 byte-identical never-executed failures deep before the first block exists.

Why the user-facing copy is half this change

Bare terminate: true was measured first and produced ⚠️ 📖 Read failed with a Retry button — blaming the tool for a run the agent ended deliberately, and inviting the user to re-trigger the whole burn. The run now states the reason plainly instead.

Known limits, stated rather than implied

  • shouldTerminateToolBatch requires every call in a batch to set terminate. The observed shape is one call per turn, so it fires. A provider emitting a parallel batch of [invalid, valid] indefinitely would not be bounded — correct semantics, since there is real progress, but a genuine residual hole.
  • A run whose hook context has neither sessionKey nor sessionId never reaches the detector. Pre-existing, untouched.
  • Every other detector (ping-pong, generic-repeat on calls that executed, poll) remains off by default. A loop of calls that execute successfully and return unhelpful results is still unbounded. That is a wider gap than this PR closes.

The trigger for the original incident was upstream: a gateway sealing a mid-stream failure into a schema-valid success carrying a tool call with empty arguments. That is fixed separately. These changes hold regardless — the client should bound itself whether or not any particular server is well behaved, and the two deploy independently.


Summary by cubic

Fixes the containment gaps behind ENG-20206, where a subagent made 1,146 identical failing tool calls over 86 minutes with nothing stopping it. Measured end to end on the incident-shaped stub: 1,231 turns/155s → 23 turns/6s.

Bug Fixes

  • Tool calls rejected before tool.execute (validation failure, unknown tool) now reach afterToolCall with executionStarted: false, so the loop detector counts them.
  • A run terminates after three consecutive blocked calls; any executed or non-error call resets the streak, so a recovering session isn't killed.
  • Subagents now inherit agents.defaults.timeoutSeconds instead of running unbounded when agents.defaults.subagents.runTimeoutSeconds is unset; an explicit runTimeoutSeconds: 0 still means no timeout.
  • Loop detection is force-enabled on never-executed calls regardless of tools.loopDetection.enabled, since a blocked call made zero progress.
  • The termination reason is surfaced to the user, keyed on a structured tool_loop_run_ended code rather than the notice text, so the generic "tool failed" badge doesn't blame the tool.
  • Containment reads the loop's own pre-execution verdict rather than the wrapped after-tool hook's result, so a hook that throws or relabels the error can't silently reopen the loop.

Written for commit f5d2776. Summary will update on new commits.

Review in cubic

Two containment failures found by an incident where a subagent session made
1,146 byte-identical failing tool calls over 86 minutes with nothing stopping
it (the upstream gateway sealed a mid-stream error into a schema-valid
tool_use with empty arguments; that is fixed separately).

1. A tool call rejected BEFORE execution (argument-validation failure,
   unknown tool, resolver error) produced an "immediate" outcome that reached
   neither agent-core tool hook, so the tool-loop detector -- which lives in
   the wrapped tool.execute -- never counted a single one. agent-core now
   reports those through afterToolCall (with a new executionStarted flag), and
   the embedded runner routes never-executed error results into the detector,
   blocking at the existing critical threshold.

2. Subagent runs took their wall-clock bound only from
   agents.defaults.subagents.runTimeoutSeconds. With that key unset the
   resolver returned 0, which resolveAgentTimeoutMs reads as the explicit
   "no timeout" sentinel -- so a fleet setting agents.defaults.timeoutSeconds:
   900 still ran subagents with a ~24.8 day deadline. Subagents now inherit the
   general agent timeout; an explicit 0 still means no timeout.
Blocking a never-executed tool call does not bound the run. An E2E against a
stub that replays the incident shape (a schema-valid tool_use for the
registered `read` tool with empty arguments, which fails argument validation
and never executes) measured 1,231 model turns on the parent commit: the
detector fired correctly at call 21 and then served 1,210 more blocks, every
one of them a full HTTP turn, until the run timeout killed it. Blocking tool
EXECUTION does nothing about the token burn that made the production incident
expensive -- only ending the RUN does.

After three consecutive blocked calls the hook now returns `terminate: true`
on the tool result. agent-core's `shouldTerminateToolBatch` clears
`hasMoreToolCalls`, which drops out of the agent loop entirely -- no further
model turn is requested (already asserted by agent-loop.test.ts "stops after a
tool result only when the finalized result explicitly terminates"). Same E2E:
1,231 -> 23 turns, 155s -> 6s.

Three, not one: the first block is the first time the model is told to stop,
so it keeps two more turns to answer without the tool or call a different one.
Any call that actually executed, or any non-error outcome, resets the streak,
so a session that recovers is never cut -- a companion E2E where the model
answers after two blocks delivers that answer untouched.

The termination is not silent. Ending the run leaves the last assistant turn
with a tool-call stop reason and a tool error, which routes to the terse
"<tool> failed" badge and blames the tool for a run the agent stopped on
purpose. The terminating result carries a fixed `TOOL_LOOP_RUN_ENDED_NOTICE`,
and the reply builder lets that one reason past the raw-detail gate (the text
is authored copy, never leaked tool output), so the user reads why.

No new config key: the not-executed path already forces loop detection on for
the same reason the unknown-tool guard is always on, and `loopDetection.enabled`
defaulting to false is exactly why nothing caught the incident.
…change

Making AfterToolCallContext.executionStarted required (edee679) broke two
existing fixtures that construct the context or a tool result by hand.
Neither was caught locally because `pnpm check:changed` delegates to a
remote testbox that is unavailable here; `pnpm tsgo:test` is the local
equivalent and was red on both commits of this branch.

- agent-loop.test.ts: execTool.execute returned no `details`, which is a
  required field of AgentToolResult. Matches the house style used by the
  sibling fixtures in the same file (`details: {}`).
- message-tool-terminal.test.ts: createAfterToolCallContext omitted the
  new flag. These fixtures all model a tool that ran, so `true` is the
  correct value, not a placeholder — noted in a comment, since the
  never-executed path has its own suite.

`pnpm tsgo:test` now clean.
@insomnius
insomnius requested a review from a team September 18, 2026 02:19
@claude

claude Bot commented Sep 18, 2026 •

Copy link
Copy Markdown

Claude encountered an error —— View job


I'll analyze this and get back to you.

@cubic-dev-ai cubic-dev-ai 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.

All reported issues were addressed across 15 files

Tip: instead of fixing issues one by one fix them all with cubic

Re-trigger cubic

Comment thread src/agents/tool-loop-detection.ts Resolved
Comment thread packages/agent-core/src/types.ts Resolved
… chain

Address review feedback on the not-executed tool-loop containment path.

The substantive fix: installNotExecutedToolLoopHook wrapped an inner
afterToolCall hook (extension code) and derived both its control flow and its
error verdict from that hook's result. Two ways that silently reopened the
unbounded loop this change exists to close:

- if the inner hook threw, the await propagated out before the detector was
  ever consulted, so the streak never advanced and no call was ever blocked;
- if the inner hook relabelled a pre-execution failure as isError: false, the
  hook treated it as progress and reset the streak.

Every kind:"immediate" outcome in the loop sets isError: true, so the decision
now reads context (the loop's own pre-execution verdict) rather than the
hook's rewrite, and the observation runs even when the hook threw. A throw is
re-raised unchanged unless the call is blocked, where containment wins.

Also replace the substring match on the run-ended notice with a structured
marker: the terminating blocked result now carries details.code, which existing
tool-result readers already lift into ToolErrorSummary.errorCode, so the
raw-detail gate no longer opens for a tool error that merely quotes the notice.

Remaining items are contract and coverage:
- document that AfterToolCallContext.args is only schema-validated when
  executionStarted is true;
- subagents no longer fall back to "no timeout" when runTimeoutSeconds is
  unset - they inherit agents.defaults.timeoutSeconds. Correct the docs and
  the stale spawn comment that still promised no timeout;
- the not-executed suite pre-enabled loop detection, so it could not catch a
  regression in the force-enable that makes containment unconditional;
- assert the executionStarted contract in the agent-loop tests;
- rename a test whose name asserted the opposite of its body.

@cubic-dev-ai cubic-dev-ai 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.

All reported issues were addressed across 13 files (changes from recent commits).

Reply with feedback, questions, or to request a fix.

Fix all with cubic | Re-trigger cubic

Comment thread src/agents/tool-loop-detection.ts Resolved
…ed-code move

The TOOL_LOOP_RUN_ENDED_NOTICE doc still described the notice text as the
marker the reply builder keys on. Gating the raw-detail path on
details.code / ToolErrorSummary.errorCode made that false and left it
contradicting the TOOL_LOOP_RUN_ENDED_CODE comment two lines below. The
notice is user-facing copy appended to the blocked reason; the code is the
key.

Also add the missing relative pronoun in a test title.

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

Reviewed current head f5d2776 against boon. No blocking correctness, security, or scope issues found.\n\nVerified the pre-execution path now reaches afterToolCall with executionStarted=false, the detector uses the loop's own verdict even when an extension hook throws or rewrites it, three consecutive blocked calls terminate the run, and subagent timeout inheritance plus the explicit 0 no-timeout sentinel are covered by code, tests, and docs. The structured run-ended error code also avoids matching untrusted error text.\n\nCurrent-head checks show 120 success, 23 skipped, 1 neutral, and 4 cancelled superseded dispatch runs, with no failures; check-test-types, check-lint, core shards, security checks, and Cubic all pass. Local diff --check and syntax checks for 17 changed TypeScript files pass. Known limits in the PR are accepted: containment is for identical-argument loops, other detectors remain opt-in, and mixed parallel batches are not terminated unless every call is marked terminate.\n\nApproved.

@insomnius
insomnius merged commit 99fedc2 into boon Sep 18, 2026
145 of 149 checks passed
@insomnius
insomnius deleted the ariefrahman/eng-20206-loop-bound branch September 18, 2026 07:24
insomnius added a commit that referenced this pull request Sep 18, 2026
…231)

* chore(release): bump version 2026.6.11-boon.44 -> 2026.6.11-boon.45

Version-bump-only train carrying #230 (ENG-20206): bounds runaway
tool-call loops and gives sub-agent runs a real wall-clock bound.

- root package.json -> 2026.6.11-boon.45
- plugin package.json files synced via scripts/sync-plugin-versions.ts
- changed npm-shrinkwrap.json files regenerated via
  scripts/generate-npm-shrinkwrap.mjs --changed
- CHANGELOG.md section for boon.45

No plugin source changed between boon.44 and boon.45; a gateway roll
delivers the whole release.

* chore(release): CHANGELOG — varying-arg loops are bounded only under a finite run timeout

Review caught that "bounded by the run timeout alone" is false when an
explicit runTimeoutSeconds: 0 is configured — there is no run timeout
then, so that case is unbounded. State the condition rather than imply
a bound that a legal config removes.
convyusboy added a commit that referenced this pull request Oct 12, 2026
…35 sync

CI on PR #281 caught three real bugs that review alone missed, plus one new
production CVE batch:

- pdf-tool.ts: upstream added early pages-validation (parse and throw before
  loading any PDF) as a new behavior in 6.35. My earlier conflict resolution
  treated the resulting duplicate `pageNumbers` declaration as dead code and
  deleted the early one, silently reverting to late (post-load) validation.
  Moved the single declaration back to its early position; the getExtractions
  closure now captures it instead of redeclaring it.
- agent-loop.ts: upstream's `executed.executionStarted && config.afterToolCall`
  guard assumes never-executed outcomes never reach this function (upstream's
  own call graph bypasses it for the immediate case). Boon's call graph does
  not bypass it — finalizeImmediateToolCall always routes through here, and
  the loop-detector safety fix from #230 depends on afterToolCall seeing
  never-executed calls with `executionStarted: false`. Adopting upstream's
  guard unconditionally broke that: it skipped afterToolCall for exactly the
  calls the loop detector needs to see. Reverted to boon's original
  unconditional `if (config.afterToolCall)`.
- ci-workflow-guards.test.ts: a new upstream test iterated testbox CI workflow
  paths the fork has never carried (ci-check-testbox.yml,
  ci-build-artifacts-testbox.yml, documented as removed since fork setup).
  Narrowed it to the one workflow the fork still has, matching the existing
  convention elsewhere in this file.

security-fast found 6 new high/critical advisories in the merged dependency
tree (GHSA-v5rq-49vh-5v5c argv-parser unsafe-editor detection,
GHSA-x6jw-m9v5-85vh/GHSA-g4wm-2vf7-vfgr/GHSA-858h-whjf-mvg5 simple-git command
execution, GHSA-jqcg-44mw-7w3h proxy-addr IP spoofing, GHSA-68fv-2mgg-jv7q
source-map-js DoS). Pinned all four to their fixed versions in
pnpm-workspace.yaml. Regenerating the lockfile surfaced a known recurring npm/
pnpm resolver mismatch under @sentry/node (npm picks @opentelemetry/resources
and @opentelemetry/sdk-trace-base 2.12.0, pnpm locks 2.11.0); added the same
class of temporary npm-only nested override used for this before (see
2026.6.34-boon.4's changelog entry) to package.json.

Also regenerated the plugin-sdk-surface budgets and API baseline
(docs/.generated/plugin-sdk-api-baseline.*) against the actual merged tree,
replacing the placeholder values called out as a follow-up in the PR
description.

Validation: pnpm-audit-prod clean; tsgo:core clean; the three directly
affected test files (pdf-tool.test.ts, agent-loop.test.ts,
ci-workflow-guards.test.ts, plugin-sdk-surface-report.test.ts) all pass;
deps:shrinkwrap:generate --check clean.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants