Repository navigation
fix(compaction): commit a deterministic reduction after a summary timeout - #164246
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. Reviewed October 4, 2026, 9:15 AM ET / 13:15 UTC (Revision 18). ClawSweeper reviewWhat this changesAutomatic conversation compaction gains a model-free reduction after qualifying summary timeouts, with diagnostics, documentation, and regression coverage. Merge readiness✅ Ready for maintainer review This PR remains useful: current main and the latest release still fail without reducing context after a summary timeout. No blocking introduced defect was found, the recorded runtime proof supports recovery, and the safeguard tradeoff has verified maintainer acceptance. Priority: P1 Review scores
Verification
How this fits togetherCompaction reduces conversation context before the agent sends another model request. This change uses the existing retention and transcript owners to preserve recent messages and resume the reply when summarization times out. flowchart TD
A[Conversation and pending request] --> B[Choose retained recent messages]
B --> C[Generate summary]
C --> D{Summary timed out and caller active?}
D -->|Yes| E[Build deterministic reduction]
D -->|No| F[Existing summary or failure handling]
E --> G[Validate ownership and append compaction]
G --> H[Continue agent reply]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +148, Tests +659, Docs +5. Total +812 across 13 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Technical reviewBest possible solution: Recover qualifying automatic summary timeouts through the existing compaction owner while preserving cancellation fences, retained messages, and full stored history. Do we have a high-confidence way to reproduce the issue? Yes: current-main source exposes the repeated-failure path, and the recorded before/after Gateway run exercises it with stalled summary requests. This review did not execute target code. Is this the best way to solve the issue? Yes: the patch reuses retention, finalization, and transcript persistence rather than adding retry state or destructive truncation; its intentional safeguard exception has verified acceptance. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 7de09d5a2337. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (17 earlier review cycles; latest 8 shown)
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review Owner decision recorded: the maintainer accepted the timeout-only safeguard exception (live caller, timeout-class only; quality rejections and other errors keep preserve-history). The docs and the PR body now say plainly that omitted facts are not restored by later compaction. |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
…eout (openclaw#164246) When an automatic compaction summary actually times out while the caller is live, the session commits a deterministic reduction (recent suffix verbatim, previous summary carried forward, loss notice, split-turn ask) so the turn answers and the next turn does not re-run the same timed-out summary. Manual /compact, Stop, run timeouts and non-timeout errors are unchanged. Co-authored-by: Ayaan Zaidi <[email protected]>
Related: #164246 ## What Problem This Solves Fixes: two compaction reference pages still promise that safeguard mode always keeps the original history when a summary cannot be produced, but since #164246 an automatic compaction whose summary times out commits a reduction without a summary. ## User Impact User impact: operators who read the `qualityGuard` setting or the compaction reference now see the summary-timeout exception and its retention cost (older unsummarized facts leave the model context). No behavior change. ## Why This Change Was Made #164246 updated `docs/concepts/compaction.md` only. Two other pages kept the old guarantee: - `docs/reference/session-management-compaction/compaction.md`: "a corrective generation failure cancels before append and leaves the original transcript authoritative." A corrective attempt that goes silent past the timeout window now commits the reduction. A corrective attempt that gets HTTP 408 still cancels, as #164246 documents under "Decisions kept". - `docs/gateway/config-agents/heartbeat-compaction-and-streaming.md` (`qualityGuard`): "When no attempt passes, OpenClaw preserves the original history." A timed-out attempt also does not pass, and the reduction commits. Both pages now name the exception and link to the canonical explanation in [Auto-compaction](https://docs.openclaw.ai/concepts/compaction#auto-compaction). ## Evidence - `pnpm run docs:check-links:anchors`: `broken_links=0` (includes the new `#auto-compaction` anchors). - `pnpm run docs:check-mdx`: passed (1340 files). - `git diff --check`: clean. - Wording checked against the #164246 source: `isSummaryTimeoutFailure` in `src/agents/embedded-agent-runner/compact-reasons.ts` (automatic only, summary watchdog or HTTP 408/504) and the corrective-attempt decision in the #164246 body. Merge danger: two-way door. Docs only; a revert restores the previous text. Blast radius: documentation readers only. Co-authored-by: Ayaan Zaidi <[email protected]>
Main's c0c6ca3 (openclaw#164246) moved formatRequiredAskContext into agent-core's compaction module. The clean textual merge kept this branch's copy in compaction-safeguard-quality.ts as well, which would import the name twice into compaction-safeguard.ts. Keep main's owner and drop this branch's move; the fit change is unchanged.
…ummary work grows with the context window (#167916) 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 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. #163636 and #164263 stopped the watchdog from killing healthy requests and #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 #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 #163636/#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 `24ca81d55bce`, 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 `24ca81d55bce` | 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 `bc1d44c838e`. The only conflict was in `compaction-safeguard.ts`, where #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]>
…aw#167640) Related: openclaw#164246 ## What Problem This Solves Fixes: two compaction reference pages still promise that safeguard mode always keeps the original history when a summary cannot be produced, but since openclaw#164246 an automatic compaction whose summary times out commits a reduction without a summary. ## User Impact User impact: operators who read the `qualityGuard` setting or the compaction reference now see the summary-timeout exception and its retention cost (older unsummarized facts leave the model context). No behavior change. ## Why This Change Was Made openclaw#164246 updated `docs/concepts/compaction.md` only. Two other pages kept the old guarantee: - `docs/reference/session-management-compaction/compaction.md`: "a corrective generation failure cancels before append and leaves the original transcript authoritative." A corrective attempt that goes silent past the timeout window now commits the reduction. A corrective attempt that gets HTTP 408 still cancels, as openclaw#164246 documents under "Decisions kept". - `docs/gateway/config-agents/heartbeat-compaction-and-streaming.md` (`qualityGuard`): "When no attempt passes, OpenClaw preserves the original history." A timed-out attempt also does not pass, and the reduction commits. Both pages now name the exception and link to the canonical explanation in [Auto-compaction](https://docs.openclaw.ai/concepts/compaction#auto-compaction). ## Evidence - `pnpm run docs:check-links:anchors`: `broken_links=0` (includes the new `#auto-compaction` anchors). - `pnpm run docs:check-mdx`: passed (1340 files). - `git diff --check`: clean. - Wording checked against the openclaw#164246 source: `isSummaryTimeoutFailure` in `src/agents/embedded-agent-runner/compact-reasons.ts` (automatic only, summary watchdog or HTTP 408/504) and the corrective-attempt decision in the openclaw#164246 body. Merge danger: two-way door. Docs only; a revert restores the previous text. Blast radius: documentation readers only. Co-authored-by: Ayaan Zaidi <[email protected]>
…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]>
Refs #164220
What Problem This Solves
An automatic compaction whose summary request times out ends the turn with "⚠️ This conversation is too long, and shortening it took too long…". The session stays above the threshold, so every following message runs the same summary again, waits out the same 180 s window, and fails again. The conversation stays dead until someone runs
/compactor/new.Root cause (provenance)
executePreparedCompactionSession(src/agents/embedded-agent-runner/compaction-session-execution.ts, client-summary block) turned every summary-stage failure intofail()without committing anything. The next turn's preflight (runSessionCompactionIfNeededinagent-runner-memory.ts, "Preflight compaction required but failed") or overflow recovery (overflow-context-recovery.ts,kind=compaction_failure) then ran the same compaction again. The per-request host watchdog from #130993 (a93a015) and #163636 (02ec714) is kept. Nothing used the cut that compaction had already prepared once that watchdog fired.Fix
compactWithoutSummary(preparation)in agent-corecompaction.tsbuilds the commit-ready artifact without a model call. It sharesfinalizeCompactionwithcompact().prepareCompactionalready chose, so the recent suffix stays verbatim and tool-call/result pairs stay intact.formatRequiredAskContextmoved fromcompaction-safeguard.tsinto agent-core, and both now share it.AgentSessionCompactionhas a new"deterministic"summary policy. It skips auth, summary hooks, and the model, and commits through the existingappendCompactionAsync. Transcript rows are untouched, so a later model compaction stacks on top normally (covered by a test).params.abortSignaldid not), or the provider answered HTTP 408 or 504. The status comes from structured provider identity:runSummarizationCompletionnow returnsSummaryProviderError, which carries the failed provider response. The delegate finds it through the error's cause chain (safeguard wraps it) instead of parsing wrapped text. Failover's broader "timeout" class, which also covers fast 5xx, 410, DNS failures, and text-only "request timed out", keeps its existing outcomes, including the model fallback chain. The compaction must also be automatic (not manual), and the caller must still be live: no Stop, run timeout, or outer host deadline. The delegate re-arms the delegated watchdog synchronously before committing.onSummaryReadysignal marks the end of generation. A timeout during persistence keeps the existing failure, so a real summary is never discarded.[compaction-diag] fallback … reason=timeout summary=deterministic(warn), and the debugendline readsreason=timeout summary=deterministic.Safeguard timeout exception (accepted by the maintainer)
In safeguard mode, a summary timeout now commits this reduction, so safeguard gives up its identifier-retention guarantee for that compaction:
Why: the alternative dead-ends the session, with every turn waiting out the same timeout. The exception covers only summary-generation timeouts while the caller is still live. Quality rejections and all other errors keep the preserve-history outcome. Documented in
docs/concepts/compaction.md.Decisions kept
/compactstill reports failures.gateway-compaction-abortQAactive-failurecontract.User-visible
No new notice. The answer arrives as usual.
notifyUserusers see the same start/end notices as for any successful compaction. NO_REPLY, quiet mode, anddelivery: nonepaths are untouched.Bounded cost
timeoutSeconds, default 180 s).Evidence
Live proof: Telegram Test Server, real gpt-6-astra
Setup:
Before: origin/main
96526f7e863cProxy: two stalled summarize requests, 179984 ms and 179995 ms (one per message). No answer request for either message.
After: this PR at
f310cdfbfee4(exact head)Proxy and gateway:
[compaction-diag] fallback … trigger=budget provider=openai/gpt-6-astra reason=timeout summary=deterministic, thenend … outcome=compacted reason=timeout summary=deterministic.Rebased head 4ca7a00 re-run (Telegram Test Server, real gpt-6-astra)
Same harness, seed, and summary-stalling proxy as above, built
distat4ca7a00588c6(currentmainplus this PR). Every run passed.[compaction-diag] fallback … reason=timeout summary=deterministic, thenend … outcome=compacted reason=timeout summary=deterministic durationMs=180284; a live answer at 246.8 s. Q2 at 600.3 s, answered at 604.3 s with no new summary request.cff-live/rebased-timeout/stopat 100.4 s, then "⚙️ Agent was aborted." at 100.8 s. Compactionoutcome=failed … Reply_operation_aborted_by_user durationMs=38971, no deterministic commit. The next message (420 s) found the session still over the threshold: it compacted again (stalled summary, then the deterministic reduction) and answeredAFTERSTOPat 604.7 s.cff-live/rebased-stop/compactwith a stalled summary/compactat 53.3 s; "⚙️ Compaction failed: Compaction timed out • Context ?/922k" at 241.3 s;end trigger=manual … outcome=failed reason=timeout, no fallback line.cff-live/rebased-manualNo new user-visible messages in any run.
Tests
src/auto-reply/reply/agent-runner-compaction-fallback.test.ts: two realrunReplyAgentturns (preflight, native delegate, SQLite, local OpenAI-compatible provider whose summary requests get HTTP 408). On origin/main, turn 1 returns the timeout notice (verified). On this branch, turn 1 returnsANSWER-1with one deterministic compaction, and turn 2 returnsANSWER-2with zero new summary requests.src/agents/embedded-agent-runner/compact.summary-fallback.test.ts: real queued compaction, AgentSession, and SQLite.4f912a5.compact.hooks.test.ts:compaction.test.ts: the loss notice, the unresolved request, and a 1,200-character split-turn ask with a mid constraint survive a capped previous summary and a constrained budget.pnpm tsgo:coreandpnpm tsgo:core:testare clean. Focused suites pass: agent-core compaction, agent-session-compaction, compact.hooks, compact.delegate, compaction-safety-timeout, compaction-safeguard, and the new files.Test cost (measured locally, isolated runs)
compact.summary-fallback.test.ts: 8 tests, about 60 s wall clock for the file run (including the vitest worker build). The first case takes about 27 s, which is cold module import; the rest take about 2 s each.agent-runner-compaction-fallback.test.ts: 1 test, about 8 s.compact.hooks.test.ts: the whole file (90 tests) took about 38–57 s wall clock isolated. The new persistence-stage case runs on a fake clock in about 2 s.Review
Earlier design, with model-fallback deferral: four gpt-6-astra rounds fixed safeguard timeout classification, loss-notice and split-turn-ask fitting, and several fallback-chain edge cases. On the maintainer's simplification decision, the chain deferral was removed entirely, along with its code and tests.
Fresh rounds on the simplified design:
3d5660a: one finding (a persistence-stage timeout discarded a generated summary). Fixed withonSummaryReady.2c01eb0: LAND.Two extra maintainer-requested reviews then found that wrapped summary text made a fast 500 look like a timeout and missed a bodyless 408, and that the split ask used the 800-character bound. Fixed with
SummaryProviderErrorand the shared 2,000-character bound.4f912a5: CHANGES. Failover's "timeout" class is broader than a timeout (410, DNS), so the gate was narrowed to watchdog-fired or 408/504. Safeguard corrective provenance was also raised.e1737e9: CHANGES. Passing the corrective error made quality cancellations fallback-eligible, so that change was reverted and the case deferred (see Decisions kept).f310cdf: LAND, no findings.Rebase onto current
main(no conflicts). Adapted to newermaindecisions:agents.listfrom the authored config type, so the turn-level test fixture now uses keyedagents.entries.compaction-session-execution.tspassed the 700-line cap, so the summary-timeout classification moved, unchanged, intocompact-reasons.ts(isSummaryTimeoutFailure), next toresolveCompactionFailure.compact.summary-fallback.test.ts.be18e614found that the extraction let a watchdog abort short-circuit beforeresolveCompactionFailure's model-fallback-stop rethrow.4ca7a005restored the original order, and the fresh review at4ca7a005returned LAND, no findings.LOC
cc1a29734ab3: production +197/−67 (6 files), docs +7/−2, tests +663/−5 (4 files), test routing +2.2c01eb0: production +63/−28, tests +52/−14.