From d53e2bc2b3874c8a580a023e6bb2acecbbbba272 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sun, 18 Oct 2026 21:54:09 -0400 Subject: [PATCH 1/2] fix: count every model call once with all four token parts, per-model prices, a token limit that can count cache tokens, and fewer cache rewrites --- infra/lib/api-stack.ts | 21 +- infra/lib/log-analyzer-stack.ts | 5 + infra/lib/worker-stack.ts | 11 + lambda/log-analyzer/handler.py | 15 +- lambda/log-analyzer/model_prices.json | 28 + lambda/log-analyzer/usage.py | 167 ++++ lambda/tests/test_log_analyzer.py | 54 + scripts/usage_backfill.py | 254 +++++ services/common/Cargo.toml | 2 +- services/common/model_prices.json | 28 + services/common/src/lib.rs | 2 + services/common/src/usage.rs | 938 ++++++++++++++++++ services/gateway/src/routes/api.rs | 159 ++- services/gateway/src/routes/github_webhook.rs | 36 +- services/gateway/src/routes/plans.rs | 189 +--- services/worker/src/agent/anthropic.rs | 124 ++- services/worker/src/agent/provider.rs | 24 +- services/worker/src/main.rs | 392 ++++---- services/worker/src/memory/mod.rs | 12 +- services/worker/src/models.rs | 155 ++- services/worker/src/passes/feedback.rs | 42 +- services/worker/src/passes/infra_analyze.rs | 6 +- services/worker/src/passes/mod.rs | 75 +- services/worker/src/passes/onboard.rs | 8 +- services/worker/src/passes/resume.rs | 40 +- services/worker/src/passes/review_pr.rs | 38 +- services/worker/src/passes/skills.rs | 16 +- services/worker/src/passes/usage_reconcile.rs | 476 +++++++++ 28 files changed, 2706 insertions(+), 611 deletions(-) create mode 100644 lambda/log-analyzer/model_prices.json create mode 100644 lambda/log-analyzer/usage.py create mode 100644 scripts/usage_backfill.py create mode 100644 services/common/model_prices.json create mode 100644 services/common/src/usage.rs create mode 100644 services/worker/src/passes/usage_reconcile.rs diff --git a/infra/lib/api-stack.ts b/infra/lib/api-stack.ts index f65a391a7..6edf90d79 100644 --- a/infra/lib/api-stack.ts +++ b/infra/lib/api-stack.ts @@ -280,6 +280,23 @@ export class ApiStack extends cdk.Stack { ], }); + // Usage reconciliation: daily 06:00 UTC, compares the previous day's + // recorded model usage with Anthropic's usage/cost report. The worker + // does nothing unless the coderhelm//anthropic-admin-keys secret + // exists, so this is safe to run before that secret is added. + new events.Rule(this, "UsageReconcileSchedule", { + ruleName: `${prefix}-usage-reconcile`, + description: "Compare recorded model usage with Anthropic's report (daily)", + schedule: events.Schedule.cron({ minute: "0", hour: "6" }), + targets: [ + new targets.SqsQueue(this.ticketQueue, { + message: events.RuleTargetInput.fromObject({ + type: "usage_reconcile", + }), + }), + ], + }); + // --- Secrets --- const secrets = secretsmanager.Secret.fromSecretNameV2( @@ -368,7 +385,9 @@ export class ApiStack extends cdk.Stack { resources: [`arn:aws:dynamodb:${this.region}:${this.account}:table/coderhelm-${props.stage}-runs/index/*`], }) ); - analyticsTable.grantReadData(this.gatewayFunction); + // Write: plan chat counts its model calls in the team's usage counters + // (read-only before, so those writes silently failed). + analyticsTable.grantReadWriteData(this.gatewayFunction); jiraEventsTable.grantReadWriteData(this.gatewayFunction); tracesTable.grantReadData(this.gatewayFunction); diff --git a/infra/lib/log-analyzer-stack.ts b/infra/lib/log-analyzer-stack.ts index 3fb1455a8..92d976ea9 100644 --- a/infra/lib/log-analyzer-stack.ts +++ b/infra/lib/log-analyzer-stack.ts @@ -62,6 +62,8 @@ export class LogAnalyzerStack extends cdk.Stack { environment: { AWS_INSIGHTS_TABLE_NAME: props.awsInsightsTable.tableName, SETTINGS_TABLE_NAME: props.settingsTable.tableName, + // Team usage counters: every analysis call is counted (tokens + cost). + ANALYTICS_TABLE_NAME: `${prefix}-analytics`, MODEL_ID: "claude-sonnet-5-5", CODERHELM_ACCOUNT_ID: this.account, LOOKBACK_HOURS: "6", @@ -72,6 +74,9 @@ export class LogAnalyzerStack extends cdk.Stack { // DynamoDB permissions props.awsInsightsTable.grantReadWriteData(analyzerFunction); props.settingsTable.grantReadData(analyzerFunction); + // Decoupled by name (like the worker) to avoid a cross-stack export. + dynamodb.TableV2.fromTableName(this, "AnalyticsTableRef", `${prefix}-analytics`) + .grantWriteData(analyzerFunction); // STS AssumeRole — the analyzer needs to assume roles in customer accounts analyzerFunction.addToRolePolicy( diff --git a/infra/lib/worker-stack.ts b/infra/lib/worker-stack.ts index d834f1428..222cde6b4 100644 --- a/infra/lib/worker-stack.ts +++ b/infra/lib/worker-stack.ts @@ -156,6 +156,17 @@ export class WorkerStack extends cdk.Stack { props.eventsTable.grantReadWriteData(this.workerFunction); props.bucket.grantReadWrite(this.workerFunction); secrets.grantRead(this.workerFunction); + // Usage reconciliation reads Anthropic Admin API keys from this secret + // (optional: reconciliation is off until it exists). Secrets Manager adds + // a 6-character suffix to secret ARNs, hence the wildcard. + this.workerFunction.addToRolePolicy( + new iam.PolicyStatement({ + actions: ["secretsmanager:GetSecretValue"], + resources: [ + `arn:aws:secretsmanager:${this.region}:${this.account}:secret:coderhelm/${props.stage}/anthropic-admin-keys-??????`, + ], + }) + ); // Bedrock: converse + invoke model this.workerFunction.addToRolePolicy( diff --git a/lambda/log-analyzer/handler.py b/lambda/log-analyzer/handler.py index 208edcfdb..25bf8afce 100644 --- a/lambda/log-analyzer/handler.py +++ b/lambda/log-analyzer/handler.py @@ -23,6 +23,8 @@ import boto3 from botocore.exceptions import ClientError +import usage + logger = logging.getLogger() logger.setLevel(logging.INFO) @@ -34,8 +36,11 @@ DASHBOARD_URL = os.environ.get("DASHBOARD_URL", "https://app.coderhelm.com") ANTHROPIC_API_URL = "https://api.anthropic.com/v1/messages" ANTHROPIC_VERSION = "2023-06-01" +# Team usage counters (empty: usage isn't counted). +ANALYTICS_TABLE = os.environ.get("ANALYTICS_TABLE_NAME", "") dynamodb = boto3.resource("dynamodb") +dynamodb_client = boto3.client("dynamodb") aws_insights_table = dynamodb.Table(AWS_INSIGHTS_TABLE) settings_table = dynamodb.Table(SETTINGS_TABLE) sts_client = boto3.client("sts") @@ -373,7 +378,7 @@ def analyze_connection(conn): new_recs.append(advisory_rec) # Send to Anthropic for analysis - recommendations = analyze_with_anthropic(all_results, account_id, api_key, existing) + recommendations = analyze_with_anthropic(all_results, account_id, api_key, existing, team_id=team_id) # None = the analysis failed: we can't tell "no issues" from "API error", # so nothing is resolved. @@ -518,7 +523,7 @@ def parse_recommendations(output_text): return [r for r in recs if isinstance(r, dict)][:10] -def analyze_with_anthropic(query_results, account_id, api_key, existing=None): +def analyze_with_anthropic(query_results, account_id, api_key, existing=None, team_id=None): """Send log error summaries to Anthropic Claude for analysis.""" # Scrub any secrets/tokens from the data before sending to AI scrubbed_results = scrub_query_results(query_results) @@ -604,6 +609,12 @@ def analyze_with_anthropic(query_results, account_id, api_key, existing=None): with urlopen(req, timeout=120) as resp: response_data = json.loads(resp.read().decode("utf-8")) + # Count the call once in the team's usage counters (tokens + cost). + usage.record_usage( + dynamodb_client, ANALYTICS_TABLE, team_id, usage.FEATURE_LOG_ANALYSIS, + MODEL_ID, response_data.get("usage"), + ) + recommendations = parse_recommendations(response_text(response_data)) if recommendations is None: logger.error("Anthropic response was not a JSON array") diff --git a/lambda/log-analyzer/model_prices.json b/lambda/log-analyzer/model_prices.json new file mode 100644 index 000000000..bcbee64df --- /dev/null +++ b/lambda/log-analyzer/model_prices.json @@ -0,0 +1,28 @@ +{ + "source": "https://platform.claude.com/docs/en/about-claude/pricing", + "checked": "2026-10-18", + "unit": "USD per million tokens", + "models": { + "claude-fable-5-1": {"input": 10.0, "output": 50.0, "cache_read": 0.25, "cache_write_5m": 12.5, "cache_write_1h": 20.0}, + "claude-mythos-5-1": {"input": 10.0, "output": 50.0, "cache_read": 0.25, "cache_write_5m": 12.5, "cache_write_1h": 20.0}, + "claude-fable-5": {"input": 10.0, "output": 50.0, "cache_read": 1.0, "cache_write_5m": 12.5, "cache_write_1h": 20.0}, + "claude-mythos-5": {"input": 10.0, "output": 50.0, "cache_read": 1.0, "cache_write_5m": 12.5, "cache_write_1h": 20.0}, + "claude-opus-5-5": {"input": 4.0, "output": 20.0, "cache_read": 0.20, "cache_write_5m": 5.0, "cache_write_1h": 8.0}, + "claude-opus-5": {"input": 5.0, "output": 25.0, "cache_read": 0.50, "cache_write_5m": 6.25, "cache_write_1h": 10.0}, + "claude-opus-4-8": {"input": 5.0, "output": 25.0, "cache_read": 0.50, "cache_write_5m": 6.25, "cache_write_1h": 10.0}, + "claude-opus-4-7": {"input": 5.0, "output": 25.0, "cache_read": 0.50, "cache_write_5m": 6.25, "cache_write_1h": 10.0}, + "claude-opus-4-6": {"input": 5.0, "output": 25.0, "cache_read": 0.50, "cache_write_5m": 6.25, "cache_write_1h": 10.0}, + "claude-opus-4-5": {"input": 5.0, "output": 25.0, "cache_read": 0.50, "cache_write_5m": 6.25, "cache_write_1h": 10.0}, + "claude-opus-4-1": {"input": 15.0, "output": 75.0, "cache_read": 1.50, "cache_write_5m": 18.75, "cache_write_1h": 30.0}, + "claude-opus-4": {"input": 15.0, "output": 75.0, "cache_read": 1.50, "cache_write_5m": 18.75, "cache_write_1h": 30.0}, + "claude-sonnet-5-5": {"input": 2.0, "output": 10.0, "cache_read": 0.10, "cache_write_5m": 2.5, "cache_write_1h": 4.0}, + "claude-sonnet-5": {"input": 2.0, "output": 10.0, "cache_read": 0.20, "cache_write_5m": 2.5, "cache_write_1h": 4.0}, + "claude-sonnet-4-6": {"input": 3.0, "output": 15.0, "cache_read": 0.30, "cache_write_5m": 3.75, "cache_write_1h": 6.0}, + "claude-sonnet-4-5": {"input": 3.0, "output": 15.0, "cache_read": 0.30, "cache_write_5m": 3.75, "cache_write_1h": 6.0}, + "claude-sonnet-4": {"input": 3.0, "output": 15.0, "cache_read": 0.30, "cache_write_5m": 3.75, "cache_write_1h": 6.0}, + "claude-haiku-5-5": {"input": 0.10, "output": 0.50, "cache_read": 0.01, "cache_write_5m": 0.125, "cache_write_1h": 0.20, + "long_prompt": {"over_tokens": 100000, "input": 0.50, "output": 2.50, "cache_read": 0.05, "cache_write_5m": 0.625, "cache_write_1h": 1.0}}, + "claude-haiku-4-5": {"input": 1.0, "output": 5.0, "cache_read": 0.10, "cache_write_5m": 1.25, "cache_write_1h": 2.0}, + "claude-haiku-3-5": {"input": 0.80, "output": 4.0, "cache_read": 0.08, "cache_write_5m": 1.0, "cache_write_1h": 1.6} + } +} diff --git a/lambda/log-analyzer/usage.py b/lambda/log-analyzer/usage.py new file mode 100644 index 000000000..19f02b31e --- /dev/null +++ b/lambda/log-analyzer/usage.py @@ -0,0 +1,167 @@ +"""Model usage accounting for the log analyzer. + +The Python twin of services/common/src/usage.rs: same price table +(model_prices.json, kept byte-identical by a Rust test), same analytics +attribute names, same periods. Each Anthropic response is ADDed once to the +team's month, all-time and day counters in one transaction. +""" + +import json +import logging +import os +from datetime import datetime, timezone + +logger = logging.getLogger() + +FEATURE_LOG_ANALYSIS = "log_analysis" + +with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "model_prices.json")) as _f: + PRICES = json.load(_f)["models"] + +_warned = set() + + +def normalize_model(model_id): + m = (model_id or "").strip().lower() + for sep in ("[", "@"): + if sep in m: + m = m[: m.index(sep)] + for p in ("global.", "us.", "eu.", "apac.", "jp.", "au."): + if m.startswith(p): + m = m[len(p):] + if m.startswith("anthropic."): + m = m[len("anthropic."):] + if "-v1" in m: + m = m[: m.index("-v1")] + if ":" in m: + m = m[: m.index(":")] + head, _, tail = m.rpartition("-") + if head and len(tail) == 8 and tail.isdigit(): + m = head + return m + + +def most_expensive_rates(): + return max(PRICES.values(), key=lambda r: r["input"] + r["output"]) + + +def rates_for(model_id): + m = normalize_model(model_id) + if m in PRICES: + return PRICES[m], True + if m not in _warned: + _warned.add(m) + logger.warning(f"Model {model_id} missing from the price table; costing it at the most expensive rate") + return most_expensive_rates(), False + + +def call_usage(usage, ttl="5m"): + """Four token parts from a Messages API usage object.""" + usage = usage or {} + n = lambda d, k: int((d or {}).get(k) or 0) + write_total = n(usage, "cache_creation_input_tokens") + cc = usage.get("cache_creation") + if isinstance(cc, dict): + w5, w1 = n(cc, "ephemeral_5m_input_tokens"), n(cc, "ephemeral_1h_input_tokens") + rest = max(write_total - w5 - w1, 0) + if ttl == "1h": + w1 += rest + else: + w5 += rest + elif ttl == "1h": + w5, w1 = 0, write_total + else: + w5, w1 = write_total, 0 + return { + "uncached_input": n(usage, "input_tokens"), + "cache_read": n(usage, "cache_read_input_tokens"), + "cache_write_5m": w5, + "cache_write_1h": w1, + "output": n(usage, "output_tokens"), + } + + +def total_tokens(u): + return u["uncached_input"] + u["cache_read"] + u["cache_write_5m"] + u["cache_write_1h"] + u["output"] + + +def call_cost(model_id, u): + r, _ = rates_for(model_id) + prompt = u["uncached_input"] + u["cache_read"] + u["cache_write_5m"] + u["cache_write_1h"] + lp = r.get("long_prompt") + if lp and prompt > lp["over_tokens"]: + r = lp + return ( + u["uncached_input"] * r["input"] + + u["output"] * r["output"] + + u["cache_read"] * r["cache_read"] + + u["cache_write_5m"] * r["cache_write_5m"] + + u["cache_write_1h"] * r["cache_write_1h"] + ) / 1_000_000 + + +def _key_part(s): + k = "".join(c for c in (s or "").lower() if c.isascii() and (c.isalnum() or c in "-_.")) + return k or "unknown" + + +def add_expression(feature, model_id, u): + cost = "%.9f" % call_cost(model_id, u) + cw = u["cache_write_5m"] + u["cache_write_1h"] + adds = [ + ("total_tokens_in", u["uncached_input"]), + ("tokens_in_uncached", u["uncached_input"]), + ("cache_read_tokens", u["cache_read"]), + ("cache_write_tokens", cw), + ("cache_write_5m_tokens", u["cache_write_5m"]), + ("cache_write_1h_tokens", u["cache_write_1h"]), + ("total_tokens_out", u["output"]), + ("total_tokens", total_tokens(u)), + ("total_cost_usd", cost), + ("model_calls", 1), + ] + for prefix, key in (("model", _key_part(normalize_model(model_id))), ("feature", _key_part(feature))): + adds += [ + (f"{prefix}#{key}#tokens_in", u["uncached_input"]), + (f"{prefix}#{key}#cache_read", u["cache_read"]), + (f"{prefix}#{key}#cache_write", cw), + (f"{prefix}#{key}#tokens_out", u["output"]), + (f"{prefix}#{key}#cost_usd", cost), + (f"{prefix}#{key}#calls", 1), + ] + names, values, parts = {}, {}, [] + for i, (attr, v) in enumerate(adds): + names[f"#a{i}"] = attr + values[f":v{i}"] = {"N": str(v)} + parts.append(f"#a{i} :v{i}") + return "ADD " + ", ".join(parts), names, values + + +def periods(now=None): + now = now or datetime.now(timezone.utc) + return [now.strftime("%Y-%m"), "ALL_TIME", "DAY#" + now.strftime("%Y-%m-%d")] + + +def record_usage(client, table, team_id, feature, model_id, usage): + """ADD one response's usage to the team's counters. Never raises.""" + try: + u = call_usage(usage) + if not table or not team_id or total_tokens(u) == 0: + return + expr, names, values = add_expression(feature, model_id, u) + client.transact_write_items( + TransactItems=[ + { + "Update": { + "TableName": table, + "Key": {"team_id": {"S": team_id}, "period": {"S": p}}, + "UpdateExpression": expr, + "ExpressionAttributeNames": names, + "ExpressionAttributeValues": values, + } + } + for p in periods() + ] + ) + except Exception as e: # never fail the analysis over accounting + logger.warning(f"Couldn't record model usage for {team_id}: {e}") diff --git a/lambda/tests/test_log_analyzer.py b/lambda/tests/test_log_analyzer.py index fe55a5da8..205bd59f1 100644 --- a/lambda/tests/test_log_analyzer.py +++ b/lambda/tests/test_log_analyzer.py @@ -11,6 +11,7 @@ import unittest HANDLER = pathlib.Path(__file__).resolve().parents[1] / "log-analyzer" / "handler.py" +sys.path.insert(0, str(HANDLER.parent)) def load_handler(model_id): @@ -108,5 +109,58 @@ def test_card_orders_by_severity_and_caps(self): self.assertEqual(c["actions"][0]["url"], "https://app.example/settings/aws") +class UsageAccounting(unittest.TestCase): + def setUp(self): + import usage + self.u = usage + + def test_all_four_parts_priced_per_model(self): + u = self.u.call_usage({ + "input_tokens": 1_000_000, "output_tokens": 1_000_000, + "cache_read_input_tokens": 2_000_000, "cache_creation_input_tokens": 2_000_000, + "cache_creation": {"ephemeral_5m_input_tokens": 1_000_000, "ephemeral_1h_input_tokens": 1_000_000}, + }) + self.assertEqual(self.u.total_tokens(u), 6_000_000) + # Same numbers as the Rust test: Sonnet 5.5 = 2 + 0.2 + 2.5 + 4 + 10. + self.assertAlmostEqual(self.u.call_cost("claude-sonnet-5-5", u), 18.7, places=9) + self.assertAlmostEqual(self.u.call_cost("claude-opus-5-5", u), 37.4, places=9) + + def test_unknown_model_is_never_free(self): + u = self.u.call_usage({"input_tokens": 1000, "output_tokens": 1000}) + unknown = self.u.call_cost("claude-imaginary-9", u) + self.assertGreater(unknown, 0) + for m in self.u.PRICES: + self.assertGreaterEqual(unknown, self.u.call_cost(m, u)) + + def test_one_call_one_transaction_with_every_counter(self): + calls = [] + + class Client: + def transact_write_items(self, **kw): + calls.append(kw) + + self.u.record_usage(Client(), "t", "team1", "log_analysis", "claude-sonnet-5-5", + {"input_tokens": 5, "output_tokens": 7, "cache_read_input_tokens": 11}) + self.u.record_usage(Client(), "t", "team1", "log_analysis", "claude-sonnet-5-5", {}) # empty: skipped + self.assertEqual(len(calls), 1) + items = calls[0]["TransactItems"] + self.assertEqual(len(items), 3) # month, all time, day + upd = items[0]["Update"] + attrs = {upd["ExpressionAttributeNames"][k]: upd["ExpressionAttributeValues"][k.replace("#a", ":v")]["N"] + for k in upd["ExpressionAttributeNames"]} + self.assertEqual(attrs["total_tokens"], "23") + self.assertEqual(attrs["total_tokens_in"], "5") + self.assertEqual(attrs["cache_read_tokens"], "11") + self.assertEqual(attrs["feature#log_analysis#tokens_out"], "7") + self.assertEqual(attrs["model#claude-sonnet-5-5#calls"], "1") + + def test_accounting_errors_never_raise(self): + class Broken: + def transact_write_items(self, **kw): + raise RuntimeError("down") + + self.u.record_usage(Broken(), "t", "team1", "log_analysis", "claude-sonnet-5-5", {"input_tokens": 1}) + + if __name__ == "__main__": unittest.main() diff --git a/scripts/usage_backfill.py b/scripts/usage_backfill.py new file mode 100644 index 000000000..45208a347 --- /dev/null +++ b/scripts/usage_backfill.py @@ -0,0 +1,254 @@ +#!/usr/bin/env python3 +"""Recompute teams' monthly usage counters from the per-run records. + +Dry run by default: prints, per team and month, what the analytics item holds +now and what it should hold. Nothing is written unless --apply is given. + +What "should" is: + * tokens: per part, the larger of the old counter and the four parts summed + over the month's runs (runs table) and the reviews that stored their usage + (REVIEW# items), for runs created before --cutoff (the old counter holds + usage that never reached a run item, like plan chat; run items hold runs + whose completion never reached the counter), plus whatever per-call + accounting has counted since the cutoff (DAY# items, written per + model call from the deploy on); + * cost: each run priced at the correct per-model rates (model_prices.json): + passes with a trace (traces table, 30-day TTL) are priced at the model + that pass uses (implement: the team's heavy model; others: primary); + runs without traces at the heavy model (the upper bound; the primary-model + lower bound is printed next to it). Reviews use the heavy model. + * calls that never stored usage before per-call accounting (plan chat via + the API, team agent asks outside runs, onboarding, infra analysis, memory + extraction, log analysis) cannot be recovered; they are reported as such. + +Usage: + python3 scripts/usage_backfill.py # this month and last + python3 scripts/usage_backfill.py --months 2026-09,2026-10 --stage prod + python3 scripts/usage_backfill.py --cutoff 2026-10-18T22:00:00Z --apply + +Run --apply once, after the deploy, with --cutoff set to the deploy time. +""" + +import argparse +import json +import os +import sys +from collections import defaultdict +from datetime import datetime, timezone +from decimal import Decimal + +import boto3 +from boto3.dynamodb.conditions import Attr, Key + +HERE = os.path.dirname(os.path.abspath(__file__)) +PRICES = json.load(open(os.path.join(HERE, "..", "services", "common", "model_prices.json")))["models"] +HEAVY_PASSES = {"implement", "review_agent", "release_notes"} + +PARTS = ("tokens_in", "cache_read", "cache_write", "tokens_out") +# Until the 5.5 models shipped (PR #89, 2026-09-29) runs used these defaults. +LEGACY_HEAVY, LEGACY_PRIMARY = "claude-opus-4-8", "claude-sonnet-4-6" + + +def models_at(created_at, heavy, primary, legacy_before): + if created_at and created_at < legacy_before: + return LEGACY_HEAVY, LEGACY_PRIMARY + return heavy, primary + + +def rates(model): + m = (model or "").strip().lower() + return PRICES.get(m) or max(PRICES.values(), key=lambda r: r["input"] + r["output"]) + + +def cost(model, t): + r = rates(model) + return ( + t["tokens_in"] * r["input"] + + t["tokens_out"] * r["output"] + + t["cache_read"] * r["cache_read"] + + t["cache_write"] * r["cache_write_5m"] + ) / 1_000_000 + + +def blended_old(t): + """The old flat estimate: $10/M input, $50/M output, read 0.1x, write 1.25x.""" + return (t["tokens_in"] * 10 + t["tokens_out"] * 50 + t["cache_read"] * 1 + t["cache_write"] * 12.5) / 1_000_000 + + +def n(item, *keys): + for k in keys: + if k in item and item[k] is not None: + return int(Decimal(str(item[k]))) + return 0 + + +def tokens_of(item, names=("tokens_in", "cache_read_tokens", "cache_write_tokens", "tokens_out")): + return dict(zip(PARTS, (n(item, k) for k in names))) + + +def add(a, b): + for k in PARTS: + a[k] += b[k] + + +def zero(): + return {k: 0 for k in PARTS} + + +def scan_all(table, **kw): + out, start = [], None + while True: + if start: + kw["ExclusiveStartKey"] = start + r = table.scan(**kw) + out += r.get("Items", []) + start = r.get("LastEvaluatedKey") + if not start: + return out + + +def query_all(table, **kw): + out, start = [], None + while True: + if start: + kw["ExclusiveStartKey"] = start + r = table.query(**kw) + out += r.get("Items", []) + start = r.get("LastEvaluatedKey") + if not start: + return out + + +def main(): + ap = argparse.ArgumentParser() + now = datetime.now(timezone.utc) + last = (now.replace(day=1) - __import__("datetime").timedelta(days=1)).strftime("%Y-%m") + ap.add_argument("--months", default=f"{last},{now.strftime('%Y-%m')}") + ap.add_argument("--stage", default="prod") + ap.add_argument("--region", default="us-east-1") + ap.add_argument("--cutoff", default=now.strftime("%Y-%m-%dT%H:%M:%SZ"), + help="runs created before this come from run records; after it, from per-call counters") + ap.add_argument("--legacy-before", default="2026-09-29T19:00:00Z", + help="runs created before this used the 4.x defaults (opus-4-8 / sonnet-4-6)") + ap.add_argument("--apply", action="store_true", help="write the recomputed counters (default: print only)") + a = ap.parse_args() + months = [m.strip() for m in a.months.split(",") if m.strip()] + ddb = boto3.resource("dynamodb", region_name=a.region) + p = f"coderhelm-{a.stage}" + runs_t, an_t = ddb.Table(f"{p}-runs"), ddb.Table(f"{p}-analytics") + tr_t, st_t = ddb.Table(f"{p}-traces"), ddb.Table(f"{p}-settings") + + runs = scan_all( + runs_t, + ProjectionExpression="team_id, run_id, created_at, tokens_in, tokens_out, cache_read_tokens, cache_write_tokens, cost_usd", + FilterExpression=Attr("created_at").begins_with(months[0]) if len(months) == 1 else + Attr("created_at").gte(months[0]) & Attr("created_at").lt(months[-1] + "-99"), + ) + by_team = defaultdict(list) + for r in runs: + by_team[r["team_id"]].append(r) + + for team in sorted(by_team): + prov = st_t.get_item(Key={"pk": team, "sk": "SETTINGS#MODEL_PROVIDER"}).get("Item", {}) + heavy = prov.get("heavy_model") or "claude-opus-5-5" + primary = prov.get("primary_model") or "claude-sonnet-5-5" + traces = defaultdict(list) + for t in query_all(tr_t, KeyConditionExpression=Key("team_id").eq(team) & Key("sk").begins_with("RUN#")): + parts = t["sk"].split("#") + if len(parts) >= 4: + traces[parts[1]].append(t) + reviews = query_all(st_t, KeyConditionExpression=Key("pk").eq(team) & Key("sk").begins_with("REVIEW#"), + FilterExpression=Attr("tokens_in").exists()) + + for month in months: + item = an_t.get_item(Key={"team_id": team, "period": month}).get("Item", {}) + before = {"tokens": tokens_of(item, ("total_tokens_in", "cache_read_tokens", "cache_write_tokens", "total_tokens_out")), + "cost": float(item.get("total_cost_usd", 0))} + hist, run_cost_old, cost_est, cost_low, traced = zero(), 0.0, 0.0, 0.0, 0 + n_runs = 0 + for r in by_team[team]: + ca = r.get("created_at", "") + if not ca.startswith(month) or ca >= a.cutoff: + continue + n_runs += 1 + t = tokens_of(r) + add(hist, t) + run_cost_old += float(r.get("cost_usd", 0)) + h, pm = models_at(ca, heavy, primary, a.legacy_before) + tr = traces.get(r["run_id"]) + if tr: + traced += 1 + rest = dict(t) + for pss in tr: + pt = tokens_of(pss, ("input_tokens", "cache_read_tokens", "cache_write_tokens", "output_tokens")) + model = h if pss.get("pass") in HEAVY_PASSES else pm + cost_est += cost(model, pt) + for k in PARTS: + rest[k] = max(rest[k] - pt[k], 0) + cost_est += cost(pm, rest) # untraced remainder (feedback, CI fixes) + cost_low += cost(pm, t) + else: + cost_est += cost(h, t) + cost_low += cost(pm, t) + n_rev = 0 + for rv in reviews: + ca = rv.get("created_at", "") + if not ca.startswith(month) or ca >= a.cutoff: + continue + n_rev += 1 + t = tokens_of(rv) + add(hist, t) + h, pm = models_at(ca, heavy, primary, a.legacy_before) + cost_est += cost(h, t) + cost_low += cost(pm, t) + # Per-call accounting since the cutoff (DAY# items exist only from the deploy on). + live, live_cost = zero(), 0.0 + for d in range(1, 32): + day = f"{month}-{d:02d}" + if day < a.cutoff[:10]: + continue + di = an_t.get_item(Key={"team_id": team, "period": f"DAY#{day}"}).get("Item") + if di: + add(live, tokens_of(di, ("total_tokens_in", "cache_read_tokens", "cache_write_tokens", "total_tokens_out"))) + live_cost += float(di.get("total_cost_usd", 0)) + # The old counter also holds usage that never reached a run item + # (plan chat, cancelled runs, feedback rounds whose run item was + # later overwritten). Keep whichever is larger per part, and + # price that excess at the heavy model (plan chat's model). + excess = {k: max(before["tokens"][k] - hist[k], 0) for k in PARTS} + after = zero() + for k in PARTS: + after[k] = max(before["tokens"][k], hist[k]) + add(after, live) + h, pm = models_at(f"{month}-15", heavy, primary, a.legacy_before) + after_cost = cost_est + cost(h, excess) + live_cost + cost_low += cost(pm, excess) + tot = lambda t: sum(t.values()) + print(f"\n== {team} {month}: {n_runs} runs ({traced} with per-pass traces), {n_rev} reviews with usage; " + f"models heavy={heavy} primary={primary} (before {a.legacy_before}: {LEGACY_HEAVY}/{LEGACY_PRIMARY})") + print(f" {'':22}{'new input':>14}{'cache read':>14}{'cache write':>14}{'output':>14}{'total':>15}") + for label, t in (("before (counter)", before["tokens"]), ("runs + reviews", hist), + ("after (to write)", after)): + print(f" {label:22}" + "".join(f"{t[k]:>14,}" for k in PARTS) + f"{tot(t):>15,}") + print(f" cost before counter ${before['cost']:,.2f} | runs' stored (old blended) ${run_cost_old:,.2f}" + f" | old blended on these tokens ${blended_old(hist):,.2f}") + print(f" after: per-model ${after_cost:,.2f} (untraced runs at the heavy model; all at the primary model: ${cost_low + live_cost:,.2f})") + if a.apply: + an_t.update_item( + Key={"team_id": team, "period": month}, + UpdateExpression="SET total_tokens_in = :i, tokens_in_uncached = :i, cache_read_tokens = :r, " + "cache_write_tokens = :w, total_tokens_out = :o, total_tokens = :t, " + "total_cost_usd = :c, backfilled_at = :b", + ExpressionAttributeValues={ + ":i": after["tokens_in"], ":r": after["cache_read"], ":w": after["cache_write"], + ":o": after["tokens_out"], ":t": tot(after), ":c": Decimal(f"{after_cost:.6f}"), + ":b": now.isoformat(), + }, + ) + print(" written") + if not a.apply: + print("\n(dry run: nothing written; add --apply to write the 'after' rows)") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/services/common/Cargo.toml b/services/common/Cargo.toml index 0be83039f..c76bfe280 100644 --- a/services/common/Cargo.toml +++ b/services/common/Cargo.toml @@ -15,7 +15,7 @@ tracing = "0.1" # alert_notify: Teams cards for alerts serde_json = "1" reqwest = { version = "0.12", features = ["json", "rustls-tls"], default-features = false } -tokio = { version = "1", features = ["macros", "time", "net"] } +tokio = { version = "1", features = ["macros", "time", "net", "rt"] } # live: read-only lookups against a team's own systems graphql-parser = "0.4" url = "2" diff --git a/services/common/model_prices.json b/services/common/model_prices.json new file mode 100644 index 000000000..bcbee64df --- /dev/null +++ b/services/common/model_prices.json @@ -0,0 +1,28 @@ +{ + "source": "https://platform.claude.com/docs/en/about-claude/pricing", + "checked": "2026-10-18", + "unit": "USD per million tokens", + "models": { + "claude-fable-5-1": {"input": 10.0, "output": 50.0, "cache_read": 0.25, "cache_write_5m": 12.5, "cache_write_1h": 20.0}, + "claude-mythos-5-1": {"input": 10.0, "output": 50.0, "cache_read": 0.25, "cache_write_5m": 12.5, "cache_write_1h": 20.0}, + "claude-fable-5": {"input": 10.0, "output": 50.0, "cache_read": 1.0, "cache_write_5m": 12.5, "cache_write_1h": 20.0}, + "claude-mythos-5": {"input": 10.0, "output": 50.0, "cache_read": 1.0, "cache_write_5m": 12.5, "cache_write_1h": 20.0}, + "claude-opus-5-5": {"input": 4.0, "output": 20.0, "cache_read": 0.20, "cache_write_5m": 5.0, "cache_write_1h": 8.0}, + "claude-opus-5": {"input": 5.0, "output": 25.0, "cache_read": 0.50, "cache_write_5m": 6.25, "cache_write_1h": 10.0}, + "claude-opus-4-8": {"input": 5.0, "output": 25.0, "cache_read": 0.50, "cache_write_5m": 6.25, "cache_write_1h": 10.0}, + "claude-opus-4-7": {"input": 5.0, "output": 25.0, "cache_read": 0.50, "cache_write_5m": 6.25, "cache_write_1h": 10.0}, + "claude-opus-4-6": {"input": 5.0, "output": 25.0, "cache_read": 0.50, "cache_write_5m": 6.25, "cache_write_1h": 10.0}, + "claude-opus-4-5": {"input": 5.0, "output": 25.0, "cache_read": 0.50, "cache_write_5m": 6.25, "cache_write_1h": 10.0}, + "claude-opus-4-1": {"input": 15.0, "output": 75.0, "cache_read": 1.50, "cache_write_5m": 18.75, "cache_write_1h": 30.0}, + "claude-opus-4": {"input": 15.0, "output": 75.0, "cache_read": 1.50, "cache_write_5m": 18.75, "cache_write_1h": 30.0}, + "claude-sonnet-5-5": {"input": 2.0, "output": 10.0, "cache_read": 0.10, "cache_write_5m": 2.5, "cache_write_1h": 4.0}, + "claude-sonnet-5": {"input": 2.0, "output": 10.0, "cache_read": 0.20, "cache_write_5m": 2.5, "cache_write_1h": 4.0}, + "claude-sonnet-4-6": {"input": 3.0, "output": 15.0, "cache_read": 0.30, "cache_write_5m": 3.75, "cache_write_1h": 6.0}, + "claude-sonnet-4-5": {"input": 3.0, "output": 15.0, "cache_read": 0.30, "cache_write_5m": 3.75, "cache_write_1h": 6.0}, + "claude-sonnet-4": {"input": 3.0, "output": 15.0, "cache_read": 0.30, "cache_write_5m": 3.75, "cache_write_1h": 6.0}, + "claude-haiku-5-5": {"input": 0.10, "output": 0.50, "cache_read": 0.01, "cache_write_5m": 0.125, "cache_write_1h": 0.20, + "long_prompt": {"over_tokens": 100000, "input": 0.50, "output": 2.50, "cache_read": 0.05, "cache_write_5m": 0.625, "cache_write_1h": 1.0}}, + "claude-haiku-4-5": {"input": 1.0, "output": 5.0, "cache_read": 0.10, "cache_write_5m": 1.25, "cache_write_1h": 2.0}, + "claude-haiku-3-5": {"input": 0.80, "output": 4.0, "cache_read": 0.08, "cache_write_5m": 1.0, "cache_write_1h": 1.6} + } +} diff --git a/services/common/src/lib.rs b/services/common/src/lib.rs index ea22414ae..ef452e61c 100644 --- a/services/common/src/lib.rs +++ b/services/common/src/lib.rs @@ -27,6 +27,8 @@ pub mod review_stats; pub mod skills; /// Signed links that turn off one email for one person, without signing in. pub mod unsubscribe; +/// Model usage accounting: every model call is counted here, once. +pub mod usage; /// GitHub's per-request override for the installation-token format, sent on /// `POST /app/installations/{id}/access_tokens`. GitHub is moving installation diff --git a/services/common/src/usage.rs b/services/common/src/usage.rs new file mode 100644 index 000000000..fd73907fb --- /dev/null +++ b/services/common/src/usage.rs @@ -0,0 +1,938 @@ +//! Model usage accounting: the one path every model call goes through. +//! +//! Each Anthropic response carries four token counts: new (uncached) input, +//! input read from the prompt cache, input written to the cache (5-minute or +//! 1-hour), and output (thinking included, it is billed as output). [`record`] +//! ADDs one call's counts to the team's analytics counters: the month, all +//! time, and the day (the day is what the daily reconciliation compares with +//! Anthropic's own report). It is the ONLY writer of token and cost counters +//! on the analytics table; runs keep their own per-run totals on the run item. +//! +//! Prices live in `model_prices.json` (USD per million tokens, from Anthropic's +//! pricing page). They are internal: cost is stored and logged, never shown. + +use std::collections::{HashMap, HashSet}; +use std::sync::{Arc, Mutex, OnceLock}; + +use aws_sdk_dynamodb::types::{AttributeValue, TransactWriteItem, Update}; +use serde::Deserialize; +use serde_json::Value; +use tracing::warn; + +/// Where a model call came from. Breakdowns are keyed by these names. +pub mod feature { + /// Ticket runs: triage, plan, implement, self review, security, PR. + pub const RUN: &str = "run"; + /// Follow-up work on a run's PR (review comments, CI fixes, conflicts). + pub const FEEDBACK: &str = "feedback"; + /// PR reviews of people's pull requests. + pub const REVIEW: &str = "review"; + /// A question asked of a team agent (skills). + pub const AGENT_ASK: &str = "agent_ask"; + /// Syncing team agents' knowledge. + pub const SKILL_SYNC: &str = "skill_sync"; + /// Alert triage and alert runs. + pub const ALERT: &str = "alert"; + /// Repository onboarding. + pub const ONBOARD: &str = "onboard"; + /// Infrastructure analysis. + pub const INFRA: &str = "infra"; + /// Plan chat in the dashboard. + pub const CHAT: &str = "chat"; + /// Executing an approved plan's tasks. + pub const PLAN: &str = "plan"; + /// The scheduled log analyzer. + pub const LOG_ANALYSIS: &str = "log_analysis"; + /// Release notes. + pub const RELEASE_NOTES: &str = "release_notes"; + /// Test result classification. + pub const TESTS: &str = "tests"; + /// Live source descriptions and tool proposals. + pub const LIVE_SOURCES: &str = "live_sources"; + /// Learnings extracted into memory after a run. + pub const MEMORY: &str = "memory"; + /// A call made outside any known scope (still counted in every total). + pub const OTHER: &str = "other"; +} + +tokio::task_local! { + static FEATURE: &'static str; +} + +/// Run `fut` with every model call inside it attributed to `feature`. +pub async fn with_feature(feature: &'static str, fut: F) -> F::Output { + FEATURE.scope(feature, fut).await +} + +/// The feature of the current task, or [`feature::OTHER`]. +pub fn current_feature() -> &'static str { + FEATURE.try_with(|f| *f).unwrap_or(feature::OTHER) +} + +// ── Prices ────────────────────────────────────────────────────────────────── + +/// USD per million tokens for one model. +#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] +pub struct Rates { + pub input: f64, + pub output: f64, + pub cache_read: f64, + pub cache_write_5m: f64, + pub cache_write_1h: f64, + /// Higher prices for a request whose prompt (all input, cache included) + /// is over `over_tokens` (Haiku 5.5). + #[serde(default)] + pub long_prompt: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Deserialize)] +pub struct LongPrompt { + pub over_tokens: u64, + pub input: f64, + pub output: f64, + pub cache_read: f64, + pub cache_write_5m: f64, + pub cache_write_1h: f64, +} + +#[derive(Deserialize)] +struct PriceFile { + models: HashMap, +} + +/// The price table, shipped with the code. The log analyzer lambda carries a +/// byte-identical copy (a test keeps them equal). +pub const PRICE_TABLE_JSON: &str = include_str!("../model_prices.json"); + +fn prices() -> &'static HashMap { + static P: OnceLock> = OnceLock::new(); + P.get_or_init(|| { + serde_json::from_str::(PRICE_TABLE_JSON) + .map(|f| f.models) + .unwrap_or_default() + }) +} + +/// The canonical id of a model: lowercase, without a provider or region +/// prefix (`anthropic.`, `us.`), a context suffix (`[1m]`), a Bedrock version +/// (`-v1:0`) or a date (`-20250805`, `@20250805`). +pub fn normalize_model(model_id: &str) -> String { + let mut m = model_id.trim().to_ascii_lowercase(); + if let Some(i) = m.find('[') { + m.truncate(i); + } + if let Some(i) = m.find('@') { + m.truncate(i); + } + for p in ["global.", "us.", "eu.", "apac.", "jp.", "au."] { + if let Some(rest) = m.strip_prefix(p) { + m = rest.to_string(); + } + } + if let Some(rest) = m.strip_prefix("anthropic.") { + m = rest.to_string(); + } + if let Some(i) = m.find("-v1") { + m.truncate(i); + } + if let Some(i) = m.find(':') { + m.truncate(i); + } + // A trailing 8-digit date. + if let Some((head, tail)) = m.rsplit_once('-') { + if tail.len() == 8 && tail.chars().all(|c| c.is_ascii_digit()) { + m = head.to_string(); + } + } + m +} + +/// The most expensive known rates (used for a model the table doesn't know, +/// so an unknown model is never counted as free). +pub fn most_expensive_rates() -> Rates { + prices() + .values() + .copied() + .max_by(|a, b| { + (a.output + a.input) + .partial_cmp(&(b.output + b.input)) + .unwrap_or(std::cmp::Ordering::Equal) + }) + .unwrap_or(Rates { + input: 15.0, + output: 75.0, + cache_read: 1.5, + cache_write_5m: 18.75, + cache_write_1h: 30.0, + long_prompt: None, + }) +} + +/// Rates for a model, and whether the table knew it. An unknown model is +/// logged once per process and priced at [`most_expensive_rates`]. +pub fn rates_for(model_id: &str) -> (Rates, bool) { + let m = normalize_model(model_id); + if let Some(r) = prices().get(&m) { + return (*r, true); + } + static WARNED: OnceLock>> = OnceLock::new(); + let first = WARNED + .get_or_init(|| Mutex::new(HashSet::new())) + .lock() + .map(|mut s| s.insert(m.clone())) + .unwrap_or(false); + if first { + warn!( + model = %model_id, + "Model missing from the price table; costing it at the most expensive known rate" + ); + } + (most_expensive_rates(), false) +} + +// ── One call's usage ──────────────────────────────────────────────────────── + +/// The cache lifetime a request asked for. Used to split cache writes when a +/// response doesn't break them down itself. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum CacheTtl { + #[default] + FiveMinutes, + OneHour, +} + +/// Token counts of one model call. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct CallUsage { + /// `usage.input_tokens`: only the input that was neither read from nor + /// written to the cache. + pub uncached_input: u64, + pub cache_read: u64, + pub cache_write_5m: u64, + pub cache_write_1h: u64, + /// `usage.output_tokens`, thinking included. + pub output: u64, +} + +impl CallUsage { + /// Parse a Messages API `usage` object. Cache writes are split by + /// `cache_creation.ephemeral_{5m,1h}_input_tokens` when present, otherwise + /// all of `cache_creation_input_tokens` goes to `ttl`. + pub fn from_api(usage: &Value, ttl: CacheTtl) -> Self { + let n = |v: &Value, k: &str| v.get(k).and_then(|x| x.as_u64()).unwrap_or(0); + let write_total = n(usage, "cache_creation_input_tokens"); + let (w5, w1) = match usage.get("cache_creation").filter(|c| c.is_object()) { + Some(c) => { + let w5 = n(c, "ephemeral_5m_input_tokens"); + let w1 = n(c, "ephemeral_1h_input_tokens"); + // Trust the total if the breakdown misses part of it. + let rest = write_total.saturating_sub(w5 + w1); + match ttl { + CacheTtl::FiveMinutes => (w5 + rest, w1), + CacheTtl::OneHour => (w5, w1 + rest), + } + } + None => match ttl { + CacheTtl::FiveMinutes => (write_total, 0), + CacheTtl::OneHour => (0, write_total), + }, + }; + CallUsage { + uncached_input: n(usage, "input_tokens"), + cache_read: n(usage, "cache_read_input_tokens"), + cache_write_5m: w5, + cache_write_1h: w1, + output: n(usage, "output_tokens"), + } + } + + pub fn cache_write(&self) -> u64 { + self.cache_write_5m + self.cache_write_1h + } + + /// Every input token of the request, cached or not. + pub fn prompt_tokens(&self) -> u64 { + self.uncached_input + self.cache_read + self.cache_write() + } + + /// All four parts: what the token limit counts. + pub fn total(&self) -> u64 { + self.prompt_tokens() + self.output + } + + pub fn is_empty(&self) -> bool { + self.total() == 0 + } + + /// USD for this call on `model_id`. + pub fn cost_usd(&self, model_id: &str) -> f64 { + let (r, _) = rates_for(model_id); + let (input, output, read, w5, w1) = match r.long_prompt { + Some(lp) if self.prompt_tokens() > lp.over_tokens => ( + lp.input, + lp.output, + lp.cache_read, + lp.cache_write_5m, + lp.cache_write_1h, + ), + _ => ( + r.input, + r.output, + r.cache_read, + r.cache_write_5m, + r.cache_write_1h, + ), + }; + (self.uncached_input as f64 * input + + self.output as f64 * output + + self.cache_read as f64 * read + + self.cache_write_5m as f64 * w5 + + self.cache_write_1h as f64 * w1) + / 1_000_000.0 + } +} + +// ── Counters ──────────────────────────────────────────────────────────────── + +/// The analytics periods one call is added to. +pub fn periods(now: chrono::DateTime) -> [String; 3] { + [ + now.format("%Y-%m").to_string(), + "ALL_TIME".to_string(), + format!("DAY#{}", now.format("%Y-%m-%d")), + ] +} + +/// A breakdown key part: lowercase letters, digits, `-`, `_`, `.` only. +fn key_part(s: &str) -> String { + let k: String = s + .chars() + .map(|c| c.to_ascii_lowercase()) + .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.')) + .collect(); + if k.is_empty() { + "unknown".into() + } else { + k + } +} + +/// Attribute name of a per-model counter, e.g. `model#claude-opus-5-5#cache_read`. +pub fn model_attr(model_id: &str, field: &str) -> String { + format!("model#{}#{field}", key_part(&normalize_model(model_id))) +} + +/// Attribute name of a per-feature counter, e.g. `feature#review#tokens_out`. +pub fn feature_attr(feature: &str, field: &str) -> String { + format!("feature#{}#{field}", key_part(feature)) +} + +fn cost_n(v: f64) -> String { + format!("{v:.9}") +} + +/// The ADD expression for one call: every counter, its name map and values. +/// Pure, so the exact attributes and amounts are tested. +pub fn add_expression( + feature: &str, + model_id: &str, + call: &CallUsage, +) -> ( + String, + HashMap, + HashMap, +) { + let cost = call.cost_usd(model_id); + let mut adds: Vec<(String, String)> = vec![ + // Kept names (history and other readers): total_tokens_in is the + // UNCACHED input, as Anthropic's `input_tokens` always was. + ("total_tokens_in".into(), call.uncached_input.to_string()), + ("tokens_in_uncached".into(), call.uncached_input.to_string()), + ("cache_read_tokens".into(), call.cache_read.to_string()), + ("cache_write_tokens".into(), call.cache_write().to_string()), + ( + "cache_write_5m_tokens".into(), + call.cache_write_5m.to_string(), + ), + ( + "cache_write_1h_tokens".into(), + call.cache_write_1h.to_string(), + ), + ("total_tokens_out".into(), call.output.to_string()), + ("total_tokens".into(), call.total().to_string()), + ("total_cost_usd".into(), cost_n(cost)), + ("model_calls".into(), "1".into()), + ]; + for (name_of, key) in [ + (model_attr as fn(&str, &str) -> String, model_id), + (feature_attr as fn(&str, &str) -> String, feature), + ] { + adds.push((name_of(key, "tokens_in"), call.uncached_input.to_string())); + adds.push((name_of(key, "cache_read"), call.cache_read.to_string())); + adds.push((name_of(key, "cache_write"), call.cache_write().to_string())); + adds.push((name_of(key, "tokens_out"), call.output.to_string())); + adds.push((name_of(key, "cost_usd"), cost_n(cost))); + adds.push((name_of(key, "calls"), "1".into())); + } + let mut names = HashMap::new(); + let mut values = HashMap::new(); + let mut parts = Vec::new(); + for (i, (attr, n)) in adds.into_iter().enumerate() { + names.insert(format!("#a{i}"), attr); + values.insert(format!(":v{i}"), AttributeValue::N(n)); + parts.push(format!("#a{i} :v{i}")); + } + (format!("ADD {}", parts.join(", ")), names, values) +} + +/// Where usage is written. `Memory` collects calls (tests). +#[derive(Clone)] +pub enum UsageSink { + Dynamo { + dynamo: aws_sdk_dynamodb::Client, + table: String, + }, + Memory(Arc>>), +} + +#[derive(Debug, Clone, PartialEq)] +pub struct RecordedCall { + pub team_id: String, + pub feature: String, + pub model: String, + pub usage: CallUsage, +} + +/// A team's meter: what a model client holds so each response is counted. +#[derive(Clone)] +pub struct UsageMeter { + pub team_id: String, + pub sink: UsageSink, +} + +impl std::fmt::Debug for UsageMeter { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("UsageMeter") + .field("team_id", &self.team_id) + .finish_non_exhaustive() + } +} + +impl UsageMeter { + pub fn dynamo(dynamo: aws_sdk_dynamodb::Client, table: &str, team_id: &str) -> Self { + Self { + team_id: team_id.to_string(), + sink: UsageSink::Dynamo { + dynamo, + table: table.to_string(), + }, + } + } + + pub fn memory(team_id: &str) -> (Self, Arc>>) { + let calls = Arc::new(Mutex::new(Vec::new())); + ( + Self { + team_id: team_id.to_string(), + sink: UsageSink::Memory(calls.clone()), + }, + calls, + ) + } + + /// Count one call under the current task's feature. Never fails the + /// caller: a failed write is logged. + pub async fn record(&self, model_id: &str, call: &CallUsage) { + self.record_as(current_feature(), model_id, call).await + } + + pub async fn record_as(&self, feature: &str, model_id: &str, call: &CallUsage) { + if call.is_empty() || self.team_id.is_empty() { + return; + } + match &self.sink { + UsageSink::Memory(calls) => { + if let Ok(mut c) = calls.lock() { + c.push(RecordedCall { + team_id: self.team_id.clone(), + feature: feature.to_string(), + model: model_id.to_string(), + usage: *call, + }); + } + } + UsageSink::Dynamo { dynamo, table } => { + if let Err(e) = record(dynamo, table, &self.team_id, feature, model_id, call).await + { + warn!(team_id = %self.team_id, feature, model = model_id, error = %e, + tokens = call.total(), "Couldn't record model usage"); + } + } + } + } +} + +/// ADD one call to the team's month, all-time and day counters, atomically. +pub async fn record( + dynamo: &aws_sdk_dynamodb::Client, + table: &str, + team_id: &str, + feature: &str, + model_id: &str, + call: &CallUsage, +) -> Result<(), String> { + if call.is_empty() { + return Ok(()); + } + let (expr, names, values) = add_expression(feature, model_id, call); + let mut tx = dynamo.transact_write_items(); + for period in periods(chrono::Utc::now()) { + let update = Update::builder() + .table_name(table) + .key("team_id", AttributeValue::S(team_id.to_string())) + .key("period", AttributeValue::S(period)) + .update_expression(&expr) + .set_expression_attribute_names(Some(names.clone())) + .set_expression_attribute_values(Some(values.clone())) + .build() + .map_err(|e| e.to_string())?; + tx = tx.transact_items(TransactWriteItem::builder().update(update).build()); + } + tx.send().await.map_err(|e| format!("{e:?}"))?; + Ok(()) +} + +// ── Reading counters back ─────────────────────────────────────────────────── + +/// The four parts of a period's usage, read from an analytics item. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct UsageTotals { + pub tokens_in_uncached: u64, + pub cache_read: u64, + pub cache_write: u64, + pub tokens_out: u64, +} + +fn n_of(item: &HashMap, k: &str) -> u64 { + item.get(k) + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse::().ok()) + .map(|f| f.max(0.0) as u64) + .unwrap_or(0) +} + +impl UsageTotals { + pub fn from_item(item: Option<&HashMap>) -> Self { + let Some(i) = item else { + return Self::default(); + }; + Self { + tokens_in_uncached: n_of(i, "total_tokens_in"), + cache_read: n_of(i, "cache_read_tokens"), + cache_write: n_of(i, "cache_write_tokens"), + tokens_out: n_of(i, "total_tokens_out"), + } + } + + /// All four parts. Summed from the parts (not `total_tokens`) so periods + /// counted before `total_tokens` existed still add up. + pub fn total(&self) -> u64 { + self.tokens_in_uncached + self.cache_read + self.cache_write + self.tokens_out + } + + /// The old limit rule: new input + output only. + pub fn uncached_total(&self) -> u64 { + self.tokens_in_uncached + self.tokens_out + } + + /// Cache read ÷ (cache read + cache write + new input); 0 with no input. + pub fn cache_hit_rate(&self) -> f64 { + let denom = self.cache_read + self.cache_write + self.tokens_in_uncached; + if denom == 0 { + 0.0 + } else { + self.cache_read as f64 / denom as f64 + } + } + + /// What the token limit compares with the team's `max_tokens`. + pub fn counted(&self, counts_cache: bool) -> u64 { + if counts_cache { + self.total() + } else { + self.uncached_total() + } + } +} + +/// Per-feature totals (all four parts summed) from an analytics item, +/// largest first. +pub fn feature_totals( + item: Option<&HashMap>, +) -> Vec<(String, UsageTotals)> { + let Some(i) = item else { + return vec![]; + }; + let mut by: HashMap = HashMap::new(); + for (k, v) in i { + let Some(rest) = k.strip_prefix("feature#") else { + continue; + }; + let Some((f, field)) = rest.rsplit_once('#') else { + continue; + }; + let n = v + .as_n() + .ok() + .and_then(|n| n.parse::().ok()) + .unwrap_or(0.0) + .max(0.0) as u64; + let e = by.entry(f.to_string()).or_default(); + match field { + "tokens_in" => e.tokens_in_uncached += n, + "cache_read" => e.cache_read += n, + "cache_write" => e.cache_write += n, + "tokens_out" => e.tokens_out += n, + _ => {} + } + } + let mut out: Vec<_> = by.into_iter().filter(|(_, t)| t.total() > 0).collect(); + out.sort_by(|a, b| b.1.total().cmp(&a.1.total()).then(a.0.cmp(&b.0))); + out +} + +/// Whether the token limit counts cache tokens for a team: the team's +/// `counts_cache` on `SETTINGS#TOKEN_LIMIT` wins; otherwise the +/// `TOKEN_LIMIT_COUNTS_CACHE` env default (off unless "true"). +pub fn counts_cache_enabled(team_setting: Option, env_default: Option<&str>) -> bool { + team_setting.unwrap_or_else(|| { + env_default + .map(|v| v.trim().eq_ignore_ascii_case("true")) + .unwrap_or(false) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn price_table_parses_and_has_every_model_in_use() { + for m in [ + "claude-opus-5-5", + "claude-sonnet-5-5", + "claude-fable-5-1", + "claude-haiku-5-5", + "claude-opus-4-8", + "claude-sonnet-4-6", + "claude-haiku-4-5", + ] { + assert!(rates_for(m).1, "{m} missing from the price table"); + } + let (o, _) = rates_for("claude-opus-5-5"); + assert_eq!( + ( + o.input, + o.output, + o.cache_read, + o.cache_write_5m, + o.cache_write_1h + ), + (4.0, 20.0, 0.20, 5.0, 8.0) + ); + let (s, _) = rates_for("claude-sonnet-5-5"); + assert_eq!( + ( + s.input, + s.output, + s.cache_read, + s.cache_write_5m, + s.cache_write_1h + ), + (2.0, 10.0, 0.10, 2.5, 4.0) + ); + let (f, _) = rates_for("claude-fable-5-1"); + assert_eq!((f.input, f.output, f.cache_read), (10.0, 50.0, 0.25)); + } + + #[test] + fn writes_cost_more_than_input_and_reads_less() { + for (m, r) in prices() { + assert!(r.cache_write_5m > r.input, "{m}"); + assert!(r.cache_write_1h > r.cache_write_5m, "{m}"); + assert!(r.cache_read < r.input, "{m}"); + assert!(r.output > r.input, "{m}"); + } + } + + #[test] + fn model_ids_normalize() { + assert_eq!(normalize_model("claude-opus-5-5"), "claude-opus-5-5"); + assert_eq!(normalize_model("Claude-Opus-5-5[1m]"), "claude-opus-5-5"); + assert_eq!( + normalize_model("us.anthropic.claude-sonnet-4-6-v1:0"), + "claude-sonnet-4-6" + ); + assert_eq!( + normalize_model("claude-opus-4-1-20250805"), + "claude-opus-4-1" + ); + assert_eq!( + normalize_model("claude-opus-4-5@20251101"), + "claude-opus-4-5" + ); + assert_eq!( + normalize_model("anthropic.claude-haiku-4-5"), + "claude-haiku-4-5" + ); + } + + #[test] + fn unknown_model_costs_the_most_expensive_rate_never_zero() { + let (r, known) = rates_for("claude-imaginary-9"); + assert!(!known); + assert_eq!(r, most_expensive_rates()); + let call = CallUsage { + uncached_input: 1_000_000, + output: 1_000_000, + ..Default::default() + }; + let unknown = call.cost_usd("claude-imaginary-9"); + assert!(unknown > 0.0); + for m in prices().keys() { + assert!( + unknown >= call.cost_usd(m), + "{m} costs more than the fallback" + ); + } + } + + #[test] + fn cost_uses_each_part_at_its_own_rate() { + let call = CallUsage { + uncached_input: 1_000_000, + cache_read: 2_000_000, + cache_write_5m: 1_000_000, + cache_write_1h: 1_000_000, + output: 1_000_000, + }; + // Opus 5.5: 4 + 2×0.20 + 5 + 8 + 20 + assert!((call.cost_usd("claude-opus-5-5") - 37.4).abs() < 1e-9); + // Sonnet 5.5: 2 + 2×0.10 + 2.5 + 4 + 10 + assert!((call.cost_usd("claude-sonnet-5-5") - 18.7).abs() < 1e-9); + } + + #[test] + fn haiku_long_prompts_pay_the_higher_tier() { + let short = CallUsage { + uncached_input: 50_000, + output: 1_000, + ..Default::default() + }; + let long = CallUsage { + uncached_input: 50_000, + cache_read: 60_000, + output: 1_000, + ..Default::default() + }; + let s = short.cost_usd("claude-haiku-5-5"); + assert!((s - (50_000.0 * 0.10 + 1_000.0 * 0.50) / 1e6).abs() < 1e-12); + let l = long.cost_usd("claude-haiku-5-5"); + assert!((l - (50_000.0 * 0.50 + 60_000.0 * 0.05 + 1_000.0 * 2.50) / 1e6).abs() < 1e-12); + } + + #[test] + fn api_usage_parses_all_parts_and_the_ttl_split() { + let u = json!({ + "input_tokens": 12, "output_tokens": 300, + "cache_read_input_tokens": 5000, "cache_creation_input_tokens": 900, + "cache_creation": {"ephemeral_5m_input_tokens": 600, "ephemeral_1h_input_tokens": 300} + }); + let c = CallUsage::from_api(&u, CacheTtl::FiveMinutes); + assert_eq!( + c, + CallUsage { + uncached_input: 12, + cache_read: 5000, + cache_write_5m: 600, + cache_write_1h: 300, + output: 300 + } + ); + assert_eq!(c.total(), 12 + 5000 + 900 + 300); + // No breakdown: all writes take the request's TTL. + let u = json!({"input_tokens": 1, "output_tokens": 2, "cache_creation_input_tokens": 70}); + assert_eq!( + CallUsage::from_api(&u, CacheTtl::OneHour).cache_write_1h, + 70 + ); + assert_eq!( + CallUsage::from_api(&u, CacheTtl::FiveMinutes).cache_write_5m, + 70 + ); + } + + fn adds(feature: &str, model: &str, c: &CallUsage) -> HashMap { + let (expr, names, values) = add_expression(feature, model, c); + assert!(expr.starts_with("ADD ")); + names + .iter() + .map(|(ph, attr)| { + let v = values[&ph.replace("#a", ":v")].as_n().unwrap().clone(); + (attr.clone(), v) + }) + .collect() + } + + #[test] + fn one_call_adds_every_counter_once() { + let c = CallUsage { + uncached_input: 10, + cache_read: 1000, + cache_write_5m: 200, + cache_write_1h: 0, + output: 50, + }; + let a = adds("review", "claude-sonnet-5-5", &c); + assert_eq!(a["total_tokens_in"], "10"); + assert_eq!(a["tokens_in_uncached"], "10"); + assert_eq!(a["cache_read_tokens"], "1000"); + assert_eq!(a["cache_write_tokens"], "200"); + assert_eq!(a["total_tokens_out"], "50"); + assert_eq!(a["total_tokens"], "1260"); + assert_eq!(a["model_calls"], "1"); + assert_eq!(a["model#claude-sonnet-5-5#cache_read"], "1000"); + assert_eq!(a["feature#review#tokens_out"], "50"); + let cost: f64 = a["total_cost_usd"].parse().unwrap(); + assert!((cost - c.cost_usd("claude-sonnet-5-5")).abs() < 1e-9); + // Every attribute appears exactly once in the expression. + let (expr, names, _) = add_expression("review", "claude-sonnet-5-5", &c); + assert_eq!(expr.matches("#a").count(), names.len()); + } + + #[tokio::test] + async fn the_meter_records_under_the_scoped_feature() { + let (meter, calls) = UsageMeter::memory("t1"); + let c = CallUsage { + uncached_input: 1, + output: 1, + ..Default::default() + }; + meter.record("claude-opus-5-5", &c).await; + with_feature(feature::REVIEW, meter.record("claude-opus-5-5", &c)).await; + meter.record("claude-opus-5-5", &CallUsage::default()).await; // empty: skipped + let got = calls.lock().unwrap().clone(); + assert_eq!(got.len(), 2); + assert_eq!(got[0].feature, feature::OTHER); + assert_eq!(got[1].feature, feature::REVIEW); + } + + #[test] + fn limit_counts_all_four_parts_only_when_enabled() { + let mut item = HashMap::new(); + for (k, v) in [ + ("total_tokens_in", "120000"), + ("cache_read_tokens", "61400000"), + ("cache_write_tokens", "8800000"), + ("total_tokens_out", "1000000"), + ] { + item.insert(k.to_string(), AttributeValue::N(v.into())); + } + let t = UsageTotals::from_item(Some(&item)); + assert_eq!(t.total(), 120_000 + 61_400_000 + 8_800_000 + 1_000_000); + assert_eq!(t.counted(true), t.total()); + assert_eq!(t.counted(false), 1_120_000); + let rate = t.cache_hit_rate(); + assert!((rate - 61_400_000.0 / 70_320_000.0).abs() < 1e-12); + assert_eq!(UsageTotals::from_item(None).total(), 0); + assert_eq!(UsageTotals::default().cache_hit_rate(), 0.0); + } + + #[test] + fn the_flag_defaults_off_and_the_team_setting_wins() { + assert!(!counts_cache_enabled(None, None)); + assert!(!counts_cache_enabled(None, Some("false"))); + assert!(counts_cache_enabled(None, Some("TRUE"))); + assert!(counts_cache_enabled(Some(true), Some("false"))); + assert!(!counts_cache_enabled(Some(false), Some("true"))); + } + + #[test] + fn feature_totals_group_the_breakdown() { + let (_, names, values) = add_expression( + "review", + "claude-sonnet-5-5", + &CallUsage { + uncached_input: 1, + cache_read: 2, + cache_write_5m: 3, + cache_write_1h: 0, + output: 4, + }, + ); + let item: HashMap = names + .iter() + .map(|(ph, attr)| (attr.clone(), values[&ph.replace("#a", ":v")].clone())) + .collect(); + let f = feature_totals(Some(&item)); + assert_eq!(f.len(), 1); + assert_eq!(f[0].0, "review"); + assert_eq!(f[0].1.total(), 10); + } + + /// Exactly once: no service adds tokens or cost to the analytics counters + /// except through this module (runs keep per-run totals on the run item). + #[test] + fn nothing_else_adds_tokens_or_cost_to_the_team_counters() { + const COUNTERS: &[&str] = &[ + "total_tokens_in", + "total_tokens_out", + "cache_read_tokens", + "cache_write_tokens", + "total_cost_usd", + "review_cost_usd", + "total_tokens", + ]; + fn walk(dir: &std::path::Path, out: &mut Vec) { + for e in std::fs::read_dir(dir).unwrap().flatten() { + let p = e.path(); + if p.is_dir() { + walk(&p, out); + } else if p.extension().is_some_and(|x| x == "rs") { + out.push(p); + } + } + } + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(".."); + let mut files = vec![]; + for svc in ["worker/src", "gateway/src"] { + walk(&root.join(svc), &mut files); + } + assert!(files.len() > 20, "found the service sources"); + let mut offenders = vec![]; + for f in files { + let src = std::fs::read_to_string(&f).unwrap(); + for (i, _) in src.match_indices("\"ADD ") { + let rest = &src[i + 1..]; + let lit = &rest[..rest.find('"').unwrap_or(rest.len())]; + let words: Vec<&str> = lit + .split(|c: char| !(c.is_alphanumeric() || c == '_')) + .collect(); + if COUNTERS.iter().any(|c| words.contains(c)) { + offenders.push(format!("{}: {lit}", f.display())); + } + } + } + assert!(offenders.is_empty(), "counted twice: {offenders:#?}"); + } + + #[test] + fn the_log_analyzer_carries_the_same_price_table() { + assert_eq!( + PRICE_TABLE_JSON, + include_str!("../../../lambda/log-analyzer/model_prices.json"), + "copy services/common/model_prices.json to lambda/log-analyzer/" + ); + } +} diff --git a/services/gateway/src/routes/api.rs b/services/gateway/src/routes/api.rs index 4d070c0f5..f7fd9b5a5 100644 --- a/services/gateway/src/routes/api.rs +++ b/services/gateway/src/routes/api.rs @@ -2913,6 +2913,7 @@ pub async fn get_stats( .and_then(|v| v.as_n().ok()) .and_then(|n| n.parse().ok()) .unwrap_or(0); + let t = common::usage::UsageTotals::from_item(item); json!({ "total_runs": total, "completed": completed, @@ -2921,6 +2922,10 @@ pub async fn get_stats( "total_cost_usd": cost, "total_tokens_in": tokens_in, "total_tokens_out": tokens_out, + "cache_read_tokens": t.cache_read, + "cache_write_tokens": t.cache_write, + "total_tokens": t.total(), + "cache_hit_rate": t.cache_hit_rate(), "merge_rate": if total > 0 { completed as f64 / total as f64 } else { 0.0 }, }) }; @@ -2982,6 +2987,9 @@ pub async fn get_stats_history( "total_cost_usd": get_f("total_cost_usd"), "total_tokens_in": get_n("total_tokens_in"), "total_tokens_out": get_n("total_tokens_out"), + "cache_read_tokens": get_n("cache_read_tokens"), + "cache_write_tokens": get_n("cache_write_tokens"), + "total_tokens": common::usage::UsageTotals::from_item(item).total(), })); } @@ -3531,8 +3539,11 @@ pub async fn get_budget( .and_then(|v| v.as_n().ok()) .and_then(|n| n.parse::().ok()) .unwrap_or(0); // 0 = unlimited + let counts_cache = super::github_webhook::token_limit_counts_cache(result.item()); - Ok(Json(json!({ "max_tokens": max_tokens }))) + Ok(Json( + json!({ "max_tokens": max_tokens, "limit_counts_cache": counts_cache }), + )) } /// PUT /api/settings/budget — set monthly token limit. @@ -3544,14 +3555,16 @@ pub async fn update_budget( claims.require_role(3)?; // admin or owner let max_tokens = body["max_tokens"].as_u64().unwrap_or(0); + // An update, not a put: keeps the item's other settings (counts_cache). state .dynamo - .put_item() + .update_item() .table_name(&state.config.settings_table_name) - .item("pk", attr_s(&claims.team_id)) - .item("sk", attr_s("SETTINGS#TOKEN_LIMIT")) - .item( - "max_tokens", + .key("pk", attr_s(&claims.team_id)) + .key("sk", attr_s("SETTINGS#TOKEN_LIMIT")) + .update_expression("SET max_tokens = :m") + .expression_attribute_values( + ":m", aws_sdk_dynamodb::types::AttributeValue::N(max_tokens.to_string()), ) .send() @@ -3597,40 +3610,61 @@ pub async fn get_usage( StatusCode::INTERNAL_SERVER_ERROR })?; - let tokens_in: u64 = analytics - .item() - .and_then(|i| i.get("total_tokens_in")) - .and_then(|v| v.as_n().ok()) - .and_then(|n| n.parse().ok()) - .unwrap_or(0); - let tokens_out: u64 = analytics - .item() - .and_then(|i| i.get("total_tokens_out")) - .and_then(|v| v.as_n().ok()) - .and_then(|n| n.parse().ok()) - .unwrap_or(0); - let total_runs: u64 = analytics - .item() - .and_then(|i| i.get("total_runs")) - .and_then(|v| v.as_n().ok()) - .and_then(|n| n.parse().ok()) - .unwrap_or(0); - - let max_tokens: u64 = limit - .item() - .and_then(|i| i.get("max_tokens")) - .and_then(|v| v.as_n().ok()) - .and_then(|n| n.parse().ok()) - .unwrap_or(0); + let counts_cache = super::github_webhook::token_limit_counts_cache(limit.item()); + Ok(Json(usage_json( + &month, + analytics.item(), + limit.item(), + counts_cache, + ))) +} - Ok(Json(json!({ +/// The usage body: tokens only (no money). `total_tokens` is all four parts; +/// `counted_tokens` is what the limit compares with `max_tokens` today. +pub fn usage_json( + month: &str, + analytics: Option<&std::collections::HashMap>, + limit: Option<&std::collections::HashMap>, + counts_cache: bool, +) -> Value { + let n = |item: Option< + &std::collections::HashMap, + >, + k: &str| + -> u64 { + item.and_then(|i| i.get(k)) + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse().ok()) + .unwrap_or(0) + }; + let t = common::usage::UsageTotals::from_item(analytics); + let features: Vec = common::usage::feature_totals(analytics) + .into_iter() + .map(|(f, ft)| { + json!({ + "feature": f, + "total_tokens": ft.total(), + "tokens_in": ft.tokens_in_uncached, + "cache_read_tokens": ft.cache_read, + "cache_write_tokens": ft.cache_write, + "tokens_out": ft.tokens_out, + }) + }) + .collect(); + json!({ "month": month, - "total_tokens": tokens_in + tokens_out, - "tokens_in": tokens_in, - "tokens_out": tokens_out, - "total_runs": total_runs, - "max_tokens": max_tokens, - }))) + "total_tokens": t.total(), + "tokens_in": t.tokens_in_uncached, + "cache_read_tokens": t.cache_read, + "cache_write_tokens": t.cache_write, + "tokens_out": t.tokens_out, + "cache_hit_rate": t.cache_hit_rate(), + "counted_tokens": t.counted(counts_cache), + "limit_counts_cache": counts_cache, + "features": features, + "total_runs": n(analytics, "total_runs"), + "max_tokens": n(limit, "max_tokens"), + }) } /// GET /api/settings/workflow — get workflow preferences. @@ -4573,7 +4607,54 @@ pub async fn purge_dlq( #[cfg(test)] mod tests { - use super::{platform_admin_listed, reset_allowed}; + use super::{platform_admin_listed, reset_allowed, usage_json}; + + #[test] + fn usage_shows_all_four_parts_tokens_only() { + use aws_sdk_dynamodb::types::AttributeValue as A; + let call = common::usage::CallUsage { + uncached_input: 120_000, + cache_read: 61_400_000, + cache_write_5m: 8_800_000, + cache_write_1h: 0, + output: 1_000_000, + }; + let (_, names, values) = common::usage::add_expression("run", "claude-opus-5-5", &call); + let mut analytics: std::collections::HashMap = names + .iter() + .map(|(ph, a)| (a.clone(), values[&ph.replace("#a", ":v")].clone())) + .collect(); + analytics.insert("total_runs".into(), A::N("3".into())); + let mut limit = std::collections::HashMap::new(); + limit.insert("max_tokens".to_string(), A::N("200000000".into())); + + let off = usage_json("2026-10", Some(&analytics), Some(&limit), false); + let parts = [ + "tokens_in", + "cache_read_tokens", + "cache_write_tokens", + "tokens_out", + ]; + let sum: u64 = parts.iter().map(|k| off[k].as_u64().unwrap()).sum(); + assert_eq!(off["total_tokens"].as_u64().unwrap(), sum); + assert_eq!(sum, 71_320_000); + assert_eq!( + off["counted_tokens"], 1_120_000, + "old rule while the flag is off" + ); + assert_eq!(off["limit_counts_cache"], false); + assert_eq!(off["max_tokens"], 200_000_000u64); + assert_eq!(off["features"][0]["feature"], "run"); + assert_eq!(off["features"][0]["total_tokens"], 71_320_000u64); + let rate = off["cache_hit_rate"].as_f64().unwrap(); + assert!((rate - 61_400_000.0 / 70_320_000.0).abs() < 1e-9); + + let on = usage_json("2026-10", Some(&analytics), Some(&limit), true); + assert_eq!(on["counted_tokens"], on["total_tokens"]); + // No money on the usage view. + let text = on.to_string(); + assert!(!text.contains("cost") && !text.contains("usd"), "{text}"); + } #[test] fn only_listed_emails_are_platform_admins() { diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index 2f5acf4bd..86bcf91f7 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -2540,6 +2540,21 @@ fn attr_n(val: impl std::fmt::Display) -> aws_sdk_dynamodb::types::AttributeValu aws_sdk_dynamodb::types::AttributeValue::N(val.to_string()) } +/// Whether a team's token limit counts cache tokens: `counts_cache` on its +/// `SETTINGS#TOKEN_LIMIT` item, else the `TOKEN_LIMIT_COUNTS_CACHE` env default. +pub fn token_limit_counts_cache( + limit_item: Option<&std::collections::HashMap>, +) -> bool { + let team = limit_item + .and_then(|i| i.get("counts_cache")) + .and_then(|v| v.as_bool().ok()) + .copied(); + common::usage::counts_cache_enabled( + team, + std::env::var("TOKEN_LIMIT_COUNTS_CACHE").ok().as_deref(), + ) +} + /// Check whether this team has budget remaining. Returns Some(reason) if blocked. pub async fn check_run_budget(state: &AppState, team_id: &str) -> Option { // 1. Read configured token limit from settings @@ -2577,21 +2592,12 @@ pub async fn check_run_budget(state: &AppState, team_id: &str) -> Option .await .ok()?; - let tokens_in: u64 = analytics - .item() - .and_then(|i| i.get("total_tokens_in")) - .and_then(|v| v.as_n().ok()) - .and_then(|n| n.parse().ok()) - .unwrap_or(0); - - let tokens_out: u64 = analytics - .item() - .and_then(|i| i.get("total_tokens_out")) - .and_then(|v| v.as_n().ok()) - .and_then(|n| n.parse().ok()) - .unwrap_or(0); - - let total_tokens = tokens_in + tokens_out; + // All four parts (new input, cache read, cache write, output) when the + // team's limit counts cache tokens; the old rule (new input + output) + // until then. See common::usage::counts_cache_enabled. + let counts_cache = token_limit_counts_cache(limit.item()); + let totals = common::usage::UsageTotals::from_item(analytics.item()); + let total_tokens = totals.counted(counts_cache); if total_tokens >= max_tokens { let limit_label = if max_tokens >= 1_000_000 { diff --git a/services/gateway/src/routes/plans.rs b/services/gateway/src/routes/plans.rs index 3556fdab4..608ed9c4b 100644 --- a/services/gateway/src/routes/plans.rs +++ b/services/gateway/src/routes/plans.rs @@ -2425,10 +2425,6 @@ pub async fn plan_chat( // Agentic loop — up to 5 tool-use turns for plan chat (gateway has 30s timeout) let max_turns = 5; - let mut total_input_tokens: u64 = 0; - let mut total_output_tokens: u64 = 0; - let mut cache_read_tokens: u64 = 0; - let mut cache_write_tokens: u64 = 0; let mut mcp_servers_used: std::collections::HashSet = std::collections::HashSet::new(); let http = reqwest::Client::new(); @@ -2458,19 +2454,6 @@ pub async fn plan_chat( .await .map_err(|e| { error!("Anthropic request failed: {e}"); - let s = state.clone(); - let t = claims.team_id.clone(); - tokio::spawn(async move { - track_chat_tokens( - &s, - &t, - total_input_tokens, - total_output_tokens, - cache_read_tokens, - cache_write_tokens, - ) - .await; - }); StatusCode::BAD_GATEWAY })?; @@ -2478,46 +2461,17 @@ pub async fn plan_chat( let status = resp.status(); let body = resp.text().await.unwrap_or_default(); error!("Anthropic API error ({status}): {body}"); - let s = state.clone(); - let t = claims.team_id.clone(); - tokio::spawn(async move { - track_chat_tokens( - &s, - &t, - total_input_tokens, - total_output_tokens, - cache_read_tokens, - cache_write_tokens, - ) - .await; - }); return Err(StatusCode::BAD_GATEWAY); } let response: Value = resp.json().await.map_err(|e| { error!("Failed to parse Anthropic response: {e}"); - let s = state.clone(); - let t = claims.team_id.clone(); - tokio::spawn(async move { - track_chat_tokens( - &s, - &t, - total_input_tokens, - total_output_tokens, - cache_read_tokens, - cache_write_tokens, - ) - .await; - }); StatusCode::BAD_GATEWAY })?; - // Track token usage + // Count this call, once, as it happens. if let Some(usage) = response.get("usage") { - total_input_tokens += usage["input_tokens"].as_u64().unwrap_or(0); - total_output_tokens += usage["output_tokens"].as_u64().unwrap_or(0); - cache_read_tokens += usage["cache_read_input_tokens"].as_u64().unwrap_or(0); - cache_write_tokens += usage["cache_creation_input_tokens"].as_u64().unwrap_or(0); + count_chat_call(&state, &claims.team_id, &model_id, usage).await; } let content = response["content"].as_array().cloned().unwrap_or_default(); @@ -2547,21 +2501,6 @@ pub async fn plan_chat( .collect::>() .join(""); - { - let state_clone = state.clone(); - let team_id_clone = claims.team_id.clone(); - tokio::spawn(async move { - track_chat_tokens( - &state_clone, - &team_id_clone, - total_input_tokens, - total_output_tokens, - cache_read_tokens, - cache_write_tokens, - ) - .await; - }); - } let servers: Vec<&str> = mcp_servers_used.iter().map(|s| s.as_str()).collect(); return Ok(Json(json!({ "content": text, "mcp_servers": servers }))); } @@ -2639,21 +2578,6 @@ pub async fn plan_chat( }) .unwrap_or_default(); - { - let state_clone = state.clone(); - let team_id_clone = claims.team_id.clone(); - tokio::spawn(async move { - track_chat_tokens( - &state_clone, - &team_id_clone, - total_input_tokens, - total_output_tokens, - cache_read_tokens, - cache_write_tokens, - ) - .await; - }); - } let servers: Vec<&str> = mcp_servers_used.iter().map(|s| s.as_str()).collect(); Ok(Json(json!({ "content": text, "mcp_servers": servers }))) } @@ -2693,8 +2617,6 @@ async fn run_anthropic_stream( let max_turns = 5; let mut total_input_tokens: u64 = 0; let mut total_output_tokens: u64 = 0; - let mut cache_read_tokens: u64 = 0; - let mut cache_write_tokens: u64 = 0; info!( model = model_id, @@ -2744,15 +2666,6 @@ async fn run_anthropic_stream( json!({"message": format!("Anthropic API error: {status}")}), )) .await; - track_chat_tokens( - state, - team_id, - total_input_tokens, - total_output_tokens, - cache_read_tokens, - cache_write_tokens, - ) - .await; return; } Err(e) => { @@ -2763,15 +2676,6 @@ async fn run_anthropic_stream( json!({"message": format!("AI service error: {e}")}), )) .await; - track_chat_tokens( - state, - team_id, - total_input_tokens, - total_output_tokens, - cache_read_tokens, - cache_write_tokens, - ) - .await; return; } }; @@ -2790,6 +2694,8 @@ async fn run_anthropic_stream( let mut blocks: std::collections::BTreeMap = std::collections::BTreeMap::new(); let mut block_json: std::collections::HashMap = std::collections::HashMap::new(); + // This turn's usage: message_start's, updated by message_delta. + let mut turn_usage = json!({}); while let Some(chunk) = stream.next().await { let chunk = match chunk { @@ -2886,16 +2792,19 @@ async fn run_anthropic_stream( if let Some(sr) = event["delta"]["stop_reason"].as_str() { stop_reason = sr.to_string(); } - if let Some(u) = event.get("usage") { - total_output_tokens += u["output_tokens"].as_u64().unwrap_or(0); + // Counts here are cumulative for the message: take + // the latest value of each, never add them up. + if let Some(u) = event.get("usage").and_then(|u| u.as_object()) { + for (k, v) in u { + if !v.is_null() { + turn_usage[k] = v.clone(); + } + } } } Some("message_start") => { if let Some(u) = event.get("message").and_then(|m| m.get("usage")) { - total_input_tokens += u["input_tokens"].as_u64().unwrap_or(0); - cache_read_tokens += u["cache_read_input_tokens"].as_u64().unwrap_or(0); - cache_write_tokens += - u["cache_creation_input_tokens"].as_u64().unwrap_or(0); + turn_usage = u.clone(); } } _ => {} @@ -2903,6 +2812,11 @@ async fn run_anthropic_stream( } } + // Count this call, once, even if the stream broke off. + total_input_tokens += turn_usage["input_tokens"].as_u64().unwrap_or(0); + total_output_tokens += turn_usage["output_tokens"].as_u64().unwrap_or(0); + count_chat_call(state, team_id, model_id, &turn_usage).await; + // Assistant turn for conversation state: every block, in order, verbatim. let assistant_content: Vec = blocks.into_values().collect(); if stop_reason == "refusal" && assistant_text.is_empty() { @@ -2937,19 +2851,6 @@ async fn run_anthropic_stream( )) .await; let _ = tx.send(sse_event("done", json!({}))).await; - let state_c = state.clone(); - let tid = team_id.to_string(); - tokio::spawn(async move { - track_chat_tokens( - &state_c, - &tid, - total_input_tokens, - total_output_tokens, - cache_read_tokens, - cache_write_tokens, - ) - .await; - }); return; } @@ -3031,19 +2932,6 @@ async fn run_anthropic_stream( )) .await; let _ = tx.send(sse_event("done", json!({}))).await; - let state_c = state.clone(); - let tid = team_id.to_string(); - tokio::spawn(async move { - track_chat_tokens( - &state_c, - &tid, - total_input_tokens, - total_output_tokens, - cache_read_tokens, - cache_write_tokens, - ) - .await; - }); } #[allow(clippy::collapsible_match)] @@ -3229,31 +3117,22 @@ fn compact_tool_result_for_model(result: &Value) -> String { let truncated: String = s.chars().take(max_chars).collect(); format!("{truncated}… [truncated]") } -async fn track_chat_tokens( - state: &AppState, - team_id: &str, - input_tokens: u64, - output_tokens: u64, - cache_read_tokens: u64, - cache_write_tokens: u64, -) { - let month = chrono::Utc::now().format("%Y-%m").to_string(); - for period in &[month.as_str(), "ALL_TIME"] { - let _ = state - .dynamo - .update_item() - .table_name(&state.config.analytics_table_name) - .key("team_id", attr_s(team_id)) - .key("period", attr_s(period)) - .update_expression( - "ADD total_tokens_in :tin, total_tokens_out :tout, cache_read_tokens :cr, cache_write_tokens :cw", - ) - .expression_attribute_values(":tin", attr_n(input_tokens)) - .expression_attribute_values(":tout", attr_n(output_tokens)) - .expression_attribute_values(":cr", attr_n(cache_read_tokens)) - .expression_attribute_values(":cw", attr_n(cache_write_tokens)) - .send() - .await; + +/// Count one plan chat model call in the team's usage counters (all four +/// token parts, priced per model). Never fails the chat. +async fn count_chat_call(state: &AppState, team_id: &str, model_id: &str, usage: &Value) { + let call = common::usage::CallUsage::from_api(usage, common::usage::CacheTtl::FiveMinutes); + if let Err(e) = common::usage::record( + &state.dynamo, + &state.config.analytics_table_name, + team_id, + common::usage::feature::CHAT, + model_id, + &call, + ) + .await + { + warn!(team_id, error = %e, "Couldn't record plan chat usage"); } } diff --git a/services/worker/src/agent/anthropic.rs b/services/worker/src/agent/anthropic.rs index 4c3b59b46..e35c4bbb0 100644 --- a/services/worker/src/agent/anthropic.rs +++ b/services/worker/src/agent/anthropic.rs @@ -15,20 +15,37 @@ static ANTHROPIC_VERSION: &str = "2023-06-01"; pub struct AnthropicClient { http: Client, api_key: String, + /// Counts every response into the team's analytics counters. Required: + /// a client can't be built without saying where its usage goes. + meter: common::usage::UsageMeter, } impl AnthropicClient { - pub fn new(api_key: String) -> Self { + pub fn new(api_key: String, meter: common::usage::UsageMeter) -> Self { Self { http: Client::builder() .timeout(std::time::Duration::from_secs(300)) .build() .unwrap_or_else(|_| Client::new()), api_key, + meter, } } } +/// The one place a response's usage is counted: into the run's own totals +/// (`usage`) and, once, into the team's analytics counters (the meter). +async fn account( + client: &AnthropicClient, + model_id: &str, + api_usage: &ApiUsage, + usage: &mut TokenUsage, +) { + let call = api_usage.call(); + usage.add_call(model_id, &call); + client.meter.record(model_id, &call).await; +} + // --- Request/Response types --- #[derive(Serialize)] @@ -92,6 +109,29 @@ const BETA_THINKING_BINDING: &str = "thinking-binding-controls-2026-08-01"; const BETA_CONTEXT_MANAGEMENT: &str = "context-management-2025-06-27"; const BETA_FALLBACK_DEFAULT: &str = "server-side-fallback-2026-07-01"; +/// Tokens a server-side clear must remove before it happens at all. A clear +/// rewrites the cached conversation from the first cleared tool result on, so +/// with no minimum (the API default) every turn past the trigger cleared one +/// old result near the START of the history and re-wrote nearly the whole +/// context to the cache (1.25x input) instead of reading it (0.05x-0.1x). +const CLEAR_AT_LEAST_TOKENS: u64 = 50_000; +/// Input size at which old tool results start being cleared. +const CLEAR_TRIGGER_TOKENS: u64 = 120_000; +/// Most recent tool results always kept. +const CLEAR_KEEP_TOOL_USES: u64 = 4; + +/// Legacy models trim history client-side; they do it once every this many turns. +const LEGACY_COMPACT_EVERY_TURNS: usize = 6; + +fn clear_tool_uses_edit() -> Value { + json!({"edits": [{ + "type": "clear_tool_uses_20250919", + "trigger": {"type": "input_tokens", "value": CLEAR_TRIGGER_TOKENS}, + "keep": {"type": "tool_uses", "value": CLEAR_KEEP_TOOL_USES}, + "clear_at_least": {"type": "input_tokens", "value": CLEAR_AT_LEAST_TOKENS} + }]}) +} + /// Fill the model-family fields of a request. `effort` None → "high". fn apply_model_family(request: &mut MessagesRequest, effort: Option<&str>, tool_loop: bool) { if ModelFamily::of(&request.model) != ModelFamily::AlwaysThinking { @@ -105,7 +145,7 @@ fn apply_model_family(request: &mut MessagesRequest, effort: Option<&str>, tool_ })); request.output_config = Some(json!({"effort": effort.unwrap_or("high")})); if tool_loop { - request.context_management = Some(json!({"edits": [{"type": "clear_tool_uses_20250919"}]})); + request.context_management = Some(clear_tool_uses_edit()); } if supports_default_fallback(&request.model) { request.fallbacks = Some(json!("default")); @@ -228,12 +268,34 @@ impl MessagesResponse { #[derive(Deserialize, Debug)] struct ApiUsage { + /// Uncached input only. input_tokens: u64, + /// Thinking included (billed as output). output_tokens: u64, #[serde(default)] cache_creation_input_tokens: u64, #[serde(default)] cache_read_input_tokens: u64, + /// Cache writes by lifetime (`ephemeral_5m_input_tokens`, + /// `ephemeral_1h_input_tokens`), priced differently. + #[serde(default)] + cache_creation: Option, +} + +impl ApiUsage { + fn call(&self) -> common::usage::CallUsage { + let mut v = json!({ + "input_tokens": self.input_tokens, + "output_tokens": self.output_tokens, + "cache_creation_input_tokens": self.cache_creation_input_tokens, + "cache_read_input_tokens": self.cache_read_input_tokens, + }); + if let Some(c) = &self.cache_creation { + v["cache_creation"] = c.clone(); + } + // Every request this client sends caches with the 5-minute lifetime. + common::usage::CallUsage::from_api(&v, common::usage::CacheTtl::FiveMinutes) + } } #[derive(Deserialize, Debug)] @@ -287,12 +349,7 @@ pub async fn converse_simple( apply_model_family(&mut request, None, false); let resp = send_request(client, &request).await?; - usage.add( - resp.usage.input_tokens, - resp.usage.output_tokens, - resp.usage.cache_read_input_tokens, - resp.usage.cache_creation_input_tokens, - ); + account(client, model_id, &resp.usage, usage).await; if let Some(refusal) = resp.refusal() { return Err(refusal.into()); } @@ -449,12 +506,7 @@ pub async fn converse_tool_loop( let response = send_with_retry(client, &request, model_id).await?; // Track usage - usage.add( - response.usage.input_tokens, - response.usage.output_tokens, - response.usage.cache_read_input_tokens, - response.usage.cache_creation_input_tokens, - ); + account(client, model_id, &response.usage, usage).await; if let Some(refusal) = response.refusal() { return Err(refusal.into()); @@ -466,8 +518,11 @@ pub async fn converse_tool_loop( // Always-thinking models: history must stay append-only (an edit // invalidates every later thinking block), so the server clears old // tool results instead (`context_management` in apply_model_family). + // Batched: each compaction edits history and so re-writes the cache + // from the first edited block on. Compacting every turn re-wrote the + // last ~8 messages on every turn; every 6th turn writes them once. let keep_recent = 4; // keep last 4 turn-pairs (~8 messages) - if family == ModelFamily::Legacy { + if family == ModelFamily::Legacy && turns.is_multiple_of(LEGACY_COMPACT_EVERY_TURNS) { compact_messages(messages, keep_recent); } @@ -812,10 +867,12 @@ mod tests { "drop_block" ); assert_eq!(v["output_config"]["effort"], "high"); - assert_eq!( - v["context_management"]["edits"][0]["type"], - "clear_tool_uses_20250919" - ); + let edit = &v["context_management"]["edits"][0]; + assert_eq!(edit["type"], "clear_tool_uses_20250919"); + // Clears happen in large batches, so the cache isn't re-written every turn. + assert_eq!(edit["clear_at_least"]["type"], "input_tokens"); + assert!(edit["clear_at_least"]["value"].as_u64().unwrap() >= 20_000); + assert!(edit["trigger"]["value"].as_u64().unwrap() >= 100_000); assert_eq!(v["fallbacks"], "default"); assert!(v.get("temperature").is_none()); let betas = beta_header(&r); @@ -857,6 +914,35 @@ mod tests { assert!(resp.refusal().is_none()); } + #[tokio::test] + async fn each_response_reaches_the_run_and_the_team_counters_exactly_once() { + let (meter, calls) = common::usage::UsageMeter::memory("team-1"); + let client = AnthropicClient::new("k".into(), meter); + let mut usage = TokenUsage::default(); + let api: ApiUsage = serde_json::from_value(json!({ + "input_tokens": 7, "output_tokens": 300, + "cache_read_input_tokens": 9000, "cache_creation_input_tokens": 1200, + "cache_creation": {"ephemeral_5m_input_tokens": 1000, "ephemeral_1h_input_tokens": 200} + })) + .unwrap(); + common::usage::with_feature(common::usage::feature::RUN, async { + account(&client, "claude-opus-5-5", &api, &mut usage).await; + account(&client, "claude-sonnet-5-5", &api, &mut usage).await; + }) + .await; + let got = calls.lock().unwrap().clone(); + assert_eq!(got.len(), 2, "one team record per response"); + let team_total: u64 = got.iter().map(|c| c.usage.total()).sum(); + assert_eq!(team_total, usage.total_tokens()); + assert_eq!(usage.total_tokens(), 2 * (7 + 300 + 9000 + 1200)); + assert_eq!(usage.cache_write_1h_tokens, 400); + let team_cost: f64 = got.iter().map(|c| c.usage.cost_usd(&c.model)).sum(); + assert!((team_cost - usage.cost_usd).abs() < 1e-12); + assert!(got + .iter() + .all(|c| c.feature == "run" && c.team_id == "team-1")); + } + #[test] fn refusal_is_an_error_not_empty_text() { let resp: MessagesResponse = serde_json::from_value(json!({ diff --git a/services/worker/src/agent/provider.rs b/services/worker/src/agent/provider.rs index 56ee755eb..5c5b53742 100644 --- a/services/worker/src/agent/provider.rs +++ b/services/worker/src/agent/provider.rs @@ -15,6 +15,9 @@ pub struct ModelProvider { pub api_key: String, pub primary_model: String, pub heavy_model: String, + /// Counts this team's model calls (set by `load_for_team`). + #[serde(skip)] + pub meter: Option, } impl ModelProvider { @@ -66,10 +69,22 @@ impl ModelProvider { .unwrap_or_else(|| "claude-opus-5-5".to_string()); info!(team_id, "Loaded Anthropic provider"); + let analytics_table = std::env::var("ANALYTICS_TABLE_NAME").unwrap_or_default(); + if analytics_table.is_empty() { + tracing::warn!( + team_id, + "ANALYTICS_TABLE_NAME unset: model usage won't be counted" + ); + } Ok(Self { api_key, primary_model, heavy_model, + meter: Some(common::usage::UsageMeter::dynamo( + dynamo.clone(), + &analytics_table, + team_id, + )), }) } @@ -88,8 +103,13 @@ impl ModelProvider { &self.api_key } - fn client(&self) -> AnthropicClient { - AnthropicClient::new(self.api_key.clone()) + /// A client whose every response is counted for this team. + pub fn client(&self) -> AnthropicClient { + let meter = self.meter.clone().unwrap_or_else(|| { + tracing::warn!("Model provider without a usage meter; usage stays uncounted"); + common::usage::UsageMeter::memory("").0 + }); + AnthropicClient::new(self.api_key.clone(), meter) } } diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index 573410ef8..27171ae36 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -81,222 +81,232 @@ async fn handle_sqs(state: Arc, event: LambdaEvent) -> Re info!("Processing SQS message"); let message: models::WorkerMessage = serde_json::from_str(&body)?; + // Every model call made while handling this message is counted under + // the message's feature (spawned tasks fall back to "other"). + let feature = message.usage_feature(); + common::usage::with_feature(feature, handle_message(Arc::clone(&state), message)).await; + } + + Ok(()) +} - match message { - models::WorkerMessage::Ticket(msg) => { - info!(team_id = %msg.team_id, ticket_id = %msg.ticket_id, "Starting ticket run"); - if let Err(e) = passes::orchestrate_ticket(&state, msg).await { - error!("Ticket run failed: {e}"); - } +async fn handle_message(state: Arc, message: models::WorkerMessage) { + match message { + models::WorkerMessage::Ticket(msg) => { + info!(team_id = %msg.team_id, ticket_id = %msg.ticket_id, "Starting ticket run"); + if let Err(e) = passes::orchestrate_ticket(&state, msg).await { + error!("Ticket run failed: {e}"); } - models::WorkerMessage::Feedback(msg) => { - info!(team_id = %msg.team_id, run_id = %msg.run_id, "Processing feedback"); - let team_id = msg.team_id.clone(); - let run_id = msg.run_id.clone(); - if let Err(e) = passes::feedback::run(&state, msg).await { - error!("Feedback run failed: {e}"); - let now = chrono::Utc::now().to_rfc3339(); - let _ = state - .dynamo - .update_item() - .table_name(&state.config.runs_table_name) - .key( - "team_id", - aws_sdk_dynamodb::types::AttributeValue::S(team_id), - ) - .key( - "run_id", - aws_sdk_dynamodb::types::AttributeValue::S(run_id.clone()), - ) - .update_expression( - "SET #s = :s, #e = :e, status_run_id = :sri, updated_at = :t", - ) - .expression_attribute_names("#s", "status") - .expression_attribute_names("#e", "error") - .expression_attribute_values( - ":s", - aws_sdk_dynamodb::types::AttributeValue::S("failed".to_string()), - ) - .expression_attribute_values( - ":e", - aws_sdk_dynamodb::types::AttributeValue::S(format!("{e}")), - ) - .expression_attribute_values( - ":sri", - aws_sdk_dynamodb::types::AttributeValue::S(format!("failed#{run_id}")), - ) - .expression_attribute_values( - ":t", - aws_sdk_dynamodb::types::AttributeValue::S(now), - ) - .send() - .await; - } + } + models::WorkerMessage::Feedback(msg) => { + info!(team_id = %msg.team_id, run_id = %msg.run_id, "Processing feedback"); + let team_id = msg.team_id.clone(); + let run_id = msg.run_id.clone(); + if let Err(e) = passes::feedback::run(&state, msg).await { + error!("Feedback run failed: {e}"); + let now = chrono::Utc::now().to_rfc3339(); + let _ = state + .dynamo + .update_item() + .table_name(&state.config.runs_table_name) + .key( + "team_id", + aws_sdk_dynamodb::types::AttributeValue::S(team_id), + ) + .key( + "run_id", + aws_sdk_dynamodb::types::AttributeValue::S(run_id.clone()), + ) + .update_expression( + "SET #s = :s, #e = :e, status_run_id = :sri, updated_at = :t", + ) + .expression_attribute_names("#s", "status") + .expression_attribute_names("#e", "error") + .expression_attribute_values( + ":s", + aws_sdk_dynamodb::types::AttributeValue::S("failed".to_string()), + ) + .expression_attribute_values( + ":e", + aws_sdk_dynamodb::types::AttributeValue::S(format!("{e}")), + ) + .expression_attribute_values( + ":sri", + aws_sdk_dynamodb::types::AttributeValue::S(format!("failed#{run_id}")), + ) + .expression_attribute_values( + ":t", + aws_sdk_dynamodb::types::AttributeValue::S(now), + ) + .send() + .await; } - models::WorkerMessage::Onboard(msg) => { - info!(team_id = %msg.team_id, repos = msg.repos.len(), "Processing onboard"); - let mut usage = models::TokenUsage::default(); - if let Err(e) = passes::onboard::run(&state, msg, &mut usage).await { - error!("Onboard failed: {e}"); - } + } + models::WorkerMessage::Onboard(msg) => { + info!(team_id = %msg.team_id, repos = msg.repos.len(), "Processing onboard"); + let mut usage = models::TokenUsage::default(); + if let Err(e) = passes::onboard::run(&state, msg, &mut usage).await { + error!("Onboard failed: {e}"); } - models::WorkerMessage::MarkReady(msg) => { - info!(team_id = %msg.team_id, pr_number = msg.pr_number, "Marking PR ready"); - if let Err(e) = mark_pr_ready(&state, msg).await { - error!("Mark PR ready failed: {e}"); - } + } + models::WorkerMessage::MarkReady(msg) => { + info!(team_id = %msg.team_id, pr_number = msg.pr_number, "Marking PR ready"); + if let Err(e) = mark_pr_ready(&state, msg).await { + error!("Mark PR ready failed: {e}"); } - models::WorkerMessage::PlanExecute(msg) => { - info!(team_id = %msg.team_id, plan_id = %msg.plan_id, "Executing plan"); - if let Err(e) = passes::plan_execute::run(&state, msg).await { - error!("Plan execute failed: {e}"); - } + } + models::WorkerMessage::PlanExecute(msg) => { + info!(team_id = %msg.team_id, plan_id = %msg.plan_id, "Executing plan"); + if let Err(e) = passes::plan_execute::run(&state, msg).await { + error!("Plan execute failed: {e}"); } - models::WorkerMessage::PlanTaskContinue(msg) => { - info!(team_id = %msg.team_id, plan_id = %msg.plan_id, tasks = msg.tasks.len(), "Continuing plan tasks"); - if let Err(e) = passes::plan_execute::continue_tasks(&state, msg).await { - error!("Plan task continue failed: {e}"); - } + } + models::WorkerMessage::PlanTaskContinue(msg) => { + info!(team_id = %msg.team_id, plan_id = %msg.plan_id, tasks = msg.tasks.len(), "Continuing plan tasks"); + if let Err(e) = passes::plan_execute::continue_tasks(&state, msg).await { + error!("Plan task continue failed: {e}"); } - models::WorkerMessage::InfraAnalyze(msg) => { - info!(team_id = %msg.team_id, "Analyzing infrastructure"); - let team_id = msg.team_id.clone(); - let mut usage = models::TokenUsage::default(); - if let Err(e) = passes::infra_analyze::run(&state, msg, &mut usage).await { - error!("Infra analyze failed: {e}"); - // Store failed status so the dashboard can show the error - let now = chrono::Utc::now().to_rfc3339(); - let _ = state - .dynamo - .put_item() - .table_name(&state.config.infra_table_name) - .item("pk", aws_sdk_dynamodb::types::AttributeValue::S(team_id)) - .item( - "sk", - aws_sdk_dynamodb::types::AttributeValue::S( - "INFRA#analysis".to_string(), - ), - ) - .item( - "status", - aws_sdk_dynamodb::types::AttributeValue::S("failed".to_string()), - ) - .item( - "has_infra", - aws_sdk_dynamodb::types::AttributeValue::Bool(false), - ) - .item( - "error", - aws_sdk_dynamodb::types::AttributeValue::S(e.to_string()), - ) - .item( - "updated_at", - aws_sdk_dynamodb::types::AttributeValue::S(now), - ) - .send() - .await; - } + } + models::WorkerMessage::InfraAnalyze(msg) => { + info!(team_id = %msg.team_id, "Analyzing infrastructure"); + let team_id = msg.team_id.clone(); + let mut usage = models::TokenUsage::default(); + if let Err(e) = passes::infra_analyze::run(&state, msg, &mut usage).await { + error!("Infra analyze failed: {e}"); + // Store failed status so the dashboard can show the error + let now = chrono::Utc::now().to_rfc3339(); + let _ = state + .dynamo + .put_item() + .table_name(&state.config.infra_table_name) + .item("pk", aws_sdk_dynamodb::types::AttributeValue::S(team_id)) + .item( + "sk", + aws_sdk_dynamodb::types::AttributeValue::S("INFRA#analysis".to_string()), + ) + .item( + "status", + aws_sdk_dynamodb::types::AttributeValue::S("failed".to_string()), + ) + .item( + "has_infra", + aws_sdk_dynamodb::types::AttributeValue::Bool(false), + ) + .item( + "error", + aws_sdk_dynamodb::types::AttributeValue::S(e.to_string()), + ) + .item( + "updated_at", + aws_sdk_dynamodb::types::AttributeValue::S(now), + ) + .send() + .await; } - models::WorkerMessage::Resume(msg) => { - info!(team_id = %msg.team_id, run_id = %msg.run_id, "Resuming run from webhook event"); - if let Err(e) = passes::resume::run(&state, msg).await { - error!("Resume failed: {e:?}"); - } + } + models::WorkerMessage::Resume(msg) => { + info!(team_id = %msg.team_id, run_id = %msg.run_id, "Resuming run from webhook event"); + if let Err(e) = passes::resume::run(&state, msg).await { + error!("Resume failed: {e:?}"); } - models::WorkerMessage::Review(msg) => { - info!(team_id = %msg.team_id, repo = %format!("{}/{}", msg.repo_owner, msg.repo_name), pr = msg.pr_number, "Reviewing PR from label"); - if let Err(e) = passes::review_pr::run(&state, msg).await { - error!("Review failed: {e:?}"); - } + } + models::WorkerMessage::Review(msg) => { + info!(team_id = %msg.team_id, repo = %format!("{}/{}", msg.repo_owner, msg.repo_name), pr = msg.pr_number, "Reviewing PR from label"); + if let Err(e) = passes::review_pr::run(&state, msg).await { + error!("Review failed: {e:?}"); } - models::WorkerMessage::ReviewReminder => { - info!("Running review-reminder sweep"); - if let Err(e) = passes::review_reminder::run(&state).await { - error!("Review reminder sweep failed: {e:?}"); - } - if let Err(e) = passes::pr_outcomes::backfill(&state).await { - error!("Merged PR backfill failed: {e:?}"); - } - if let Err(e) = passes::skills::sweep(&state).await { - error!("Skill repository sweep failed: {e:?}"); - } + } + models::WorkerMessage::ReviewReminder => { + info!("Running review-reminder sweep"); + if let Err(e) = passes::review_reminder::run(&state).await { + error!("Review reminder sweep failed: {e:?}"); } - models::WorkerMessage::SkillSync(msg) => { - info!(team_id = %msg.team_id, repo = %msg.repo, force = msg.force, "Skill repository sync"); - if let Err(e) = passes::skills::sync(&state, msg).await { - error!("Skill sync failed: {e:?}"); - } + if let Err(e) = passes::pr_outcomes::backfill(&state).await { + error!("Merged PR backfill failed: {e:?}"); } - models::WorkerMessage::SkillAsk(msg) => { - info!(team_id = %msg.team_id, repo = %msg.repo, agent = %msg.path, "Admin trying a team agent"); - if let Err(e) = passes::skills::try_ask(&state, msg).await { - error!("Team agent try failed: {e:?}"); - } + if let Err(e) = passes::skills::sweep(&state).await { + error!("Skill repository sweep failed: {e:?}"); } - models::WorkerMessage::HealthCheck(msg) => { - info!(team_id = %msg.team_id, pr = msg.pr_number, attempt = msg.attempts, "Post-merge health check"); - if let Err(e) = passes::health_check::run(&state, msg).await { - error!("Health check failed: {e:?}"); - } + } + models::WorkerMessage::SkillSync(msg) => { + info!(team_id = %msg.team_id, repo = %msg.repo, force = msg.force, "Skill repository sync"); + if let Err(e) = passes::skills::sync(&state, msg).await { + error!("Skill sync failed: {e:?}"); } - models::WorkerMessage::AwaitMerge(msg) => { - info!(team_id = %msg.team_id, pr = msg.pr_number, attempt = msg.attempts, "Armed auto-merge check"); - if let Err(e) = passes::await_merge::run(&state, msg).await { - error!("Await-merge failed: {e:?}"); - } + } + models::WorkerMessage::SkillAsk(msg) => { + info!(team_id = %msg.team_id, repo = %msg.repo, agent = %msg.path, "Admin trying a team agent"); + if let Err(e) = passes::skills::try_ask(&state, msg).await { + error!("Team agent try failed: {e:?}"); } - models::WorkerMessage::ToolProposals(msg) => { - info!(team_id = %msg.team_id, repo = %format!("{}/{}", msg.repo_owner, msg.repo_name), files = msg.paths.len(), "Tool proposals from repo"); - if let Err(e) = passes::tool_proposals::run(&state, msg).await { - error!("Tool proposals failed: {e:?}"); - } + } + models::WorkerMessage::HealthCheck(msg) => { + info!(team_id = %msg.team_id, pr = msg.pr_number, attempt = msg.attempts, "Post-merge health check"); + if let Err(e) = passes::health_check::run(&state, msg).await { + error!("Health check failed: {e:?}"); } - models::WorkerMessage::TagSweep(msg) => { - info!(team_id = %msg.team_id, repo = %format!("{}/{}", msg.repo_owner, msg.repo_name), remaining_secs = msg.delay_remaining_secs, "Batched release-tag sweep"); - if let Err(e) = passes::review_actions::run_tag_sweep(&state, msg).await { - error!("Tag sweep failed: {e:?}"); - } + } + models::WorkerMessage::AwaitMerge(msg) => { + info!(team_id = %msg.team_id, pr = msg.pr_number, attempt = msg.attempts, "Armed auto-merge check"); + if let Err(e) = passes::await_merge::run(&state, msg).await { + error!("Await-merge failed: {e:?}"); } - models::WorkerMessage::ReleaseNotes(msg) => { - info!(team_id = %msg.team_id, repo = %format!("{}/{}", msg.repo_owner, msg.repo_name), tag = %msg.tag, resend = %msg.resend, "Release notes"); - if let Err(e) = passes::release_notes::run(&state, msg).await { - error!("Release notes failed: {e:?}"); - } + } + models::WorkerMessage::ToolProposals(msg) => { + info!(team_id = %msg.team_id, repo = %format!("{}/{}", msg.repo_owner, msg.repo_name), files = msg.paths.len(), "Tool proposals from repo"); + if let Err(e) = passes::tool_proposals::run(&state, msg).await { + error!("Tool proposals failed: {e:?}"); } - models::WorkerMessage::TestIngest(msg) => { - info!(team_id = %msg.team_id, repo = %format!("{}/{}", msg.repo_owner, msg.repo_name), run_id = msg.run_id, "Reading E2E results"); - if let Err(e) = passes::e2e::ingest(&state, msg).await { - error!("E2E ingest failed: {e:?}"); - } + } + models::WorkerMessage::TagSweep(msg) => { + info!(team_id = %msg.team_id, repo = %format!("{}/{}", msg.repo_owner, msg.repo_name), remaining_secs = msg.delay_remaining_secs, "Batched release-tag sweep"); + if let Err(e) = passes::review_actions::run_tag_sweep(&state, msg).await { + error!("Tag sweep failed: {e:?}"); } - models::WorkerMessage::TestAction(msg) => { - info!(team_id = %msg.team_id, repo = %msg.repo, action = %msg.action, "E2E action"); - if let Err(e) = passes::e2e::act(&state, msg).await { - error!("E2E action failed: {e:?}"); - } + } + models::WorkerMessage::ReleaseNotes(msg) => { + info!(team_id = %msg.team_id, repo = %format!("{}/{}", msg.repo_owner, msg.repo_name), tag = %msg.tag, resend = %msg.resend, "Release notes"); + if let Err(e) = passes::release_notes::run(&state, msg).await { + error!("Release notes failed: {e:?}"); } - models::WorkerMessage::WeeklySummary => { - info!("Weekly summary emails"); - if let Err(e) = passes::weekly_summary::run(&state).await { - error!("Weekly summary failed: {e:?}"); - } + } + models::WorkerMessage::TestIngest(msg) => { + info!(team_id = %msg.team_id, repo = %format!("{}/{}", msg.repo_owner, msg.repo_name), run_id = msg.run_id, "Reading E2E results"); + if let Err(e) = passes::e2e::ingest(&state, msg).await { + error!("E2E ingest failed: {e:?}"); } - models::WorkerMessage::WeeklySummaryTest(msg) => { - info!(team_id = %msg.team_id, "Weekly summary test email"); - if let Err(e) = passes::weekly_summary::run_test(&state, msg).await { - error!("Weekly summary test failed: {e:?}"); - } + } + models::WorkerMessage::TestAction(msg) => { + info!(team_id = %msg.team_id, repo = %msg.repo, action = %msg.action, "E2E action"); + if let Err(e) = passes::e2e::act(&state, msg).await { + error!("E2E action failed: {e:?}"); } - models::WorkerMessage::GraphIndex(msg) => { - info!(team_id = %msg.team_id, repo = %format!("{}/{}", msg.repo_owner, msg.repo_name), incremental = msg.changed_files.is_some(), "Code-graph index pass"); - if let Err(e) = passes::code_graph::run(&state, msg).await { - error!("Code-graph index failed: {e:?}"); - } + } + models::WorkerMessage::WeeklySummary => { + info!("Weekly summary emails"); + if let Err(e) = passes::weekly_summary::run(&state).await { + error!("Weekly summary failed: {e:?}"); + } + } + models::WorkerMessage::WeeklySummaryTest(msg) => { + info!(team_id = %msg.team_id, "Weekly summary test email"); + if let Err(e) = passes::weekly_summary::run_test(&state, msg).await { + error!("Weekly summary test failed: {e:?}"); + } + } + models::WorkerMessage::GraphIndex(msg) => { + info!(team_id = %msg.team_id, repo = %format!("{}/{}", msg.repo_owner, msg.repo_name), incremental = msg.changed_files.is_some(), "Code-graph index pass"); + if let Err(e) = passes::code_graph::run(&state, msg).await { + error!("Code-graph index failed: {e:?}"); + } + } + models::WorkerMessage::UsageReconcile(msg) => { + info!(day = %msg.day, "Usage reconciliation"); + if let Err(e) = passes::usage_reconcile::run(&state, msg).await { + error!("Usage reconciliation failed: {e}"); } } } - - Ok(()) } async fn mark_pr_ready( diff --git a/services/worker/src/memory/mod.rs b/services/worker/src/memory/mod.rs index 032a4678a..9bf24549f 100644 --- a/services/worker/src/memory/mod.rs +++ b/services/worker/src/memory/mod.rs @@ -292,10 +292,11 @@ impl AgentMemory { pub async fn extract_learnings_from_conversation( &mut self, conversation_json: &[serde_json::Value], - api_key: &str, - model_id: &str, + provider: &crate::agent::provider::ModelProvider, origin: &LearningOrigin, ) { + let api_key = provider.api_key(); + let model_id = provider.primary_model_id(); if conversation_json.is_empty() || api_key.is_empty() { return; } @@ -385,6 +386,13 @@ impl AgentMemory { return; } }; + // Count the call (after the run: the team's counters, not the run's). + if let (Some(meter), Some(u)) = (&provider.meter, body.get("usage")) { + let call = common::usage::CallUsage::from_api(u, common::usage::CacheTtl::FiveMinutes); + meter + .record_as(common::usage::feature::MEMORY, model_id, &call) + .await; + } // First TEXT block — thinking models lead with a `thinking` block. let text = body["content"] diff --git a/services/worker/src/models.rs b/services/worker/src/models.rs index 31a83a74a..68ac04fc8 100644 --- a/services/worker/src/models.rs +++ b/services/worker/src/models.rs @@ -182,6 +182,47 @@ pub enum WorkerMessage { /// One test weekly summary for a team, to one address only. #[serde(rename = "weekly_summary_test")] WeeklySummaryTest(crate::passes::weekly_summary::WeeklySummaryTestMessage), + /// Daily (EventBridge → SQS): compare our recorded usage with Anthropic's + /// usage and cost report. Off unless the admin-key secret exists. + #[serde(rename = "usage_reconcile")] + UsageReconcile(UsageReconcileMessage), +} + +#[derive(Serialize, Deserialize, Debug, Default)] +pub struct UsageReconcileMessage { + /// `YYYY-MM-DD` (UTC) to compare; empty = yesterday. + #[serde(default)] + pub day: String, +} + +impl WorkerMessage { + /// The usage feature every model call made while handling this message + /// is counted under (`common::usage::feature`). + pub fn usage_feature(&self) -> &'static str { + use common::usage::feature as f; + match self { + WorkerMessage::Ticket(t) if matches!(t.source, TicketSource::Alert) => f::ALERT, + WorkerMessage::Ticket(_) | WorkerMessage::Resume(_) | WorkerMessage::MarkReady(_) => { + f::RUN + } + WorkerMessage::Feedback(_) => f::FEEDBACK, + WorkerMessage::Onboard(_) => f::ONBOARD, + WorkerMessage::PlanExecute(_) | WorkerMessage::PlanTaskContinue(_) => f::PLAN, + WorkerMessage::InfraAnalyze(_) => f::INFRA, + WorkerMessage::Review(_) | WorkerMessage::ReviewReminder => f::REVIEW, + WorkerMessage::SkillSync(_) => f::SKILL_SYNC, + WorkerMessage::SkillAsk(_) => f::AGENT_ASK, + WorkerMessage::ReleaseNotes(_) | WorkerMessage::TagSweep(_) => f::RELEASE_NOTES, + WorkerMessage::TestIngest(_) | WorkerMessage::TestAction(_) => f::TESTS, + WorkerMessage::ToolProposals(_) => f::LIVE_SOURCES, + WorkerMessage::HealthCheck(_) + | WorkerMessage::AwaitMerge(_) + | WorkerMessage::GraphIndex(_) + | WorkerMessage::WeeklySummary + | WorkerMessage::WeeklySummaryTest(_) + | WorkerMessage::UsageReconcile(_) => f::OTHER, + } + } } /// A code-graph index job. `changed_files: None` ⇒ full index of the branch @@ -437,23 +478,50 @@ pub struct ReviewComment { pub is_context: bool, } -/// Token usage tracking with prompt cache metrics. +/// One run's (or one job's) token usage with prompt cache metrics. Per-run +/// totals only: the team's monthly counters are written per model call by +/// `common::usage` (never from this struct), so nothing is counted twice. #[derive(Debug, Default, Clone)] pub struct TokenUsage { + /// Uncached input (Anthropic `input_tokens`). pub input_tokens: u64, + /// Output, thinking included. pub output_tokens: u64, pub cache_read_tokens: u64, + /// All cache writes (5-minute + 1-hour). pub cache_write_tokens: u64, + /// The 1-hour part of `cache_write_tokens`. + pub cache_write_1h_tokens: u64, + /// USD, each call priced at its own model's rates. + pub cost_usd: f64, pub tool_calls: u64, pub tool_names: Vec, } impl TokenUsage { - pub fn add(&mut self, input: u64, output: u64, cache_read: u64, cache_write: u64) { - self.input_tokens += input; - self.output_tokens += output; - self.cache_read_tokens += cache_read; - self.cache_write_tokens += cache_write; + /// Add one model call's usage, priced at `model_id`'s rates. + pub fn add_call(&mut self, model_id: &str, call: &common::usage::CallUsage) { + self.input_tokens += call.uncached_input; + self.output_tokens += call.output; + self.cache_read_tokens += call.cache_read; + self.cache_write_tokens += call.cache_write(); + self.cache_write_1h_tokens += call.cache_write_1h; + self.cost_usd += call.cost_usd(model_id); + } + + /// Add another usage's tokens and cost (tool calls are not merged). + pub fn merge(&mut self, other: &TokenUsage) { + self.input_tokens += other.input_tokens; + self.output_tokens += other.output_tokens; + self.cache_read_tokens += other.cache_read_tokens; + self.cache_write_tokens += other.cache_write_tokens; + self.cache_write_1h_tokens += other.cache_write_1h_tokens; + self.cost_usd += other.cost_usd; + } + + /// All four parts. + pub fn total_tokens(&self) -> u64 { + self.input_tokens + self.output_tokens + self.cache_read_tokens + self.cache_write_tokens } pub fn record_tool_call(&mut self, name: &str, duration_ms: u64) { @@ -464,21 +532,34 @@ impl TokenUsage { let _ = duration_ms; // tracked for logging, not stored in cumulative } - /// Estimated cost using blended rates across Opus (implement) and Sonnet (other passes). - /// Actual Anthropic billing is model-specific; this is an approximation for display. - /// Blended: ~60% of input goes to Opus, ~40% to Sonnet (implement is the heaviest pass). + /// USD for this usage: the sum of each call at its own model's price. pub fn estimated_cost(&self) -> f64 { - // Blended input rate: weighted average of Opus ($15/M) and Sonnet ($3/M) - let input_rate = 10.0 / 1_000_000.0; - // Blended output rate: weighted average of Opus ($75/M) and Sonnet ($15/M) - let output_rate = 50.0 / 1_000_000.0; - - let input_cost = self.input_tokens as f64 * input_rate; - let output_cost = self.output_tokens as f64 * output_rate; - let cache_read_cost = self.cache_read_tokens as f64 * input_rate * 0.1; - let cache_write_cost = self.cache_write_tokens as f64 * input_rate * 1.25; + self.cost_usd + } - input_cost + output_cost + cache_read_cost + cache_write_cost + /// Rebuild a saved usage. Old checkpoints carry no cost: their tokens are + /// priced at `model_id`'s rates. + pub fn restored( + model_id: &str, + input: u64, + output: u64, + cache_read: u64, + cache_write: u64, + cost_usd: Option, + ) -> Self { + let call = common::usage::CallUsage { + uncached_input: input, + cache_read, + cache_write_5m: cache_write, + cache_write_1h: 0, + output, + }; + let mut u = TokenUsage::default(); + u.add_call(model_id, &call); + if let Some(c) = cost_usd { + u.cost_usd = c; + } + u } } @@ -588,12 +669,36 @@ mod tests { #[test] fn token_usage_cost() { let mut usage = TokenUsage::default(); - usage.add(1000, 500, 200, 100); - assert_eq!(usage.input_tokens, 1000); - assert_eq!(usage.output_tokens, 500); - assert_eq!(usage.cache_read_tokens, 200); - assert_eq!(usage.cache_write_tokens, 100); - assert!(usage.estimated_cost() > 0.0); + let call = common::usage::CallUsage { + uncached_input: 1000, + cache_read: 200, + cache_write_5m: 100, + cache_write_1h: 0, + output: 500, + }; + usage.add_call("claude-opus-5-5", &call); + usage.add_call("claude-sonnet-5-5", &call); + assert_eq!(usage.input_tokens, 2000); + assert_eq!(usage.output_tokens, 1000); + assert_eq!(usage.cache_read_tokens, 400); + assert_eq!(usage.cache_write_tokens, 200); + assert_eq!(usage.total_tokens(), 3600); + // Each call at its own model's price, not one blended rate. + let want = call.cost_usd("claude-opus-5-5") + call.cost_usd("claude-sonnet-5-5"); + assert!((usage.estimated_cost() - want).abs() < 1e-12); + let mut merged = TokenUsage::default(); + merged.merge(&usage); + assert_eq!(merged.total_tokens(), usage.total_tokens()); + assert!((merged.cost_usd - usage.cost_usd).abs() < 1e-12); + } + + #[test] + fn restored_usage_keeps_a_saved_cost_or_prices_the_tokens() { + let r = TokenUsage::restored("claude-opus-5-5", 10, 20, 30, 40, Some(1.5)); + assert_eq!(r.total_tokens(), 100); + assert_eq!(r.cost_usd, 1.5); + let r = TokenUsage::restored("claude-opus-5-5", 1_000_000, 0, 0, 0, None); + assert!((r.cost_usd - 4.0).abs() < 1e-9); } #[test] diff --git a/services/worker/src/passes/feedback.rs b/services/worker/src/passes/feedback.rs index ebd4c68c8..01594836f 100644 --- a/services/worker/src/passes/feedback.rs +++ b/services/worker/src/passes/feedback.rs @@ -668,6 +668,7 @@ Rules: "SET tokens_in = tokens_in + :ti, tokens_out = tokens_out + :to, \ cache_read_tokens = if_not_exists(cache_read_tokens, :zero) + :crt, \ cache_write_tokens = if_not_exists(cache_write_tokens, :zero) + :cwt, \ + cost_usd = if_not_exists(cost_usd, :zero) + :c, \ updated_at = :t, #s = :s, current_pass = :p, status_run_id = :sri, \ pass_history = list_append(if_not_exists(pass_history, :empty), :entry) \ REMOVE error_message, #err", @@ -699,6 +700,10 @@ Rules: ":zero", aws_sdk_dynamodb::types::AttributeValue::N("0".to_string()), ) + .expression_attribute_values( + ":c", + aws_sdk_dynamodb::types::AttributeValue::N(format!("{:.4}", usage.estimated_cost())), + ) .expression_attribute_values( ":t", aws_sdk_dynamodb::types::AttributeValue::S(now.clone()), @@ -737,41 +742,8 @@ Rules: .send() .await?; - // Update analytics counters (current month + all-time) - let month = chrono::Utc::now().format("%Y-%m").to_string(); - for period in &[month.as_str(), "ALL_TIME"] { - state - .dynamo - .update_item() - .table_name(&state.config.analytics_table_name) - .key( - "team_id", - aws_sdk_dynamodb::types::AttributeValue::S(msg.team_id.clone()), - ) - .key( - "period", - aws_sdk_dynamodb::types::AttributeValue::S(period.to_string()), - ) - .update_expression("ADD total_tokens_in :ti, total_tokens_out :to, cache_read_tokens :crt, cache_write_tokens :cwt") - .expression_attribute_values( - ":ti", - aws_sdk_dynamodb::types::AttributeValue::N(usage.input_tokens.to_string()), - ) - .expression_attribute_values( - ":to", - aws_sdk_dynamodb::types::AttributeValue::N(usage.output_tokens.to_string()), - ) - .expression_attribute_values( - ":crt", - aws_sdk_dynamodb::types::AttributeValue::N(usage.cache_read_tokens.to_string()), - ) - .expression_attribute_values( - ":cwt", - aws_sdk_dynamodb::types::AttributeValue::N(usage.cache_write_tokens.to_string()), - ) - .send() - .await?; - } + // The team's counters already have these tokens: each model call is + // counted as it happens (common::usage). // If code was pushed, schedule a delayed resume to watch for CI if code_pushed { diff --git a/services/worker/src/passes/infra_analyze.rs b/services/worker/src/passes/infra_analyze.rs index 99b6d0bd2..971746434 100644 --- a/services/worker/src/passes/infra_analyze.rs +++ b/services/worker/src/passes/infra_analyze.rs @@ -1,7 +1,7 @@ use aws_sdk_dynamodb::types::AttributeValue; use tracing::{info, warn}; -use crate::agent::anthropic::{self, AnthropicClient}; +use crate::agent::anthropic; use crate::agent::provider::ModelProvider; use crate::models::{InfraAnalyzeMessage, TokenUsage}; use crate::WorkerState; @@ -832,7 +832,7 @@ async fn call_anthropic( "Analyze this infrastructure code and generate the diagram and findings:\n\n{code_context}" ); - let client = AnthropicClient::new(provider.api_key().to_string()); + let client = provider.client(); anthropic::converse_simple(&client, provider.primary_model_id(), SYSTEM, &prompt, usage).await } @@ -853,7 +853,7 @@ async fn call_anthropic_retry( Use junctions for 3+ edges from one port." ); - let client = AnthropicClient::new(provider.api_key().to_string()); + let client = provider.client(); anthropic::converse_simple(&client, provider.primary_model_id(), SYSTEM, &prompt, usage).await } diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 1d7bc4838..5784dc558 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -672,6 +672,7 @@ pub mod syntax_check; mod test; pub mod tool_proposals; mod triage; +pub mod usage_reconcile; pub mod weekly_summary; pub mod write_guard; @@ -850,23 +851,8 @@ pub async fn orchestrate_ticket( .expression_attribute_values(":t", attr_s(&chrono::Utc::now().to_rfc3339())) .send() .await; - // Also update analytics for cancelled runs - let month = chrono::Utc::now().format("%Y-%m").to_string(); - for period in &[month.as_str(), "ALL_TIME"] { - let _ = state - .dynamo - .update_item() - .table_name(&state.config.analytics_table_name) - .key("team_id", attr_s(&msg.team_id)) - .key("period", attr_s(period)) - .update_expression("ADD total_tokens_in :ti, total_tokens_out :to, cache_read_tokens :crt, cache_write_tokens :cwt") - .expression_attribute_values(":ti", attr_n(usage.input_tokens)) - .expression_attribute_values(":to", attr_n(usage.output_tokens)) - .expression_attribute_values(":crt", attr_n(usage.cache_read_tokens)) - .expression_attribute_values(":cwt", attr_n(usage.cache_write_tokens)) - .send() - .await; - } + // The team's counters already have these tokens: each model + // call is counted as it happens (common::usage). } else { error!(run_id, error = %e, "Orchestration failed"); let checkpoint = load_checkpoint(state, &msg.team_id, &run_id).await; @@ -1562,17 +1548,8 @@ async fn run_passes( .table_name(&state.config.analytics_table_name) .key("team_id", attr_s(&msg.team_id)) .key("period", attr_s(period)) - .update_expression( - "ADD completed :one, total_cost_usd :cost, \ - total_tokens_in :ti, total_tokens_out :to, \ - cache_read_tokens :cr, cache_write_tokens :cw", - ) + .update_expression("ADD completed :one") .expression_attribute_values(":one", attr_n(1)) - .expression_attribute_values(":cost", attr_n(format!("{:.4}", cost))) - .expression_attribute_values(":ti", attr_n(usage.input_tokens)) - .expression_attribute_values(":to", attr_n(usage.output_tokens)) - .expression_attribute_values(":cr", attr_n(usage.cache_read_tokens)) - .expression_attribute_values(":cw", attr_n(usage.cache_write_tokens)) .send() .await; } @@ -1667,17 +1644,8 @@ async fn run_passes( .table_name(&state.config.analytics_table_name) .key("team_id", attr_s(&msg.team_id)) .key("period", attr_s(period)) - .update_expression( - "ADD completed :one, total_cost_usd :cost, \ - total_tokens_in :ti, total_tokens_out :to, \ - cache_read_tokens :cr, cache_write_tokens :cw", - ) + .update_expression("ADD completed :one") .expression_attribute_values(":one", attr_n(1)) - .expression_attribute_values(":cost", attr_n(format!("{:.4}", cost))) - .expression_attribute_values(":ti", attr_n(usage.input_tokens)) - .expression_attribute_values(":to", attr_n(usage.output_tokens)) - .expression_attribute_values(":cr", attr_n(usage.cache_read_tokens)) - .expression_attribute_values(":cw", attr_n(usage.cache_write_tokens)) .send() .await; } @@ -3325,8 +3293,7 @@ async fn run_passes( if let Some(mut mem) = agent_memory { mem.extract_learnings_from_conversation( &impl_result.conversation_log, - provider.api_key(), - provider.primary_model_id(), + &provider, &crate::memory::LearningOrigin { run_id: run_id.to_string(), ticket_id: msg.ticket_id.clone(), @@ -4068,17 +4035,8 @@ async fn complete_run( .table_name(&state.config.analytics_table_name) .key("team_id", attr_s(&msg.team_id)) .key("period", attr_s(period)) - .update_expression( - "ADD completed :one, total_cost_usd :cost, \ - total_tokens_in :ti, total_tokens_out :to, \ - cache_read_tokens :cr, cache_write_tokens :cw", - ) + .update_expression("ADD completed :one") .expression_attribute_values(":one", attr_n(1)) - .expression_attribute_values(":cost", attr_n(format!("{:.4}", cost))) - .expression_attribute_values(":ti", attr_n(usage.input_tokens)) - .expression_attribute_values(":to", attr_n(usage.output_tokens)) - .expression_attribute_values(":cr", attr_n(usage.cache_read_tokens)) - .expression_attribute_values(":cw", attr_n(usage.cache_write_tokens)) .send() .await?; } @@ -4216,17 +4174,8 @@ async fn fail_run( .table_name(&state.config.analytics_table_name) .key("team_id", attr_s(&msg.team_id)) .key("period", attr_s(period)) - .update_expression( - "ADD failed :one, total_cost_usd :cost, \ - total_tokens_in :ti, total_tokens_out :to, \ - cache_read_tokens :cr, cache_write_tokens :cw", - ) + .update_expression("ADD failed :one") .expression_attribute_values(":one", attr_n(1)) - .expression_attribute_values(":cost", attr_n(format!("{:.4}", cost))) - .expression_attribute_values(":ti", attr_n(usage.input_tokens)) - .expression_attribute_values(":to", attr_n(usage.output_tokens)) - .expression_attribute_values(":cr", attr_n(usage.cache_read_tokens)) - .expression_attribute_values(":cw", attr_n(usage.cache_write_tokens)) .send() .await; } @@ -5859,6 +5808,13 @@ pub(crate) async fn write_pass_trace( .item("output_tokens", attr_n(output_tokens)) .item("cache_read_tokens", attr_n(cache_read)) .item("cache_write_tokens", attr_n(cache_write)) + .item( + "cost_usd", + attr_n(format!( + "{:.6}", + (usage_after.cost_usd - usage_before.cost_usd).max(0.0) + )), + ) .item("tool_calls", attr_n(tool_calls)) .item("timestamp", AttributeValue::S(now)) .item( @@ -6024,6 +5980,7 @@ pub(crate) async fn save_checkpoint( .item("tokens_out", attr_n(usage.output_tokens)) .item("cache_read", attr_n(usage.cache_read_tokens)) .item("cache_write", attr_n(usage.cache_write_tokens)) + .item("cost_usd", attr_n(format!("{:.6}", usage.estimated_cost()))) .item("updated_at", attr_n(now)) .item("ttl", attr_n(ttl)) .send() diff --git a/services/worker/src/passes/onboard.rs b/services/worker/src/passes/onboard.rs index 252494a55..b4c87dc00 100644 --- a/services/worker/src/passes/onboard.rs +++ b/services/worker/src/passes/onboard.rs @@ -1,7 +1,7 @@ use aws_sdk_dynamodb::types::AttributeValue; use tracing::{error, info, warn}; -use crate::agent::anthropic::{self, AnthropicClient}; +use crate::agent::anthropic; use crate::agent::provider::ModelProvider; use crate::clients::github::GitHubClient; use crate::models::{OnboardMessage, TokenUsage}; @@ -261,7 +261,7 @@ async fn onboard_repo( )); } - let client = AnthropicClient::new(provider.api_key().to_string()); + let client = provider.client(); let agents_md = anthropic::converse_simple( &client, provider.primary_model_id(), @@ -364,7 +364,7 @@ async fn generate_voice_md( samples = samples.join("\n\n") ); - let client = AnthropicClient::new(provider.api_key().to_string()); + let client = provider.client(); let voice_md = anthropic::converse_simple(&client, provider.primary_model_id(), system, &prompt, usage) .await?; @@ -416,7 +416,7 @@ async fn generate_global_context( repo_summaries.join("\n\n") ); - let client = AnthropicClient::new(provider.api_key().to_string()); + let client = provider.client(); anthropic::converse_simple(&client, provider.primary_model_id(), system, &prompt, usage).await } diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 02af52bc4..ae156053a 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -1752,14 +1752,18 @@ async fn load_usage_from_checkpoint( .and_then(|n| n.parse().ok()) .unwrap_or(0) }; - TokenUsage { - input_tokens: get_n("tokens_in"), - output_tokens: get_n("tokens_out"), - cache_read_tokens: get_n("cache_read"), - cache_write_tokens: get_n("cache_write"), - tool_calls: 0, - tool_names: vec![], - } + let cost = item + .get("cost_usd") + .and_then(|v| v.as_n().ok()) + .and_then(|n| n.parse::().ok()); + TokenUsage::restored( + &state.config.model_id, + get_n("tokens_in"), + get_n("tokens_out"), + get_n("cache_read"), + get_n("cache_write"), + cost, + ) } else { TokenUsage::default() } @@ -2090,24 +2094,8 @@ async fn complete_run_with_status( Err(e) => return Err(e.into()), } - // Update analytics - let month = chrono::Utc::now().format("%Y-%m").to_string(); - for period in &[month.as_str(), "ALL_TIME"] { - let _ = state - .dynamo - .update_item() - .table_name(&state.config.analytics_table_name) - .key("team_id", attr_s(&msg.team_id)) - .key("period", attr_s(period)) - .update_expression("ADD total_tokens_in :ti, total_tokens_out :to, cache_read_tokens :crt, cache_write_tokens :cwt") - .expression_attribute_values(":ti", attr_n(usage.input_tokens)) - .expression_attribute_values(":to", attr_n(usage.output_tokens)) - .expression_attribute_values(":crt", attr_n(usage.cache_read_tokens)) - .expression_attribute_values(":cwt", attr_n(usage.cache_write_tokens)) - .send() - .await; - } - + // The team's counters already have these tokens: each model call is + // counted as it happens (common::usage). info!(run_id, status, "Run completed"); Ok(()) } diff --git a/services/worker/src/passes/review_pr.rs b/services/worker/src/passes/review_pr.rs index 63a931c62..7ec2aa70c 100644 --- a/services/worker/src/passes/review_pr.rs +++ b/services/worker/src/passes/review_pr.rs @@ -1523,13 +1523,12 @@ fn review_cost_str(usage: &TokenUsage) -> String { /// True when the review used the model at all. fn has_usage(usage: &TokenUsage) -> bool { - usage.input_tokens + usage.output_tokens + usage.cache_read_tokens + usage.cache_write_tokens - > 0 + usage.total_tokens() > 0 } -/// Persist what a review cost on its REVIEW# record, and add it to the team's -/// usage counters — the same per-month analytics item runs add to and the token -/// budget reads — so reviews are no longer free in the team's accounting. +/// Persist what a review used on its REVIEW# record and count the review on the +/// team's analytics item. Its tokens and cost reach the team's counters per +/// model call (common::usage), so they are not added again here. async fn record_review_usage( state: &WorkerState, team_id: &str, @@ -1572,16 +1571,9 @@ async fn record_review_usage( .table_name(&state.config.analytics_table_name) .key("team_id", attr_s(team_id)) .key("period", attr_s(period)) - .update_expression( - "ADD total_cost_usd :cost, total_tokens_in :ti, total_tokens_out :to, \ - cache_read_tokens :cr, cache_write_tokens :cw, \ - reviews :one, review_cost_usd :cost", - ) - .expression_attribute_values(":cost", attr_n(&cost)) - .expression_attribute_values(":ti", attr_n(usage.input_tokens)) - .expression_attribute_values(":to", attr_n(usage.output_tokens)) - .expression_attribute_values(":cr", attr_n(usage.cache_read_tokens)) - .expression_attribute_values(":cw", attr_n(usage.cache_write_tokens)) + // Tokens and cost are already counted per model call + // (common::usage, feature "review"); only the review count here. + .update_expression("ADD reviews :one") .expression_attribute_values(":one", attr_n(1)) .send() .await @@ -1638,12 +1630,18 @@ mod review_usage_tests { #[test] fn cost_matches_the_run_formula() { - let u = TokenUsage { - input_tokens: 100_000, - output_tokens: 10_000, - ..Default::default() - }; + let mut u = TokenUsage::default(); + u.add_call( + "claude-opus-5-5", + &common::usage::CallUsage { + uncached_input: 100_000, + output: 10_000, + ..Default::default() + }, + ); assert_eq!(review_cost_str(&u), format!("{:.4}", u.estimated_cost())); + // Opus 5.5: 0.1M × $4 + 0.01M × $20. + assert_eq!(review_cost_str(&u), "0.6000"); assert!(review_cost_str(&u).parse::().unwrap() > 0.0); } } diff --git a/services/worker/src/passes/skills.rs b/services/worker/src/passes/skills.rs index a33989817..5a107ae8e 100644 --- a/services/worker/src/passes/skills.rs +++ b/services/worker/src/passes/skills.rs @@ -314,12 +314,7 @@ impl TeamSkills { pub fn drain_usage_into(&self, usage: &mut crate::models::TokenUsage) { if let Ok(mut u) = self.usage.lock() { let spent = std::mem::take(&mut *u); - usage.add( - spent.input_tokens, - spent.output_tokens, - spent.cache_read_tokens, - spent.cache_write_tokens, - ); + usage.merge(&spent); } } @@ -548,12 +543,7 @@ impl TeamSkills { } let usage = reply.usage; if let Ok(mut u) = self.usage.lock() { - u.add( - usage.input_tokens, - usage.output_tokens, - usage.cache_read_tokens, - usage.cache_write_tokens, - ); + u.merge(&usage); } let Some(answer) = reply.answer else { return match reply.outcome { @@ -821,6 +811,7 @@ async fn answer_as_agent( None, None, ); + let call = common::usage::with_feature(common::usage::feature::AGENT_ASK, call); match tokio::time::timeout(ASK_TIMEOUT, call).await { Ok(Ok(a)) => { reply.outcome = "answered"; @@ -1300,6 +1291,7 @@ mod tests { api_key: String::new(), primary_model: "team-primary".into(), heavy_model: "team-heavy".into(), + meter: None, }; assert_eq!(pick_model(Some("opus"), &p), "team-heavy"); assert_eq!(pick_model(Some("sonnet"), &p), "team-primary"); diff --git a/services/worker/src/passes/usage_reconcile.rs b/services/worker/src/passes/usage_reconcile.rs new file mode 100644 index 000000000..458314cb2 --- /dev/null +++ b/services/worker/src/passes/usage_reconcile.rs @@ -0,0 +1,476 @@ +//! Daily reconciliation of our recorded model usage against Anthropic's own +//! Usage & Cost Admin API (`/v1/organizations/usage_report/messages` and +//! `/v1/organizations/cost_report`). +//! +//! Off unless the Secrets Manager secret named by `USAGE_RECONCILE_SECRET_NAME` +//! (default `coderhelm//anthropic-admin-keys`) exists. Teams bring their +//! own Anthropic keys, so the secret maps each team to an Admin API key of the +//! organization its key belongs to: +//! +//! ```json +//! {"": {"admin_key": "sk-ant-admin01-...", "api_key_ids": ["apikey_..."]}} +//! ``` +//! +//! `api_key_ids` (optional) limits Anthropic's report to the key CoderHelm +//! uses, so other traffic in that organization doesn't read as drift. Per day +//! and model, a difference over [`DRIFT_LIMIT`] in tokens or cost is logged as +//! `usage_drift` (a warning); the comparison is kept on the analytics item +//! `RECONCILE#`. Key values are never logged. + +use std::collections::{BTreeMap, HashMap}; + +use aws_sdk_dynamodb::types::AttributeValue; +use serde::Deserialize; +use serde_json::Value; +use tracing::{info, warn}; + +use crate::models::UsageReconcileMessage; +use crate::WorkerState; + +/// Relative difference that counts as drift. +pub const DRIFT_LIMIT: f64 = 0.02; + +const API: &str = "https://api.anthropic.com/v1/organizations"; + +#[derive(Deserialize)] +struct TeamKey { + admin_key: String, + #[serde(default)] + api_key_ids: Vec, +} + +/// One model's day: tokens (all four parts) and USD. +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct DayTotals { + pub tokens: u64, + pub cost_usd: f64, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Drift { + pub model: String, + pub ours: DayTotals, + pub theirs: DayTotals, + pub token_drift: f64, + pub cost_drift: f64, +} + +impl Drift { + pub fn flagged(&self) -> bool { + self.token_drift > DRIFT_LIMIT || self.cost_drift > DRIFT_LIMIT + } +} + +fn rel(ours: f64, theirs: f64) -> f64 { + let base = theirs.abs().max(ours.abs()); + if base == 0.0 { + 0.0 + } else { + (ours - theirs).abs() / base + } +} + +/// Compare per model; models on either side only show up with the other at 0. +pub fn compare( + ours: &BTreeMap, + theirs: &BTreeMap, +) -> Vec { + let mut models: Vec<&String> = ours.keys().chain(theirs.keys()).collect(); + models.sort(); + models.dedup(); + models + .into_iter() + .map(|m| { + let o = ours.get(m).copied().unwrap_or_default(); + let t = theirs.get(m).copied().unwrap_or_default(); + Drift { + model: m.clone(), + ours: o, + theirs: t, + token_drift: rel(o.tokens as f64, t.tokens as f64), + cost_drift: rel(o.cost_usd, t.cost_usd), + } + }) + .collect() +} + +/// Our per-model day from the `DAY#` analytics item. +pub fn ours_from_item( + item: Option<&HashMap>, +) -> BTreeMap { + let mut out: BTreeMap = BTreeMap::new(); + let Some(i) = item else { + return out; + }; + for (k, v) in i { + let Some(rest) = k.strip_prefix("model#") else { + continue; + }; + let Some((model, field)) = rest.rsplit_once('#') else { + continue; + }; + let n: f64 = v.as_n().ok().and_then(|n| n.parse().ok()).unwrap_or(0.0); + let e = out.entry(model.to_string()).or_default(); + match field { + "tokens_in" | "cache_read" | "cache_write" | "tokens_out" => e.tokens += n as u64, + "cost_usd" => e.cost_usd += n, + _ => {} + } + } + out +} + +fn model_key(m: &str) -> String { + common::usage::normalize_model(m) +} + +/// Add one `usage_report/messages` page to per-model tokens. +pub fn add_usage_page(page: &Value, into: &mut BTreeMap) { + let n = |v: &Value, k: &str| v.get(k).and_then(|x| x.as_u64()).unwrap_or(0); + for bucket in page["data"].as_array().into_iter().flatten() { + for r in bucket["results"].as_array().into_iter().flatten() { + let model = r["model"].as_str().unwrap_or("unknown"); + let cc = &r["cache_creation"]; + let tokens = n(r, "uncached_input_tokens") + + n(r, "cache_read_input_tokens") + + n(cc, "ephemeral_5m_input_tokens") + + n(cc, "ephemeral_1h_input_tokens") + + n(r, "output_tokens"); + into.entry(model_key(model)).or_default().tokens += tokens; + } + } +} + +/// Add one `cost_report` page (grouped by description) to per-model USD. +/// Amounts are decimal strings in cents. +pub fn add_cost_page(page: &Value, into: &mut BTreeMap) { + for bucket in page["data"].as_array().into_iter().flatten() { + for r in bucket["results"].as_array().into_iter().flatten() { + let Some(model) = r["model"].as_str() else { + continue; // web search, code execution: not token usage + }; + let cents: f64 = match &r["amount"] { + Value::String(s) => s.parse().unwrap_or(0.0), + Value::Number(n) => n.as_f64().unwrap_or(0.0), + _ => 0.0, + }; + into.entry(model_key(model)).or_default().cost_usd += cents / 100.0; + } + } +} + +async fn fetch_all( + http: &reqwest::Client, + admin_key: &str, + url: &str, + query: &[(String, String)], + mut on_page: impl FnMut(&Value), +) -> Result<(), String> { + let mut page: Option = None; + for _ in 0..50 { + let mut q = query.to_vec(); + if let Some(p) = &page { + q.push(("page".into(), p.clone())); + } + let resp = http + .get(url) + .header("x-api-key", admin_key) + .header("anthropic-version", "2023-06-01") + .query(&q) + .send() + .await + .map_err(|e| format!("request failed: {e}"))?; + let status = resp.status(); + let body: Value = resp.json().await.map_err(|e| format!("bad body: {e}"))?; + if !status.is_success() { + return Err(format!( + "{status}: {}", + body["error"]["message"].as_str().unwrap_or("error") + )); + } + on_page(&body); + if body["has_more"].as_bool() != Some(true) { + return Ok(()); + } + page = body["next_page"].as_str().map(str::to_string); + if page.is_none() { + return Ok(()); + } + } + Ok(()) +} + +/// The day to reconcile: the message's, or yesterday (UTC). +pub fn day_of( + msg: &UsageReconcileMessage, + now: chrono::DateTime, +) -> Option { + if msg.day.trim().is_empty() { + Some((now - chrono::Duration::days(1)).date_naive()) + } else { + chrono::NaiveDate::parse_from_str(msg.day.trim(), "%Y-%m-%d").ok() + } +} + +pub async fn run( + state: &WorkerState, + msg: UsageReconcileMessage, +) -> Result<(), Box> { + let secret_name = std::env::var("USAGE_RECONCILE_SECRET_NAME") + .ok() + .filter(|s| !s.trim().is_empty()) + .unwrap_or_else(|| format!("coderhelm/{}/anthropic-admin-keys", state.config.stage)); + let aws = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await; + let sm = aws_sdk_secretsmanager::Client::new(&aws); + let raw = match sm.get_secret_value().secret_id(&secret_name).send().await { + Ok(out) => out.secret_string().unwrap_or_default().to_string(), + Err(e) => { + info!(secret = %secret_name, error = %aws_sdk_secretsmanager::error::DisplayErrorContext(&e), + "Usage reconciliation is off: no Anthropic admin-key secret"); + return Ok(()); + } + }; + let teams: HashMap = + serde_json::from_str(&raw).map_err(|_| "admin-key secret is not the expected JSON map")?; + let Some(day) = day_of(&msg, chrono::Utc::now()) else { + return Err(format!("bad day {:?}", msg.day).into()); + }; + let start = format!("{day}T00:00:00Z"); + let end = format!("{}T00:00:00Z", day + chrono::Duration::days(1)); + + for (team_id, key) in &teams { + if key.admin_key.trim().is_empty() { + continue; + } + let ours_item = state + .dynamo + .get_item() + .table_name(&state.config.analytics_table_name) + .key("team_id", AttributeValue::S(team_id.clone())) + .key("period", AttributeValue::S(format!("DAY#{day}"))) + .send() + .await?; + let ours = ours_from_item(ours_item.item()); + + let mut base: Vec<(String, String)> = vec![ + ("starting_at".into(), start.clone()), + ("ending_at".into(), end.clone()), + ("bucket_width".into(), "1d".into()), + ]; + for id in &key.api_key_ids { + base.push(("api_key_ids[]".into(), id.clone())); + } + let mut theirs: BTreeMap = BTreeMap::new(); + let mut usage_q = base.clone(); + usage_q.push(("group_by[]".into(), "model".into())); + if let Err(e) = fetch_all( + &state.http, + &key.admin_key, + &format!("{API}/usage_report/messages"), + &usage_q, + |p| add_usage_page(p, &mut theirs), + ) + .await + { + warn!(team_id, error = %e, "Anthropic usage report failed"); + continue; + } + // The cost report has no api_key filter: compare cost only when the + // organization is CoderHelm-only (no key filter given). + let mut cost_q: Vec<(String, String)> = base + .iter() + .filter(|(k, _)| k != "api_key_ids[]" && k != "bucket_width") + .cloned() + .collect(); + cost_q.push(("group_by[]".into(), "description".into())); + let compare_cost = key.api_key_ids.is_empty(); + if compare_cost { + if let Err(e) = fetch_all( + &state.http, + &key.admin_key, + &format!("{API}/cost_report"), + &cost_q, + |p| add_cost_page(p, &mut theirs), + ) + .await + { + warn!(team_id, error = %e, "Anthropic cost report failed"); + } + } + + let mut drifts = compare(&ours, &theirs); + if !compare_cost { + for d in &mut drifts { + d.cost_drift = 0.0; + } + } + let mut item: HashMap = HashMap::new(); + item.insert("team_id".into(), AttributeValue::S(team_id.clone())); + item.insert( + "period".into(), + AttributeValue::S(format!("RECONCILE#{day}")), + ); + item.insert( + "checked_at".into(), + AttributeValue::S(chrono::Utc::now().to_rfc3339()), + ); + let mut flagged = 0; + for d in &drifts { + if d.flagged() { + flagged += 1; + warn!( + event = "usage_drift", team_id, day = %day, model = %d.model, + ours_tokens = d.ours.tokens, anthropic_tokens = d.theirs.tokens, + ours_cost_usd = d.ours.cost_usd, anthropic_cost_usd = d.theirs.cost_usd, + token_drift = d.token_drift, cost_drift = d.cost_drift, + "Recorded usage differs from Anthropic's report by more than 2%" + ); + } else { + info!(team_id, day = %day, model = %d.model, token_drift = d.token_drift, + cost_drift = d.cost_drift, "Usage matches Anthropic's report"); + } + let m = &d.model; + item.insert( + format!("model#{m}#ours_tokens"), + AttributeValue::N(d.ours.tokens.to_string()), + ); + item.insert( + format!("model#{m}#anthropic_tokens"), + AttributeValue::N(d.theirs.tokens.to_string()), + ); + item.insert( + format!("model#{m}#ours_cost_usd"), + AttributeValue::N(format!("{:.6}", d.ours.cost_usd)), + ); + item.insert( + format!("model#{m}#anthropic_cost_usd"), + AttributeValue::N(format!("{:.6}", d.theirs.cost_usd)), + ); + } + item.insert( + "flagged_models".into(), + AttributeValue::N(flagged.to_string()), + ); + if let Err(e) = state + .dynamo + .put_item() + .table_name(&state.config.analytics_table_name) + .set_item(Some(item)) + .send() + .await + { + warn!(team_id, error = %e, "Couldn't store the reconciliation result"); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn anthropic_reports_parse_into_per_model_days() { + let usage = json!({"data": [{"starting_at": "2026-10-17T00:00:00Z", "results": [ + {"model": "claude-opus-5-5", "uncached_input_tokens": 10, "cache_read_input_tokens": 1000, + "cache_creation": {"ephemeral_5m_input_tokens": 200, "ephemeral_1h_input_tokens": 50}, + "output_tokens": 40}, + {"model": "claude-sonnet-5-5", "uncached_input_tokens": 1, "output_tokens": 1} + ]}], "has_more": false}); + let cost = json!({"data": [{"results": [ + {"model": "claude-opus-5-5", "amount": "123.5", "currency": "USD", "token_type": "uncached_input_tokens"}, + {"model": "claude-opus-5-5", "amount": "26.5", "currency": "USD", "token_type": "output_tokens"}, + {"description": "Code Execution Usage", "amount": "999"} + ]}]}); + let mut t = BTreeMap::new(); + add_usage_page(&usage, &mut t); + add_cost_page(&cost, &mut t); + assert_eq!(t["claude-opus-5-5"].tokens, 1300); + assert!((t["claude-opus-5-5"].cost_usd - 1.5).abs() < 1e-9); + assert_eq!(t["claude-sonnet-5-5"].tokens, 2); + assert_eq!(t.len(), 2); + } + + #[test] + fn our_day_item_reads_back_per_model() { + let (_, names, values) = common::usage::add_expression( + "run", + "claude-opus-5-5", + &common::usage::CallUsage { + uncached_input: 10, + cache_read: 1000, + cache_write_5m: 250, + cache_write_1h: 0, + output: 40, + }, + ); + let item: HashMap = names + .iter() + .map(|(ph, a)| (a.clone(), values[&ph.replace("#a", ":v")].clone())) + .collect(); + let ours = ours_from_item(Some(&item)); + assert_eq!(ours["claude-opus-5-5"].tokens, 1300); + assert!(ours["claude-opus-5-5"].cost_usd > 0.0); + } + + #[test] + fn drift_over_two_percent_is_flagged() { + let mut ours = BTreeMap::new(); + let mut theirs = BTreeMap::new(); + ours.insert( + "a".to_string(), + DayTotals { + tokens: 1000, + cost_usd: 1.0, + }, + ); + theirs.insert( + "a".to_string(), + DayTotals { + tokens: 1015, + cost_usd: 1.01, + }, + ); + ours.insert( + "b".to_string(), + DayTotals { + tokens: 1000, + cost_usd: 1.0, + }, + ); + theirs.insert( + "b".to_string(), + DayTotals { + tokens: 1100, + cost_usd: 1.0, + }, + ); + theirs.insert( + "c".to_string(), + DayTotals { + tokens: 5, + cost_usd: 0.0, + }, + ); + let d = compare(&ours, &theirs); + assert_eq!(d.len(), 3); + assert!(!d[0].flagged(), "1.5% is within the limit"); + assert!(d[1].flagged(), "9% is drift"); + assert!(d[2].flagged(), "a model we never recorded is drift"); + } + + #[test] + fn the_day_defaults_to_yesterday() { + let now = chrono::DateTime::parse_from_rfc3339("2026-10-18T03:00:00Z") + .unwrap() + .with_timezone(&chrono::Utc); + let d = day_of(&UsageReconcileMessage::default(), now).unwrap(); + assert_eq!(d.to_string(), "2026-10-17"); + let m = UsageReconcileMessage { + day: "2026-10-01".into(), + }; + assert_eq!(day_of(&m, now).unwrap().to_string(), "2026-10-01"); + assert!(day_of(&UsageReconcileMessage { day: "x".into() }, now).is_none()); + } +} From 731c2b1890c82658b5b999ce009f2b87ffe0e85d Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sun, 18 Oct 2026 21:59:35 -0400 Subject: [PATCH 2/2] fix(analytics): run tokens count all four parts --- services/gateway/src/routes/analytics.rs | 28 +++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/services/gateway/src/routes/analytics.rs b/services/gateway/src/routes/analytics.rs index d6a9fc829..712cfa7c7 100644 --- a/services/gateway/src/routes/analytics.rs +++ b/services/gateway/src/routes/analytics.rs @@ -66,6 +66,8 @@ pub struct RunRow { pub cost_usd: f64, pub tokens_in: f64, pub tokens_out: f64, + pub cache_read_tokens: f64, + pub cache_write_tokens: f64, pub duration_s: f64, pub pr_number: u64, pub pr_url: String, @@ -80,6 +82,11 @@ pub struct RunRow { } impl RunRow { + /// All four parts: new input, cache read, cache write, output. + fn tokens(&self) -> f64 { + self.tokens_in + self.cache_read_tokens + self.cache_write_tokens + self.tokens_out + } + fn from_item(i: &Item) -> RunRow { RunRow { run_id: s(i, "run_id"), @@ -92,6 +99,8 @@ impl RunRow { cost_usd: n(i, "cost_usd"), tokens_in: n(i, "tokens_in"), tokens_out: n(i, "tokens_out"), + cache_read_tokens: n(i, "cache_read_tokens"), + cache_write_tokens: n(i, "cache_write_tokens"), duration_s: n(i, "duration_s"), pr_number: n(i, "pr_number") as u64, pr_url: s(i, "pr_url"), @@ -289,7 +298,7 @@ pub fn summary(runs: &[&RunRow], reviews: &[&ReviewRow]) -> Value { let closed = with_pr.iter().filter(|r| r.pr_outcome == "closed").count(); let failed = runs.iter().filter(|r| r.status == "failed").count(); let cost: f64 = runs.iter().map(|r| r.cost_usd).sum(); - let tokens: f64 = runs.iter().map(|r| r.tokens_in + r.tokens_out).sum(); + let tokens: f64 = runs.iter().map(|r| r.tokens()).sum(); let hours: Vec = merged.iter().filter_map(|r| r.hours_to_merge()).collect(); let edits_known: Vec<&&&RunRow> = merged .iter() @@ -325,6 +334,8 @@ pub fn summary(runs: &[&RunRow], reviews: &[&ReviewRow]) -> Value { "tokens_per_merged_pr": ratio(tokens, merged.len() as f64).map(f64::round), "tokens_in": runs.iter().map(|r| r.tokens_in).sum::(), "tokens_out": runs.iter().map(|r| r.tokens_out).sum::(), + "cache_read_tokens": runs.iter().map(|r| r.cache_read_tokens).sum::(), + "cache_write_tokens": runs.iter().map(|r| r.cache_write_tokens).sum::(), "median_run_minutes": median(durations).map(round2), "median_hours_to_merge": median(hours.clone()).map(round2), "time_to_merge_known": hours.len(), @@ -390,7 +401,7 @@ pub fn build( e[3] += 1.0; } e[4] += r.cost_usd; - e[6] += r.tokens_in + r.tokens_out; + e[6] += r.tokens(); } } // Merges land on the day they happened, when known. @@ -444,7 +455,7 @@ pub fn build( e[3] += 1.0; } e[4] += r.cost_usd; - e[5] += r.tokens_in + r.tokens_out; + e[5] += r.tokens(); let who = if r.sender.is_empty() { String::new() } else { @@ -674,6 +685,7 @@ async fn load_runs(state: &AppState, team: &str, w: Window) -> Result