Skip to content

fix(usage): correct cached long-context cost estimates - #133349

Merged
steipete merged 2 commits into
mainfrom
steipete/hungry-williams-ed51ec
Aug 30, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/hungry-williams-ed51ec

Conversation

@steipete

@steipete steipete commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

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-core selects 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-5 selects extended rates strictly above 200,000 prompt tokens; venice/qwen-3-7-plus strictly above 256,000. Exact-threshold requests retain base rates. Output tokens do not select the tier.
  • Runtime records, turn summaries, footers, status, session snapshots, cron and worker diagnostics preserve per-call prices and provider-billed totals, including zero. Billed amounts without token counts do not fabricate token/context observations.
  • A tiered aggregate with incomplete per-request prices remains unknown. Flat-rate fallback remains available to token-only runtimes. A transport's untagged zero placeholder is not treated as observed billing.
  • Explicit user prices are preserved. Sibling providers' rate/threshold tables are unchanged.

Evidence

Before and after

Actual parser/calculator/reporting paths, synthetic usage, and public rates; no paid inference:

Request, with 1,000 output tokens Before Corrected estimate
Grok: prompt 200,001, cached 100,001 $0.26780034 $0.53460068
Qwen: prompt 256,001, cached 100,001, new writes 56,000 $0.08500005 $0.27600015

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 base 6e6319440e7a9a9758cdf18995ebdc6455d826d0. Current head 7479e9c65a7fafb671ba742a7cdda13df5178df9 rebases the repair and test-only CI correction onto 52eed802cd551bf63e762db8877304cf0624e195 after 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 build passed 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 were 0.5346, 0.2760, 0.1250, and 0.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 ChatMetadataSnapshotUnavailableError was recorded as an unclassified diagnostic, not a confirmed product defect. Exact-head hosted CI passed, attempt 2 on 7479e9c65a7fafb671ba742a7cdda13df5178df9. 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 defines prompt_tokens as 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.375 total. 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-2 does not consume the hosted OpenClaw catalog; its installed-manifest/OpenRouter/LiteLLM path and explicit-price precedence were inspected at tag commit 0790d9f593ad30c940ed93b5872a8cf6d6f3cf8c. 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

node scripts/run-vitest.mjs extensions/opencode extensions/opencode-go extensions/qianfan extensions/tencent extensions/venice extensions/volcengine packages/ai/src/providers/anthropic.test.ts packages/ai/src/providers/openai-completions-usage-parity.test.ts packages/ai/src/providers/openai-responses-service-tier-pricing.test.ts packages/ai/src/transports/anthropic-transport-stream.test.ts packages/ai/src/transports/openai-completions-stream.usage.test.ts src/agents/agent-command.ingress-diagnostics.test.ts src/agents/command/session-store.test.ts src/agents/embedded-agent-runner/run.attempt-normalization.direct.test.ts src/agents/embedded-agent-runner/run/helpers.test.ts src/agents/embedded-agent-runner/run/terminal-preparation.test.ts src/agents/embedded-agent-runner/usage-accumulator.test.ts src/agents/embedded-agent-subscribe.handlers.messages.lifecycle.test.ts src/agents/embedded-agent-subscribe.subscribe-embedded-agent-session.subscribeembeddedagentsession.test.ts src/agents/models-config.providers.normalize-keys.test.ts src/agents/usage.normalization.test.ts src/agents/usage.test.ts src/auto-reply/reply/agent-runner-usage-line.test.ts src/auto-reply/reply/agent-runner.misc.runreplyagent.test.ts src/auto-reply/reply/reply-usage-state.test.ts src/config/defaults.test.ts src/cron/isolated-agent/run.diagnostic-events.test.ts src/cron/isolated-agent/run.usage-accounting.test.ts src/gateway/session-utils.perf.test.ts src/gateway/worker-environments/inference-runtime.test.ts src/gateway/worker-environments/worker-turn-payload.test.ts src/infra/session-cost-usage-cache.sqlite.test.ts src/infra/session-cost-usage-reporting.test.ts src/infra/session-cost-usage.test.ts src/llm/model-utils.test.ts src/plugins/runtime/runtime-llm-diagnostics.runtime.test.ts src/plugins/runtime/runtime-llm-isolated.runtime.test.ts src/status/status-message.test.ts src/utils/usage-format.cost.test.ts src/utils/usage-format.test.ts

