Repository navigation
fix: compaction aborts a slow summary request that is still streaming - #164263
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. |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Codex review: blocked before merge. Reviewed October 4, 2026, 12:23 PM ET / 16:23 UTC (Revision 11). ClawSweeper reviewWhat this changesCompaction now refreshes its timeout on streamed summary output, caps total duration, and reserves time for automatic timeout recovery. Merge readiness⛔ Blocked before merge - 1 item remains This PR remains useful and has no actionable correctness findings. The recorded maintainer acceptance covers the timeout-policy change, and final-head runtime evidence resolves the previous compatibility blocker. Priority: P2 Review scores
Verification
How this fits togetherCompaction shortens long conversations before the next agent request. Its watchdog wraps built-in summarization and plugin delegation, controlling when generation stops and existing recovery can proceed. flowchart TD
A[Long conversation] --> B[Compaction host watchdog]
B --> C[Built-in runtime delegate]
C --> D[Summary model stream]
D --> E{Meaningful output arrives?}
E -->|Yes| B
E -->|Silence or ceiling| F[Stop summary generation]
F --> G[Automatic reduction or manual failure]
D -->|Completed summary| H[Commit compacted context]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +59, Tests +202, Docs 0, Generated 0. Total +261 across 13 files. View PR surface stats
Review metrics
Technical reviewBest possible solution: Keep one progress-aware compaction timeout owner with a finite ceiling, immediate caller cancellation, and time reserved for existing automatic recovery. Do we have a high-confidence way to reproduce the issue? Yes: current-main source kills a request that streams beyond the configured window because only request starts refresh the watchdog. Recorded real before/after runs demonstrate that trigger; this reviewer did not execute it. Is this the best way to solve the issue? Yes: the patch uses existing stream observation and watchdog owners, excludes keepalives, and preserves automatic recovery before the ceiling. The changed timeout semantics have explicit maintainer acceptance. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 94975271e351. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (10 earlier review cycles; latest 8 shown)
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Maintainer decision on the timeout policy: accept option A. @clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Maintainer decision: accepted. |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
82bf344 to
5532d8e
Compare
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review — the remaining "Review config compatibility" item is the maintainer acceptance already recorded at #164263 (comment) (timeoutSeconds becomes the idle window with a 10× operation ceiling; no migration needed). Head 5532d8e only rebases onto main and adapts a test to the |
|
🦞👀 Re-review progress:
|
|
Maintainer config compatibility review for head 5532d8e: confirmed.
Accepted for landing. |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
… an operation ceiling A built-in compaction model request that keeps streaming summary output is no longer killed after timeoutSeconds. Each request start and each non-empty streamed output delta refreshes the host and native watchdogs, so the window measures silence, not request duration. Keepalives and empty deltas never count. The whole operation stops after 10 windows even if a stream trickles forever. Plugin-owned work stays bounded by one host window. Refs #130971
5532d8e to
ea03e21
Compare
…o automatic compaction keeps its timeout fallback
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
…openclaw#164263) Built-in compaction requests now time out on silence rather than total duration: every streamed output delta refreshes the watchdog, and the whole operation is capped at 10 x timeoutSeconds. Plugin-owned compaction keeps one host window.
…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]>
Related: #130971
What Problem This Solves
Fixes: compaction aborts a healthy summary request that is still streaming output, because the timeout window (⚠️ This conversation is too long, and shortening it took too long." while the model was still writing the summary.
agents.defaults.compaction.timeoutSeconds, 180 s default) caps each request's total duration instead of its silence. On a large session or a slower model the user sees "User Impact
User impact: large sessions compact even when a single summary request runs longer than
timeoutSeconds, as long as it keeps streaming. A request that goes silent is still aborted one window after its last output, so a hung provider still fails at about the same time as before. No new config keys, messages, or warnings; the timeout error and its user-facing text are unchanged.New bound: the whole compaction stops after 10 windows (30 minutes at the default) even if output keeps trickling. Built-in compaction had no operation-level ceiling on
mainonce #130993 made every request start a fresh window; plugin-owned compaction keeps its one-window bound.Why This Change Was Made
Root cause. The host compaction watchdog is refreshed only at request boundaries: after setup, when each provider request starts (
onStartedinsrc/agents/embedded-agent-runner/compaction-session-execution.ts:343-348onmain), and after success or before a thinking fallback. Nothing refreshes it while a request streams, so a single request is bounded bytimeoutSecondsfrom its start no matter how much output it produces.Provenance. #130993 (a93a015) introduced the per-request refresh ("keep staged compaction progress alive") and kept plugin compaction "bounded once at the host boundary". #163636 (02ec714) moved the refresh capability onto the operation's composed abort signal (
compactionWatchdogResets) so delegating plugins get it too. Both left single-request progress open, as noted in the issue thread. Both invariants are kept here. #164246 (c0c6ca3, merged after this PR opened) made an automatic compaction whose summary times out commit a deterministic reduction instead of failing; this PR keeps that outcome reachable at the new ceiling (see Summary cutoff).Fix.
onOutputDeltacallback for each non-emptytext_delta,thinking_deltaortoolcall_delta(attempt.model-diagnostic-lifecycle.ts). Compaction wires it to the same refresh asonStarted, which resets both the native and delegated watchdogs. These are parsed provider events, not raw bytes: SSE keepalives,response.in_progress-style frames, structural*_start/*_endevents, empty deltas and loop ticks never count (the point from the issue's idleDeadline/totalDeadline comment). Reasoning deltas count because the model is producing output; a provider that hangs produces none.runAbortableTimeouttakes an optionalmaxTotalMs: each reset armsmin(timeoutMs, deadline - now)(never below 0), and resets at or after the deadline leave the due timer alone. The host watchdog (compactContextEngineWithSafetyTimeout) fixes its ceiling at10 × timeoutMsfrom the operation start, so there is no new config key. It is derived from the existing knob: raisingtimeoutSecondsraises both. At the default that is 30 minutes: 5.5× the 327 s this 963k-token session's compaction took in run 2 below, and 3.4× the slowest earlier measurement of a similar session (527 s, fix: auto-compaction times out on large sessions when a context-engine plugin delegates compaction #163636).{ reset, deadlineAt }for its signal (compactionWatchdogs, replacing the reset-onlycompactionWatchdogResets), anddelegateCompactionToRuntimeforwards both. The native summary watchdog ends one window before the host ceiling, so a summary still streaming at the ceiling times out on its own watchdog: an automatic compaction commits fix(compaction): commit a deterministic reduction after a summary timeout #164246's deterministic reduction inside the reserved window, and manual/compactkeeps failing with "Compaction timed out". Without this, the host deadline fired first (it starts before the summary), aborted the caller signal, and the automatic fallback was skipped (found by the post-rebase review). Direct compaction without a host keeps its own 10-window ceiling./compact,sessions.compactand preflight/overflow/timeout recovery all enter throughcompactContextEngineWithSafetyTimeout. When they reach built-in compaction, they share the runtime delegate, the native watchdog and the same wrapped stream. fix: recovery compaction ignores Stop and loses committed counts #133260 (Stop honored) and fix: stop compaction recovery when a run times out #159105 (run timeout stops recovery) are untouched: caller cancellation still aborts the composed signal immediately.Evidence
Regression through the real path (
compact.hooks.test.ts› "progress-aware compaction watchdog"). The chain is real:compactEmbeddedAgentSession→ host watchdog → context engine → realdelegateCompactionToRuntime→ native watchdog → realAgentSession→ core summarizer → diagnostic stream wrapper. Only the provider stream is scripted (one text delta every 20 s, 30 s window, 300 s ceiling).{ ok: false, reason: "Compaction timed out" }at 30 sok: true, compacted: true){ ok: false, compacted: false }The trickle cadence is chosen so the last delta before the cutoff leaves less than one window: a revision that ignored refreshes near the deadline instead of clamping them would fail the manual case at 255 s.
with-timeout.test.tsadds that an already-passed deadline times out immediately without Node'sTimeoutNegativeWarning(fails without the clamp).Focused suites pass on the rebased head (the final commit only touched
with-timeout, rerun there):compact.hooks.test.ts(94),compact.summary-fallback.test.ts(8),delegate-watchdog.test.ts(5),embedded-agent-runner.compaction-safety-timeout.test.ts,with-timeout.test.ts(4),attempt.model-diagnostic-events.test.ts,attempt.model-diagnostic-lifecycle.test.ts,run.compaction-runtime.test.ts,run.recovery-deadline.test.ts,run.overflow-compaction.test.ts,compact.queued-successor.test.ts,context-engine-lifecycle.test.ts. Alsopnpm tsgo:core, oxlint/oxfmt on the changed files, andpnpm config:docs:check.Live: Telegram Test Server, real
gpt-6-astraSetup: real-user DM on the Telegram Test Server, built
distof each head, default context engine, compaction mode as shipped. Every model request goes through a forwarding proxy in front of the OpenAI API. In runs 1–3 it only records timing: per-request duration, first/last output-delta time, and the largest gap between deltas as forwarded to the gateway. Every run uses the same synthetic 1,250-message seed (3.8M chars; estimator 963k tokens vs the 902k threshold), so the next DM triggers preflight compaction.1. Before/after at
timeoutSeconds: 60(the live model's natural request length is 45–85 s, so this reproduces a request outliving its window without injecting anything):outcome=failed reason=timeout durationMs=110758outcome=compacted durationMs=301232, one attemptPer compaction request (ms; gap = longest silence between forwarded output deltas):
Before: the update request was still streaming 11 ms before the watchdog killed it at exactly 60.0 s. After: two requests ran past the 60 s window (60.8 s, 83.3 s) without ever being silent for more than 344 ms, and compaction finished in one attempt.
2. Default
timeoutSeconds(unset → 180 s), this PR at 82bf344: compactionoutcome=compacted durationMs=326671in one attempt (6 serial requests, no retries, no timeout lines). The user got a normal answer to the question 334 s after sending it.3. Forced mid-stream stall, default window, this PR at 82bf344. The live model can't be made to stall on demand, so for the first compaction request the proxy forwards real⚠️ This conversation is too long, and shortening it took too long. …"). The stall failed at the idle window, not at the 30-minute ceiling, and no new text appeared.
gpt-6-astraoutput until 40 output deltas reach the gateway (6.25 s in). It then stops forwarding and cancels upstream while holding the gateway's socket open and silent. Result: the gateway closed the request 180.003 s after the last forwarded delta (186.3 s after it started), compaction endedoutcome=failed reason=timeout durationMs=186742(Compaction timed out), and the user got the existing timeout message ("Proof artifacts (local): proxy NDJSON per request, gateway log, and the Telegram event timeline for each run. The forwarding proxies never log the API key or request/response bodies.
Rebased head 5532d8e re-run (Telegram Test Server, real
gpt-6-astra)Rebase onto current main, provenance decisions:
compaction-safety-timeout.ts: main replaced the localraceCompactionWithAbortSignalwith the sharedracePromiseWithAbortSignal(caller-cancel error mapping). Kept main's helper and error mapping; the PR's ceiling-clamped reset now runs inside it. No behavior change to the PR.compact.hooks.test.ts: refactor(sdk): retire superseded worker prompt/bootstrap SDK exports #164768 retired thecreateAgentSessionForEmbeddedRunnerSDK export in favor ofcreateAgentSession; the PR's test now mockscreateAgentSession.docs/.generated/config-baseline.sha256: regenerated on the new base.Same harness and 963k-token seed as above, built
distat5532d8e8eb, defaulttimeoutSeconds:outcome=compacted durationMs=387436, one attempt, 6 compaction requests; user got a normal two-sentence answerdcw-live/idle/rebased-defaultoutcome=failed reason=timeout durationMs=193339; user got the existing "dcw-live/idle/rebased-stalldelegating-probe, ~2 s plugin work thendelegateCompactionToRuntime)outcome=compacted durationMs=361406, one attempt; user got a normal answerdcw-live/idle/rebased-pluginThe live proof above remains valid: the rebase did not change the PR's behavior, and these runs confirm it on the exact head.
Rebased head d1e3885 onto main with #164246 (Telegram Test Server, real
gpt-6-astra)Rebase provenance:
compact.hooks.test.tsconflicted after fix(compaction): commit a deterministic reduction after a summary timeout #164246 (c0c6ca3) and its neighbor rewrote the adjacent "plans direct compaction with the admitted workspace manifest policy" test into theplans canonical fallback plugins from the $sourceit.each. Kept main'sit.eachunchanged and inserted this PR'sdescribebefore it.compaction-session-execution.tsauto-merged with fix(compaction): commit a deterministic reduction after a summary timeout #164246's fallback path.Same harness and 963k-token seed, built
distof each head:timeoutSeconds: 30(ceiling 300 s), summary still streaming at the ceilingtrigger=budget outcome=failed reason=timeout durationMs=299983; user got "[compaction-diag] fallback … reason=timeout summary=deterministic,outcome=compacted reason=timeout summary=deterministic durationMs=269874; user got a normal two-sentence answerdcw-live/idle/r2-before-ceiling30,r2-after-ceiling30outcome=compacted reason=none durationMs=334793, one attempt, 6 compaction requests (longest 77.9 s, max delta gap 474 ms); normal answerdcw-live/idle/r2-defaultoutcome=compacted reason=timeout summary=deterministic durationMs=185978) and the user got a normal answer instead of the timeout textdcw-live/idle/r2-stalldelegating-probe, ~2 s plugin work thendelegateCompactionToRuntime)outcome=compacted reason=none durationMs=321600, one attempt; normal answerdcw-live/idle/r2-pluginNo
TimeoutNegativeWarningor other new warning lines in any gateway log; no new user-visible text.Compatibility
agents.defaults.compaction.timeoutSecondschanges meaning. Onmainit is the duration of each built-in compaction model request, restarted when the next serial request begins. With this PR it is how long a request may go without progress, where progress means a request start or a non-empty streamed text, reasoning or tool-call delta. Keepalives and empty deltas don't count. It also sets a new operation ceiling of 10 × timeoutSeconds (30 minutes at the default 180 s) on built-in compaction, whichmaindidn't have./compactfails with the existing "Compaction timed out". The measured runs are well inside that: 327 s (1.8 windows) for the 963k-token session in run 2 above, and 527 s (2.9 windows) for the slowest similar run measured in fix: auto-compaction times out on large sessions when a context-engine plugin delegates compaction #163636.timeoutSeconds. That raises both the idle window and the ceiling. No config migration is needed, and existing values stay valid.main, and caller Stop or a run timeout still cancels immediately.timeoutSecondsentries indocs/gateway/config-agents/heartbeat-compaction-and-streaming.mdand the config help text describe the new semantics and the ceiling.Maintainer decision recorded: keep the idle semantics with the 10-window operation ceiling (option A). The alternative, a per-request cap with no operation ceiling, was rejected because it drops the absolute bound the issue asked for (
totalDeadline).Bounded cost
compactionWatchdogsdeadline, its forwarding indelegate.ts, one internal param and the zero clamp). Tests +205 (onedescribewith 6 cases sharing one fixture, plus onewith-timeoutcase). Docs and help: 2 lines plus the regenerated config hash.lengthcheck per streamed provider event on compaction requests, plus aclearTimeout/setTimeoutpair per output delta. Normal agent turns pass noonOutputDelta, so they skip the check. No new timers, retries, config keys, SDK exports, warnings or messages.mainwhen it is silent from the start). Any built-in compaction stops at 10 windows; under a host the summary stops at 9, leaving one window to commit. Plugin-owned work keeps one window.gpt-6-astratokens across the first four runs; about 3.4M input and 88k output across the five runs on the rebased heads (aborted requests report no usage and are not counted).Not changed
timeoutSeconds, server-side Responses compaction (server-endpoint-compaction.tskeeps its own single-request window), the Codex app-server and Copilot harness compaction paths.