Skip to content

fix: prevent premature context overflow after compaction - #149462

Merged
steipete merged 3 commits into
mainfrom
codex/compaction-checkpoint-recovery
Sep 16, 2026
Merged

steipete merged 3 commits into
mainfrom
codex/compaction-checkpoint-recovery

Conversation

@steipete

@steipete steipete commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Controlled red/green regressions cover premature estimates, persisted replay, stale bindings, streaming tool results, current tool overhead, native budget routing, pending-request preservation, and failure detail.
  • Real OpenAI API: five inference requests and two native budget compactions, with actual tool calls, 24 KB synthetic results, complete persisted-entry reloads, and exact durable-marker recall after both cycles. Checkpoint-aware pressure was 4,301 / 4,422 tokens, versus 15,375 / 15,728 without the binding.
  • Live testing exposed different encrypted reasoning in streamed items and terminal snapshots. The fix binds the persisted representation, with a corresponding offline regression.
  • Focused suites passed: 330 recovery/lifecycle checks and 92 transport/pressure checks; affected core and test typechecks passed. Independent P0–P2 review is clean.
  • CI exposed a stale /reset expectation; 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.
  • The PR contains only the compaction repair. Newer main fixture changes were checked separately: all 93 wrapper cases passed on the composed merge tree, including repeated dependency setup and alias trust/refusal behavior. The first local integration attempt exhausted host disk space; the full retry passed after clearing expendable cache space.
  • The complete changed-file check and pnpm build passed 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 on 3c105301344efab2a942fc34d17e56614785afae, 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.

@clawsweeper

clawsweeper Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@steipete
steipete marked this pull request as ready for review September 15, 2026 21:57
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Sep 15, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 15, 2026
@clawsweeper

clawsweeper Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 15, 2026, 10:00 PM ET / September 16, 2026, 02:00 UTC (Revision 5).

ClawSweeper review

What this changes

Uses 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
Reviewed head: 3c105301344efab2a942fc34d17e56614785afae

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A coherent owner-level repair with relevant live evidence and focused regressions; no blocking finding remains.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The captured real OpenAI run exercises the production transport and native budget compactor through two saved-entry reload cycles, preserves exact marker recall, and demonstrates lower checkpoint-aware pressure; the body reports a successful rerun on the reviewed head.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured real OpenAI run exercises the production transport and native budget compactor through two saved-entry reload cycles, preserves exact marker recall, and demonstrates lower checkpoint-aware pressure; the body reports a successful rerun on the reviewed head.
Evidence reviewed 10 items Introduced change ownership: The host verified the merge-base-to-head delta and the two-parent test merge. The daemon changes are base-only work, and the wrapper fixture repair is absent from the introduced files.
Current main still needs the repair: Current main removes later contextUsage snapshots from checkpoint replay accounting and estimates the retained conversation instead. Its compact-endpoint policy also lacks the public OpenAI budget default.
Measurement binding and safe fallback: The producer records hashes and measured usage within existing replay metadata. The consumer checks provider, endpoint, session, profile, usage, and canonical prefix identity; absent or incompatible metadata falls back to estimation. String input and missing terminal output skip optional binding.
Findings None None.
Security None None.

How this fits together

OpenClaw’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]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +308, Tests +785, Docs +14. Total +1107 across 27 files.

View PR surface stats
Area Files Added Removed Net
Source 13 418 110 +308
Tests 10 999 214 +785
Docs 4 19 5 +14
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 27 1436 329 +1107

Review metrics

Metric Value Why it matters
Compaction default 1 default changed; 0 new configuration options Public OpenAI budget compaction becomes automatic while preserving the existing explicit opt-out and manual behavior.
Production versus regression coverage Production +308 net lines; tests and support +785 Production growth implements request-bound accounting, supported by transport, persistence-roundtrip, and recovery regressions.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #149425
Summary: This PR is the explicit implementation candidate for the premature-overflow issue; the linked persistence-scale issue has a distinct remaining scope.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best 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.

Labels