Remaining owner and sibling suites; passed

node scripts/run-vitest.mjs extensions/opencode extensions/opencode-go extensions/qianfan extensions/tencent extensions/venice extensions/volcengine src/agents/agent-command.ingress-diagnostics.test.ts src/agents/command/session-store.test.ts src/agents/embedded-agent-runner/run.attempt-normalization.direct.test.ts src/agents/embedded-agent-runner/run/terminal-preparation.test.ts src/agents/embedded-agent-subscribe.handlers.messages.lifecycle.test.ts src/agents/embedded-agent-subscribe.subscribe-embedded-agent-session.subscribeembeddedagentsession.test.ts src/agents/models-config.providers.normalize-keys.test.ts src/gateway/session-utils.perf.test.ts src/gateway/worker-environments/inference-runtime.test.ts src/gateway/worker-environments/worker-turn-payload.test.ts src/plugins/runtime/runtime-llm-diagnostics.runtime.test.ts src/plugins/runtime/runtime-llm-isolated.runtime.test.ts src/utils/usage-format.test.ts

Session usage owner; passed

node scripts/run-vitest.mjs src/auto-reply/reply/session.test.ts -t persistSessionUsageUpdate

Corrected original reply order; 90 passed

node scripts/run-vitest.mjs src/auto-reply/reply/reply-usage-state.test.ts src/auto-reply/reply/agent-runner.misc.runreplyagent.test.ts --reporter=verbose

Compacted worker boundary table; 30 passed

node scripts/run-vitest.mjs src/gateway/worker-environments/inference-runtime.test.ts

Complete changed gate; passed

node scripts/check-changed.mjs --base 52eed802cd551bf63e762db8877304cf0624e195 -- config/assertion-safety-baseline.txt docs/cli/agent.md docs/providers/venice.md docs/reference/token-use.md extensions/venice/models.test.ts extensions/venice/onboard.test.ts extensions/venice/openclaw.plugin.json packages/ai/src/model-utils.ts packages/ai/src/providers/openai-completions-usage-parity.test.ts packages/ai/src/transports/openai-transport-shared.ts packages/llm-core/src/index.ts packages/llm-core/src/types.ts packages/llm-core/src/usage-cost.ts src/agents/agent-command.ingress-diagnostics.test.ts src/agents/command/ingress-diagnostics.ts src/agents/command/session-store.test.ts src/agents/command/session-store.ts src/agents/embedded-agent-runner/run.attempt-normalization.direct.test.ts src/agents/embedded-agent-runner/run/helpers.ts src/agents/embedded-agent-runner/run/terminal-preparation.test.ts src/agents/embedded-agent-runner/run/terminal-preparation.ts src/agents/embedded-agent-runner/usage-accumulator.test.ts src/agents/embedded-agent-runner/usage-accumulator.ts src/agents/embedded-agent-subscribe.handlers.messages.lifecycle.test.ts src/agents/embedded-agent-subscribe.handlers.messages.lifecycle.ts src/agents/embedded-agent-subscribe.handlers.ts src/agents/embedded-agent-subscribe.subscribe-embedded-agent-session.subscribeembeddedagentsession.test.ts src/agents/embedded-agent-subscribe.ts src/agents/models-config.providers.normalize-keys.test.ts src/agents/models-config.providers.normalize.ts src/agents/usage.normalization.test.ts src/agents/usage.ts src/auto-reply/reply/agent-runner-result-accounting.ts src/auto-reply/reply/agent-runner-result-payloads.ts src/auto-reply/reply/agent-runner-usage-line.test.ts src/auto-reply/reply/agent-runner-usage-line.ts src/auto-reply/reply/agent-runner.misc.runreplyagent.test.ts src/auto-reply/reply/reply-usage-state.test.ts src/auto-reply/reply/reply-usage-state.ts src/auto-reply/reply/session-usage.ts src/auto-reply/reply/session.test.ts src/config/defaults.test.ts src/config/defaults.ts src/config/model-cost.ts src/config/types.models.ts src/cron/isolated-agent/run-finalize.ts src/cron/isolated-agent/run.diagnostic-events.test.ts src/gateway/session-utils-core.ts src/gateway/session-utils.perf.test.ts src/gateway/worker-environments/inference-runtime.test.ts src/gateway/worker-environments/inference-runtime.ts src/gateway/worker-environments/worker-turn-payload.ts src/infra/session-cost-usage-aggregation.ts src/infra/session-cost-usage-pricing.ts src/infra/session-cost-usage-reporting.test.ts src/infra/session-cost-usage.test.ts src/llm/model-utils.test.ts src/plugins/runtime/runtime-llm-isolated.runtime.test.ts src/plugins/runtime/runtime-llm.runtime.ts src/status/status-message.test.ts src/status/status-message.ts src/utils/usage-format-pricing.ts src/utils/usage-format.cost.test.ts src/utils/usage-format.test.ts src/utils/usage-format.ts

