Skip to content

fix(agents): meter the CLI turn budget on retained output and stop the child when it trips - #85

Merged
tomorrowflow merged 6 commits into
mainfrom
fix/cli-output-retained-budget
Oct 15, 2026
Merged

tomorrowflow merged 6 commits into
mainfrom
fix/cli-output-retained-budget

Conversation

@tomorrowflow

Copy link
Copy Markdown
Owner

Problem

A Workboard node ticket runs as one long Claude CLI turn. On 2026-10-15 at 19:03:55 the UFH-06 ticket failed after 18 minutes of normal, tool-heavy work with this error:

CLI JSONL output exceeded 8388608 characters; refusing to parse output.

Its final reply was lost and the card was blocked. The work itself was already committed on the node.

The stream-json parser (src/agents/cli-output-stream.ts) charged its 8 MiB per-turn budget on wire bytes, but it keeps only the reply and thinking text and tool bookkeeping. Every record it reads and immediately drops still counted against the budget:

  • tool results, counted twice: the message copy and the tool_use_result echo;
  • full assistant snapshots that repeat already-counted deltas;
  • system and subagent records.

Why 8 MiB: it dates from 02c4ea5cf4e, when the live session stored every raw line. The streaming parser no longer does. Since then each upstream fix carved out one more record type: media in openclaw#128699, partial deltas in openclaw#153545.

On a trip, nothing stopped the run. push returned early from then on, nothing stopped the child, and the CLI ran blind until it exited. Only then did the error surface, as a format failure.

Why node turns hit it now: fork #69 forwards all node stdout to the Gateway, which exposed node turns to this budget.

Solution

  • Count what the parser keeps. createRetainedOutputLedger in cli-output-stream-limits.ts keeps a running total of what the parser currently holds. retain adds to it and scopes release their bytes when that state is freed. Over 8 MiB is a runaway.

    • Kept for the turn: reply text, result text, and tool ids and names.
    • Released when their message or block ends: the message's snapshot diff base, tagged reasoning, native thinking, and pending tool input.
    • A fixed 32-char overhead per append bounds floods of tiny deltas.
    • Records the parser hands off and drops meet only the existing 8 MiB per-line limit.
    • Removed: measureClaudePartialMessage, the omitted-raw arithmetic, maxTurnLines, and the per-chunk charge for other dialects. Their text is counted through the same ledger.
    • Kept: the media normalizer, because it keeps base64 out of tool-result events and the transcript mirror.
  • Stop the run on a parser failure. execute-process.ts aborts as soon as the parser reports an error, and the abort is wired to each execution path:

    • supervisor runs: supervisor.cancel;
    • node runs: a new stopSignal, which sends node.invoke.cancel;
    • plugin runs: the same cancelRun the reply backend uses.

    A caller abort that lands at the same time still wins.

  • Message: "CLI turn retained output exceeded the 8388608-character Gateway parse budget; the CLI was stopped and its final reply was lost. Work the CLI already did (files, commits) may exist; check it before re-running."

  • Subagent stream events stay out of the parent reply. stream_event text deltas and message boundaries with parent_tool_use_id were treated as the parent's. Their text joined the reply ('Hello\n\nSUBAGENT') and was counted as kept reply text. A subagent message_start also reset the parent's snapshot base. They are now ignored, as the snapshot path already did.

Evidence

  • Failing tests land before each fix:
    • e00e88eece3, a turn whose dropped tool results exceed 8 MiB: expected 'CLI JSONL output exceeded 8388608 cha…' to be null.
    • 55c4717ecb8: 4 failures. Tool input was not released at block stop, thinking was not released at the next message, and both the input on a tool block's start and custom tool names were kept uncounted.
    • 0da9993ae27: expected 'Hello\n\nSUBAGENT' to be 'Hello'.
  • Targeted tests: pnpm test src/agents/cli-output-stream.test.ts src/agents/cli-output-framing.test.ts src/agents/cli-output-partial-messages.test.ts src/agents/cli-output-jsonl.test.ts src/agents/cli-output-events.test.ts --maxWorkers=1: 110 passed, about 3 s wall.
  • Runner stop test: execute.supervisor-capture.test.ts checks that a budget trip stops the child and reports the budget message. A mutation check with the abort removed makes it hang, which was the old run-blind behavior.
  • Wider gate: pnpm test src/agents/cli-runner src/agents/cli-output-{framing,partial-messages,stream,jsonl,events}.test.ts src/gateway/node-claude-skill-runtime.test.ts --maxWorkers=2 passes 780 tests at the final head.
  • Typecheck: pnpm tsgo is clean. oxfmt and git diff --check are clean.
  • Two independent adversarial reviews.
    • First review: it found the tool-input and thinking releases missing, plus the two uncounted kept paths. Those are fixed in ecfe40344ae.

    • Second review: it found no correctness defect in the ledger. Its probes:

      • a realistic 200-message tool-heavy turn (712 MiB on the wire) ends with the total near the kept reply size, about 50–170 KB;
      • 2000 messages (7.1 GB) still don't trip;
      • the total never goes negative;
      • exactly one error is reported on every stop path.

      Its subagent finding is fixed in 4e2a612d90d.

