Skip to content

fix(compaction): avoid cached usage overcount#99864

Merged
vincentkoc merged 1 commit into
openclaw:mainfrom
LZY3538:codex/99843-compaction-context-estimate
Jul 5, 2026
Merged

fix(compaction): avoid cached usage overcount#99864
vincentkoc merged 1 commit into
openclaw:mainfrom
LZY3538:codex/99843-compaction-context-estimate

Conversation

@LZY3538

@LZY3538 LZY3538 commented Jul 4, 2026

Copy link
Copy Markdown
Contributor

Closes #99843

What Problem This Solves

Long cached Anthropic tool loops could report aggregate cache billing buckets as
if they were one live context-window snapshot. That inflated token counts and
could trigger compaction well below the configured reserve threshold.

Why This Change Was Made

Both Anthropic stream adapters now preserve the prompt snapshot from
message_start for context-window accounting while retaining the final
aggregate cache buckets for billing and cost reporting.

The shared context-token helper prefers an explicit prompt snapshot, then
derives the latest call's prompt size from total - output, and finally falls
back to component sums. Accumulated session usage remains component-based.
Metadata persistence and timeout-driven compaction use the same helper so the
decision is consistent across runner paths.

User Impact

Cached Anthropic sessions no longer compact early because repeated cache-read
and cache-write billing totals are mistaken for the current prompt size.
Billing totals remain intact, and sessions above the real context threshold
still compact normally.

Evidence

  • Exact PR head: b054cb5c5921218b0c5b2b8783efb84cf3728df8.
  • Local focused proof:
    node scripts/run-vitest.mjs src/agents/usage.test.ts src/agents/embedded-agent-runner/run/helpers.test.ts src/llm/providers/anthropic.test.ts src/agents/anthropic-transport-stream.test.ts src/auto-reply/status.test.ts src/agents/embedded-agent-runner/run.empty-error-retry.test.ts src/agents/embedded-agent-runner/run.compaction-loop-guard.test.ts src/agents/embedded-agent-runner/run.overflow-compaction.loop.test.ts src/agents/embedded-agent-runner/run.overflow-compaction.test.ts
    • 9 files, 380 tests passed.
  • Blacksmith Testbox tbx_01kwr9ecvcty3pvvtthtkw60kc:
    • verified the exact head SHA;
    • repeated the same 380 focused tests successfully;
    • pnpm check:changed passed, including production/test typechecks, all core
      oxlint shards, import-cycle checks, and changed-surface guards.
  • Fresh autoreview:
    .agents/skills/autoreview/scripts/autoreview --mode local --prompt-file .local/review-ci-followup.md --stream-engine-output
    • no accepted/actionable findings;
    • patch correct, confidence 0.98.
  • Hosted compact jobs still expose four unrelated docs-sync failures. Each was
    reproduced unchanged on current origin/main at
    1d9fb2773f04ee8828d98077130b06496344ac2a:
    src/docs/environment-docs.test.ts,
    src/config/talk-defaults.test.ts,
    src/agents/minimax-docs.test.ts, and
    src/cron/isolated-agent/run-fallback-policy.test.ts.
    This PR changes none of those files or docs.

@clawsweeper

clawsweeper Bot commented Jul 4, 2026

Copy link
Copy Markdown
Contributor

Codex review: stale review; fresh review needed.

Summary
The latest durable ClawSweeper review was for head f8f7878534960589affe2b6b736b00d9bcd2ae95, but the PR head is now 5fc8f0ab37c208b7864262269ac55e307d473316. Its old verdict and PR readiness labels are no longer current.

Next step
Run or wait for a fresh ClawSweeper review on the current PR head.

Review history (8 earlier review cycles)
  • reviewed 2026-07-04T07:15:55.535Z sha 6cc347b :: needs real behavior proof before merge. :: [P1] Preserve cached prompt tokens in the fallback
  • reviewed 2026-07-04T09:18:23.136Z sha 4bc55b6 :: found issues before merge. :: [P1] Carry a real context snapshot before dropping cache buckets
  • reviewed 2026-07-04T12:06:46.712Z sha f38d668 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-04T12:19:52.464Z sha f38d668 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-04T12:27:29.837Z sha f38d668 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-04T12:38:02.900Z sha f38d668 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-05T01:34:36.716Z sha 5e6c485 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-05T07:35:36.799Z sha 3657fa3 :: needs real behavior proof before merge. :: none

