Skip to content

[ENG-21265] fix(engine): retry a mid-stream cut-off once in smaller steps + opt-in spawn failure backstop - #298

Merged
william-antoline-boon merged 6 commits into
boonfrom
fix/eng-21265-stream-cutoff-retry
Oct 19, 2026
Merged

william-antoline-boon merged 6 commits into
boonfrom
fix/eng-21265-stream-cutoff-retry

Conversation

@william-antoline-boon

@william-antoline-boon william-antoline-boon commented Oct 19, 2026 •

Copy link
Copy Markdown
Collaborator

ENG-21265: one giant model call shouldn't sink the whole job

Targets boon, the branch production runs. This supersedes #296, which targeted the stale main mirror.

The bug

Egan's Pass 3 builds an Excel workbook through a single tool call. That makes one generation run for 8–15 minutes, and Bedrock drops streams that long. When a drop happened after tool use, run.ts treated it as not safe to replay and failed the run. Model fallback ran next, then the parent re-spawned the sub-agent. Every retry re-sent the same giant call, so it failed the same way each time.

The result was about 60 minutes, about 714k tokens, and then an error. Any skill that builds a large artifact in one call can hit this.

The fix (engine-level: covers every skill, no skill edits)

  1. Retry a cut-off generation once, in smaller steps (run/stream-cutoff-retry.ts, wired into run.ts).
    • What counts as cut off: the stream ended mid-generation. That covers SDK stream ended before message_stop, Bedrock messageStop, Anthropic/Bedrock stream ended with an unclosed content block, proxy stream ended before terminal event, gateway upstream error during stream, and completed stream with an incomplete tool call.

    • The retry: one retry on the same model, inside the run. Its prompt tells the model to redo that step as several smaller tool calls, or to put a long reply into a file.

    • What's kept: completed tool work stays. The original user message isn't sent again.

    • Why it redoes the step: a half-written tool call can't be resumed, and the transport strips errored turns before they reach the provider. So the retry has to redo the step, smaller.

    • When it's skipped:

      • the run was aborted or timed out, or a prompt error occurred;
      • the failure is rate limit, overload, auth, billing, format, or edge-blocked;
      • the dropped attempt already left delivery, media, or async evidence (hasAttemptTerminalState).

      In those cases the existing handling applies.

    • Cap: one retry per run, per the ticket's acceptance criteria ("max 1 retry before requiring user confirmation"). It shows up in the trace as stream_cutoff_retry.

  2. Spawn backstop (subagent-consecutive-failures.ts, subagent-spawn-backstop.ts). Opt-in via agents.defaults.subagents.maxConsecutiveFailures; it's off when unset or 0.
    • What it does: after N failed child runs in a row (error, timeout, or unknown) for one requester session, the next sessions_spawn is refused. The refusal message tells the agent to report what was attempted and ask the user before trying again.
    • In-flight runs are skipped: they neither extend nor break the streak.
    • Scope: sub-agent spawns only (runtime: "subagent"). ACP runs aren't recorded in the sub-agent registry.
    • What restarts the count:
      • a successful child run;
      • a new user turn, meaning unmarked provenance or external_user.
    • What keeps counting:
      • completion wakes (inter_session);
      • internal handoffs (internal_system).
    • Plumbing: provenance and turn id are passed attempt.ts → agent-tools → openclaw-tools → sessions_spawn → spawn context.
    • Bug fixed while porting: runs are looked up under ownership.completionRequesterSessionKey, the key they're actually registered under. fix(engine): retry a cut-off model generation in smaller steps instead of restarting the job (ENG-21265) #296 queried the raw agentSessionKey, which misses runs whenever a completion owner differs from the caller. A test now pins this.

Proof

  • Full-loop reproduction on boon: run.stream-cutoff-retry.test.ts drives the real runEmbeddedAgent loop.
    • It failed first: one attempt, then the run ended. That's Egan's failure on production code.
    • With the fix: a cut-off followed by a completion takes 2 attempts on the same provider and model. Attempt 2 carries the smaller-steps instruction, with no fallback and no error.
    • Ceiling: six cut-offs in a row still stop after 2 attempts.
  • Unit tests: stream-cutoff-retry.test.ts has 44 tests. All cut-off variants retry. Rate-limit, overload, auth, billing, format, and edge-blocked failures don't. Abort, timeout, and terminal evidence don't. Only one retry happens.
  • Backstop tests:
    • 28 unit tests.
    • 14 integration tests against the real spawnSubagentDirect. They failed first, then passed. They cover:
      • a completion wake being blocked;
      • user turns resetting the count;
      • the same turn continuing to count;
      • the completion-owner key.
  • Checks run: tsgo:core, tsgo:test, oxlint, oxfmt, and config:docs:check pass. The embedded-agent-runner and subagent suites pass.

