Repository navigation
fix(agents): compact on predicted overflow instead of trimming tool results the provider already cached - #199530
Conversation
…esults the provider already cached The pre-request pressure check counted every tool result as reducible and, on the truncate-only route, rewrote the oldest already-sent results down to the aggregate budget. That changed bytes inside the provider's cached prefix and, because it trimmed only enough to fit, recurred on every run near the window. Predicted pressure now counts and trims only results the provider has not received (after the last assistant message). Overflow from sent history routes to compaction, an allowed rebuild point. Recovery after a real provider rejection is unchanged. Co-authored-by: obviyus <[email protected]>
|
🦞👀 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 preserves previously sent tool results during predicted overflow recovery and routes pressure from that history to compaction. Example: An isolated OpenAI Responses session crosses its 260,000-token window with large tool results already in history.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep open: this maintainer-authored PR addresses a source-supported prompt-cache defect with a focused repair; no blocking correctness defect was found, and the author's draft hold remains. Priority: P2 Before mergeNone. Findings
Agent review detailsHow this fits togetherThe embedded agent runner estimates outgoing request pressure, selects truncation or compaction, and prepares transcript messages for the provider. flowchart TD
A[Session history and pending results] --> B[Request pressure decision]
B --> C[Shared truncation planner]
C --> D[Cap unsent oversized results]
C --> E[Compact sent history]
D --> F[Provider request]
E --> F
Technical reviewBest possible solution: Keep prediction and truncation on the existing shared planner, preserve sent results during direct precheck recovery, and describe the retained failure fallback accurately. Do we have a high-confidence way to reproduce the issue? Current main counts previously sent tool results as reducible and can rewrite them during predicted-pressure recovery; the reported live comparison confirms that routing, although its baseline rewrite was refused. Is this the best way to solve the issue? The repair enforces the sent-history boundary in the existing planner and uses it consistently for estimation and execution, without adding another state owner. Full review comments:
Overall correctness: patch is correct AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against b135516219ab. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +8, Tests +106, Docs +5. Total +119 across 7 files. Added test files: 0. 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: 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 Reviewed November 15, 2026, 3:55 AM ET / 08:55 UTC. |
Co-authored-by: steipete <[email protected]>
Baseline-Refresh: 30105881727984111af2ab3bd5b67d0cdb5b3bc2 Co-authored-by: steipete <[email protected]>
Co-authored-by: steipete <[email protected]>
…esults the provider already cached (#199530) * fix(agents): compact on predicted overflow instead of trimming tool results the provider already cached The pre-request pressure check counted every tool result as reducible and, on the truncate-only route, rewrote the oldest already-sent results down to the aggregate budget. That changed bytes inside the provider's cached prefix and, because it trimmed only enough to fit, recurred on every run near the window. Predicted pressure now counts and trims only results the provider has not received (after the last assistant message). Overflow from sent history routes to compaction, an allowed rebuild point. Recovery after a real provider rejection is unchanged. Co-authored-by: obviyus <[email protected]> * fix(agents): preserve sent output in all predicted-overflow paths Co-authored-by: steipete <[email protected]> * test(agents): model unsent tool results at the request boundary Co-authored-by: steipete <[email protected]> --------- Co-authored-by: obviyus <[email protected]> Co-authored-by: steipete <[email protected]> (cherry picked from commit 535f3ea)
|
Merged via squash auto-merge.
|
…esults the provider already cached (openclaw#199530) * fix(agents): compact on predicted overflow instead of trimming tool results the provider already cached The pre-request pressure check counted every tool result as reducible and, on the truncate-only route, rewrote the oldest already-sent results down to the aggregate budget. That changed bytes inside the provider's cached prefix and, because it trimmed only enough to fit, recurred on every run near the window. Predicted pressure now counts and trims only results the provider has not received (after the last assistant message). Overflow from sent history routes to compaction, an allowed rebuild point. Recovery after a real provider rejection is unchanged. Co-authored-by: obviyus <[email protected]> * fix(agents): preserve sent output in all predicted-overflow paths Co-authored-by: steipete <[email protected]> * test(agents): model unsent tool results at the request boundary Co-authored-by: steipete <[email protected]> --------- Co-authored-by: obviyus <[email protected]> Co-authored-by: steipete <[email protected]>
…low and a concurrent chat on five transports (#201723) ## What was wrong The prompt-cache journey is the CI check that each provider request in a chat extends the previous request byte for byte, except where a rebuild is expected. It skipped four triggers that real chats hit: a scheduled job that comes due in the chat, a user message steered into a running tool call, tool results that fill the context window, and an unrelated chat that compacts while this one runs. It also covered only three transports. A break in any of those paths could land without CI noticing. **Example:** a scheduled job sent its reply to the model twice on every route. On Chat Completions and Gemini the copy merged into the next tool-call message, which rewrote history and lost the cache from that point on. Fixed in #201838. This journey would have caught it. ## Fix - Adds the cron, steer, tool-result overflow and concurrent-compaction steps to the stability journey. It now runs on five transports: Anthropic, Responses, Chat Completions, Gemini and Bedrock. - Adds a seeded randomized journey: 15 turn kinds on five transports, plus a variant with Tool Search turned off. - Lists the breaks main still has, each with its owner. Entries expire: when a fix lands, the journey fails until its entry is removed. Each entry checks the whole request, so a known change cannot hide a second one. - Rebuild steps are excused only when the rebuild actually happened. A compaction must put its new summary into the next request, and a model switch must make the next request come from the selected model. - The steer step holds the tool open until the Gateway reports that the run has taken the steer. Before, it slept for a fixed 3 s. ## Numbers | | main (before this PR) | this PR | |---|---|---| | Triggers covered | ordinary turns, tools, compaction | + cron, steer, tool-result overflow, concurrent compaction, cron-first chat, 15-kind randomized journey | | Transports | 3 | 5 | | Stability journey | n/a | 5/5 | | Randomized journey (default seeds, 6 files) + negative controls | n/a | 12/12 + 5/5 | | Anthropic and Tool Search off, seeds 1 and 6 | n/a | 2/2 and 2/2 | <details><summary>Breaks still on main (accepted entries)</summary> | Where | Change | Owner | |---|---|---| | Gemini, tool-result overflow (other chat) | the pre-request pressure check trims tool results that were already sent | #199530 | | Bedrock, randomized | a dropped silent reply merges the user turns around it | accepted gap (#201654 closed) | | Tool Search off, randomized | a provider switch adds `skills_read`/`skills_search` on turns started by a subagent completion or inter-session message | #201710 / documented exception of the opt-out surface | Removed because their owners landed: the cron reply twice (#201838), the Chat Completions silent-turn merge (#201843), the cron-first `message` growth (#201710), and the skills rebuild after `config.patch` (issue #202150, which no longer reproduces on Anthropic seeds 1 and 6). Bedrock refuses `cron.add` for AWS-SDK auth by design, and the journey expects that refusal. </details> <details><summary>Steer signal</summary> - The steer is sent with `queueMode: "steer"`, as the chat composer sends it. The test waits for `sessions.changed` with reason `agent.input.steering`, which the Gateway emits when the active run accepts the steer into its queue. The tool is released only after that event. - On all five transports the event arrives about 200-260 ms after the send is acknowledged, while the tool is still held. - Negative control: releasing right after the acknowledgment lost the race on Gemini (1/5). The steered input became a separate turn. - A default `chat.send` steer exposes nothing before release. Its pending input stays `queued` with no `steerNow`, and `agent.input.steering` only fires when the tool ends. So the step uses the composer's steer path. </details> <details><summary>Rebuild evidence checks</summary> - Compaction: the fake numbers each compaction summary. The step needs a new summary, and the turn after it must contain that summary. - Model switch: the alternate provider has its own model id. Every request after the switch must name exactly the selected model, read from the request body or the URL (Gemini, Bedrock), and at least one request must arrive. - Teeth: with `sessions.compact` turned into a no-op, all 10 randomized seeds failed. With `sessions.patch` pinned to the first model, all 10 failed too. </details> <details><summary>Cron-first red on base</summary> On the parent of #201710 with this PR's test files (no entry), the cron-first step fails on Anthropic and Responses at the owner turn's tool list (`at: 1, change: tools`). On main the step passes. </details> <details><summary>Harness fixes</summary> - Each seed uses its own session keys. A retained subagent from the previous seed made every turn fail with `Retained subagent payload is unavailable`. - After a silent reply, the fake acts only on the newest step marker, because main drops silent replies from replay. - Every request is assigned to its session by its runtime line. A request from an unexpected session fails the journey. - The Advisor fork check is dropped. Forks never arrived in earlier runs. When they did arrive, their requests differed from the parent's on all transports, which needs its own investigation. </details> <details><summary>Gates</summary> - `ocx test` from source with an in-process Gateway and fake provider endpoints: 5 stability files, 6 randomized files and the known-breaks unit, 17/17. Anthropic and Tool Search off at seeds 1 and 6, 2/2 each. A second stability pass, 5/5. - `pnpm tsgo:test:root`, oxfmt and oxlint on the changed files, and the test-lines ratchet all pass. - Local review on this head: patch is correct, no findings. </details> Co-authored-by: Ayaan Zaidi <[email protected]>
…low and a concurrent chat on five transports (openclaw#201723) ## What was wrong The prompt-cache journey is the CI check that each provider request in a chat extends the previous request byte for byte, except where a rebuild is expected. It skipped four triggers that real chats hit: a scheduled job that comes due in the chat, a user message steered into a running tool call, tool results that fill the context window, and an unrelated chat that compacts while this one runs. It also covered only three transports. A break in any of those paths could land without CI noticing. **Example:** a scheduled job sent its reply to the model twice on every route. On Chat Completions and Gemini the copy merged into the next tool-call message, which rewrote history and lost the cache from that point on. Fixed in openclaw#201838. This journey would have caught it. ## Fix - Adds the cron, steer, tool-result overflow and concurrent-compaction steps to the stability journey. It now runs on five transports: Anthropic, Responses, Chat Completions, Gemini and Bedrock. - Adds a seeded randomized journey: 15 turn kinds on five transports, plus a variant with Tool Search turned off. - Lists the breaks main still has, each with its owner. Entries expire: when a fix lands, the journey fails until its entry is removed. Each entry checks the whole request, so a known change cannot hide a second one. - Rebuild steps are excused only when the rebuild actually happened. A compaction must put its new summary into the next request, and a model switch must make the next request come from the selected model. - The steer step holds the tool open until the Gateway reports that the run has taken the steer. Before, it slept for a fixed 3 s. ## Numbers | | main (before this PR) | this PR | |---|---|---| | Triggers covered | ordinary turns, tools, compaction | + cron, steer, tool-result overflow, concurrent compaction, cron-first chat, 15-kind randomized journey | | Transports | 3 | 5 | | Stability journey | n/a | 5/5 | | Randomized journey (default seeds, 6 files) + negative controls | n/a | 12/12 + 5/5 | | Anthropic and Tool Search off, seeds 1 and 6 | n/a | 2/2 and 2/2 | <details><summary>Breaks still on main (accepted entries)</summary> | Where | Change | Owner | |---|---|---| | Gemini, tool-result overflow (other chat) | the pre-request pressure check trims tool results that were already sent | openclaw#199530 | | Bedrock, randomized | a dropped silent reply merges the user turns around it | accepted gap (openclaw#201654 closed) | | Tool Search off, randomized | a provider switch adds `skills_read`/`skills_search` on turns started by a subagent completion or inter-session message | openclaw#201710 / documented exception of the opt-out surface | Removed because their owners landed: the cron reply twice (openclaw#201838), the Chat Completions silent-turn merge (openclaw#201843), the cron-first `message` growth (openclaw#201710), and the skills rebuild after `config.patch` (issue openclaw#202150, which no longer reproduces on Anthropic seeds 1 and 6). Bedrock refuses `cron.add` for AWS-SDK auth by design, and the journey expects that refusal. </details> <details><summary>Steer signal</summary> - The steer is sent with `queueMode: "steer"`, as the chat composer sends it. The test waits for `sessions.changed` with reason `agent.input.steering`, which the Gateway emits when the active run accepts the steer into its queue. The tool is released only after that event. - On all five transports the event arrives about 200-260 ms after the send is acknowledged, while the tool is still held. - Negative control: releasing right after the acknowledgment lost the race on Gemini (1/5). The steered input became a separate turn. - A default `chat.send` steer exposes nothing before release. Its pending input stays `queued` with no `steerNow`, and `agent.input.steering` only fires when the tool ends. So the step uses the composer's steer path. </details> <details><summary>Rebuild evidence checks</summary> - Compaction: the fake numbers each compaction summary. The step needs a new summary, and the turn after it must contain that summary. - Model switch: the alternate provider has its own model id. Every request after the switch must name exactly the selected model, read from the request body or the URL (Gemini, Bedrock), and at least one request must arrive. - Teeth: with `sessions.compact` turned into a no-op, all 10 randomized seeds failed. With `sessions.patch` pinned to the first model, all 10 failed too. </details> <details><summary>Cron-first red on base</summary> On the parent of openclaw#201710 with this PR's test files (no entry), the cron-first step fails on Anthropic and Responses at the owner turn's tool list (`at: 1, change: tools`). On main the step passes. </details> <details><summary>Harness fixes</summary> - Each seed uses its own session keys. A retained subagent from the previous seed made every turn fail with `Retained subagent payload is unavailable`. - After a silent reply, the fake acts only on the newest step marker, because main drops silent replies from replay. - Every request is assigned to its session by its runtime line. A request from an unexpected session fails the journey. - The Advisor fork check is dropped. Forks never arrived in earlier runs. When they did arrive, their requests differed from the parent's on all transports, which needs its own investigation. </details> <details><summary>Gates</summary> - `ocx test` from source with an in-process Gateway and fake provider endpoints: 5 stability files, 6 randomized files and the known-breaks unit, 17/17. Anthropic and Tool Search off at seeds 1 and 6, 2/2 each. A second stability pass, 5/5. - `pnpm tsgo:test:root`, oxfmt and oxlint on the changed files, and the test-lines ratchet all pass. - Local review on this head: patch is correct, no findings. </details> Co-authored-by: Ayaan Zaidi <[email protected]>
…esults the provider already cached (openclaw#199530) * fix(agents): compact on predicted overflow instead of trimming tool results the provider already cached The pre-request pressure check counted every tool result as reducible and, on the truncate-only route, rewrote the oldest already-sent results down to the aggregate budget. That changed bytes inside the provider's cached prefix and, because it trimmed only enough to fit, recurred on every run near the window. Predicted pressure now counts and trims only results the provider has not received (after the last assistant message). Overflow from sent history routes to compaction, an allowed rebuild point. Recovery after a real provider rejection is unchanged. Co-authored-by: obviyus <[email protected]> * fix(agents): preserve sent output in all predicted-overflow paths Co-authored-by: steipete <[email protected]> * test(agents): model unsent tool results at the request boundary Co-authored-by: steipete <[email protected]> --------- Co-authored-by: obviyus <[email protected]> Co-authored-by: steipete <[email protected]> Release adaptation: Preserve reviewed individual adaptation; source bytes unchanged. Parent-inspected framing fixture correction: unchanged baseline ceil(12*1.2)=15, expected41015/1015; exact assertions retained. (cherry picked from commit 535f3ea) Co-authored-by: RomneyDa <[email protected]>
…esults the provider already cached (#199530) Baseline adaptation: filter reducible results at the last assistant in the existing measured branch planner, and persist only actual planner edits during predicted overflow. Use the release request guard and frozen projection/rewrite owners; leave actual provider rejection recovery unchanged. (cherry picked from commit 535f3ea) Co-authored-by: obviyus <[email protected]> Co-authored-by: steipete <[email protected]> Co-authored-by: RomneyDa <[email protected]> (cherry picked from commit c243246e52dc550f77115c04540d13725f13b482)
What Problem This Solves
On a production gateway over 36 hours, one signature caused 14 warm prompt-cache breaks (about 3.1M cached tokens lost), all on
openai-responses:[prompt-cache] message N (toolResult) differs from the previous request; history must be append-only; changed fields: content[0].text, with N an early message (3, 16, 17, 27).cache read dropped ~250k -> ~19-23k(the system prompt only) onrequest=1of a new run,systemPromptSeries=pinned, request gap 0.8-5.6 s.All 14 breaks follow, within 20 s, a
[context-overflow-midturn-precheck] route=truncate_tool_results_only handled=true truncatedCount=Nline and a[tool-result-truncation] Truncated N tool result(s) in session (... aggregate=N)line for the same session. The sessions were near their context window (260k on that route) and had no compaction in between.Root cause
resolveCompactionPressureDecision,run/preemptive-compaction.ts) predicts an overflow, it choosestruncate_tool_results_onlyif trimming tool results could recover 1.5x the overflow. It counts every tool result in history, including results that earlier requests already sent in full.handleEmbeddedAttemptMidTurnPrecheck(run/attempt-prompt-preflight.ts) then callstruncateOversizedToolResultsInSessionManager. That rewrites the transcript in recovery mode, which ignores the frozen projection state, and trims the oldest results down to the aggregate tool-result budget./new,/reset, compaction, model or provider switch) indocs/reference/prompt-caching.md.truncateOversizedToolResultsInMessageswith its frozen projection state) already keeps sent results byte-stable. It is not part of this break. The difference comes from the session rewrite above.Fix
buildToolResultReplacementPlan(tool-result-truncation.ts) getspreserveSentToolResults. Results before the last assistant message are already sent, and the plan does not touch them. Only the unconsumed tail (results the provider has not received) can still be capped.compact_onlyorcompact_then_truncate. Compaction is an allowed rebuild point, and it frees enough space that the following runs append again.Proof
Real route (isolated throwaway Gateway, direct OpenAI Responses,
openai/gpt-6.1-sol,serviceTier: ultrafast= 260k window, server compaction threshold set to the window). One session: runs of threeexeccalls (~60k chars each) until the next run starts above the window.route=truncate_tool_results_only toolResultReducibleChars=364430route=compact_only toolResultReducibleChars=0Pending input relocation does not match its admitted transcript entry), fallback to compactionPrefix-stability journey (
test/prompt-cache-prefix-stability.test-support.ts, both routes): a new step sends 14 large exec results (past the aggregate budget), then 4 parallel results with the provider reporting the session just under the proactive threshold. This puts the next request past the window. The journey now allows breaks only at compactions and requires that this step compacts. A debug probe on main showed that this step reachesroute=truncate_tool_results_only. On main the journey still passes, because the trim falls back to compaction as above. The journey makes sure the outcome stays a compaction.Focused tests:
preemptive-compaction.test.ts: sent results over the aggregate budget with a small overflow now route tocompact_only(on main:truncate_tool_results_only; the test fails on main).tool-result-truncation.test.ts: a session rewrite withpreserveSentToolResultskeeps the sent results byte for byte and still caps the unsent oversized tail.truncate_tool_results_only/compact_then_truncate) are unchanged and green.