Skip to content

fix: auto-compaction times out on large sessions when a context-engine plugin delegates compaction - #163636

Merged
obviyus merged 1 commit into
mainfrom
fix/delegated-compaction-watchdog
Oct 2, 2026
Merged

obviyus merged 1 commit into
mainfrom
fix/delegated-compaction-watchdog

Conversation

@obviyus

@obviyus obviyus commented Oct 2, 2026 •

Copy link
Copy Markdown
Collaborator

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: false delegates to built-in compaction via delegateCompactionToRuntime(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 raised timeoutSeconds to 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:113 on main: isRuntimeCompactionDelegate(contextEngine.compact)), and only then injected runtimeContext.compactionTimeoutReset. A plugin's compact() 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/inheritRuntimeCompactionDelegate so 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. compactContextEngineWithSafetyTimeout already hands every engine a fresh composed abort signal for this operation; it now registers its reset under that signal (compactionWatchdogResets, a process-global WeakMap<AbortSignal, () => void> so duplicated dist chunks share it). delegateCompactionToRuntime resolves the reset from params.abortSignal and 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 passing params unchanged or as { ...params }, survives registry host-param projection (the only host param always forwarded to compact), 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 + real delegateCompactionToRuntime, only the physical runtime is a three-stage fake; 60 ms window, 3 × 40 ms stages):

case origin/main 32e30e5 this PR
default engine pass pass
plugin passing params unchanged fail: Compaction timed out pass
logical-turn plugin spreading params fail: Compaction timed out pass
quarantined plugin's legacy fallback pass pass
plugin hangs after delegating → still bounded fail (delegate aborted first) pass

pnpm 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.ts pass. run.compaction-runtime.test.ts has 4 failures that reproduce identically on clean origin/main 32e30e5 on this host (unrelated). pnpm tsgo:core, pnpm tsgo:core:test, and pnpm check:changed pass.

Live before/after

Telegram Test Server, real-user DM, real gpt-6-astra through a forwarding proxy (timing only, no stalls injected), default timeoutSeconds (unset → 180 s). A minimal plugin context engine (ownsCompaction: false) runs a 2 s plugin-owned step, then return await delegateCompactionToRuntime(params) with params unchanged. 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).

origin/main 32e30e5 this PR 6c313a7
compaction outcome outcome=failed reason=timeout durationMs=177982, Compaction timed out outcome=compacted durationMs=526610, no timeout lines
user saw "⚠️ This conversation is too long, and shortening it took too long. Try again, use /compact, or use /new to start a fresh session." a normal assistant answer to the question (568 s after the DM)

Per-request compaction durations (proxy log, ms):

stage before after
chunk 1 summarize (254k in) 53,883 66,541
chunk 1 update (136k in) 71,908 94,473
chunk 2 summarize (255k in) 51,576 → aborted by the aggregate deadline 74,039
chunk 2 update (138k in) – 98,023
merge – 35,076 (upstream stream ended early; retried)
merge retry – 148,478
small follow-up summarize – 8,941

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-tail line (also present in normal default-engine compactions; unrelated to the watchdog).

Bounded cost

  • Production: +27 / −106 (net −79) across 7 files; tests +172 / −157; docs +1 / −1.
  • Runtime cost per compaction: one WeakMap.set at the host boundary and one WeakMap.get in the delegate; entries are collected with the operation's signal. No new timers, retries, config, SDK exports, warnings, or messages.
  • Worst-case deadline: unchanged for plugin-owned work (one window); built-in compaction reached through a plugin gets the same per-request windows as the default engine.

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.

@clawsweeper

clawsweeper Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: M labels Oct 2, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 2, 2026
@clawsweeper

clawsweeper Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 2, 2026, 2:40 PM ET / 18:40 UTC (Revision 3).

ClawSweeper review

What this changes

The 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
Reviewed head: 6c313a7f3e3568522efc201aa382ede0ef4d35be

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused simplification with strong real before/after evidence and no blocking correctness finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): The captured exact-head Test Server run exercises a real delegating plugin through the host watchdog and native compactor: baseline times out near 180 seconds, while after-fix serial requests complete in 526.6 seconds and produce a normal reply. No stored-data contract changes require migration proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (logs): The captured exact-head Test Server run exercises a real delegating plugin through the host watchdog and native compactor: baseline times out near 180 seconds, while after-fix serial requests complete in 526.6 seconds and produce a normal reply. No stored-data contract changes require migration proof.
Evidence reviewed 9 items Pinned introduction and merge result: Inspected the merge-base-to-head changes. Independently verified that the test merge records the pinned base followed by the exact PR head; its watchdog and delegate changes match the introduced repair.
Current main still excludes plugin wrappers: Fetched main still checks compact function identity before supplying the reset callback. A plugin method calling the documented delegate is not the tagged function, so healthy serial requests share an aggregate deadline.
Latest release retains the old mechanism: The supplied v2026.9.7 release commit also conditionally injects refresh based on function identity; this repair is not already shipped there.
Findings None None.
Security None None.

