Skip to content

fix(anthropic): keep context usage for providers that never write cache - #126473

Merged
steipete merged 4 commits into
openclaw:mainfrom
ayaangazali:fix/anthropic-usage-absent-cache-write
Sep 2, 2026
Merged

steipete merged 4 commits into
openclaw:mainfrom
ayaangazali:fix/anthropic-usage-absent-cache-write

Conversation

@ayaangazali

@ayaangazali ayaangazali commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Closes #126436

What Problem This Solves

Fixes an issue where MiniMax sessions would discard provider-reported context usage when a stream started with zero placeholders and its final usage reported only one cache counter. Compaction would then use an estimate instead of the provider's prompt total.

Why This Change Was Made

The shared no-iterations delta owner reuses the existing prompt snapshot validator when at least one valid cache counter is present. That validator distinguishes an absent/null counter from a malformed present counter. The final-iteration contract remains strict, and missing billing fields still preserve the SDK accumulator's previous values. Production +2/-3, net -1; tests +39.

User Impact

Affected Anthropic-compatible streams retain authoritative context totals. Malformed usage still remains unavailable. Both direct and managed Anthropic streams use the repaired owner; no configuration, schema, protocol, or dependency changes.

Evidence

Actual source provider entrypoints, installed SDKs, and HTTPS MiniMax-M3 requests were exercised before and after the repair on trusted main f74dde8. Both direct and managed streams returned HTTP 200 with text. Before the fix, context usage was unavailable; after it, each recorded promptTokens=1763, totalTokens=1765 and sessionPromptTokens=1763. Billing totals stayed 1765, with no cache-write tokens.

The seven-case regression table covers missing read/write counters after zero-placeholder starts, absent cache evidence, and malformed present counters. Changed-owner and both-stream suites passed as part of a five-suite, 321-test provider validation run. The combined baseline had eight expected failures across this repair and the mapped-thinking repair. The live command exited 0 and its one-shot Testbox stopped. Source/dependency SHA-256 bindings and both exact runtime verdict JSON records were recovered; the final two files match their historical hashes. The baseline owner and stream callers were also checked against current main during review.

Thanks @ayaangazali for the report and original repair.

Fresh independent P0 review of the complete frozen candidate against inspected main a9469a2119a6cd4251c7346c896c8d9cae3633a3 returned no findings. The six relevant runtime/package files are bound to the tested candidate below; SDK importer versions remain OpenAI 7.5.0 and Anthropic 0.120.0. The overall lockfile changed elsewhere. No new API or test run was performed during recovery; exact published-head CI remains required.

Auditable provider trace and published-head binding

The following retained JSON records came from actual authenticated MiniMax HTTPS calls through both production stream entrypoints. They contain only the public provider endpoint, model, response counters and verdicts; credentials, prompts, response text and local paths are omitted. Baseline passed means the expected unavailable-context behavior was observed. The candidate was independently authored on trusted main; this is the retained run, not a newly executed published-head run.

These six affected runtime/package files in published head e2442b78b9ba67b32c9f880eb1d8ac743c667306 were rehashed and are byte-identical to the tested candidate:

File SHA-256
packages/ai/package.json 262478c3acb2d4ec333bfa00f38896014232a288183e70ec39409e35873c0091
packages/ai/src/providers/anthropic-usage.ts af08040903f8923bdf4b8fb2ce70ca24268951fd13620389ba5e35ec182a3903
packages/ai/src/providers/anthropic.ts 457274639c0d98bb8f0033240b18aa0b5d000ab5410d23fc4f0fd3056fd589a2
packages/ai/src/transports/anthropic-transport-stream.ts 3987f41134675389d2974c6063e5e6ce606a280c144791cffb2a21faede248f9
packages/ai/src/host.ts 0dec2ae17aa539ea43099a46f662aedb13566aeae48b9501466b70650ac03fd0
src/agents/usage.ts c8b713e015591e546ad351e81ba8742f01525f6a84423fc7f8678965ec8e6997

The baseline usage owner SHA-256 was 00d9aea67224ef4d2e7de2c4ef3bd8f3dfab870af800e5235c80272a805d5bb9. The lockfile changed elsewhere after that run; full-tree equivalence is not claimed. Installed SDK versions are recorded below. Both direct and managed paths changed from unavailable context usage to the authoritative 1763-token prompt snapshot while billing remained 1765 total tokens.