Known limits

  • The fix relies on the model following the "split into smaller tool calls" instruction. It will be verified by canary on Egan's host, not by unit tests.
  • No hard per-call output cap yet. That's a follow-up.

Rollout

  • The smaller-steps retry is on. It only changes a path that fails today.
  • The backstop is opt-in. Canary maxConsecutiveFailures: 3 on Egan's host, then roll out to the fleet.

🤖 Generated with Claude Code

william-antoline-boon and others added 2 commits October 19, 2026 11:17
…teps (ENG-21265)

A model generation cut off mid-stream (SDK "stream ended before message_stop",
Bedrock "messageStop", gateway "upstream error during stream", or a stream that
closed mid tool call) went to model fallback and, when every model failed, to a
sub-agent re-spawn; each restart re-sent the same oversized call, which kept
being dropped (Egan thread 15003: ~60 min, ~714k tokens).

Retry once on the same model, from the existing transcript, with an instruction
to redo that step split into smaller tool calls. Skipped for rate-limit /
overload / auth / billing / edge-blocked failures, for aborted or timed-out
runs, and when the attempt left delivery/media/async evidence. After the one
retry the existing failure handling applies.

Full-loop test: cut off, then complete => 2 attempts, same model, no fallback;
without the retry the run ends after 1 attempt.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…wns (ENG-21265)

Adds agents.defaults.subagents.maxConsecutiveFailures (unset/0 = off).
After N failed child runs in a row for one requester session, the next
sessions_spawn is refused with guidance to report and ask the user. A new
user turn (unmarked or external_user provenance) or a successful child
restarts the count; completion wakes and internal handoffs keep counting.

Runs are looked up under the completion-owner key they register under.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@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 21 files

Heads up: you’re close to your included review allowance. Set a flex budget so reviews don’t pause.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread src/agents/tools/sessions-spawn-tool.ts Resolved
Comment thread src/agents/subagent-spawn-backstop.ts Resolved
…stop

- Match the unclosed-content-block (Anthropic/Bedrock) and proxy
  terminal-event cut-offs, which the transports actually emit.
- In-flight child runs no longer break the failure streak; the refusal
  lists only the failed attempts.
- Ceiling test asserts the exhausted retry surfaces as an incomplete-turn
  error; terminal-evidence cases cover client tool calls, delivery, media.
- Docs: the cap applies to sub-agent spawns.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@boon-hermes-bot boon-hermes-bot 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.

Approved (head 4a1bd4a)

Engine-level fix for ENG-21265: a mid-stream cut-off gets one same-model retry in smaller steps, and the sub-agent spawn backstop is opt-in and off by default.

Verified

  • Cut-off patterns match what the transports actually emit: anthropic-transport-stream.ts:1600/1621, amazon-bedrock/stream.runtime.ts:290/307, runtime/proxy.ts:394. They are also consistent with failover-matches.ts:168-172.
  • The retry sits after the silent-error retry and before fallback and profile rotation. It reuses the existing nextAttemptPromptOverride and suppressNextUserMessagePersistence mechanism (run.ts ~1731/2030), so the original user message is not re-sent. Capped at 1 per run (MAX_STREAM_CUTOFF_RETRIES).
  • Guards are correct: abort, timeout, idle timeout, promptError, auth, rate-limit and billing are skipped. RETRYABLE_REASONS is an allowlist, so wrapped rate_limit/overloaded/edge_blocked/format keep their own handling. hasAttemptTerminalState excludes delivery, media, yield and client tool calls.
  • Backstop is lazy-gated on maxConsecutiveFailures (unset or 0 returns null before any lookup), runs before side effects, and reads the registry under completionRequesterSessionKey. In-flight runs are skipped (neither extend nor break the streak). Reset happens once per user turn, and inter_session and internal_system keep counting.
  • Config surface: zod, types, docs and generated baselines are aligned. Rolling-deploy safe, because it adds an optional key only.
  • Local run on this SHA: run.stream-cutoff-retry, stream-cutoff-retry, subagent-consecutive-failures, subagent-spawn.consecutive-failures = 53 tests, all pass.
  • CI: all substantive checks green (checks-node-*, dispatch). Only skipped/cancelled-superseded jobs otherwise. cubic: all findings addressed.

Non-blocking notes

  • ACP runtime spawns (runtime: "acp") bypass the backstop. This is documented as sub-agent only; worth a follow-up if ACP loops show up.
  • The streak-reset map is in-process, so a gateway restart re-baselines it on the next user turn. Acceptable for a backstop.
  • Effectiveness depends on the model obeying the "smaller calls" instruction. Canary on Egan's host is the real proof. Watch for [stream-cutoff-retry] warn logs and stream_cutoff_retry in the trace, and whether the retry succeeds or just burns one extra attempt.

