Repository navigation
fix(agents): keep the turn's request in a bounded summary view after large tool results - #184704
Conversation
…large tool results Settled-turn finalization reopens the session within the replay byte bound (eight bytes per context token). Screenshot-heavy turns filled that bound before reaching the turn's request, so the tool-free summary answered without it. Finalization now uses the existing toolResultOverflow omit mode, which replaces result bodies with omission notices before dropping earlier requests. The bound and ordinary attempts are unchanged. (openclaw#178300)
|
🦞👀 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 changesThe built-in finalizer omits large tool-result bodies before dropping earlier requests from its bounded replay view. Example: Write a.txt=alpha, read 27 screenshots, then hit an output limit before writing b.txt=beta.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Partial Merge readiness✅ Ready for maintainer review This PR provides a useful, focused repair for lost finalizer context, with no introduced correctness findings; the broader unfinished-work report remains open. Priority: P2 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherThe embedded runtime loads persisted conversation history into a bounded model view, then sends that view to a separate tool-free finalization request. flowchart LR
A[Stored transcript] --> B[Bounded history selector]
B --> C[Ordinary attempt]
B --> D[Finalizer omission view]
D --> E[Tool-free provider request]
E --> F[Summary and incomplete outcome]
Technical reviewBest possible solution: Use the existing omission selector for the isolated finalizer while retaining bounded reads, durable history, and incomplete-work outcomes. Do we have a high-confidence way to reproduce the issue? Current-main source retains strict bounded hydration, and the supplied shipped Gateway capture demonstrates request loss on the pinned baseline and retention on the candidate; no target code was executed during this review. Is this the best way to solve the issue? This is the smallest complete fix for the scoped context-loss path: enable the existing selector at its shared limits owner and preserve ordinary replay, compaction, and terminal handling. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against c6f047ff5667. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +13, Tests +87, Docs +8. Total +108 across 5 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes: No label 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 (1 earlier review cycle)
Reviewed October 27, 2026, 1:04 AM ET / 05:04 UTC (Revision 2). |
|
@sukhdeepjohar, one adjacent integration question for this context-retention fix: #184830 now clarifies that the affected finalized run had no source delivery of its own—the earlier explicit send belonged to the previous run. This PR controls what the finalizer sees, while that issue concerns where its answer may be delivered. Current main still marks answered-finalizer payloads to override source-reply suppression, with a test intentionally expecting that behavior. I’m not suggesting this PR introduced the disclosure or should absorb the policy repair. Could the context-retention scenario also be checked through dispatch in a |
|
@ekinnee thanks, agreed on the split. This PR changes only what the finalizer reads (which history it loads, with oversized tool results replaced by a short note). It does not touch delivery. The answered-finalizer override in On ownership: ClawSweeper on #184830 routes the boundary (generated finalizer text vs required-user host notices) to the security and reply-policy owners as a product decision, and I think that's the right owner. Once that acceptance case is set, I'm happy to run this PR's many-screenshot scenario through |
|
Built Node 24.22.1 Gateway plus shipped agent CLI, frozen main ddf2e98 versus candidate 26c7f27 (same production source as pushed head; only the bounded-docs caveat follows). Local OpenAI Chat Completions HTTP/SSE fixture, no hosted credentials. Original request: PROBE_TASK marker, write a.txt=alpha then b.txt=beta. The fixture makes one real write, 27 real PNG screenshot reads (160x120, 57,803 bytes each), then returns reasoning-only finish_reason=length. It records the actual subsequent tool-free finalizer request and answers according to whether that request still includes the task. One-read control on both refs retains the task and correctly reports a done/b unfinished. Source requests before finalization retain the task and all 27 images on both refs, without omission notices. Only the separately keyed finalizer changes its bounded selection; no duplicate writes or second-file write occurs. Saved chat.history contains the candidate summary. Both refs retain the output-limit warning and incomplete_turn outcome: recovering context does not pretend interrupted work completed. 83 focused tests across finalization-incomplete, bounded session manager, model-context limits and compaction runtime passed. All changed-file formatting/lint passed, including the final docs caveat; both repository runtime builds passed. Production +17/-4; tests +95/-8. Simplification reuses the existing omission selector and preserves strict ordinary/compaction limits rather than loading an unbounded transcript. Not fixed here: the broader issue's overflow-compaction and reasoning-only recovery paths, follow-up ordinary-turn context, other harness loaders, exact reporter computer-use/80-screenshot flow, or live llama.cpp behavior. If omission notices alone exceed the bound, older messages may still be dropped. The fixture uses the real read tool as the screenshot stand-in; it is deterministic request/outcome evidence, not a new real-model claim. |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Landed in 5a8be2a. Thanks @sukhdeepjohar. Cut-off summaries now keep the original task. |
…large tool results (openclaw#184704) fix(agents): keep the original task in the finalizer request when replay is trimmed When a long turn hit the replay size bound, the finalizer request dropped the original task, so the cut-off summary said the task was unavailable. The finalizer now keeps the task within the same bound, so the summary can say what was done and what was left. Evidence: built Gateway turns with one real file write and 27 real screenshot reads. On main the task was missing from the finalizer request and the summary said the task was unavailable (twice); with this change the task was present and the summary said the first write was done and the second was unfinished (twice). Both stay within the unchanged 2,097,152-byte bound and keep the length / incomplete_turn result, cut-off warning and exit 1. A one-screenshot turn and ordinary requests are unchanged. Details: openclaw#184704 (comment). Items under "Not fixed here" in the body are not addressed. Thanks @sukhdeepjohar. Co-authored-by: Ayaan Zaidi <[email protected]>
…#203536) Result: between two compactions, the history the model sees now only grows. It no longer slides on each new attempt, so the provider prompt cache and the OpenAI Responses continuation keep matching. Token-based compaction is the only step that shortens it. ## What Problem This Solves Each attempt (a new turn, a subagent settle, `sessions_send`, a retry) loads history through `selectBoundedModelRequests` with a byte cap of `contextTokenBudget × 8`. The attempt then grows that history in memory with no cap. The next attempt reloads it and cuts the oldest turns again. Message 0/1 moves, the Responses continuation becomes `history_changed`/`history_shorter`, and the full replay hits only instructions and tools. The cap counts serialized bytes. Encrypted reasoning, thinking signatures, images and event envelopes use 8-30 bytes per token, so the cut fires far below the token budget (1-2 MB for 70-170k tokens of a 272k budget). The cut also hides the dropped history from the compaction estimate, so the session slides on every quarter-cap of growth and never compacts. On a busy production host this is the largest remaining cache loss: 186 head cuts in 24 h, 14.64M uncached input tokens (1.84% of input). All are `request=1`, the first request of an attempt. ## Why This Change Was Made Repo rule (AGENTS.md, stable conversation context): "Preserve transcript bytes; only compaction rewrites history." The hydration cut rewrote history outside compaction. - `resolveEmbeddedSessionContextLimits` returns a fixed 16 MiB / 10,000-event guard. It no longer depends on the token budget. 16 MiB stays below the smallest provider request-body limit (Gemini inline data, 20 MB). Images count only about 2,000 tokens each in the compaction estimate, so a larger guard could let a request pass a body limit before compaction fires. - Token compaction (preflight, mid-turn precheck, overflow recovery) already owns model-context size. It now sees the whole history since the boundary, so a long session compacts once, as a recorded and declared rebuild, instead of sliding on every attempt. - The `contextTokenBudget` plumbing that existed only for this cap is removed (`prepareRecoverySession`, `readCompactionTranscriptBytes`, `readPreflightTranscriptContextMessages`). - Unchanged: `selectBoundedModelRequests` and its fallbacks (quarter-cap steps, #191146 trailing prompt, #201636 in-turn request reservation). They now run only past the 16 MiB guard. The settled-tool finalizer keeps `toolResultOverflow: "omit"` (#184704). With the larger guard, it keeps every result body in every case that fit before. - Rejected: a sticky recorded cut (it still moves once per growth step, and it needs a new boundary writer outside compaction) and byte counting that excludes opaque fields (that needs per-provider payload parsing). Accepted edge cases, without code: - A session that passes 16 MiB before it compacts (a long run of screenshots) still slides in 4 MiB steps, not 512 KB steps. - On deploy, a session that already slid loads its history again once (one uncached replay). Then it can compact. - Plugin harnesses that use `resolveAgentHarnessHistoryLimits` (Plugin SDK) keep their own budget-based bound. That is a public SDK export with different seeding semantics, so it gets its own follow-up. ## Evidence **Regression step on every transport.** The step is in the prefix-stability journey (`test/prompt-cache-prefix-stability.test-support.ts`). A chat on the 64k-window model views four incompressible screenshots: more than 512 KB, the old cut, and far below compaction. Two plain turns follow. Each turn is a new attempt, and every request must extend the previous one. - Base `8d1e59c2fddc`: red on all 5 transports (anthropic, bedrock, google, openai-completions, openai-responses), with two `message 0` breaks each. - This head: green on all 5. - Mutation: the head with the old `budget × 8` cap restored is red again. **Scratch Gateway E2E.** Native `https://api.openai.com/v1`, `openai/gpt-6.2-astra`, Code Mode, 64k context window. Six turns: four view screenshots, two are plain. Request bodies and `response.completed` usage were captured. | req | base status | base input / cached | head status | head input / cached | |---|---|---|---|---| | 1-6 | first, then `continued` | 17096/0 … 18214/18099 | same | same | | 7 (turn 3, request=1) | `history_shorter`, msg 1 moved, 10 items sent in full | 17959 / **16430** | `continued`, 2 items sent | 18853 / 18211 | | 8-10 | `continued` | … 18853/18738 | `continued` | … 19747/19632 | | 11 (turn 5, request=1) | `history_shorter`, msg 1 moved, 13 items sent in full | 18598 / **16430** | `continued`, 2 items sent | 20386 / 19744 | | 12 | `continued` | 19237/18030 | `continued` | 21025/19818 | 16430 is the instructions+tools prefix alone. Base logged `historyRewrite(message 0 (user) differs ...)` twice, and head logged it zero times. Tests: the touched test files and every test file that imports a changed source (31 files), `pnpm check:changed`, oxfmt and oxlint. ## What Changes for Users Long sessions with reasoning, screenshots or many tool calls keep their prompt cache across turns, subagent settles and retries. The model also sees its full history until compaction, where before old turns were dropped silently. ## Merge danger Two-way door. No schema, config or stored-row change. A revert restores the budget-based cut. Blast radius: embedded attempts whose history since the last compaction is larger than 8 bytes per budget token. These now send more history, and token compaction trims it. Co-authored-by: Ayaan Zaidi <[email protected]>
…openclaw#203536) Result: between two compactions, the history the model sees now only grows. It no longer slides on each new attempt, so the provider prompt cache and the OpenAI Responses continuation keep matching. Token-based compaction is the only step that shortens it. ## What Problem This Solves Each attempt (a new turn, a subagent settle, `sessions_send`, a retry) loads history through `selectBoundedModelRequests` with a byte cap of `contextTokenBudget × 8`. The attempt then grows that history in memory with no cap. The next attempt reloads it and cuts the oldest turns again. Message 0/1 moves, the Responses continuation becomes `history_changed`/`history_shorter`, and the full replay hits only instructions and tools. The cap counts serialized bytes. Encrypted reasoning, thinking signatures, images and event envelopes use 8-30 bytes per token, so the cut fires far below the token budget (1-2 MB for 70-170k tokens of a 272k budget). The cut also hides the dropped history from the compaction estimate, so the session slides on every quarter-cap of growth and never compacts. On a busy production host this is the largest remaining cache loss: 186 head cuts in 24 h, 14.64M uncached input tokens (1.84% of input). All are `request=1`, the first request of an attempt. ## Why This Change Was Made Repo rule (AGENTS.md, stable conversation context): "Preserve transcript bytes; only compaction rewrites history." The hydration cut rewrote history outside compaction. - `resolveEmbeddedSessionContextLimits` returns a fixed 16 MiB / 10,000-event guard. It no longer depends on the token budget. 16 MiB stays below the smallest provider request-body limit (Gemini inline data, 20 MB). Images count only about 2,000 tokens each in the compaction estimate, so a larger guard could let a request pass a body limit before compaction fires. - Token compaction (preflight, mid-turn precheck, overflow recovery) already owns model-context size. It now sees the whole history since the boundary, so a long session compacts once, as a recorded and declared rebuild, instead of sliding on every attempt. - The `contextTokenBudget` plumbing that existed only for this cap is removed (`prepareRecoverySession`, `readCompactionTranscriptBytes`, `readPreflightTranscriptContextMessages`). - Unchanged: `selectBoundedModelRequests` and its fallbacks (quarter-cap steps, openclaw#191146 trailing prompt, openclaw#201636 in-turn request reservation). They now run only past the 16 MiB guard. The settled-tool finalizer keeps `toolResultOverflow: "omit"` (openclaw#184704). With the larger guard, it keeps every result body in every case that fit before. - Rejected: a sticky recorded cut (it still moves once per growth step, and it needs a new boundary writer outside compaction) and byte counting that excludes opaque fields (that needs per-provider payload parsing). Accepted edge cases, without code: - A session that passes 16 MiB before it compacts (a long run of screenshots) still slides in 4 MiB steps, not 512 KB steps. - On deploy, a session that already slid loads its history again once (one uncached replay). Then it can compact. - Plugin harnesses that use `resolveAgentHarnessHistoryLimits` (Plugin SDK) keep their own budget-based bound. That is a public SDK export with different seeding semantics, so it gets its own follow-up. ## Evidence **Regression step on every transport.** The step is in the prefix-stability journey (`test/prompt-cache-prefix-stability.test-support.ts`). A chat on the 64k-window model views four incompressible screenshots: more than 512 KB, the old cut, and far below compaction. Two plain turns follow. Each turn is a new attempt, and every request must extend the previous one. - Base `735a7475c1fb`: red on all 5 transports (anthropic, bedrock, google, openai-completions, openai-responses), with two `message 0` breaks each. - This head: green on all 5. - Mutation: the head with the old `budget × 8` cap restored is red again. **Scratch Gateway E2E.** Native `https://api.openai.com/v1`, `openai/gpt-6.2-astra`, Code Mode, 64k context window. Six turns: four view screenshots, two are plain. Request bodies and `response.completed` usage were captured. | req | base status | base input / cached | head status | head input / cached | |---|---|---|---|---| | 1-6 | first, then `continued` | 17096/0 … 18214/18099 | same | same | | 7 (turn 3, request=1) | `history_shorter`, msg 1 moved, 10 items sent in full | 17959 / **16430** | `continued`, 2 items sent | 18853 / 18211 | | 8-10 | `continued` | … 18853/18738 | `continued` | … 19747/19632 | | 11 (turn 5, request=1) | `history_shorter`, msg 1 moved, 13 items sent in full | 18598 / **16430** | `continued`, 2 items sent | 20386 / 19744 | | 12 | `continued` | 19237/18030 | `continued` | 21025/19818 | 16430 is the instructions+tools prefix alone. Base logged `historyRewrite(message 0 (user) differs ...)` twice, and head logged it zero times. Tests: the touched test files and every test file that imports a changed source (31 files), `pnpm check:changed`, oxfmt and oxlint. ## What Changes for Users Long sessions with reasoning, screenshots or many tool calls keep their prompt cache across turns, subagent settles and retries. The model also sees its full history until compaction, where before old turns were dropped silently. ## Merge danger Two-way door. No schema, config or stored-row change. A revert restores the budget-based cut. Blast radius: embedded attempts whose history since the last compaction is larger than 8 bytes per budget token. These now send more history, and token compaction trims it. Co-authored-by: Ayaan Zaidi <[email protected]>
…204028) Result: the settled-turn finalizer again builds its summary request within eight bytes per context token, so a screenshot-heavy cut-off turn sends a bounded request with the user's request in view. Scheduled `main` CI has been red on `settled-turn-finalization.incomplete.test.ts` since #203536, and this change fixes it. Normal attempts keep the #203536 behavior: all history since the latest compaction, with no per-attempt slide. ## What Problem This Solves #203536 changed `resolveEmbeddedSessionContextLimits` to a fixed 16 MiB guard for every operation. The settled-tool finalizer (#178300, #184704) also takes its bound from that owner. It answers for its turn alone under its own cache key, and it relied on the old `contextTokenBudget × 8` bound to replace screenshot bodies with short notices before it dropped the turn's request. At 16 MiB the omission never fired, so the finalizer sent every screenshot body. Measured in the failing test (10 screenshots, 64k context window, bound 524,288 B): | Build | Finalizer request | Tool-result bodies | |---|---|---| | `6198f78b^` | 472,487 B | 4 of 10 replaced by notices (77,339 B → 429 B each) | | `6198f78b` (#203536) | **780,415 B** | all 10 kept, 77,339 B each | | this head | 472,487 B | 4 of 10 replaced by notices | ## Why This Change Was Made - The fix is in the existing owner, `resolveEmbeddedSessionContextLimits`, which already special-cased the finalizer. For `operation: "settled-tool-finalization"`, it returns `min(16 MiB, max(1 KiB, contextTokenBudget × 8))` with `toolResultOverflow: "omit"`. Every other operation keeps the fixed 16 MiB guard. - The finalizer's cut cannot break an append-only prefix, because it is a separately keyed side request. Normal attempts, recovery and compaction reads are unchanged. - The 512 KiB test limit is unchanged. - The `attempt-history-prepare.test.ts` budget case that #203536 deleted is restored. It covers the finalizer omitting a body under a small budget. - Docs: `docs/concepts/compaction.md` names the finalizer as the one exception to the history guard. ## Evidence - `settled-turn-finalization.incomplete.test.ts`: passes on `6198f78b^`, fails on `6198f78b` (`expected 780415 to be less than 524288`) and fails on `main`. It passes on this head. The request sizes in the table came from a temporary per-message size log in scratch copies; the log is not committed. - #203536's prefix-journey step (screenshot chat) passes on all 5 transports on this head. - The targeted tests pass: every test file that imports `session-context-limits` or one of its callers. `pnpm check:changed` and oxfmt/oxlint pass on the changed files. ## Merge danger Two-way door. The change touches only the finalizer's bound. A revert restores the oversized finalizer request. Co-authored-by: Ayaan Zaidi <[email protected]>
…penclaw#204028) Result: the settled-turn finalizer again builds its summary request within eight bytes per context token, so a screenshot-heavy cut-off turn sends a bounded request with the user's request in view. Scheduled `main` CI has been red on `settled-turn-finalization.incomplete.test.ts` since openclaw#203536, and this change fixes it. Normal attempts keep the openclaw#203536 behavior: all history since the latest compaction, with no per-attempt slide. ## What Problem This Solves openclaw#203536 changed `resolveEmbeddedSessionContextLimits` to a fixed 16 MiB guard for every operation. The settled-tool finalizer (openclaw#178300, openclaw#184704) also takes its bound from that owner. It answers for its turn alone under its own cache key, and it relied on the old `contextTokenBudget × 8` bound to replace screenshot bodies with short notices before it dropped the turn's request. At 16 MiB the omission never fired, so the finalizer sent every screenshot body. Measured in the failing test (10 screenshots, 64k context window, bound 524,288 B): | Build | Finalizer request | Tool-result bodies | |---|---|---| | `d67eac7f^` | 472,487 B | 4 of 10 replaced by notices (77,339 B → 429 B each) | | `d67eac7f` (openclaw#203536) | **780,415 B** | all 10 kept, 77,339 B each | | this head | 472,487 B | 4 of 10 replaced by notices | ## Why This Change Was Made - The fix is in the existing owner, `resolveEmbeddedSessionContextLimits`, which already special-cased the finalizer. For `operation: "settled-tool-finalization"`, it returns `min(16 MiB, max(1 KiB, contextTokenBudget × 8))` with `toolResultOverflow: "omit"`. Every other operation keeps the fixed 16 MiB guard. - The finalizer's cut cannot break an append-only prefix, because it is a separately keyed side request. Normal attempts, recovery and compaction reads are unchanged. - The 512 KiB test limit is unchanged. - The `attempt-history-prepare.test.ts` budget case that openclaw#203536 deleted is restored. It covers the finalizer omitting a body under a small budget. - Docs: `docs/concepts/compaction.md` names the finalizer as the one exception to the history guard. ## Evidence - `settled-turn-finalization.incomplete.test.ts`: passes on `d67eac7f^`, fails on `d67eac7f` (`expected 780415 to be less than 524288`) and fails on `main`. It passes on this head. The request sizes in the table came from a temporary per-message size log in scratch copies; the log is not committed. - openclaw#203536's prefix-journey step (screenshot chat) passes on all 5 transports on this head. - The targeted tests pass: every test file that imports `session-context-limits` or one of its callers. `pnpm check:changed` and oxfmt/oxlint pass on the changed files. ## Merge danger Two-way door. The change touches only the finalizer's bound. A revert restores the oversized finalizer request. Co-authored-by: Ayaan Zaidi <[email protected]>
Related: #178300
What Problem This Solves
Fixes the bounded settled-tool finalizer losing the user's original task after large screenshot/tool results fill its replay window.
User Impact
Recovery can distinguish completed work from unfinished requested work instead of describing tool output without the task. It still reports an output-limit interruption as incomplete; it does not claim the remaining actions finished.
Why This Change Was Made
Use the existing toolResultOverflow: omit selector only for the separately keyed finalizer. Keep the same maxBytes/maxEvents bounds, strict ordinary replay and compaction behavior, and unchanged stored transcript. Large result bodies are replaced before older messages are dropped; omission notices are not permission to infer an outcome or repeat an action.
Thanks to @sukhdeepjohar for the focused fix and regression coverage.
Evidence
Built Gateway before/after capture.
Built Gateway and shipped agent CLI with a local HTTP/SSE provider: write a.txt once, read 27 real PNG screenshots, then cut off before the requested b.txt write. Main twice omits the task from finalization; this head twice retains it. Finalizer message JSON is 2,015,245 bytes here versus 2,013,541 on main, both below the unchanged 2,097,152-byte replay bound. Candidate summary identifies a.txt done and b.txt unfinished. Both refs preserve length/incomplete_turn, the cut-off warning and exit 1.
The one-screenshot control retains the task on both refs. Ordinary source requests retain all 27 images and the task with no omission notices on either ref. No duplicate or second-file writes. All 83 focused finalization/bounded-history/compaction tests, changed-file formatting/lint and both runtime builds passed.
Simplification keeps one existing bounded-view owner and omission selector: production +17/-4, tests +95/-8. Docs explicitly retain the fallback when omission notices alone exceed the bound.
Not fixed here
This is a partial repair of #178300, not its closure. Overflow-compaction, other reasoning-only recovery paths, subsequent ordinary-turn context and other harness loaders are unchanged. The reporter's exact computer-use/80-screenshot path and live llama.cpp are not proven here; read stands in for screenshot output. If omission notices alone exceed the bound, older messages can still be dropped. No new real-model result is claimed.
Merge danger
Two-way door: revert restores the old view selection, with no migration or stored-data rewrite. Blast radius is the built-in settled-tool finalizer under replay-byte pressure. It intentionally sees less detail from omitted results; ordinary replay, compaction, prompts and permissions remain unchanged.