Skip to content

fix(compaction): commit a deterministic reduction after a summary timeout - #164246

Merged
obviyus merged 15 commits into
mainfrom
fix/compaction-failure-fallback
Oct 4, 2026
Merged

obviyus merged 15 commits into
mainfrom
fix/compaction-failure-fallback

Conversation

@obviyus

@obviyus obviyus commented Oct 3, 2026 •

Copy link
Copy Markdown
Collaborator

Refs #164220

What Problem This Solves

An automatic compaction whose summary request times out ends the turn with "⚠️ This conversation is too long, and shortening it took too long…". The session stays above the threshold, so every following message runs the same summary again, waits out the same 180 s window, and fails again. The conversation stays dead until someone runs /compact or /new.

Root cause (provenance)

executePreparedCompactionSession (src/agents/embedded-agent-runner/compaction-session-execution.ts, client-summary block) turned every summary-stage failure into fail() without committing anything. The next turn's preflight (runSessionCompactionIfNeeded in agent-runner-memory.ts, "Preflight compaction required but failed") or overflow recovery (overflow-context-recovery.ts, kind=compaction_failure) then ran the same compaction again. The per-request host watchdog from #130993 (a93a015) and #163636 (02ec714) is kept. Nothing used the cut that compaction had already prepared once that watchdog fired.