@boon-hermes-bot boon-hermes-bot 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.

Code Review: APPROVE

Verdict: APPROVE (siap-rilis)

Summary & Technical Verification

  • Mid-Stream Cut-Off Retry (ENG-21265): Adds single-attempt retry on the same model for generations terminated prematurely during active streaming (e.g. Bedrock dropping 8-15 minute single tool calls). Prompts the model with explicit instructions to break large payloads into smaller tool calls or disk artifacts.
  • Failure Classification Safety: Correctly gates retries so non-retryable failures (auth, billing, rate-limits, timeouts, aborts, or turns with committed terminal side-effects) bypass the retry and preserve existing fallback mechanisms.
  • Opt-In Subagent Spawn Backstop: Introduces maxConsecutiveFailures configuration to halt runaway spawn loops after consecutive failures under the same completion requester session, ignoring in-flight runs and resetting upon fresh user turns.
  • Test Coverage & CI: 44 unit tests in stream-cutoff-retry.test.ts, full embedded agent runner loop tests in run.stream-cutoff-retry.test.ts, plus 42 unit and integration tests across subagent failure backstops. All 155 CI checks passed cleanly.

…ailed spawns (ENG-21265)

Found by gateway e2e:
- Model fallback re-enters the runner once per candidate with the same
  runId, so a per-call counter gave every fallback model its own
  smaller-steps retry. Key the budget by runId: one retry per user turn.
- The backstop refusal listed every attempt as "(unlabeled)" because
  sessions_spawn stores the agent-given name as `label`, not `taskName`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@william-antoline-boon

Copy link
Copy Markdown
Collaborator Author

ENG-21265 e2e test report

Result: with the fix (8b5f357), all 9 scenarios pass. On unchanged boon (95003120c3d), Egan's failure reproduces exactly: the sub-agent dies with All models failed (2): … stream ended before message_stop and no work is saved.

How it was tested (end-to-end, not unit tests)

  • Real code under test: the gateway (startGatewayServer), its HTTP API (POST /v1/responses), the Anthropic stream transport, the agent run loop, model fallback, real write tool calls into a temp workspace, real sessions_spawn sub-agents, and real completion wakes.
  • Only the model is fake: a local Anthropic Messages API server streaming real SSE. It can complete, cut a stream off mid tool call (no message_stop), send message_stop with the tool block left open, or return HTTP 429/500.
  • Model setup: primary anthropic/claude-opus-4-8, fallback anthropic/claude-sonnet-4-6, the same shape as production.
  • Safety: no real provider, credentials, or production system was touched.
  • Two runs: the same harness ran on the fix branch ("after") and on base boon ("before").

Results

# Scenario Before (boon) After (fix)
S1 Egan replay: tool work, then the giant write call is cut off (no message_stop) ❌ falls back to sonnet, which is cut off too. User gets upstream provider timeout. Workbook never built. ✅ one retry on opus asking for smaller steps. Workbook built in 2 parts. User gets a success reply.
S2 Bedrock/Anthropic variant: message_stop arrives but the tool block was never closed ❌ same failure as S1 ✅ same recovery as S1
S3 Ceiling: every attempt is cut off 3 calls, then error ✅ exactly 1 retry per user turn, including across fallback models. 4 calls, then a clear error. No loop.
S4 Rate limit (HTTP 429) normal fallback ✅ unchanged: no retry, normal fallback
S5 Happy path ✅ ✅ unchanged: 2 calls, no instruction added
S6 Egan's real setup: main agent spawns the Pass-3 sub-agent, whose giant call is cut off ❌ sub-agent fails (FallbackSummaryError: All models failed (2)). Only pass-1 notes on disk. ✅ sub-agent retries once, finishes, and reports status: completed. Parent doesn't re-spawn. Workbook parts on disk.
S7 Backstop on (maxConsecutiveFailures: 2): failing sub-agents, and the parent re-spawns after every failure (the loop that burned the tokens) n/a (setting is new) ✅ 2 spawns accepted, the 3rd is refused with "Stop here — tell the user… ask the user…" and the names of the failed attempts. User says "yes, keep trying" → spawn allowed again.
S8 Backstop off (default, unset): same loop 3 spawns, 6 calls ✅ not blocked, as designed. Each child gets one smaller-steps retry.
S9 Server error (HTTP 500), not a cut-off normal fallback ✅ unchanged: no retry, normal fallback

Request traces (fake-provider view)

S1 after (fix):

#1 opus   → tool write estimate/pass-1-notes.md
#2 opus   → write full-workbook.csv … 8 KB then connection dropped
#3 opus   → tool write estimate/part-1.csv   [smaller-steps instruction]
#4 opus   → tool write estimate/part-2.csv
#5 opus   → "Workbook complete in smaller pieces"

