Repository navigation
fix(agents): move the model-context history window only at compaction - #203536
Conversation
Attempts hydrated history through a contextTokenBudget x 8 byte cut. Opaque replay bytes reach it far below the token budget, so each new attempt dropped the oldest turns, broke the prompt-cache prefix and hid history from the compaction estimate. The hydration cap is now a fixed 16 MiB memory guard; token compaction is the only step that shortens model-visible history. 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 replaces the embedded runtime’s token-scaled history byte cap with a fixed 16 MiB guard and adds screenshot-heavy prefix-stability coverage. Example: A 64,000-token session reads four screenshots and continues across new attempts.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review This PR addresses a current history-replay defect with a focused shared-owner change and relevant live evidence; no actionable introduced bug was found. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe embedded runner loads saved transcript history through a shared bounded selector before preparing provider requests; token compaction summarizes history when context pressure requires it. flowchart TD
A[Saved transcript] --> B[Shared history guard]
B --> C[Embedded attempt]
C --> D[Provider request]
D --> A
C --> E[Token compaction]
E --> A
Technical reviewBest possible solution: Land the shared-limit repair once the existing head CI gate passes. Do we have a high-confidence way to reproduce the issue? Current-main source confirms the premature byte-window path, and the PR supplies matching base/head Gateway observations and regression controls; no target code was executed during this read-only review. Is this the best way to solve the issue? The change is a small repair at the existing hydration owner, preserves established selector safeguards, and explicitly documents the exceptional guard behavior. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against f56171778657. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource -6, Tests +61, Docs -3. Total +52 across 10 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. Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed November 22, 2026, 11:10 AM ET / 16:10 UTC. |
|
Landed as 6198f78. Bug: every new attempt reloaded history through a contextTokenBudget x 8 byte cut, so opaque-heavy sessions lost their oldest turns and their prompt cache on each request=1. Fix: hydration uses a fixed 16 MiB memory guard, and token compaction is the only step that shortens history. Proof: the new prefix-journey step is red on base and green on head on all 5 transports, and red again when the old cap is restored. Scratch Gateway, native OpenAI Responses: base had 2 history_shorter replays (cached 16430 = instructions+tools only); head had 12/12 requests continued. |
Result: plugin harnesses (Codex app-server, Agents API, Muse) now read session history with the same guard as the embedded runner. Their history keeps everything since the latest compaction and only grows between compactions. Follow-up to #203536. ## What Problem This Solves `resolveAgentHarnessHistoryLimits` (Plugin SDK) still computed its own byte cap: `contextTokenBudget × 8`. Each Codex hook/continuity read, Agents API prompt-hook read and Muse session transfer therefore cut the oldest turns once history passed 8 bytes per budget token. Reasoning, images and tool payloads reach that size far below the token budget. Each new attempt reread and cut the history again, so it was rewritten outside compaction. This is the same class #203536 fixed for the embedded runner. ## Why This Change Was Made - `resolveAgentHarnessHistoryLimits` now returns `resolveEmbeddedSessionContextLimits({})` (16 MiB / 10,000 events) plus its existing `toolResultOverflow: "omit"`. There is one owner for the bound, and the duplicate budget-based computation is gone. - The export keeps its name and signature. Its `contextTokenBudget` argument is still accepted, but it is **deprecated and ignored** (documented in the doc comment and in `docs/plugins/sdk-agent-harness/attempt-runtime.md`). - Bundled callers stop passing it. Codex drops the `contextTokenBudget` argument from `readCodexMirroredSessionHistoryMessages` / `readMirroredSessionHistoryMessages`. Agents API drops the limits from its history-reuse scope key: the limits are now constant, so a budget change no longer forces a fresh read. Muse calls it with no argument. - No schema, protocol or dependency change. Tests that asserted the removed budget cut are deleted or rewritten: - Codex `session-history.test.ts`: the budget-128 cut and budget-512 omission tests are replaced by the regression test below. - `run-attempt.bounded-continuity.test.ts`: the "assistant-only bounded suffix" case is kept. Its user turn is now larger than the 16 MiB guard, so it still covers the fallback past the guard. - Agents API: the "new budget" retry case is removed, and the pinned `maxBytes: 256_000` assertion is removed. ## Evidence Regression test through the Codex harness history consumer (`readCodexMirroredSessionHistoryMessages`): 1.3 MB of history, which is past the old default-budget cut and far below compaction. Two consecutive reads with a new turn appended between them. - Base `2754763da236`: red, `expected … to have a length of 43 but got 25` (the oldest turns were cut). - Head: green. All 43 messages are returned, and the second read extends the first one exactly. - Mutation: head with the harness cap set back to `128_000 × 8` is red again (the same 25-message cut). Tests: the touched test files plus every test file that imports a changed source (25 files), oxfmt/oxlint on the changed files, and `pnpm check:changed`. ## What Changes for Users Codex, Agents API and Muse sessions with reasoning, screenshots or large tool output keep their whole history (and the provider cache prefix) until compaction. Before, old turns dropped silently on each attempt. ## Merge danger Two-way door. A revert restores the budget-based cut. Third-party plugins that pass a budget get the shared guard; their call still compiles. 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]>
Result: plugin harnesses (Codex app-server, Agents API, Muse) now read session history with the same guard as the embedded runner. Their history keeps everything since the latest compaction and only grows between compactions. Follow-up to openclaw#203536. ## What Problem This Solves `resolveAgentHarnessHistoryLimits` (Plugin SDK) still computed its own byte cap: `contextTokenBudget × 8`. Each Codex hook/continuity read, Agents API prompt-hook read and Muse session transfer therefore cut the oldest turns once history passed 8 bytes per budget token. Reasoning, images and tool payloads reach that size far below the token budget. Each new attempt reread and cut the history again, so it was rewritten outside compaction. This is the same class openclaw#203536 fixed for the embedded runner. ## Why This Change Was Made - `resolveAgentHarnessHistoryLimits` now returns `resolveEmbeddedSessionContextLimits({})` (16 MiB / 10,000 events) plus its existing `toolResultOverflow: "omit"`. There is one owner for the bound, and the duplicate budget-based computation is gone. - The export keeps its name and signature. Its `contextTokenBudget` argument is still accepted, but it is **deprecated and ignored** (documented in the doc comment and in `docs/plugins/sdk-agent-harness/attempt-runtime.md`). - Bundled callers stop passing it. Codex drops the `contextTokenBudget` argument from `readCodexMirroredSessionHistoryMessages` / `readMirroredSessionHistoryMessages`. Agents API drops the limits from its history-reuse scope key: the limits are now constant, so a budget change no longer forces a fresh read. Muse calls it with no argument. - No schema, protocol or dependency change. Tests that asserted the removed budget cut are deleted or rewritten: - Codex `session-history.test.ts`: the budget-128 cut and budget-512 omission tests are replaced by the regression test below. - `run-attempt.bounded-continuity.test.ts`: the "assistant-only bounded suffix" case is kept. Its user turn is now larger than the 16 MiB guard, so it still covers the fallback past the guard. - Agents API: the "new budget" retry case is removed, and the pinned `maxBytes: 256_000` assertion is removed. ## Evidence Regression test through the Codex harness history consumer (`readCodexMirroredSessionHistoryMessages`): 1.3 MB of history, which is past the old default-budget cut and far below compaction. Two consecutive reads with a new turn appended between them. - Base `319099fbfe2d`: red, `expected … to have a length of 43 but got 25` (the oldest turns were cut). - Head: green. All 43 messages are returned, and the second read extends the first one exactly. - Mutation: head with the harness cap set back to `128_000 × 8` is red again (the same 25-message cut). Tests: the touched test files plus every test file that imports a changed source (25 files), oxfmt/oxlint on the changed files, and `pnpm check:changed`. ## What Changes for Users Codex, Agents API and Muse sessions with reasoning, screenshots or large tool output keep their whole history (and the provider cache prefix) until compaction. Before, old turns dropped silently on each attempt. ## Merge danger Two-way door. A revert restores the budget-based cut. Third-party plugins that pass a budget get the shared guard; their call still compiles. 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]>
…1766) (cherry picked from commit 9156690) Release adaptation: Keep the stable full-prefix test. Exercise in-budget and omitted tool results using stable’s 16 MiB cap; stable no longer sizes this context from contextTokenBudget. Companion audit: #204028, #203901, #202306 and #203536 are separate finalizer-budget, custody, project-transfer and context-window changes; not dependencies of the timestamp guard. Co-authored-by: RomneyDa <[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]>
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 throughselectBoundedModelRequestswith a byte cap ofcontextTokenBudget × 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 becomeshistory_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.
resolveEmbeddedSessionContextLimitsreturns 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.contextTokenBudgetplumbing that existed only for this cap is removed (prepareRecoverySession,readCompactionTranscriptBytes,readPreflightTranscriptContextMessages).selectBoundedModelRequestsand its fallbacks (quarter-cap steps, fix: next turn starts blank when the previous turn exceeds the byte cap #191146 trailing prompt, fix: keep a sub-agent's task when a retry reloads oversized history #201636 in-turn request reservation). They now run only past the 16 MiB guard. The settled-tool finalizer keepstoolResultOverflow: "omit"(fix(agents): keep the turn's request in a bounded summary view after large tool results #184704). With the larger guard, it keeps every result body in every case that fit before.Accepted edge cases, without code:
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.8d1e59c2fddc: red on all 5 transports (anthropic, bedrock, google, openai-completions, openai-responses), with twomessage 0breaks each.budget × 8cap 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 andresponse.completedusage were captured.continuedhistory_shorter, msg 1 moved, 10 items sent in fullcontinued, 2 items sentcontinuedcontinuedhistory_shorter, msg 1 moved, 13 items sent in fullcontinued, 2 items sentcontinuedcontinued16430 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: obviyus [email protected]