Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion infra/lib/api-stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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/<stage>/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(
Expand Down Expand Up @@ -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);

Expand Down
5 changes: 5 additions & 0 deletions infra/lib/log-analyzer-stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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(
Expand Down
11 changes: 11 additions & 0 deletions infra/lib/worker-stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
15 changes: 13 additions & 2 deletions lambda/log-analyzer/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
import boto3
from botocore.exceptions import ClientError

import usage

logger = logging.getLogger()
logger.setLevel(logging.INFO)

Expand All @@ -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")
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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")
Expand Down
28 changes: 28 additions & 0 deletions lambda/log-analyzer/model_prices.json
Original file line number Diff line number Diff line change
@@ -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}
}
}
167 changes: 167 additions & 0 deletions lambda/log-analyzer/usage.py
Original file line number Diff line number Diff line change
@@ -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}")
54 changes: 54 additions & 0 deletions lambda/tests/test_log_analyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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()
Loading
Loading