Skip to content

fix(compaction): plan cut points in trigger units - #115309

Merged
steipete merged 1 commit into
mainfrom
steipete/compaction-planner-units-111886
Jul 28, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/compaction-planner-units-111886

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Auto-compaction's trigger measures provider context tokens (usage-based, including system prompt and tool schemas), but the cut-point planner accumulates a chars/4 estimate that excludes them. When provider usage is high while the transcript's estimated size is small (cached system prompt + tool definitions dominating), the cut walk never reaches the keepRecentTokens budget, cutIndex stays at the first entry, and compaction selects zero or near-zero messages — freeing nothing while the trigger keeps firing. Downstream this exhausts the overflow-recovery ladder (residual reports in #78562's thread) and was the root of the "safeguard thrash" residual from #100982.

Closes #111886.

Why This Change Was Made

prepareCompaction (packages/agent-core/src/harness/compaction/compaction.ts) now normalizes the retained-tail budget into trigger units: it computes the ratio of provider usage tokens to the summed per-message estimates and divides keepRecentTokens by it (clamped to ≥1 so estimates above usage never inflate the tail, and bounded so the budget never drops below one token). The kept tail then costs ~keepRecentTokens in the same units the trigger measures, so the cut point advances past compactable prefix whenever the trigger fires. When no finite usage/estimate ratio exists, the scale is 1 and behavior is byte-identical to before. Auto-skip on genuinely empty cuts and the manual keepRecentTokens: 0 full-branch retry are preserved unchanged.

User Impact

Sessions with high provider usage but compact transcripts (the common cached-system-prompt shape) now free real tokens on auto-compaction instead of entering repeated no-progress compaction cycles.

Evidence

@openclaw-barnacle openclaw-barnacle Bot added size: XS maintainer Maintainer-authored PR labels Jul 28, 2026
@steipete
steipete marked this pull request as ready for review July 28, 2026 17:04
@steipete
steipete merged commit c7fecd3 into main Jul 28, 2026
147 of 149 checks passed
@steipete
steipete deleted the steipete/compaction-planner-units-111886 branch July 28, 2026 17:24
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit that referenced this pull request Jul 28, 2026
…224005-host

* origin/main: (72 commits)
  fix: macOS-only Parallels smoke harness regression (#75293)
  fix(ios): use configured speech language for system voice (#113372)
  refactor: centralize isolated agent test ownership (#115340)
  test(ui): stabilize browser route readiness (#115320)
  fix(cron): clear automation after failed scheduler shutdown (#115316)
  fix: keep isolated gateway workspaces and skills inside state dir (#114487)
  docs: document local TTS on macOS, Linux, and Windows (#110230)
  fix(tasks): clone only the requested task page (#114277)
  fix(agents): prevent Code Mode resume loss and unbounded preparation (#115314)
  fix(process): preserve the first process cancellation reason (#115317)
  fix(nostr): report unavailable ingress when queue open fails (#115313)
  fix: prevent Slack and Feishu ingress startup leaks (#115295)
  fix(slack): avoid unsafe emphasis boundaries (#111575)
  fix: prevent changed checks from expanding into full lint (#115322)
  fix(codex): stabilize prompts and expose real cache regressions (#115238)
  refactor(ui): derive page route specs from the route table (#115214)
  fix(compaction): plan cut points in trigger units (#111886) (#115309)
  fix: prevent cron and gateway stress-run timeouts (#115241)
  fix(ci): validate frozen Matrix QA targets (#115298)
  test(macos): block real process fallthrough (#113337)
  ...

# Conflicts:
#	CHANGELOG.md
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 29, 2026
…afea23-host

* origin/main: (72 commits)
  fix: macOS-only Parallels smoke harness regression (openclaw#75293)
  fix(ios): use configured speech language for system voice (openclaw#113372)
  refactor: centralize isolated agent test ownership (openclaw#115340)
  test(ui): stabilize browser route readiness (openclaw#115320)
  fix(cron): clear automation after failed scheduler shutdown (openclaw#115316)
  fix: keep isolated gateway workspaces and skills inside state dir (openclaw#114487)
  docs: document local TTS on macOS, Linux, and Windows (openclaw#110230)
  fix(tasks): clone only the requested task page (openclaw#114277)
  fix(agents): prevent Code Mode resume loss and unbounded preparation (openclaw#115314)
  fix(process): preserve the first process cancellation reason (openclaw#115317)
  fix(nostr): report unavailable ingress when queue open fails (openclaw#115313)
  fix: prevent Slack and Feishu ingress startup leaks (openclaw#115295)
  fix(slack): avoid unsafe emphasis boundaries (openclaw#111575)
  fix: prevent changed checks from expanding into full lint (openclaw#115322)
  fix(codex): stabilize prompts and expose real cache regressions (openclaw#115238)
  refactor(ui): derive page route specs from the route table (openclaw#115214)
  fix(compaction): plan cut points in trigger units (openclaw#111886) (openclaw#115309)
  fix: prevent cron and gateway stress-run timeouts (openclaw#115241)
  fix(ci): validate frozen Matrix QA targets (openclaw#115298)
  test(macos): block real process fallthrough (openclaw#113337)
  ...

# Conflicts:
#	CHANGELOG.md
@kahana1247zero-web

Copy link
Copy Markdown

Independent reproduction and verification

TL;DR: Reproduced on npm stable 2026.7.1-2: manual sessions compact on a 3-turn plain-text session sent a summarizer request with an empty <conversation> ("\n\n", captured via forwarding proxy) and wrote an all-(none) summary with compacted: true — wasted model call + useless record + false success. Upgrading the same isolated setup to 2026.7.2-beta.7 fixes it: non-empty summarization payload, facts preserved in the summary, post-compaction follow-up still recalls them. npm latest is still 2026.7.1-2, so stable users hit this today.


Root cause (short)

prepareCompaction()/findCutPoint() compare keepRecentTokens (default 20000) against the character-heuristic estimator (chars/4). For the repro session the whole branch accumulates to ~68 tokens while the provider reports ~17,464 — a ~250× under-count — so the cut never moves, messagesToSummarize = [], and the SDK compact() non-split-turn branch calls generateSummary([]) without an empty guard → empty <conversation> sent → LLM returns all-(none).

Reproduction (full)

Environment:

  • OpenClaw: 2026.7.1-2 (npm stable/latest)
  • OpenAI-compatible provider (also reproduced on SiliconFlow deepseek-ai/DeepSeek-V3)
  • Isolated profile, three plain-text turns (My dog is named Doudou. She is two years old and likes carrots.)
  • No tools, no channel plugins

Command:

openclaw sessions compact <session> --json

Observed on 2026.7.1-2:

ok: true
compacted: true

A local forwarding proxy captured the summarizer request before it left OpenClaw:

<conversation>

</conversation>

The <conversation> body contained only whitespace ("\n\n", length 2, trim length 0). The request had just 2 messages (system + user) and a 1,479-byte body, while the three normal turns had 2/3/4 messages and ~63 KB bodies — the empty content exists before the request leaves OpenClaw; the provider never saw the transcript.

OpenClaw then wrote a compaction entry whose structured summary sections were all (none), with "fromHook": false and firstKeptEntryId pointing at the pre-conversation model_change entry.

Bundle analysis (matched the capture)

provider-reported usage: ~17,464 tokens
character-based estimate: ~68 tokens
messagesToSummarize:     []

Why this happens (confirmed in the 2026.7.1-2 bundle):

  • Default config (no agents.defaults.compaction section) → resolveEffectiveCompactionMode() returns "default" → the compaction safeguard extension is not registered → SDK-native compact() runs.
  • findCutPoint() accumulates the character-heuristic estimate over type: "message" entries only; the 20k budget is never hit for this branch → messagesToSummarize = [], turnPrefixMessages = [], isSplitTurn = false.
  • SDK compact() non-split-turn branch (L2495) calls generateSummary(messagesToSummarize, …) unconditionally (the split-turn branch has an empty guard; the normal branch does not) → serializeConversation([]) = "" → <conversation>\n\n</conversation> is sent.

Note: because the budget is compared against the character heuristic rather than provider tokens, the trigger condition is not "session under 20k provider tokens" — sessions well above 20k provider-reported tokens can be affected too.

Also verified on the old build: buildSessionContext() on the written transcript retains all 3 user/assistant turns with the facts — so this is an empty-call + false-success defect, not data loss on this path. The genuinely lossy variant (tail dropped via firstKeptEntryId hard-set to the summary) is the scenario covered by #79297.

Verification after the upstream fix

We repeated the same isolated test after upgrading to:

Bundle-level (read-only, same transcript, pre-compaction state):

messagesToSummarize: 4           (was 0)
summarization payload: non-blank (was blank)

The beta.7 bundle contains the changes from this PR (trigger-unit scaling of keepRecentTokens by the provider-usage/estimate ratio, e.g. triggerUnitScale in agent-core) plus an empty-summarizable fail-closed gate in prepareCompaction, and a keepRecentTokens: 0 fallback in the manual-compaction preflight — an empty payload can no longer reach generateSummary.

End-to-end with the real provider (SiliconFlow, deepseek-ai/DeepSeek-V3), fresh session:

  • three normal turns: status: ok;
  • sessions compact: ok: true, compacted: true, tokensBefore: 20088; the summarization request carried a non-empty <conversation> containing the facts (75 chars, was "\n\n");
  • the written summary preserved the test facts:
dog name: Doudou
age: two years old
favorite food: carrots
  • a post-compaction follow-up asked "What is my dog's name and age? What does she like?" and the model recalled all three facts correctly:
Your dog's name is Doudou, she is 2 years old, and she likes carrots.

This independently confirms that the compaction-planner/manual-compaction changes represented by this PR fix the reproduced empty-summary path.

Note

The live end-to-end run used the auto-migrated compaction.mode: "safeguard" (the beta.7 config migration enables it). The default-mode path was also verified read-only in the beta.7 bundle, including the new empty-summarizable guard in prepareCompaction — an empty payload is unreachable in either mode.

Suggestion: please ship this in a stable release soon

For context (dates verified against npm / GitHub):

2026-07-18  npm latest 2026.7.1-2 published  (still the buggy build)
2026-07-28  this PR (#115309) merged to main
2026-08-02  2026.7.2-beta.7 published        (verified fixed end-to-end)
2026-08-10  2026.8.1-beta.1 published        (newest beta)

The latest tag has not moved since 07-18, so every stable user installing today still gets the empty-summary compact. The fix has been on main for over two weeks, but only beta builds carry it. This is a silent failure — wasted calls, junk (none) entries, and a compacted: true that means nothing — and stable users have been living with it for weeks. A stable release containing #115309 (and #79297) would close this out; please consider cutting one soon.

No credentials, authorization headers, private paths, complete transcripts, or auth databases are included.


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

maintainer Maintainer-authored PR size: XS

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Compaction frees zero tokens when transcript estimates undershoot the context-usage trigger (firstKeptEntryId stuck at first entry)

2 participants