Repository navigation
fix(engine): retry a cut-off model generation in smaller steps instead of restarting the job (ENG-21265) - #296
william-antoline-boon wants to merge 8 commits into
Conversation
…onfig key (ENG-21265)
…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.
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]>
There was a problem hiding this comment.
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
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]>
There was a problem hiding this comment.
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). |
There was a problem hiding this comment.
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>
| - `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). |
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:
handleEmbeddedAssistantFailuresaw a drop after tool use as "not replay-safe" and returnedproceed, so the run failed;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)
assistant-failure.ts). A generation cut offmid-stream (SDK
stream ended before message_stop, BedrockmessageStop, gatewayupstream error during stream, or a stream that closed mid–tool call) is retried on thesame 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.subagent-spawn.ts,consecutive-failure-cap.ts, opt-in viaagents.defaults.subagents.maxConsecutiveFailures):try, so a block releases its admission/swarm reservation(previously each block leaked a slot and could wedge a session's spawning);
external_user); completion wakes(
inter_session) and handoffs (internal_system) keep counting — provenance plumbedagent-tools → sessions_spawn → spawn context;
off (
DEFAULT_LENGTH_CONTINUATION_LIMIT = 0).Proof
runEmbeddedAgentloop: 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.
dropped attempt that already delivered a reply doesn't.
spawnSubagentDirect: reproduced the leaked slot(next spawn
forbidden) and the over-block (user request blocked); both fixed.tsgo:coreclean; embedded-agent-runner, subagents, failover, tools suites green.Known limits
verified by canary, not by unit tests.
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=3on Egan's host, then fleet.🤖 Generated with Claude Code