Repository navigation
fix(anthropic): keep context usage for providers that never write cache - #126473
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: needs real behavior proof before merge. Reviewed September 1, 2026, 7:47 PM ET / 23:47 UTC. ClawSweeper reviewWhat this changesThis 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 provenancePossible 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 Review scores
Verification
How this fits togetherAnthropic-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
Before merge
Agent review detailsSecurityNone. PR surfaceSource -1, Tests +39. Total +38 across 2 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest 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. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (12 earlier review cycles; latest 8 shown)
|
e6835ca to
c8f9724
Compare
PR #126473 — real-behaviour evidence from an affected deployment
Environment
1. The symptom is model-specific, not provider-specificEight consecutive turns, same portal, same account, same build, before any patch:
Same client, same endpoint. The two models differ, which narrows the report considerably. 2. Isolation experiment — three states, each proved separately
Verbatim, from the isolated state (patch A verified absent, marker count 0): Patch A alone: no effect. Patch B alone: cures. Both verified with the other patch removed, so 3. Where the gate actually isFor this wire, the decision is not made in
The provider sends
This matches defect #1 of the PR's own review (the reviewer listed two defects; the PR fixes 4. Corrections we owe the readerReported because a write-up that hides its wrong turns does not deserve trust:
5. Current state and offerThis deployment currently runs patch B only — the isolation state — and reports Suggested action for the PR: apply the same coercion at the top-level delta fallback. Without |
Addendum to the evidence above — a stronger data point, and a methodology correctionPosted after the original comment. Two things a reader deserves. The strongest single observation: one long-lived session, before and afterOne session was open across the change. It emits
The patch went live between those two timestamps. Nothing else changed. This is a natural Methodology correctionOur first pass read the first We re-ran the count over all occurrences per file. The conclusion is unchanged and better
The 22-occurrence baseline matters: zero of its iterations ever reached Note also that within a single turn, early iterations legitimately report |
c8f9724 to
5f7932c
Compare
5f7932c to
e198187
Compare
|
The P1 was right and it explains the field report. Fixed in My one-counter rule only touched (inputTokens !== undefined && cacheReadTokens !== undefined && cacheWriteTokens !== undefined)A provider that never writes cache omits The missing counter is now settled for the readiness guard only. Two things deliberately left alone:
Provider-boundary trace, same delta payload, only Two regression tests. The reported-path one fails on the unfixed reader (
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. |
e198187 to
989b0a1
Compare
f50c997 to
e8401f7
Compare
|
This one is GitHub infrastructure, not code. No speculative fix pushed.
The runner could not resolve GitHub's own internal action-download host, so Context worth having: all 15 of my open PRs went red together after I rebased them onto current 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.
e8401f7 to
f37a28d
Compare
|
Rechecked this against current
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
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 Happy to narrow the diff to just those two functions if the snapshot-side overlap makes review easier. |
shojikumaru
left a comment
There was a problem hiding this comment.
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.
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]>
|
Merged via squash.
|
…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]>
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
a9469a2119a6cd4251c7346c896c8d9cae3633a3returned 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
passedmeans 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
e2442b78b9ba67b32c9f880eb1d8ac743c667306were rehashed and are byte-identical to the tested candidate:packages/ai/package.json262478c3acb2d4ec333bfa00f38896014232a288183e70ec39409e35873c0091packages/ai/src/providers/anthropic-usage.tsaf08040903f8923bdf4b8fb2ce70ca24268951fd13620389ba5e35ec182a3903packages/ai/src/providers/anthropic.ts457274639c0d98bb8f0033240b18aa0b5d000ab5410d23fc4f0fd3056fd589a2packages/ai/src/transports/anthropic-transport-stream.ts3987f41134675389d2974c6063e5e6ce606a280c144791cffb2a21faede248f9packages/ai/src/host.ts0dec2ae17aa539ea43099a46f662aedb13566aeae48b9501466b70650ac03fd0src/agents/usage.tsc8b713e015591e546ad351e81ba8742f01525f6a84423fc7f8678965ec8e6997The 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.