Known limits and follow-ups (not in this PR)

  • Lower single-reply ceiling: with tiny streamed deltas, the largest single reply that passes is lower than before. At 4-char deltas it is about 466 K chars, against 780 K before, because each append pays a fixed overhead. That is still above a typical maximum Claude output.
  • Untested stop paths: only the supervisor path has a test for the stop. The node and plugin paths are traced through the code but have no cheap test harness.
  • Every parser failure now stops the child, including a parser throw. That's intended.
  • The new message never reaches a Workboard card. The card shows only "The ticket session ended without a workboard-report block". The chat failure copy also puts "LLM request rejected:" in front of it, which is misleading for a Gateway-side limit.
  • format failures still go through model fallback. With fallback candidates configured, a stopped turn would be replayed on the next model, side effects included. Workboard node tickets pin an explicit model, so they are strict: the live failure logged next=none.
  • Large screenshots: the 8 MiB per-line limit is checked before base64 is stripped. Claude echoes image bytes twice, so one screenshot above about 3 MB of PNG still trips it.
  • Unbounded downstream: toolArgsByCallId in execute-events.ts keeps args for tool starts that never get a result. The old wire budget capped that indirectly.
  • Upstream: all of this code is upstream openclaw/openclaw. The fix should be offered there as well.

Impact

Long tool-heavy CLI turns, such as Workboard node tickets, no longer lose their reply. A real runaway now stops the CLI immediately instead of letting it run blind, and subagent text no longer appears in the parent's reply.

🤖 Generated with Claude Code

tomorrowflow and others added 6 commits October 15, 2026 19:47
…utput

A long tool-heavy Claude CLI turn trips the per-turn stream-json budget on
wire bytes the parser never retains: tool_result text arrives twice (message
copy and tool_use_result echo), is handed to onToolResult, and is dropped,
yet every byte is charged against the 8 MiB turn budget. Four 1.5 MB reads
discard the final reply with "CLI JSONL output exceeded 8388608 characters".

Fails on current code at the getErrorText() assertion.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e child on parse failure

A Workboard node ticket runs as one long Claude Code CLI turn. After ~18 min
of tool-heavy work the Gateway discarded its report with "CLI JSONL output
exceeded 8388608 characters", tool tracking froze at tool:Edit:started, and
the child kept running blind until exit.