Full build; passed

pnpm build

Rebase composition and both retained performance tables; 184 passed

node scripts/run-vitest.mjs src/gateway/session-utils.perf.test.ts src/agents/command/session-store.test.ts src/auto-reply/reply/reply-usage-state.test.ts src/auto-reply/reply/agent-runner.misc.runreplyagent.test.ts src/agents/embedded-agent-runner/run.attempt-normalization.direct.test.ts

Worker terminal metadata CI correction; 37 passed, including a repeat on the rebased head

node scripts/run-vitest.mjs src/gateway/worker-environments/worker-turn-launcher-terminal-results.test.ts src/gateway/worker-environments/worker-turn-payload.test.ts src/agents/embedded-agent-runner/usage-accumulator.test.ts

Test-only correction classified gates; passed

node scripts/check-changed.mjs -- src/gateway/worker-environments/worker-turn-launcher-terminal-results.test.ts

Final built-Gateway proof; 4/4 passed with synthetic loopback services

env -i PATH="$PATH" HOME="$PWD/.artifacts/venice-gateway-proof-final/driver-home" OPENCLAW_HOME="$PWD/.artifacts/venice-gateway-proof-final/driver-home" OPENCLAW_STATE_DIR="$PWD/.artifacts/venice-gateway-proof-final/driver-state" TMPDIR="$PWD/.artifacts/venice-gateway-proof-final/tmp" node --import tsx .artifacts/venice-gateway-proof-final/run-proof.ts --repo-root . --output-dir .artifacts/venice-gateway-proof-final --baseline .artifacts/venice-gateway-proof-final/attempt-1-display-expectation.json --expect-cost-breakdown --include-cost-only

@steipete steipete self-assigned this Aug 30, 2026
@clawsweeper

clawsweeper Bot commented Aug 30, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling extensions: venice size: XL maintainer Maintainer-authored PR labels Aug 30, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 30, 2026
@clawsweeper

clawsweeper Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 30, 2026, 3:28 PM ET / 19:28 UTC.

ClawSweeper review

What this changes

The 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 readiness

⚠️ Ready for maintainer review - 2 items remain

The 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
Reviewed head: 7479e9c65a7fafb671ba742a7cdda13df5178df9

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A well-scoped, net-negative production repair with concrete boundary evidence and no identified patch defect; exact-head CI remains the normal landing gate.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (logs): The supplied evidence records an after-fix built Gateway using the real Venice parser/accounting path with a synthetic SSE provider and mock Telegram transport, observing corrected threshold and billed-cost output. Its runtime artifact is bound to commit 803cd69; independently, the reviewed head differs from the repair commit only in a test, while exact-head hosted checks remain incomplete.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (logs): The supplied evidence records an after-fix built Gateway using the real Venice parser/accounting path with a synthetic SSE provider and mock Telegram transport, observing corrected threshold and billed-cost output. Its runtime artifact is bound to commit 803cd69; independently, the reviewed head differs from the repair commit only in a test, while exact-head hosted checks remain incomplete.
Evidence reviewed 7 items Current-main gap: Current main does not contain the new shared pricing module, so it does not yet implement the per-request cache-aware tier calculation.
Pricing owner and calculation: The introduced calculator selects a tier from uncached input plus cache reads and writes, then applies that tier to every bucket in the request.
Aggregate-boundary preservation: Aggregate usage deliberately uses recorded per-call totals and declines to infer a tiered total from combined token buckets.
Findings None None.
Security None None.

How this fits together

Venice 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]
Loading

Before merge

  • Resolve merge risk (P1) - Existing configurations with partial explicit flat pricing will no longer inherit a catalog tier schedule; the PR documents and tests that intentional precedence change, but it remains compatibility-sensitive until the exact head’s checks finish.
  • Complete next step (P2) - No repair job is warranted: the review found no actionable introduced defect, and remaining handling is normal exact-head validation and maintainer merge review.
Agent review details

Security

None.

PR surface

Source -25, Tests +1163, Docs +25, Other -1. Total +1162 across 66 files.

View PR surface stats
Area Files Added Removed Net
Source 34 516 541 -25
Tests 28 1627 464 +1163
Docs 3 36 11 +25
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 2 -1
Total 66 2180 1018 +1162

Review metrics

Metric Value Why it matters
Production versus test delta production +516/-541 (net -25); tests +1627/-464 The broad accounting refactor is net-negative in production while adding boundary coverage for pricing, aggregation, and reporting.

Stored data model

Persistent data-model change detected: durable storage schema: src/gateway/worker-environments/inference-runtime.ts, durable storage schema: src/gateway/worker-environments/worker-turn-payload.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #133343
Summary: This PR is the concrete candidate repair for the linked cached long-context pricing issue.

Members:

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

Merge-risk options

Maintainer options:

  1. Complete exact-head validation (recommended)
    Wait for the reviewed head’s relevant checks to finish green before landing the compatibility-sensitive pricing change.
  2. Retain documented override precedence
    Accept the tested behavior that a nonempty operator-authored price suppresses lower-priority catalog tiers while omitted or empty prices inherit them.

Technical review

Best 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.

Labels

Label changes:

  • add proof: telegram-e2e: This PR needs Telegram Test Server proof with the repository E2E skill. Usage/footer and status cost output can be visible in Telegram conversations, so a Telegram Test Server proof lane is applicable if additional channel-visible proof is requested.

Label justifications:

  • P2: This repairs inaccurate estimates for a bounded provider/model pricing path without evidence of invoice changes or runtime unavailability.
  • merge-risk: 🚨 compatibility: The PR deliberately changes how existing explicit model-price entries interact with catalog tier schedules.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): The supplied evidence records an after-fix built Gateway using the real Venice parser/accounting path with a synthetic SSE provider and mock Telegram transport, observing corrected threshold and billed-cost output. Its runtime artifact is bound to commit 803cd69; independently, the reviewed head differs from the repair commit only in a test, while exact-head hosted checks remain incomplete.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied evidence records an after-fix built Gateway using the real Venice parser/accounting path with a synthetic SSE provider and mock Telegram transport, observing corrected threshold and billed-cost output. Its runtime artifact is bound to commit 803cd69; independently, the reviewed head differs from the repair commit only in a test, while exact-head hosted checks remain incomplete.
  • proof: telegram-e2e: This PR needs Telegram Test Server proof with the repository E2E skill. Usage/footer and status cost output can be visible in Telegram conversations, so a Telegram Test Server proof lane is applicable if additional channel-visible proof is requested.

Evidence

What I checked:

Likely related people:

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

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 (4 earlier review cycles)
  • reviewed 2026-08-30T16:05:54.151Z sha 9c60887 :: found issues before merge. :: [P2] Preserve cost-only totals through run aggregation
  • reviewed 2026-08-30T18:12:50.703Z sha 803cd69 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-30T18:40:38.158Z sha 803cd69 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-30T19:02:04.972Z sha d2e5265 :: needs maintainer review before merge. :: none

@steipete
steipete force-pushed the steipete/hungry-williams-ed51ec branch from 9c60887 to 803cd69 Compare August 30, 2026 18:06
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 30, 2026
@steipete
steipete marked this pull request as ready for review August 30, 2026 18:17
@steipete

steipete commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor Author

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 6da350f42aaa171f9bf78d2722b791e7f282cda0934df54239a557a05b28c0aa). The official OpenAPI explicitly says, “When input tokens exceed context_token_threshold, extended rates apply to the entire request.” The cache guide defines prompt tokens as total input and distinguishes cache reads/writes. The strict boundaries are therefore 200,001 and 256,001. The current Grok extended input/output/cache-read rates are 4.53/13.6/0.68; Qwen input/output/cache-read/cache-write rates are 1.5/6/0.15/1.875 USD per million tokens.

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: ed45769930466968fda9cb090d88e45d9acfc3790146e043bd6bedb00d59f77e.

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 d2e52655df2757969cbc8667f77c9ca06647e5b0 changes only that test: it retains strict equality and zero-cost coverage, and adds the independent cross-model total 0.125 + 0.25 = 0.375. Its launcher/payload/accumulator proof passes 37/37; classified gates and fresh scoped review pass. Production bytes are identical to the Gateway-proof commit. Exact commands are in the updated PR body.

The first corrected-head run was superseded after main advanced into a real merge conflict. Head 7479e9c65a7fafb671ba742a7cdda13df5178df9 rebases the two-commit repair onto 52eed802cd551bf63e762db8877304cf0624e195. The only manual conflict was adjacent performance-test additions; both main's yield-budget cases and the pricing cache table are retained. Main's presence-aware compaction snapshots merged intact. The inspected range diff changes only surrounding context; the worker correction is patch-identical.

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 7479e9c65a7fafb671ba742a7cdda13df5178df9. Attempt 1 had one unrelated desktop-shutdown root-work assertion failure (expected 0, got 1). The unchanged standalone test passed 6/6, its immediate original-order sequence passed 39/39, and the full original two-worker CI shard passed 2,938/2,938 across 196 files. Source investigation did not prove a leaking producer. One targeted hosted rerun passed; no source edits, victim reset, weaker assertion, or timeout increase was applied. The preserved incident is a named follow-up. Native preparation and squash merge completed successfully. The built-Gateway verdict above remains honestly bound to its recorded pre-rebase commit, not relabeled as a new-head run.

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 verification

Merged 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 02c095ff389dd4f503d72a16c44d33f3fc87ce68, which includes the pricing merge.

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

@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Aug 30, 2026
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.
@steipete
steipete force-pushed the steipete/hungry-williams-ed51ec branch from d2e5265 to 7479e9c Compare August 30, 2026 19:14
@clawsweeper clawsweeper Bot added the proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. label Aug 30, 2026
@steipete
steipete merged commit 97998cb into main Aug 30, 2026
430 of 434 checks passed
@steipete
steipete deleted the steipete/hungry-williams-ed51ec branch August 30, 2026 20:05
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

steipete added a commit that referenced this pull request Aug 31, 2026
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).
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 31, 2026
* 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
steipete added a commit that referenced this pull request Aug 31, 2026
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).
steipete added a commit that referenced this pull request Aug 31, 2026
* 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.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 1, 2026
…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.
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 extensions: venice gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: cached long-context usage is underpriced and custom prices can inherit catalog tiers

1 participant