Fix

  • Reduction. compactWithoutSummary(preparation) in agent-core compaction.ts builds the commit-ready artifact without a model call. It shares finalizeCompaction with compact().
    • It uses the cut prepareCompaction already chose, so the recent suffix stays verbatim and tool-call/result pairs stay intact.
    • It carries the previous summary forward, keeps file operations and the unresolved request, and names how many messages were dropped.
    • The loss notice and a split turn's raw source ask are required content during fitting; only the carried summary shrinks. This keeps the fix: Responses sessions compact before reaching context limit #130993 split-turn source-ask invariant. The source ask uses safeguard's existing 2,000-character bound: formatRequiredAskContext moved from compaction-safeguard.ts into agent-core, and both now share it.
  • Commit path. AgentSessionCompaction has a new "deterministic" summary policy. It skips auth, summary hooks, and the model, and commits through the existing appendCompactionAsync. Transcript rows are untouched, so a later model compaction stacks on top normally (covered by a test).
  • Trigger: an actual summary timeout only. Either the summary watchdog fired (its composed signal aborted while the caller's params.abortSignal did not), or the provider answered HTTP 408 or 504. The status comes from structured provider identity: runSummarizationCompletion now returns SummaryProviderError, which carries the failed provider response. The delegate finds it through the error's cause chain (safeguard wraps it) instead of parsing wrapped text. Failover's broader "timeout" class, which also covers fast 5xx, 410, DNS failures, and text-only "request timed out", keeps its existing outcomes, including the model fallback chain. The compaction must also be automatic (not manual), and the caller must still be live: no Stop, run timeout, or outer host deadline. The delegate re-arms the delegated watchdog synchronously before committing.
  • Persistence-stage timeout. A new onSummaryReady signal marks the end of generation. A timeout during persistence keeps the existing failure, so a real summary is never discarded.
  • Backoff: the committed reduction brings the session under the threshold, so the next turn does not compact. No new state, store, or config.
  • Diagnostics: [compaction-diag] fallback … reason=timeout summary=deterministic (warn), and the debug end line reads reason=timeout summary=deterministic.
  • No model fallback after a timeout (deliberate). A timed-out summary commits the reduction instead of trying the next model. Each extra candidate could add another full window to the user's wait; with two configured fallbacks that is about 9 minutes. On main the chain never ran after a watchdog timeout anyway, because the outer watchdog fired at the same moment. Rate limits and other failover errors still use the chain. A test documents this.

Safeguard timeout exception (accepted by the maintainer)

In safeguard mode, a summary timeout now commits this reduction, so safeguard gives up its identifier-retention guarantee for that compaction:

  • Older facts that were never summarized leave the model context.
  • Later compactions do not bring them back, because each one starts from the previous compaction boundary. Transcript rows stay for history and explicit retrieval.
  • The recent suffix, tool pairs, the pending request, and a split turn's original request are kept verbatim.

Why: the alternative dead-ends the session, with every turn waiting out the same timeout. The exception covers only summary-generation timeouts while the caller is still live. Quality rejections and all other errors keep the preserve-history outcome. Documented in docs/concepts/compaction.md.

Decisions kept

User-visible

No new notice. The answer arrives as usual. notifyUser users see the same start/end notices as for any successful compaction. NO_REPLY, quiet mode, and delivery: none paths are untouched.

Bounded cost

  • One wasted summary window per timed-out compaction (the configured timeoutSeconds, default 180 s).
  • Then local work only: no model call, one transcript append.
  • No later turn pays the window again until the transcript grows back to the threshold.
  • No extra model candidates are tried after a timeout.

Evidence

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

Setup:

  • DM with an isolated gateway on the native context engine;
  • the synthetic 1250-message seed (~968k estimated tokens) in front of the real OpenAI API, through a timing proxy;
  • the proxy stalls only compaction-summary requests, because the live model can't be forced to stall; everything else is forwarded live;
  • two user messages about 9 minutes apart.

Before: origin/main 96526f7e863c

t (ms) Who Message
48081 tester Quick check-in after all that work: in two short sentences, what was the last service we discussed, and what should I look at next?
232599 SUT ⚠️ This conversation is too long, and shortening it took too long. Try again, use /compact, or use /new to start a fresh session.
600357 tester Thanks. In one sentence: what is the biggest risk in that next step?
782080 SUT ⚠️ This conversation is too long, and shortening it took too long. Try again, use /compact, or use /new to start a fresh session.

Proxy: two stalled summarize requests, 179984 ms and 179995 ms (one per message). No answer request for either message.

After: this PR at f310cdfbfee4 (exact head)

t (ms) Who Message
35987 tester (same first question)
225186 SUT Your last request concerned report-builder (Go), specifically deprecating its streaming feature flag. Next, inspect that flag's definition and callers; my previous reply went off-topic and showed no verified changes.
600283 tester (same second question)
604085 SUT The biggest risk is missing runtime or configuration dependencies and wrongly concluding that report-builder's streaming feature flag is safe to retire.

Proxy and gateway:

  • One stalled summarize request (179986 ms, client-aborted), which exercises the watchdog-signal gate.
  • Gateway logged [compaction-diag] fallback … trigger=budget provider=openai/gpt-6-astra reason=timeout summary=deterministic, then end … outcome=compacted reason=timeout summary=deterministic.
  • Message 1 was answered by a live gpt-6-astra request with 30,353 input tokens.
  • Message 2 was answered in about 4 s with zero summary requests (30,925 input tokens).
  • No extra chat messages.

Rebased head 4ca7a00 re-run (Telegram Test Server, real gpt-6-astra)

Same harness, seed, and summary-stalling proxy as above, built dist at 4ca7a00588c6 (current main plus this PR). Every run passed.

Scenario What happened Artifact
Summary timeout, then a second message Q1 at 53.5 s; one stalled summarize request; [compaction-diag] fallback … reason=timeout summary=deterministic, then end … outcome=compacted reason=timeout summary=deterministic durationMs=180284; a live answer at 246.8 s. Q2 at 600.3 s, answered at 604.3 s with no new summary request. cff-live/rebased-timeout
Stop during compaction Q1 at 53.9 s; /stop at 100.4 s, then "⚙️ Agent was aborted." at 100.8 s. Compaction outcome=failed … Reply_operation_aborted_by_user durationMs=38971, no deterministic commit. The next message (420 s) found the session still over the threshold: it compacted again (stalled summary, then the deterministic reduction) and answered AFTERSTOP at 604.7 s. cff-live/rebased-stop
Manual /compact with a stalled summary /compact at 53.3 s; "⚙️ Compaction failed: Compaction timed out • Context ?/922k" at 241.3 s; end trigger=manual … outcome=failed reason=timeout, no fallback line. cff-live/rebased-manual

No new user-visible messages in any run.

Tests

  • src/auto-reply/reply/agent-runner-compaction-fallback.test.ts: two real runReplyAgent turns (preflight, native delegate, SQLite, local OpenAI-compatible provider whose summary requests get HTTP 408). On origin/main, turn 1 returns the timeout notice (verified). On this branch, turn 1 returns ANSWER-1 with one deterministic compaction, and turn 2 returns ANSWER-2 with zero new summary requests.
  • src/agents/embedded-agent-runner/compact.summary-fallback.test.ts: real queued compaction, AgentSession, and SQLite.
    • A bodyless 408 commits the reduction with a verbatim tool-pair suffix and full history, and a later model compaction carries the loss notice forward. Fails on main.
    • With a fallback model configured, a 408 commits the reduction without trying it.
    • Safeguard mode with a bodyless 408 reduces, which exercises the cause-chain lookup.
    • These keep failing with no entry: Stop, manual timeout, a 400, a fast 500, and a bodyless 410. The 500 and 410 fall into failover's broad "timeout" class and reduced at 4f912a5.
    • No case waits on a real deadline. Stop waits on a request-arrival signal.
  • compact.hooks.test.ts:
    • A timeout after summary generation (persistence stage) stays a failure (fake clock).
    • Safeguard provider 408 reduces without switching models.
    • A text-only "request timed out" keeps main's chain and cancel outcomes.
    • A corrective-attempt 408 stays a terminal quality cancellation.
  • agent-core compaction.test.ts: the loss notice, the unresolved request, and a 1,200-character split-turn ask with a mid constraint survive a capped previous summary and a constrained budget.
  • pnpm tsgo:core and pnpm tsgo:core:test are clean. Focused suites pass: agent-core compaction, agent-session-compaction, compact.hooks, compact.delegate, compaction-safety-timeout, compaction-safeguard, and the new files.

Test cost (measured locally, isolated runs)

  • compact.summary-fallback.test.ts: 8 tests, about 60 s wall clock for the file run (including the vitest worker build). The first case takes about 27 s, which is cold module import; the rest take about 2 s each.
  • agent-runner-compaction-fallback.test.ts: 1 test, about 8 s.
  • compact.hooks.test.ts: the whole file (90 tests) took about 38–57 s wall clock isolated. The new persistence-stage case runs on a fake clock in about 2 s.
  • The agent-core additions are pure and sub-second.

Review

Earlier design, with model-fallback deferral: four gpt-6-astra rounds fixed safeguard timeout classification, loss-notice and split-turn-ask fitting, and several fallback-chain edge cases. On the maintainer's simplification decision, the chain deferral was removed entirely, along with its code and tests.

Fresh rounds on the simplified design:

  • 3d5660a: one finding (a persistence-stage timeout discarded a generated summary). Fixed with onSummaryReady.

  • 2c01eb0: LAND.

  • Two extra maintainer-requested reviews then found that wrapped summary text made a fast 500 look like a timeout and missed a bodyless 408, and that the split ask used the 800-character bound. Fixed with SummaryProviderError and the shared 2,000-character bound.

  • 4f912a5: CHANGES. Failover's "timeout" class is broader than a timeout (410, DNS), so the gate was narrowed to watchdog-fired or 408/504. Safeguard corrective provenance was also raised.

  • e1737e9: CHANGES. Passing the corrective error made quality cancellations fallback-eligible, so that change was reverted and the case deferred (see Decisions kept).

  • f310cdf: LAND, no findings.

  • Rebase onto current main (no conflicts). Adapted to newer main decisions:

    • refactor(config): retire agents.list and default markers from the authored config type #164103 retired agents.list from the authored config type, so the turn-level test fixture now uses keyed agents.entries.
    • compaction-session-execution.ts passed the 700-line cap, so the summary-timeout classification moved, unchanged, into compact-reasons.ts (isSummaryTimeoutFailure), next to resolveCompactionFailure.
    • Lint fixes in compact.summary-fallback.test.ts.
    • The fresh review at be18e614 found that the extraction let a watchdog abort short-circuit before resolveCompactionFailure's model-fallback-stop rethrow. 4ca7a005 restored the original order, and the fresh review at 4ca7a005 returned LAND, no findings.

LOC

  • vs merge base cc1a29734ab3: production +197/−67 (6 files), docs +7/−2, tests +663/−5 (4 files), test routing +2.
  • vs the previous LAND head 2c01eb0: production +63/−28, tests +52/−14.

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

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: L labels Oct 3, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 3, 2026
@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 4, 2026, 9:15 AM ET / 13:15 UTC (Revision 18).

ClawSweeper review

What this changes

Automatic conversation compaction gains a model-free reduction after qualifying summary timeouts, with diagnostics, documentation, and regression coverage.

Merge readiness

✅ Ready for maintainer review

This PR remains useful: current main and the latest release still fail without reducing context after a summary timeout. No blocking introduced defect was found, the recorded runtime proof supports recovery, and the safeguard tradeoff has verified maintainer acceptance.

Priority: P1
Reviewed head: 4ca7a00588c6fff33a459ef5b89c2d5c07e1b52d

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Strong before/after runtime evidence accompanies a focused recovery path with meaningful cancellation, persistence, and retention controls.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The captured real Gateway and Telegram Test Server trace exercises the native summary-timeout owner: one stalled summary commits a reduction, the reply continues through a real provider, and the next turn answers without another summary request. Production-source comparison supports reusing that prior-head proof. Existing compaction serialization and schema are unchanged.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured real Gateway and Telegram Test Server trace exercises the native summary-timeout owner: one stalled summary commits a reduction, the reply continues through a real provider, and the next turn answers without another summary request. Production-source comparison supports reusing that prior-head proof. Existing compaction serialization and schema are unchanged.
Evidence reviewed 10 items Pinned introduction: Reviewed the merge-base-to-head introduced delta, retaining the original head and current-main identities separately; base-only refactors were not attributed to this PR.
Still necessary on current main: Current main directly awaits client compaction without deterministic timeout recovery. Required preflight subsequently throws when compaction fails. Existing manual line truncation permanently removes transcript content and does not provide this automatic recovery.
Latest release remains affected: The v2026.9.8 source likewise awaits compaction without the new timeout catch or deterministic retry. No merged replacement establishing this behavior was identified.
Findings None None.
Security None None.

How this fits together

Compaction reduces conversation context before the agent sends another model request. This change uses the existing retention and transcript owners to preserve recent messages and resume the reply when summarization times out.

flowchart TD
  A[Conversation and pending request] --> B[Choose retained recent messages]
  B --> C[Generate summary]
  C --> D{Summary timed out and caller active?}
  D -->|Yes| E[Build deterministic reduction]
  D -->|No| F[Existing summary or failure handling]
  E --> G[Validate ownership and append compaction]
  G --> H[Continue agent reply]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +148, Tests +659, Docs +5. Total +812 across 13 files.

View PR surface stats
Area Files Added Removed Net
Source 7 216 68 +148
Tests 5 664 5 +659
Docs 1 7 2 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 13 887 75 +812

Review metrics

Metric Value Why it matters
Recovery policy 2 HTTP statuses and the summary watchdog; 0 new settings The accepted behavior change is limited to actual automatic summary timeouts.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #164220
Summary: This PR addresses the canonical issue's timeout dead-end; other summarizer failures remain outside its accepted scope.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best possible solution:

Recover qualifying automatic summary timeouts through the existing compaction owner while preserving cancellation fences, retained messages, and full stored history.

Do we have a high-confidence way to reproduce the issue?

Yes: current-main source exposes the repeated-failure path, and the recorded before/after Gateway run exercises it with stalled summary requests. This review did not execute target code.

Is this the best way to solve the issue?

Yes: the patch reuses retention, finalization, and transcript persistence rather than adding retry state or destructive truncation; its intentional safeguard exception has verified acceptance.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 7de09d5a2337.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: Repeated summary timeouts leave long conversations unable to answer subsequent turns.
  • merge-risk: 🚨 compatibility: The verified maintainer-accepted exception replaces timeout model fallback with deterministic reduction, including safeguard mode.
  • merge-risk: 🚨 session-state: The accepted tradeoff removes older unsummarized facts from future model context while retaining every stored transcript message.
  • 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 (live_output): The captured real Gateway and Telegram Test Server trace exercises the native summary-timeout owner: one stalled summary commits a reduction, the reply continues through a real provider, and the next turn answers without another summary request. Production-source comparison supports reusing that prior-head proof. Existing compaction serialization and schema are unchanged.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured real Gateway and Telegram Test Server trace exercises the native summary-timeout owner: one stalled summary commits a reduction, the reply continues through a real provider, and the next turn answers without another summary request. Production-source comparison supports reusing that prior-head proof. Existing compaction serialization and schema are unchanged.

Evidence

What I checked:

Likely related people:

  • obviyus: 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)
  • Peter Steinberger: 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 (17 earlier review cycles; latest 8 shown)
  • reviewed 2026-10-03T12:34:06.282Z sha 3d5660a :: blocked before merge. :: none
  • reviewed 2026-10-03T13:16:12.271Z sha 2c01eb0 :: blocked before merge. :: none
  • reviewed 2026-10-03T13:48:40.587Z sha 2c01eb0 :: blocked before merge. :: none
  • reviewed 2026-10-03T14:05:40.815Z sha 4f912a5 :: blocked before merge. :: none
  • reviewed 2026-10-03T14:21:12.551Z sha e1737e9 :: blocked before merge. :: none
  • reviewed 2026-10-03T14:35:55.745Z sha f310cdf :: blocked before merge. :: [P2] Keep corrective-attempt watchdog timeouts terminal
  • reviewed 2026-10-03T15:09:39.775Z sha f310cdf :: blocked before merge. :: none
  • reviewed 2026-10-04T10:14:02.255Z sha f310cdf :: needs maintainer review before merge. :: none