S1 before (boon):

#1 opus   → tool write estimate/pass-1-notes.md
#2 opus   → write full-workbook.csv … dropped
#3 sonnet → write full-workbook.csv … dropped   (same giant call re-sent)
→ user: {"code":"api_error","message":"upstream provider timeout"}

S7 (backstop on):

spawn pass-3-try-1 → child: opus cut off, opus retry cut off, sonnet cut off → failed
spawn pass-3-try-2 → same → failed
spawn pass-3-try-3 → REFUSED: "Sub-agent spawn blocked: 2 attempts in a row failed this session (...). Stop here — tell the user what was attempted and how each ended, then ask the user whether to keep trying..."
agent → "Pass 3 failed twice in a row. Stopping — should I keep trying?"
user  → "yes, keep trying" → spawn accepted → child completes

Bugs the e2e found (fixed in 8b5f357, each with a failing test first)

  1. The retry ran once per fallback model, not once per turn. Model fallback re-enters the runner for each model with the same runId, so sonnet got a second smaller-steps retry, breaking the ticket's "max 1 retry". The budget is now keyed by runId. S3 confirms it: 1 retry total.
  2. The backstop message listed every attempt as (unlabeled). sessions_spawn stores the agent's name for a run in label, but the message read taskName. It now uses taskName → label → task text.

Known trade-off

When every attempt is cut off (S3), the fix spends one extra call: 4 instead of 3. That buys the one retry that recovers S1, S2 and S6. In production the retry is asked to work in small steps, so it should be much shorter than the giant call it replaces.

Other checks

  • tsgo:core, tsgo:test, oxlint, oxfmt and config:docs:check pass.
  • Unit and integration tests for the changed modules pass.
  • The sub-agent, spawn-tool and config suites pass: 161 files, 2,018 tests.

🤖 Generated with Claude Code

@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 6 files (changes from recent commits).

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

View guided diff | Turn on auto-fix | Re-trigger cubic

…nId (ENG-21265)

Cron and CLI runs reuse the session id as runId, so the runId-keyed map
left a spent budget behind and later executions of the same session got
no retry. runWithModelFallback now opens one budget scope per execution
(AsyncLocalStorage, global singleton); every fallback candidate shares
it and each new execution starts fresh. No global map, nothing to evict.

The fallback-chain test also asserts the fallback attempt's model id.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@william-antoline-boon

Copy link
Copy Markdown
Collaborator Author

E2E addendum: 4950301

I reran the full gateway e2e on the final code. All 10 scenarios pass: S1–S9 from the report above, plus a new S10.

  • S10, two turns in the same session, each cut off once: both turns recover, with exactly one retry per turn. The retry budget is now scoped per execution, so a reused runId (cron/CLI) no longer leaves a spent budget behind.
  • S3, every attempt cut off: still exactly 1 retry across opus and its sonnet fallback, 4 calls total, then a clear error.

Other checks on 4950301:

  • tsgo:core and tsgo:test are clean, and oxlint passes.
  • Stream-cutoff, model-fallback, cron isolated-agent, agent-command, auto-reply agent-runner, and runner run.* suites pass: 1,000+ tests.

🤖 Generated with Claude Code

@william-antoline-boon
william-antoline-boon merged commit 052aaf2 into boon Oct 19, 2026
143 checks passed
@william-antoline-boon
william-antoline-boon deleted the fix/eng-21265-stream-cutoff-retry branch October 19, 2026 10:15
convyusboy added a commit that referenced this pull request Oct 26, 2026
* chore(release): bump version 2026.6.35-boon.1 -> 2026.6.35-boon.2

Cuts the fork release covering the 9 PRs merged to boon since v2026.6.35-boon.1:
#298 (ENG-21265) stuck-generation cut-off retry + sub-agent spawn backstop,
#299 workspaceDir threading through outbound channel media adapters,
#304 (ENG-19208) real inbound media path in the system prompt,
#301 (ENG-21585) forced sessions_yield on narrated sub-agent turns,
#305 message-tool source reply observed outside message_tool_only,
#306 (ENG-19103) reasoning-stream callbacks honor message_tool_only,
#303 sub-agent/completion-turn usage attribution,
#302 clears 7 high-severity pnpm-audit-prod advisories,
#300 (ENG-21588) boon-estimation trajectory label detail.

Bump root package.json/npm-shrinkwrap.json, all bundled plugin manifests, and
the version + openclaw peer floor in every extension npm-shrinkwrap.json. Add
the 2026.6.35-boon.2 CHANGELOG.md section. No additional dependency or source
changes beyond what already shipped in #299 and #302.

Co-Authored-By: Claude Sonnet 5 <[email protected]>

* docs(changelog): fold PR #309's advisory fixes into the 2026.6.35-boon.2 entry

---------

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