{
  "publishedHead": "e2442b78b9ba67b32c9f880eb1d8ac743c667306",
  "binding": "Affected runtime files are SHA-256 identical to the actual tested candidate; this is not a new execution of the full published tree.",
  "runtime": {
    "node": "v24.19.0",
    "openai": "7.5.0",
    "anthropic": "0.120.0"
  },
  "fixtureSha256": "680872b33f85728244995730e388c07324a2cfe71eca8d94fc149900028b797d",
  "phases": [
    {
      "phase": "baseline",
      "trustedBase": "f74dde80b6c951124d9f8c7038d8391945296e79",
      "cases": [
        {
          "name": "minimax-provider",
          "endpoint": "https://api.minimax.io/anthropic",
          "model": "MiniMax-M3",
          "httpStatuses": [
            200
          ],
          "stopReason": "stop",
          "hasText": true,
          "input": 1635,
          "output": 2,
          "cacheRead": 128,
          "cacheWrite": 0,
          "totalTokens": 1765,
          "contextUsage": {
            "state": "unavailable"
          },
          "passed": true
        },
        {
          "name": "minimax-transport",
          "endpoint": "https://api.minimax.io/anthropic",
          "model": "MiniMax-M3",
          "httpStatuses": [
            200
          ],
          "stopReason": "stop",
          "hasText": true,
          "input": 1,
          "output": 2,
          "cacheRead": 1762,
          "cacheWrite": 0,
          "totalTokens": 1765,
          "contextUsage": {
            "state": "unavailable"
          },
          "passed": true
        }
      ]
    },
    {
      "phase": "candidate",
      "trustedBase": "f74dde80b6c951124d9f8c7038d8391945296e79",
      "cases": [
        {
          "name": "minimax-provider",
          "endpoint": "https://api.minimax.io/anthropic",
          "model": "MiniMax-M3",
          "httpStatuses": [
            200
          ],
          "stopReason": "stop",
          "hasText": true,
          "input": 1,
          "output": 2,
          "cacheRead": 1762,
          "cacheWrite": 0,
          "totalTokens": 1765,
          "contextUsage": {
            "state": "available",
            "promptTokens": 1763,
            "totalTokens": 1765
          },
          "sessionPromptTokens": 1763,
          "passed": true
        },
        {
          "name": "minimax-transport",
          "endpoint": "https://api.minimax.io/anthropic",
          "model": "MiniMax-M3",
          "httpStatuses": [
            200
          ],
          "stopReason": "stop",
          "hasText": true,
          "input": 1,
          "output": 2,
          "cacheRead": 1762,
          "cacheWrite": 0,
          "totalTokens": 1765,
          "contextUsage": {
            "state": "available",
            "promptTokens": 1763,
            "totalTokens": 1765
          },
          "sessionPromptTokens": 1763,
          "passed": true
        }
      ]
    }
  ]
}

This addresses the latest ClawSweeper trace and hash-binding rank-up request. Native prepare passed on the exact published head with hosted CI admission; source and strict malformed-counter regression coverage remain unchanged.

@clawsweeper

clawsweeper Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@ayaangazali
ayaangazali marked this pull request as ready for review August 19, 2026 23:26
Copilot AI lite review requested due to automatic review settings August 19, 2026 23:26

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. 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 Aug 19, 2026
@clawsweeper

clawsweeper Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed September 1, 2026, 7:47 PM ET / 23:47 UTC.

ClawSweeper review

What this changes

This PR lets Anthropic-compatible streams retain context-window usage when a final no-iterations delta has one valid cache counter and the peer counter is absent.

Regression provenance

Possible regression — probable (reproduction; reviewed change). No predecessor PR is attributed.

Merge readiness

⛔ Blocked until stronger real behavior proof is added - 3 items remain

The no-iterations fallback fix is correct and still needed on current main, but this external-provider PR needs auditable after-fix behavior evidence before merge.