@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

@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

@clawsweeper re-review

Owner decision recorded: the maintainer accepted the timeout-only safeguard exception (live caller, timeout-class only; quality rejections and other errors keep preserve-history). The docs and the PR body now say plainly that omitted facts are not restored by later compaction.

@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added 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. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. 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:

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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 3, 2026
@obviyus

obviyus commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@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

@clawsweeper

clawsweeper Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus
obviyus merged commit c0c6ca3 into main Oct 4, 2026
136 of 137 checks passed
@obviyus
obviyus deleted the fix/compaction-failure-fallback branch October 4, 2026 13:40
@obviyus

obviyus commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

Landed as c0c6ca3.

Checked on the exact head 4ca7a00: fresh reviewer LAND, ClawSweeper ready, CI green, and live Telegram E2E (summary timeout, Stop during compaction, manual /compact) in the body.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 5, 2026
…eout (openclaw#164246)

When an automatic compaction summary actually times out while the caller is live, the session commits a deterministic reduction (recent suffix verbatim, previous summary carried forward, loss notice, split-turn ask) so the turn answers and the next turn does not re-run the same timed-out summary. Manual /compact, Stop, run timeouts and non-timeout errors are unchanged.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Oct 9, 2026
Related: #164246

## What Problem This Solves

Fixes: two compaction reference pages still promise that safeguard mode always keeps the original history when a summary cannot be produced, but since #164246 an automatic compaction whose summary times out commits a reduction without a summary.

## User Impact

User impact: operators who read the `qualityGuard` setting or the compaction reference now see the summary-timeout exception and its retention cost (older unsummarized facts leave the model context). No behavior change.

## Why This Change Was Made

#164246 updated `docs/concepts/compaction.md` only. Two other pages kept the old guarantee:

- `docs/reference/session-management-compaction/compaction.md`: "a corrective generation failure cancels before append and leaves the original transcript authoritative." A corrective attempt that goes silent past the timeout window now commits the reduction. A corrective attempt that gets HTTP 408 still cancels, as #164246 documents under "Decisions kept".
- `docs/gateway/config-agents/heartbeat-compaction-and-streaming.md` (`qualityGuard`): "When no attempt passes, OpenClaw preserves the original history." A timed-out attempt also does not pass, and the reduction commits.

Both pages now name the exception and link to the canonical explanation in [Auto-compaction](https://docs.openclaw.ai/concepts/compaction#auto-compaction).

## Evidence

- `pnpm run docs:check-links:anchors`: `broken_links=0` (includes the new `#auto-compaction` anchors).
- `pnpm run docs:check-mdx`: passed (1340 files).
- `git diff --check`: clean.
- Wording checked against the #164246 source: `isSummaryTimeoutFailure` in `src/agents/embedded-agent-runner/compact-reasons.ts` (automatic only, summary watchdog or HTTP 408/504) and the corrective-attempt decision in the #164246 body.

Merge danger: two-way door. Docs only; a revert restores the previous text. Blast radius: documentation readers only.

Co-authored-by: Ayaan Zaidi <[email protected]>
amittell added a commit to amittell/openclaw that referenced this pull request Oct 9, 2026
Main's c0c6ca3 (openclaw#164246) moved formatRequiredAskContext into
agent-core's compaction module. The clean textual merge kept this
branch's copy in compaction-safeguard-quality.ts as well, which would
import the name twice into compaction-safeguard.ts. Keep main's owner
and drop this branch's move; the fit change is unchanged.
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
…aw#167640)

Related: openclaw#164246

## What Problem This Solves

Fixes: two compaction reference pages still promise that safeguard mode always keeps the original history when a summary cannot be produced, but since openclaw#164246 an automatic compaction whose summary times out commits a reduction without a summary.

## User Impact

User impact: operators who read the `qualityGuard` setting or the compaction reference now see the summary-timeout exception and its retention cost (older unsummarized facts leave the model context). No behavior change.

## Why This Change Was Made

openclaw#164246 updated `docs/concepts/compaction.md` only. Two other pages kept the old guarantee:

- `docs/reference/session-management-compaction/compaction.md`: "a corrective generation failure cancels before append and leaves the original transcript authoritative." A corrective attempt that goes silent past the timeout window now commits the reduction. A corrective attempt that gets HTTP 408 still cancels, as openclaw#164246 documents under "Decisions kept".
- `docs/gateway/config-agents/heartbeat-compaction-and-streaming.md` (`qualityGuard`): "When no attempt passes, OpenClaw preserves the original history." A timed-out attempt also does not pass, and the reduction commits.

Both pages now name the exception and link to the canonical explanation in [Auto-compaction](https://docs.openclaw.ai/concepts/compaction#auto-compaction).

## Evidence

- `pnpm run docs:check-links:anchors`: `broken_links=0` (includes the new `#auto-compaction` anchors).
- `pnpm run docs:check-mdx`: passed (1340 files).
- `git diff --check`: clean.
- Wording checked against the openclaw#164246 source: `isSummaryTimeoutFailure` in `src/agents/embedded-agent-runner/compact-reasons.ts` (automatic only, summary watchdog or HTTP 408/504) and the corrective-attempt decision in the openclaw#164246 body.

Merge danger: two-way door. Docs only; a revert restores the previous text. Blast radius: documentation readers only.

Co-authored-by: Ayaan Zaidi <[email protected]>
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 merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: L 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