Label justifications:

  • P1: Premature overflow prevents follow-ups in existing long-running Responses sessions.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The captured real OpenAI run exercises the production transport and native budget compactor through two saved-entry reload cycles, preserves exact marker recall, and demonstrates lower checkpoint-aware pressure; the body reports a successful rerun on the reviewed head.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured real OpenAI run exercises the production transport and native budget compactor through two saved-entry reload cycles, preserves exact marker recall, and demonstrates lower checkpoint-aware pressure; the body reports a successful rerun on the reviewed head.

Evidence

What I checked:

  • Introduced change ownership: The host verified the merge-base-to-head delta and the two-parent test merge. The daemon changes are base-only work, and the wrapper fixture repair is absent from the introduced files. (3c105301344e)
  • Current main still needs the repair: Current main removes later contextUsage snapshots from checkpoint replay accounting and estimates the retained conversation instead. Its compact-endpoint policy also lacks the public OpenAI budget default. (packages/ai/src/transports/provider-compaction-replay.ts:169, 83f948498fde)
  • Measurement binding and safe fallback: The producer records hashes and measured usage within existing replay metadata. The consumer checks provider, endpoint, session, profile, usage, and canonical prefix identity; absent or incompatible metadata falls back to estimation. String input and missing terminal output skip optional binding. (packages/ai/src/transports/openai-responses-context-usage.ts:50, 3c105301344e)
  • Default and compatibility boundaries: The new default requires budget purpose, the OpenAI provider, the canonical Responses API, and the public endpoint. Explicit false remains authoritative, manual defaults remain unchanged, and endpoint failures retain client recovery. Tests cover old checkpoints, preserved transcripts, opt-outs, and excluded routes. (packages/ai/src/transports/openai-responses-payload-policy.ts:235, 3c105301344e)
  • Recovery and security invariants: Budget recovery uses the existing admitted compaction owner and transcript-write guards. The new pending-request flag conveys recovery state rather than authorization. Structured lifecycle errors still pass through the existing sensitive-text redactor, with expanded regression coverage. (src/agents/embedded-agent-runner/run/compaction-runtime.ts:232, 3c105301344e)
  • Real API proof mapped to production owners: The captured PR body reports five real inference requests, two native budget compactions, saved-entry reloads, real tool calls, and exact marker recall after both cycles. Reported pressure was 4,301/4,422 tokens versus 15,375/15,728 without binding, with a rerun on the reviewed head. The inspected live case calls the production transport, endpoint compactor, session-entry reload, and pressure decision. Reload proof uses serialized in-memory entries, not a deployed Gateway or database upgrade. (src/agents/sessions/agent-session.openai-compaction.live.test.ts:185, 3c105301344e)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • SunnyShu: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (4 earlier review cycles)
  • reviewed 2026-09-15T22:48:19.300Z sha 344d9616b0618aaf476c815009d6c7da44c47544 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-15T23:29:49.421Z sha 9deecca64a16d378cbb749b5418f0bdd0375019c :: needs maintainer review before merge. :: none
  • reviewed 2026-09-16T00:35:46.399Z sha f288b6e1d5e888f6a9a9ce6964765095849bac74 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-16T01:25:14.967Z sha ff72b50eb42670c5dd8d1c85c01d7e1739b8ed28 :: needs maintainer review before merge. :: none

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.
@steipete
steipete force-pushed the codex/compaction-checkpoint-recovery branch from ff72b50 to 3c10530 Compare September 16, 2026 01:48
@steipete
steipete merged commit 8432c13 into main Sep 16, 2026
200 checks passed
@steipete
steipete deleted the codex/compaction-checkpoint-recovery branch September 16, 2026 03:34
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 16, 2026
…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.
obviyus added a commit that referenced this pull request Nov 27, 2026
…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]>
tideclaw-bot pushed a commit that referenced this pull request Nov 28, 2026
…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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 28, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation maintainer Maintainer-authored PR P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Long Responses sessions can fail with premature context overflow

1 participant