Priority: P1
Reviewed head: e2442b78b9ba67b32c9f880eb1d8ac743c667306

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The shared-owner repair and regression tests are sound, but externally auditable affected-provider proof is still missing.
Proof confidence 🦪 silver shellfish (2/6) Needs stronger real behavior proof before merge: Both production stream entry points call the changed usage owner, and the PR body describes after-fix MiniMax HTTPS results, but it does not provide the underlying redacted trace or an auditable binding to this exact head; source tests remain supplemental. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: Both production stream entry points call the changed usage owner, and the PR body describes after-fix MiniMax HTTPS results, but it does not provide the underlying redacted trace or an auditable binding to this exact head; source tests remain supplemental. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 6 items Introduced owner-boundary repair: The PR replaces the all-three-counter readiness condition with the canonical prompt snapshot validator, which accepts an absent peer counter but rejects malformed values.
Regression coverage: The added table covers either single valid counter, no counter, and malformed counter combinations after a zero-placeholder start; the positive cases fail under the prior all-three-counter guard.
Both stream entry points share the repaired owner: The direct SDK stream and managed transport each pass message-start and message-delta usage through this helper, so the shared owner test covers both call paths.
Findings None None.
Security None None.

How this fits together

Anthropic-compatible stream adapters normalize provider usage into billing totals and context-window usage. The resulting context usage drives session compaction, which otherwise falls back to an estimate.

flowchart LR
A[Provider stream usage] --> B[Anthropic usage normalizer]
B --> C{Usable prompt snapshot?}
C -->|yes| D[Context-window usage]
C -->|no| E[Unavailable context usage]
D --> F[Session compaction]
E --> F
Loading

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: Both production stream entry points call the changed usage owner, and the PR body describes after-fix MiniMax HTTPS results, but it does not provide the underlying redacted trace or an auditable binding to this exact head; source tests remain supplemental. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Resolve merge risk (P1) - A malformed or differently shaped compatible-provider response could still change session compaction incorrectly; the claimed live result is not auditable against this exact PR head.
  • Complete next step (P2) - No source repair is needed; an exact-head affected-provider trace is the remaining human merge gate.
Agent review details

Security

None.

PR surface

Source -1, Tests +39. Total +38 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 2 3 -1
Tests 1 39 0 +39
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 41 3 +38

Review metrics

Metric Value Why it matters
Production versus regression test delta production +2/-3; tests +39/-0 The production repair is net-negative and the added table exercises the changed shared usage owner.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #126436
Summary: This PR is the open candidate repair for the canonical report's no-iterations, single-cache-counter path.

Members:

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

Merge-risk options

Maintainer options:

  1. Provide exact-head provider proof (recommended)
    Post a redacted direct or managed affected-provider trace that identifies this head or a hash-verifiable equivalent and shows unavailable context usage becoming available.
  2. Accept the proof gap
    A maintainer may accept the source-level regression coverage without independently auditable provider-path evidence.

Technical review

Best possible solution:

Keep the shared no-iterations repair and strict iteration policy, then land it after a redacted after-fix affected-provider trace is bound to this head or an explicitly hash-equivalent candidate.

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

Yes, from source: a zero-placeholder start followed by a no-iterations delta with input, output, and one cache counter fails the current-main readiness guard; this review did not execute the test.

Is this the best way to solve the issue?

Yes for the reported no-iterations path: reusing the existing snapshot validator centralizes absent-versus-malformed handling without altering billing or the separate strict-iterations policy.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 50f7f06d8ba3.

Labels