@LZY3538
LZY3538 marked this pull request as ready for review July 4, 2026 07:07
@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 Jul 4, 2026
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M and removed size: S labels Jul 4, 2026
@clawsweeper clawsweeper Bot 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 Jul 4, 2026
@clawsweeper

clawsweeper Bot commented Jul 4, 2026

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed 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: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Jul 4, 2026
@clawsweeper

clawsweeper Bot commented Jul 4, 2026

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 4, 2026
@clawsweeper clawsweeper Bot removed 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 Jul 5, 2026
@vincentkoc
vincentkoc force-pushed the codex/99843-compaction-context-estimate branch 2 times, most recently from db59127 to 3657fa3 Compare July 5, 2026 05:35
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 5, 2026
@vincentkoc
vincentkoc force-pushed the codex/99843-compaction-context-estimate branch from 3657fa3 to 405ba6b Compare July 5, 2026 09:00
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: XL and removed size: M labels Jul 5, 2026
@vincentkoc
vincentkoc force-pushed the codex/99843-compaction-context-estimate branch from 405ba6b to f8f7878 Compare July 5, 2026 09:14
@vincentkoc

vincentkoc commented Jul 5, 2026

Copy link
Copy Markdown
Member

Maintainer repair landed as e6ec74c25430f2df94eb6a99fb5e050ebbdd87ad from final PR head 5fc8f0ab37c208b7864262269ac55e307d473316.

The repaired implementation separates cumulative Anthropic billing buckets from the final-iteration context snapshot across provider streams, compaction/overflow decisions, persistence, active-branch transcript recovery, and fork preflight. Partial final usage updates preserve already-accumulated prompt buckets; unavailable snapshots remain fail-closed.

Validation:

  • node scripts/run-vitest.mjs src/agents/sessions/agent-session.context-usage.test.ts src/agents/usage.test.ts src/gateway/session-utils.fs.test.ts src/gateway/session-transcript-readers.test.ts src/auto-reply/reply/session-fork.runtime.test.ts packages/agent-core/src/harness/compaction/compaction.test.ts packages/ai/src/utils/overflow.test.ts packages/ai/src/providers/anthropic-usage.test.ts packages/ai/src/providers/anthropic.test.ts src/agents/anthropic-transport-stream.test.ts src/agents/embedded-agent-runner/run.timeout-triggered-compaction.test.ts src/agents/embedded-agent-runner.sanitize-session-history.test.ts src/agents/embedded-agent-runner/run/attempt.test.ts src/agents/embedded-agent-runner/run/helpers.test.ts - 838 passed across five shards.
  • node scripts/generate-docs-map.mjs --check - passed.
  • git diff --check - passed.
  • Autoreview - no findings after the partial-final-delta repair; final whole-branch confidence 0.82.
  • Final exact-head CI - 54/54 jobs passed: https://github.com/openclaw/openclaw/actions/runs/28736168153
  • Final Workflow Sanity - passed: https://github.com/openclaw/openclaw/actions/runs/28736168157
  • OPENCLAW_TESTBOX=1 scripts/pr prepare-run 99864 - passed in hosted_exact_head mode.

Known proof gaps: none.

@vincentkoc
vincentkoc force-pushed the codex/99843-compaction-context-estimate branch from f8f7878 to 5fc8f0a Compare July 5, 2026 09:24
@vincentkoc
vincentkoc merged commit e6ec74c into openclaw:main Jul 5, 2026
98 checks passed
@vincentkoc

Copy link
Copy Markdown
Member

Merged via squash.

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 P1 High-priority user-facing bug, regression, or broken workflow. size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Compaction trigger overestimates context ~5.7x when usage fallback sums turn-aggregated cacheRead — fires far below configured reserveTokens

2 participants