Root cause: the per-turn budget in cli-output-stream.ts metered wire bytes
(every stdout line, with discounts for partial deltas and echoed media),
while the parser retains only text, reasoning, result text, and tool
bookkeeping. Tool results are handed to onToolResult and dropped, yet each
was charged twice (message copy and tool_use_result echo), as were full
assistant snapshots and subagent traffic. The budget dates from 02c4ea5,
when the retired claude-live-session kept every raw line; every later fix
(openclaw#119488, openclaw#128699, openclaw#153545) carved out one more record type instead of
charging what is kept.

Fix:
- One ledger in the parser charges what it appends to turn state: streamed
  deltas, custom text/thinking events, item texts, result text, Gemini
  content, tool ids and names, pending tool-input JSON, and native thinking.
  The tool and thinking trackers report their own retention through a
  `retain` callback. Each append also pays a fixed 32-char overhead so floods
  of one-character appends stay bounded (string pieces and map entries cost
  memory the payload alone does not show).
- Records the parser hands off or drops only meet the per-line limit.
  `measureClaudePartialMessage`, the omitted-raw arithmetic, and the
  per-chunk charge for non-Claude dialects are removed; those dialects retain
  text through the same ledger. The media normalizer stays because it keeps
  base64 out of tool-result events and the transcript mirror, but it no
  longer re-serializes the record for accounting.
- maxTurnLines is removed. It guarded per-line retention that no longer
  exists: blank, system, and empty frames retain nothing, and per-tool
  bookkeeping is now charged by content. A long turn with subagent traffic
  was the next way to hit it.
- execute-process.ts owns an output-rejection AbortController. Any parser
  failure stops the child promptly through the existing cancellation of each
  path (supervisor cancel, node abort which sends node.invoke.cancel, plugin
  turn abort) and reports the parser failure as the "format" failover. A
  caller abort that coincides with it still wins.
- Limit messages now say the retained output exceeded the Gateway parse
  budget, the CLI was stopped, and work on the node or worktree may exist.

Tests:
- cli-output-framing: 12 MB of handed-off tool results keep the reply
  (committed first, failed on the old budget); the oversized-text case now
  uses streamed deltas because a finished assistant snapshot is never a
  retained delta; the wire-byte cases (plugin-claimed media bytes,
  whitespace padding, 20,000-line cap) are rewritten or removed because the
  budget no longer meters wire bytes.
- cli-output-partial-messages: retained delta payloads still trip; dropped
  input_json_delta without an open block does not; the tiny-delta flood is
  bounded by the per-append overhead; frame-limit and padding cases removed.
- execute.supervisor-capture: a budget trip cancels the child
  ("manual-cancel") and rejects with the new message; without the stop the
  test times out at 120 s.
- execute.pending-cancellation: the fixture aborts in the same tick as the
  unrelated parser failure, since the failure now stops the child itself.

Cost (--maxWorkers=1): framing + partial-messages 4.6 s wall, supervisor-capture
37.5 s wall (18 s compiled-worker preparation, test bodies 4%), pending-cancellation
12.5 s wall.

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

The retained ledger is cumulative, but the parser frees pending tool input
at content_block_stop and native thinking at each message start without a
refund, so a turn of 30 Write calls (9 MB streamed, 300 KB live) and a turn
of 20 reasoning messages (1 MB live) both trip the 8 MiB budget. Tool input
carried on content_block_start and names from custom toolResult events are
retained without any charge, so 40 unterminated 300 KB starts and ten 1 MB
names pass silently.

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

The retained ledger was cumulative, but the parser frees state during the
turn without a refund: pending tool input at content_block_stop and native
thinking at each message start. With --include-partial-messages every Write
or Edit input streams as input_json_delta, so a long tool-heavy turn tripped
the 8 MiB budget while holding a few hundred KB. Two retentions were also
uncharged: tool input carried on content_block_start and tool names from
custom toolResult events.

- cli-output-stream-limits.ts owns a RetainedOutputLedger: retain/release
  for turn-lived state and scope() for lifetimes refunded as one unit. The
  per-append overhead is paid into the scope and refunded with it.
- Each pending tool block owns a scope (id, name, serialized start input,
  streamed input JSON), refunded at content_block_stop, when a start replaces
  the index, or at the next message_start, since block indexes restart per
  message and an unstopped block can only be abandoned.
- The thinking tracker owns a message scope covering both copies it keeps
  (per-index block text and the message aggregate), refunded on reset.
- The tagged-reasoning router charges what it holds back and refunds on
  settle. The stream's message scope covers the snapshot diff base and
  tagged reasoning, refunded at the next message start and at a result, so
  a reply streamed in one message and repeated by the result holds two
  copies (reply text, result text), not three. Commentary pending text has
  its own scope, refunded on flush. Reply text is charged where appended.
- Tool names are charged once per id via retainToolName, replacing a prior
  name refunds it; custom toolResult names go through the same path.
- The limit message names the lost final reply and work the CLI already did
  (files, commits) for local and node runs alike.

Tests: the four reproductions pass; the bounded-payload cases use 2 MB
payloads with a bounded push count since text and thinking are now held
twice within a message; a new case pins the 2x headroom at the result (fails
if the message copy is kept through the result).

Cost (--maxWorkers=1): partial-messages 3.4 s wall, framing 3.2 s wall,
pending-cancellation 30.6 s wall (compiled-worker transform; comment only).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Streamed text deltas and message boundaries from subagent records
(parent_tool_use_id set) were treated as the parent's: their text joined
the reply and was charged to the turn budget as kept reply text, and a
subagent message_start reset the parent's snapshot base. Ignore them like
the snapshot path already does. Also keep the append overhead constant
module-private.

Co-Authored-By: Claude Opus 5.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.

1 participant