Repository navigation
fix: auto-compaction times out on large sessions when a context-engine plugin delegates compaction - #163636
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 2, 2026, 2:40 PM ET / 18:40 UTC (Revision 3). ClawSweeper reviewWhat this changesThe PR lets plugins that delegate conversation compaction use the built-in per-request timeout by carrying watchdog refresh through the operation’s abort signal. Merge readiness✅ Ready for maintainer review This repair remains necessary on current main and the latest release. No blocking introduced defect was found; the supplied live proof is sufficient, and the previous draft-status blocker is resolved. Priority: P2 Review scores
Verification
How this fits togetherContext engines prepare conversation history and can delegate summarization to OpenClaw’s built-in compactor. The host watchdog bounds this work and forwards cancellation before the next model request. flowchart TD
A[Large conversation] --> B[Host compaction watchdog]
B --> C[Context engine plugin]
C --> D[Built-in compaction delegate]
D --> E[Serial summarization requests]
E --> B
E --> F[Compacted conversation]
B --> G[Cancellation or timeout]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource -79, Tests +15, Docs 0. Total -64 across 16 files. View PR surface stats
Review metricsNone. Technical reviewBest possible solution: Keep watchdog refresh at the existing native delegate while preserving operation-scoped cancellation and transcript-write fencing. Do we have a high-confidence way to reproduce the issue? Yes: current-main source establishes the wrapper eligibility failure, and the supplied baseline run shows healthy serial requests hitting the aggregate deadline. This reviewer did not execute a current-main reproduction. Is this the best way to solve the issue? Yes: the existing operation signal survives plugin wrappers and registry projection, removing fragile identity tagging without adding another API or changing stored configuration. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 165bd8d01db8. 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
History |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
…e plugin delegates compaction (openclaw#163636) A context-engine plugin that wraps the built-in compaction (delegateCompactionToRuntime) now keeps the per-stage watchdog refresh, so large sessions compact instead of timing out at the aggregate 180 s limit. Plugin-owned work stays bounded by one host window. Co-authored-by: Ayaan Zaidi <[email protected]>
…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]>
…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]>
What Problem This Solves
Fixes: auto-compaction times out on every turn ("Auto-compaction timed out before the next model request. Try again or run /compact.") when a context-engine plugin with
ownsCompaction: falsedelegates to built-in compaction viadelegateCompactionToRuntime(params)and the session is large enough that built-in staged compaction needs more than one timeout window in total.User Impact
Sessions using a delegating context-engine plugin (memory plugins that checkpoint and then hand compaction to the runtime) can compact large transcripts with the default
agents.defaults.compaction.timeoutSeconds(180 s): built-in compaction keeps its per-model-request window exactly as it does with the default engine. Plugin-owned work and engines that never delegate stay bounded by one host window. No config, SDK, or user-visible message changes; operators who raisedtimeoutSecondsto work around this can return to the default.Why This Change Was Made
Root cause: the host decided who may refresh the compaction watchdog by the function identity of
contextEngine.compact(src/agents/embedded-agent-runner/compaction-safety-timeout.ts:113onmain:isRuntimeCompactionDelegate(contextEngine.compact)), and only then injectedruntimeContext.compactionTimeoutReset. A plugin'scompact()is its own function that calls the delegate, so it is never marked; the delegate was reached without the reset, and the plugin's whole operation got one aggregate 180 s deadline. Built-in staged compaction of a ~900k-token transcript does not fit in that.Provenance: #130993 (a93a015) introduced the progress-refreshable native watchdog and made it "capability-bound to the canonical native delegate" because "a broader attempted timeout exception for every non-owning engine was unsafe: a synthetic custom CLI engine could then hang without a host deadline". #133260 (fa6b02a) then had to add
bindContextEngineCompaction/inheritRuntimeCompactionDelegateso registry proxies and recovery/queued wrappers kept the identity tag. Identity was the wrong carrier: every wrapper layer had to re-tag, and a third-party wrapper cannot.Fix: the capability now belongs to the operation, not to a function.
compactContextEngineWithSafetyTimeoutalready hands every engine a fresh composed abort signal for this operation; it now registers its reset under that signal (compactionWatchdogResets, a process-globalWeakMap<AbortSignal, () => void>so duplicated dist chunks share it).delegateCompactionToRuntimeresolves the reset fromparams.abortSignaland passes it to the native runtime, which already refreshes at setup completion, at each serial model request, before fallback, and before post-processing. The signal survives a plugin passingparamsunchanged or as{ ...params }, survives registry host-param projection (the only host param always forwarded tocompact), and needs no new SDK surface. All identity-marker machinery is deleted (marker WeakSet,bindContextEngineCompaction,inheritRuntimeCompactionDelegate, registry proxy tagging, quarantine-fallback tagging, the runtimeContext copy).Why #130993's safety intent still holds: the reset is only reachable by the canonical delegate, and only refreshes while native compaction makes progress. Plugin code before the delegate runs in the first window; after the delegate returns it has at most one window measured from the delegate's last progress refresh; an engine that never delegates, or that wraps the host signal in its own
AbortSignal.any(...), keeps the old single aggregate deadline. The existing custom-engine hang test (threads timeout cancellation into the plugin compactor) is unchanged and passes, and a new case proves a plugin that hangs after delegating still times out one window later.Evidence
Regression (
src/context-engine/delegate-watchdog.test.ts, real registry resolution + real host watchdog + realdelegateCompactionToRuntime, only the physical runtime is a three-stage fake; 60 ms window, 3 × 40 ms stages):Compaction timed outCompaction timed outpnpm test src/context-engine/delegate-watchdog.test.ts --maxWorkers=1: 5 passed, 13.8 s wall (transform-dominated; tests ~0.1 s).Focused suites:
context-engine.test.ts,host-param-projection.test.ts,embedded-agent-runner.compaction-safety-timeout.test.ts,compact.hooks.test.ts,compact.delegate.test.ts,compact.queued-successor.test.ts,run.overflow-compaction.test.ts,run.recovery-deadline.test.ts,context-engine-lifecycle.test.ts,cli-compaction.test.ts,run-orchestrator.suspension.test.ts,context-engine-maintenance.test.tspass.run.compaction-runtime.test.tshas 4 failures that reproduce identically on clean origin/main 32e30e5 on this host (unrelated).pnpm tsgo:core,pnpm tsgo:core:test, andpnpm check:changedpass.Live before/after
Telegram Test Server, real-user DM, real
gpt-6-astrathrough a forwarding proxy (timing only, no stalls injected), defaulttimeoutSeconds(unset → 180 s). A minimal plugin context engine (ownsCompaction: false) runs a 2 s plugin-owned step, thenreturn await delegateCompactionToRuntime(params)withparamsunchanged. Same synthetic seed in both runs: 1,250 alternating user/assistant filler messages, 3.8M chars (estimator 963k tokens vs 902k threshold, so the next DM triggers preflight auto-compaction).outcome=failed reason=timeout durationMs=177982,Compaction timed outoutcome=compacted durationMs=526610, no timeout linesPer-request compaction durations (proxy log, ms):
Before: three healthy requests, none over 72 s, killed by the 180 s aggregate. After: seven serial requests, 526.6 s total, longest single request 148.5 s, under the 180 s per-request window. The after run logged the pre-existing informational
Compaction safeguard: finalized artifact truncated; loss=summary-tailline (also present in normal default-engine compactions; unrelated to the watchdog).Bounded cost
WeakMap.setat the host boundary and oneWeakMap.getin the delegate; entries are collected with the operation's signal. No new timers, retries, config, SDK exports, warnings, or messages.Not changed
Per-request headroom: on this ~825k-token (provider-counted) transcript the slowest single compaction request took 148.5 s against the 180 s per-request window. Chunk sizes and the default timeout are untouched here; if a single stage request on a larger or slower session exceeds 180 s it will still time out, which is the intended per-request safety bound.