Skip to content

fix: count every model call once, with all four token parts and per-model prices - #166

Merged
nambok merged 2 commits into
mainfrom
feat/usage-accounting
Oct 19, 2026
Merged

nambok merged 2 commits into
mainfrom
feat/usage-accounting

Conversation

@nambok

@nambok nambok commented Oct 19, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Every model call is now counted once, with all four token parts, priced at the model that was actually used.

  • One path: common::usage takes the team, the feature, the model and the four token counts (new input, cache read, cache write 5m/1h, output) and adds them in one transaction to the team's month, all-time and day counters, with per-model and per-feature breakdowns and a per-model cost. The worker's Anthropic client cannot be built without a usage meter, so every worker call goes through it. Plan chat (API and streaming), memory extraction and the log analyzer record through the same fields.
  • Exactly once: run, feedback, resume, review and plan chat completions no longer add tokens or cost to the monthly counters (they keep their per-run totals). A test fails if any service adds those counters anywhere else.
  • Prices: one table (services/common/model_prices.json, from Anthropic's pricing page) with input, output, cache read and 5-minute and 1-hour cache write rates per model. A model missing from the table is logged once and costed at the most expensive rate, never zero. Run costs are now the sum of each call at its own model's price instead of one flat rate.
  • Token limit: can count all four parts. It is off by default, so enforcement keeps today's rule (new input + output). It turns on per team with counts_cache = true on the team's SETTINGS#TOKEN_LIMIT item, or for everyone with TOKEN_LIMIT_COUNTS_CACHE=true. GET /api/usage returns the total, the four parts, the cache hit rate, the per-feature split and the number the limit compares. No money in it. Saving the limit no longer wipes the item's other fields.
  • Reconciliation: a daily job compares each day's recorded tokens and cost per model with Anthropic's Usage and Cost Admin API, and logs usage_drift when they differ by more than 2%. It stays off until the coderhelm/<stage>/anthropic-admin-keys secret exists.
  • Cache rewrites: server-side clearing of old tool results now waits until it can clear at least 50k tokens, so the cached conversation isn't re-written on every turn. Client-side compaction on 4.x models runs every 6th turn instead of every turn. September's writes (84.5M against 76.4M reads) came from that per-turn compaction while runs were on 4.x models.
  • Backfill: scripts/usage_backfill.py recomputes this month's and last month's counters. It prints by default and writes only with --apply.

Changes

  • services/common/src/usage.rs, services/common/model_prices.json: accounting, prices, limit math, the exactly-once source check.
  • Worker: metered AnthropicClient, per-model TokenUsage, feature scope per queue message, team agent asks under agent_ask, passes/usage_reconcile.rs, per-pass cost on traces, cost kept on checkpoints, per-run cost kept after feedback rounds.
  • Gateway: budget check and /api/usage count all four parts behind the flag; plan chat counts per call.
  • Log analyzer: usage.py (the same fields and price table; a Rust test keeps the two tables identical).
  • Infra: daily usage_reconcile schedule, worker read access to the admin-key secret, log analyzer write access to analytics, gateway write access to analytics. The gateway was read-only before, so non-streaming plan chat usage had never been saved.

Verification

  • cargo fmt --all -- --check, cargo clippy --workspace --all-targets -- -D warnings, cargo test --workspace (220 + 108 + 246 passed), tsc --noEmit in infra, python3 -m unittest discover -s lambda/tests (14 passed).
  • New tests cover: the price table and per-part rates, the unknown-model fallback, Haiku long-prompt pricing, parsing cache writes by TTL, one call adding each counter exactly once, a run's usage reaching the run totals and the team counters once per response, limit math with all four parts and with the flag off and on, the usage body's total equal to the sum of its parts with no money in it, reconciliation parsing and the 2% check.
  • Backfill dry run against current data, read-only.

@nambok
nambok force-pushed the feat/usage-accounting branch from 88a78a8 to 731c2b1 Compare October 19, 2026 02:19
@nambok
nambok merged commit 1dc51a0 into main Oct 19, 2026
2 checks passed
@nambok
nambok deleted the feat/usage-accounting branch October 19, 2026 02:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant