Repository navigation
fix(usage): correct cached long-context cost estimates - #133349
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: needs maintainer review before merge. Reviewed August 30, 2026, 3:28 PM ET / 19:28 UTC. ClawSweeper reviewWhat this changesThe PR adds cache-aware whole-request pricing tiers for two Venice models and preserves per-call or provider-billed costs through OpenClaw run, session, diagnostic, and status reporting. Merge readinessThe central pricing defect remains absent from current main, and this PR’s introduced repair has no supported correctness finding. It remains open for normal maintainer handling while exact-head checks complete. Priority: P2 Review scores
Verification
How this fits togetherVenice model metadata supplies rates to the shared LLM cost calculator. Per-call costs then flow through agent-run accounting into persisted session summaries, diagnostics, and user-visible usage/status output. flowchart LR
A[Venice model manifest] --> B[Shared pricing calculator]
C[Provider usage response] --> D[Usage normalization]
D --> B
B --> E[Per-call monetary fact]
E --> F[Agent run accounting]
F --> G[Session and diagnostics]
G --> H[Usage and status output]
Before merge
Agent review detailsSecurityNone. PR surfaceSource -25, Tests +1163, Docs +25, Other -1. Total +1162 across 66 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: 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: Land one canonical per-request pricing path that retains operator-authored prices, keeps Venice-specific schedules in the plugin manifest, and uses recorded call totals wherever aggregate tokens cannot identify a tier. Do we have a high-confidence way to reproduce the issue? Yes—source provides deterministic parser and calculator inputs for cached threshold crossings and explicit-price precedence, though this read-only review did not execute them. Is this the best way to solve the issue? Yes—the vendor schedule remains with the Venice plugin while the shared calculator owns provider-neutral bucket and per-request tier accounting, avoiding divergent downstream estimates. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against d434b3dbe0b2. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (4 earlier review cycles)
|
9c60887 to
803cd69
Compare
|
Final behavior proof and maintainer decision for the cached long-context pricing repair. The latest ClawSweeper review has no actionable code findings. Its remaining contract/upgrade question is resolved: a fresh unauthenticated Venice catalog GET at 2026-08-30 18:49:21 UTC returned the same rates as the earlier 19-model comparison (response SHA-256 Maintainer decision: preserve nonempty authored prices, including explicit zero and authored tiers, without inheriting a lower-priority catalog schedule. Omitted/empty cost objects still inherit. This accepts the intended explicit-override repair; it does not attribute client configuration semantics to Venice. The automated stored-schema flag is a false positive for the worker files: those edits carry costs through existing result/diagnostic boundaries, not DDL or a new store. The derived reporting cache uses its existing semantic invalidation version; SQLite schema/layout/retention/concurrency are unchanged. The real built Gateway, built Venice/Telegram paths, synthetic SSE provider and mock Telegram API passed all four cases. This condensed verdict projects the inspected full artifact: {
"kind": "mock-channel-api + synthetic-provider-sse + ephemeral-built-gateway",
"head": "803cd6989364c1c22d5b13165e2d4552794ac7bf",
"finishedAt": "2026-08-30T18:18:15.706Z",
"passed": true,
"cases": [
{"id":"grok-cached-threshold","requestUsd":0.53460068,"visibleCost":"0.5346","cumulativeUsd":0.53460068,"passed":true},
{"id":"qwen-nested-cache-writes","requestUsd":0.27600015,"visibleCost":"0.2760","cumulativeUsd":0.81060083,"passed":true},
{"id":"provider-billed-positive","requestUsd":0.125,"visibleCost":"0.1250","cumulativeUsd":0.93560083,"passed":true},
{"id":"provider-billed-zero","requestUsd":0,"visibleCost":"0.0000","cumulativeUsd":0.93560083,"passed":true}
],
"finalTokenBuckets":{"input":200000,"output":2000,"cacheRead":200002,"cacheWrite":56000,"totalTokens":458002},
"finalCostBuckets":{"input":0.603,"output":0.0196,"cacheRead":0.08300083000000001,"cacheWrite":0.105},
"providerRequests":4,
"realCredentials":false,
"paidInference":false,
"operatorGatewayOrState":false,
"ownedProcessesStopped":true
}The cost-only turns leave token/bucket totals unchanged, record snapshot/log costs of 0.125 then 0, and keep current context honestly unknown/stale. The usage-cache observer waits for fresh state and the turn's updated timestamp before asserting values; it does not retry until prices match. Source/build fingerprints remained unchanged. Full verdict SHA-256: Local proof: 1,254 focused/sibling tests across 57 files, full classified gates, full build, and independent scoped Codex review passed on the production candidate. The first integrated CI run caught six outdated strict worker-launcher expectations. Commit The first corrected-head run was superseded after main advanced into a real merge conflict. Head After integration, 184 boundary tests plus the 37 worker/payload/accumulator tests passed, along with the full classified changed gates and a fresh scoped Codex review. Exact-head CI is green on unchanged Limits: mock Telegram, not live Telegram or a paid Venice invoice; four sequential turns, with same-turn tool loops/retries covered separately by boundary tests. A recurring synthetic-agent metadata-snapshot diagnostic was retained as an unclassified observation, not a proven product bug. No unrelated provider rates, new config options, dependency versions, or protocol versions changed. Production LOC remains +516/-541 (net -25); tests are +1627/-464. Post-merge verificationMerged via the native workflow as 97998cb25f9; the cached-pricing issue is closed as completed. The catalog refresh succeeded. At 2026-08-30 20:10:49 UTC, an ordinary GET of the served catalog contained all 19 Venice rows and both tier schedules exactly matching the landed manifest, including starts 200001/256001 and every base/extended USD rate. Its source commit is Post-merge verification on that main revision passed 58/58 tests across the Venice models, shared cost estimator and status-message suites. This also checks composition with the later mainline status-context changes. Exact command: node scripts/run-vitest.mjs src/status/status-message.test.ts src/utils/usage-format.cost.test.ts extensions/venice/models.test.ts |
Keep Venice extended schedules in the owning manifest, select per-call tiers from total prompt input, and preserve explicit pricing and provider-billed totals through run accounting. Fixes #133343.
d2e5265 to
7479e9c
Compare
|
Merged via squash.
|
Use complete native OpenCode and Venice pricing schedules while preserving authored zero, partial, flat and tiered costs across preparation and lookup. Avoid generated price pins during fresh merge-mode Venice onboarding. Follow-up to #133349 (cached long-context accounting) and #129694 (Venice runtime pricing); related to #113549 (broader OpenCode catalog drift).
* fix(usage): correct cached long-context cost estimates Keep Venice extended schedules in the owning manifest, select per-call tiers from total prompt input, and preserve explicit pricing and provider-billed totals through run accounting. Fixes openclaw#133343. * test(usage): assert worker monetary result metadata
Use complete native OpenCode and Venice pricing schedules while preserving authored zero, partial, flat and tiered costs across preparation and lookup. Avoid generated price pins during fresh merge-mode Venice onboarding. Follow-up to #133349 (cached long-context accounting) and #129694 (Venice runtime pricing); related to #113549 (broader OpenCode catalog drift).
* fix(models): refresh native pricing without pinning defaults Use complete native OpenCode and Venice pricing schedules while preserving authored zero, partial, flat and tiered costs across preparation and lookup. Avoid generated price pins during fresh merge-mode Venice onboarding. Follow-up to #133349 (cached long-context accounting) and #129694 (Venice runtime pricing); related to #113549 (broader OpenCode catalog drift). * fix(pricing): preserve native schedules through resolution Merge prepared costs beneath authored display prices, retain validated native free schedules under exact owner policy, and compile OpenRouter overrides with strict thresholds and source-order inheritance for each price key. Preserve zero, partial, flat and tiered user pricing without new settings or storage. Follow-up repairs for #133695.
…w#133695) * fix(models): refresh native pricing without pinning defaults Use complete native OpenCode and Venice pricing schedules while preserving authored zero, partial, flat and tiered costs across preparation and lookup. Avoid generated price pins during fresh merge-mode Venice onboarding. Follow-up to openclaw#133349 (cached long-context accounting) and openclaw#129694 (Venice runtime pricing); related to openclaw#113549 (broader OpenCode catalog drift). * fix(pricing): preserve native schedules through resolution Merge prepared costs beneath authored display prices, retain validated native free schedules under exact owner policy, and compile OpenRouter overrides with strict thresholds and source-order inheritance for each price key. Preserve zero, partial, flat and tiered user pricing without new settings or storage. Follow-up repairs for openclaw#133695.
Closes #133343 (cached long-context pricing and custom-price precedence).
Related: #129694 (the already-merged Venice runtime price-preservation fix; this is a separate repair).
What Problem This Solves
Fixes inaccurate cost estimates when cached requests cross a long-context pricing threshold, when tool loops combine multiple calls, or when a provider reports a billed amount without token counters. Venice's Grok and Qwen Plus entries were missing their published extended schedules; cache writes could also be counted as ordinary input. Explicit flat or zero prices could inherit catalog tiers and stop being honored.
Why This Change Was Made
Vendor-specific rates stay in the Venice manifest. One provider-neutral calculator in
llm-coreselects the whole-request tier from uncached input plus cache reads and writes, then prices those buckets separately. The completion transport recognizes Venice's documented nested cache-write field. Run accounting carries complete per-call monetary totals instead of reconstructing request boundaries from accumulated tokens.Price precedence is repaired at config/default and duplicate-row owners: omitted or empty cost objects inherit catalog pricing; explicit flat, zero, or tier schedules win. Transcript repricing now retains the bucket breakdown as well as the total. Rebuildable usage rollups invalidate obsolete pricing results through their existing semantic cache version; no SQLite schema, table, retention, or concurrency change is made.
The old internal pricing module and duplicated arithmetic/projections are removed. No new configuration option, dependency, or Gateway protocol change is introduced. Production is +516/-541 (net -25).
User Impact
venice/grok-4-5selects extended rates strictly above 200,000 prompt tokens;venice/qwen-3-7-plusstrictly above 256,000. Exact-threshold requests retain base rates. Output tokens do not select the tier.Evidence
Before and after
Actual parser/calculator/reporting paths, synthetic usage, and public rates; no paid inference:
The unauthenticated public catalog was rechecked 2026-08-30 at 16:49:13 UTC: HTTP 200, 111 models, all 19 bundled base prices and both extended schedules matched. Earlier real guarded discovery and 19 boundary replays also passed.
Integrated local verification
Production/build/Gateway proof commit:
803cd6989364c1c22d5b13165e2d4552794ac7bf; original base6e6319440e7a9a9758cdf18995ebdc6455d826d0. Current head7479e9c65a7fafb671ba742a7cdda13df5178df9rebases the repair and test-only CI correction onto52eed802cd551bf63e762db8877304cf0624e195after a real merge conflict. The sole manual conflict was adjacent performance-test additions: both main's yield-budget cases and the monetary cache table are retained. The inspected range diff changes only surrounding context; the worker CI correction is patch-identical.The rebased candidate passed 184 focused integration tests, the full classified changed gates, and a fresh independent scoped review with no findings. Main's presence-aware compaction snapshots are preserved: writer custody alone does not invent a context observation, and cost-only billing remains independent. The earlier built-Gateway proof is bound to its recorded commit rather than being represented as a new-head run.
1,254 unique focused/sibling tests passed across 57 files, including threshold boundaries, cache reads/writes and one-hour subsets, transport parity, explicit overrides, multi-call costs, missing-price handling, cost-only billing, stream deduplication, persisted snapshots, worker fault paths, and six provider-plugin directories. This is not the full repository suite; 175 unrelated session tests were deliberately filtered out.
Full classified changed gates passed: formatting, core/plugin production and test types, lint, dead exports, metadata, schema/legacy-store guards, import cycles, and the remaining classified checks.
pnpm buildpassed with zero ineffective-dynamic-import warnings. Fresh independent Codex review of the complete integrated candidate was scoped-clean through P1, with no accepted findings.Red/green proof covers the original accounting defects plus the review's cost-only finding. A broader run exposed an existing early-flush test fixture that lost its configured model row after persistence and entered real catalog discovery. The fixture now establishes one source-backed config shared by persistence and both model calls. The original two-file order passed 90/90 tests; the early-flush case fell from an observed 109.8 seconds to 237 ms. No production context logic, timeout, environment, or broader mock was changed. The later queue assertion passed in the same order; its original cascade attribution is not claimed as independently proven.
The assertion baseline shrinks to reflect two removed assertions. The worker test table was compacted without deleting any of its four cases or increasing the line limit.
Operator-visible proof
Final built-Gateway proof passed 4/4 on
803cd6989364c1c22d5b13165e2d4552794ac7bf, completed 2026-08-30 at 18:18:15 UTC. Real built Venice/Telegram paths used a loopback SSE provider and mock Telegram API. Delivered monetary values were0.5346,0.2760,0.1250, and0.0000; cumulative session cost was$0.93560083. Input/output/cache-read/cache-write costs were$0.603 / $0.0196 / $0.08300083 / $0.105. Billed-cost-only turns left these buckets and token counters unchanged, while recording positive/zero dollars and honestly unknown/stale current context.Exactly four synthetic provider requests were made; no real credentials, operator Gateway/state, or paid inference was used. The proof waits for the documented fresh usage-cache state before asserting values, not for money to happen to match. Source and built fingerprints were unchanged; all owned processes were stopped and temporary runtime state removed. Verdict SHA-256:
ed45769930466968fda9cb090d88e45d9acfc3790146e043bd6bedb00d59f77e.Limits: this is mock-channel Gateway proof, not live Telegram or a Venice invoice. The four turns are sequential; same-turn tool loops/retries have separate boundary regressions. A recurring synthetic-agent
ChatMetadataSnapshotUnavailableErrorwas recorded as an unclassified diagnostic, not a confirmed product defect. Exact-head hosted CI passed, attempt 2 on7479e9c65a7fafb671ba742a7cdda13df5178df9. Attempt 1 had one unrelated desktop-shutdown root-work assertion failure. Unchanged standalone, original-neighborhood and full original CI-shard controls passed (6, 39 and 2,938 tests respectively); the single targeted hosted rerun passed without source changes. The cause remains unproven and its evidence is retained as a named follow-up—not hidden by a reset, relaxed assertion or timeout increase.Condensed mock-Gateway verdict
{ "kind": "mock-channel-api + synthetic-provider-sse + ephemeral-built-gateway", "head": "803cd6989364c1c22d5b13165e2d4552794ac7bf", "finishedAt": "2026-08-30T18:18:15.706Z", "passed": true, "cases": [ {"id":"grok-cached-threshold","requestUsd":0.53460068,"cumulativeUsd":0.53460068,"passed":true}, {"id":"qwen-nested-cache-writes","requestUsd":0.27600015,"cumulativeUsd":0.81060083,"passed":true}, {"id":"provider-billed-positive","requestUsd":0.125,"cumulativeUsd":0.93560083,"passed":true}, {"id":"provider-billed-zero","requestUsd":0,"cumulativeUsd":0.93560083,"passed":true} ], "finalTokenBuckets":{"input":200000,"output":2000,"cacheRead":200002,"cacheWrite":56000,"totalTokens":458002}, "finalCostBuckets":{"input":0.603,"output":0.0196,"cacheRead":0.08300083000000001,"cacheWrite":0.105}, "providerRequests":4, "realCredentials":false, "paidInference":false, "ownedProcessesStopped":true }Maintainer review decision
The current public Venice response was re-fetched without authentication at 2026-08-30 18:49:21 UTC and is byte-identical to the 16:49 verification (
SHA-256 6da350f42aaa171f9bf78d2722b791e7f282cda0934df54239a557a05b28c0aa). The official OpenAPI says: “When input tokens exceed context_token_threshold, extended rates apply to the entire request.” The prompt-caching guide definesprompt_tokensas total input, including cached and newly written tokens. Exact-threshold requests remain base-priced; extended ranges therefore start at 200,001 and 256,001.The intended upgrade behavior is accepted: nonempty authored prices are authoritative and must not acquire lower-priority catalog tiers; omitted and empty objects still inherit. This is OpenClaw's explicit-override contract, not a claim that Venice defines client configuration semantics. No stored schema is changed in either worker file flagged by the automated classifier; those edits carry monetary metadata through existing result/diagnostic boundaries. The reporting change invalidates a rebuildable projection through its existing semantic cache version only.
Hosted CI on the first integrated head caught six strict worker-launcher expectations that still described token-only metadata. The test-only correction retains strict equality, covers known zero, and adds an independent cross-model
$0.125 + $0.25 = $0.375total. The corrected launcher, payload and accumulator suites pass 37/37. No production behavior changed for this CI correction.Contract sources and limits
Qianfan/Tencent documentation supports input-length tiers with cached-input accounting. Volcengine's official pricing page was inaccessible, so its complete billing contract is not claimed; its schedule is unchanged and its focused tests passed. A separate OpenCode seed-rate discrepancy remains outside this PR. No real credentials, high-token paid inference, or live invoice verification were used.
Stock current stable
2026.7.1-2does not consume the hosted OpenClaw catalog; its installed-manifest/OpenRouter/LiteLLM path and explicit-price precedence were inspected at tag commit0790d9f593ad30c940ed93b5872a8cf6d6f3cf8c. No new stable rollout gate is needed. Beta/nightly/custom backport behavior was not claimed as a stable contract.Exact local command ledger
Initial broad run; exposed the fixture timeout described above
Remaining owner and sibling suites; passed
Session usage owner; passed
Corrected original reply order; 90 passed
Compacted worker boundary table; 30 passed
Complete changed gate; passed
Full build; passed
Rebase composition and both retained performance tables; 184 passed
Worker terminal metadata CI correction; 37 passed, including a repeat on the rebased head
Test-only correction classified gates; passed
Final built-Gateway proof; 4/4 passed with synthetic loopback services