Repository navigation
fix(agents): Claude CLI turns hit output limits on discarded stream frames - #185404
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesThis PR discounts discarded Claude CLI control frames within the existing output budgets. Example: A Claude CLI turn runs 1,980 sequential echo commands.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep this PR open: it repairs a demonstrated Claude CLI reply-loss bug that remains on current main, with no actionable correctness or security findings. Current-head CI is still pending. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe CLI streaming parser receives Claude Code JSONL, accounts for retained content and framing, and emits reply text, thinking progress, and tool events. flowchart LR
A[Claude Code stdout] --> B[Bounded JSONL framing]
B --> C[Record decoding]
C --> D[Stream budget accounting]
D --> E[Event and reply parser]
E --> F[Agent callbacks and final reply]
Technical reviewBest possible solution: Merge the focused accounting repair once the required current-head checks pass. Do we have a high-confidence way to reproduce the issue? Current-main source still charges these discarded frames at raw size, matching the supplied failing shipped-entry trace; no target code was executed during this read-only review. Is this the best way to solve the issue? The patch fixes the accounting owner directly, shares existing envelope validation, preserves retained-content charges, and avoids restoring tuning knobs. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 941b949f8c72. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +73, Tests +264, Docs +2, Other +2. Total +341 across 5 files. Added test files: 1. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (4 earlier review cycles)
Reviewed November 6, 2026, 10:37 PM ET / November 7, 2026, 03:37 UTC (Revision 5). |
|
Real-world data point for the "behavior proof" request: I've run the equivalent change locally on 2026.10.7 and #186085 should remove most of the line overcount on current Claude Code, but tool-result-heavy turns still hit the |
…lowance - Thinking progress ticks (only estimated_tokens is read), content_block_stop and message_stop frames are charged 32 characters plus padding and skip the ordinary-line limit, like recognized partial frames. - signature_delta and message_delta frames, whose content the parser discards, keep the ordinary-line limit and leave at most 8 KiB of each line uncharged. - Unknown keys at any level, oversized or non-string metadata, invalid indexes, non-numeric estimates and thinking text keep full accounting; the 8 MiB budget, per-line cap and 20,000-line limit are unchanged. - Control frames reuse the partial-frame envelope check (metadata keys and caps from openclaw#186085, block index), now shared in readBoundedStreamEvent. - docs/gateway/cli-backends.md describes the control-frame accounting.
d7fa12e to
21fe916
Compare
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
…growth - cli-output-partial-messages.test.ts: drop the empty thinking progress and signature delta rows that expected full accounting; the control-frame suite covers both shapes with their new charges. - cli-output-control-frames.test.ts: drop the small-frame line-limit cases already covered by the allowance-sized mixed-frame test. - config/test-lines-allocations: record the net test growth of this change.
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review Merged current |
|
🦞👀 Re-review progress:
|
|
Merged via squash.
Thanks, @etzelm, for the accounting fix and the 1,980-step reproduction. |
…rames (openclaw#185404) * fix(agents): charge discarded Claude stream control frames a fixed allowance - Thinking progress ticks (only estimated_tokens is read), content_block_stop and message_stop frames are charged 32 characters plus padding and skip the ordinary-line limit, like recognized partial frames. - signature_delta and message_delta frames, whose content the parser discards, keep the ordinary-line limit and leave at most 8 KiB of each line uncharged. - Unknown keys at any level, oversized or non-string metadata, invalid indexes, non-numeric estimates and thinking text keep full accounting; the 8 MiB budget, per-line cap and 20,000-line limit are unchanged. - Control frames reuse the partial-frame envelope check (metadata keys and caps from openclaw#186085, block index), now shared in readBoundedStreamEvent. - docs/gateway/cli-backends.md describes the control-frame accounting. * test(agents): retire superseded control-frame rows and allocate test growth - cli-output-partial-messages.test.ts: drop the empty thinking progress and signature delta rows that expected full accounting; the control-frame suite covers both shapes with their new charges. - cli-output-control-frames.test.ts: drop the small-frame line-limit cases already covered by the allowance-sized mixed-frame test. - config/test-lines-allocations: record the net test growth of this change.
Related: #153545, #184352, #186085, #166127, #159930, #111382
This PR no longer adds environment overrides. The earlier revision restored output-limit tuning that #111382 removed; it is replaced here by an accounting repair inside the existing fixed limits, the direction the first review recommended. No limit, setting or environment variable changes.
What Problem This Solves
Claude stream frames the parser throws away (thinking signatures, empty thinking progress ticks, block and message stops, message deltas) are charged their full raw size against the 8 MiB output budget, and every one counts toward the 20,000-line limit. In long tool-heavy
claude-cliturns that framing alone stops the turn withCLI JSONL output exceeded 8388608 charactersand loses the final reply. This change charges those frames a fixed allowance. Other record types are charged as before.User Impact
On the 1,980-step tool loop below, current
mainstops the turn after step 1,744 and returns no reply; with this change the same loop completes all 1,980 steps and repliesDONE. Per tool round the charge drops from about 4,700 to 3,590 characters, so aclaude-cliturn fits about 30 percent more tool calls before the unchanged limits apply.Why This Change Was Made
chargeClaudeStreamJsonLinecharges each Claude stream-json line its raw length unless a narrower rule applies: #153545 charges text, thinking and tool-input deltas their payload plus 32 characters (#186085 extended it to frames carryingapi_message_id), and #184352 charges discarded child messages a fixed 64. Fivestream_eventkinds have no rule, although the parser reads at most one small field from them:signature_deltacli-output-events.ts:491: "opaque continuation material")thinking_deltawith emptythinking(progress tick)estimated_tokens(cli-output-events.ts:483)content_block_stopindex(cli-output-events.ts:330,:467)message_stopcli-output-stream.ts:524)message_deltasrc/has no reader ofmessage_delta;readCliUsagereads top-levelusage, notevent.usage)The charge only feeds the budget; it never changes what the parser reads or emits.
measureClaudeStreamControlFrame(new, beside the partial-frame helper) charges a matching frame 32 characters, plus theestimated_tokensfield for progress ticks and any wire whitespace around the JSON:onThinkingProgressonce per frame.api_message_idat most 64 characters,thinking_displayat most 32, valid block index) moves intoreadBoundedStreamEventand is shared by both helpers instead of duplicated.thinking_displayis accepted only on progress ticks.message_startandcontent_block_startstay fully charged because they feed parser state.#166127 (tool results) and #159930 (Edit/Write file echoes) discount other record types and do not overlap.
Evidence
Real behavior proof (shipped entry point). One
openclaw agent execturn per build through the bundledclaude-clibackend, built frommain(67c3c3a) and from this PR at 21fe916 (the follow-up commit changes only tests and the test-lines allocation, so the production code exercised is the code under review). macOS, Node 24, Claude Code 2.1.296,claude-haiku-5-5,--thinking low, each run with its own temporaryOPENCLAW_HOMEand this config:{ "agents": { "defaults": { "model": "anthropic/claude-haiku-5-5", "models": { "anthropic/claude-haiku-5-5": { "agentRuntime": { "id": "claude-cli" } } }, "timeoutSeconds": 7200 } } }Prompt: run
echo step-Kwith theexectool for K = 1 to 1,980, one call per message, then replyDONE. Each round is one tiny tool call, so most of the stream is per-message framing (message start, block start and stop, message delta, message stop, snapshots and tool results), the shape of a long tool loop.main67c3c3aCLI JSONL output exceeded 8388608 charactersafter step 1,744, no reply (2,174 s)ToolSearchand the cancelled step 1,745)ok, finalDONE(2,882 s)ToolSearch, 1 rejected first guessThe
mainrun stops after step 1,744: the parser refuses the stream mid-turn, the in-flight call is cancelled and no reply is returned. In the head run the model first called a bareexec(rejected: the tool was not loaded yet), loadedmcp__openclaw__execwithToolSearch, then ran all 1,980 steps; that rejected first guess is the single tool failure and the two extra calls. The working directory holds only the prompt after both runs.A pass-through wrapper on
PATHcopied Claude Code's stdout to a file in both runs, because the gateway does not log the stream of a failed turn. Replaying each file throughchargeClaudeStreamJsonLinefrom both builds, fed the way the live transport feeds the parser (it consumes control messages first):mainaccountingmainrun (25,659 lines)On the completed stream that is about 4,700 characters per tool round on
mainand 3,590 with this change.main67c3c3a: redacted outputthis PR 21fe916: redacted output
Redaction replaced run and session ids, hashes and temporary paths, and dropped repeated skill-loading lines. This run shape exercises stop frames and message deltas; it has almost no thinking, so the signature and progress-tick savings show in the captured-stream breakdown below.
Charge breakdown on captured streams. Each line fed through
chargeClaudeStreamJsonLinefrommain(67c3c3a) and from this PR, applying the real limits:mainThe four production turns failed on
mainbefore #186085 at 109 to 114 percent of the budget; #186085 brings them to 61 to 65 percent, and this change takes off another 0.95 to 1.06 MB each.Tests and checks (macOS, Node 24). The RED and mutation runs were done at 11b83ab; the code and test changes in this PR are byte-identical at the current head (only the docs paragraph was rewrapped around a
mainedit). Everything else was rerun at the current head ff03f75 (this branch merged withmain638a185), from a fresh clone:src/agents/cli-output-control-frames.test.ts(new): 45 passed. Covers the Claude Code 2.1.296 shape of each frame kind (exact charge and line accounting), wire padding, index-less and child-attributed frames, the 8 KiB allowance (at, just over, far over, with padding), every metadata cap at its limit, and full accounting for each rejected shape above. It also checks that progress ticks and tool starts still reach the parser callbacks, that 20,001 progress or stop frames complete, that signature and message deltas at the allowance stop on the 20,001st line, and that progress, block-stop and message-stop floods hit the 8 MiB budget at the computed frame.cli-output-stream-limits.tsreverted tomain, 26 fail and 19 pass. 21 single-site mutations of the production file (zero charges, dropped or moved metadata caps,thinking_displayanywhere, unknown event or delta keys, no padding, empty signatures, no index check, skipping the shared envelope check, no overflow charge, larger allowance, line-count flips, no estimate charge): 20 fail at least one test. The survivor removes thethinking === ""guard on progress ticks; it is equivalent today because the fix(agents): Claude CLI turns hit the 20,000-line limit when Claude Code adds stream frame metadata #186085 partial-frame rule charges any thinking delta with text first, and the guard stays so the control-frame rule never discounts thinking text on its own.src/agents/cli-output*.test.tsfiles: 284 passed.src/agents/cli-runner/(74 files): 911 passed.cli-output-partial-messages.test.tsdrops its empty-thinking-progress and signature-delta rows, which expected full accounting for the frames this PR now discounts; the new suite covers both shapes with their new charges. The net test growth (264 lines) is recorded inconfig/test-lines-allocations/claude-stream-control-frames.txt;pnpm check:test-lines-ratchet --base 638a1851e7e(6,556,625 lines, ceiling 6,556,696) andgit diff --checkpass.pnpm tsgo:prod,pnpm tsgo:ui,pnpm tsgo:scripts,pnpm check:test-types,pnpm tsgo:core:test, andpnpm check:baseline-ratchets --base 638a1851e7e(all 9 ratchets ok).pnpm check:changed --base 638a1851e7epasses every step (including lint, format, dead-export scan, and core typecheck) exceptchangelog attributions, which flags 20 existingThanks @...lines inCHANGELOG/*.md. This PR touches no changelog file, and the check prints the same output onmain638a185.mainf2c27f0. Every failure came from that base and shows up the same onmain7c2ff8f (the merge base at that point) with no changes from this PR. The type lanes all failed on one error in a file this PR does not touch:ui/src/components/browser/browser-panel-render.tsx(149,11): error TS2322, fixed onmainby fix(ui): restore browser panel type checks #192868. The ratchet lane failed ontest-lines:over by: 191.mainalone was over by the same 191 lines, and fix(ci): reconcile remaining seven-line test budget debt #192905 reconciled them; this PR's own +264 is covered by its allocation. Neither fix was in f2c27f0, so a rerun of that CI run would test the same merge again. That is why this branch takes currentmain.docs/gateway/cli-backends.md("Inputs and outputs") gains one sentence on the control-frame allowance.CHANGELOG.mdis left to release generation.