Skip to content

fix: auto-compaction fires on fresh cached token counts (#66520)#66716

Closed
KeWang0622 wants to merge 2 commits into
openclaw:mainfrom
KeWang0622:fix/compaction-cached-tokens
Closed

fix: auto-compaction fires on fresh cached token counts (#66520)#66716
KeWang0622 wants to merge 2 commits into
openclaw:mainfrom
KeWang0622:fix/compaction-cached-tokens

Conversation

@KeWang0622

Copy link
Copy Markdown
Contributor

Summary

  • Bug: runPreflightCompactionIfNeeded returned early when totalTokensFresh === true without checking the compaction threshold, so auto-compaction never triggered for sessions with fresh token counts — even at 153% of the context window
  • Root cause: The early-return optimization (skip transcript estimation when fresh data is available) accidentally bypassed the threshold comparison entirely
  • Fix: Restructure token resolution so fresh persisted totals (which include cacheRead from Anthropic prompt caching) are projected forward and checked against contextWindow - reserveTokens - softThreshold before deciding whether to compact

Details

When Anthropic's prompt cache absorbs nearly all tokens (100% hit rate), derivePromptTokens correctly computes input + cacheRead + cacheWrite (e.g. 99 + 305,000 + 0 = 305,099), and this is persisted as totalTokens with totalTokensFresh: true. However, runPreflightCompactionIfNeeded had this logic:

if (!shouldUseTranscriptFallback) {
    return entry;  // BUG: skips threshold check entirely
}

The fix moves the threshold check into both branches (fresh and stale), using the fresh persisted value directly when available.

Edge cases verified

  • 100% cache hit (Anthropic): totalTokens=305k, contextWindow=200k — compaction now fires
  • 0% cache hit: Stale tokens fall through to transcript estimation path — behavior unchanged
  • Partial cache: 180k total with 166k threshold — fires correctly
  • Below threshold: 50k total with 166k threshold — no compaction, as expected
  • Heartbeat/CLI: Still skipped regardless of token count
  • Non-Anthropic providers: No change — providers without caching have cacheRead=0, so totalTokens is just input + cacheWrite, same as before

Test plan

  • shouldRunPreflightCompaction unit tests: 100% cache hit triggers, below threshold skips, partial cache boundary correct
  • runPreflightCompactionIfNeeded integration tests: fresh tokens above threshold trigger compaction, below threshold skip, stale tokens use transcript fallback, heartbeat skips
  • All existing compaction tests pass unchanged
  • Session usage persistence tests pass (65 tests)
  • Followup runner tests pass (19 tests)
  • Preemptive compaction tests pass (9 tests)

Fixes #66520

🤖 Generated with Claude Code

…reshold

When a provider like Anthropic has a high prompt cache hit rate, totalTokens
on the session entry includes cached tokens (input + cacheRead + cacheWrite)
and is marked as fresh. Previously, runPreflightCompactionIfNeeded returned
early when totalTokensFresh was true WITHOUT checking the compaction threshold,
so auto-compaction never triggered — even at 153% of the context window.

This change restructures the token resolution so that fresh persisted totals
are checked against the compaction threshold (contextWindow - reserveTokens -
softThreshold) before deciding whether to compact. The stale/transcript
fallback path is preserved unchanged.

Fixes openclaw#66520

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@greptile-apps

greptile-apps Bot commented Apr 14, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a real bug where runPreflightCompactionIfNeeded returned early for sessions with fresh token counts (totalTokensFresh === true), skipping the threshold comparison entirely. The fix restructures the token-resolution logic so fresh persisted totals — which correctly include cacheRead from Anthropic's prompt cache — are projected forward and checked against the compaction threshold before deciding whether to compact, matching the behavior already in place for the stale/transcript-fallback path.

Confidence Score: 5/5

  • This PR is safe to merge — it fixes a well-scoped compaction bypass with no regressions on existing paths.
  • The fix is minimal and surgically correct: it replaces an unconditional early return with a threshold check in the fresh-token branch while leaving the stale/transcript-fallback path byte-identical. The new tests validate all documented edge cases (100% cache hit, below threshold, partial cache, heartbeat bypass, stale fallback), and existing tests are described as passing unchanged. No security, data-integrity, or API-contract concerns.
  • No files require special attention.

Reviews (1): Last reviewed commit: "fix: preflight compaction now fires when..." | Re-trigger Greptile

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 86352d78cb

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +414 to +417
if (!shouldUseTranscriptFallback) {
// Fresh persisted tokens available — project forward with prompt estimate
const projectedFreshTokens = resolveEffectivePromptTokens(
freshPersistedTokens,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require explicit freshness before using persisted token totals

The new fresh-token branch now runs preflight compaction when shouldUseTranscriptFallback is false, but that predicate still treats totalTokensFresh: undefined as fresh. For legacy/unknown session entries (where freshness is not guaranteed), this branch uses freshPersistedTokens directly and can trigger compaction from stale totals, causing unnecessary summarization on the next turn. This behavior is introduced by the new branch because these sessions previously returned early without compacting; please gate this path on totalTokensFresh === true (or fall back to transcript estimation when freshness is unknown).

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c149fe4. Three changes to runPreflightCompactionIfNeeded:

  1. Replaced shouldUseTranscriptFallback with hasFreshPersistedTokens that requires totalTokensFresh === true explicitly. The previous predicate (entry.totalTokensFresh === false || !hasPersistedTotalTokens) treated undefined as "not needing fallback" because undefined === false is false. Now when totalTokensFresh is undefined (legacy) or false (known-stale), the function falls through to transcript estimation.

  2. Always run transcript estimation in the fallback branch. The old guard (typeof freshPersistedTokens === "number") skipped transcript estimation for legacy sessions because resolveFreshSessionTotalTokens treats totalTokensFresh: undefined as fresh and returns a number. Now the else branch unconditionally estimates from the transcript.

  3. Bail out before shouldRunPreflightCompaction when freshness is unconfirmed. Even with the above fixes, if transcript estimation returns undefined (e.g. no session file), shouldRunPreflightCompaction would fall back to resolveFreshSessionTotalTokens internally, which again treats undefined as fresh. Added an explicit guard: if tokenCountForCompaction is not a number and totalTokensFresh !== true, return early.

Added a test case for totalTokensFresh: undefined (legacy sessions) that verifies compaction is not triggered from stale persisted totals. All 9 tests in the test suite pass, along with the related test files (followup-runner, commands-compact, agent-runner-direct-runtime-config, reply-state).

The fresh-token branch in runPreflightCompactionIfNeeded ran when
shouldUseTranscriptFallback was false, but that predicate treated
totalTokensFresh: undefined as NOT needing fallback (undefined === false
evaluates to false). For legacy sessions where totalTokensFresh was
never set, this caused the fresh-token path to use potentially stale
persisted totals, triggering unnecessary compaction.

Three changes:

1. Replace shouldUseTranscriptFallback with hasFreshPersistedTokens
   that requires totalTokensFresh === true explicitly. When undefined
   (legacy) or false (known-stale), falls through to transcript
   estimation.

2. In the transcript fallback branch, always run transcript estimation
   instead of skipping when resolveFreshSessionTotalTokens returns a
   value (that function also treats undefined freshness as fresh).

3. Add bail-out before shouldRunPreflightCompaction when transcript
   estimation returns no count and freshness is unconfirmed, preventing
   the gate function from falling back to stale totals via
   resolveFreshSessionTotalTokens.

Resolves Codex P2 review on PR openclaw#66716.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@prtags

prtags Bot commented Apr 23, 2026

Copy link
Copy Markdown

Related work from PRtags group infinite-dodo-7d3e

Title: Preflight compaction skips fresh token totals

Number Title
#63892 Title unavailable
#64384 fix(reply): gate preflight compaction fast-path on token threshold (#63892)
#65600 Title unavailable
#65622 fix(agents): reevaluate preflight compaction on fresh totals
#66520 Title unavailable
#66716* fix: auto-compaction fires on fresh cached token counts (#66520)

* This PR

@clawsweeper

clawsweeper Bot commented Apr 27, 2026

Copy link
Copy Markdown
Contributor

Thanks for the context here. I did a careful shell check against current main, and the useful part of this older PR is already implemented there.

Close this stale PR: current main and the latest release already cover the central fresh-token preflight compaction problem with a broader token-accounting path, while the remaining branch-specific diff is conflicting and no longer a useful landing candidate.

So I’m closing this older PR as already covered on main rather than keeping a mostly-duplicated branch open.

Review details

Best possible solution:

Keep the current main implementation and close this stale branch; any remaining compaction edge case should be opened as a narrow follow-up against the current token-accounting path.

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

Yes. The old source and the PR diff show a high-confidence source reproduction: when persisted total tokens were treated as fresh, runPreflightCompactionIfNeeded returned before the threshold check.

Is this the best way to solve the issue?

No. This PR was a plausible April fix, but current main now solves the central behavior through a broader compaction accounting path, and the stale branch would be the wrong landing vehicle.

Security review:

Security review cleared: The diff only changes compaction runtime logic and tests; it does not add dependency, workflow, secret, permission, network, or package-resolution surface.

AGENTS.md: found and applied where relevant.

What I checked:

  • Repository policy read: Root AGENTS.md was read fully and applied; no scoped AGENTS.md owns src/auto-reply/reply, and the only maintainer note found was Telegram-only and not relevant to this compaction PR. (AGENTS.md:1, d28691da97fc)
  • PR branch behavior: The branch removes the old fresh-token early return and adds tests for fresh totalTokens above threshold, stale transcript fallback, and legacy totalTokensFresh omission. (src/auto-reply/reply/agent-runner-memory.ts:390, c149fe41f0b0)
  • Current main preflight gate: Current main/latest release derives tokenCountForCompaction from projected transcript usage and persisted prompt totals, then calls shouldRunPreflightCompaction without the PR's old fresh-token early return path. (src/auto-reply/reply/agent-runner-memory.ts:793, 8c802aa68351)
  • Cached prompt-token accounting: derivePromptTokens sums input, cacheRead, and cacheWrite, and deriveSessionTotalTokens persists that prompt/context snapshot without clamping, so cached Anthropic prompt usage is represented in session totals. (src/agents/usage.ts:253, 8c802aa68351)
  • Release provenance: The implementation proof commit is contained in v2026.6.6, the latest release in the review context. (8c802aa68351)
  • History provenance: History around this surface shows the current implementation was built from the merged stale-usage preflight fallback path and later preserved-token work, not this stale branch; the branch's remaining legacy-freshness behavior is superseded by current conservative accounting. (src/auto-reply/reply/agent-runner-memory.ts:793, 8c802aa68351)

Likely related people:

  • steipete: Recent and historical changes in this area include context prompt-token resolution, oversized transcript compaction, issue cleanup, and several compaction/session-state repairs. (role: recent area contributor; confidence: high; commits: bb6cf7546321, 29af4add2a8e, 6a65ea8c3ac1; files: src/agents/usage.ts, src/auto-reply/reply/agent-runner-memory.ts, src/auto-reply/reply/session-usage.ts)
  • jalehman: Merged and contributed to the stale-usage preflight compaction path and authored related context-engine token-budget work that sits in the same compaction/session-state area. (role: feature-history owner; confidence: high; commits: c6d8318d07f5, 75e7fc97f804; files: src/auto-reply/reply/agent-runner-memory.ts, src/context-engine/types.ts, src/agents/pi-embedded-runner/run/attempt.ts)
  • Takhoffman: Authored the cached prompt token normalization change that feeds the cached-token accounting used by session totals. (role: introduced adjacent accounting behavior; confidence: medium; commits: 079494aee559; files: src/agents/usage.ts)
  • njuboy11: Contributed the merged post-compaction token freshness preservation fix that affects how stale/fresh totalTokens behave around repeated auto-compaction. (role: adjacent bug-fix contributor; confidence: medium; commits: 6a65ea8c3ac1; files: src/auto-reply/reply/session-usage.ts)
  • vincentkoc: The latest shipped proof commit carrying the current compaction helper snapshot is authored by Vincent Koc, and nearby recent work touched compaction notice behavior. (role: recent release/current snapshot contributor; confidence: medium; commits: 8c802aa68351, 280d1cb977c4; files: src/auto-reply/reply/agent-runner-memory.ts, src/auto-reply/reply/agent-runner-memory.test.ts)

Codex review notes: model internal, reasoning high; reviewed against d28691da97fc; fix evidence: release v2026.6.6, commit 8c802aa68351.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels May 19, 2026
@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. label May 19, 2026
@clawsweeper

clawsweeper Bot commented May 20, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper PR egg

🎁 Pass real behavior proof to wake the egg and unlock a hatchable treat.

Where did the egg go?
  • The egg game starts only after the PR passes the real-behavior proof check.
  • Before that, no creature or rarity is rolled. The treat waits for real proof.
  • This is still just collectible flavor: proof affects review readiness, not creature quality.

@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Jun 6, 2026
@clawsweeper clawsweeper Bot added rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 6, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Jun 7, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. labels Jun 14, 2026
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. P1 High-priority user-facing bug, regression, or broken workflow. and removed P1 High-priority user-facing bug, regression, or broken workflow. P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. labels Jun 14, 2026
@clawsweeper

clawsweeper Bot commented Jun 14, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper applied the proposed close for this PR.

@clawsweeper clawsweeper Bot closed this Jun 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: M status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Auto-compaction never fires when Anthropic prompt cache hit rate is ~100%

2 participants