Skip to content

fix(engine): retry a cut-off model generation in smaller steps instead of restarting the job (ENG-21265) - #296

Closed
william-antoline-boon wants to merge 8 commits into
mainfrom
feat/eng-21265-subagent-attempt-resilience
Closed

william-antoline-boon wants to merge 8 commits into
mainfrom
feat/eng-21265-subagent-attempt-resilience

Conversation

@william-antoline-boon

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

Copy link
Copy Markdown
Collaborator

ENG-21265 — stop one giant model call from sinking the whole job

The bug

Egan's Pass 3 builds an Excel workbook, which the model does through a tool call. That made
one monolithic 8–15-minute generation. AWS Bedrock drops streams that long. When it did:

  • handleEmbeddedAssistantFailure saw a drop after tool use as "not replay-safe" and returned
    proceed, so the run failed;
  • the outer model fallback and then the parent sub-agent re-spawn started over — and each retry
    re-sent the same giant call, which kept losing the same coin flip.

Result: ~60 min, ~714k tokens, then an error. Any skill that builds a big artifact in one call
can hit this.

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

  1. Retry a cut-off generation in smaller steps (assistant-failure.ts). A 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) is retried on the
    same model, inside the run
    , up to 3 times, with an instruction to redo that step split
    into smaller tool calls
    (or put a long reply into a file). Completed tool work is kept; the
    original prompt is not replayed. A half-written tool call can't be continued, and the failed
    partial isn't replayed to providers, so the retry deliberately redoes the step — smaller.
    Skipped when the dropped attempt left delivery / media / async evidence a fresh attempt
    wouldn't carry over (hasAttemptTerminalState); today's handling applies then.
  2. Backstop fixes (subagent-spawn.ts, consecutive-failure-cap.ts, opt-in via
    agents.defaults.subagents.maxConsecutiveFailures):
    • the check now runs inside try, so a block releases its admission/swarm reservation
      (previously each block leaked a slot and could wedge a session's spawning);
    • the streak restarts on a user turn (unmarked or external_user); completion wakes
      (inter_session) and handoffs (internal_system) keep counting — provenance plumbed
      agent-tools → sessions_spawn → spawn context;
    • counts in creation order; ignores collector/swarm children.
  3. Cleanup: removed the unused prior-attempts note builder; length-continuation branch stays
    off (DEFAULT_LENGTH_CONTINUATION_LIMIT = 0).

Proof

  • Thread-15003 replay through the real runEmbeddedAgent loop: cut off → cut off →
    completes ⇒ 3 attempts, same model, split instruction on attempts 2–3, no model fallback,
    no error. Mutation check: with retries disabled the run stops after 1 attempt (old
    behavior). Ceiling: stops at 1 + 3.
  • Drop-handler unit tests: all cut-off variants retry; rate-limit / overload / auth don't; a
    dropped attempt that already delivered a reply doesn't.
  • Backstop integration against the real spawnSubagentDirect: reproduced the leaked slot
    (next spawn forbidden) and the over-block (user request blocked); both fixed.
  • tsgo:core clean; embedded-agent-runner, subagents, failover, tools suites green.

Known limits

  • Relies on the model following "split into smaller tool calls" — models generally do, but it's
    verified by canary, not by unit tests.
  • No hard per-call output cap in this PR: the length-continuation path doesn't yet stitch a
    capped text reply back together for delivery, so enabling a cap now would regress long text
    replies. Follow-up.

Rollout

The smaller-steps retry is on (it only changes a path that currently fails). Backstop stays
opt-in; canary maxConsecutiveFailures=3 on Egan's host, then fleet.

🤖 Generated with Claude Code

…ct (ENG-21265)

Wire the session-scoped cap into the spawn orchestrator before any side effect,
reusing the existing { status: error } refusal. The block message instructs the
agent to check in with the user instead of re-spawning. Keyed on requesterSessionKey
(persists across completion-wake turns), reusing listSubagentRunsForRequester.
Extract shared formatRunEntries (DRY with the resume note); fix plural grammar.
tsgo:core clean; spawn suite 588/588; unit suites 20/20.
@william-antoline-boon william-antoline-boon changed the title feat(subagents): attempt-resilience primitives — prior-attempts note + consecutive-failure cap (ENG-21265) feat(subagents): attempt-resilience — enforce consecutive-failure cap + resume-note builder (ENG-21265) Oct 15, 2026
william-antoline-boon and others added 4 commits October 16, 2026 15:14
Add a length-continuation branch in resolveEmbeddedRunTerminal: when a turn stops at
the output-length limit with partial prose, commit the partial to the transcript and
retry with a continuation prompt so heavy work finishes in short, drop-resistant turns.
Gated by DEFAULT_LENGTH_CONTINUATION_LIMIT (0 = OFF; zero behavior change). Prose-only
(skips tool/yield/structured). Ceiling-bounded. Real tests assert the partial is
committed (not a tautology). commitPartialAssistantTurn is a guarded placeholder while
off; real transcript-append + enablement gated on production data (see code comment).

tsgo:core clean; embedded-agent-runner/run suite 2855/2855.
…ad of restarting (ENG-21265)

A mid-stream drop ("stream ended before message_stop" / gateway "upstream error
during stream") after the agent had run tools was not replay-safe, so the failure
handler returned "proceed": the run failed and the outer model fallback / parent
re-spawn restarted the whole generation from zero. Egan thread 15003 burned ~60 min
and ~714k tokens this way.

Resume the drop on the same model with an internal continuation prompt (max 3 per
run, then today's handling). It continues from the transcript instead of replaying
the prompt, so it is safe after tool activity: the dropped turn never completed and
none of its tool calls ran. The partial output is already persisted by the session
guard and replayed.

On replay, merge an interrupted stream partial into the turn that continued it
(continuation thinking blocks stay first) so providers never see consecutive
assistant roles. Drop the unneeded commitPartialAssistantTurn placeholder from the
(still off) length-continuation branch.

Thread-15003 replay test drives the full run loop: drop, drop, complete => 3
attempts, same model, no fallback, no error; with resume disabled the run stops
after 1 attempt. tsgo:core clean; embedded-agent-runner 5579/5579; failover 1455/1455.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…d resets on new user turns (ENG-21265)

Review found two bugs in the opt-in consecutive-failure cap, both now reproduced
against the real spawnSubagentDirect and fixed:

- Leak: the cap returned before the try block, skipping the finally that releases
  the child-admission / swarm reservations, so each block leaked a slot and could
  wedge a session's spawning. The check now runs inside try.
- Over-block: old failures lingered across user turns, blocking unrelated new
  requests. A spawn from a new user message (InputProvenance.kind ===
  "external_user", now plumbed agent-tools -> sessions_spawn -> spawn context)
  restarts the streak; completion wakes keep counting.

Also count in creation order and ignore collector/swarm children. Move
formatRunEntries into the cap module (prior-attempts-note builder removed).

subagents 2435/2435; tools 214/214; tsgo:core clean.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…sets on unmarked user turns (ENG-21265)

Fresh review of the previous commits found the resume did not work as designed:
providers never see the errored partial (transport-message-transform drops
stopReason=error turns), and Egan's Pass 3 generation is a tool call (it builds
an .xlsx), which cannot be continued anyway. Root cause is a single monolithic
8-15 min call that AWS drops, re-sent unchanged on every retry.

- Retry a generation cut off mid-stream on the same model with an instruction to
  redo that step split into smaller tool calls (or put a long reply into a file),
  instead of "continue where you stopped". Matches the SDK message_stop, Bedrock
  messageStop, gateway upstream-stream and incomplete-tool-call errors; not rate
  limit / overload / auth.
- Skip the retry when the dropped attempt left delivery / media / async evidence
  that a fresh attempt would not carry over (hasAttemptTerminalState).
- Remove the replay-history partial merge (only served the partial-continuation idea).
- Backstop: treat an unmarked turn as a user turn (ordinary channel/chat messages
  carry no provenance); inter_session wakes and internal_system handoffs keep counting.

Replay through the full run loop: cut off, cut off, complete => 3 attempts, same
model, split instruction, no fallback; with retries disabled it stops after 1.
tsgo:core clean; embedded-agent-runner 5585/5585; subagents 2439/2439;
failover 1455/1455; tools 214/214.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@william-antoline-boon william-antoline-boon changed the title feat(subagents): attempt-resilience — enforce consecutive-failure cap + resume-note builder (ENG-21265) fix(engine): retry a cut-off model generation in smaller steps instead of restarting the job (ENG-21265) Oct 16, 2026
@william-antoline-boon
william-antoline-boon marked this pull request as ready for review October 16, 2026 12:43

@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 22 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/config/zod-schema.agent-defaults.ts Resolved
Comment thread src/config/types.agent-defaults.ts Resolved
Review (cubic):
- Cap autonomous cut-off retries at 1 per run (ticket AC: default max 1 retry before
  user confirmation); the failure handling / sub-agent backstop takes over after.
- Do not treat a gateway "upstream error during stream" that wraps a rate limit,
  overload, auth, or billing failure as a cut-off: retry only transient reasons.
- Backstop: restart the streak once per requester turn, so several spawns within one
  user turn keep counting each other's failures.
- Document agents.defaults.subagents.maxConsecutiveFailures (subagents + config docs).
- Remove the unused, off-by-default length-continuation path (not part of this fix;
  resolves the side-effect-guard concern).
- Drop ticket IDs from test names and source comments; tighten the most-recent test;
  narrow the registry-read mock to the two reads the spawn graph uses.

CI:
- knip: stop exporting module-internal helpers (count retries from the run trace,
  test the cap through its public function).
- max-lines: move the backstop into subagent-spawn-backstop.ts; pass the drop handler
  the session prompt state instead of a precomputed suspension id (run-loop +-1 line).

tsgo:core and tsgo:test clean; deadcode clean; embedded-agent-runner 5583/5583;
subagents 2438/2438; failover 1455/1455; tools+config 3633/3633.

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.

1 issue found across 17 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="docs/gateway/config-agents.md">

<violation number="1" location="docs/gateway/config-agents.md:1049">
P3: This description makes the cap sound as though every failed child run contributes to the streak, but the implementation excludes completion wakes and collector/swarm children and only counts `error`, `timeout`, and `unknown` terminal outcomes. Document those exclusions here too so operators do not expect parallel work or completion wakes to trigger the backstop.</violation>
</file>

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

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

- `subagents.requireAgentId`: when true, block `sessions_spawn` calls that omit `agentId` (forces explicit profile selection; default: false).
- `subagents.maxConcurrent`: max concurrent child-agent runs across subagent execution. Default: `8`.
- `subagents.maxChildrenPerAgent`: max active children a single agent session can spawn. Default: `5`.
- `subagents.maxConsecutiveFailures`: after this many consecutive failed child runs for one requester session, refuse the next `sessions_spawn` and have the agent ask the user before continuing. A successful child or a new user message restarts the count. Default: unset (`0` also disables it).

@cubic-dev-ai cubic-dev-ai Bot Oct 16, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: This description makes the cap sound as though every failed child run contributes to the streak, but the implementation excludes completion wakes and collector/swarm children and only counts error, timeout, and unknown terminal outcomes. Document those exclusions here too so operators do not expect parallel work or completion wakes to trigger the backstop.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At docs/gateway/config-agents.md, line 1049:

<comment>This description makes the cap sound as though every failed child run contributes to the streak, but the implementation excludes completion wakes and collector/swarm children and only counts `error`, `timeout`, and `unknown` terminal outcomes. Document those exclusions here too so operators do not expect parallel work or completion wakes to trigger the backstop.</comment>

<file context>
@@ -1046,6 +1046,7 @@ for provider examples and precedence.
 - `subagents.requireAgentId`: when true, block `sessions_spawn` calls that omit `agentId` (forces explicit profile selection; default: false).
 - `subagents.maxConcurrent`: max concurrent child-agent runs across subagent execution. Default: `8`.
 - `subagents.maxChildrenPerAgent`: max active children a single agent session can spawn. Default: `5`.
+- `subagents.maxConsecutiveFailures`: after this many consecutive failed child runs for one requester session, refuse the next `sessions_spawn` and have the agent ask the user before continuing. A successful child or a new user message restarts the count. Default: unset (`0` also disables it).
 - `subagents.maxSpawnDepth`: max nesting depth for sub-agent spawning (`1`-`5`). Default: `1` (no nesting).
 - `subagents.archiveAfterMinutes`: age before completed subagent state is archived. Default: `60`.
</file context>
Suggested change
- `subagents.maxConsecutiveFailures`: after this many consecutive failed child runs for one requester session, refuse the next `sessions_spawn` and have the agent ask the user before continuing. A successful child or a new user message restarts the count. Default: unset (`0` also disables it).
- `subagents.maxConsecutiveFailures`: after this many consecutive failed (`error`, `timeout`, or `unknown`) child runs for one requester session, refuse the next `sessions_spawn` and have the agent ask the user before continuing. A successful child or a new user message restarts the count; completion wakes and collector/swarm children do not count. Default: unset (`0` also disables it).
Fix with cubic

@william-antoline-boon

Copy link
Copy Markdown
Collaborator Author

Superseded by #298. This PR targeted main, a stale upstream mirror; production deploys boon. #298 recreates the fix on the latest boon with TDD. It also fixes a latent key bug: backstop runs are now looked up under the completion-owner session key.

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.

1 participant