Skip to content

fix: compaction aborts a slow summary request that is still streaming - #164263

Merged
obviyus merged 6 commits into
mainfrom
fix/compaction-idle-watchdog
Oct 4, 2026
Merged

obviyus merged 6 commits into
mainfrom
fix/compaction-idle-watchdog

Conversation

@obviyus

@obviyus obviyus commented Oct 3, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #130971

What Problem This Solves

Fixes: compaction aborts a healthy summary request that is still streaming output, because the timeout window (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 "⚠️ This conversation is too long, and shortening it took too long." while the model was still writing the summary.

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 main once #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 (onStarted in src/agents/embedded-agent-runner/compaction-session-execution.ts:343-348 on main), and after success or before a thinking fallback. Nothing refreshes it while a request streams, so a single request is bounded by timeoutSeconds from 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.

  • Progress = a streamed model output delta. The compaction diagnostic stream wrapper already sees every provider event. It now calls a new onOutputDelta callback for each non-empty text_delta, thinking_delta or toolcall_delta (attempt.model-diagnostic-lifecycle.ts). Compaction wires it to the same refresh as onStarted, 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/*_end events, 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.
  • Ceiling. runAbortableTimeout takes an optional maxTotalMs: each reset arms min(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 at 10 × timeoutMs from the operation start, so there is no new config key. It is derived from the existing knob: raising timeoutSeconds raises 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).
  • Summary cutoff. The host registers { reset, deadlineAt } for its signal (compactionWatchdogs, replacing the reset-only compactionWatchdogResets), and delegateCompactionToRuntime forwards 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 /compact keeps 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.
  • Plugin work stays bounded once. Only the runtime delegate's model requests refresh the host window. Plugin code before or after delegating, and engines that never delegate, still get one window. The fix: auto-compaction times out on large sessions when a context-engine plugin delegates compaction #163636 test "keeps plugin-owned work after the delegate under one host window" and the fix: Responses sessions compact before reaching context limit #130993 test "threads timeout cancellation into the plugin compactor" are unchanged and pass.
  • Same model everywhere. Manual /compact, sessions.compact and preflight/overflow/timeout recovery all enter through compactContextEngineWithSafetyTimeout. 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 → real delegateCompactionToRuntime → native watchdog → real AgentSession → core summarizer → diagnostic stream wrapper. Only the provider stream is scripted (one text delta every 20 s, 30 s window, 300 s ceiling).

case origin/main b2bdae9 this PR
streams 220 s, longer than the window fail: { ok: false, reason: "Compaction timed out" } at 30 s compacts
last delta at 100 s, then silent fail: settled at 30 s, before the idle deadline fails at exactly 130 s with "Compaction timed out"
last delta at 100 s, then empty-delta keepalives fail: settled at 30 s fails at exactly 130 s (keepalives don't extend it)
delta every 20 s forever, 5 s setup (manual) fail: settled at 30 s fails at exactly 270 s, one window before the 300 s ceiling; the last delta (265 s) leaves less than a window
automatic compaction, last delta at 100 s then silent n/a idle window fires; #164246's deterministic reduction is committed (ok: true, compacted: true)
automatic compaction, delta every 20 s forever, 5 s setup n/a summary cutoff at 270 s; deterministic reduction committed. At ea03e21 (before the cutoff) this case returned { 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.ts adds that an already-passed deadline times out immediately without Node's TimeoutNegativeWarning (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. Also pnpm tsgo:core, oxlint/oxfmt on the changed files, and pnpm config:docs:check.

Live: Telegram Test Server, real gpt-6-astra

Setup: real-user DM on the Telegram Test Server, built dist of 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):

origin/main b2bdae9 this PR
compaction outcome=failed reason=timeout durationMs=110758 outcome=compacted durationMs=301232, one attempt
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 answer to the question

Per compaction request (ms; gap = longest silence between forwarded output deltas):

stage before: duration / first delta / max gap after: duration / first delta / max gap
chunk 1 summarize (254k in) 50,311 / 7,668 / 314 43,589 / 5,575 / 217
chunk 1 update (136k in) 60,000 aborted while streaming: last delta at 59,989, max gap 152 57,662 / 5,689 / 215
chunk 2 summarize (255k in) – 50,885 / 10,958 / 207
chunk 2 update (139k in) – 60,772 / 5,227 / 344
merge (12k in, 8.3k out) – 83,309 / 4,686 / 204
follow-up summarize – 4,399 / 1,457 / 134

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: compaction outcome=compacted durationMs=326671 in one attempt (6 serial requests, no retries, no timeout lines). The user got a normal answer to the question 334 s after sending it.

stage duration / first delta / max gap (ms)
chunk 1 summarize (254k in) 46,024 / 4,721 / 632
chunk 1 update (136k in) 63,671 / 6,026 / 282
chunk 2 summarize (255k in) 51,736 / 5,854 / 342
chunk 2 update (139k in) 64,837 / 5,107 / 327
merge (12k in, 9.0k out) 96,317 / 6,967 / 349
follow-up summarize 3,529 / 1,266 / 80

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 gpt-6-astra output 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 ended outcome=failed reason=timeout durationMs=186742 (Compaction timed out), and the user got the existing timeout message ("⚠️ 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.

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 local raceCompactionWithAbortSignal with the shared racePromiseWithAbortSignal (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 the createAgentSessionForEmbeddedRunner SDK export in favor of createAgentSession; the PR's test now mocks createAgentSession.
  • docs/.generated/config-baseline.sha256: regenerated on the new base.

Same harness and 963k-token seed as above, built dist at 5532d8e8eb, default timeoutSeconds:

Scenario Outcome Artifact
Large session, default settings outcome=compacted durationMs=387436, one attempt, 6 compaction requests; user got a normal two-sentence answer dcw-live/idle/rebased-default
Forced mid-stream stall (proxy stops forwarding after 40 real deltas, 12.9 s in) gateway closed the request 180.005 s after the last delta; outcome=failed reason=timeout durationMs=193339; user got the existing "⚠️ This conversation is too long, and shortening it took too long. …" text, nothing new dcw-live/idle/rebased-stall
Plugin-delegating context engine (delegating-probe, ~2 s plugin work then delegateCompactionToRuntime) outcome=compacted durationMs=361406, one attempt; user got a normal answer dcw-live/idle/rebased-plugin

The 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:

Same harness and 963k-token seed, built dist of each head:

Scenario ea03e21 (rebased, before the cutoff) d1e3885 (this head) Artifact
timeoutSeconds: 30 (ceiling 300 s), summary still streaming at the ceiling merge request aborted 32.3 s in, 41 ms after its last delta; trigger=budget outcome=failed reason=timeout durationMs=299983; user got "⚠️ This conversation is too long, and shortening it took too long. …" summary cut at the cutoff (merge request 27.8 s in, still streaming); [compaction-diag] fallback … reason=timeout summary=deterministic, outcome=compacted reason=timeout summary=deterministic durationMs=269874; user got a normal two-sentence answer dcw-live/idle/r2-before-ceiling30, r2-after-ceiling30
Large session, default settings – outcome=compacted reason=none durationMs=334793, one attempt, 6 compaction requests (longest 77.9 s, max delta gap 474 ms); normal answer dcw-live/idle/r2-default
Forced mid-stream stall (proxy stops forwarding after 40 real deltas, 5.7 s in) – gateway closed the request 180.005 s after the last delta; with #164246 on main this automatic compaction now commits the deterministic reduction (outcome=compacted reason=timeout summary=deterministic durationMs=185978) and the user got a normal answer instead of the timeout text dcw-live/idle/r2-stall
Plugin-delegating context engine (delegating-probe, ~2 s plugin work then delegateCompactionToRuntime) – outcome=compacted reason=none durationMs=321600, one attempt; normal answer dcw-live/idle/r2-plugin

No TimeoutNegativeWarning or other new warning lines in any gateway log; no new user-visible text.

Compatibility

agents.defaults.compaction.timeoutSeconds changes meaning. On main it 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, which main didn't have.

  • Who notices: a built-in compaction that keeps making progress for more than 10 windows now stops: the summary request ends one window before the ceiling, an automatic compaction then commits fix(compaction): commit a deterministic reduction after a summary timeout #164246's deterministic reduction, and manual /compact fails 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.
  • What to do: raise timeoutSeconds. That raises both the idle window and the ceiling. No config migration is needed, and existing values stay valid.
  • Unchanged: plugin-owned compaction work keeps one window for the complete operation, a request that is silent from the start fails at the same time as on main, and caller Stop or a run timeout still cancels immediately.
  • Docs: the timeoutSeconds entries in docs/gateway/config-agents/heartbeat-compaction-and-streaming.md and 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

  • Production (vs merge base): +83 / −24 across 8 files (the summary cutoff added the compactionWatchdogs deadline, its forwarding in delegate.ts, one internal param and the zero clamp). Tests +205 (one describe with 6 cases sharing one fixture, plus one with-timeout case). Docs and help: 2 lines plus the regenerated config hash.
  • Runtime: one type/length check per streamed provider event on compaction requests, plus a clearTimeout/setTimeout pair per output delta. Normal agent turns pass no onOutputDelta, so they skip the check. No new timers, retries, config keys, SDK exports, warnings or messages.
  • Worst-case deadline: a silent request dies one window after its last output (same as main when 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.
  • Live proof spend: about 2.4M input and 65k output gpt-6-astra tokens 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

@clawsweeper

clawsweeper Bot commented Oct 3, 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.

@obviyus

obviyus commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: M labels Oct 3, 2026
@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed October 4, 2026, 12:23 PM ET / 16:23 UTC (Revision 11).

ClawSweeper review

What this changes

Compaction 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
Reviewed head: d1e38859e77d10fee4b16e264204ce28f74bfd28

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Strong before/after runtime evidence and focused deadline regressions support the implementation, with the compatibility decision already accepted.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): The hash-matched complete body records final-head real Gateway/provider runs covering healthy streaming, forced silence, plugin delegation, and deterministic recovery at the summary cutoff. Config keys, types, defaults, and stored formats remain compatible; no data-model migration is introduced.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (logs): The hash-matched complete body records final-head real Gateway/provider runs covering healthy streaming, forced silence, plugin delegation, and deterministic recovery at the summary cutoff. Config keys, types, defaults, and stored formats remain compatible; no data-model migration is introduced.
Evidence reviewed 9 items Pinned introduced change: Reviewed the merge-base-to-head delta at the supplied identities. The stale test merge was not used to infer removal of current-main behavior.
Progress and deadline owners: Nonempty text, thinking, and tool-call deltas refresh both watchdogs. The host carries its ceiling through the existing delegate; summary generation stops one window earlier so automatic deterministic recovery remains reachable. Empty deltas do not refresh timers.
Bounded timer behavior: Each reset clamps the timer to the remaining total budget, leaves an already-due timer intact, and clamps an initially expired deadline to zero. Callers omitting the new optional total budget retain their existing timeout behavior.
Findings None None.
Security None None.

How this fits together

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

Before merge

  • Review config compatibility - Confirm compatibility and upgrade impact for the changed config or default surface before merge.
Agent review details

Security

None.

PR surface

Source +59, Tests +202, Docs 0, Generated 0. Total +261 across 13 files.

View PR surface stats
Area Files Added Removed Net
Source 9 84 25 +59
Tests 2 205 3 +202
Docs 1 1 1 0
Config 0 0 0 0
Generated 1 2 2 0
Other 0 0 0 0
Total 13 292 31 +261

Review metrics

Metric Value Why it matters
Default timeout bounds 180-second idle window; 27-minute summary cutoff; 30-minute host ceiling The accepted policy reserves one complete window for automatic recovery.
Production versus regression growth Runtime production net +59 lines; tests net +202 lines Production growth carries the deadline and observes output through existing owners; shared regression setup exercises six deadline scenarios.

Technical review

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

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.

Label justifications:

  • P2: This is a bounded long-session reliability improvement with a concrete slow-stream failure path.
  • merge-risk: 🚨 compatibility: The existing setting gains idle semantics and a finite operation ceiling; the verified maintainer has explicitly accepted that upgrade tradeoff.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): The hash-matched complete body records final-head real Gateway/provider runs covering healthy streaming, forced silence, plugin delegation, and deterministic recovery at the summary cutoff. Config keys, types, defaults, and stored formats remain compatible; no data-model migration is introduced.
  • proof: sufficient: Contributor real behavior proof is sufficient. The hash-matched complete body records final-head real Gateway/provider runs covering healthy streaming, forced silence, plugin delegation, and deterministic recovery at the summary cutoff. Config keys, types, defaults, and stored formats remain compatible; no data-model migration is introduced.

Evidence

What I checked:

  • Pinned introduced change: Reviewed the merge-base-to-head delta at the supplied identities. The stale test merge was not used to infer removal of current-main behavior. (d1e38859e77d)
  • Progress and deadline owners: Nonempty text, thinking, and tool-call deltas refresh both watchdogs. The host carries its ceiling through the existing delegate; summary generation stops one window earlier so automatic deterministic recovery remains reachable. Empty deltas do not refresh timers. (src/agents/embedded-agent-runner/compaction-session-execution.ts:300, d1e38859e77d)
  • Bounded timer behavior: Each reset clamps the timer to the remaining total budget, leaves an already-due timer intact, and clamps an initially expired deadline to zero. Callers omitting the new optional total budget retain their existing timeout behavior. (src/node-host/with-timeout.ts:24, d1e38859e77d)
  • Still necessary on main and latest release: Fetched main still refreshes at request starts without an output-delta callback. GitHub source for v2026.9.8 likewise retains request-boundary refreshes. The merged delegation and deterministic-recovery repairs do not implement this PR's streaming idle window. (src/agents/embedded-agent-runner/compaction-session-execution.ts:317, 94975271e351)
  • Maintainer acceptance verified: fix: compaction aborts a slow summary request that is still streaming #164263 (comment) explicitly accepts unchanged config values, idle-window semantics, and the ten-window ceiling. GitHub independently confirms obviyus has the maintain role. The current head preserves that policy while reserving the final window for already-merged recovery; another acceptance request is unnecessary.
  • Complete captured runtime proof: Read the full GitHub body and verified SHA-256 a432b439e1c42c5acfdbfe250993be5258b40d52a876b85482c6a296a7cee517 matches the captured snapshot. Final-head live evidence exercises the real Gateway and provider through Telegram Test Server: the 30-second-window ceiling case commits a deterministic reduction at 269874 ms; default compaction completes at 334793 ms; an injected stall expires 180.005 seconds after its last delta and recovers; plugin delegation completes at 321600 ms. Earlier natural-stream before/after evidence shows requests exceeding a 60-second window completing successfully. (d1e38859e77d)

Likely related people:

  • obviyus: 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)
  • VACInc: 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 (10 earlier review cycles; latest 8 shown)
  • reviewed 2026-10-03T11:29:06.277Z sha 82bf344 :: blocked before merge. :: none
  • reviewed 2026-10-03T11:40:55.506Z sha 82bf344 :: blocked before merge. :: none
  • reviewed 2026-10-04T10:14:08.626Z sha 82bf344 :: blocked before merge. :: none
  • reviewed 2026-10-04T11:20:37.498Z sha 5532d8e :: blocked before merge. :: none
  • reviewed 2026-10-04T11:33:16.263Z sha 5532d8e :: blocked before merge. :: none
  • reviewed 2026-10-04T12:14:29.690Z sha 5532d8e :: blocked before merge. :: none
  • reviewed 2026-10-04T15:02:24.237Z sha ea03e21 :: blocked before merge. :: none
  • reviewed 2026-10-04T15:23:04.788Z sha d1e3885 :: blocked before merge. :: none

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 3, 2026
@obviyus

obviyus commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

Maintainer decision on the timeout policy: accept option A. agents.defaults.compaction.timeoutSeconds becomes the per-request idle window (refreshed by request starts and non-empty streamed output deltas, not by keepalives), and built-in compaction gets a 10 × timeoutSeconds operation ceiling (30 min at the default). Measured runs used 1.8 and 2.9 windows; raising timeoutSeconds raises both bounds. The upgrade impact is in the PR body's Compatibility section, and the docs and help text for timeoutSeconds are updated.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

Maintainer decision: accepted. agents.defaults.compaction.timeoutSeconds now means the longest a built-in compaction request may go without streamed progress. Built-in compaction is capped at 10 × timeoutSeconds overall, 30 minutes at the default. Plugin-owned compaction work keeps its single host window (#130993).

@obviyus
obviyus marked this pull request as ready for review October 4, 2026 10:10
@obviyus

obviyus commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus
obviyus force-pushed the fix/compaction-idle-watchdog branch from 82bf344 to 5532d8e Compare October 4, 2026 11:16
@obviyus

obviyus commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

@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 createAgentSession rename from #164768.

@clawsweeper

clawsweeper Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

Maintainer config compatibility review for head 5532d8e: confirmed.

  • agents.defaults.compaction.timeoutSeconds keeps its key, type and default. Existing values stay valid and need no Doctor migration.
  • Upgrade impact: with the same setting, built-in compaction gets more time, not less, while it keeps streaming. The new limit is the 10-window operation ceiling (30 minutes at the default 180 s), well above the measured runs (327–527 s). Operators who need more raise timeoutSeconds, which raises both bounds.
  • Requests that are silent from the start, plugin-owned work, Stop and run timeouts behave as on main.

Accepted for landing.

@obviyus

obviyus commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added the rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. label Oct 4, 2026
@clawsweeper clawsweeper Bot removed the rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. label Oct 4, 2026
… 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
@obviyus
obviyus force-pushed the fix/compaction-idle-watchdog branch from 5532d8e to ea03e21 Compare October 4, 2026 14:56
@clawsweeper clawsweeper Bot added 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 4, 2026
@obviyus

obviyus commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Oct 4, 2026
@obviyus
obviyus merged commit 5f497e7 into main Oct 4, 2026
138 checks passed
@obviyus
obviyus deleted the fix/compaction-idle-watchdog branch October 4, 2026 16:24
@obviyus

obviyus commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

Landed as 5f497e7.

Checked on the exact head d1e3885: fresh reviewer LAND, CI green, ClawSweeper no findings (its config-compatibility checkbox was cleared by the maintainer), and live Telegram E2E rerun after the rebase, in the body.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 5, 2026
…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.
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 merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor 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