Label justifications:

  • P1: Affected active Anthropic-compatible sessions can use estimated rather than provider-reported context usage for compaction.
  • merge-risk: 🚨 session-state: This changes the context state used by session compaction for compatible-provider streams, without auditable exact-head provider proof.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: Both production stream entry points call the changed usage owner, and the PR body describes after-fix MiniMax HTTPS results, but it does not provide the underlying redacted trace or an auditable binding to this exact head; source tests remain supplemental. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

  • Introduced owner-boundary repair: The PR replaces the all-three-counter readiness condition with the canonical prompt snapshot validator, which accepts an absent peer counter but rejects malformed values. (packages/ai/src/providers/anthropic-usage.ts:250, e2442b78b9ba)
  • Regression coverage: The added table covers either single valid counter, no counter, and malformed counter combinations after a zero-placeholder start; the positive cases fail under the prior all-three-counter guard. (packages/ai/src/providers/anthropic-usage.test.ts:121, e2442b78b9ba)
  • Both stream entry points share the repaired owner: The direct SDK stream and managed transport each pass message-start and message-delta usage through this helper, so the shared owner test covers both call paths. (packages/ai/src/providers/anthropic.ts:677, e2442b78b9ba)
  • Current main still has the defect: Current main retains the fallback requiring input plus both raw cache counters, while an absent iterations field routes into that fallback. (packages/ai/src/providers/anthropic-usage.ts:247, 50f7f06d8ba3)
  • Release and current-main provenance: The latest stable release contains the existing usage behavior, while the PR head is not contained in that release; the proposed repair is unshipped. (e2442b78b9ba)
  • Proof gap: The complete PR body describes successful direct and managed MiniMax requests, but supplies neither the redacted runtime trace nor a verifiable exact-head or file-hash binding for those claimed records.

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Post a redacted after-fix affected-provider trace for direct or managed streaming that identifies this head or a hash-verifiable equivalent; include the resulting context usage and redact private endpoints, keys, and identifiers.

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 (12 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-22T17:57:51.425Z sha e19818764b3efa4800fb703dad5f06e0b53481a8 :: needs real behavior proof before merge. :: [P1] Normalize the no-iterations delta fallback too
  • reviewed 2026-08-23T16:59:09.952Z sha 989b0a16b701d6bb9c61e9431526f96c87a66642 :: needs real behavior proof before merge. :: [P2] Do not coerce malformed cache counters to zero
  • reviewed 2026-08-23T17:32:17.400Z sha f50c997dd2cf11ae4c0ace75fc3a07ae407708c0 :: needs real behavior proof before merge. :: [P2] Keep malformed cache counters unavailable
  • reviewed 2026-08-24T21:02:04.055Z sha f50c997dd2cf11ae4c0ace75fc3a07ae407708c0 :: needs real behavior proof before merge. :: [P2] Keep malformed delta counters unavailable
  • reviewed 2026-08-24T21:19:33.214Z sha f50c997dd2cf11ae4c0ace75fc3a07ae407708c0 :: needs real behavior proof before merge. :: [P2] Keep malformed delta counters unavailable
  • reviewed 2026-08-25T06:58:15.355Z sha f50c997dd2cf11ae4c0ace75fc3a07ae407708c0 :: needs real behavior proof before merge. :: [P2] Preserve malformed delta counters as unavailable
  • reviewed 2026-08-25T22:33:53.716Z sha f37a28d :: needs real behavior proof before merge. :: [P2] Keep malformed delta counters unavailable
  • reviewed 2026-09-01T12:16:40.933Z sha f37a28d :: needs real behavior proof before merge. :: [P2] Keep malformed delta counters unavailable

@Oliverbot26

Copy link
Copy Markdown

PR #126473 — real-behaviour evidence from an affected deployment

Measured 2026-08-21 on the deployment that filed issue #126436.
Headline: the PR as it stands does not fix the reported symptom on this provider. A second,
untouched call site does.
Isolation experiment below.
No message content, no local paths, no real session ids — turns are labelled a–j.

Environment

Product version 2026.7.1-2
Affected provider MiniMax portal, Anthropic-compatible endpoint
Patch A (this PR) head c8f97246, applied verbatim — @openclaw/ai … readLastAnthropicIterationUsage
Patch B (ours) same unilateral-coercion semantics, applied to the top-level delta fallback in provider-stream (applyAnthropicMessageDeltaUsage)
Method each state proved with a gateway restart and a brand-new session, real turns

1. The symptom is model-specific, not provider-specific

Eight consecutive turns, same portal, same account, same build, before any patch:

turn model contextUsage
a–c, e–g MiniMax-M3 {"state":"unavailable"} — 6 / 6
d, h MiniMax-M2.7-highspeed {"state":"available","promptTokens":36541,"totalTokens":36604} — 2 / 2

Same client, same endpoint. The two models differ, which narrows the report considerably.

2. Isolation experiment — three states, each proved separately

state patch A patch B model result
baseline ✗ ✗ M3 unavailable (6/6)
PR as-is ✓ ✗ M3 unavailable ← turn i
PR's untouched sibling ✗ ✓ M3 available ← turns j₁, j₂

Verbatim, from the isolated state (patch A verified absent, marker count 0):

turn j₁   MiniMax-M3   {"state":"available","promptTokens":38784,"totalTokens":38924}
turn j₂   MiniMax-M3   {"state":"available","promptTokens":37828,"totalTokens":37862}

Patch A alone: no effect. Patch B alone: cures. Both verified with the other patch removed, so
neither result is confounded.

3. Where the gate actually is

For this wire, the decision is not made in readLastAnthropicIterationUsage. It is made in the
top-level delta fallback, which

  • reads usage?.cache_creation_input_tokens raw, with no unilateral coercion, and
  • requires all three counters (or a messageStart) before it will call the record usable.

The provider sends cache_read_input_tokens and omits cache_creation_input_tokens. On the
normalised record of an affected turn:

"usage": {"input":35593, "output":61, "cacheRead":128, "cacheWrite":0, "totalTokens":35782}

cacheRead is populated — the delta does carry one cache counter — so applying this PR's own
"one present ⇒ the other is 0" rule at that site closes the trio, and the state becomes
available. That is exactly what patch B does, and nothing else.

This matches defect #1 of the PR's own review (the reviewer listed two defects; the PR fixes
one). The guard for "no counters at all ⇒ stay invalid" is preserved in patch B, unchanged.