How this fits together

Context 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]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source -79, Tests +15, Docs 0. Total -64 across 16 files.

View PR surface stats
Area Files Added Removed Net
Source 7 27 106 -79
Tests 8 172 157 +15
Docs 1 1 1 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 16 200 264 -64

Review metrics

None.

Technical review

Best 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.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This repairs large-session compaction failures limited to plugins delegating to the built-in runtime.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): The captured exact-head Test Server run exercises a real delegating plugin through the host watchdog and native compactor: baseline times out near 180 seconds, while after-fix serial requests complete in 526.6 seconds and produce a normal reply. No stored-data contract changes require migration proof.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured exact-head Test Server run exercises a real delegating plugin through the host watchdog and native compactor: baseline times out near 180 seconds, while after-fix serial requests complete in 526.6 seconds and produce a normal reply. No stored-data contract changes require migration proof.

Evidence

What I checked:

  • Pinned introduction and merge result: Inspected the merge-base-to-head changes. Independently verified that the test merge records the pinned base followed by the exact PR head; its watchdog and delegate changes match the introduced repair. (6c313a7f3e35)
  • Current main still excludes plugin wrappers: Fetched main still checks compact function identity before supplying the reset callback. A plugin method calling the documented delegate is not the tagged function, so healthy serial requests share an aggregate deadline. (src/agents/embedded-agent-runner/compaction-safety-timeout.ts:113, 165bd8d01db8)
  • Latest release retains the old mechanism: The supplied v2026.9.7 release commit also conditionally injects refresh based on function identity; this repair is not already shipped there. (src/agents/embedded-agent-runner/compaction-safety-timeout.ts:113, c074824a27c9)
  • Existing supported plugin contract: The context-engine guide explicitly demonstrates a non-owning plugin calling delegateCompactionToRuntime(params), and src/plugin-sdk/core.ts continues exporting that helper. The patch repairs this existing path without adding a public API or setting. Public docs: docs/plugins/architecture-internals/context-engines.md. (docs/plugins/architecture-internals/context-engines.md:76, 6c313a7f3e35)
  • Operation-scoped refresh and cancellation: The host registers refresh under its composed signal and the delegate retrieves it from that signal. Registry projection always retains abortSignal for compact. Caller cancellation, queued writer fences, recovery commit assertions, and the timeout owner's settled/aborted reset guard remain intact; no persisted format changes. (src/context-engine/delegate.ts:112, 6c313a7f3e35)
  • Exact-head live before/after proof: The captured body reports a real Telegram Test Server DM through a delegating plugin and real provider, with the same large synthetic transcript and default timeout. Baseline compaction fails at 177982 ms; the pinned head completes at 526610 ms and returns a normal answer. Seven serial requests complete, with the longest at 148478 ms below the 180-second window. This exercises the changed host-watchdog-to-native-delegate path. (6c313a7f3e35)

Likely related people:

  • VACInc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (2 earlier review cycles)
  • reviewed 2026-10-02T16:45:09.471Z sha 6c313a7 :: needs changes before merge. :: none
  • reviewed 2026-10-02T18:28:53.752Z sha 6c313a7 :: needs changes before merge. :: none

@obviyus

obviyus commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. labels Oct 2, 2026
@obviyus
obviyus marked this pull request as ready for review October 2, 2026 18:36
@obviyus

obviyus commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus
obviyus merged commit 02ec714 into main Oct 2, 2026
226 of 232 checks passed
@obviyus
obviyus deleted the fix/delegated-compaction-watchdog branch October 2, 2026 18:49
@obviyus

obviyus commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

Landed as 02ec714.

Checked on the exact head 6c313a7: reviewer LAND, ClawSweeper ready, CI green, and live before/after Telegram proof with real model timings in the body.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 3, 2026
…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]>
obviyus added a commit that referenced this pull request Oct 9, 2026
…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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 10, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant