Repository navigation
fix: prevent premature context overflow after compaction - #149462
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. Reviewed September 15, 2026, 10:00 PM ET / September 16, 2026, 02:00 UTC (Revision 5). ClawSweeper reviewWhat this changesUses matching provider measurements to budget compacted conversations, routes predicted pressure through native compaction, and preserves pending requests and useful recovery errors. Merge readiness✅ Ready for maintainer review This PR remains necessary: current main still discards unbound post-compaction measurements. The reviewed patch addresses the linked failure, has relevant real API evidence, and introduces no identified blocking defect. Priority: P1 Review scores
Verification
How this fits togetherOpenClaw’s compaction system prepares long conversations for the next model request. It combines saved conversation checkpoints, provider token measurements, and new input to decide whether to continue or compact. flowchart TD
A[Saved conversation and checkpoint] --> C[Validate measured request prefix]
B[Provider token measurement] --> C
C --> D[Estimate new input and request overhead]
D --> E{Fits context budget?}
E -->|Yes| F[Continue model request]
E -->|No| G[Native budget compaction]
G -->|Unavailable or failed| H[Client compaction preserving pending request]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +308, Tests +785, Docs +14. Total +1107 across 27 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Technical reviewBest possible solution: Keep measurement validation in the transport owner and reuse existing compaction recovery, preserving conservative fallback for older or edited history. Do we have a high-confidence way to reproduce the issue? Yes, source establishes the failure path: current main discards post-checkpoint measurements and estimates the retained tail. The supplied controlled regressions and real API comparison support it; this read-only review did not execute them. Is this the best way to solve the issue? Yes. Binding measurements to replayed content repairs the accounting owner, while existing endpoint and client-compaction paths handle pressure without replacing stored preferences or conversation history. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 83f948498fde. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (4 earlier review cycles)
|
f288b6e to
ff72b50
Compare
Bind measured Responses usage to the admitted replay prefix and persisted assistant output, including streamed reasoning and pending tool results. Keep legacy pressure counts complete, route predicted pressure through native budget compaction, and preserve actionable failure detail and pending requests. Fixes #149425
Skip optional measurement binding for string input and absent terminal output. Keep compaction failure guidance and completed-tool non-replay assertions aligned with budget recovery.
ff72b50 to
3c10530
Compare
|
Merged via squash.
|
…9462) * fix(agents): prevent premature context overflow after compaction Bind measured Responses usage to the admitted replay prefix and persisted assistant output, including streamed reasoning and pending tool results. Keep legacy pressure counts complete, route predicted pressure through native budget compaction, and preserve actionable failure detail and pending requests. Fixes openclaw#149425 * refactor(ai): keep compaction validation within existing contracts * fix: preserve response success when checkpoint usage is unavailable Skip optional measurement binding for string input and absent terminal output. Keep compaction failure guidance and completed-tool non-replay assertions aligned with budget recovery.
…checkpoint (#206918) ## What Problem This Solves After a provider compaction checkpoint (OpenAI Responses or Anthropic server compaction), OpenClaw ignores the provider's own token count for the rest of the window. It estimates the whole window locally and adds a 1.2 safety margin. So long sessions: - compact early; - have prompts refused that the provider would accept ("Context overflow: prompt too large for the model (precheck)"). Production signal (a production deployment, 2.76 days of Gateway logs, read-only): - 186 `[context-overflow-diag]` lines, all from OpenClaw's own precheck (`source=promptError trigger=budget compactionAttempts=0`): - 137 "Context maintenance scheduled before the next model request" (compaction triggers); - 49 "prompt too large for the model (precheck)" hard refusals. - 103 "predicted context pressure persisted after in-attempt compaction". - Paired with the session's previous provider-reported prompt (input + cache read + cache write), the estimate was a median 1.18× the provider count (p25 1.10, p75 1.22). Every Sol/Astra hard refusal had a provider-measured previous prompt below the 902k budget. - All 162 paired assistant records carried `usage.contextUsage.state = "available"`. Only 6 carried the wire-prefix binding that the replay path requires before it trusts that number. Related: #203594 (estimate above the provider-reported prompt). #149462 added the binding for this symptom. It records only when the request carried a compaction item and no `previous_response_id`, and not after WebSocket input replay, steering or retries. It never records for Anthropic. In production it applied to 4% of measured turns. Reproduced on main (`e3bf9e7d0216`): a Responses window with a compaction checkpoint and a later assistant measured at 2,001 tokens (no binding) estimates **40,910** tokens. The new test is red on main. ## Fix The owner is `resolveCompactionReplayPressure`: - It now strips usage only from: - the checkpoint owner, whose request predates its own replacement window; - later assistants on another provider/api/model (another route measures its own window); - a response whose recorded delivery order moved earlier input after it (`openclawResponsesInputReplay.after`, e.g. a steering response sent before a deferred tool result). Its total does not cover everything before it. Other later same-route usage stays. - The existing measured-boundary rule (`resolveProviderContextBoundary`, already used by the non-replay path) anchors on the latest measured assistant, and only content after it is estimated with the 1.2 margin. Same anchor, same rule, both paths. - Current tool definitions are still reserved on top of a measured replay anchor, as on main: tools enabled after the measured request are not in its total. - Async tool results persisted between a response's fragments and its terminal usage record were not in that response's request. The shared boundary counts them as new input (by matching `responseId`). This also fixes the same undercount in the non-replay path on main. Deleted: - `openai-responses-context-usage.ts`: the wire-prefix fingerprint binding (`recordResponsesContextUsage`, `resolveResponsesContextUsageBoundary`, `takeResponsesContextUsageInput`); - its `contextUsageEligible` plumbing in the Responses client and the three recording call sites; - the admission conversion handoff that only existed to share the binding's conversion; - three perf scripts that measured the binding; - tests that asserted the binding contract. Accepted edge cases (named, not coded): - If server compaction was toggled off for a turn, that turn's usage covers full history and overcounts the next replayed window. This is the conservative direction: at worst one early compaction. ## User impact - Gateway and one-shot (`agent --local`) users on the embedded runtime, in any session that has a provider compaction checkpoint. Pressure goes through `estimateTranscriptBoundaryTokenPressure` (`src/agents/embedded-agent-runner/run/preemptive-compaction.ts`) from the attempt preflight and the mid-turn precheck. - On the production pairs above, the replay-path estimate falls by a median 14.9% (hard refusals) and 14.6% (maintenance triggers), back to the provider's count plus the margin on new content only. - No config change. ## Evidence - `src/agents/embedded-agent-runner/run/preemptive-compaction.replay.test.ts`: "anchors on provider-measured usage after the checkpoint without a saved wire binding". Main: 40,910; this PR: 2,001 to 2,100. The checkpoint owner's own pre-compaction usage never anchors. - `provider-compaction-replay.test.ts` and `anthropic-transport-stream.compaction.test.ts` now assert that later measured usage is kept after a restart round trip. - Design reviewed once before coding (one-anchor rule vs extending the binding per transport); the one-anchor rule was chosen because the binding protected prefix identity, while pressure needs only size within the margin. - Importers of every changed source (68 files, provider live tests excluded) pass after updating the three tests that asserted the binding. All core, packages and root typecheck shards pass. - Size: 17 files, +96 / −1,727 lines (production +56 / −351). Co-authored-by: Ayaan Zaidi <[email protected]>
…checkpoint (#206918) After a provider compaction checkpoint (OpenAI Responses or Anthropic server compaction), OpenClaw ignores the provider's own token count for the rest of the window. It estimates the whole window locally and adds a 1.2 safety margin. So long sessions: - compact early; - have prompts refused that the provider would accept ("Context overflow: prompt too large for the model (precheck)"). Production signal (a production deployment, 2.76 days of Gateway logs, read-only): - 186 `[context-overflow-diag]` lines, all from OpenClaw's own precheck (`source=promptError trigger=budget compactionAttempts=0`): - 137 "Context maintenance scheduled before the next model request" (compaction triggers); - 49 "prompt too large for the model (precheck)" hard refusals. - 103 "predicted context pressure persisted after in-attempt compaction". - Paired with the session's previous provider-reported prompt (input + cache read + cache write), the estimate was a median 1.18× the provider count (p25 1.10, p75 1.22). Every Sol/Astra hard refusal had a provider-measured previous prompt below the 902k budget. - All 162 paired assistant records carried `usage.contextUsage.state = "available"`. Only 6 carried the wire-prefix binding that the replay path requires before it trusts that number. Related: #203594 (estimate above the provider-reported prompt). #149462 added the binding for this symptom. It records only when the request carried a compaction item and no `previous_response_id`, and not after WebSocket input replay, steering or retries. It never records for Anthropic. In production it applied to 4% of measured turns. Reproduced on main (`e3bf9e7d0216`): a Responses window with a compaction checkpoint and a later assistant measured at 2,001 tokens (no binding) estimates **40,910** tokens. The new test is red on main. The owner is `resolveCompactionReplayPressure`: - It now strips usage only from: - the checkpoint owner, whose request predates its own replacement window; - later assistants on another provider/api/model (another route measures its own window); - a response whose recorded delivery order moved earlier input after it (`openclawResponsesInputReplay.after`, e.g. a steering response sent before a deferred tool result). Its total does not cover everything before it. Other later same-route usage stays. - The existing measured-boundary rule (`resolveProviderContextBoundary`, already used by the non-replay path) anchors on the latest measured assistant, and only content after it is estimated with the 1.2 margin. Same anchor, same rule, both paths. - Current tool definitions are still reserved on top of a measured replay anchor, as on main: tools enabled after the measured request are not in its total. - Async tool results persisted between a response's fragments and its terminal usage record were not in that response's request. The shared boundary counts them as new input (by matching `responseId`). This also fixes the same undercount in the non-replay path on main. Deleted: - `openai-responses-context-usage.ts`: the wire-prefix fingerprint binding (`recordResponsesContextUsage`, `resolveResponsesContextUsageBoundary`, `takeResponsesContextUsageInput`); - its `contextUsageEligible` plumbing in the Responses client and the three recording call sites; - the admission conversion handoff that only existed to share the binding's conversion; - three perf scripts that measured the binding; - tests that asserted the binding contract. Accepted edge cases (named, not coded): - If server compaction was toggled off for a turn, that turn's usage covers full history and overcounts the next replayed window. This is the conservative direction: at worst one early compaction. - Gateway and one-shot (`agent --local`) users on the embedded runtime, in any session that has a provider compaction checkpoint. Pressure goes through `estimateTranscriptBoundaryTokenPressure` (`src/agents/embedded-agent-runner/run/preemptive-compaction.ts`) from the attempt preflight and the mid-turn precheck. - On the production pairs above, the replay-path estimate falls by a median 14.9% (hard refusals) and 14.6% (maintenance triggers), back to the provider's count plus the margin on new content only. - No config change. - `src/agents/embedded-agent-runner/run/preemptive-compaction.replay.test.ts`: "anchors on provider-measured usage after the checkpoint without a saved wire binding". Main: 40,910; this PR: 2,001 to 2,100. The checkpoint owner's own pre-compaction usage never anchors. - `provider-compaction-replay.test.ts` and `anthropic-transport-stream.compaction.test.ts` now assert that later measured usage is kept after a restart round trip. - Design reviewed once before coding (one-anchor rule vs extending the binding per transport); the one-anchor rule was chosen because the binding protected prefix identity, while pressure needs only size within the margin. - Importers of every changed source (68 files, provider live tests excluded) pass after updating the three tests that asserted the binding. All core, packages and root typecheck shards pass. - Size: 17 files, +96 / −1,727 lines (production +56 / −351). Co-authored-by: Ayaan Zaidi <[email protected]> (cherry picked from commit 60b37b1) Backport adaptation: Remove the obsolete usage-binding owner and release-only benchmark/hash tests; preserve the release observer transport entry point and keep the source regression cases. Co-authored-by: RomneyDa <[email protected]>
…checkpoint (openclaw#206918) ## What Problem This Solves After a provider compaction checkpoint (OpenAI Responses or Anthropic server compaction), OpenClaw ignores the provider's own token count for the rest of the window. It estimates the whole window locally and adds a 1.2 safety margin. So long sessions: - compact early; - have prompts refused that the provider would accept ("Context overflow: prompt too large for the model (precheck)"). Production signal (a production deployment, 2.76 days of Gateway logs, read-only): - 186 `[context-overflow-diag]` lines, all from OpenClaw's own precheck (`source=promptError trigger=budget compactionAttempts=0`): - 137 "Context maintenance scheduled before the next model request" (compaction triggers); - 49 "prompt too large for the model (precheck)" hard refusals. - 103 "predicted context pressure persisted after in-attempt compaction". - Paired with the session's previous provider-reported prompt (input + cache read + cache write), the estimate was a median 1.18× the provider count (p25 1.10, p75 1.22). Every Sol/Astra hard refusal had a provider-measured previous prompt below the 902k budget. - All 162 paired assistant records carried `usage.contextUsage.state = "available"`. Only 6 carried the wire-prefix binding that the replay path requires before it trusts that number. Related: openclaw#203594 (estimate above the provider-reported prompt). openclaw#149462 added the binding for this symptom. It records only when the request carried a compaction item and no `previous_response_id`, and not after WebSocket input replay, steering or retries. It never records for Anthropic. In production it applied to 4% of measured turns. Reproduced on main (`e03f4aa4d888`): a Responses window with a compaction checkpoint and a later assistant measured at 2,001 tokens (no binding) estimates **40,910** tokens. The new test is red on main. ## Fix The owner is `resolveCompactionReplayPressure`: - It now strips usage only from: - the checkpoint owner, whose request predates its own replacement window; - later assistants on another provider/api/model (another route measures its own window); - a response whose recorded delivery order moved earlier input after it (`openclawResponsesInputReplay.after`, e.g. a steering response sent before a deferred tool result). Its total does not cover everything before it. Other later same-route usage stays. - The existing measured-boundary rule (`resolveProviderContextBoundary`, already used by the non-replay path) anchors on the latest measured assistant, and only content after it is estimated with the 1.2 margin. Same anchor, same rule, both paths. - Current tool definitions are still reserved on top of a measured replay anchor, as on main: tools enabled after the measured request are not in its total. - Async tool results persisted between a response's fragments and its terminal usage record were not in that response's request. The shared boundary counts them as new input (by matching `responseId`). This also fixes the same undercount in the non-replay path on main. Deleted: - `openai-responses-context-usage.ts`: the wire-prefix fingerprint binding (`recordResponsesContextUsage`, `resolveResponsesContextUsageBoundary`, `takeResponsesContextUsageInput`); - its `contextUsageEligible` plumbing in the Responses client and the three recording call sites; - the admission conversion handoff that only existed to share the binding's conversion; - three perf scripts that measured the binding; - tests that asserted the binding contract. Accepted edge cases (named, not coded): - If server compaction was toggled off for a turn, that turn's usage covers full history and overcounts the next replayed window. This is the conservative direction: at worst one early compaction. ## User impact - Gateway and one-shot (`agent --local`) users on the embedded runtime, in any session that has a provider compaction checkpoint. Pressure goes through `estimateTranscriptBoundaryTokenPressure` (`src/agents/embedded-agent-runner/run/preemptive-compaction.ts`) from the attempt preflight and the mid-turn precheck. - On the production pairs above, the replay-path estimate falls by a median 14.9% (hard refusals) and 14.6% (maintenance triggers), back to the provider's count plus the margin on new content only. - No config change. ## Evidence - `src/agents/embedded-agent-runner/run/preemptive-compaction.replay.test.ts`: "anchors on provider-measured usage after the checkpoint without a saved wire binding". Main: 40,910; this PR: 2,001 to 2,100. The checkpoint owner's own pre-compaction usage never anchors. - `provider-compaction-replay.test.ts` and `anthropic-transport-stream.compaction.test.ts` now assert that later measured usage is kept after a restart round trip. - Design reviewed once before coding (one-anchor rule vs extending the binding per transport); the one-anchor rule was chosen because the binding protected prefix identity, while pressure needs only size within the margin. - Importers of every changed source (68 files, provider live tests excluded) pass after updating the three tests that asserted the binding. All core, packages and root typecheck shards pass. - Size: 17 files, +96 / −1,727 lines (production +56 / −351). Co-authored-by: Ayaan Zaidi <[email protected]>
Closes #149425
What Problem This Solves
Fixes long-running Responses sessions refusing a follow-up because a conservative checkpoint estimate triggers premature context overflow and slow client compaction.
User Impact
Sessions can continue using measured context usage after compaction. Predicted pressure can use the public OpenAI compact endpoint automatically; manual compaction, explicit endpoint opt-outs, and provider-confirmed overflow retain their existing behavior. Failed recovery preserves the pending request and reports the actual compaction failure. No configuration or database migration is required.
Why This Change Was Made
The transport binds usage to the admitted request and the assistant representation actually saved for replay. Matching history uses that measurement plus estimated new input and current request overhead; changed checkpoints, input, or provider identity fall back to estimation. Canonical input ordering accounts for tool results saved before the final usage event. The existing pressure helper still includes the complete prefix count for older callers.
Budget recovery is distinct from a provider rejection, allowing the existing native compactor to handle predicted pressure. Client fallback preserves the unresolved request, and structured errors no longer collapse to “Agent run failed.” Session and writer authority checks remain intact.
Evidence
/resetexpectation; the corrected integration suite passed all 120 checks while retaining once-only execution and completed-tool non-replay. Two additional red/green cases preserve successful responses for payload-hook string input and missing terminal output; all 32 transport/pressure siblings pass.pnpm buildpassed before the follow-ups; each follow-up passed its selected changed checks. The three compaction commits are patch-identical after refreshing from main. The real API case passed again on3c105301344efab2a942fc34d17e56614785afae, and required hosted CI passed on that exact head. Live evidence uses isolated synthetic sessions against the real API; no operator Gateway was deployed or restarted.