4. Corrections we owe the reader

Reported because a write-up that hides its wrong turns does not deserve trust:

  1. We first read cacheWrite: 0 on a post-patch turn as evidence that patch A was doing something.
    It was not — that field is present in pre-patch trajectories too. We had compared two shapes
    inside one file and assumed one was older. Re-measured across files with timestamps, the
    field predates the patch. Two of us reached this correction independently.
  2. Our first guesses for the gate (session-store, proxy) were wrong; the gate sits before
    them, in the delta fallback.

5. Current state and offer

This deployment currently runs patch B only — the isolation state — and reports available
consistently. We are an affected deployment and will run whatever additional measurement the
maintainers want, including capturing the raw provider payload for an M3 turn, which our
trajectory format does not retain.

Suggested action for the PR: apply the same coercion at the top-level delta fallback. Without
it, the merge will not resolve the reported symptom for Anthropic-compatible providers that report
a single cache counter — which is the class this issue was filed from.

@Oliverbot26

Copy link
Copy Markdown

Addendum to the evidence above — a stronger data point, and a methodology correction

Posted after the original comment. Two things a reader deserves.

The strongest single observation: one long-lived session, before and after

One session was open across the change. It emits contextUsage on every iteration, so it recorded
both sides of the patch with everything else held constant — same session, same model, same
account, same process:

count
unavailable, from 05:26:36Z through 16:56:38Z 94
available, at 16:56:42Z (the two final iterations) 2

The patch went live between those two timestamps. Nothing else changed. This is a natural
before/after with no cross-session confounds at all.

Methodology correction

Our first pass read the first contextUsage occurrence per trajectory. For short turns (two
occurrences, both identical) that is the settled value. For a long-lived session it is a stale
early line
, and it briefly led us to report a post-patch turn as unavailable when its settled
state was available.

We re-ran the count over all occurrences per file. The conclusion is unchanged and better
supported:

trajectory (pre-patch, M3) occurrences available
baseline A 22 0
baseline B 2 0
baseline C 2 0
baseline D (patch A only) 2 0
post-patch B, turn j₁ 2 2
post-patch B, turn j₂ 2 2

The 22-occurrence baseline matters: zero of its iterations ever reached available, so the
original reading was not an artefact of sampling the first line.

Note also that within a single turn, early iterations legitimately report unavailable before the
provider returns usage; the meaningful value is the settled one at the end of the turn.

@ayaangazali
ayaangazali force-pushed the fix/anthropic-usage-absent-cache-write branch from c8f9724 to 5f7932c Compare August 21, 2026 19:40
@openclaw-barnacle openclaw-barnacle Bot removed the docs Improvements or additions to documentation label Aug 21, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. and removed P2 Normal backlog priority with limited blast radius. labels Aug 21, 2026
@ayaangazali
ayaangazali force-pushed the fix/anthropic-usage-absent-cache-write branch from 5f7932c to e198187 Compare August 22, 2026 17:05
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Aug 22, 2026
@ayaangazali

Copy link
Copy Markdown
Contributor Author

The P1 was right and it explains the field report. Fixed in 989b0a16b70.

My one-counter rule only touched readLastAnthropicIterationUsage. On a payload with no iterations array that reader returns absent, and the delta fallback then still required both raw counters:

(inputTokens !== undefined && cacheReadTokens !== undefined && cacheWriteTokens !== undefined)

A provider that never writes cache omits cache_creation_input_tokens entirely, so that guard stayed false and context usage stayed unavailable. That is the path the affected deployment runs, which is why the branch did not resolve the symptom for them. A one-sided fix on my part.

The missing counter is now settled for the readiness guard only. Two things deliberately left alone:

  • Billing keeps its documented behavior. The comment above it says absent or null cache counters preserve prior values, so I did not normalize the values feeding resolved, only the guard. promptTokens reads the accumulator, not these locals, so the computed number is unchanged.
  • A payload reporting neither counter still resolves unavailable, since there is nothing to settle against.

Provider-boundary trace, same delta payload, only anthropic-usage.ts swapped:

[trace] delta payload: {"input_tokens":5,"output_tokens":7,"cache_read_input_tokens":11}

PRE-FIX   contextUsage: {"state":"unavailable"}
POST-FIX  contextUsage: {"state":"available","promptTokens":16,"totalTokens":23}
          billed cacheWrite preserved at: 0

Two regression tests. The reported-path one fails on the unfixed reader (× settles context usage with no iterations when the provider never writes cache, 1 failed | 13 passed); the second asserts a payload with neither counter stays unavailable, so the settling rule cannot silently invent a zeroed prompt total.

node scripts/run-vitest.mjs packages/ai/src/providers: 867 passed, 42 files. Production delta +21/-4.

Honest gap: this is the owner boundary with a real payload shape, not a live Anthropic call. I do not have that deployment's credentials, so if the reporting operator can rerun their flow on this head that would be stronger than anything I can produce here.

@ayaangazali
ayaangazali force-pushed the fix/anthropic-usage-absent-cache-write branch from e198187 to 989b0a1 Compare August 23, 2026 16:53
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Aug 23, 2026
@ayaangazali
ayaangazali force-pushed the fix/anthropic-usage-absent-cache-write branch from f50c997 to e8401f7 Compare August 25, 2026 21:43
@ayaangazali

Copy link
Copy Markdown
Contributor Author

This one is GitHub infrastructure, not code. No speculative fix pushed.

checks-node-compact-small-17, job 97979858496:

##[warning]Failed to download action
'https://internal-api.service.iad.github.net/repos/actions/setup-go/tarball/b7ad1dad31e...'
Error: Name or service not known (internal-api.service.iad.github.net:443)

The runner could not resolve GitHub's own internal action-download host, so actions/setup-go never landed and the job failed before running any test. There is no test failure in that log at all.

Context worth having: all 15 of my open PRs went red together after I rebased them onto current main today. Most share a genuine main breakage in model-resolution-consistency.test.ts (a vi.mock factory missing withPluginMetadataSnapshotScope), which #129607 fixes. This PR's failure is not that one, it is the DNS failure above, which is why I checked it separately rather than assuming it matched the cluster.

Nothing here is actionable from the branch. It should clear on any re-run that lands on a healthy runner, and I will pick that up on the next rebase.

readLastAnthropicIterationUsage required every cache counter to be readable.
An Anthropic-compatible provider that never writes cache omits
cache_creation_input_tokens entirely, so the final iteration was scored
invalid, contextUsage fell to "unavailable", and the session then sized its
context window from a character estimate rather than the provider's numbers.
Threshold compaction fires on that estimate.

readAnthropicPromptUsageSnapshot already reads an absent counter as zero on
the message_start path, so the two paths disagreed about the same payload.

Absence now means zero only when the record carries at least one cache
counter, which is what proves the provider reports them. An iteration with no
cache counter at all stays invalid: that is a partial payload, and assuming
zero would understate the context window, which is the case openclaw#99864 added and
its test still covers.

Refs openclaw#126436
The one-counter rule only covered the final-iteration reader. With no
iterations array that reader returns absent and the delta fallback still
required both raw cache counters, so a provider that never writes cache stayed
on unavailable context and estimate-based compaction. That is the path the
affected deployment actually runs.

