Repository navigation
fix(compaction): large sessions wait minutes for compaction because summary work grows with the context window - #167916
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. |
f750b6e to
ca78382
Compare
|
Codex review: needs maintainer review before merge. What this changesCompaction, which summarizes older conversation history, uses bounded summarizer input to reduce delays and model costs in large sessions. Example: A user continues the recorded 1,250-message conversation.
Review scores
ProductKind: Performance · Worth it: Yes Merge readiness✅ Ready for maintainer review This PR addresses a measured latency problem that remains on current main. The previous findings remain resolved after the merge, and no additional actionable defect was found. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherCompaction prepares older conversation history for a model-generated summary while retaining recent context and the stored transcript. Built-in summaries pass through shared request budgeting and safeguard quality checks before the conversation continues. flowchart TD
A[Conversation history] --> B[Compaction preparation]
B --> C{Summary provider}
C --> D[Plugin receives full history]
C --> E[Built-in bounded history sample]
E --> F[Model summary request]
D --> G[Summary checks]
F --> G
G --> H[Conversation continues]
Technical reviewBest possible solution: Keep bounded summarization at the shared completion owner with provider-aware reservations and the documented sampling tradeoff. Do we have a high-confidence way to reproduce the issue? Yes: current main scales serial summary work with the context window, and the supplied seeded-session live comparison demonstrates the delay. This read-only review did not execute target code. Is this the best way to solve the issue? Yes: the shared completion owner bounds the expensive model input and the branch removes the replaced planning pipeline. Existing cancellation, quality checks, provider delegation, and previous-summary handling remain intact. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 6eacab6c2940. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource -877, Tests -886, Docs -2, Generated 0, Other -7. Total -1772 across 47 files. Added test files: 1. View PR surface stats
Review metrics
LabelsLabel changes: No label changes. Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (5 earlier review cycles)
Reviewed October 9, 2026, 6:04 PM ET / 22:04 UTC (Revision 6). |
…h repeated call IDs
|
Landed as 1d09a03. Large sessions waited about 6 minutes for compaction (and often timed out) because the summary work grew with the context window: about 880k tokens through 5 serial requests on a 1M window. Compaction now makes one summary request with a bounded, sampled input: the newest messages verbatim, older user messages, the oldest messages and evenly spaced runs of the rest, with marked gaps and tool results labeled by their call. Proof: Telegram Test Server with real gpt-6-astra, compaction 370 s → 25 s and reply 454 s → 85 s on the same 963k-token seed; focused and migrated suites, full changed-lane checks, CI green and ClawSweeper ready on e01017a. |
Two reasons, both from the stale base: - The pr-fail-fast job checks out scripts/ci-pr-fail-fast.mjs from the pull request's recorded base, f6a3ed7 (2026-09-23), and main only gained that script in d53f229 (openclaw#156375, 2026-09-25), so the job fails with "Cannot find module" before it inspects this diff. - Main's 1d09a03 (openclaw#167916) renamed the safeguard's summarizer seam to summarizeCompactionHistory and its test hook to setSummarizeCompactionHistoryForTest. The textual merge is clean, but the quality-feedback suite then fails on "testing.setSummarizeInStagesForTest is not a function" (6 of 6) and the agents-other test graph on TS2305/TS2339. The suite now uses main's names; its assertions are unchanged. The branch still changes only compaction-safeguard-quality.ts and its quality-feedback suite.
|
Post-merge live check at the merged head
|
Main's 1d09a03 (openclaw#167916) reworked the safeguard under this branch and conflicted in four files: - compaction-safeguard.ts: main's imports stay, minus the two the tool-failure helpers took with them to their own module. - compaction-safeguard.test-support.ts: main's setSummarizeCompactionHistoryForTest seam stays; the two tool-failure entries are gone with the helpers. - compaction-safeguard.test.ts: main's fail-closed case stays replaced by the degraded-fallback suite. - assertion-safety-baseline.txt: compaction-safeguard.ts 11 -> 9, the same two casts that moved with the tool-failure helpers. Two changes the textual merge could not see: openclaw#167916 dropped effectivePreviousSummary with history pruning, so the degraded fallback builds from previousSummary, and the degraded-fallback suite uses the renamed summarizeCompactionHistory seam.
Main's 1d09a03 (openclaw#167916) renamed the safeguard's summarizer seam to summarizeCompactionHistory and its test hook to setSummarizeCompactionHistoryForTest. The textual merge is clean, but the summary-budget suite then fails 3 of 3 on "testing.setSummarizeInStagesForTest is not a function" and the agents-other test graph on TS2305/TS2339. The suite now uses main's names; its assertions are unchanged, and the fit guard and the runtime bounds move apply to main's reworked safeguard as they were.
…ummary work grows with the context window (openclaw#167916) Related: openclaw#164220, openclaw#164246, openclaw#164263, openclaw#130971 ## What Problem This Solves Fixes: on a large session, automatic compaction keeps the user waiting about six minutes, and often times out, because the summary work grows with the size of the context window. ## User Impact User impact: large sessions compact in about 25 seconds instead of about 6 minutes, and each compaction costs about 33k summary input tokens instead of about 700k. On a 1M-token window the user's next answer arrived in 85 s instead of 454 s. Timeouts like openclaw#164220, and the lossy no-summary fallback from openclaw#164246, become rare. No new config keys, messages, or warnings. Tradeoff (approved by the maintainer): when the history to summarize is larger than one request's budget, the summarizer sees a sample of it, not every message. The newest messages stay verbatim; the user's older messages (asks, decisions, corrections) come next and are all kept when they fit; then the oldest messages and evenly spaced runs of the rest. Every gap is marked with the number of messages left out. The transcript still stores every message; only the summarizer input is bounded. Histories that fit the budget are summarized exactly as before, byte for byte. ## Why This Change Was Made **Root cause.** Compaction fires at `contextWindow − reserveTokens` (about 984k tokens on a 1M window) and keeps only `keepRecentTokens` (20k) verbatim, so about 880k tokens go to the summarizer. `summarizeInStages` then split that into two stages of sub-chunks sized at `contextWindow × 0.4`, summarized each serially with a running summary, and merged the parts: five serial reasoning-model requests (about 250k, 105k, 250k, 110k input tokens, then a merge). A failed quality audit repeated all five. Work, latency and cost grew linearly with the window, so every larger model made compaction slower. openclaw#163636 and openclaw#164263 stopped the watchdog from killing healthy requests and openclaw#164246 recovers from a real timeout; none of them reduced the work. **Fix.** - *One bounded request* (agent-core `runSummarizationCompletion`). The conversation input is capped at 160,000 CJK-weighted characters, lowered to fit the summarizer's own context window next to the system prompt, the previous summary, the instructions and the output reservation. `serializeConversationWithinBudget` (`utils.ts`) fills it in order: the newest entries verbatim (half; the newest entry keeps both ends when it alone is larger); older user messages (a quarter, each trimmed to at most 2,000 characters, spread evenly across the history when they do not all fit), because they carry the asks, decisions and corrections; the oldest entries (a tenth); and eight evenly spaced runs of the rest, trimmed to 6,000 characters each. Gap-marker cost is charged exactly, and the whole input never exceeds the budget. Gaps carry `[... N entries omitted ...]`, and the prompt tells the summarizer not to guess what they said and to keep the previous summary's facts. In sampled input each tool result names the call that produced it (`[Tool result of exec(cmd="...")]`), matched by call occurrence, because sampling can separate the two. - *Window budget:* the input budget reserves the largest completion the transport may request. `resolveCompletionTokenReservation` (`@openclaw/ai/transports`, next to `applyAnthropicThinkingOptions`) adds the thinking budget only for budget-based Anthropic Messages thinking; other transports keep `maxTokens` as the total output limit. A history that fits is always sent unchanged. When the prompt alone overflows the window, or the history must be sampled and the window leaves under 4,000 characters, the request returns a non-retried `SummaryOutputBudgetError` that names `agents.defaults.compaction.model`, without a model call. - *Callers:* `summarizeCompactionHistory` (`src/agents/compaction.ts`) replaces `summarizeInStages` and keeps its retry policy (3 attempts; caller abort, transport timeout and output-budget errors are terminal) and the `toolResult.details` and runtime-context stripping. The safeguard hook makes one call and passes the previous summary as `previousSummary`; the quality audit, corrective retries, split-turn prefix summary, preserved turns, and the openclaw#164246 timeout fallback are unchanged. - *Removed:* the stage split, sub-chunking, merge request, history-prune pass and its extra dropped-chunk summary, oversized-message and partial-summary fallbacks, adaptive chunk ratio, and the planning worker that only computed those plans (`compaction-planning-worker*.ts`, `compaction-planning.worker.ts`, `compaction-planning-projection.ts`) with its tsdown entry, knip entry and worker-kind registrations. Safeguard runtime fields `contextWindowTokens` and the unused `maxHistoryShare` are gone with the factory params that only fed them. - Docs: `docs/concepts/compaction.md` describes the bound and the sampling; config help and the provider docs no longer name `summarizeInStages`. ## Evidence ### Live: Telegram Test Server, real `gpt-6-astra` Same harness as openclaw#163636/openclaw#164263: real-user DM, built `dist` of each head, default context engine, default compaction settings (safeguard mode), a forwarding proxy that records timing only, and the same deterministic 1,250-message seed (3.53M chars, 901k estimated tokens). BEFORE = merge base `dc969b5aa2e4`, AFTER = `f750b6e5ca9c` (clean tree). The seed carries no provider usage, and current `main` no longer starts preflight compaction from the transcript estimate alone, so both runs also set the seeded session row's persisted usage to `totalTokens: 963000, totalTokensFresh: true` (transcript bytes unchanged). Both gateways then logged `preflightCompaction triggered: tokenCount=963040 threshold=902000 trigger=tokens`. | | before `dc969b5aa2e4` | after `f750b6e5ca9c` | | --- | --- | --- | | history summary requests | 5 serial: summarize, update, summarize, update, merge | 1 | | per request (body / input / duration) | 1.24 MB 38.5 s; 523 KB 47.5 s; 1.24 MB 73.0 s; 543 KB 91.3 s; merge 39 KB 111.9 s | 164 KB / 32,754 input tokens (provider usage) / 20.9 s | | compaction (`[compaction-diag] end`) | `outcome=compacted durationMs=370348`, plus `finalized artifact truncated; loss=summary-tail` | `outcome=compacted durationMs=25369`, no truncation | | after compaction | 30 messages, 23,333 est. tokens | 30 messages, 22,712 est. tokens | | question → visible reply | **454.5 s** | **85.4 s** | | reply | "Your last request concerned billing-api: splitting its lazy backfill job in Python. Next, look at the existing job implementation and tests; …" | "Your last request was to split the lazy backfill job in billing-api (Python). Next, look at its implementation and tests to identify safe split boundaries; …" | | follow-up 22 min later | answered in 13.0 s, no compaction | answered in 22.1 s, no compaction | AFTER's summary request carried 8 gap markers. BEFORE input tokens are estimated from body size at AFTER's measured 5.02 bytes per token (the BEFORE proxy did not capture usage of streams the client closes). Both runs also spent 36–52 s in the pre-compaction memory flush, which sends the full transcript and is outside this change. The seed has no tool calls, so the live run does not exercise the tool-result labels; the tests below do. **Re-run with user-message priority** (`2ed02d442b1`, same seed, override and trigger gate): still one history-summary request, 164,544 B and 33,235 provider input tokens, `outcome=compacted durationMs=54821`, normal answers to both questions, and no compaction on the follow-up. The request carried 112 of the span's 612 user-role entries (each trimmed to 400 characters at that density), 96 gap markers and 1,085 omitted entries. Two differences from `f750b6e5ca9c`: the summarizer wrote 2,762 output tokens instead of 1,092, so the request took 49.4 s instead of 20.9 s, and the safeguard's 16,000-character artifact cap clipped the summary tail again (`finalized artifact truncated; loss=summary-tail`, as on `main`). End-to-end reply latency (243.6 s) is not comparable: the host load average was 43–50 during that run, the gap between compaction end and the answer request alone was 40 s instead of 4.7 s, and the answer model request itself took 2.6 s. ### Tests New `packages/agent-core/src/harness/compaction/summarization-input-budget.test.ts`, through `generateSummary` and the serializer: - A small history is sent byte-identical to `serializeConversation`. - A 1,250-turn tool session (5.5M characters) produces one request within 160,000 weighted characters. The newest turn is verbatim, the oldest turn is present, gap counts plus kept entries equal the total, every kept tool result names its own call, and the previous summary and omission instruction are in the prompt. - A 32k window keeps prompt plus output inside the window. A 4k window with a large previous summary returns `SummaryOutputBudgetError` without a model call, for long and short histories alike, while a short history on a 4k window without that summary is still sent unchanged. Budgets below one gap marker send nothing. - Anthropic Messages with high thinking reserves the 16,384-token thinking budget on top of the output; an OpenAI request with the same settings reserves no thinking budget. - An oversized newest entry keeps both ends. A 1M-character mixed CJK/ASCII newest entry keeps an excerpt. - CJK text counts by token weight. - Tool-result naming across budgets 4,000–60,000, after the ninth-image omission note, with a 30,000-character argument, with a 24-call batch, with a user message between a call and its result, and with repeated call IDs (matched by occurrence through `createToolCallOccurrenceQueue`). - User priority: in a 400-turn tool-heavy history, all 400 user messages (including four decisions in the middle) reach the summarizer; with 2,000 long user messages that cannot all fit, every tenth of the history keeps some. Negative controls: each case above fails on the commit before its fix, except the "every tenth" spread case, which guards the stride against a newest-first regression and also passes on the earlier even sampling. Migrated suites (deleted tests covered only removed mechanisms; kept behavior moved to `summarizeCompactionHistory`): `compaction.summarize-fallback`, `compaction.summary-format`, `compaction.tool-result-details`, `compaction.identifier-preservation`, `compaction.abort-http`, `agent-hooks/compaction-safeguard*`, `embedded-agent-runner/compact.hooks`, `compact.summary-fallback`, `compact.small-context`, `extensions`, `agent-session-tool-result-redaction`, and `src/agents/sessions/` (small-window sessions). All pass, as does `node scripts/check-changed.mjs --base origin/main` (typecheck all lanes, oxlint, import cycles, ratchets, config docs baseline). ### Review `gpt-6-astra` review, eleven rounds on this branch. Rounds 1–6 found, and this branch fixed: a mixed CJK/ASCII newest entry could be dropped; an oversized newest entry lost its end; tiny summarizer windows could overflow or send markers only; a dead export; and four cases where a sampled tool result could lose its call. The last one led to the self-describing result labels. Round 7: **LAND, no findings**. Hosted review then found three more, fixed in `f55ae2a202f` and `2e7cc05cafd`: a short history was rejected on a tiny window before measuring it; budget-based Anthropic thinking adds its budget on top of `maxTokens`; repeated call IDs mislabeled results. Round 8 found that the first thinking fix also reserved thinking on OpenAI, so the reservation moved to the Anthropic transport owner. Round 9: **LAND, no findings**. `4786e7233fa` adds user-message priority (maintainer request). Round 10 found that when the prompt alone overflowed the window, closing the only gap refunded the marker cost and let a short history through; `2ed02d442b1` enforces the overall budget in every selection and rejects a negative budget. Round 11 on `2ed02d442b1`: **LAND, no findings**. Rebase: onto `a1f5076939b`. The only conflict was in `compaction-safeguard.ts`, where openclaw#167816 had folded the adaptive chunk-ratio code into a `resolveMaxChunkTokens` helper that this PR deletes, so the resolution keeps this branch's side. No overlap with Pash/Sarah changes: their commits on touched files only touch `docs/.generated/config-baseline.sha256` and an unrelated test in `compact.hooks.test.ts`. Merge danger: two-way door. No schema, stored-row, config or protocol change; a revert restores the staged pipeline. `@openclaw/ai/transports` gains one additive export, `resolveCompletionTokenReservation`. Blast radius: every built-in compaction summary (default and safeguard modes, manual `/compact`, preflight and overflow recovery). Histories that fit 160,000 characters (about 40k tokens) are unchanged; larger ones are summarized from the sampled input. Plugin compaction providers still receive the full messages. Co-authored-by: Ayaan Zaidi <[email protected]>
…ary-output-budget Resolves the compaction-safeguard.test.ts conflicts with openclaw#167916: the old summarizeInStages dropped-history test stays removed as upstream intended, and the cap-model-limit and cap-staged-limit rows now assert through mockSummarizeCompactionHistory. The production change is unchanged.
…aries (openclaw#119404) openclaw#167916 replaced staged summaries with one bounded summarizeCompactionHistory request, so the comment names the current path. No behavior change.
Related: #158044, #126171, #115514, #167916 ## What Problem This Solves Fixes repeated host summarization on ordinary Codex turns, including the turn after native `/compact`, when OpenClaw's transcript mirror exceeds its byte limit. ## User Impact Healthy native Codex threads continue without a host byte-summary request or a following native compaction. OpenClaw bounds the mirror only when it must seed a fresh native thread, attempting one host compaction only if the bounded seed would omit history not already covered by a host summary. The full stored transcript remains available to history, search, export, backups, cold storage, and memory indexing. Native rollout-size/token fuses, manual native compaction, built-in/CLI behavior, and explicit context-engine ownership are preserved. Fresh seeds can still omit oversized history after the single attempt; an existing bounded-context notice tells the user when history is omitted. This does not add a native SQLite replay boundary or change `memoryFlush.forceFlushTranscriptBytes` (#126171). ## Why This Change Was Made The guard introduced in #115514 protects fresh-thread bootstrap size, but ran on every turn. Native compaction deliberately produces a display-only note, not a host compaction boundary, so it cannot clear that trigger. The bound and conditional host compaction now live at fresh-thread seed consumption instead. Thanks to @scotthuang for diagnosing the repeated post-`/compact` work in #158044; this implements the maintainer's [lazy-seed direction](#158044 (comment)), not host-first manual compaction. Removed: the Codex byte-preflight branch, its private WeakMap authority/claim module, projected compaction configuration, queued special-authority handling, post-maintenance latch callback, byte-triggered native follow-up, and tests of those retired paths. Owning engines retain engine-first compaction and their native follow-up. The existing compactor and atomic summary/count writer are reused; #167916's bounded summarization remains unchanged. **Accepted compatibility boundary:** Ayaan, the SDK and security owner, approved the optional additive `AgentHarnessHostCapabilities.prepareBoundedSeed({ assertCurrent, signal, tokenBudget? }): Promise<readonly AgentMessage[]>` capability on 2026-10-17, including the narrowing-only delivery allowance. The host captures session, configuration, source, byte budget, cancellation, and writer fences; callers cannot select another target or widen the captured token budget. Older hosts keep bounded selection without a plugin-side summary request. Explicit context engines retain their projections. The required main integration now supplies the canonical nullable-latch writer contract unchanged: seed commits pass explicit `null` to clear prior suppression. No schema, stored-row shape, external protocol, or config key changes. Stored Codex latches are ignored on ordinary turns; non-Codex latch behavior is retained. ## Evidence **Complete:** 57 paired result rows, seven reduced paid-confirmation turns, and supporting manual-compaction/harness-switch campaigns. The final report records no unresolved regressions or coverage gaps. Full local evidence is retained in `codex-mirror-lazy-seed/results.md` and `results.json`; private transcript contents and credentials are not published here. BEFORE executed `7bfde4923e84f67e2961ea24d6a6fb6108680a03`; AFTER executed `df4c0017e1a8c4971afd8b0819e29923242ba970`. Final head `7083100abbdcc77bb9a28ac1afc41e647e299ead` is **production-identical to df4c**: `git diff df4c001 7083100 --stat` contains only `host-seed.test.ts | 12` (11 additions, one deletion) for its test-table type. The [67 incoming main commits](7bfde49...0b64fd1) changed none of the seed/compactor/writer/maintenance/harness-capability owners, so the same BEFORE remains applicable. The OpenShell config fingerprint conflict was regenerated canonically. ### Paired runtime results “Op” means a committed host compaction; “calls” means summary-provider requests within that operation. Native history injection is not native compaction. | Scenario | Repeats | BEFORE host ops / calls | AFTER host ops / calls | Result | |---|---:|---:|---:|---| | Oversized ordinary turn | 5 | 1 / 1 | 0 / 0 | All three historical facts retained | | Below-budget control | 5 | 0 / 0 | 0 / 0 | All three facts retained | | Fresh rotation at final history allowance | 2 | 0 / 0 | 1 / 2 | 73,678-byte seed; all three facts retained | | Subsequent rotation with covering summary | 2 | 0 / 0 | 0 / 0 | No repeat host summary; all three facts retained | | 8 KiB refresh, compaction disabled | 2 | 0 / 0 | 0 / 0 | 20,459 / 20,463-byte seeds retain the active 17,862-byte exchange and task once; older facts omitted with the native-seed notice | | Same refresh, compaction enabled | 1 paired, plus 2 repair-proof repeats | 1 / 1 | 1 / 1 | 22,222-byte seed; active exchange and all three facts retained | | Forced-cold upgrade, first next turn | 2 | 1 / 2 | 1 / 1 | 1,744-byte seed contains persisted summary; settings/auth/history and all facts retained | | Same upgrade, second next turn | 2 | 1 / 2 | 0 / 0 | Warm native reuse, no repeat host maintenance | | High-byte-cap but token-bounded upgrade | 1 | 0 / 0 | 1 / 2, then 0 / 0 | Deliberately not a below-all-budgets control; all facts retained | Supporting recorded-head campaigns also exercised real native `/compact` followed by a normal turn, built-in/CLI harness switching, and an owning context engine's engine-first compaction plus native follow-up. Their head identities remain explicit in the full report; they are not mislabeled as current-head executions. The final focused batch passed **74 tests in three owner files**, with Oxfmt/Oxlint and independent P0/P1 review clean; the main-integration batch separately passed 136 tests in five files. ### Five-repeat latency Wall times include CLI startup through terminal reply. These are loopback comparisons, not a promise of a fixed live-provider speedup. | Cell | BEFORE median [min–max], ms | AFTER median [min–max], ms | |---|---:|---:| | Oversized ordinary turn, n=5 each | 1,714.492 [1,683.089–1,792.939] | 1,484.624 [1,462.629–1,495.408] | | Control, n=5 each | 1,492.385 [1,463.280–1,495.413] | 1,523.846 [1,478.522–1,551.325] | ### Real-provider confirmation Each rotation entry below is one measured turn. Inputs are provider-reported totals across summary and native requests; model names are redacted as A/B/C. All six rotation turns recalled all three facts with zero errors and zero native `thread/compact/start` requests. | Model | Summary calls BEFORE → AFTER | Input tokens BEFORE → AFTER | Wall ms BEFORE → AFTER | AFTER seed bytes | |---|---:|---:|---:|---:| | A | 2 → 1 | 41,896 → 41,700 | 10,284.090 → 9,766.600 | 67,614 | | B | 2 → 1 | 41,855 → 41,602 | 12,733.944 → 11,388.505 | 67,174 | | C | 2 → 1 | 41,873 → 41,639 | 12,074.490 → 11,443.134 | 67,368 | The seventh confirmation turn was BEFORE model-A ordinary maintenance: 35,518 input tokens and two summary calls. Earlier full three-model campaigns remain supporting evidence. Final confirmation used 286,083 input tokens against a 286,841 forecast; the whole paid campaign used **3,593,931 input / 26,838 output tokens / 280 requests**, below the approved 3,650,000-input cap. Credentials were removed. ### Authority, compatibility, and limitations - The task-owned observer exercised the real host compactor, atomic persistence, and stock native injection: one host operation, two summary calls, nine injected items / 73,678 bytes, and **zero native compaction RPCs**. The report's legacy `nativeSyncAfterHost` flag also counts expected injection; it does not mean `thread/compact/start`. - Retained callbacks after completed-source retirement and after public reset rejected with zero additional summary/native effects; transcript-plus-entry hashes stayed identical. Reset during prepared seeding produced zero stale injections; the next turn was healthy with neither old-thread reuse nor stale seed markers. Public reset retires both source and writer; isolated writer-only reassignment is additionally covered by the owner regression. - E2E exposed and repaired two real defects: an oversized tail crowded out a fitting persisted summary, and the compactor's default kept tail exceeded the final seed allowance. The seed now reserves a fitting summary and gives the existing compactor the matching retention budget. Negative owner tests fail before these repairs. - The upgrade is explicitly **forced-cold**: native 0.160.0→0.162.0 changes runtime/policy identity. This is not presented as a warm-binding migration. Saved operator settings, authentication, logical history, and real pre-existing latch state were checked. - The existing [160,000-CJK-weighted-character summary input cap](https://github.com/openclaw/openclaw/blob/0b64fd18fcdccfa5ef3a1837909e7321ebcbca50/packages/agent-core/src/harness/compaction/utils.ts#L393) samples oversized histories and marks gaps. This PR does not promise lossless summaries or hide that pre-existing limitation. - With compaction disabled, the configured cap still omits older historical facts with a notice; no-cap defaults and the full saved record are unchanged. In the disabled 8 KiB case, BEFORE recalled three old facts and AFTER recalled none, while preserving the active task/exchange. That is the explicit configured-bound behavior, not an inherited-loss claim. - Cleanup removed 98 receipt-owned temporary roots, deferred none, and stopped all test Gateways/providers. Private evidence was retained; no operator Gateway or live state was touched. [Exact-head CI is green](https://github.com/openclaw/openclaw/actions/runs/39046961062). The final build, proof identity, budget ledger, and cleanup receipts are recorded; merge remains gated on ClawSweeper's exact-head readiness. `pr-simplify` against merge base `0b64fd18fcdccfa5ef3a1837909e7321ebcbca50`: production **+460/-362 (+98)**; tests **+487/-602 (-115)**; docs including generated fingerprints **+43/-44 (-1)**. Total: **36 files, +990/-1008, net -18 lines**. No coverage was cut. The remaining production increase is **295 lines** of host-owned seed preparation (authority/cancellation, retained-input budgeting, media costs, summary reservation and atomic persistence), plus **62 net lines** of SDK/injection/notice integration, offset by **259 removed lines** of eager preflight and private claim machinery. Shared bounds have distinct jobs: avoid restoring discarded media, account for actual media/active input, then reserve notice/summary only when needed. Non-Codex and owning-engine contracts remain intact. Merge danger: **two-way door**. Reverting restores eager host byte preflight; any summaries already appended remain valid existing-format transcript events. The main risk is incorrect fresh-thread seed selection or source/writer handoff for Codex sessions with the byte guard enabled. Healthy native reuse and explicit engine ownership are protected separately. No operator Gateway or operator state was touched. Co-authored-by: Ayaan Zaidi <[email protected]>
…175256) Related: openclaw#158044, openclaw#126171, openclaw#115514, openclaw#167916 ## What Problem This Solves Fixes repeated host summarization on ordinary Codex turns, including the turn after native `/compact`, when OpenClaw's transcript mirror exceeds its byte limit. ## User Impact Healthy native Codex threads continue without a host byte-summary request or a following native compaction. OpenClaw bounds the mirror only when it must seed a fresh native thread, attempting one host compaction only if the bounded seed would omit history not already covered by a host summary. The full stored transcript remains available to history, search, export, backups, cold storage, and memory indexing. Native rollout-size/token fuses, manual native compaction, built-in/CLI behavior, and explicit context-engine ownership are preserved. Fresh seeds can still omit oversized history after the single attempt; an existing bounded-context notice tells the user when history is omitted. This does not add a native SQLite replay boundary or change `memoryFlush.forceFlushTranscriptBytes` (openclaw#126171). ## Why This Change Was Made The guard introduced in openclaw#115514 protects fresh-thread bootstrap size, but ran on every turn. Native compaction deliberately produces a display-only note, not a host compaction boundary, so it cannot clear that trigger. The bound and conditional host compaction now live at fresh-thread seed consumption instead. Thanks to @scotthuang for diagnosing the repeated post-`/compact` work in openclaw#158044; this implements the maintainer's [lazy-seed direction](openclaw#158044 (comment)), not host-first manual compaction. Removed: the Codex byte-preflight branch, its private WeakMap authority/claim module, projected compaction configuration, queued special-authority handling, post-maintenance latch callback, byte-triggered native follow-up, and tests of those retired paths. Owning engines retain engine-first compaction and their native follow-up. The existing compactor and atomic summary/count writer are reused; openclaw#167916's bounded summarization remains unchanged. **Accepted compatibility boundary:** Ayaan, the SDK and security owner, approved the optional additive `AgentHarnessHostCapabilities.prepareBoundedSeed({ assertCurrent, signal, tokenBudget? }): Promise<readonly AgentMessage[]>` capability on 2026-10-17, including the narrowing-only delivery allowance. The host captures session, configuration, source, byte budget, cancellation, and writer fences; callers cannot select another target or widen the captured token budget. Older hosts keep bounded selection without a plugin-side summary request. Explicit context engines retain their projections. The required main integration now supplies the canonical nullable-latch writer contract unchanged: seed commits pass explicit `null` to clear prior suppression. No schema, stored-row shape, external protocol, or config key changes. Stored Codex latches are ignored on ordinary turns; non-Codex latch behavior is retained. ## Evidence **Complete:** 57 paired result rows, seven reduced paid-confirmation turns, and supporting manual-compaction/harness-switch campaigns. The final report records no unresolved regressions or coverage gaps. Full local evidence is retained in `codex-mirror-lazy-seed/results.md` and `results.json`; private transcript contents and credentials are not published here. BEFORE executed `81dde48ac1141487da66e6b9106aa6f7412e6e3b`; AFTER executed `df4c0017e1a8c4971afd8b0819e29923242ba970`. Final head `7083100abbdcc77bb9a28ac1afc41e647e299ead` is **production-identical to df4c**: `git diff df4c001 7083100 --stat` contains only `host-seed.test.ts | 12` (11 additions, one deletion) for its test-table type. The [67 incoming main commits](openclaw/openclaw@81dde48...140f7d9) changed none of the seed/compactor/writer/maintenance/harness-capability owners, so the same BEFORE remains applicable. The OpenShell config fingerprint conflict was regenerated canonically. ### Paired runtime results “Op” means a committed host compaction; “calls” means summary-provider requests within that operation. Native history injection is not native compaction. | Scenario | Repeats | BEFORE host ops / calls | AFTER host ops / calls | Result | |---|---:|---:|---:|---| | Oversized ordinary turn | 5 | 1 / 1 | 0 / 0 | All three historical facts retained | | Below-budget control | 5 | 0 / 0 | 0 / 0 | All three facts retained | | Fresh rotation at final history allowance | 2 | 0 / 0 | 1 / 2 | 73,678-byte seed; all three facts retained | | Subsequent rotation with covering summary | 2 | 0 / 0 | 0 / 0 | No repeat host summary; all three facts retained | | 8 KiB refresh, compaction disabled | 2 | 0 / 0 | 0 / 0 | 20,459 / 20,463-byte seeds retain the active 17,862-byte exchange and task once; older facts omitted with the native-seed notice | | Same refresh, compaction enabled | 1 paired, plus 2 repair-proof repeats | 1 / 1 | 1 / 1 | 22,222-byte seed; active exchange and all three facts retained | | Forced-cold upgrade, first next turn | 2 | 1 / 2 | 1 / 1 | 1,744-byte seed contains persisted summary; settings/auth/history and all facts retained | | Same upgrade, second next turn | 2 | 1 / 2 | 0 / 0 | Warm native reuse, no repeat host maintenance | | High-byte-cap but token-bounded upgrade | 1 | 0 / 0 | 1 / 2, then 0 / 0 | Deliberately not a below-all-budgets control; all facts retained | Supporting recorded-head campaigns also exercised real native `/compact` followed by a normal turn, built-in/CLI harness switching, and an owning context engine's engine-first compaction plus native follow-up. Their head identities remain explicit in the full report; they are not mislabeled as current-head executions. The final focused batch passed **74 tests in three owner files**, with Oxfmt/Oxlint and independent P0/P1 review clean; the main-integration batch separately passed 136 tests in five files. ### Five-repeat latency Wall times include CLI startup through terminal reply. These are loopback comparisons, not a promise of a fixed live-provider speedup. | Cell | BEFORE median [min–max], ms | AFTER median [min–max], ms | |---|---:|---:| | Oversized ordinary turn, n=5 each | 1,714.492 [1,683.089–1,792.939] | 1,484.624 [1,462.629–1,495.408] | | Control, n=5 each | 1,492.385 [1,463.280–1,495.413] | 1,523.846 [1,478.522–1,551.325] | ### Real-provider confirmation Each rotation entry below is one measured turn. Inputs are provider-reported totals across summary and native requests; model names are redacted as A/B/C. All six rotation turns recalled all three facts with zero errors and zero native `thread/compact/start` requests. | Model | Summary calls BEFORE → AFTER | Input tokens BEFORE → AFTER | Wall ms BEFORE → AFTER | AFTER seed bytes | |---|---:|---:|---:|---:| | A | 2 → 1 | 41,896 → 41,700 | 10,284.090 → 9,766.600 | 67,614 | | B | 2 → 1 | 41,855 → 41,602 | 12,733.944 → 11,388.505 | 67,174 | | C | 2 → 1 | 41,873 → 41,639 | 12,074.490 → 11,443.134 | 67,368 | The seventh confirmation turn was BEFORE model-A ordinary maintenance: 35,518 input tokens and two summary calls. Earlier full three-model campaigns remain supporting evidence. Final confirmation used 286,083 input tokens against a 286,841 forecast; the whole paid campaign used **3,593,931 input / 26,838 output tokens / 280 requests**, below the approved 3,650,000-input cap. Credentials were removed. ### Authority, compatibility, and limitations - The task-owned observer exercised the real host compactor, atomic persistence, and stock native injection: one host operation, two summary calls, nine injected items / 73,678 bytes, and **zero native compaction RPCs**. The report's legacy `nativeSyncAfterHost` flag also counts expected injection; it does not mean `thread/compact/start`. - Retained callbacks after completed-source retirement and after public reset rejected with zero additional summary/native effects; transcript-plus-entry hashes stayed identical. Reset during prepared seeding produced zero stale injections; the next turn was healthy with neither old-thread reuse nor stale seed markers. Public reset retires both source and writer; isolated writer-only reassignment is additionally covered by the owner regression. - E2E exposed and repaired two real defects: an oversized tail crowded out a fitting persisted summary, and the compactor's default kept tail exceeded the final seed allowance. The seed now reserves a fitting summary and gives the existing compactor the matching retention budget. Negative owner tests fail before these repairs. - The upgrade is explicitly **forced-cold**: native 0.160.0→0.162.0 changes runtime/policy identity. This is not presented as a warm-binding migration. Saved operator settings, authentication, logical history, and real pre-existing latch state were checked. - The existing [160,000-CJK-weighted-character summary input cap](https://github.com/openclaw/openclaw/blob/140f7d9e325f6f38f94bf8a9041050ecc3fd1e55/packages/agent-core/src/harness/compaction/utils.ts#L393) samples oversized histories and marks gaps. This PR does not promise lossless summaries or hide that pre-existing limitation. - With compaction disabled, the configured cap still omits older historical facts with a notice; no-cap defaults and the full saved record are unchanged. In the disabled 8 KiB case, BEFORE recalled three old facts and AFTER recalled none, while preserving the active task/exchange. That is the explicit configured-bound behavior, not an inherited-loss claim. - Cleanup removed 98 receipt-owned temporary roots, deferred none, and stopped all test Gateways/providers. Private evidence was retained; no operator Gateway or live state was touched. [Exact-head CI is green](https://github.com/openclaw/openclaw/actions/runs/39046961062). The final build, proof identity, budget ledger, and cleanup receipts are recorded; merge remains gated on ClawSweeper's exact-head readiness. `pr-simplify` against merge base `140f7d9e325f6f38f94bf8a9041050ecc3fd1e55`: production **+460/-362 (+98)**; tests **+487/-602 (-115)**; docs including generated fingerprints **+43/-44 (-1)**. Total: **36 files, +990/-1008, net -18 lines**. No coverage was cut. The remaining production increase is **295 lines** of host-owned seed preparation (authority/cancellation, retained-input budgeting, media costs, summary reservation and atomic persistence), plus **62 net lines** of SDK/injection/notice integration, offset by **259 removed lines** of eager preflight and private claim machinery. Shared bounds have distinct jobs: avoid restoring discarded media, account for actual media/active input, then reserve notice/summary only when needed. Non-Codex and owning-engine contracts remain intact. Merge danger: **two-way door**. Reverting restores eager host byte preflight; any summaries already appended remain valid existing-format transcript events. The main risk is incorrect fresh-thread seed selection or source/writer handoff for Codex sessions with the byte guard enabled. Healthy native reuse and explicit engine ownership are protected separately. No operator Gateway or operator state was touched. Co-authored-by: Ayaan Zaidi <[email protected]>
Related: #164220, #164246, #164263, #130971
What Problem This Solves
Fixes: on a large session, automatic compaction keeps the user waiting about six minutes, and often times out, because the summary work grows with the size of the context window.
User Impact
User impact: large sessions compact in about 25 seconds instead of about 6 minutes, and each compaction costs about 33k summary input tokens instead of about 700k. On a 1M-token window the user's next answer arrived in 85 s instead of 454 s. Timeouts like #164220, and the lossy no-summary fallback from #164246, become rare. No new config keys, messages, or warnings.
Tradeoff (approved by the maintainer): when the history to summarize is larger than one request's budget, the summarizer sees a sample of it, not every message. The newest messages stay verbatim; the user's older messages (asks, decisions, corrections) come next and are all kept when they fit; then the oldest messages and evenly spaced runs of the rest. Every gap is marked with the number of messages left out. The transcript still stores every message; only the summarizer input is bounded. Histories that fit the budget are summarized exactly as before, byte for byte.
Why This Change Was Made
Root cause. Compaction fires at
contextWindow − reserveTokens(about 984k tokens on a 1M window) and keeps onlykeepRecentTokens(20k) verbatim, so about 880k tokens go to the summarizer.summarizeInStagesthen split that into two stages of sub-chunks sized atcontextWindow × 0.4, summarized each serially with a running summary, and merged the parts: five serial reasoning-model requests (about 250k, 105k, 250k, 110k input tokens, then a merge). A failed quality audit repeated all five. Work, latency and cost grew linearly with the window, so every larger model made compaction slower. #163636 and #164263 stopped the watchdog from killing healthy requests and #164246 recovers from a real timeout; none of them reduced the work.Fix.
runSummarizationCompletion). The conversation input is capped at 160,000 CJK-weighted characters, lowered to fit the summarizer's own context window next to the system prompt, the previous summary, the instructions and the output reservation.serializeConversationWithinBudget(utils.ts) fills it in order: the newest entries verbatim (half; the newest entry keeps both ends when it alone is larger); older user messages (a quarter, each trimmed to at most 2,000 characters, spread evenly across the history when they do not all fit), because they carry the asks, decisions and corrections; the oldest entries (a tenth); and eight evenly spaced runs of the rest, trimmed to 6,000 characters each. Gap-marker cost is charged exactly, and the whole input never exceeds the budget. Gaps carry[... N entries omitted ...], and the prompt tells the summarizer not to guess what they said and to keep the previous summary's facts. In sampled input each tool result names the call that produced it ([Tool result of exec(cmd="...")]), matched by call occurrence, because sampling can separate the two.resolveCompletionTokenReservation(@openclaw/ai/transports, next toapplyAnthropicThinkingOptions) adds the thinking budget only for budget-based Anthropic Messages thinking; other transports keepmaxTokensas the total output limit. A history that fits is always sent unchanged. When the prompt alone overflows the window, or the history must be sampled and the window leaves under 4,000 characters, the request returns a non-retriedSummaryOutputBudgetErrorthat namesagents.defaults.compaction.model, without a model call.summarizeCompactionHistory(src/agents/compaction.ts) replacessummarizeInStagesand keeps its retry policy (3 attempts; caller abort, transport timeout and output-budget errors are terminal) and thetoolResult.detailsand runtime-context stripping. The safeguard hook makes one call and passes the previous summary aspreviousSummary; the quality audit, corrective retries, split-turn prefix summary, preserved turns, and the fix(compaction): commit a deterministic reduction after a summary timeout #164246 timeout fallback are unchanged.compaction-planning-worker*.ts,compaction-planning.worker.ts,compaction-planning-projection.ts) with its tsdown entry, knip entry and worker-kind registrations. Safeguard runtime fieldscontextWindowTokensand the unusedmaxHistoryShareare gone with the factory params that only fed them.docs/concepts/compaction.mddescribes the bound and the sampling; config help and the provider docs no longer namesummarizeInStages.Evidence
Live: Telegram Test Server, real
gpt-6-astraSame harness as #163636/#164263: real-user DM, built
distof each head, default context engine, default compaction settings (safeguard mode), a forwarding proxy that records timing only, and the same deterministic 1,250-message seed (3.53M chars, 901k estimated tokens). BEFORE = merge base24ca81d55bce, AFTER =f750b6e5ca9c(clean tree).The seed carries no provider usage, and current
mainno longer starts preflight compaction from the transcript estimate alone, so both runs also set the seeded session row's persisted usage tototalTokens: 963000, totalTokensFresh: true(transcript bytes unchanged). Both gateways then loggedpreflightCompaction triggered: tokenCount=963040 threshold=902000 trigger=tokens.24ca81d55bcef750b6e5ca9c[compaction-diag] end)outcome=compacted durationMs=370348, plusfinalized artifact truncated; loss=summary-tailoutcome=compacted durationMs=25369, no truncationAFTER's summary request carried 8 gap markers. BEFORE input tokens are estimated from body size at AFTER's measured 5.02 bytes per token (the BEFORE proxy did not capture usage of streams the client closes). Both runs also spent 36–52 s in the pre-compaction memory flush, which sends the full transcript and is outside this change. The seed has no tool calls, so the live run does not exercise the tool-result labels; the tests below do.
Re-run with user-message priority (
2ed02d442b1, same seed, override and trigger gate): still one history-summary request, 164,544 B and 33,235 provider input tokens,outcome=compacted durationMs=54821, normal answers to both questions, and no compaction on the follow-up. The request carried 112 of the span's 612 user-role entries (each trimmed to 400 characters at that density), 96 gap markers and 1,085 omitted entries. Two differences fromf750b6e5ca9c: the summarizer wrote 2,762 output tokens instead of 1,092, so the request took 49.4 s instead of 20.9 s, and the safeguard's 16,000-character artifact cap clipped the summary tail again (finalized artifact truncated; loss=summary-tail, as onmain). End-to-end reply latency (243.6 s) is not comparable: the host load average was 43–50 during that run, the gap between compaction end and the answer request alone was 40 s instead of 4.7 s, and the answer model request itself took 2.6 s.Tests
New
packages/agent-core/src/harness/compaction/summarization-input-budget.test.ts, throughgenerateSummaryand the serializer:serializeConversation.SummaryOutputBudgetErrorwithout a model call, for long and short histories alike, while a short history on a 4k window without that summary is still sent unchanged. Budgets below one gap marker send nothing.createToolCallOccurrenceQueue).Negative controls: each case above fails on the commit before its fix, except the "every tenth" spread case, which guards the stride against a newest-first regression and also passes on the earlier even sampling. Migrated suites (deleted tests covered only removed mechanisms; kept behavior moved to
summarizeCompactionHistory):compaction.summarize-fallback,compaction.summary-format,compaction.tool-result-details,compaction.identifier-preservation,compaction.abort-http,agent-hooks/compaction-safeguard*,embedded-agent-runner/compact.hooks,compact.summary-fallback,compact.small-context,extensions,agent-session-tool-result-redaction, andsrc/agents/sessions/(small-window sessions). All pass, as doesnode scripts/check-changed.mjs --base origin/main(typecheck all lanes, oxlint, import cycles, ratchets, config docs baseline).Review
gpt-6-astrareview, eleven rounds on this branch. Rounds 1–6 found, and this branch fixed: a mixed CJK/ASCII newest entry could be dropped; an oversized newest entry lost its end; tiny summarizer windows could overflow or send markers only; a dead export; and four cases where a sampled tool result could lose its call. The last one led to the self-describing result labels. Round 7: LAND, no findings.Hosted review then found three more, fixed in
f55ae2a202fand2e7cc05cafd: a short history was rejected on a tiny window before measuring it; budget-based Anthropic thinking adds its budget on top ofmaxTokens; repeated call IDs mislabeled results. Round 8 found that the first thinking fix also reserved thinking on OpenAI, so the reservation moved to the Anthropic transport owner. Round 9: LAND, no findings.4786e7233faadds user-message priority (maintainer request). Round 10 found that when the prompt alone overflowed the window, closing the only gap refunded the marker cost and let a short history through;2ed02d442b1enforces the overall budget in every selection and rejects a negative budget. Round 11 on2ed02d442b1: LAND, no findings.Rebase: onto
bc1d44c838e. The only conflict was incompaction-safeguard.ts, where #167816 had folded the adaptive chunk-ratio code into aresolveMaxChunkTokenshelper that this PR deletes, so the resolution keeps this branch's side.Related history: the inspected commits on touched files only touch
docs/.generated/config-baseline.sha256and an unrelated test incompact.hooks.test.ts.Merge danger: two-way door. No schema, stored-row, config or protocol change; a revert restores the staged pipeline.
@openclaw/ai/transportsgains one additive export,resolveCompletionTokenReservation. Blast radius: every built-in compaction summary (default and safeguard modes, manual/compact, preflight and overflow recovery). Histories that fit 160,000 characters (about 40k tokens) are unchanged; larger ones are summarized from the sampled input. Plugin compaction providers still receive the full messages.