Settle the missing counter for the readiness guard only. Billing still
preserves prior values when a counter is absent, and a payload reporting
neither counter stays unavailable.
emptyUsage() returns a literal without contextUsage, so reading the property
directly failed the test-types gate. Match the neighbouring assertions instead.
@ayaangazali
ayaangazali force-pushed the fix/anthropic-usage-absent-cache-write branch from e8401f7 to f37a28d Compare August 25, 2026 22:27
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 28, 2026
@ayaangazali

Copy link
Copy Markdown
Contributor Author

Rechecked this against current main and the scope has narrowed, so flagging what is left.

readAnthropicPromptUsageSnapshot has since been fixed on main in the same shape this PR uses:

const cacheRead =
  usage.cache_read_input_tokens == null ? 0 : readAnthropicUsageTokenCount(usage.cache_read_input_tokens);

The two call sites this PR targets still carry the original behaviour on main:

  • readLastAnthropicIterationUsage still does readAnthropicUsageTokenCount(record.cache_read_input_tokens) with no null settlement
  • applyAnthropicMessageDeltaUsage still requires both raw counters before it treats context as available

So a provider that reports one cache counter and omits the other still lands on unavailable context and estimate-based compaction through those paths, which is the case in #99864. The difference from the snapshot fix is that this PR only settles the missing side to zero when the payload carries at least one cache counter, so a payload with neither is still rejected as partial rather than silently understating the window.

The branch is conflict-free against current main and its checks are green. I have deliberately not rebased it, since there is nothing to resolve and a large replay onto a fast-moving base risks losing hunks for no gain.

Happy to narrow the diff to just those two functions if the snapshot-side overlap makes review easier.

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

Real-setup verification — tested at head f37a28d60dbac0abc036fd925c52c01a019e0b05

Setup: isolated checkout (git fetch origin pull/126473/head), Docker node:26, pnpm install --ignore-scripts, no secrets in env, tests run with --network=none. Linux host.

After (head f37a28d6): node scripts/run-vitest.mjs packages/ai/src/providers/anthropic-usage.test.ts → 14/14 passed (1.71s).

Before (merge-base fbf67353): overlaid only the PR's test file(s) onto the merge-base, same command → 2 failed | 12 passed — reproducing the base behavior the PR fixes.

Not covered: live usage accounting against a real Anthropic API response (unit-level proof only).

Verified by Sho (human) + Alpha (AI agent) on a real OpenClaw setup. Happy to re-run against a new head if the branch moves.

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Sep 1, 2026
Reuse the canonical prompt snapshot validator for no-iteration deltas.
Keep malformed counters unavailable and preserve strict iteration usage
and existing billing accumulation.

Closes openclaw#126436

Co-authored-by: ayaangazali <[email protected]>
@steipete
steipete merged commit 2f7e103 into openclaw:main Sep 2, 2026
211 of 212 checks passed
@steipete

steipete commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 2, 2026
…he (openclaw#126473)

* fix(anthropic): keep context usage for providers that never write cache

readLastAnthropicIterationUsage required every cache counter to be readable.
An Anthropic-compatible provider that never writes cache omits
cache_creation_input_tokens entirely, so the final iteration was scored
invalid, contextUsage fell to "unavailable", and the session then sized its
context window from a character estimate rather than the provider's numbers.
Threshold compaction fires on that estimate.

readAnthropicPromptUsageSnapshot already reads an absent counter as zero on
the message_start path, so the two paths disagreed about the same payload.

Absence now means zero only when the record carries at least one cache
counter, which is what proves the provider reports them. An iteration with no
cache counter at all stays invalid: that is a partial payload, and assuming
zero would understate the context window, which is the case openclaw#99864 added and
its test still covers.

Refs openclaw#126436

* fix(anthropic): settle context usage on the no-iterations delta path too

The one-counter rule only covered the final-iteration reader. With no
iterations array that reader returns absent and the delta fallback still
required both raw cache counters, so a provider that never writes cache stayed
on unavailable context and estimate-based compaction. That is the path the
affected deployment actually runs.

Settle the missing counter for the readiness guard only. Billing still
preserves prior values when a counter is absent, and a payload reporting
neither counter stays unavailable.

* test(anthropic): assert the unavailable guard through toMatchObject

emptyUsage() returns a literal without contextUsage, so reading the property
directly failed the test-types gate. Match the neighbouring assertions instead.

---------

Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: ayaangazali <[email protected]>
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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: XS status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

5 participants