Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
A cost figure that says how it is known, and a gateway the default install can reach (#834)
Beenu Arora59b200884fd0
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 87728529b..a210c2679 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -428,6 +428,20 @@ jobs:run: python3 scripts/check_llm_model_routing.py --self-test- name: LLM model routing gaterun: python3 scripts/check_llm_model_routing.py+ # The routing gate above says a model name can reach a model. This says+ # that what the call cost arrives with the thing that says how it is+ # known. The tracker priced the `aisoc-<role>` *alias* against a hosted+ # list table it does not appear in, so every call took a default rate:+ # a 903-token completion on an operator's own hardware reported+ # $0.000999, and that figure reached the cost dashboard, the funnel, the+ # ledger and the budget circuit breaker. Self-test first, as always —+ # its corpora contain text shaped exactly like what it looks for,+ # including this module's own docstring table of the five decoy cost+ # headers it exists to refuse.+ - name: Cost provenance gate — self-test+ run: python3 scripts/check_cost_provenance.py --self-test+ - name: Cost provenance gate+ run: python3 scripts/check_cost_provenance.py# The count claim above says how many connectors exist; this says# whether a reader can find out how to use them. 35 of 84 had no page# at all and the sidebar listed 34 of 96, so most connectordiff --git a/.github/workflows/integration.yml b/.github/workflows/integration.ymlindex 513d0a0a4..ae849258e 100644--- a/.github/workflows/integration.yml+++ b/.github/workflows/integration.yml@@ -242,8 +242,32 @@ jobs:[ "${running}" = "true" ] || { echo "::error::connectors container is not running"; docker compose logs --tail=60 --no-color connectors || true; exit 1; }echo "── ingest enabled the graph writer ──"- docker compose logs --no-color ingest-worker 2>/dev/null | grep -q "graph: ingest-side writer enabled" \- || { echo "::error::graph-at-ingest was not enabled by default"; docker compose logs --tail=60 --no-color ingest-worker || true; exit 1; }+ # Capture first, then grep the capture. This step runs under+ # `set -euo pipefail`, and the previous shape+ #+ # docker compose logs … 2>/dev/null | grep -q "<early match>"+ #+ # fails intermittently *when the match succeeds*. `grep -q` exits+ # the instant it matches — and this string is line 4 of the+ # service's output — which closes the pipe while `docker compose`+ # is still writing. Compose exits 255 on the broken pipe, and+ # `pipefail` promotes that over grep's 0, so the pipeline reports+ # failure over a line that is present. Reproduced deterministically:+ # with a large log the pipeline returns 255 every time, with a small+ # one that fits the pipe buffer it returns 0 every time, and the+ # match is in both. That size dependence is why it read as a flake.+ #+ # `2>/dev/null` made it worse by discarding the only message that+ # would have distinguished "compose failed" from "the line is+ # absent", so the run reported the wrong cause. Compose's stderr is+ # now kept and its exit status checked on its own.+ if ! docker compose logs --no-color ingest-worker > /tmp/ingest-worker.log 2>/tmp/ingest-worker.err; then+ echo "::error::could not read ingest-worker logs — this is not the same as the graph writer being off"+ cat /tmp/ingest-worker.err || true+ exit 1+ fi+ grep -q "graph: ingest-side writer enabled" /tmp/ingest-worker.log \+ || { echo "::error::graph-at-ingest was not enabled by default"; tail -60 /tmp/ingest-worker.log || true; exit 1; }echo "── graph has nodes after the spine flowed ──"ok=""diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c0232ab03..e73edaadb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -150,6 +150,64 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### BREAKING+- **`CostTracker` no longer reports an estimated dollar figure as a measured+ one, and `CostTracker.total_cost_usd` is gone.** It priced a call by looking+ its **model name** up in a table of hosted list prices, and the name it+ looked up was an `aisoc-<role>` alias — a label the LiteLLM gateway resolves+ to a model, not a model. No alias is in the table, so every call fell+ through a `(0.001, 0.002)` default and was booked at a price nobody charges+ for a model nobody named. Measured live: a 903-token completion on an+ operator's own hardware, through a local Ollama model, reported+ `total_cost_usd=0.000999`. The same call now reports `$0.00`, measured.++ The figure was not confined to a dashboard. It fed the funnel insights, the+ per-run Investigation Ledger, the investigation summary export, and the+ **budget circuit breaker** — which trips at `AISOC_BUDGET_HARD_USD` and+ would eventually have degraded a working local install to+ deterministic-only over money nobody spent.++ Every cost is now one of three things, and says which:++ - **measured** — the gateway reported it. The real figure comes off the+ response headers (`x-litellm-response-cost`, and `x-litellm-model-name`+ for what the alias resolved to), so `make_chat_model` now builds clients+ with `include_response_headers=True`. A measured `0.0` — what a local+ model genuinely costs — is a value, not a gap.+ - **estimated** — re-priced from a public list price for a *concrete* model+ id, and labelled an estimate on every surface: `~$` in the console, an+ `estimated_cost_usd` field of its own on every response, and+ "list-price estimate … not billed" in the export. Never merged into a+ measured figure, because one number cannot be labelled two ways.+ - **not measured** — neither. Rendered as an em dash with the reason, never+ as `$0.00`. Following the MTTR precedent: the count of calls a sum was+ computed over travels with the sum, so a zero can be told from an absence.++ There is deliberately no default price any more. An unknown model imputes+ nothing and is counted as unpriced; the BYOK savings panel reports+ "not estimable" rather than a saving computed from an invented rate.++ **The wire is fully additive — no generated SDK client breaks.** The obvious+ shape for "not knowable" is a nullable number, and four fields were written+ that way first (`ByokSavings.imputed_public_cost_usd` / `savings_usd`,+ `ModelBreakdown.imputed_public_cost_usd`, `CostAggregateRow.avg_cost_per_run`).+ That is the wrong shape here for the same reason the MTTR pass rejected it:+ it breaks every client for a fact a companion field already carries. Each+ keeps its type and gains a qualifier — `imputed_is_estimable`, or the+ existing `measured_call_count` — and the console reads the qualifier before+ the number. `scripts/openapi_diff.py` reports no breaking change.++ What callers must change: `CostTracker.total_cost_usd` is replaced by+ `measured_cost_usd` (`float | None`) plus `measured_call_count`, mirrored by+ `estimated_cost_usd` / `estimated_call_count` / `unpriced_call_count`;+ `CallRecord.cost_usd` is now `float | None` and carries `cost_source`;+ `summary()` no longer emits a `total_cost_usd` key. On the wire the fields+ are additive — `total_cost_usd` keeps its name and now carries measured+ cost only, with `measured_call_count` beside it. Migration+ `063_cost_provenance.sql` adds the columns; **every pre-063 row reads as+ "not measured"**, which is the truth about it, and the historical values are+ left in place rather than deleted. Gated by+ `scripts/check_cost_provenance.py`.+- **Three MSSP response schemas describing fabricated data are removed:`MSSPKpiOverview`, `ManagedTenantRow`, `CrossTenantIncident`.** They werethe shape of five hardcoded companies with invented alert counts, not the@@ -218,6 +276,48 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **The LLM gateway moves from the `full` profile into CORE, so the documented+ default install can actually do AI triage.** It was `full`-profile on the+ reasoning that the gateway is "only needed when a provider key is+ configured" — which skipped a step: every task role resolves to an+ `aisoc-<role>` alias, and an alias resolves at the gateway and nowhere else,+ so a CORE deployment could not use a key either. `make up`, the quickstart's+ Path B, and a plain `docker compose up -d` all now start it.++ With no provider key it boots, serves its seven aliases and answers+ `/health/liveliness` (verified against the bundled config with both provider+ keys empty); AiSOC makes no LLM call and the deterministic path is+ unchanged. CORE goes from 10 to 11 services and ~6 GB to ~6.5 GB — the image+ is 1.67 GB and idles at 451 MiB, measured, so "one lightweight container"+ was not true and the README's numbers moved rather than staying put. The+ gateway is also the only party that can report what a call cost, so CORE's+ cost figures were previously unmeasurable by construction. Reasoning and the+ two rejected alternatives: `docs/decisions/0006-llm-gateway-in-core.md`.+ While correcting that table, the `full` row's service count was checked and+ was wrong: `make up-full` starts **21** services, not 30 (30 is `full` plus+ the `monitoring`, `chatops`, `extras` and `osquery` profiles).++- **`Event spine (real containers)` had a genuine race, not a flaky+ environment.** The graph-writer assertion was+ `docker compose logs … 2>/dev/null | grep -q "<early string>"` inside a step+ running under `set -euo pipefail`. `grep -q` exits the instant it matches —+ and that string is line 4 of the service's output — which closes the pipe+ while Compose is still writing; Compose exits 255 on the broken pipe and+ `pipefail` promotes that over grep's 0. The pipeline reported failure over a+ line that was present, which the failing run proves: the log dump its own+ error handler printed 115 ms later contains the exact string.++ Reproduced deterministically rather than inferred — with a large log the+ pipeline returns 255 every time, with a small one that fits the pipe buffer+ it returns 0 every time, and the match is in both. That size dependence is+ why it read as a flake. `2>/dev/null` made it worse by discarding the only+ message that distinguished "Compose failed" from "the line is absent", so+ the run reported the wrong cause. Fixed by capturing the logs once and+ grepping the capture, and by checking Compose's own exit status separately —+ not by a retry or a longer sleep, which would have converted a real race+ into a slower real race. `scripts/doctor.sh` has the same shape twice and is+ unaffected: it does not set `pipefail`.+- **The dependency audit only ever looked at one of the repository's two pnpminstall roots.** `run_pnpm_audit` ran `pnpm audit` in the repo root andnowhere else, so `apps/mobile` — a deliberately separate install root, withdiff --git a/README.md b/README.mdindex 9fcd7af49..07029d11c 100644--- a/README.md+++ b/README.md@@ -123,13 +123,22 @@ One architecture, three profiles of it.| Profile | Command | Services | RAM | What you get ||---|---|---|---|---|-| **core** | `make up` | 10 | ~6 GB | The full alerting pipeline: ingest → detect → correlate → alert → triage → console |-| **full** | `make up-full` | 30 | ~12 GB | Core plus event lake, entity graph, vector store, enrichment, scheduled connectors |-| **demo** | `make up && make demo` | 10 | ~6 GB | Core plus labelled synthetic data |+| **core** | `make up` | 11 | ~6.5 GB | The full alerting pipeline: ingest → detect → correlate → alert → triage → console, plus the LLM gateway |+| **full** | `make up-full` | 21 | ~12 GB | Core plus event lake, entity graph, vector store, enrichment, scheduled connectors |+| **demo** | `make up && make demo` | 11 | ~6.5 GB | Core plus labelled synthetic data |CORE is not a cut-down toy — it is the smallest deployment that takes a realevent and produces a real alert.+**What CORE can and cannot do about AI.** The LLM gateway ships in CORE, so+AI triage works as soon as you put a provider key in `.env` — no profile+change and no second command. Until you do, there is no AI: every alert is+triaged by the deterministic path, the console says so, and no LLM call is+made. That is the honest default, not a degraded one. The gateway is also+what reports what a call cost, so a CORE install's cost figures are measured+rather than estimated. Reasoning:+[ADR-0006](docs/decisions/0006-llm-gateway-in-core.md).+## Real vs synthetic dataThis matters more than any feature, so it is stated plainly.diff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.mdindex a44a97c0f..a87a50ba4 100644--- a/apps/docs/docs/compliance/evidence-pack.md+++ b/apps/docs/docs/compliance/evidence-pack.md@@ -33,7 +33,7 @@ and says so.| Prompt-injection resistance | 32-payload adversarial corpus with a recall floor and a false-positive ceiling | `services/agents/tests/adversarial/` || Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |-The last row is the one worth reading first. It is the honest index: 130 rows+The last row is the one worth reading first. It is the honest index: 131 rows`GATED`, 8 `PARTIAL` with the specific gap named, and a ratchet that refusesto let a row sit at `NO GATE`.diff --git a/apps/docs/docs/deployment/docker.md b/apps/docs/docs/deployment/docker.mdindex 5466dc8aa..d726b393e 100644--- a/apps/docs/docs/deployment/docker.md+++ b/apps/docs/docs/deployment/docker.md@@ -70,6 +70,7 @@ or compose override if you need LAN access.| `realtime` (Node WS + Web Push) | 8086 | 4000 | || `connectors` (50-vendor poller) | 8088 | 8003 | `profiles: [connectors]` || `osquery-tls` (host telemetry server) | 8091 | 8007 | `profiles: [osquery]` |+| `litellm` (LLM gateway) | 4000 | 4000 | CORE — resolves every `aisoc-<role>` alias || `web` (Next.js console + Responder PWA) | 3000 | 3000 | |`mcp` (the Model Context Protocol stdio server) runs without a port — it isdiff --git a/apps/docs/docs/operations/llm-cost.md b/apps/docs/docs/operations/llm-cost.mdnew file mode 100644index 000000000..a5b99f997--- /dev/null+++ b/apps/docs/docs/operations/llm-cost.md@@ -0,0 +1,127 @@+---+title: LLM cost — what is measured, what is estimated, what is not known+sidebar_label: LLM cost+---++# LLM cost++Every dollar figure AiSOC shows is one of three things, and every surface says+which. There is no fourth state, and in particular there is no "we don't know,+so call it zero".++| | What it means | How it looks |+|---|---|---|+| **Measured** | The LLM gateway reported what the call cost. Real money. | `$0.42` with "measured over N calls" |+| **Estimated** | Re-priced from a public list price for a concrete model. An approximation. | `~$0.42` with "list-price estimate … not billed" |+| **Not measured** | Neither was available. | `—` with the reason |++A **measured `$0.00`** is a value, not a gap. That is what a local model+genuinely costs, and it is reported as a measurement because it is one.++## Where the number comes from++AiSOC asks the gateway for a logical alias (`aisoc-triage`,+`aisoc-investigation`, …). The gateway resolves that alias to a real model, so+the gateway is the only party that knows what actually ran and what it cost.+It reports both on the response headers:++```+x-litellm-model-name: ollama/qwen2:1.5b+x-litellm-response-cost-original: 0.0+```++```+x-litellm-model-name: openai/gpt-4o-mini+x-litellm-response-cost: 1.35e-05+```++Those are real responses from the same alias set against one gateway — a local+model and a hosted one. The alias alone distinguishes neither, which is why+the cost is read from the gateway rather than computed from the model name.++Two consequences worth knowing:++- **The gateway has to be in the deployment for cost to be measurable.** It+ ships in the CORE profile+ ([ADR-0006](https://github.com/beenuar/AiSOC/blob/main/docs/decisions/0006-llm-gateway-in-core.md)),+ so the default install measures cost.+- **A model pinned directly at a provider is not measured.** Setting+ `AISOC_MODEL_PIN_<ROLE>` to a concrete provider model bypasses the gateway+ by design, and a provider returns no cost header. Those calls are estimated+ when the model has a published list price and reported as not measured+ otherwise.++## Why the counts are there++Every sum arrives with the number of calls it was computed over —+`measured_call_count`, `estimated_call_count`, `unpriced_call_count`. Without+them a console cannot distinguish "this tenant spent nothing" from "nobody+recorded what this tenant spent", and it will show the first. This is the same+contract the MTTR tiles use, for the same reason.++So on `/costs/dashboard`, a window with real LLM traffic and no measured cost+renders no currency amount at all — the headline says *not measured · N calls+the gateway did not price*, the daily chart says why it is flat, and the BYOK+panel says *not estimable* rather than claiming a saving.++## Why there is no default price++There used to be one. `CostTracker` looked a call's **model name** up in a+table of hosted list prices, and the name it looked up was an `aisoc-<role>`+alias — which is not a model and appears in no price table. So every call fell+through a `(0.001, 0.002)` default and was booked at a price nobody charges+for a model nobody named. A 903-token completion on an operator's own hardware+reported `total_cost_usd=0.000999`.++That figure was not confined to a dashboard. It reached the funnel metrics,+the per-run Investigation Ledger, the investigation summary export, and the+budget circuit breaker — which trips at `AISOC_BUDGET_HARD_USD` and would+eventually have degraded a working local-model install to deterministic-only+over money nobody spent.++A model with no published price now imputes **nothing**. "We know this model's+price" and "we guessed" were previously the same return type, and therefore+the same number.++## Reading it from the API++`GET /api/v1/costs/dashboard` and the `/investigations` routes carry the same+shape everywhere:++```jsonc+{+ "headline": {+ "total_cost_usd": 0.0, // measured only — never includes the estimate+ "measured_call_count": 0, // 0 => the figure above is not a measurement+ "estimated_cost_usd": 0.0, // always labelled an estimate when surfaced+ "estimated_call_count": 0,+ "unpriced_call_count": 1287, // calls nothing could price+ "avg_cost_per_run_usd": null // null, not 0.0, when nothing was measured+ }+}+```++The rule for any client: **read the qualifier before the money.** If+`measured_call_count` is `0`, `total_cost_usd` is not a total of anything; if+`imputed_is_estimable` is `false`, `imputed_public_cost_usd` and `savings_usd`+are `0` because there was nothing to compute, not because the answer is zero.++Those qualifiers are booleans and counts rather than `null` numbers on+purpose. Making the numbers nullable is the obvious shape and breaks every+generated SDK client for a fact the qualifier already carries — the same+choice the MTTR tiles made.++Rows written before migration `063_cost_provenance.sql` have a zero+`measured_call_count` and therefore read as not measured — which is the truth+about them. Their historical values are left in place rather than deleted, and+no read path treats them as measured.++## What enforces this++`scripts/check_cost_provenance.py`, in `ci.yml :: python-lint`, with its+self-test first. Seven structural rules, each checked in both directions:+money fields and their counts, written columns and migration columns, the+absence of a fallback rate in either pricing table, the gateway headers that+carry a total versus the five that share their prefix and do not, the Python+and TypeScript sides of the wire, and whether a console surface consults a+provenance count before printing a currency amount.diff --git a/apps/docs/docs/operations/llm-gateway.md b/apps/docs/docs/operations/llm-gateway.mdindex a6dc267be..df4f8ab19 100644--- a/apps/docs/docs/operations/llm-gateway.md+++ b/apps/docs/docs/operations/llm-gateway.md@@ -51,9 +51,9 @@ point is that you change it. The alias names stay constant.## Enable the gateway-The `litellm` service is part of the `full` profile in `docker-compose.yml`, and-routing to it is already wired. Put your provider key in `.env` and bring the-profile up:+The `litellm` service is in the **CORE** profile, so `make up` and a plain+`docker compose up -d` already start it and routing to it is already wired.+Supplying a key is the only step:```bashOPENAI_API_KEY=<your-real-provider-key> # the gateway uses this to reach the upstream model@@ -61,9 +61,20 @@ LITELLM_MASTER_KEY=<a-strong-key> # AiSOC authenticates to the gateway``````bash-docker compose --profile full up -d+docker compose up -d # or: make up```+It was a `full`-profile service until 2026-09, which meant a CORE deployment+could not do AI triage *even with a key* — every `aisoc-<role>` alias resolves+here and nowhere else. See+[ADR-0006](https://github.com/beenuar/AiSOC/blob/main/docs/decisions/0006-llm-gateway-in-core.md)+for the trade-off, including the measured cost of the container.++**With no provider key**, the gateway still boots, serves its seven aliases+and answers `/health/liveliness`; AiSOC makes no LLM call and every alert is+triaged by the deterministic path. Nothing about the install is broken and+nothing claims AI is running.+That is the whole configuration. `docker-compose.yml` sets `LLM_GATEWAY_URL` onthe `api` and `agents` services, and both services' resolvers read it for any`aisoc-<role>` alias — an alias resolves nowhere else, so the gateway is thediff --git a/apps/docs/docs/quickstart.md b/apps/docs/docs/quickstart.mdindex ada71ad25..9d6f6e4a8 100644--- a/apps/docs/docs/quickstart.md+++ b/apps/docs/docs/quickstart.md@@ -129,6 +129,25 @@ docker compose up -ddocker compose ps```+**What this gives you about AI.** `docker compose up -d` starts the CORE+profile, which includes the `litellm` LLM gateway. AiSOC asks for logical task+aliases (`aisoc-triage`, `aisoc-investigation`, …) and the gateway is the only+thing that resolves them, so it has to be running for AI triage to happen at+all — it was a `full`-profile service until 2026-09, which meant this exact+command could not do AI triage even with the key you just set+([ADR-0006](https://github.com/beenuar/AiSOC/blob/main/docs/decisions/0006-llm-gateway-in-core.md)).++- **With a provider key** in `.env`: alerts are triaged by the AI, and the+ cost dashboard reports what each call actually cost, because the gateway+ reports it.+- **Without one**: the gateway still boots and the stack is healthy, but no+ LLM call is made. Every alert is triaged by the deterministic path and the+ console labels it as such. Nothing pretends the AI ran.++Path A above needs no gateway: the demo compose pins every role to a concrete+provider model, and a concrete pin goes straight to the provider rather than+through the gateway.+This starts the full set of services:- **PostgreSQL** (5432) · **Redis** (6379) · **Kafka** (9092)diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.tsindex 480312112..19801d9a3 100644--- a/apps/docs/sidebars.ts+++ b/apps/docs/sidebars.ts@@ -187,6 +187,7 @@ const sidebars: SidebarsConfig = {"operations/airgap","operations/air-gapped","operations/llm-gateway",+ "operations/llm-cost","operations/codespaces","operations/theming","operations/upgrades",diff --git a/apps/web/src/components/admin/CostDashboardView.test.tsx b/apps/web/src/components/admin/CostDashboardView.test.tsxindex 4b1152093..73565b452 100644--- a/apps/web/src/components/admin/CostDashboardView.test.tsx+++ b/apps/web/src/components/admin/CostDashboardView.test.tsx@@ -49,41 +49,59 @@ function fixture(overrides: Partial<CostDashboard> = {}): CostDashboard {},headline: {total_cost_usd: 142.37,+ measured_call_count: 1287,+ estimated_cost_usd: 0,+ estimated_call_count: 0,+ unpriced_call_count: 0,total_tokens: 4_321_000,total_calls: 1287,total_runs: 312,avg_cost_per_run_usd: 0.456,},daily_costs: [- { day: '2026-05-07', total_cost_usd: 12.5, total_tokens: 320_000, call_count: 80 },- { day: '2026-05-08', total_cost_usd: 18.2, total_tokens: 410_000, call_count: 95 },- { day: '2026-05-09', total_cost_usd: 9.7, total_tokens: 280_000, call_count: 65 },+ { day: '2026-05-07', total_cost_usd: 12.5, measured_call_count: 80, estimated_cost_usd: 0, estimated_call_count: 0, unpriced_call_count: 0, total_tokens: 320_000, call_count: 80 },+ { day: '2026-05-08', total_cost_usd: 18.2, measured_call_count: 95, estimated_cost_usd: 0, estimated_call_count: 0, unpriced_call_count: 0, total_tokens: 410_000, call_count: 95 },+ { day: '2026-05-09', total_cost_usd: 9.7, measured_call_count: 65, estimated_cost_usd: 0, estimated_call_count: 0, unpriced_call_count: 0, total_tokens: 280_000, call_count: 65 },],by_model: [{model: 'gpt-4o-mini',+ resolved_model: 'openai/gpt-4o-mini',runs: 200,calls: 800,total_prompt_tokens: 1_200_000,total_completion_tokens: 600_000,total_cost_usd: 65.4,+ measured_call_count: 800,+ estimated_cost_usd: 0,+ estimated_call_count: 0,+ unpriced_call_count: 0,imputed_public_cost_usd: 65.4,+ imputed_is_estimable: true,+ unpriced_tokens: 0,avg_latency_ms: 1240,},{model: 'claude-3-5-sonnet-20241022',+ resolved_model: null,runs: 112,calls: 487,total_prompt_tokens: 900_000,total_completion_tokens: 410_000,total_cost_usd: 76.97,+ measured_call_count: 487,+ estimated_cost_usd: 0,+ estimated_call_count: 0,+ unpriced_call_count: 0,imputed_public_cost_usd: 76.97,+ imputed_is_estimable: true,+ unpriced_tokens: 0,avg_latency_ms: 2100,},],top_cases: [- { case_id: 'CASE-2026-0042', runs: 6, total_cost_usd: 18.4, total_tokens: 420_000 },- { case_id: 'CASE-2026-0044', runs: 4, total_cost_usd: 12.1, total_tokens: 280_000 },+ { case_id: 'CASE-2026-0042', runs: 6, total_cost_usd: 18.4, measured_call_count: 24, estimated_cost_usd: 0, estimated_call_count: 0, total_tokens: 420_000 },+ { case_id: 'CASE-2026-0044', runs: 4, total_cost_usd: 12.1, measured_call_count: 16, estimated_cost_usd: 0, estimated_call_count: 0, total_tokens: 280_000 },],action_counts: [{ action: 'cases:read', count: 482 },@@ -93,7 +111,10 @@ function fixture(overrides: Partial<CostDashboard> = {}): CostDashboard {is_byok_active: false,provider: 'openai',recorded_cost_usd: 142.37,+ recorded_is_measured: true,imputed_public_cost_usd: 142.37,+ imputed_is_estimable: true,+ unpriced_tokens: 0,savings_usd: 0,},...overrides,@@ -169,7 +190,10 @@ describe('CostDashboardView', () => {is_byok_active: true,provider: 'local-ollama',recorded_cost_usd: 0,+ recorded_is_measured: true,imputed_public_cost_usd: 142.37,+ imputed_is_estimable: true,+ unpriced_tokens: 0,savings_usd: 142.37,},}),@@ -205,6 +229,10 @@ describe('CostDashboardView', () => {fixture({headline: {total_cost_usd: 0,+ measured_call_count: 0,+ estimated_cost_usd: 0,+ estimated_call_count: 0,+ unpriced_call_count: 0,total_tokens: 0,total_calls: 0,total_runs: 0,@@ -227,3 +255,173 @@ describe('CostDashboardView', () => {expect(screen.getByText('No audit events recorded for this window.')).toBeInTheDocument();});});++/**+ * The local-model deployment: real LLM traffic, and no money spent.+ *+ * This is the state PR #829 produced live — 903 tokens through a local model+ * via the gateway — and the state the old tracker reported as $0.000999. Every+ * assertion here is on **first paint** of the real payload, not on an error+ * branch: the defect was never an error, it was a confident wrong number in+ * the success path.+ */+describe('CostDashboardView — a window nothing measured', () => {+ function unmeasured(): CostDashboard {+ const base = fixture();+ return {+ ...base,+ headline: {+ total_cost_usd: 0,+ measured_call_count: 0,+ estimated_cost_usd: 0,+ estimated_call_count: 0,+ unpriced_call_count: 1287,+ total_tokens: 4_321_000,+ total_calls: 1287,+ total_runs: 312,+ avg_cost_per_run_usd: null,+ },+ daily_costs: [+ {+ day: '2026-05-09',+ total_cost_usd: 0,+ measured_call_count: 0,+ estimated_cost_usd: 0,+ estimated_call_count: 0,+ unpriced_call_count: 65,+ total_tokens: 280_000,+ call_count: 65,+ },+ ],+ by_model: [+ {+ model: 'aisoc-triage',+ resolved_model: 'ollama/qwen2:1.5b',+ runs: 312,+ calls: 1287,+ total_prompt_tokens: 3_000_000,+ total_completion_tokens: 1_321_000,+ total_cost_usd: 0,+ measured_call_count: 0,+ estimated_cost_usd: 0,+ estimated_call_count: 0,+ unpriced_call_count: 1287,+ imputed_public_cost_usd: 0,+ imputed_is_estimable: false,+ unpriced_tokens: 4_321_000,+ avg_latency_ms: 5094,+ },+ ],+ top_cases: [+ {+ case_id: 'CASE-2026-0042',+ runs: 6,+ total_cost_usd: 0,+ measured_call_count: 0,+ estimated_cost_usd: 0,+ estimated_call_count: 0,+ total_tokens: 420_000,+ },+ ],+ byok_savings: {+ is_byok_active: true,+ provider: 'local-ollama',+ recorded_cost_usd: 0,+ recorded_is_measured: false,+ imputed_public_cost_usd: 0,+ imputed_is_estimable: false,+ unpriced_tokens: 4_321_000,+ savings_usd: 0,+ },+ };+ }++ it('shows no dollar figure anywhere when nothing was measured', () => {+ seed(30, unmeasured());+ render(<CostDashboardView />);++ // The single most important assertion in this file: a page rendering+ // 1,287 real LLM calls must not print a currency amount it did not+ // measure. Not "$0.00", not "<$0.01", not a default-rate estimate.+ expect(document.body.textContent).not.toMatch(/\$\d/);+ });++ it('labels the headline "not measured" rather than zero', () => {+ seed(30, unmeasured());+ render(<CostDashboardView />);++ const headline = screen.getByTestId('cost-headline');+ expect(within(headline).queryByText('$0.00')).not.toBeInTheDocument();+ expect(+ within(headline).getByText(/not measured · 1,?287 calls the gateway did not price/),+ ).toBeInTheDocument();+ // Tokens are measurable without a price and must still be reported.+ expect(within(headline).getByText('4.32M')).toBeInTheDocument();+ });++ it('says why the spend chart is flat instead of implying a free week', () => {+ seed(30, unmeasured());+ render(<CostDashboardView />);++ expect(screen.getByTestId('daily-spend-unmeasured')).toHaveTextContent(+ /had LLM calls whose\s+cost was not measured/,+ );+ });++ it('names the model the alias resolved to, and imputes nothing for it', () => {+ seed(30, unmeasured());+ render(<CostDashboardView />);++ const table = screen.getByTestId('model-table');+ expect(within(table).getByText('aisoc-triage')).toBeInTheDocument();+ expect(within(table).getByText('→ ollama/qwen2:1.5b')).toBeInTheDocument();+ expect(within(table).getByText('no published price')).toBeInTheDocument();+ });++ it('refuses to claim a BYOK saving it cannot compute', () => {+ seed(30, unmeasured());+ render(<CostDashboardView />);++ const panel = screen.getByTestId('byok-panel');+ expect(panel).toHaveAttribute('data-byok', 'active');+ expect(+ within(panel).getByText(+ 'Not estimable — no model in this window has a published list price',+ ),+ ).toBeInTheDocument();+ expect(within(panel).getByText('not estimable')).toBeInTheDocument();+ });+});++/**+ * The mixed window: some calls billed, some only estimable.+ *+ * An estimate is allowed to appear — it is useful — but never without the+ * word, and never merged into the measured figure.+ */+describe('CostDashboardView — estimates are labelled', () => {+ it('prefixes an estimated figure and says it was not billed', () => {+ const base = fixture();+ seed(30, {+ ...base,+ headline: {+ total_cost_usd: 0,+ measured_call_count: 0,+ estimated_cost_usd: 3.5,+ estimated_call_count: 400,+ unpriced_call_count: 0,+ total_tokens: 900_000,+ total_calls: 400,+ total_runs: 40,+ avg_cost_per_run_usd: null,+ },+ });+ render(<CostDashboardView />);++ const headline = screen.getByTestId('cost-headline');+ expect(within(headline).getByText('~$3.50')).toBeInTheDocument();+ expect(+ within(headline).getByText('list-price estimate over 400 calls — not billed'),+ ).toBeInTheDocument();+ });+});diff --git a/apps/web/src/components/admin/CostDashboardView.tsx b/apps/web/src/components/admin/CostDashboardView.tsxindex b9e0f7579..ed47d2cb7 100644--- a/apps/web/src/components/admin/CostDashboardView.tsx+++ b/apps/web/src/components/admin/CostDashboardView.tsx@@ -17,6 +17,20 @@* imputed savings vs a hosted alternative without us claiming billing-grade* accuracy.*+ * Every dollar on this page is one of three things and says which:+ *+ * measured the gateway reported it. Real money. A measured $0.00 — what+ * a local model costs — is a value, not a gap.+ * estimate re-priced from a public list price. Always prefixed "~" and+ * labelled, never merged into a measured figure.+ * — not measured. Rendered as an em dash with the reason, never+ * as $0.00.+ *+ * The last case is why the counts exist. Before them the page could not tell+ * "the agents spent nothing" from "nobody recorded what the agents spent",+ * and rendered the first: a free AI-SOC, on a tracker that was pricing a+ * gateway alias against a hosted table it does not appear in.+ ** Styling intentionally mirrors `components/reports/ExecutiveDigest.tsx` so* the two admin reports feel like siblings (same Card, KpiCard, Stat* primitives, same dark-on-violet hero band).@@ -45,6 +59,43 @@ function fmtUsd(value: number | null | undefined): string {return `$${(value / 1_000_000).toFixed(2)}M`;}+/**+ * A measured amount, an estimate, or an em dash — decided by the count.+ *+ * Every spend cell on this page goes through here so none can quietly print+ * `$0.00` for a figure nobody measured. `measuredCount` is the same contract+ * the MTTR tiles use: a sum over zero rows is not a sum.+ */+function fmtSpend(+ measured: number | null | undefined,+ measuredCount: number,+ estimated?: number | null,+ estimatedCount?: number,+): string {+ if (measuredCount > 0) return fmtUsd(measured);+ if ((estimatedCount ?? 0) > 0) return `~${fmtUsd(estimated)}`;+ return '—';+}++/** The words under a spend cell explaining which of the three it is. */+function spendProvenance(+ measuredCount: number,+ estimatedCount: number,+ unpricedCount: number,+): string {+ if (measuredCount > 0) {+ const suffix = estimatedCount > 0 ? `, ${estimatedCount} estimated` : '';+ return `measured over ${measuredCount} call${measuredCount === 1 ? '' : 's'}${suffix}`;+ }+ if (estimatedCount > 0) {+ return `list-price estimate over ${estimatedCount} call${estimatedCount === 1 ? '' : 's'} — not billed`;+ }+ if (unpricedCount > 0) {+ return `not measured · ${unpricedCount} call${unpricedCount === 1 ? '' : 's'} the gateway did not price`;+ }+ return 'not measured';+}+function fmtNumber(value: number | null | undefined): string {if (value === null || value === undefined) return '—';if (value < 1000) return value.toLocaleString();@@ -90,8 +141,9 @@ export function CostDashboardView() {<div><h1 className="text-2xl font-bold text-white">Cost Dashboard</h1><p className="mt-1 text-sm text-gray-400">- LLM spend, automation activity, and BYOK savings for the current tenant. Numbers are- recorded by the cost tracker — no estimation unless explicitly labelled.+ LLM spend, automation activity, and BYOK savings for the current tenant. Spend figures+ are what the LLM gateway reported it charged. Anything it could not price is shown as+ an estimate or as not measured — never as zero.</p></div><div className="flex flex-wrap items-center gap-2">@@ -158,15 +210,32 @@ function PeriodHero({ data }: { data: CostDashboard }) {if (headline.total_calls === 0) {return 'No LLM calls recorded in this window.';}- const perRun = headline.avg_cost_per_run_usd;const runsLabel = headline.total_runs === 1 ? 'investigation' : 'investigations';const callsLabel = headline.total_calls === 1 ? 'call' : 'calls';- const cost = fmtUsd(headline.total_cost_usd);const tokens = fmtNumber(headline.total_tokens);+ const volume = `${headline.total_calls.toLocaleString()} ${callsLabel} (${tokens} tokens) across ${headline.total_runs.toLocaleString()} ${runsLabel}`;++ // The sentence used to open with a dollar figure unconditionally. When+ // nothing has been measured there is no figure to open with, and saying+ // "$0.00 of LLM spend" about an unmeasured window is the whole defect in+ // one sentence.+ if (headline.measured_call_count === 0) {+ if (headline.estimated_call_count > 0) {+ return `${volume}. Spend was not measured — the gateway reported no cost — but ${fmtUsd(headline.estimated_cost_usd)} is the list price for the models involved.`;+ }+ return `${volume}. Spend is not measured: no call in this window reported a cost, and nothing here has a published price to estimate from.`;+ }++ const perRun = headline.avg_cost_per_run_usd;+ const cost = fmtUsd(headline.total_cost_usd);+ const unmeasured =+ headline.estimated_call_count + headline.unpriced_call_count > 0+ ? ` ${(headline.estimated_call_count + headline.unpriced_call_count).toLocaleString()} further calls were not billed by the gateway.`+ : '';if (perRun === null) {- return `${cost} of LLM spend across ${headline.total_calls.toLocaleString()} ${callsLabel} (${tokens} tokens). No completed investigation runs in the window.`;+ return `${cost} of measured LLM spend across ${volume}.${unmeasured}`;}- return `${cost} of LLM spend across ${headline.total_runs.toLocaleString()} ${runsLabel}, averaging ${fmtUsd(perRun)} per run on ${tokens} tokens.`;+ return `${cost} of measured LLM spend across ${volume}, averaging ${fmtUsd(perRun)} per run.${unmeasured}`;}, [headline]);return (@@ -185,13 +254,32 @@ function Headline({ data }: { data: CostDashboard }) {const { headline } = data;return (<section className="grid grid-cols-2 gap-4 sm:grid-cols-4" data-testid="cost-headline">- <KpiCard label="Total LLM spend" value={fmtUsd(headline.total_cost_usd)} sub={`${fmtNumber(headline.total_calls)} calls`} />+ <KpiCard+ label="Measured LLM spend"+ value={fmtSpend(+ headline.total_cost_usd,+ headline.measured_call_count,+ headline.estimated_cost_usd,+ headline.estimated_call_count,+ )}+ sub={spendProvenance(+ headline.measured_call_count,+ headline.estimated_call_count,+ headline.unpriced_call_count,+ )}+ /><KpiCard label="Tokens consumed" value={fmtNumber(headline.total_tokens)} sub="prompt + completion" /><KpiCard label="Investigation runs" value={fmtNumber(headline.total_runs)} sub={`${data.action_counts.length} distinct actions`} /><KpiCardlabel="Avg cost / run"- value={fmtUsd(headline.avg_cost_per_run_usd)}- sub={headline.total_runs === 0 ? 'no completed runs yet' : 'rolling window mean'}+ value={headline.measured_call_count > 0 ? fmtUsd(headline.avg_cost_per_run_usd) : '—'}+ sub={+ headline.measured_call_count === 0+ ? 'not measured'+ : headline.total_runs === 0+ ? 'no completed runs yet'+ : 'rolling window mean of measured spend'+ }/></section>);@@ -204,8 +292,12 @@ function DailySpend({ data }: { data: CostDashboard }) {[daily_costs],);+ // A day with calls but nothing measured draws no bar, which is honest only+ // if the reader is told why — otherwise a flat chart reads as a free week.+ const unmeasuredDays = daily_costs.filter((b) => b.measured_call_count === 0 && b.call_count > 0).length;+return (- <Card title="Daily LLM spend" subtitle="One bar per UTC day in the window — bars are scaled to the peak day">+ <Card title="Daily measured LLM spend" subtitle="One bar per UTC day in the window — bars are scaled to the peak day">{daily_costs.length === 0 ? (<p className="text-sm text-gray-500">No LLM activity recorded for this window.</p>) : (@@ -213,11 +305,17 @@ function DailySpend({ data }: { data: CostDashboard }) {<div className="flex h-32 items-end gap-1">{daily_costs.map((bucket) => {const pct = max > 0 ? (bucket.total_cost_usd / max) * 100 : 0;+ const spend = fmtSpend(+ bucket.total_cost_usd,+ bucket.measured_call_count,+ bucket.estimated_cost_usd,+ bucket.estimated_call_count,+ );return (<divkey={bucket.day}className="group relative flex h-full flex-1 flex-col justify-end"- title={`${fmtDate(bucket.day)}: ${fmtUsd(bucket.total_cost_usd)} · ${fmtNumber(bucket.call_count)} calls · ${fmtNumber(bucket.total_tokens)} tokens`}+ title={`${fmtDate(bucket.day)}: ${spend} · ${fmtNumber(bucket.call_count)} calls · ${fmtNumber(bucket.total_tokens)} tokens · ${spendProvenance(bucket.measured_call_count, bucket.estimated_call_count, bucket.unpriced_call_count)}`}><divclassName="rounded-t bg-violet-500/70 transition-colors group-hover:bg-violet-400"@@ -229,9 +327,15 @@ function DailySpend({ data }: { data: CostDashboard }) {</div><div className="mt-2 flex justify-between text-xs text-gray-500"><span>{fmtDate(daily_costs[0]!.day)}</span>- <span>peak {fmtUsd(max)}</span>+ <span>peak {max > 0 ? fmtUsd(max) : '—'}</span><span>{fmtDate(daily_costs[daily_costs.length - 1]!.day)}</span></div>+ {unmeasuredDays > 0 && (+ <p className="mt-2 text-xs text-amber-300/80" data-testid="daily-spend-unmeasured">+ {unmeasuredDays} day{unmeasuredDays === 1 ? '' : 's'} in this window had LLM calls whose+ cost was not measured — those days draw no bar, which is not the same as costing nothing.+ </p>+ )}</div>)}</Card>@@ -241,19 +345,22 @@ function DailySpend({ data }: { data: CostDashboard }) {function ModelTable({ data }: { data: CostDashboard }) {const { by_model } = data;return (- <Card title="Spend by model" subtitle="Recorded vs imputed list-price cost, per model id">+ <Card+ title="Spend by model"+ subtitle="Measured cost vs imputed list price, per model. An alias row shows what the gateway resolved it to."+ >{by_model.length === 0 ? (<p className="text-sm text-gray-500">No per-model rows recorded for this window.</p>) : (<div className="overflow-x-auto" data-testid="model-table">- <table className="w-full min-w-[720px] text-left text-sm">+ <table className="w-full min-w-[800px] text-left text-sm"><thead><tr className="border-b border-gray-700 text-xs uppercase tracking-wide text-gray-500"><th className="py-2 pr-4 font-medium">Model</th><th className="py-2 pr-4 font-medium text-right">Calls</th><th className="py-2 pr-4 font-medium text-right">Prompt tokens</th><th className="py-2 pr-4 font-medium text-right">Completion tokens</th>- <th className="py-2 pr-4 font-medium text-right">Recorded</th>+ <th className="py-2 pr-4 font-medium text-right">Measured</th><th className="py-2 pr-4 font-medium text-right">Imputed (list)</th><th className="py-2 font-medium text-right">Avg latency</th></tr>@@ -261,7 +368,12 @@ function ModelTable({ data }: { data: CostDashboard }) {<tbody>{by_model.map((m) => (<tr key={m.model} className="border-b border-gray-800/80">- <td className="py-2.5 pr-4 font-mono text-xs text-gray-100">{m.model}</td>+ <td className="py-2.5 pr-4 font-mono text-xs text-gray-100">+ {m.model}+ {m.resolved_model && (+ <span className="block text-[10px] text-gray-500">→ {m.resolved_model}</span>+ )}+ </td><td className="py-2.5 pr-4 text-right text-gray-200 tabular-nums">{fmtNumber(m.calls)}</td>@@ -272,10 +384,27 @@ function ModelTable({ data }: { data: CostDashboard }) {{fmtNumber(m.total_completion_tokens)}</td><td className="py-2.5 pr-4 text-right text-white tabular-nums">- {fmtUsd(m.total_cost_usd)}+ {fmtSpend(+ m.total_cost_usd,+ m.measured_call_count,+ m.estimated_cost_usd,+ m.estimated_call_count,+ )}+ <span className="block text-[10px] font-normal text-gray-500">+ {spendProvenance(+ m.measured_call_count,+ m.estimated_call_count,+ m.unpriced_call_count,+ )}+ </span></td><td className="py-2.5 pr-4 text-right text-gray-400 tabular-nums">- {fmtUsd(m.imputed_public_cost_usd)}+ {!m.imputed_is_estimable ? '—' : fmtUsd(m.imputed_public_cost_usd)}+ {m.unpriced_tokens > 0 && (+ <span className="block text-[10px] text-gray-500">+ {!m.imputed_is_estimable ? 'no published price' : `excludes ${fmtNumber(m.unpriced_tokens)} unpriced tokens`}+ </span>+ )}</td><td className="py-2.5 text-right text-gray-400 tabular-nums">{fmtMs(m.avg_latency_ms)}@@ -293,7 +422,7 @@ function ModelTable({ data }: { data: CostDashboard }) {function CasesAndActions({ data }: { data: CostDashboard }) {return (<section className="grid grid-cols-1 gap-4 lg:grid-cols-2">- <Card title="Top-cost investigations" subtitle="Cases ranked by recorded LLM spend in the window">+ <Card title="Top-cost investigations" subtitle="Cases ranked by measured LLM spend in the window">{data.top_cases.length === 0 ? (<p className="text-sm text-gray-500">No case-attributed runs recorded for this window.</p>) : (@@ -305,7 +434,14 @@ function CasesAndActions({ data }: { data: CostDashboard }) {<span className="text-xs text-gray-500 tabular-nums">{fmtNumber(c.runs)} runs · {fmtNumber(c.total_tokens)} tokens</span>- <span className="w-20 text-right text-white tabular-nums">{fmtUsd(c.total_cost_usd)}</span>+ <span className="w-20 text-right text-white tabular-nums">+ {fmtSpend(+ c.total_cost_usd,+ c.measured_call_count,+ c.estimated_cost_usd,+ c.estimated_call_count,+ )}+ </span></span></li>))}@@ -350,26 +486,44 @@ function ByokPanel({ data }: { data: CostDashboard }) {<div><p className="text-xs uppercase tracking-wide text-gray-400">BYOK savings</p><p className="mt-1 text-lg font-semibold text-white">- {b.is_byok_active- ? `~${fmtUsd(b.savings_usd)} saved by running your own model`- : `Hosted via ${b.provider} — no local-model savings to attribute`}+ {!b.imputed_is_estimable+ ? 'Not estimable — no model in this window has a published list price'+ : b.is_byok_active+ ? `~${fmtUsd(b.savings_usd)} saved by running your own model`+ : `Hosted via ${b.provider} — no local-model savings to attribute`}</p></div><span className={`rounded-full px-3 py-1 text-xs font-medium ${badge.cls}`}>{badge.text}</span></div><dl className="mt-4 grid grid-cols-1 gap-4 text-sm sm:grid-cols-3">- <Stat label="Recorded cost" value={fmtUsd(b.recorded_cost_usd)} />- <Stat label="Imputed list-price cost" value={fmtUsd(b.imputed_public_cost_usd)} />+ <Stat+ label="Measured cost"+ value={b.recorded_is_measured ? fmtUsd(b.recorded_cost_usd) : '—'}+ hint={b.recorded_is_measured ? 'reported by the gateway' : 'not measured'}+ />+ <Stat+ label="Imputed list-price cost"+ value={!b.imputed_is_estimable ? '—' : `~${fmtUsd(b.imputed_public_cost_usd)}`}+ hint={+ !b.imputed_is_estimable+ ? 'no published price for these models'+ : b.unpriced_tokens > 0+ ? `estimate · excludes ${fmtNumber(b.unpriced_tokens)} unpriced tokens`+ : 'estimate'+ }+ /><Statlabel="Estimated savings"- value={fmtUsd(b.savings_usd)}- accent={b.is_byok_active ? 'text-emerald-300' : 'text-gray-300'}+ value={!b.imputed_is_estimable ? '—' : `~${fmtUsd(b.savings_usd)}`}+ hint={!b.imputed_is_estimable ? 'not estimable' : 'estimate'}+ accent={b.is_byok_active && b.imputed_is_estimable ? 'text-emerald-300' : 'text-gray-300'}/></dl><p className="mt-4 text-xs text-gray-500">- Imputed cost re-prices recorded prompt + completion tokens against each model's public list- price. Savings approximate what an equivalent hosted call would have cost — not a billing-grade- figure.+ Imputed cost re-prices prompt + completion tokens against each model's public list price,+ and only for models that have one — there is no default rate, so a model nobody publishes a+ price for contributes nothing here rather than a guess. Savings approximate what an equivalent+ hosted call would have cost; they are an estimate, not a billing-grade figure.</p></section>);@@ -419,15 +573,18 @@ function Stat({label,value,accent,+ hint,}: {label: string;value: number | string;accent?: string;+ hint?: string;}) {return (<div><dt className="text-xs text-gray-500">{label}</dt><dd className={`mt-1 text-xl font-semibold tabular-nums ${accent ?? 'text-white'}`}>{value}</dd>+ {hint && <p className="mt-0.5 text-[10px] text-gray-500">{hint}</p>}</div>);}diff --git a/apps/web/src/components/cases/InvestigationLedger.tsx b/apps/web/src/components/cases/InvestigationLedger.tsxindex bba104f5f..05f8e1b25 100644--- a/apps/web/src/components/cases/InvestigationLedger.tsx+++ b/apps/web/src/components/cases/InvestigationLedger.tsx@@ -528,8 +528,7 @@ function RunSummaryCard({value={<span>{run.total_tokens.toLocaleString()}{' '}- <span className="text-slate-500">·</span>{' '}- ${run.total_cost_usd.toFixed(4)}+ <span className="text-slate-500">·</span> {formatRunCost(run)}</span>}/>@@ -568,11 +567,15 @@ function RunSummaryCard({* Sorted by spend descending so the most expensive model surfaces first.*/function ModelCostsCard({ costs }: { costs: LedgerModelCost[] }) {- // Defensive sort — backend already orders by total_cost_usd DESC, but a+ // Defensive sort — backend already orders by measured cost DESC, but a// future caller could pass an arbitrary list and we want the UI invariant- // (most expensive first) to hold regardless.+ // (most expensive first) to hold regardless. Falls through to the estimate+ // so a run with nothing measured still orders by the best figure there is.const sorted = useMemo(- () => [...costs].sort((a, b) => b.total_cost_usd - a.total_cost_usd),+ () =>+ [...costs].sort(+ (a, b) => b.total_cost_usd - a.total_cost_usd || b.estimated_cost_usd - a.estimated_cost_usd,+ ),[costs],);@@ -603,6 +606,9 @@ function ModelCostsCard({ costs }: { costs: LedgerModelCost[] }) {<tr key={c.model} className="text-slate-300"><td className="px-3 py-2 font-mono text-[11px] text-slate-200">{c.model}+ {c.resolved_model && (+ <span className="block text-[10px] text-slate-500">→ {c.resolved_model}</span>+ )}</td><td className="px-3 py-2 text-right">{c.call_count.toLocaleString()}</td><td className="px-3 py-2 text-right">@@ -612,7 +618,7 @@ function ModelCostsCard({ costs }: { costs: LedgerModelCost[] }) {{c.total_completion_tokens.toLocaleString()}</td><td className="px-3 py-2 text-right tabular-nums">- ${c.total_cost_usd.toFixed(4)}+ {formatModelCost(c)}</td><td className="px-3 py-2 text-right text-slate-400">{formatLatencyMs(c.total_latency_ms)}@@ -626,6 +632,28 @@ function ModelCostsCard({ costs }: { costs: LedgerModelCost[] }) {);}+/**+ * A run's cost cell: measured money, a labelled estimate, or "not measured".+ *+ * It read `$${run.total_cost_usd.toFixed(4)}` unconditionally. Deep+ * investigations never wrote that column at all, so every one of them showed+ * `$0.0000` next to a real token count, and auto-triage runs showed a+ * list-price guess made against a gateway alias. Both were a dollar figure+ * the product could not support.+ */+function formatRunCost(run: LedgerRunSummary): string {+ if (run.measured_call_count > 0) return `$${run.total_cost_usd.toFixed(4)}`;+ if (run.estimated_call_count > 0) return `~$${run.estimated_cost_usd.toFixed(4)} est.`;+ return 'cost not measured';+}++/** Same three-way rule for one model's row in the per-model breakdown. */+function formatModelCost(c: LedgerModelCost): string {+ if (c.measured_call_count > 0) return `$${c.total_cost_usd.toFixed(4)}`;+ if (c.estimated_call_count > 0) return `~$${c.estimated_cost_usd.toFixed(4)} est.`;+ return '—';+}+/** Compact human-friendly latency string. ms under 1s, seconds otherwise. */function formatLatencyMs(ms: number): string {if (!Number.isFinite(ms) || ms <= 0) return '—';diff --git a/apps/web/src/components/dashboard/SOCMetricsDashboard.tsx b/apps/web/src/components/dashboard/SOCMetricsDashboard.tsxindex 30d7c3f92..ab9428710 100644--- a/apps/web/src/components/dashboard/SOCMetricsDashboard.tsx+++ b/apps/web/src/components/dashboard/SOCMetricsDashboard.tsx@@ -57,11 +57,11 @@ const MOCK_SOC_METRICS: SOCMetrics = {const MOCK_COST_AGGREGATE: CostAggregate = {window_days: 30,by_model: [- { model: "gpt-4o", runs: 312, calls: 1840, total_prompt_tokens: 4_620_000, total_completion_tokens: 890_000, total_cost_usd: 42.18, total_latency_ms: 7_360_000, avg_cost_per_run: 0.1352, avg_latency_per_call_ms: 4000 },- { model: "gpt-4o-mini", runs: 580, calls: 3200, total_prompt_tokens: 2_100_000, total_completion_tokens: 620_000, total_cost_usd: 4.86, total_latency_ms: 3_200_000, avg_cost_per_run: 0.0084, avg_latency_per_call_ms: 1000 },- { model: "claude-3.5-sonnet", runs: 145, calls: 870, total_prompt_tokens: 3_480_000, total_completion_tokens: 710_000, total_cost_usd: 29.61, total_latency_ms: 4_350_000, avg_cost_per_run: 0.2042, avg_latency_per_call_ms: 5000 },+ { model: "gpt-4o", runs: 312, calls: 1840, total_prompt_tokens: 4_620_000, total_completion_tokens: 890_000, total_cost_usd: 42.18, measured_call_count: 1840, estimated_cost_usd: 0, estimated_call_count: 0, unpriced_call_count: 0, total_latency_ms: 7_360_000, avg_cost_per_run: 0.1352, avg_latency_per_call_ms: 4000 },+ { model: "gpt-4o-mini", runs: 580, calls: 3200, total_prompt_tokens: 2_100_000, total_completion_tokens: 620_000, total_cost_usd: 4.86, measured_call_count: 3200, estimated_cost_usd: 0, estimated_call_count: 0, unpriced_call_count: 0, total_latency_ms: 3_200_000, avg_cost_per_run: 0.0084, avg_latency_per_call_ms: 1000 },+ { model: "claude-3.5-sonnet", runs: 145, calls: 870, total_prompt_tokens: 3_480_000, total_completion_tokens: 710_000, total_cost_usd: 29.61, measured_call_count: 870, estimated_cost_usd: 0, estimated_call_count: 0, unpriced_call_count: 0, total_latency_ms: 4_350_000, avg_cost_per_run: 0.2042, avg_latency_per_call_ms: 5000 },],- totals: { model: "all", runs: 1037, calls: 5910, total_prompt_tokens: 10_200_000, total_completion_tokens: 2_220_000, total_cost_usd: 76.65, total_latency_ms: 14_910_000, avg_cost_per_run: 0.0739, avg_latency_per_call_ms: 2523 },+ totals: { model: "all", runs: 1037, calls: 5910, total_prompt_tokens: 10_200_000, total_completion_tokens: 2_220_000, total_cost_usd: 76.65, measured_call_count: 5910, estimated_cost_usd: 0, estimated_call_count: 0, unpriced_call_count: 0, total_latency_ms: 14_910_000, avg_cost_per_run: 0.0739, avg_latency_per_call_ms: 2523 },};function formatUsd(n: number): string {@@ -508,7 +508,10 @@ function CostTelemetryPanel() {<KpiCard label="LLM Calls" value={totals.calls} /><KpiCardlabel="Avg $/Run"- value={formatUsd(totals.avg_cost_per_run)}+ // null when nothing in the window was measured. A mean of an+ // unmeasured zero is not a cost per run.+ value={totals.avg_cost_per_run === null ? "—" : formatUsd(totals.avg_cost_per_run)}+ hint={totals.avg_cost_per_run === null ? "not measured" : undefined}/><KpiCardlabel="Avg Latency/Call"diff --git a/apps/web/src/components/dashboard/operations/AgentThroughputPanel.tsx b/apps/web/src/components/dashboard/operations/AgentThroughputPanel.tsxindex 01d70cc1a..3eb0310c2 100644--- a/apps/web/src/components/dashboard/operations/AgentThroughputPanel.tsx+++ b/apps/web/src/components/dashboard/operations/AgentThroughputPanel.tsx@@ -44,6 +44,19 @@ export function AgentThroughputPanel() {const headline = data?.headline;const byModel = data?.by_model ?? [];const maxModelCost = Math.max(...byModel.map((m) => m.total_cost_usd), 0.0001);+ // A bar can only be drawn from a measured figure. Scaling an unmeasured+ // zero still draws nothing, but the label beside it would have read+ // "$0.00" — a claim the panel has no basis for.+ //+ // A *missing* count is treated as zero, i.e. not measured. This is the+ // opposite of what the MTTR tiles do with a missing sample count, and+ // deliberately so: an older API that omits a sample size still sent a real+ // mean, whereas an older API that omits these counts sent a figure we now+ // know was a list-price guess keyed on a gateway alias. Rendering the+ // familiar number is the safe default there and the unsafe one here.+ const measuredCalls = headline?.measured_call_count ?? 0;+ const estimatedCalls = headline?.estimated_call_count ?? 0;+ const anyMeasured = measuredCalls > 0;return (<section@@ -82,15 +95,24 @@ export function AgentThroughputPanel() {<Stat label="Runs" value={headline.total_runs.toLocaleString()} /><Stat label="LLM calls" value={formatCompact(headline.total_calls)} /><Stat label="Tokens" value={formatCompact(headline.total_tokens)} />- <Stat label="Spend" value={formatUsd(headline.total_cost_usd)} />+ <Stat+ label="Measured spend"+ value={anyMeasured ? formatUsd(headline.total_cost_usd) : '—'}+ /></div>{/* Only render the derived per-run figure the server computed. Whenit is null the server had no basis for it, and dividing herewould invent one. */}- {headline.avg_cost_per_run_usd != null && (+ {anyMeasured && headline.avg_cost_per_run_usd != null ? (<p className="text-[11px] text-gray-500">- {`${formatUsd(headline.avg_cost_per_run_usd)} per run on average.`}+ {`${formatUsd(headline.avg_cost_per_run_usd)} per run on average, measured over ${measuredCalls.toLocaleString()} calls.`}+ </p>+ ) : (+ <p className="text-[11px] text-gray-500">+ {estimatedCalls > 0+ ? `Spend not measured — the gateway reported no cost. List price for the models involved is ~${formatUsd(headline.estimated_cost_usd)}.`+ : 'Spend not measured: no call in this window reported a cost.'}</p>)}@@ -107,17 +129,25 @@ export function AgentThroughputPanel() {{m.model}</span><span className="shrink-0 text-[11px] text-gray-500">- {`${m.runs} runs · ${formatUsd(m.total_cost_usd)}`}+ {`${m.runs} runs · ${+ (m.measured_call_count ?? 0) > 0+ ? formatUsd(m.total_cost_usd)+ : (m.estimated_call_count ?? 0) > 0+ ? `~${formatUsd(m.estimated_cost_usd)} est.`+ : 'cost not measured'+ }`}</span></div>- <div className="h-1 rounded-full bg-gray-800">- <div- className="h-1 rounded-full bg-indigo-500/60"- style={{- width: `${Math.round((m.total_cost_usd / maxModelCost) * 100)}%`,- }}- />- </div>+ {anyMeasured && (+ <div className="h-1 rounded-full bg-gray-800">+ <div+ className="h-1 rounded-full bg-indigo-500/60"+ style={{+ width: `${Math.round((m.total_cost_usd / maxModelCost) * 100)}%`,+ }}+ />+ </div>+ )}</li>))}</ul>diff --git a/apps/web/src/components/dashboard/operations/OperationsDashboard.test.tsx b/apps/web/src/components/dashboard/operations/OperationsDashboard.test.tsxindex b4e3ba2c1..0fc0cd324 100644--- a/apps/web/src/components/dashboard/operations/OperationsDashboard.test.tsx+++ b/apps/web/src/components/dashboard/operations/OperationsDashboard.test.tsx@@ -112,6 +112,10 @@ const COSTS = {period: { start: '', end: '', window_days: 7, label: '7d' },headline: {total_cost_usd: 4.21,+ measured_call_count: 612,+ estimated_cost_usd: 0,+ estimated_call_count: 0,+ unpriced_call_count: 0,total_tokens: 1_840_000,total_calls: 612,total_runs: 96,@@ -121,12 +125,19 @@ const COSTS = {by_model: [{model: 'local-llm',+ resolved_model: null,runs: 96,calls: 612,total_prompt_tokens: 1_500_000,total_completion_tokens: 340_000,total_cost_usd: 4.21,+ measured_call_count: 612,+ estimated_cost_usd: 0,+ estimated_call_count: 0,+ unpriced_call_count: 0,imputed_public_cost_usd: 9.1,+ imputed_is_estimable: true,+ unpriced_tokens: 0,avg_latency_ms: 880,},],@@ -136,7 +147,10 @@ const COSTS = {is_byok_active: true,provider: 'local',recorded_cost_usd: 4.21,+ recorded_is_measured: true,imputed_public_cost_usd: 9.1,+ imputed_is_estimable: true,+ unpriced_tokens: 0,savings_usd: 4.89,},};diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex d500c6f65..5e40cdfe8 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -1842,7 +1842,12 @@ export interface LedgerRunSummary {model_used: string | null;iterations: number;total_tokens: number;+ /** Measured (gateway-reported) spend; 0 with a 0 count means unmeasured. */total_cost_usd: number;+ measured_call_count: number;+ estimated_cost_usd: number;+ estimated_call_count: number;+ unpriced_call_count: number;started_at: string;completed_at: string | null;error: string | null;@@ -1850,9 +1855,15 @@ export interface LedgerRunSummary {export interface LedgerModelCost {model: string;+ /** What the gateway resolved ``model`` to; ``model`` is often an alias. */+ resolved_model: string | null;total_prompt_tokens: number;total_completion_tokens: number;total_cost_usd: number;+ measured_call_count: number;+ estimated_cost_usd: number;+ estimated_call_count: number;+ unpriced_call_count: number;total_latency_ms: number;call_count: number;}@@ -2110,7 +2121,12 @@ export interface CostAggregateRow {total_prompt_tokens: number;total_completion_tokens: number;total_cost_usd: number;+ measured_call_count: number;+ estimated_cost_usd: number;+ estimated_call_count: number;+ unpriced_call_count: number;total_latency_ms: number;+ /** Read with ``measured_call_count``: zero there means this is not a mean. */avg_cost_per_run: number;avg_latency_per_call_ms: number;}@@ -5375,36 +5391,66 @@ export interface DashboardPeriod {}export interface CostHeadline {- /** Sum of recorded LLM cost in USD over the window. */+ /**+ * **Measured** LLM cost in USD — what the gateway reported it charged.+ * Only meaningful when ``measured_call_count > 0``: a zero there means+ * nothing measured this window, which is not the same as a free one.+ */total_cost_usd: number;+ /** Calls the measured sum was computed over. 0 ⇒ render "not measured". */+ measured_call_count: number;+ /** List-price estimate for calls the gateway did not price. Label it. */+ estimated_cost_usd: number;+ estimated_call_count: number;+ /** Calls nothing could price at all. */+ unpriced_call_count: number;/** Sum of prompt + completion tokens. */total_tokens: number;/** Total LLM API call count (one row in aisoc_run_costs ≈ one call). */total_calls: number;/** Distinct investigation_runs that produced cost in the window. */total_runs: number;- /** Mean cost per run; null when no runs landed in the window. */+ /** Mean measured cost per run; null when nothing was measured. */avg_cost_per_run_usd: number | null;}export interface CostBucket {/** Calendar day in UTC, ISO ``YYYY-MM-DD``. */day: string;+ /** Measured cost for the day; see ``measured_call_count``. */total_cost_usd: number;+ measured_call_count: number;+ estimated_cost_usd: number;+ estimated_call_count: number;+ unpriced_call_count: number;total_tokens: number;call_count: number;}export interface ModelBreakdown {- /** Lowercased model id, e.g. ``gpt-4o-mini``. */+ /** Lowercased model id as requested — usually an ``aisoc-<role>`` alias. */model: string;+ /** What the gateway resolved that alias to, e.g. ``ollama/qwen2:1.5b``. */+ resolved_model: string | null;runs: number;calls: number;total_prompt_tokens: number;total_completion_tokens: number;+ /** Measured cost; see ``measured_call_count``. */total_cost_usd: number;- /** What this volume would have cost on the public list price. */+ measured_call_count: number;+ estimated_cost_usd: number;+ estimated_call_count: number;+ unpriced_call_count: number;+ /**+ * What this volume would have cost on the public list price. Read it with+ * ``imputed_is_estimable``: false means the model has no published price+ * and this is 0 because there is nothing to compute, not because it is free.+ */imputed_public_cost_usd: number;+ imputed_is_estimable: boolean;+ /** Tokens the imputation had to skip, so partial coverage is visible. */+ unpriced_tokens: number;avg_latency_ms: number | null;}@@ -5412,6 +5458,9 @@ export interface TopCostCase {case_id: string;runs: number;total_cost_usd: number;+ measured_call_count: number;+ estimated_cost_usd: number;+ estimated_call_count: number;total_tokens: number;}@@ -5426,13 +5475,24 @@ export interface ByokSavings {is_byok_active: boolean;/** Provider id from /llm/status (e.g. ``openai``, ``local-ollama``). */provider: string;- /** Recorded cost — what the cost tracker actually booked. */+ /** Measured cost — what the gateway reported. See ``recorded_is_measured``. */recorded_cost_usd: number;- /** Re-priced cost using public list pricing (BYOK-neutral baseline). */+ /** False when nothing in the window was measured, so 0 means "unknown". */+ recorded_is_measured: boolean;+ /**+ * Re-priced using public list pricing (BYOK-neutral baseline). There is no+ * default rate: applying one to a gateway alias is what produced savings+ * figures for spend that never happened.+ */imputed_public_cost_usd: number;+ /** False => no model in the window has a published price; render "—". */+ imputed_is_estimable: boolean;+ /** Tokens excluded from the imputation because nothing prices them. */+ unpriced_tokens: number;/*** Estimated savings vs hosted: equals imputed_public_cost on BYOK,- * ``max(imputed - recorded, 0)`` otherwise.+ * ``max(imputed - recorded, 0)`` otherwise. Meaningless unless+ * ``imputed_is_estimable``.*/savings_usd: number;}diff --git a/docker-compose.yml b/docker-compose.ymlindex 2e57cd11d..9884e4e04 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -557,8 +557,24 @@ services:# unless a service is pointed at it via OPENAI_BASE_URL — see the note on the# `agents` service above.litellm:- # full profile — LLM gateway. Only needed when a provider key is configured.- profiles: ["full"]+ # CORE, deliberately — see docs/architecture/decisions/0001-llm-gateway-in-core.md.+ #+ # This was `profiles: ["full"]` on the reasoning that the gateway is "only+ # needed when a provider key is configured". The reasoning skipped a step:+ # a CORE deployment *with* a key could not use it either, because every+ # `aisoc-<role>` alias resolves nowhere except here. So the documented+ # default install — what `make up` starts and what the quickstart walks a+ # new evaluator through — could not do AI triage at all, and the profile+ # table said it did "triage".+ #+ # With no key it boots, serves its seven aliases and answers /health;+ # AiSOC's deterministic path is unchanged and still honest. Measured cost:+ # a 1.67 GB image idling at ~451 MiB, which is why the RAM figure in the+ # README moved rather than staying put.+ #+ # It is also the only party that can say what a call cost — the real+ # figure comes off its response headers — so leaving it out of CORE left+ # the default install's cost dashboard permanently unmeasurable.image: ghcr.io/berriai/litellm:main-stablecontainer_name: aisoc-litellmcommand: ["--config", "/etc/litellm/config.yaml", "--port", "4000"]diff --git a/docs/architecture/README.md b/docs/architecture/README.mdindex 6c2fa756b..c95000385 100644--- a/docs/architecture/README.md+++ b/docs/architecture/README.md@@ -112,6 +112,7 @@ flowchart LRrt["services/realtime<br/>TS · :8086"]agt["services/agents<br/>Python · :8084"]web["apps/web<br/>Next.js · :3000"]+ llm["litellm<br/>LLM gateway · :4000"]endsubgraph full ["full profile — optional"]@@ -134,6 +135,8 @@ flowchart LRkafd --> rtkafd --> agtagt --> pg+ agt -->|"aisoc-<role> alias"| llm+ api --> llmapi --> pgapi -.-> chapi -.-> neodiff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex 9bed5da5a..6c9db5824 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -146,10 +146,11 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| Every check resolves its root from git and carries a `--self-test` | `scripts/` (the gates themselves) | `ci.yml :: python-test` (`scripts/check_gate_contract.py` — a check that derives a repository root from `__file__` without consulting git fails as `root-from-file`, and one that declares no `--self-test` fails as `no-self-test`. Both read from the syntax tree: the first spelling matched `repo_root` anywhere in the text and `check_gate_coverage.py` emits it as a JSON key, so a non-compliant gate read as compliant on the strength of a dictionary key in its own output. Both exception lists are empty — all 72 comply — and an entry added to either must carry a reason) | GATED | - || Every model AiSOC sends has a gateway that defines it, and the variable compose supplies is the variable the resolvers read | `apps/docs/docs/operations/llm-gateway.md`, `.env.example`, README (AI triage) | `ci.yml :: python-lint` (`scripts/check_llm_model_routing.py` — both directions on every name: each role pin's alias must be defined by `infra/litellm/config.yaml` and each alias must be claimed by a pin; every model named in `.env.example` or `docker-compose.yml`, in a file that wires the bundled gateway, must be one the gateway defines; every variable compose points at the gateway must be read by *both* resolvers, and every gateway variable the resolvers read must be set by compose — the defect that shipped was compose supplying `LLM_GATEWAY_URL` and both resolvers deliberately ignoring it, so AI triage could not reach a model at all; a service given the gateway URL must also get `LITELLM_MASTER_KEY`, because a provider key sent there is rejected. Every parser is AST- or comment-aware and the self-test proves it: the config's commented Ollama example repeats `model_name: aisoc-triage` verbatim, `.env.example` documents the escape hatch as a commented `AISOC_MODEL_PIN_TRIAGE=`, and compose explains the gateway in prose two lines above the key it describes — a line regex credits all three) + `services/agents/tests/test_llm_factory.py` + `services/api/tests/test_model_aliases_routing.py` | GATED | Embeddings are a recorded exclusion — the gateway's model list is chat aliases only — and the gate checks that in both directions rather than trusting the comment || Every test file in the tree is executed by a workflow | `CONTRIBUTING.md` / the suites themselves | `ci.yml :: python-test` (`scripts/check_test_discovery.py` — the corpus is `git ls-files`, so a service added tomorrow is scanned with no edit, and an untracked install tree is out by construction rather than by a name somebody remembered. Reach is modelled the way pytest collects: directory arguments, `--ignore`, `conftest` `collect_ignore`, and `-m` marker deselection, because a file whose every test is deselected runs nothing however plainly it is named. Both directions — an invocation naming a path that is not in the tree fails too. Quarantine is a shrink-only list where each entry carries a reason and an entry that has become reachable fails as stale. Two blind spots in this parser were found by counting what it **credited**: a step that `cd`s into a service and then names `tests/` had its paths resolved against the repository root, which reported all 82 agents files unreached *and* credited the root tree with a package's invocation; and `-m` was first skipped as "a filter, not a collection rule", which would have credited a file in full under `-m "not integration"`) + `tests/test_test_discovery_gate.py` | GATED | - |+| Every reported LLM cost is measured, labelled an estimate, or absent | admin cost dashboard, `/costs/dashboard`, `/investigations` run + aggregate responses, Investigation Ledger, `/metrics/funnel` insights, investigation summary export | `ci.yml :: python-lint` (`scripts/check_cost_provenance.py` — the tracker priced the `aisoc-<role>` **alias** against a table of hosted list prices it does not appear in, so every call fell through a `(0.001, 0.002)` default: a 903-token completion on an operator's own hardware reported `total_cost_usd=0.000999`, and that figure reached the cost dashboard, the funnel, the per-run ledger and the budget circuit breaker, which trips at `AISOC_BUDGET_HARD_USD`. Seven rules, each a structural relationship with both name spaces enumerated: every money field has the count that qualifies it and every provenance count qualifies a money field; every column the writer writes is added by migration 063 and every column 063 adds is written or read; neither pricing table carries a fallback rate and neither can key on an alias; the two gateway headers read are the ones carrying a **total**, not the five sharing their prefix that carry a component, an adjustment or a *percentage*; every provenance field on the wire exists on both the Python and TypeScript sides, which cannot import one another; and a console surface that renders a currency amount consults a provenance count first. Every parser is AST- or comment-aware, proven by nine blind-spot cases built from text already in the corpus — `gateway_cost.py`'s docstring enumerates all seven cost headers to explain why five are refused, `cost_telemetry.py`'s docstring names the removed `(0.001, 0.002)` default, the migration's `COMMENT ON COLUMN` statements repeat every column name, and `api.ts` documents fields in comments above them — a line regex credits all of them) + `services/agents/tests/test_cost_provenance.py` (22 cases, header fixtures captured from a real gateway) + `apps/web/src/components/admin/CostDashboardView.test.tsx` (first-paint assertion that a window with 1,287 unmeasured calls renders no `$` at all) | GATED | A measured `0.0` — what a local model genuinely costs — is a value and is reported as one; only an *absence* renders as not measured |## Summary-- GATED: 130+- GATED: 131- PARTIAL: 8- NO GATE: 0 (**every claim is backed by a failing test.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The remaining PARTIAL rows are honest, named deferrals — each states the specific gap and what closes it — not unproven claims.)diff --git a/docs/decisions/0006-llm-gateway-in-core.md b/docs/decisions/0006-llm-gateway-in-core.mdnew file mode 100644index 000000000..a5aed06af--- /dev/null+++ b/docs/decisions/0006-llm-gateway-in-core.md@@ -0,0 +1,116 @@+# ADR-0006 — The LLM gateway belongs in the CORE profile++- **Status:** accepted+- **Date:** 2026-09-24+- **Supersedes:** the `profiles: ["full"]` marking on the `litellm` service in `docker-compose.yml`++## Context++`litellm` was a `full`-profile service, on the stated reasoning that the+gateway is "only needed when a provider key is configured".++The reasoning skipped a step. Every task role in this product resolves to an+`aisoc-<role>` alias, and an alias means something to the bundled gateway and+to nothing else (`services/agents/app/llm/routing.py`). So a CORE deployment+could not do AI triage **with** a key either. Before PR #829 the alias went to+`api.openai.com`, which 404s, and the caller's `except` rendered that as "no+LLM available". After #829 it fails with a connection error naming the absent+gateway — honest, and still broken.++CORE is what `make up` starts, what the quickstart walks a new evaluator+through, and what the README calls "the smallest deployment that takes a real+event and produces a real alert". The README's own profile table said CORE+gave you "triage". An evaluator following the documented path could not see+the product's central claim work, and would not have been told why.++This is a real trade-off, not an obvious fix: the repository's stated+principle is that CORE is the smallest *genuinely useful* deployment, and+every service added to it is paid for by every self-hoster.++## What was measured, rather than assumed++The convenient framing is "one lightweight container". That is false, and the+numbers matter to the decision:++| | Measured |+|---|---|+| `ghcr.io/berriai/litellm:main-stable` image | **1.67 GB** |+| Idle resident memory | **451 MiB** |+| For comparison — `aisoc-core-api` / `aisoc-agents` images | 1.31 GB / 1.69 GB |+| CORE service count | 10 → **11** |++451 MiB is roughly 7.5% of CORE's ~6 GB budget. The gateway is comparable in+size to the services already in CORE; it is not free.++Two other properties were verified rather than taken from a comment:++- **It boots with no provider key.** Running the bundled+ `infra/litellm/config.yaml` with `OPENAI_API_KEY=` and `ANTHROPIC_API_KEY=`+ empty, the container reaches `running`, serves all seven aliases, and+ answers `/health/liveliness` with `"I'm alive!"`. So adding it to CORE+ cannot break a keyless install.+- **It is the only party that can report a cost.** The real per-call figure+ comes off the gateway's response headers (`x-litellm-response-cost`,+ `x-litellm-model-name`); a provider called directly returns no such header.++## Decision++**Move `litellm` into CORE**, unconditionally — no `profiles:` key, so it+starts with `docker compose up` and `make up`. `full` is unchanged, because a+service in no profile is included in every profile run.++### Why not leave it in `full`++Because then the documented first run cannot demonstrate the product's central+claim, and the only honest fix would be to stop claiming CORE does triage —+which trades a broken capability for a diminished one. The evaluator still+never sees the AI.++### Why not start it conditionally when a key is present++A `Makefile` conditional (`--profile llm` when `OPENAI_API_KEY` is set) looks+strictly better and is not, for two reasons:++1. **It relocates the manual step rather than removing it.** An operator who+ runs `make up`, then adds a key to `.env`, has a running stack with no+ gateway and must know to re-run `make up`. Supplying a key should make AI+ work, not make AI work *after* you remember a second command.+2. **It makes `make up` and `docker compose up` disagree.** The compose file+ is the documented alternative to Make; a conditional that lives only in the+ Makefile means the same repository behaves differently depending on which+ documented command you ran. Two paths that disagree about what is running+ is a defect class this repository has repeatedly had to dig out.++### Why not route the evaluator somewhere else++Sending a new user to `full` (30 services, ~12 GB) to see the headline feature+inverts the on-ramp: the profile that exists to be the easy first run stops+being the one that shows the product. And it does not fix the underlying+statement — CORE would still be documented as doing triage it cannot do.++## Consequences++- CORE gains a container: 11 services, and the README's RAM figure moves from+ ~6 GB to ~6.5 GB. Both numbers are corrected in the profile table rather+ than left stale.+- AI triage works in CORE the moment an operator supplies a provider key, with+ no further step and no profile change.+- With no key, behaviour is unchanged: the gateway idles, and AiSOC uses its+ deterministic path. The documentation says this plainly rather than implying+ AI is running.+- The default install can now report a **measured** LLM cost. Previously a+ CORE deployment had no gateway, so the cost figure was structurally+ unmeasurable there — see `services/agents/app/core/gateway_cost.py`.+- Self-hosters who genuinely never want the gateway can stop that one service;+ nothing else depends on it, and every caller degrades to the deterministic+ path.++## Corrected alongside this++While editing the profile table, the `full` row's service count was checked+against the tree and was wrong: `make up-full` runs `--profile full`, which is+**21** services. The published 30 is the count with `full` *plus* the+`monitoring`, `chatops`, `extras` and `osquery` profiles — which `make up-full`+does not start. Corrected rather than left, since the table is being edited+anyway and a published number that is not true is the thing this repository+keeps having to find.diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex c8362f32e..1451cac1a 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -16984,9 +16984,20 @@ components:recorded_cost_usd:type: numbertitle: Recorded Cost Usd+ recorded_is_measured:+ type: boolean+ title: Recorded Is Measuredimputed_public_cost_usd:type: numbertitle: Imputed Public Cost Usd+ imputed_is_estimable:+ type: boolean+ title: Imputed Is Estimable+ default: false+ unpriced_tokens:+ type: integer+ title: Unpriced Tokens+ default: 0savings_usd:type: numbertitle: Savings Usd@@ -16995,10 +17006,11 @@ components:- is_byok_active- provider- recorded_cost_usd+ - recorded_is_measured- imputed_public_cost_usd- savings_usdtitle: ByokSavings- description: 'Imputed savings vs hosted pricing.+ description: 'Imputed savings vs hosted pricing — an estimate, labelled everywhere.``is_byok_active`` is True when the live LLM provider (per@@ -17009,7 +17021,22 @@ components:computed (so the UI can show "if you switched to BYOK, you''d save- ~X") but should be labelled "potential savings" in the UI.'+ ~X") but should be labelled "potential savings" in the UI.+++ ``imputed_is_estimable`` is False when no row in the window names a model++ with a public list price, and then ``imputed_public_cost_usd`` and++ ``savings_usd`` are ``0.0`` because there is nothing to compute, not++ because the answer is zero. They used to be real-looking numbers in that++ case, built from a default rate applied to a gateway alias, and the BYOK++ panel announced savings against it — an invented saving on invented spend.++ ``unpriced_tokens`` says how much of the window the estimate omits.'CalibrationBucket:properties:predicted_lower:@@ -17953,6 +17980,22 @@ components:total_cost_usd:type: numbertitle: Total Cost Usd+ measured_call_count:+ type: integer+ title: Measured Call Count+ default: 0+ estimated_cost_usd:+ type: number+ title: Estimated Cost Usd+ default: 0.0+ estimated_call_count:+ type: integer+ title: Estimated Call Count+ default: 0+ unpriced_call_count:+ type: integer+ title: Unpriced Call Count+ default: 0total_latency_ms:type: integertitle: Total Latency Ms@@ -17984,6 +18027,22 @@ components:total_cost_usd:type: numbertitle: Total Cost Usd+ measured_call_count:+ type: integer+ title: Measured Call Count+ default: 0+ estimated_cost_usd:+ type: number+ title: Estimated Cost Usd+ default: 0.0+ estimated_call_count:+ type: integer+ title: Estimated Call Count+ default: 0+ unpriced_call_count:+ type: integer+ title: Unpriced Call Count+ default: 0total_tokens:type: integertitle: Total Tokens@@ -17997,7 +18056,14 @@ components:- total_tokens- call_counttitle: CostBucket- description: LLM spend bucketed by day.+ description: 'LLM spend bucketed by day.+++ ``total_cost_usd`` is measured cost. ``measured_call_count`` says how much++ of the day''s traffic that covers, so a bar of height zero can be read as++ "a free day" or "an unmeasured day" rather than silently as the first.'CostDashboard:properties:tenant_id:@@ -18043,6 +18109,22 @@ components:total_cost_usd:type: numbertitle: Total Cost Usd+ measured_call_count:+ type: integer+ title: Measured Call Count+ default: 0+ estimated_cost_usd:+ type: number+ title: Estimated Cost Usd+ default: 0.0+ estimated_call_count:+ type: integer+ title: Estimated Call Count+ default: 0+ unpriced_call_count:+ type: integer+ title: Unpriced Call Count+ default: 0total_tokens:type: integertitle: Total Tokens@@ -18065,6 +18147,14 @@ components:- total_runs- avg_cost_per_run_usdtitle: CostHeadline+ description: 'Window totals, each with the count of calls it was computed over.+++ ``total_cost_usd`` is **measured** spend. When ``measured_call_count`` is++ zero it is not a total of anything and the console must render "not++ measured" — the same contract the MTTR tiles use.'CoverageCell:properties:techniqueId:@@ -22699,6 +22789,11 @@ components:model:type: stringtitle: Model+ resolved_model:+ anyOf:+ - type: string+ - type: 'null'+ title: Resolved Modelruns:type: integertitle: Runs@@ -22714,9 +22809,33 @@ components:total_cost_usd:type: numbertitle: Total Cost Usd+ measured_call_count:+ type: integer+ title: Measured Call Count+ default: 0+ estimated_cost_usd:+ type: number+ title: Estimated Cost Usd+ default: 0.0+ estimated_call_count:+ type: integer+ title: Estimated Call Count+ default: 0+ unpriced_call_count:+ type: integer+ title: Unpriced Call Count+ default: 0imputed_public_cost_usd:type: numbertitle: Imputed Public Cost Usd+ imputed_is_estimable:+ type: boolean+ title: Imputed Is Estimable+ default: false+ unpriced_tokens:+ type: integer+ title: Unpriced Tokens+ default: 0avg_latency_ms:anyOf:- type: number@@ -22739,6 +22858,11 @@ components:model:type: stringtitle: Model+ resolved_model:+ anyOf:+ - type: string+ - type: 'null'+ title: Resolved Modeltotal_prompt_tokens:type: integertitle: Total Prompt Tokens@@ -22748,6 +22872,22 @@ components:total_cost_usd:type: numbertitle: Total Cost Usd+ measured_call_count:+ type: integer+ title: Measured Call Count+ default: 0+ estimated_cost_usd:+ type: number+ title: Estimated Cost Usd+ default: 0.0+ estimated_call_count:+ type: integer+ title: Estimated Call Count+ default: 0+ unpriced_call_count:+ type: integer+ title: Unpriced Call Count+ default: 0total_latency_ms:type: integertitle: Total Latency Ms@@ -25786,6 +25926,22 @@ components:total_cost_usd:type: numbertitle: Total Cost Usd+ measured_call_count:+ type: integer+ title: Measured Call Count+ default: 0+ estimated_cost_usd:+ type: number+ title: Estimated Cost Usd+ default: 0.0+ estimated_call_count:+ type: integer+ title: Estimated Call Count+ default: 0+ unpriced_call_count:+ type: integer+ title: Unpriced Call Count+ default: 0started_at:type: stringformat: date-time@@ -26027,6 +26183,22 @@ components:total_cost_usd:type: numbertitle: Total Cost Usd+ measured_call_count:+ type: integer+ title: Measured Call Count+ default: 0+ estimated_cost_usd:+ type: number+ title: Estimated Cost Usd+ default: 0.0+ estimated_call_count:+ type: integer+ title: Estimated Call Count+ default: 0+ unpriced_call_count:+ type: integer+ title: Unpriced Call Count+ default: 0started_at:type: stringformat: date-time@@ -28167,6 +28339,18 @@ components:total_cost_usd:type: numbertitle: Total Cost Usd+ measured_call_count:+ type: integer+ title: Measured Call Count+ default: 0+ estimated_cost_usd:+ type: number+ title: Estimated Cost Usd+ default: 0.0+ estimated_call_count:+ type: integer+ title: Estimated Call Count+ default: 0total_tokens:type: integertitle: Total Tokensdiff --git a/scripts/check_cost_provenance.py b/scripts/check_cost_provenance.pynew file mode 100644index 000000000..6ca8be9f4--- /dev/null+++ b/scripts/check_cost_provenance.py@@ -0,0 +1,834 @@+#!/usr/bin/env python3+"""A dollar figure must arrive with the thing that says how it is known.++Why this exists+---------------+``CostTracker`` priced a call by looking its **model name** up in a table of+hosted list prices. The name it looked up was an ``aisoc-<role>`` alias, which+is not a model — it is a label the LiteLLM gateway resolves to one. No alias+is in the table, so every call fell through a ``(0.001, 0.002)`` default and+was booked at a price nobody charges for a model nobody named. A 903-token+completion on an operator's own hardware reported ``total_cost_usd=0.000999``,+and that figure reached the cost dashboard, the funnel, the per-run ledger and+the budget circuit breaker — which trips at ``AISOC_BUDGET_HARD_USD`` and+would eventually have degraded a working local install to deterministic-only+over money nobody spent.++Nothing in a diff shows that. The number was well-formed, plausibly small, and+wrong. What was missing was not a value but a *provenance*: no caller could ask+"measured, estimated, or unknown?", so every surface assumed the first.++What it checks, in both directions+----------------------------------+Every rule is a structural relationship between two name spaces, and both are+enumerated. The dominant defect shape in this repository is the check that+compares A against B and never B against A, so drift in the direction things+actually change slips through while the check prints OK.++ MONEY <-> COUNT every money field in a response model has the count that+ qualifies it, and every provenance count qualifies a money+ field. A sum with no count cannot say "not measured"; a+ count with no sum qualifies nothing+ WRITE <-> COLUMN every provenance column the writer writes exists in the+ migration, and every provenance column the migration adds+ is written or read. A column nobody writes is a permanent+ zero that reads as "not measured" forever+ NO-DEFAULT no pricing table has a fallback rate, in either copy. The+ default *was* the defect: it turned "unknown price" into a+ confident number+ ALIAS-NEVER an alias prefix can never become a pricing key, checked in+ both the agents table and the API mirror+ HEADER-EXACT the gateway cost headers read are the two that carry a+ total, and none of the five that share their prefix but+ carry a component, an adjustment, or a *percentage*+ PY <-> TS the provenance fields on the wire exist on both sides. The+ two packages cannot import one another, so they drift+ CONSOLE a console surface that renders a currency amount from a+ cost field consults a provenance count before doing so++Usage+-----+ python3 scripts/check_cost_provenance.py # gate+ python3 scripts/check_cost_provenance.py --json+ python3 scripts/check_cost_provenance.py --self-test # prove it bites++``--repo-root`` overrides the tree under inspection. The resolved root comes+from ``git rev-parse``, every file read and every count is printed before the+verdict, and a missing or empty input is a hard error rather than a quiet+zero: a gate that reports OK about a tree it never opened is worse than none.++Stdlib only. The lint job that runs this installs ruff and mypy and nothing+else, and a gate that needs a ``pip install`` to render a verdict can be+skipped.++Exit codes: 0 clean, 1 findings, 2 the scan itself could not run.+"""++from __future__ import annotations++import argparse+import ast+import json+import re+import sys+from dataclasses import dataclass, field+from pathlib import Path++# `scripts/` is on sys.path when this file is run as a program, but not when a+# test loads it by path with importlib. gate_toolkit sits beside it either way.+sys.path.insert(0, str(Path(__file__).resolve().parent))++from gate_toolkit import repo_root, self_test_main # noqa: E402++TRACKER_REL = "services/agents/app/core/cost_telemetry.py"+GATEWAY_COST_REL = "services/agents/app/core/gateway_cost.py"+DASHBOARD_REL = "services/api/app/services/cost_dashboard.py"+INVESTIGATIONS_REL = "services/api/app/api/v1/endpoints/investigations.py"+MIGRATION_REL = "services/api/migrations/063_cost_provenance.sql"+API_TS_REL = "apps/web/src/lib/api.ts"++#: Console surfaces that render a cost to a human. Each must consult a+#: provenance count before printing a currency amount.+CONSOLE_RELS = (+ "apps/web/src/components/admin/CostDashboardView.tsx",+ "apps/web/src/components/dashboard/operations/AgentThroughputPanel.tsx",+ "apps/web/src/components/cases/InvestigationLedger.tsx",+)++#: A field name holding an amount of money.+MONEY_FIELD_RE = re.compile(r"^(?:total_|measured_|estimated_|recorded_|imputed_|savings_|avg_)?\w*?cost_usd$|^savings_usd$")++#: A field name holding the number of calls a money field was computed over.+#: `unpriced_call_count` is a provenance count with no money of its own — it+#: is the count of what could not be priced at all — so it is exempt from the+#: COUNT -> MONEY direction and named here rather than special-cased inline.+COUNT_FIELD_RE = re.compile(r"^(measured|estimated|unpriced)_call_count$")+COUNTLESS_PROVENANCE = frozenset({"unpriced_call_count"})++#: money field -> the count that qualifies it. Both directions are checked+#: against this map, so an added field must be paired here to pass.+MONEY_TO_COUNT = {+ "total_cost_usd": "measured_call_count",+ "measured_cost_usd": "measured_call_count",+ "estimated_cost_usd": "estimated_call_count",+}++#: Provenance columns. Written by the agents service, added by the migration.+PROVENANCE_COLUMNS = frozenset(+ {+ "measured_cost_usd",+ "measured_call_count",+ "estimated_cost_usd",+ "estimated_call_count",+ "unpriced_call_count",+ "resolved_model",+ }+)++#: The LiteLLM headers that carry a **total** cost. Only these may be read.+TOTAL_COST_HEADERS = frozenset({"x-litellm-response-cost", "x-litellm-response-cost-original"})++#: Headers that share the prefix and are NOT a total. `-margin-percent` is not+#: even denominated in money. A prefix match accepts all of these and produces+#: a plausible wrong number instead of an obvious absence, which is the harder+#: failure to notice.+DECOY_COST_HEADERS = frozenset(+ {+ "x-litellm-response-cost-input",+ "x-litellm-response-cost-output",+ "x-litellm-response-cost-discount-amount",+ "x-litellm-response-cost-margin-amount",+ "x-litellm-response-cost-margin-percent",+ "x-litellm-response-cost-tool-usage",+ }+)++#: Prefix of a logical gateway alias. Never a pricing key.+ALIAS_PREFIX = "aisoc-"++#: Pricing tables, by file, that must contain no alias and no default rate.+PRICING_TABLES = {TRACKER_REL: "_PRICING", DASHBOARD_REL: "_PUBLIC_PRICING"}+++class GateError(RuntimeError):+ """The scan could not be performed — distinct from the scan finding nothing."""+++@dataclass+class Finding:+ code: str+ detail: str++ def __str__(self) -> str:+ return f"[{self.code}] {self.detail}"+++@dataclass+class Corpus:+ """Everything the gate read, named, so a caller cannot lose which tree."""++ files_read: list[str] = field(default_factory=list)+ #: model name -> ({field name}, on_the_wire) for every class carrying money+ py_models: dict[str, tuple[set[str], bool]] = field(default_factory=dict)+ ts_interfaces: dict[str, set[str]] = field(default_factory=dict)+ written_columns: set[str] = field(default_factory=set)+ migration_columns: set[str] = field(default_factory=set)+ read_columns: set[str] = field(default_factory=set)+ pricing_keys: dict[str, set[str]] = field(default_factory=dict)+ pricing_defaults: dict[str, list[str]] = field(default_factory=dict)+ headers_read: set[str] = field(default_factory=set)+ console_guards: dict[str, bool] = field(default_factory=dict)++ def counts(self) -> dict[str, int]:+ return {+ "files_read": len(self.files_read),+ "python_models": len(self.py_models),+ "typescript_interfaces": len(self.ts_interfaces),+ "columns_written": len(self.written_columns),+ "columns_in_migration": len(self.migration_columns),+ "pricing_tables": len(self.pricing_keys),+ "cost_headers_read": len(self.headers_read),+ "console_surfaces": len(self.console_guards),+ }+++# --------------------------------------------------------------------------+# Parsing.+#+# Every parser below is AST- or structure-aware, never a bare regex over raw+# source, because each corpus contains text shaped exactly like what the gate+# looks for:+#+# * ``gateway_cost.py``'s module docstring **enumerates all seven**+# ``x-litellm-response-cost*`` headers in a table explaining why five are+# refused. A line regex reads that as the code reading them, and credits+# the gate's own documentation of a blind spot as the blind spot.+# * ``cost_telemetry.py``'s docstring shows ``total_cost_usd=0.000999`` and+# names ``(0.001, 0.002)`` while describing the defect it removed. A+# regex for a default rate fires on the explanation of the default rate.+# * ``api.ts`` carries doc comments naming ``measured_call_count`` above+# fields, so a comment can satisfy a field requirement it does not meet.+# * The migration's own ``COMMENT ON COLUMN`` statements repeat every+# column name in prose.+#+# The self-test injects each of those shapes and requires the parser to+# decline to credit it.+# --------------------------------------------------------------------------+++def _read(root: Path, rel: str, corpus: Corpus) -> str:+ path = root / rel+ if not path.is_file():+ raise GateError(f"missing input: {rel} (looked in {root})")+ text = path.read_text(encoding="utf-8", errors="replace")+ if not text.strip():+ raise GateError(f"empty input: {rel}")+ corpus.files_read.append(rel)+ return text+++def _parse_python(text: str, rel: str) -> ast.Module:+ try:+ return ast.parse(text)+ except SyntaxError as exc:+ raise GateError(f"{rel}: could not parse: {exc}") from exc+++def parse_py_models(text: str, rel: str) -> dict[str, tuple[set[str], bool]]:+ """Class name -> (annotated field names, is-on-the-wire), for money classes.++ AST, so a field named only in a docstring or a comment is not a field.++ The second element is whether the class inherits ``BaseModel``, i.e.+ whether it is serialised to a client. Only those are reconciled against+ TypeScript: an internal dataclass like ``CostRow`` mirrors a database row+ and has no business appearing in ``api.ts``. Discriminating on the base+ class rather than on a name convention means a new response model is+ reconciled automatically and a new internal row is not falsely demanded.+ """+ tree = _parse_python(text, rel)+ out: dict[str, tuple[set[str], bool]] = {}+ for node in ast.walk(tree):+ if not isinstance(node, ast.ClassDef):+ continue+ fields = {stmt.target.id for stmt in node.body if isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name)}+ if not any(MONEY_FIELD_RE.match(f) for f in fields):+ continue+ bases = {b.id for b in node.bases if isinstance(b, ast.Name)} | {b.attr for b in node.bases if isinstance(b, ast.Attribute)}+ out[f"{rel}::{node.name}"] = (fields, "BaseModel" in bases)+ return out+++def parse_ts_interfaces(text: str) -> dict[str, set[str]]:+ """Interface name -> field names, comments stripped.++ Block and line comments go first so a documented-but-absent field cannot+ satisfy a requirement, and neither can a commented-out one.+ """+ stripped = re.sub(r"/\*.*?\*/", "", text, flags=re.DOTALL)+ stripped = re.sub(r"^\s*//.*$", "", stripped, flags=re.MULTILINE)++ out: dict[str, set[str]] = {}+ for match in re.finditer(r"export\s+interface\s+(\w+)\s*(?:extends\s+\w+\s*)?\{", stripped):+ name = match.group(1)+ depth, i = 1, match.end()+ while i < len(stripped) and depth:+ if stripped[i] == "{":+ depth += 1+ elif stripped[i] == "}":+ depth -= 1+ i += 1+ body = stripped[match.end() : i - 1]+ fields = set(re.findall(r"^\s*(\w+)\??\s*:", body, flags=re.MULTILINE))+ if any(MONEY_FIELD_RE.match(f) for f in fields):+ out[name] = fields+ return out+++def parse_sql_columns(text: str) -> set[str]:+ """Columns an ``ALTER TABLE ... ADD COLUMN`` actually adds.++ Driven off the ADD COLUMN clause rather than a name scan, so the+ ``COMMENT ON COLUMN`` statements — which repeat every column name in+ prose, and are the point of the file being readable — are not credited as+ adding anything. Line comments are stripped first.+ """+ without_comments = re.sub(r"^\s*--.*$", "", text, flags=re.MULTILINE)+ return {m.group(1) for m in re.finditer(r"ADD\s+COLUMN\s+(?:IF\s+NOT\s+EXISTS\s+)?(\w+)", without_comments, re.IGNORECASE)}+++def parse_written_columns(text: str, rel: str) -> set[str]:+ """Provenance columns named inside SQL string literals in Python code.++ Only string constants are considered, so a column named in a docstring is+ not a write... except that a docstring *is* a string constant. The+ discriminator is that a write names the column inside a statement that+ also contains INSERT, UPDATE or SELECT, which a prose docstring does not.+ """+ tree = _parse_python(text, rel)+ found: set[str] = set()+ for node in ast.walk(tree):+ if not isinstance(node, ast.Constant) or not isinstance(node.value, str):+ continue+ blob = node.value+ if not re.search(r"\b(INSERT|UPDATE|SELECT)\b", blob, re.IGNORECASE):+ continue+ for column in PROVENANCE_COLUMNS:+ if re.search(rf"\b{re.escape(column)}\b", blob):+ found.add(column)+ return found+++def parse_pricing_table(text: str, rel: str, table_name: str) -> tuple[set[str], list[str]]:+ """(keys, default-rate sites) for a pricing dict, from the AST.++ A "default-rate site" is a ``.get(key, <2-tuple of numbers>)`` on the+ table, or a module constant whose value is a 2-tuple of numbers and whose+ name mentions default and price. Both are the shape that turns "unknown+ price" into a confident number. Found structurally, so the docstring that+ *describes* the removed ``(0.001, 0.002)`` default is not a finding.+ """+ tree = _parse_python(text, rel)+ keys: set[str] = set()+ defaults: list[str] = []++ for node in ast.walk(tree):+ if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.target.id == table_name:+ if isinstance(node.value, ast.Dict):+ keys = {k.value for k in node.value.keys if isinstance(k, ast.Constant) and isinstance(k.value, str)}+ elif isinstance(node, ast.Assign) and isinstance(node.value, ast.Dict):+ for target in node.targets:+ if isinstance(target, ast.Name) and target.id == table_name:+ keys = {k.value for k in node.value.keys if isinstance(k, ast.Constant) and isinstance(k.value, str)}++ # `.get(x, (a, b))` on the table — a default rate by any other name.+ if (+ isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and node.func.attr == "get"+ and isinstance(node.func.value, ast.Name)+ and node.func.value.id == table_name+ and len(node.args) == 2+ ):+ fallback = node.args[1]+ if _is_rate_tuple(fallback) or isinstance(fallback, ast.Name):+ defaults.append(f"{table_name}.get(..., {ast.unparse(fallback)})")++ # A module constant holding a rate pair, named like a default.+ if isinstance(node, ast.AnnAssign | ast.Assign):+ assigned = node.value+ if assigned is None or not _is_rate_tuple(assigned):+ continue+ names = _assigned_names(node)+ for name in names:+ if "DEFAULT" in name.upper() and ("PRIC" in name.upper() or "RATE" in name.upper()):+ defaults.append(f"{name} = {ast.unparse(assigned)}")+ return keys, defaults+++def _assigned_names(node: ast.AnnAssign | ast.Assign) -> list[str]:+ """Plain names this statement assigns to."""+ if isinstance(node, ast.AnnAssign):+ return [node.target.id] if isinstance(node.target, ast.Name) else []+ return [t.id for t in node.targets if isinstance(t, ast.Name)]+++def _is_rate_tuple(node: ast.AST | None) -> bool:+ return (+ isinstance(node, ast.Tuple)+ and len(node.elts) == 2+ and all(isinstance(e, ast.Constant) and isinstance(e.value, int | float) for e in node.elts)+ )+++def parse_headers_read(text: str, rel: str) -> set[str]:+ """Cost headers the extractor actually reads.++ Taken from the ``COST_HEADERS`` tuple's elements via the AST. The module+ docstring lists all seven headers in a table — five of them to explain why+ they are refused — so a line regex over this file credits the code with+ reading the very decoys the code exists to decline.+ """+ tree = _parse_python(text, rel)+ for node in ast.walk(tree):+ if not isinstance(node, ast.AnnAssign | ast.Assign):+ continue+ if "COST_HEADERS" not in _assigned_names(node):+ continue+ assigned = node.value+ if isinstance(assigned, ast.Tuple):+ return {e.value for e in assigned.elts if isinstance(e, ast.Constant) and isinstance(e.value, str)}+ raise GateError(f"{rel}: COST_HEADERS tuple not found — cannot tell which headers are read")+++def parse_console_guard(text: str) -> bool:+ """Whether a console surface consults a provenance count.++ Comments stripped first: this file's own explanation of why the guard+ exists names the guard, and would otherwise satisfy the requirement it+ describes. A JSX/TS surface that formats currency from a cost field must+ reference a provenance count in live code.+ """+ stripped = re.sub(r"/\*.*?\*/", "", text, flags=re.DOTALL)+ stripped = re.sub(r"^\s*//.*$", "", stripped, flags=re.MULTILINE)+ renders_currency = bool(re.search(r"\$\{?[^}\n]*cost", stripped) or re.search(r"fmtUsd|formatUsd|fmtSpend", stripped))+ consults_count = bool(re.search(r"measured_call_count|measuredCalls|measuredCount|spendProvenance|fmtSpend", stripped))+ return (not renders_currency) or consults_count+++# --------------------------------------------------------------------------+# Collection+# --------------------------------------------------------------------------+++def collect(root: Path) -> Corpus:+ corpus = Corpus()++ tracker = _read(root, TRACKER_REL, corpus)+ gateway = _read(root, GATEWAY_COST_REL, corpus)+ dashboard = _read(root, DASHBOARD_REL, corpus)+ investigations = _read(root, INVESTIGATIONS_REL, corpus)+ migration = _read(root, MIGRATION_REL, corpus)+ api_ts = _read(root, API_TS_REL, corpus)++ for rel, text in ((DASHBOARD_REL, dashboard), (INVESTIGATIONS_REL, investigations)):+ corpus.py_models.update(parse_py_models(text, rel))+ corpus.ts_interfaces = parse_ts_interfaces(api_ts)++ corpus.migration_columns = parse_sql_columns(migration)+ corpus.written_columns = parse_written_columns(tracker, TRACKER_REL)+ corpus.read_columns = parse_written_columns(dashboard, DASHBOARD_REL) | parse_written_columns(investigations, INVESTIGATIONS_REL)++ for rel, table in PRICING_TABLES.items():+ text = tracker if rel == TRACKER_REL else dashboard+ keys, defaults = parse_pricing_table(text, rel, table)+ corpus.pricing_keys[rel] = keys+ corpus.pricing_defaults[rel] = defaults++ corpus.headers_read = parse_headers_read(gateway, GATEWAY_COST_REL)++ for rel in CONSOLE_RELS:+ corpus.console_guards[rel] = parse_console_guard(_read(root, rel, corpus))++ return corpus+++# --------------------------------------------------------------------------+# Rules — every one enumerated in both directions+# --------------------------------------------------------------------------+++def evaluate(corpus: Corpus) -> list[Finding]:+ findings: list[Finding] = []++ # MONEY -> COUNT, and COUNT -> MONEY. Applies to every money-carrying+ # class, internal rows included: a row that loses its count silently+ # re-enters the sums as measured.+ for model, (fields, _on_wire) in sorted(corpus.py_models.items()):+ for money, count in MONEY_TO_COUNT.items():+ if money in fields and count not in fields:+ findings.append(+ Finding("MONEY-WITHOUT-COUNT", f"{model} carries `{money}` with no `{count}` — it cannot say 'not measured'")+ )+ for f in sorted(fields):+ if COUNT_FIELD_RE.match(f) and f not in COUNTLESS_PROVENANCE:+ qualified = [m for m, c in MONEY_TO_COUNT.items() if c == f]+ if not any(m in fields for m in qualified):+ findings.append(Finding("COUNT-WITHOUT-MONEY", f"{model} carries `{f}` qualifying no money field"))++ # WRITE -> COLUMN, and COLUMN -> WRITE/READ.+ for column in sorted(corpus.written_columns - corpus.migration_columns):+ findings.append(Finding("WRITE-NO-COLUMN", f"`{column}` is written by the agents service and no migration adds it"))+ touched = corpus.written_columns | corpus.read_columns+ for column in sorted(corpus.migration_columns & PROVENANCE_COLUMNS - touched):+ findings.append(+ Finding("COLUMN-NO-WRITE", f"migration adds `{column}` and nothing writes or reads it — a permanent unmeasured zero")+ )++ # NO-DEFAULT, and ALIAS-NEVER, over both pricing tables.+ for rel, defaults in sorted(corpus.pricing_defaults.items()):+ for site in defaults:+ findings.append(Finding("DEFAULT-RATE", f"{rel}: `{site}` supplies a fallback price — an unknown model must impute nothing"))+ for rel, keys in sorted(corpus.pricing_keys.items()):+ if not keys:+ findings.append(Finding("EMPTY-PRICING", f"{rel}: pricing table parsed as empty — the parser or the table is wrong"))+ for key in sorted(k for k in keys if k.lower().startswith(ALIAS_PREFIX)):+ findings.append(Finding("ALIAS-PRICED", f"{rel}: `{key}` is a gateway alias and cannot carry a price"))++ # HEADER-EXACT, both directions.+ for header in sorted(corpus.headers_read - TOTAL_COST_HEADERS):+ kind = "a component/adjustment, not a total" if header in DECOY_COST_HEADERS else "not a known cost header"+ findings.append(Finding("HEADER-NOT-A-TOTAL", f"`{header}` is read as a cost and is {kind}"))+ for header in sorted(TOTAL_COST_HEADERS - corpus.headers_read):+ findings.append(Finding("HEADER-TOTAL-UNREAD", f"`{header}` carries a total and is not read — some gateway versions emit only it"))++ # PY <-> TS.+ # Only classes actually serialised to a client. An internal dataclass+ # mirrors a database row, not the wire, and demanding it appear in api.ts+ # would be the gate inventing a requirement rather than checking one.+ py_fields = {+ f for fields, on_wire in corpus.py_models.values() if on_wire for f in fields if MONEY_FIELD_RE.match(f) or COUNT_FIELD_RE.match(f)+ }+ ts_fields = {f for fields in corpus.ts_interfaces.values() for f in fields if MONEY_FIELD_RE.match(f) or COUNT_FIELD_RE.match(f)}+ if not corpus.ts_interfaces:+ findings.append(Finding("EMPTY-TS", f"{API_TS_REL}: no money-carrying interface parsed — the parser or the file is wrong"))+ for name in sorted(py_fields - ts_fields):+ findings.append(Finding("PY-NOT-IN-TS", f"`{name}` is on the wire from Python and absent from {API_TS_REL}"))+ for name in sorted(ts_fields - py_fields):+ findings.append(Finding("TS-NOT-IN-PY", f"`{name}` is declared in {API_TS_REL} and no Python model sends it"))++ # CONSOLE.+ for rel, guarded in sorted(corpus.console_guards.items()):+ if not guarded:+ findings.append(Finding("CONSOLE-UNGUARDED", f"{rel} renders a currency amount without consulting a provenance count"))++ return findings+++# --------------------------------------------------------------------------+# Self-test+# --------------------------------------------------------------------------+++def _self_test_cases() -> list[tuple[str, bool]]:+ """Injected defects and parser blind spots, each caught by its own code.++ Every corpus is built with a fresh constructor call rather than mutating a+ shared baseline. PR #829's self-test shallow-copied its nested corpora, so+ one case poisoned the baseline and every later case "caught" three codes it+ had inherited — a self-test that passes for the wrong reason is the gate's+ own defect one level up.+ """++ def baseline() -> Corpus:+ """A clean corpus, constructed fresh every call. No shared mutables."""+ c = Corpus()+ c.files_read = list(CONSOLE_RELS)+ c.py_models = {+ f"{DASHBOARD_REL}::CostHeadline": (+ {+ "total_cost_usd",+ "measured_call_count",+ "estimated_cost_usd",+ "estimated_call_count",+ "unpriced_call_count",+ },+ True,+ )+ }+ c.ts_interfaces = {+ "CostHeadline": {+ "total_cost_usd",+ "measured_call_count",+ "estimated_cost_usd",+ "estimated_call_count",+ "unpriced_call_count",+ }+ }+ c.written_columns = set(PROVENANCE_COLUMNS)+ c.migration_columns = set(PROVENANCE_COLUMNS)+ c.read_columns = set(PROVENANCE_COLUMNS)+ c.pricing_keys = {TRACKER_REL: {"gpt-4o"}, DASHBOARD_REL: {"gpt-4o"}}+ c.pricing_defaults = {TRACKER_REL: [], DASHBOARD_REL: []}+ c.headers_read = set(TOTAL_COST_HEADERS)+ c.console_guards = dict.fromkeys(CONSOLE_RELS, True)+ return c++ cases: list[tuple[str, bool]] = []++ # The baseline must itself be clean, or every case below proves nothing.+ base_findings = evaluate(baseline())+ cases.append(("a clean corpus produces no findings (the baseline is not pre-poisoned)", not base_findings))++ def caught(description: str, mutate, code: str) -> None:+ c = baseline()+ mutate(c)+ codes = {f.code for f in evaluate(c)}+ cases.append((f"{description} -> {code}", code in codes))++ # --- injected defects, one per rule, both directions ------------------+ def drop_count(c: Corpus) -> None:+ c.py_models[f"{DASHBOARD_REL}::CostHeadline"][0].discard("measured_call_count")++ caught("a money field loses the count that qualifies it", drop_count, "MONEY-WITHOUT-COUNT")++ def orphan_count(c: Corpus) -> None:+ c.py_models[f"{DASHBOARD_REL}::CostHeadline"][0].discard("estimated_cost_usd")++ caught("a provenance count qualifies no money field", orphan_count, "COUNT-WITHOUT-MONEY")++ caught(+ "a column is written with no migration adding it",+ lambda c: c.migration_columns.discard("measured_cost_usd"),+ "WRITE-NO-COLUMN",+ )+ caught(+ "a migration adds a column nothing writes or reads",+ lambda c: (c.written_columns.discard("resolved_model"), c.read_columns.discard("resolved_model")),+ "COLUMN-NO-WRITE",+ )+ caught(+ "a pricing table regains a fallback rate",+ lambda c: c.pricing_defaults[TRACKER_REL].append("_DEFAULT_PRICE = (0.001, 0.002)"),+ "DEFAULT-RATE",+ )+ caught(+ "a gateway alias becomes a pricing key",+ lambda c: c.pricing_keys[DASHBOARD_REL].add("aisoc-triage"),+ "ALIAS-PRICED",+ )+ caught(+ "a component header is read as if it were a total",+ lambda c: c.headers_read.add("x-litellm-response-cost-margin-percent"),+ "HEADER-NOT-A-TOTAL",+ )+ caught(+ "a header that carries a total stops being read",+ lambda c: c.headers_read.discard("x-litellm-response-cost"),+ "HEADER-TOTAL-UNREAD",+ )+ caught(+ "a provenance field exists in Python and not TypeScript",+ lambda c: c.ts_interfaces["CostHeadline"].discard("unpriced_call_count"),+ "PY-NOT-IN-TS",+ )+ caught(+ "a provenance field exists in TypeScript and not Python",+ lambda c: c.ts_interfaces["CostHeadline"].add("recorded_cost_usd"),+ "TS-NOT-IN-PY",+ )+ caught(+ "a console surface prints currency with no provenance guard",+ lambda c: c.console_guards.__setitem__(CONSOLE_RELS[0], False),+ "CONSOLE-UNGUARDED",+ )+ caught("a pricing table parses as empty", lambda c: c.pricing_keys.__setitem__(TRACKER_REL, set()), "EMPTY-PRICING")+ caught("no TypeScript interface parses", lambda c: c.ts_interfaces.clear(), "EMPTY-TS")++ # --- parser blind spots: what the parser CREDITS, not what it flags ----+ # Each of these is text shaped exactly like the thing the gate looks for.+ # A line regex credits every one of them.++ docstring_headers = '''+"""Doc table explaining the decoys:++ x-litellm-response-cost-input a component+ x-litellm-response-cost-margin-percent a percentage, not money+"""+COST_HEADERS: tuple[str, ...] = ("x-litellm-response-cost", "x-litellm-response-cost-original")+'''+ cases.append(+ (+ "a docstring enumerating the five decoy headers is not credited as reading them",+ parse_headers_read(docstring_headers, "probe.py") == set(TOTAL_COST_HEADERS),+ )+ )++ described_default = '''+_PRICING: dict[str, tuple[float, float]] = {"gpt-4o": (0.005, 0.015)}+# The removed default was (0.001, 0.002) and it priced an alias.+def _estimate(model):+ """Previously fell through to _DEFAULT_PRICE = (0.001, 0.002); now returns None."""+ return _PRICING.get(model)+'''+ keys, defaults = parse_pricing_table(described_default, "probe.py", "_PRICING")+ cases.append(+ (+ "a docstring and comment describing the removed default rate are not findings",+ keys == {"gpt-4o"} and defaults == [],+ )+ )++ real_default = """+_PRICING: dict[str, tuple[float, float]] = {"gpt-4o": (0.005, 0.015)}+def _estimate(model):+ return _PRICING.get(model, (0.001, 0.002))+"""+ _, real_defaults = parse_pricing_table(real_default, "probe.py", "_PRICING")+ cases.append(("an inline `.get(k, (a, b))` default rate IS caught, not just a named constant", bool(real_defaults)))++ commented_ts = """+export interface CostHeadline {+ total_cost_usd: number;+ /** measured_call_count: number; — documented but absent */+ // estimated_call_count: number;+}+"""+ parsed_ts = parse_ts_interfaces(commented_ts)+ cases.append(+ (+ "a TS field named only in a comment or commented out is not credited as declared",+ parsed_ts.get("CostHeadline") == {"total_cost_usd"},+ )+ )++ comment_only_sql = """+-- ADD COLUMN IF NOT EXISTS measured_cost_usd DOUBLE PRECISION+ALTER TABLE t ADD COLUMN IF NOT EXISTS estimated_cost_usd DOUBLE PRECISION NOT NULL DEFAULT 0;+COMMENT ON COLUMN t.measured_call_count IS 'calls the sum covers';+"""+ cases.append(+ (+ "a commented-out ADD COLUMN and a COMMENT ON COLUMN are not credited as adding columns",+ parse_sql_columns(comment_only_sql) == {"estimated_cost_usd"},+ )+ )++ docstring_column = '''+def persist():+ """Writes measured_cost_usd and resolved_model to aisoc_run_costs."""+ conn.execute("UPDATE aisoc_run_costs SET estimated_cost_usd = $1")+'''+ cases.append(+ (+ "a docstring naming columns is not credited as writing them",+ parse_written_columns(docstring_column, "probe.py") == {"estimated_cost_usd"},+ )+ )++ comment_guard = """+// measured_call_count guards this, honest+export function Cell() { return <span>{fmtUsd(row.total_cost_usd)}</span>; }+"""+ cases.append(+ (+ "a console guard named only in a comment does not satisfy the guard requirement",+ parse_console_guard(comment_guard) is False,+ )+ )++ docstring_model = '''+class NotAModel:+ """Has total_cost_usd and measured_call_count in prose only."""+'''+ cases.append(+ (+ "a class naming money fields only in its docstring is not parsed as a model",+ parse_py_models(docstring_model, "probe.py") == {},+ )+ )++ wire_vs_internal = """+from pydantic import BaseModel++class OnTheWire(BaseModel):+ total_cost_usd: float+ measured_call_count: int++@dataclass(frozen=True)+class InternalRow:+ measured_cost_usd: float+ measured_call_count: int+"""+ parsed = parse_py_models(wire_vs_internal, "probe.py")+ cases.append(+ (+ "a BaseModel is on the wire and a dataclass is not, so TS reconciliation skips the row",+ parsed["probe.py::OnTheWire"][1] is True and parsed["probe.py::InternalRow"][1] is False,+ )+ )++ # ... and that the distinction actually changes the verdict, not just the+ # parse. An internal row whose fields are absent from TypeScript must not+ # be reported, while a wire model's must.+ internal_only = baseline()+ internal_only.py_models["probe::InternalRow"] = ({"measured_cost_usd", "measured_call_count"}, False)+ cases.append(+ (+ "an internal row's fields are not demanded of api.ts",+ "PY-NOT-IN-TS" not in {f.code for f in evaluate(internal_only)},+ )+ )++ return cases+++# --------------------------------------------------------------------------+# CLI+# --------------------------------------------------------------------------+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--repo-root", type=Path, default=None)+ parser.add_argument("--json", action="store_true", dest="as_json")+ parser.add_argument("--self-test", action="store_true")+ args = parser.parse_args(argv)++ if args.self_test:+ return self_test_main(Path(__file__).name, extra=_self_test_cases())++ root = args.repo_root.resolve() if args.repo_root else repo_root()+ try:+ corpus = collect(root)+ except GateError as exc:+ print(f"check_cost_provenance: {exc}", file=sys.stderr)+ return 2++ findings = evaluate(corpus)++ if args.as_json:+ print(json.dumps({"root": str(root), "counts": corpus.counts(), "findings": [f.__dict__ for f in findings]}, indent=2))+ return 1 if findings else 0++ print(f"repository root: {root}")+ print("files read:")+ for rel in corpus.files_read:+ print(f" {rel}")+ print("counts:")+ for key, value in corpus.counts().items():+ print(f" {key}: {value}")+ print()++ if findings:+ print(f"{len(findings)} finding(s):")+ for finding in findings:+ print(f" {finding}")+ return 1++ print("OK: every cost figure carries the provenance that says how it is known.")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/services/agents/app/core/cost_telemetry.py b/services/agents/app/core/cost_telemetry.pyindex 4788d6d36..54982aceb 100644--- a/services/agents/app/core/cost_telemetry.py+++ b/services/agents/app/core/cost_telemetry.py@@ -1,8 +1,45 @@-"""Investigation cost telemetry.--Tracks token usage, model calls, latency, and estimated USD cost per run.-Persists aggregates to PostgreSQL (best-effort) and emits structlog events-that feed into the SOC metrics dashboard.+"""Investigation cost telemetry — what a run spent, and how that is known.++Tracks token usage, model calls, latency, and USD cost per run. Persists+aggregates to PostgreSQL (best-effort) and emits structlog events that feed+the cost dashboard and the SOC metrics dashboard.++Every dollar figure here carries its provenance+-----------------------------------------------+This module used to price a call by looking its **model name** up in a table+of hosted list prices. The name it looked up was an ``aisoc-<role>`` alias,+which is not a model — it is a label the LiteLLM gateway resolves to one. No+alias is in the table, so every call fell through to a ``(0.001, 0.002)``+default: a price nobody charges, for a model nobody named. A 903-token+completion on an operator's own hardware was reported as+``total_cost_usd=0.000999``, and that number reached the cost dashboard, the+per-run ledger, and the budget circuit breaker, which trips at+``AISOC_BUDGET_HARD_USD`` and would have degraded a working local deployment+to deterministic-only over money that was never spent.++A call is now booked under exactly one of three provenances, and the counts+travel with the sums everywhere:++``GATEWAY`` — measured+ The gateway reported the cost on the response headers. It resolved the+ alias, so it is the only party that knows what was actually called. This+ is real money (and is legitimately ``0.0`` for a local model, which is a+ *measured* zero, not an absent one).++``LIST_PRICE_ESTIMATE`` — estimated, and labelled as such on every surface+ No gateway figure, but the concrete model is one this table has a public+ list price for. Only ever keyed on a **concrete** model id — the alias, or+ the resolved model name the gateway supplied — never on an alias alone.++``UNPRICED`` — not measured+ Neither of the above. Reported as *not measured*, never as zero. Following+ the precedent set for MTTR (``services/api/app/api/v1/endpoints/metrics.py``),+ where a mean over zero rows was shipping as a confident ``0.0`` until the+ sample count travelled with it.++There is deliberately no "total cost" that mixes measured with estimated+money: a single number cannot be labelled two ways, and un-labelling an+estimate by adding it to a measurement is the defect one level up.Usage::@@ -11,10 +48,9 @@ Usage::async with CostTracker(run_id="r1", tenant_id="t1") as tracker:result = await llm_call(...)tracker.record(- model="gpt-4o",- prompt_tokens=result.usage.prompt_tokens,- completion_tokens=result.usage.completion_tokens,- latency_ms=elapsed_ms,+ model="aisoc-triage",+ prompt_tokens=..., completion_tokens=..., latency_ms=...,+ gateway_cost=extract_gateway_cost(result), # None => not measured)# On __aexit__, aggregates are flushed to DB."""@@ -29,6 +65,7 @@ from typing import Anyimport structlog+from app.core.gateway_cost import GatewayCost, extract_gateway_cost, extract_resolved_modelfrom app.core.schema_bootstrap import ensure_tablelogger = structlog.get_logger()@@ -53,7 +90,30 @@ def current_cost_tracker() -> CostTracker | None:# ----------------------------------------------------------------------------# Model pricing (USD per 1 k tokens, input / output)+# Cost provenance+# ---------------------------------------------------------------------------++#: The gateway reported what the call cost. Real money; ``0.0`` is a measured+#: zero (a local model), not a missing figure.+GATEWAY = "gateway"++#: Re-priced from a public list price for a concrete model. An approximation,+#: and labelled as one on every surface it reaches.+LIST_PRICE_ESTIMATE = "list_price_estimate"++#: Neither available. Reported as "not measured", never as zero.+UNPRICED = "unpriced"++COST_SOURCES = (GATEWAY, LIST_PRICE_ESTIMATE, UNPRICED)+++# ---------------------------------------------------------------------------+# Public list pricing (USD per 1 k tokens, input / output)+#+# Keys are **concrete model ids**. There is deliberately no default entry: a+# model absent from this table has no known price, and inventing one is the+# defect this module was rewritten to remove. A gateway alias is never a key+# here and can never become one — see ``_estimate_cost``.# ---------------------------------------------------------------------------_PRICING: dict[str, tuple[float, float]] = {"gpt-4o": (0.005, 0.015),@@ -68,12 +128,40 @@ _PRICING: dict[str, tuple[float, float]] = {"gemini-1.5-flash": (0.000075, 0.0003),}-_DEFAULT_PRICE = (0.001, 0.002)+#: Shape of a logical task alias. An alias is resolved by the gateway and+#: carries no price of its own, so it is refused as a pricing key outright+#: rather than being allowed to miss the table and take a default.+_GATEWAY_ALIAS_PREFIX = "aisoc-"-def _estimate_cost(model: str, prompt_tokens: int, completion_tokens: int) -> float:- in_price, out_price = _PRICING.get(model.lower(), _DEFAULT_PRICE)- return (prompt_tokens / 1000) * in_price + (completion_tokens / 1000) * out_price+def _price_key(model: str | None) -> str | None:+ """The table key for ``model``, or ``None`` if it cannot be priced.++ Providers are commonly prefixed at the gateway (``openai/gpt-4o-mini``,+ ``ollama/qwen2:1.5b``), so the provider segment is dropped before lookup —+ but only for a name that actually carries one, and never for an alias.+ """+ name = (model or "").strip().lower()+ if not name or name.startswith(_GATEWAY_ALIAS_PREFIX):+ return None+ if name in _PRICING:+ return name+ bare = name.rsplit("/", 1)[-1]+ return bare if bare in _PRICING else None+++def _estimate_cost(model: str | None, prompt_tokens: int, completion_tokens: int) -> float | None:+ """List-price estimate for ``model``, or ``None`` when it has no known price.++ ``None`` is the whole point. The previous version returned a number+ unconditionally, so "we know this model's price" and "we guessed" were+ indistinguishable by the time the figure reached a dashboard.+ """+ key = _price_key(model)+ if key is None:+ return None+ in_price, out_price = _PRICING[key]+ return (max(prompt_tokens, 0) / 1000) * in_price + (max(completion_tokens, 0) / 1000) * out_price# ---------------------------------------------------------------------------@@ -83,16 +171,83 @@ def _estimate_cost(model: str, prompt_tokens: int, completion_tokens: int) -> fl@dataclassclass CallRecord:+ """One LLM call, with what it cost and how that is known.++ ``cost_usd`` is ``None`` when ``cost_source`` is :data:`UNPRICED`. It is+ never silently zero: a caller that wants to add these up must decide what+ to do about the calls nobody can price.+ """+model: strprompt_tokens: intcompletion_tokens: intlatency_ms: float- cost_usd: float = 0.0+ cost_usd: float | None = None+ cost_source: str = UNPRICED+ #: What the gateway resolved ``model`` to, when it said. The alias asked+ #: for is not the model billed, and only this answers "billed for what".+ resolved_model: str | None = None+ #: Correlates with the gateway's own ``/spend/logs`` entry.+ call_id: str | None = Nonetool: str | None = Nonestep: str | None = None+ gateway_cost: GatewayCost | None = Nonedef __post_init__(self) -> None:- self.cost_usd = _estimate_cost(self.model, self.prompt_tokens, self.completion_tokens)+ gateway = self.gateway_cost+ if gateway is not None:+ self.cost_usd = gateway.cost_usd+ self.cost_source = GATEWAY+ self.resolved_model = self.resolved_model or gateway.resolved_model+ self.call_id = self.call_id or gateway.call_id+ return+ # No gateway figure. An estimate is allowed only against a concrete+ # model id — preferring what the gateway said it resolved to, since+ # that is the thing that would actually have been billed.+ estimate = _estimate_cost(self.resolved_model, self.prompt_tokens, self.completion_tokens)+ if estimate is None:+ estimate = _estimate_cost(self.model, self.prompt_tokens, self.completion_tokens)+ if estimate is None:+ self.cost_usd = None+ self.cost_source = UNPRICED+ else:+ self.cost_usd = estimate+ self.cost_source = LIST_PRICE_ESTIMATE++ @property+ def is_measured(self) -> bool:+ return self.cost_source == GATEWAY++ @property+ def is_estimated(self) -> bool:+ return self.cost_source == LIST_PRICE_ESTIMATE+++@dataclass(frozen=True)+class CostSummary:+ """A run's spend and the provenance of it, as one value.++ Exists so callers pass the whole picture around rather than a bare float.+ A single ``cost_usd: float = 0.0`` parameter is what let an unmeasured run+ be persisted, traced and budgeted as a free one — the default was+ indistinguishable from a measurement of zero at every call site.+ """++ measured_usd: float | None = None+ measured_calls: int = 0+ estimated_usd: float | None = None+ estimated_calls: int = 0+ unpriced_calls: int = 0++ @classmethod+ def from_tracker(cls, tracker: CostTracker) -> CostSummary:+ return cls(+ measured_usd=tracker.measured_cost_usd,+ measured_calls=tracker.measured_call_count,+ estimated_usd=tracker.estimated_cost_usd,+ estimated_calls=tracker.estimated_call_count,+ unpriced_calls=tracker.unpriced_call_count,+ )# ---------------------------------------------------------------------------@@ -121,6 +276,21 @@ CREATE INDEX IF NOT EXISTS aisoc_run_costs_tenant_runON aisoc_run_costs (tenant_id, run_id);"""+#: Cost provenance, added by ``services/api/migrations/055_cost_provenance.sql``.+#: Applied here too because this writer has to run against a database whose+#: migrations it does not own, and a write that silently drops the provenance+#: columns would leave every new row indistinguishable from the pre-provenance+#: rows it exists to separate. Idempotent, and a no-op where 055 already ran.+_RUN_COSTS_PROVENANCE_DDL = """+ALTER TABLE aisoc_run_costs+ ADD COLUMN IF NOT EXISTS measured_cost_usd DOUBLE PRECISION NOT NULL DEFAULT 0,+ ADD COLUMN IF NOT EXISTS measured_call_count INTEGER NOT NULL DEFAULT 0,+ ADD COLUMN IF NOT EXISTS estimated_cost_usd DOUBLE PRECISION NOT NULL DEFAULT 0,+ ADD COLUMN IF NOT EXISTS estimated_call_count INTEGER NOT NULL DEFAULT 0,+ ADD COLUMN IF NOT EXISTS unpriced_call_count INTEGER NOT NULL DEFAULT 0,+ ADD COLUMN IF NOT EXISTS resolved_model TEXT;+"""+async def _get_pool() -> Any | None:global _POOL@@ -145,6 +315,14 @@ async def _get_pool() -> Any | None:if not await ensure_table(conn, "aisoc_run_costs", _RUN_COSTS_DDL):await pool.close()return None+ try:+ await conn.execute(_RUN_COSTS_PROVENANCE_DDL)+ except Exception as exc: # noqa: BLE001+ # The runtime role may hold DML only, in which case migration+ # 055 is the one that adds these. Loud enough to diagnose a+ # dashboard stuck on "not measured", quiet enough not to fail+ # the run: the token counts still land.+ logger.warning("cost_telemetry.provenance_columns_unavailable", error=str(exc))_POOL = poolreturn _POOLexcept Exception as exc:@@ -166,29 +344,67 @@ async def _flush_to_db(# Aggregate by modelby_model: dict[str, dict] = {}for r in records:- m = by_model.setdefault(r.model, {"prompt": 0, "completion": 0, "cost": 0.0, "latency": 0.0, "calls": 0})+ m = by_model.setdefault(+ r.model,+ {+ "prompt": 0,+ "completion": 0,+ "measured": 0.0,+ "measured_calls": 0,+ "estimated": 0.0,+ "estimated_calls": 0,+ "unpriced_calls": 0,+ "latency": 0.0,+ "calls": 0,+ "resolved": None,+ },+ )m["prompt"] += r.prompt_tokensm["completion"] += r.completion_tokens- m["cost"] += r.cost_usdm["latency"] += r.latency_msm["calls"] += 1+ if r.is_measured:+ m["measured"] += r.cost_usd or 0.0+ m["measured_calls"] += 1+ elif r.is_estimated:+ m["estimated"] += r.cost_usd or 0.0+ m["estimated_calls"] += 1+ else:+ m["unpriced_calls"] += 1+ if r.resolved_model and not m["resolved"]:+ m["resolved"] = r.resolved_modeltry:async with pool.acquire() as conn:for model, agg in by_model.items():await conn.execute(+ # ``total_cost_usd`` carries **measured** cost only, and the+ # provenance columns beside it say how much of the window+ # that covers. It cannot also carry the estimate: a column+ # named for money cannot be labelled two ways at once, and+ # summing a guess into a measurement is how the guess stops+ # looking like one."""INSERT INTO aisoc_run_costs(run_id, tenant_id, model,total_prompt_tokens, total_completion_tokens,- total_cost_usd, total_latency_ms, call_count)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8)+ total_cost_usd, total_latency_ms, call_count,+ measured_cost_usd, measured_call_count,+ estimated_cost_usd, estimated_call_count,+ unpriced_call_count, resolved_model)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)ON CONFLICT (run_id, tenant_id, model) DO UPDATESET total_prompt_tokens = aisoc_run_costs.total_prompt_tokens + EXCLUDED.total_prompt_tokens,total_completion_tokens = aisoc_run_costs.total_completion_tokens + EXCLUDED.total_completion_tokens,total_cost_usd = aisoc_run_costs.total_cost_usd + EXCLUDED.total_cost_usd,total_latency_ms = aisoc_run_costs.total_latency_ms + EXCLUDED.total_latency_ms,call_count = aisoc_run_costs.call_count + EXCLUDED.call_count,+ measured_cost_usd = aisoc_run_costs.measured_cost_usd + EXCLUDED.measured_cost_usd,+ measured_call_count = aisoc_run_costs.measured_call_count + EXCLUDED.measured_call_count,+ estimated_cost_usd = aisoc_run_costs.estimated_cost_usd + EXCLUDED.estimated_cost_usd,+ estimated_call_count = aisoc_run_costs.estimated_call_count + EXCLUDED.estimated_call_count,+ unpriced_call_count = aisoc_run_costs.unpriced_call_count + EXCLUDED.unpriced_call_count,+ resolved_model = COALESCE(EXCLUDED.resolved_model, aisoc_run_costs.resolved_model),recorded_at = now()""",run_id,@@ -196,9 +412,15 @@ async def _flush_to_db(model,agg["prompt"],agg["completion"],- agg["cost"],+ agg["measured"],agg["latency"],agg["calls"],+ agg["measured"],+ agg["measured_calls"],+ agg["estimated"],+ agg["estimated_calls"],+ agg["unpriced_calls"],+ agg["resolved"],)except Exception as exc:logger.warning("cost_telemetry.flush_error", run_id=run_id, error=str(exc))@@ -242,6 +464,8 @@ class CostTracker:latency_ms: float,tool: str | None = None,step: str | None = None,+ gateway_cost: GatewayCost | None = None,+ resolved_model: str | None = None,) -> CallRecord:rec = CallRecord(model=model,@@ -250,6 +474,8 @@ class CostTracker:latency_ms=latency_ms,tool=tool,step=step,+ gateway_cost=gateway_cost,+ resolved_model=resolved_model,)self._records.append(rec)logger.info(@@ -257,9 +483,14 @@ class CostTracker:run_id=self.run_id,tenant_id=self.tenant_id,model=model,+ resolved_model=rec.resolved_model,prompt_tokens=prompt_tokens,completion_tokens=completion_tokens,- cost_usd=f"{rec.cost_usd:.6f}",+ # "not_measured" rather than "0.000000": the log line is read by a+ # human deciding whether a deployment is spending money, and the+ # two answers are not the same answer.+ cost_usd=("not_measured" if rec.cost_usd is None else f"{rec.cost_usd:.6f}"),+ cost_source=rec.cost_source,latency_ms=f"{latency_ms:.1f}",tool=tool,step=step,@@ -267,8 +498,33 @@ class CostTracker:return rec@property- def total_cost_usd(self) -> float:- return sum(r.cost_usd for r in self._records)+ def measured_cost_usd(self) -> float | None:+ """Money the gateway said was spent, or ``None`` if nothing was measured.++ ``None`` and ``0.0`` are different facts: the first is "no call on this+ run reported a cost", the second is "every call that reported one+ reported zero", which is what a local model genuinely costs.+ """+ measured = [r.cost_usd or 0.0 for r in self._records if r.is_measured]+ return sum(measured) if measured else None++ @property+ def measured_call_count(self) -> int:+ return sum(1 for r in self._records if r.is_measured)++ @property+ def estimated_cost_usd(self) -> float | None:+ """List-price estimate for the calls nobody billed us for, or ``None``."""+ estimated = [r.cost_usd or 0.0 for r in self._records if r.is_estimated]+ return sum(estimated) if estimated else None++ @property+ def estimated_call_count(self) -> int:+ return sum(1 for r in self._records if r.is_estimated)++ @property+ def unpriced_call_count(self) -> int:+ return sum(1 for r in self._records if r.cost_source == UNPRICED)@propertydef total_tokens(self) -> int:@@ -279,14 +535,27 @@ class CostTracker:return sum(r.latency_ms for r in self._records)def summary(self) -> dict:+ """The run's spend, with the provenance of every figure in it.++ There is no ``total_cost_usd`` key by design. It used to hold a number+ composed entirely of guesses against a default price, and a consumer+ reading a key by that name has no way to ask how it was arrived at.+ Anything that needs one dollar figure should use ``measured_cost_usd``+ and say "not measured" when ``measured_call_count`` is zero.+ """return {"run_id": self.run_id,"tenant_id": self.tenant_id,- "total_cost_usd": self.total_cost_usd,+ "measured_cost_usd": self.measured_cost_usd,+ "measured_call_count": self.measured_call_count,+ "estimated_cost_usd": self.estimated_cost_usd,+ "estimated_call_count": self.estimated_call_count,+ "unpriced_call_count": self.unpriced_call_count,"total_tokens": self.total_tokens,"total_latency_ms": self.total_latency_ms,"call_count": len(self._records),"models": list({r.model for r in self._records}),+ "resolved_models": sorted({r.resolved_model for r in self._records if r.resolved_model}),}async def flush(self) -> None:@@ -350,8 +619,14 @@ def record_llm_call("""Record an LLM call against the currently active CostTracker, if any.No-op when no tracker is bound. Returns the ``CallRecord`` so callers can- persist ``cost_usd`` into the audit log alongside the existing- ``tokens_used`` field.+ persist ``cost_usd`` and ``cost_source`` into the audit log alongside the+ existing ``tokens_used`` field.++ The cost is taken off the gateway's response headers when they are there.+ They are there when the client asked for them — see+ ``INCLUDE_HEADERS_PARAM`` in :mod:`app.core.gateway_cost` and the factory+ that sets it — and absent otherwise, in which case the call is booked as+ an estimate or as not measured rather than as zero."""tracker = current_cost_tracker()if tracker is None:@@ -364,4 +639,6 @@ def record_llm_call(latency_ms=latency_ms,tool=tool,step=step,+ gateway_cost=extract_gateway_cost(response),+ resolved_model=extract_resolved_model(response),)diff --git a/services/agents/app/core/gateway_cost.py b/services/agents/app/core/gateway_cost.pynew file mode 100644index 000000000..431223eac--- /dev/null+++ b/services/agents/app/core/gateway_cost.py@@ -0,0 +1,178 @@+"""What the call actually cost, according to the thing that placed it.++The defect this replaces+------------------------+``CostTracker`` priced a call by looking its **model name** up in a table of+hosted list prices. The name it looked up was an ``aisoc-<role>`` alias, which+is not a model — it is a label the gateway resolves to one. No alias appears in+the price table, so every call fell through to a ``(0.001, 0.002)`` default and+was booked at a price nobody charges for a model nobody named.++On a local deployment that is not an approximation, it is an invention. A+903-token completion on the operator's own hardware was reported as+``total_cost_usd=0.000999``, and the same figure flowed into the cost+dashboard, the per-run ledger and the budget circuit breaker — which trips at+``AISOC_BUDGET_HARD_USD`` and would eventually degrade a working local+deployment to deterministic-only over money that was never spent.++Where the real number comes from+--------------------------------+The gateway resolved the alias, so the gateway is the only party that knows+what was actually called and what it cost. LiteLLM returns both on the+response headers. Measured against a real gateway (1.102.1) driving a local+Ollama model and a hosted model in the same config::++ alias x-litellm-model-name cost header+ aisoc-triage ollama/qwen2:1.5b x-litellm-response-cost-original: 0.0+ aisoc-summary openai/gpt-4o-mini x-litellm-response-cost: 1.35e-05++Same alias set, same request path: the local call is free and says so, the+hosted call carries the provider's real price. The alias alone distinguishes+neither.++``langchain_openai.ChatOpenAI`` only keeps response headers when built with+``include_response_headers=True``; without it ``response_metadata`` has no+``headers`` key at all and the cost is simply **not knowable from here** —+which is a third answer, distinct from zero and from an estimate.++Header selection is exact, never a prefix+-----------------------------------------+LiteLLM emits seven headers starting ``x-litellm-response-cost``:++ x-litellm-response-cost the total (hosted call above)+ x-litellm-response-cost-original the total before margin/discount+ x-litellm-response-cost-input a component+ x-litellm-response-cost-output a component+ x-litellm-response-cost-discount-amount an adjustment+ x-litellm-response-cost-margin-amount an adjustment+ x-litellm-response-cost-margin-percent a *percentage*, not money++A prefix match would accept any of them, and ``-margin-percent`` is not even+denominated in dollars. Only the two totals are read, in a declared order, and+the self-test asserts a response carrying the five non-totals alone yields no+cost rather than a plausible-looking wrong one.++Stdlib only, and it never raises: a telemetry module that can throw would take+down the LLM call it is measuring.+"""++from __future__ import annotations++import math+from dataclasses import dataclass+from typing import Any++#: The only two headers that carry a total, most authoritative first.+#: ``x-litellm-response-cost`` is the billed figure; ``-original`` is the same+#: number before any margin or discount the gateway applies, and is the only+#: one some versions emit. Everything else sharing the prefix is a component,+#: an adjustment, or a percentage — see the module docstring.+COST_HEADERS: tuple[str, ...] = (+ "x-litellm-response-cost",+ "x-litellm-response-cost-original",+)++#: What the gateway resolved the requested alias to, e.g. ``ollama/qwen2:1.5b``.+#: Recording it is what makes a later estimate possible at all: an estimate+#: keyed on the alias is meaningless, one keyed on the resolved model is not.+RESOLVED_MODEL_HEADER = "x-litellm-model-name"++#: Correlates a recorded call with the gateway's own spend log, so an operator+#: reconciling the dashboard against ``/spend/logs`` has a join key.+CALL_ID_HEADER = "x-litellm-call-id"++#: Asking for the headers is what makes the cost knowable. Named here so the+#: factory that sets it and the gate that checks it cannot disagree.+INCLUDE_HEADERS_PARAM = "include_response_headers"+++@dataclass(frozen=True)+class GatewayCost:+ """A cost the gateway reported, with what it was reported for."""++ cost_usd: float+ resolved_model: str | None = None+ call_id: str | None = None+++def response_headers(response: Any) -> dict[str, str]:+ """Lower-cased response headers off a LangChain result, or ``{}``.++ ``{}`` means the headers were never captured, which is not the same as a+ gateway that reported no cost.+ """+ metadata = getattr(response, "response_metadata", None)+ if not isinstance(metadata, dict):+ return {}+ raw = metadata.get("headers")+ if raw is None:+ return {}+ try:+ items = raw.items()+ except AttributeError:+ return {}+ out: dict[str, str] = {}+ for key, value in items:+ try:+ out[str(key).strip().lower()] = str(value)+ except Exception: # noqa: BLE001 — a malformed header is not a crash+ continue+ return out+++def _as_float(value: str | None) -> float | None:+ if value is None:+ return None+ try:+ parsed = float(str(value).strip())+ except (TypeError, ValueError):+ return None+ # A negative cost is not a cost. Neither is NaN or an infinity, both of+ # which float() accepts and which would poison every sum downstream.+ # `math.isfinite` covers both rather than the `x != x` NaN idiom, which+ # reads as a self-comparison to a static analyser and to most people.+ if not math.isfinite(parsed) or parsed < 0:+ return None+ return parsed+++def extract_gateway_cost(response: Any) -> GatewayCost | None:+ """The cost the gateway reported for ``response``, or ``None``.++ ``None`` means *not measurable here* — no gateway, or a client that did not+ keep the headers. Callers must not substitute zero for it.+ """+ headers = response_headers(response)+ if not headers:+ return None+ for name in COST_HEADERS:+ cost = _as_float(headers.get(name))+ if cost is not None:+ return GatewayCost(+ cost_usd=cost,+ resolved_model=(headers.get(RESOLVED_MODEL_HEADER) or "").strip() or None,+ call_id=(headers.get(CALL_ID_HEADER) or "").strip() or None,+ )+ return None+++def extract_resolved_model(response: Any) -> str | None:+ """What the gateway resolved the requested alias to, if it said.++ Useful even when no cost header arrived: a recorded ``ollama/qwen2:1.5b``+ is why a later surface can say "local model, no spend" rather than guessing+ at an alias.+ """+ return (response_headers(response).get(RESOLVED_MODEL_HEADER) or "").strip() or None+++__all__ = [+ "CALL_ID_HEADER",+ "COST_HEADERS",+ "GatewayCost",+ "INCLUDE_HEADERS_PARAM",+ "RESOLVED_MODEL_HEADER",+ "extract_gateway_cost",+ "extract_resolved_model",+ "response_headers",+]diff --git a/services/agents/app/investigator/forensic_agent.py b/services/agents/app/investigator/forensic_agent.pyindex c5c94b9a5..26f41b5bc 100644--- a/services/agents/app/investigator/forensic_agent.py+++ b/services/agents/app/investigator/forensic_agent.py@@ -112,7 +112,11 @@ async def _llm_forensic(state: InvestigatorState) -> dict[str, Any]:step="forensic",tool="llm.forensic",)- cost_usd = call_record.cost_usd if call_record is not None else 0.0+ # None when nothing could price the call — see app/core/gateway_cost.py.+ # Not 0.0: an unpriced call is not a free one.+ cost_usd = call_record.cost_usd if call_record is not None else None+ cost_source = call_record.cost_source if call_record is not None else "unpriced"+ resolved_model = call_record.resolved_model if call_record is not None else Nonestate.log_llm_response(agent="ForensicAgent",response=content if isinstance(content, str) else str(content),@@ -121,6 +125,8 @@ async def _llm_forensic(state: InvestigatorState) -> dict[str, Any]:tokens_used=tokens,latency_ms=latency_ms,cost_usd=cost_usd,+ cost_source=cost_source,+ resolved_model=resolved_model,)json_match = re.search(r"\{[\s\S]*\}", content)if json_match:diff --git a/services/agents/app/investigator/ledger.py b/services/agents/app/investigator/ledger.pyindex 114d0106d..9ec9d7ba6 100644--- a/services/agents/app/investigator/ledger.py+++ b/services/agents/app/investigator/ledger.py@@ -343,9 +343,24 @@ async def complete_run(error: str | None = None,iterations: int = 0,total_tokens: int = 0,- total_cost_usd: float = 0.0,+ total_cost_usd: float | None = None,+ measured_call_count: int = 0,+ estimated_cost_usd: float | None = None,+ estimated_call_count: int = 0,+ unpriced_call_count: int = 0,) -> None:- """Finalise the run. Status should be 'completed' or 'failed'."""+ """Finalise the run. Status should be 'completed' or 'failed'.++ ``total_cost_usd`` is **measured** cost — what the gateway reported — and+ ``None`` means no call on this run reported one. It is not defaulted to+ ``0.0`` any more: every caller in this service omitted it, so every deep+ investigation closed with a hard-coded zero that the ledger UI rendered as+ ``$0.0000`` beside a run that had made real LLM calls.++ The counts travel with the sums so a consumer can distinguish "measured,+ and it was free" from "nothing measured it" — see migration+ ``055_cost_provenance.sql``.+ """pool = await get_pool()if pool is None:return@@ -360,7 +375,11 @@ async def complete_run(error = $3,iterations = $4,total_tokens = $5,- total_cost_usd = $6,+ total_cost_usd = COALESCE($6, total_cost_usd),+ measured_call_count = $7,+ estimated_cost_usd = COALESCE($8, estimated_cost_usd),+ estimated_call_count = $9,+ unpriced_call_count = $10,completed_at = now()WHERE id = $1""",@@ -370,6 +389,10 @@ async def complete_run(iterations,total_tokens,total_cost_usd,+ measured_call_count,+ estimated_cost_usd,+ estimated_call_count,+ unpriced_call_count,)logger.info("ledger.run_completed",@@ -408,7 +431,11 @@ async def persist_auto_triage(auto_closed: bool = False,iterations: int = 0,tokens: int = 0,- cost_usd: float = 0.0,+ cost_usd: float | None = None,+ measured_call_count: int = 0,+ estimated_cost_usd: float | None = None,+ estimated_call_count: int = 0,+ unpriced_call_count: int = 0,groundedness: float | None = None,ungrounded: bool | None = None,) -> bool:@@ -487,16 +514,30 @@ async def persist_auto_triage(),)await conn.execute(+ # `total_cost_usd` is measured cost only. It used to carry+ # a list-price guess keyed on a gateway alias, so a local+ # deployment that spent nothing accrued a per-alert dollar+ # figure here and everywhere reading from here."""UPDATE investigation_runsSET status = 'completed', iterations = $2,- total_tokens = $3, total_cost_usd = $4, completed_at = now()+ total_tokens = $3,+ total_cost_usd = $4,+ measured_call_count = $5,+ estimated_cost_usd = $6,+ estimated_call_count = $7,+ unpriced_call_count = $8,+ completed_at = now()WHERE id = $1""",run_id,iterations,tokens,cost_usd,+ measured_call_count,+ estimated_cost_usd,+ estimated_call_count,+ unpriced_call_count,)if alert_uuid is not None:# Surface the automated verdict on the alert row. Status isdiff --git a/services/agents/app/investigator/orchestrator.py b/services/agents/app/investigator/orchestrator.pyindex ff7ce9046..6e85fc137 100644--- a/services/agents/app/investigator/orchestrator.py+++ b/services/agents/app/investigator/orchestrator.py@@ -32,6 +32,25 @@ from .state import InvestigatorState, StepKindlogger = structlog.get_logger()++def _ledger_cost_kwargs(cost_summary: dict[str, Any] | None) -> dict[str, Any]:+ """Map ``CostTracker.summary()`` onto :func:`ledger.complete_run`'s cost args.++ ``.get(key)`` with no default on the two money keys is deliberate: a+ missing summary means nothing was measured, and defaulting to ``0.0``+ there is exactly the substitution this whole change exists to remove.+ """+ summary = cost_summary or {}+ return {+ "total_cost_usd": summary.get("measured_cost_usd"),+ "measured_call_count": int(summary.get("measured_call_count") or 0),+ "estimated_cost_usd": summary.get("estimated_cost_usd"),+ "estimated_call_count": int(summary.get("estimated_call_count") or 0),+ "unpriced_call_count": int(summary.get("unpriced_call_count") or 0),+ "total_tokens": int(summary.get("total_tokens") or 0),+ }++try:from app.core.telemetry import get_tracer as _get_tracer@@ -207,27 +226,47 @@ class InvestigatorOrchestrator:content=final.report_md,)+ # Carry the run's spend to the ledger row. Every caller here+ # omitted these, so `total_cost_usd` defaulted to 0.0 and the+ # console rendered "$0.0000" for a deep investigation that had+ # made real model calls — the same fiction as an invented+ # figure, arrived at from the other direction.await ledger.complete_run(run_id=run_uuid,tenant_id=tenant_uuid,status=final.status,error=final.error,iterations=final.iteration,+ **_ledger_cost_kwargs(final.cost_summary),)span.set_attribute("investigation.status", final.status)span.set_attribute("investigation.iterations", final.iteration)span.set_attribute("investigation.run_id", str(run_uuid))if final.cost_summary:- span.set_attribute("investigation.cost_usd", final.cost_summary.get("cost_usd", 0.0))- span.set_attribute("investigation.tokens_total", final.cost_summary.get("tokens_total", 0))+ # These read `cost_usd` and `tokens_total`, two keys the+ # summary has never emitted, so the span carried the `or 0`+ # defaults on every run: a trace attribute asserting zero+ # spend regardless of what was spent. The keys are now the+ # ones `CostTracker.summary()` actually produces, and the+ # count travels so a zero can be told from an absence.+ # An OTel attribute cannot hold None, and a sentinel would be+ # a second invented number, so an unmeasured run simply has no+ # cost attribute. The call count is always set, so a reader can+ # tell "nothing measured" from "attribute dropped".+ measured = final.cost_summary.get("measured_cost_usd")+ if measured is not None:+ span.set_attribute("investigation.measured_cost_usd", measured)+ span.set_attribute("investigation.measured_call_count", final.cost_summary.get("measured_call_count", 0))+ span.set_attribute("investigation.tokens_total", final.cost_summary.get("total_tokens", 0))logger.info("investigation.end",case_id=case_id,run_id=str(run_uuid),status=final.status,iterations=final.iteration,- cost_usd=final.cost_summary.get("cost_usd") if final.cost_summary else None,+ measured_cost_usd=final.cost_summary.get("measured_cost_usd") if final.cost_summary else None,+ measured_call_count=final.cost_summary.get("measured_call_count") if final.cost_summary else None,)return final@@ -346,6 +385,7 @@ class InvestigatorOrchestrator:status=last_state.status,error=last_state.error,iterations=last_state.iteration,+ **_ledger_cost_kwargs(cost_summary),)yield {"type": "done",diff --git a/services/agents/app/investigator/recon_agent.py b/services/agents/app/investigator/recon_agent.pyindex 832a13673..f55840df4 100644--- a/services/agents/app/investigator/recon_agent.py+++ b/services/agents/app/investigator/recon_agent.py@@ -111,7 +111,11 @@ async def _llm_recon(state: InvestigatorState) -> dict[str, Any]:step="recon",tool="llm.recon",)- cost_usd = call_record.cost_usd if call_record is not None else 0.0+ # None when nothing could price the call — see app/core/gateway_cost.py.+ # Not 0.0: an unpriced call is not a free one.+ cost_usd = call_record.cost_usd if call_record is not None else None+ cost_source = call_record.cost_source if call_record is not None else "unpriced"+ resolved_model = call_record.resolved_model if call_record is not None else Nonestate.log_llm_response(agent="ReconAgent",response=content if isinstance(content, str) else str(content),@@ -120,6 +124,8 @@ async def _llm_recon(state: InvestigatorState) -> dict[str, Any]:tokens_used=tokens,latency_ms=latency_ms,cost_usd=cost_usd,+ cost_source=cost_source,+ resolved_model=resolved_model,)# Extract JSON from the responseimport rediff --git a/services/agents/app/investigator/report_writer_agent.py b/services/agents/app/investigator/report_writer_agent.pyindex 6bfb96d85..4d22a923c 100644--- a/services/agents/app/investigator/report_writer_agent.py+++ b/services/agents/app/investigator/report_writer_agent.py@@ -202,7 +202,11 @@ async def run_report_writer(state_dict: dict[str, Any]) -> dict[str, Any]:step="report_writer",tool="llm.report_writer",)- cost_usd = call_record.cost_usd if call_record is not None else 0.0+ # None when nothing could price the call — see app/core/gateway_cost.py.+ # Not 0.0: an unpriced call is not a free one.+ cost_usd = call_record.cost_usd if call_record is not None else None+ cost_source = call_record.cost_source if call_record is not None else "unpriced"+ resolved_model = call_record.resolved_model if call_record is not None else Nonestate.log_llm_response(agent="ReportWriterAgent",response=state.report_md if isinstance(state.report_md, str) else str(state.report_md),@@ -211,6 +215,8 @@ async def run_report_writer(state_dict: dict[str, Any]) -> dict[str, Any]:tokens_used=tokens,latency_ms=latency_ms,cost_usd=cost_usd,+ cost_source=cost_source,+ resolved_model=resolved_model,)except Exception as exc: # noqa: BLE001logger.warning("report_writer llm failed", error=str(exc))diff --git a/services/agents/app/investigator/responder_agent.py b/services/agents/app/investigator/responder_agent.pyindex 2ed9e4002..66b6caa42 100644--- a/services/agents/app/investigator/responder_agent.py+++ b/services/agents/app/investigator/responder_agent.py@@ -116,7 +116,11 @@ async def _llm_responder(state: InvestigatorState) -> dict[str, Any]:step="responder",tool="llm.responder",)- cost_usd = call_record.cost_usd if call_record is not None else 0.0+ # None when nothing could price the call — see app/core/gateway_cost.py.+ # Not 0.0: an unpriced call is not a free one.+ cost_usd = call_record.cost_usd if call_record is not None else None+ cost_source = call_record.cost_source if call_record is not None else "unpriced"+ resolved_model = call_record.resolved_model if call_record is not None else Nonestate.log_llm_response(agent="ResponderAgent",response=content if isinstance(content, str) else str(content),@@ -125,6 +129,8 @@ async def _llm_responder(state: InvestigatorState) -> dict[str, Any]:tokens_used=tokens,latency_ms=latency_ms,cost_usd=cost_usd,+ cost_source=cost_source,+ resolved_model=resolved_model,)json_match = re.search(r"\{[\s\S]*\}", content)if json_match:diff --git a/services/agents/app/investigator/state.py b/services/agents/app/investigator/state.pyindex 7eddd2789..40312ea5b 100644--- a/services/agents/app/investigator/state.py+++ b/services/agents/app/investigator/state.py@@ -190,17 +190,29 @@ class InvestigatorState(BaseModel):*,prompt_hash: str | None = None,model: str | None = None,+ resolved_model: str | None = None,tokens_used: int = 0,latency_ms: int = 0,- cost_usd: float = 0.0,+ cost_usd: float | None = None,+ cost_source: str = "unpriced",) -> str:- """Record the literal LLM response. Returns the output hash."""+ """Record the literal LLM response. Returns the output hash.++ ``cost_usd`` is ``None`` when nothing could price the call, and the+ ledger entry says so via ``cost_source`` rather than recording a+ confident ``0.0``. It defaulted to ``0.0`` while the only writer fed+ it a list-price guess against a gateway alias, so the ledger asserted+ a cost for every call and the cheapest-looking ones were the ones+ nothing had measured.+ """output_hash = _stable_hash(response)meta = {"response": response[:8000],"model": model,+ "resolved_model": resolved_model,"tokens_used": tokens_used,"cost_usd": cost_usd,+ "cost_source": cost_source,"prompt_hash": prompt_hash,}self.audit_log.append(diff --git a/services/agents/app/llm/factory.py b/services/agents/app/llm/factory.pyindex f732a96c8..877fad935 100644--- a/services/agents/app/llm/factory.py+++ b/services/agents/app/llm/factory.py@@ -32,6 +32,7 @@ from typing import Anyfrom langchain_openai import ChatOpenAI+from app.core.gateway_cost import INCLUDE_HEADERS_PARAMfrom app.llm.contract import DEFAULT_OPENAI_CHAT_COMPLETIONS_URLfrom app.llm.model_pins import get_pin@@ -140,6 +141,13 @@ def make_chat_model(api_key = (override or {}).get("api_key") or resolve_api_key(model)if api_key:params["api_key"] = api_key+ # Keep the response headers. The gateway reports what it resolved the+ # alias to and what the call actually cost on them, and without this flag+ # `response_metadata` has no `headers` key at all — so the cost tracker+ # had nothing to read and priced the *alias* against a hosted price table,+ # billing a free local run. See app/core/gateway_cost.py.+ if INCLUDE_HEADERS_PARAM in getattr(ChatOpenAI, "model_fields", {}):+ params.setdefault(INCLUDE_HEADERS_PARAM, True)params.update(kwargs)return ChatOpenAI(**params)diff --git a/services/agents/app/workers/fused_alert_consumer.py b/services/agents/app/workers/fused_alert_consumer.pyindex 6ce70d98c..620d95e0f 100644--- a/services/agents/app/workers/fused_alert_consumer.py+++ b/services/agents/app/workers/fused_alert_consumer.py@@ -46,7 +46,7 @@ from app.agents.dispositions import AUTO_CLOSEABLE_DISPOSITIONS, NEEDS_REVIEW, nfrom app.agents.triage_agent import run_triagefrom app.confidence.groundedness import score_groundednessfrom app.core.cost_governor import Decision, get_governor-from app.core.cost_telemetry import CostTracker+from app.core.cost_telemetry import CostSummary, CostTrackerfrom app.graph.runner import default_budget, run_escalationfrom app.investigator import ledger as ledger_modulefrom app.investigator import siem_writeback@@ -410,7 +410,9 @@ class FusedAlertTriageWorker:decision = governor.check(str(state.tenant_id), fingerprint)tier: str- cost_usd = 0.0+ # None, not 0.0: a cached or deterministic verdict placed no LLM call,+ # and "no call was made" is a different fact from "the call was free".+ cost: CostSummary = CostSummary()tokens = 0if decision.decision is Decision.DEDUPLICATED and decision.cached_verdict:_METRICS["deduplicated"] += 1@@ -449,7 +451,7 @@ class FusedAlertTriageWorker:state = await run_triage(state)tier = "deterministic"_METRICS["deterministic"] += 1- cost_usd = tracker.total_cost_usd+ cost = CostSummary.from_tracker(tracker)tokens = tracker.total_tokensverdict = state.verdictconfidence = state.confidence@@ -466,11 +468,18 @@ class FusedAlertTriageWorker:# dedups instead of re-paying) and account the spend (so per-tenant# budgets + the circuit breaker actually fire). Best-effort.try:+ # The budget circuit breaker gets measured spend only. Fed the+ # old alias-priced guess it would eventually trip+ # AISOC_BUDGET_HARD_USD on a local deployment and degrade a+ # working install to deterministic-only over money nobody+ # spent. An unmeasured call contributes no dollars — it still+ # contributes tokens, which is the cap that can be enforced+ # honestly without a price.governor.record_verdict(str(state.tenant_id),fingerprint,{"verdict": verdict, "confidence": confidence},- usd=cost_usd,+ usd=cost.measured_usd or 0.0,tokens=tokens,)except Exception as exc: # noqa: BLE001 — governance accounting is best-effort@@ -484,7 +493,7 @@ class FusedAlertTriageWorker:verdict, confidence = self._apply_groundedness_gate(state, verdict, confidence)_METRICS["triaged"] += 1- await self._record(state, tier=tier, verdict=verdict, confidence=confidence, tokens=tokens, cost_usd=cost_usd)+ await self._record(state, tier=tier, verdict=verdict, confidence=confidence, tokens=tokens, cost=cost)# Wave 1 — write the durable outcome back as a per-signature prior so# autonomous closures compound (a later identical alert can suppress).@@ -803,7 +812,7 @@ class FusedAlertTriageWorker:verdict: Any,confidence: float,tokens: int = 0,- cost_usd: float = 0.0,+ cost: CostSummary | None = None,) -> None:"""Durably persist the triage outcome (issue #571).@@ -839,7 +848,11 @@ class FusedAlertTriageWorker:auto_closed=state.status is AgentStatus.COMPLETED,iterations=state.iteration_count,tokens=tokens,- cost_usd=cost_usd,+ cost_usd=(cost or CostSummary()).measured_usd,+ measured_call_count=(cost or CostSummary()).measured_calls,+ estimated_cost_usd=(cost or CostSummary()).estimated_usd,+ estimated_call_count=(cost or CostSummary()).estimated_calls,+ unpriced_call_count=(cost or CostSummary()).unpriced_calls,# Persisted so an ungrounded auto-closure is auditable after the# fact and aggregatable on /metrics/funnel, rather than surviving# only inside a findings string.diff --git a/services/agents/tests/test_cost_provenance.py b/services/agents/tests/test_cost_provenance.pynew file mode 100644index 000000000..ca48da59c--- /dev/null+++ b/services/agents/tests/test_cost_provenance.py@@ -0,0 +1,265 @@+"""A cost figure must be measured, labelled an estimate, or absent.++The defect these cover+----------------------+``CostTracker`` priced a call by looking its **model name** up in a table of+hosted list prices, and the name it looked up was an ``aisoc-<role>`` alias —+a label the gateway resolves, not a model. No alias is in the table, so every+call took a ``(0.001, 0.002)`` default. A 903-token completion on an+operator's own hardware was reported as ``total_cost_usd=0.000999``, and that+number reached the cost dashboard, the funnel, the per-run ledger and the+budget circuit breaker.++The header fixtures below are not invented. They are the literal header sets+returned by ``ghcr.io/berriai/litellm:main-stable`` (1.102.1) driving a local+``ollama/qwen2:1.5b`` and a hosted ``openai/gpt-4o-mini`` from the same alias+config — including the fact that the local success response carries+``x-litellm-response-cost-original`` but *not* the plain+``x-litellm-response-cost``, which is why both spellings are read.+"""++from __future__ import annotations++from types import SimpleNamespace++import pytest+from app.core.cost_telemetry import (+ GATEWAY,+ LIST_PRICE_ESTIMATE,+ UNPRICED,+ CallRecord,+ CostSummary,+ CostTracker,+ _estimate_cost,+ _price_key,+)+from app.core.gateway_cost import extract_gateway_cost, extract_resolved_model++# Measured: `aisoc-triage` -> ollama/qwen2:1.5b, a free local model.+LOCAL_HEADERS = {+ "x-litellm-call-id": "716640f2-e268-47dd-b53e-d956fe9d6361",+ "x-litellm-model-name": "ollama/qwen2:1.5b",+ "x-litellm-model-api-base": "http://aisoc-probe-ollama:11434",+ "x-litellm-version": "1.102.1",+ "x-litellm-response-cost-original": "0.0",+ "x-litellm-response-cost-input": "0.0",+ "x-litellm-response-cost-output": "0",+ "x-litellm-response-cost-discount-amount": "0.0",+ "x-litellm-response-cost-margin-amount": "0.0",+ "x-litellm-response-cost-margin-percent": "0.0",+ "x-litellm-response-cost-tool-usage": "0.0",+ "x-litellm-model-group": "aisoc-triage",+}++# Measured: `aisoc-summary` -> openai/gpt-4o-mini, a hosted model with a price.+HOSTED_HEADERS = {+ "x-litellm-call-id": "7bd2c2f0-1f2a-4a44-9a66-8b7c9f5b1f21",+ "x-litellm-model-name": "openai/gpt-4o-mini",+ "x-litellm-response-cost": "1.35e-05",+ "x-litellm-response-cost-original": "1.35e-05",+ "x-litellm-response-cost-input": "1.5e-06",+ "x-litellm-response-cost-output": "1.2e-05",+ "x-litellm-response-cost-margin-percent": "0.0",+ "x-litellm-model-group": "aisoc-summary",+}+++def _response(headers: dict[str, str] | None, *, prompt: int = 19, completion: int = 3):+ metadata: dict[str, object] = {"model_name": "aisoc-triage"}+ if headers is not None:+ metadata["headers"] = dict(headers)+ return SimpleNamespace(+ content="ok",+ usage_metadata={"input_tokens": prompt, "output_tokens": completion},+ response_metadata=metadata,+ )+++# --------------------------------------------------------------------------+# Header extraction+# --------------------------------------------------------------------------+++def test_local_model_reports_a_measured_zero():+ cost = extract_gateway_cost(_response(LOCAL_HEADERS))+ assert cost is not None, "the gateway reported a cost and it must be read"+ assert cost.cost_usd == 0.0+ assert cost.resolved_model == "ollama/qwen2:1.5b"+ assert cost.call_id == "716640f2-e268-47dd-b53e-d956fe9d6361"+++def test_hosted_model_reports_its_real_price():+ cost = extract_gateway_cost(_response(HOSTED_HEADERS))+ assert cost is not None+ assert cost.cost_usd == pytest.approx(1.35e-05)+ assert cost.resolved_model == "openai/gpt-4o-mini"+++def test_no_headers_means_not_measurable_not_free():+ """The distinction the whole change rests on."""+ assert extract_gateway_cost(_response(None)) is None+ assert extract_resolved_model(_response(None)) is None+++def test_component_headers_alone_yield_no_cost():+ """A prefix match would accept ``-margin-percent`` as a dollar amount.++ Seven headers start ``x-litellm-response-cost`` and only two are totals.+ ``-margin-percent`` is not even denominated in money, and ``-input`` /+ ``-output`` are halves of one. Feeding any of them to the tracker would+ produce a plausible-looking wrong number rather than an obvious absence,+ which is the harder failure to notice.+ """+ partial = {k: v for k, v in HOSTED_HEADERS.items() if k not in ("x-litellm-response-cost", "x-litellm-response-cost-original")}+ assert any(k.startswith("x-litellm-response-cost") for k in partial), "fixture must still contain the decoys"+ assert extract_gateway_cost(_response(partial)) is None+++def test_malformed_and_impossible_costs_are_refused():+ for bad in ("", "n/a", "NaN", "inf", "-0.5", " "):+ headers = {**HOSTED_HEADERS, "x-litellm-response-cost": bad, "x-litellm-response-cost-original": bad}+ assert extract_gateway_cost(_response(headers)) is None, bad+++# --------------------------------------------------------------------------+# Pricing: an alias is never a price key+# --------------------------------------------------------------------------++[email protected]("alias", ["aisoc-triage", "aisoc-report", "AISOC-Summary"])+def test_an_alias_has_no_price(alias):+ assert _price_key(alias) is None+ assert _estimate_cost(alias, 10_000, 10_000) is None+++def test_an_unknown_model_has_no_price():+ """No default rate. The default rate is what invented $0.000999."""+ assert _estimate_cost("some-bespoke-local-7b", 1_000_000, 1_000_000) is None+ assert _estimate_cost("ollama/qwen2:1.5b", 1_000_000, 1_000_000) is None+++def test_a_known_model_prices_with_or_without_its_provider_prefix():+ bare = _estimate_cost("gpt-4o-mini", 1000, 1000)+ prefixed = _estimate_cost("openai/gpt-4o-mini", 1000, 1000)+ assert bare == prefixed == pytest.approx(0.00015 + 0.0006)+++# --------------------------------------------------------------------------+# CallRecord provenance+# --------------------------------------------------------------------------+++def test_gateway_cost_wins_over_any_estimate():+ """The gateway resolved the alias; nothing else is entitled to a view.++ A hosted model the table *does* know still books the gateway's figure,+ not the table's, because the gateway applies the operator's actual+ contract, discounts and margin.+ """+ rec = CallRecord(+ model="aisoc-summary",+ prompt_tokens=19,+ completion_tokens=3,+ latency_ms=88.0,+ gateway_cost=extract_gateway_cost(_response(HOSTED_HEADERS)),+ )+ assert rec.cost_source == GATEWAY+ assert rec.cost_usd == pytest.approx(1.35e-05)+ assert rec.resolved_model == "openai/gpt-4o-mini"+++def test_local_run_books_a_measured_zero_not_an_estimate():+ rec = CallRecord(+ model="aisoc-triage",+ prompt_tokens=884,+ completion_tokens=19,+ latency_ms=5094.0,+ gateway_cost=extract_gateway_cost(_response(LOCAL_HEADERS)),+ )+ assert rec.cost_source == GATEWAY+ assert rec.cost_usd == 0.0+ assert rec.is_measured and not rec.is_estimated+++def test_alias_with_no_gateway_is_unpriced_not_default_priced():+ """The exact shape of the reported defect, as a regression test.++ 903 tokens of `aisoc-triage` against the old default rate produced+ $0.000999. It must now produce no figure at all.+ """+ rec = CallRecord(model="aisoc-triage", prompt_tokens=884, completion_tokens=19, latency_ms=5094.0)+ assert rec.cost_source == UNPRICED+ assert rec.cost_usd is None+++def test_resolved_model_enables_an_estimate_the_alias_could_not():+ """A gateway that named the model but reported no cost is still estimable."""+ rec = CallRecord(+ model="aisoc-summary",+ prompt_tokens=1000,+ completion_tokens=1000,+ latency_ms=10.0,+ resolved_model="openai/gpt-4o-mini",+ )+ assert rec.cost_source == LIST_PRICE_ESTIMATE+ assert rec.cost_usd == pytest.approx(0.00075)+++# --------------------------------------------------------------------------+# Tracker aggregation+# --------------------------------------------------------------------------+++async def test_tracker_keeps_measured_and_estimated_apart():+ async with CostTracker(run_id="r1", tenant_id="t1") as tracker:+ tracker.record(+ model="aisoc-triage",+ prompt_tokens=884,+ completion_tokens=19,+ latency_ms=5094.0,+ gateway_cost=extract_gateway_cost(_response(LOCAL_HEADERS)),+ )+ tracker.record(model="gpt-4o-mini", prompt_tokens=1000, completion_tokens=1000, latency_ms=10.0)+ tracker.record(model="aisoc-report", prompt_tokens=100, completion_tokens=100, latency_ms=10.0)++ assert tracker.measured_cost_usd == 0.0, "a measured zero is a value, not an absence"+ assert tracker.measured_call_count == 1+ assert tracker.estimated_cost_usd == pytest.approx(0.00075)+ assert tracker.estimated_call_count == 1+ assert tracker.unpriced_call_count == 1++ summary = tracker.summary()+ assert summary["resolved_models"] == ["ollama/qwen2:1.5b"]+ # No key sums the two together: one number cannot be labelled both+ # "measured" and "estimated", and merging them un-labels the estimate.+ assert "total_cost_usd" not in summary+++async def test_a_run_with_no_measured_call_reports_none_not_zero():+ async with CostTracker(run_id="r2", tenant_id="t2") as tracker:+ tracker.record(model="aisoc-triage", prompt_tokens=10, completion_tokens=5, latency_ms=1.0)+ assert tracker.measured_cost_usd is None+ assert tracker.estimated_cost_usd is None+ assert CostSummary.from_tracker(tracker) == CostSummary(+ measured_usd=None,+ measured_calls=0,+ estimated_usd=None,+ estimated_calls=0,+ unpriced_calls=1,+ )+++async def test_cost_summary_default_carries_no_money():+ """The value a cached or deterministic verdict is recorded with.++ ``cost_usd: float = 0.0`` was the old default at every call site, so a+ verdict that placed no LLM call was persisted, traced and budgeted as one+ that cost nothing — which happens to be the same words but is not the+ same claim.+ """+ empty = CostSummary()+ assert empty.measured_usd is None and empty.measured_calls == 0+ assert empty.estimated_usd is Nonediff --git a/services/agents/tests/test_llm_hot_path.py b/services/agents/tests/test_llm_hot_path.pyindex 5fa86c014..c203e99ef 100644--- a/services/agents/tests/test_llm_hot_path.py+++ b/services/agents/tests/test_llm_hot_path.py@@ -24,14 +24,24 @@ class _FakeLLM:@pytest.mark.asyncio-async def test_safe_ainvoke_records_cost_into_bound_tracker():+async def test_safe_ainvoke_records_tokens_and_refuses_to_invent_a_cost():+ """Tokens are measured; the cost of an unpriceable alias is not invented.++ The previous assertion was ``tracker.total_cost_usd >= 0.0``, which every+ float satisfies — including the ``$0.000999`` the tracker produced by+ pricing the *alias* ``aisoc-triage`` against a hosted list table it does+ not appear in. A no-gateway call now books as ``unpriced``.+ """llm = _FakeLLM()msgs = [SystemMessage(content="You are a triage agent."), HumanMessage(content="Alert: benign login from office")]async with CostTracker(run_id="r-cost", tenant_id="t-cost") as tracker:await safe_ainvoke(llm, msgs)# record_llm_call fired via safe_ainvoke — was invisible ($0) before.assert tracker.total_tokens == 15- assert tracker.total_cost_usd >= 0.0+ assert tracker.measured_cost_usd is None+ assert tracker.measured_call_count == 0+ assert tracker.unpriced_call_count == 1+ assert "total_cost_usd" not in tracker.summary()@pytest.mark.asynciodiff --git a/services/api/app/api/v1/endpoints/insights.py b/services/api/app/api/v1/endpoints/insights.pyindex 1fedd624a..a5b5d7de3 100644--- a/services/api/app/api/v1/endpoints/insights.py+++ b/services/api/app/api/v1/endpoints/insights.py@@ -296,16 +296,21 @@ async def _llm_cost_aggregate(start: datetime,end: datetime,) -> tuple[float, int]:- """Return ``(total_cost_usd, distinct_run_count)`` over the window.+ """Return ``(measured_cost_usd, distinct_run_count)`` over the window.Joins ``aisoc_run_costs`` with ``investigation_runs`` to tenant-scopethe spend. Returns ``(0.0, 0)`` if the cost table isn't deployedyet so the UI can render zeroes rather than a 500.++ The sum is over ``measured_cost_usd`` — cost the gateway reported — not+ ``total_cost_usd``, which on rows written before migration 063 holds a+ list-price guess keyed on a gateway alias. Summing those published spend+ for a deployment that had spent nothing."""sql = text("""- SELECT COALESCE(SUM(c.total_cost_usd), 0.0) AS cost,- COUNT(DISTINCT c.run_id) AS runs+ SELECT COALESCE(SUM(c.measured_cost_usd), 0.0) AS cost,+ COUNT(DISTINCT c.run_id) AS runsFROM aisoc_run_costs cJOIN investigation_runs r ON r.id::text = c.run_idWHERE r.tenant_id = :tenant_id@@ -346,7 +351,7 @@ async def _llm_cost_sparkline(sql = text("""SELECT r.started_at AS started_at,- c.total_cost_usd AS cost+ c.measured_cost_usd AS costFROM aisoc_run_costs cJOIN investigation_runs r ON r.id::text = c.run_idWHERE r.tenant_id = :tenant_iddiff --git a/services/api/app/api/v1/endpoints/investigations.py b/services/api/app/api/v1/endpoints/investigations.pyindex b128541e5..6eb1a1575 100644--- a/services/api/app/api/v1/endpoints/investigations.py+++ b/services/api/app/api/v1/endpoints/investigations.py@@ -65,7 +65,17 @@ class RunSummary(BaseModel):model_used: str | Noneiterations: inttotal_tokens: int+ #: Measured (gateway-reported) spend. Trustworthy only when+ #: ``measured_call_count > 0``; zero means *not measured*, which is what+ #: every run recorded before migration 063 was, and what a deep+ #: investigation was until this release passed the figure through at all.total_cost_usd: float+ measured_call_count: int = 0+ #: List-price estimate for the calls the gateway did not price. Presented+ #: as an estimate, never added to ``total_cost_usd``.+ estimated_cost_usd: float = 0.0+ estimated_call_count: int = 0+ unpriced_call_count: int = 0started_at: datetimecompleted_at: datetime | Noneerror: str | None@@ -80,9 +90,16 @@ class ModelCostBreakdown(BaseModel):"""model: str+ #: What the gateway resolved ``model`` to. ``model`` is usually a logical+ #: alias, which is a request label rather than the thing billed.+ resolved_model: str | None = Nonetotal_prompt_tokens: inttotal_completion_tokens: inttotal_cost_usd: float+ measured_call_count: int = 0+ estimated_cost_usd: float = 0.0+ estimated_call_count: int = 0+ unpriced_call_count: int = 0total_latency_ms: intcall_count: int@@ -105,7 +122,16 @@ class CostAggregateRow(BaseModel):total_prompt_tokens: inttotal_completion_tokens: inttotal_cost_usd: float+ measured_call_count: int = 0+ estimated_cost_usd: float = 0.0+ estimated_call_count: int = 0+ unpriced_call_count: int = 0total_latency_ms: int+ #: A mean of an unmeasured zero is not a cost per run, it is the absence+ #: of one. Read it with ``measured_call_count``: zero there means this is+ #: not a mean of anything and the console must not render it as a cost.+ #: Kept non-nullable on the MTTR precedent — making it optional breaks+ #: every generated SDK client for a fact the count already carries.avg_cost_per_run: floatavg_latency_per_call_ms: float@@ -172,6 +198,27 @@ class ExplainResponse(BaseModel):# ---------------------------------------------------------------------------+def _export_cost_cell(run: InvestigationRun) -> str:+ """The cost row of an exported summary, or why there is not one.++ The row was headed "Estimated cost (USD)" and printed+ ``${run.total_cost_usd:.4f}`` unconditionally, so an exported PDF that+ reached a customer asserted a dollar figure for every run — including+ deep investigations, which never wrote the column at all and therefore+ all reported ``$0.0000``. Measured spend is now printed as spend, an+ estimate is printed as an estimate, and an unmeasured run says so.+ """+ measured_calls = int(getattr(run, "measured_call_count", 0) or 0)+ if measured_calls:+ plural = "s" if measured_calls != 1 else ""+ return f"${float(run.total_cost_usd):.4f} (measured over {measured_calls} call{plural})"+ estimated_calls = int(getattr(run, "estimated_call_count", 0) or 0)+ if estimated_calls:+ plural = "s" if estimated_calls != 1 else ""+ return f"~${float(run.estimated_cost_usd):.4f} (list-price estimate, {estimated_calls} call{plural}, not billed)"+ return "not measured"++def _run_to_summary(run: InvestigationRun) -> RunSummary:return RunSummary(id=run.id,@@ -181,6 +228,10 @@ def _run_to_summary(run: InvestigationRun) -> RunSummary:iterations=run.iterations,total_tokens=run.total_tokens,total_cost_usd=float(run.total_cost_usd),+ measured_call_count=int(run.measured_call_count or 0),+ estimated_cost_usd=float(run.estimated_cost_usd or 0),+ estimated_call_count=int(run.estimated_call_count or 0),+ unpriced_call_count=int(run.unpriced_call_count or 0),started_at=run.started_at,completed_at=run.completed_at,error=run.error,@@ -232,7 +283,8 @@ def _aggregate_row(row: RowMapping) -> CostAggregateRow:"""runs = int(row["runs"] or 0)calls = int(row["calls"] or 0)- cost = float(row["total_cost_usd"] or 0.0)+ cost = float(row["measured_cost_usd"] or 0.0)+ measured_calls = int(row["measured_call_count"] or 0)latency = int(row["total_latency_ms"] or 0)return CostAggregateRow(model=row["model"],@@ -241,8 +293,14 @@ def _aggregate_row(row: RowMapping) -> CostAggregateRow:total_prompt_tokens=int(row["total_prompt_tokens"] or 0),total_completion_tokens=int(row["total_completion_tokens"] or 0),total_cost_usd=cost,+ measured_call_count=measured_calls,+ estimated_cost_usd=float(row["estimated_cost_usd"] or 0.0),+ estimated_call_count=int(row["estimated_call_count"] or 0),+ unpriced_call_count=int(row["unpriced_call_count"] or 0),total_latency_ms=latency,- avg_cost_per_run=(cost / runs) if runs else 0.0,+ # 0.0 when nothing was measured, qualified by measured_call_count+ # above — the console must not render it as a cost per run.+ avg_cost_per_run=((cost / runs) if runs else 0.0) if measured_calls else 0.0,avg_latency_per_call_ms=(latency / calls) if calls else 0.0,)@@ -264,14 +322,19 @@ async def _fetch_model_costs(text("""SELECT model,+ resolved_model,total_prompt_tokens,total_completion_tokens,- total_cost_usd,+ measured_cost_usd,+ measured_call_count,+ estimated_cost_usd,+ estimated_call_count,+ unpriced_call_count,total_latency_ms,call_countFROM aisoc_run_costsWHERE run_id = :run_id- ORDER BY total_cost_usd DESC, model ASC+ ORDER BY measured_cost_usd DESC, estimated_cost_usd DESC, model ASC"""),{"run_id": str(run_id)},@@ -280,9 +343,14 @@ async def _fetch_model_costs(return [ModelCostBreakdown(model=row["model"],+ resolved_model=(str(row["resolved_model"]) if row["resolved_model"] else None),total_prompt_tokens=int(row["total_prompt_tokens"] or 0),total_completion_tokens=int(row["total_completion_tokens"] or 0),- total_cost_usd=float(row["total_cost_usd"] or 0.0),+ total_cost_usd=float(row["measured_cost_usd"] or 0.0),+ measured_call_count=int(row["measured_call_count"] or 0),+ estimated_cost_usd=float(row["estimated_cost_usd"] or 0.0),+ estimated_call_count=int(row["estimated_call_count"] or 0),+ unpriced_call_count=int(row["unpriced_call_count"] or 0),total_latency_ms=int(row["total_latency_ms"] or 0),call_count=int(row["call_count"] or 0),)@@ -358,14 +426,18 @@ async def aggregate_costs(SUM(c.call_count) AS calls,SUM(c.total_prompt_tokens) AS total_prompt_tokens,SUM(c.total_completion_tokens) AS total_completion_tokens,- SUM(c.total_cost_usd) AS total_cost_usd,+ SUM(c.measured_cost_usd) AS measured_cost_usd,+ SUM(c.measured_call_count) AS measured_call_count,+ SUM(c.estimated_cost_usd) AS estimated_cost_usd,+ SUM(c.estimated_call_count) AS estimated_call_count,+ SUM(c.unpriced_call_count) AS unpriced_call_count,SUM(c.total_latency_ms) AS total_latency_msFROM aisoc_run_costs cJOIN investigation_runs r ON r.id::text = c.run_idWHERE r.tenant_id = :tenant_idAND r.started_at >= now() - make_interval(days => :window_days)GROUP BY GROUPING SETS ((c.model), ())- ORDER BY GROUPING(c.model), SUM(c.total_cost_usd) DESC+ ORDER BY GROUPING(c.model), SUM(c.measured_cost_usd) DESC"""),{@@ -865,7 +937,7 @@ def _build_summary_markdown(|--------|-------|| Iterations | {run.iterations} || Total tokens | {run.total_tokens:,} |- | Estimated cost (USD) | ${float(run.total_cost_usd):.4f} |+ | LLM cost (USD) | {_export_cost_cell(run)} || Events recorded | {len(events)} |## Event Kind Breakdowndiff --git a/services/api/app/models/investigation.py b/services/api/app/models/investigation.pyindex eb8294a64..06dd8b778 100644--- a/services/api/app/models/investigation.py+++ b/services/api/app/models/investigation.py@@ -54,7 +54,17 @@ class InvestigationRun(Base):status: Mapped[str] = mapped_column(String(20), nullable=False, default="running")error: Mapped[str | None] = mapped_column(Text)total_tokens: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ #: Measured (gateway-reported) cost only — see migration 063. Trustworthy+ #: only when ``measured_call_count > 0``; a row with a zero count holds+ #: either a pre-063 list-price guess or nothing at all, and both must read+ #: as "not measured" rather than as a free run.total_cost_usd: Mapped[float] = mapped_column(Numeric(10, 4), nullable=False, default=0)+ measured_call_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ #: List-price estimate for calls the gateway did not price. Always+ #: presented as an estimate, never merged into ``total_cost_usd``.+ estimated_cost_usd: Mapped[float] = mapped_column(Numeric(10, 4), nullable=False, default=0)+ estimated_call_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)+ unpriced_call_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)iterations: Mapped[int] = mapped_column(Integer, nullable=False, default=0)started_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, server_default=func.now())completed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))diff --git a/services/api/app/services/cost_dashboard.py b/services/api/app/services/cost_dashboard.pyindex ec3b100ae..692ad68ae 100644--- a/services/api/app/services/cost_dashboard.py+++ b/services/api/app/services/cost_dashboard.py@@ -22,14 +22,39 @@ Following the WS-G2 pattern, the module splits into:2. ``build_cost_dashboard`` — a thin async orchestrator that runs theSQL queries and forwards rows into the pure builder.-BYOK savings are *imputed*: we re-price every recorded prompt+completion-token pair against the public list price for the model that handled it-(``cost_telemetry._PRICING``). When the runtime LLM is local-(``llm_status().is_local``), the difference between imputed cost and-recorded cost approximates what the operator would have paid a hosted-provider had they not brought their own key. We never claim this is a-billing-grade number — the response carries an ``is_byok_active`` flag so-the UI can label the panel accordingly.+Every dollar figure carries its provenance+------------------------------------------+Cost arrives here already classified by the agents service (migration 063):++``measured``+ The LiteLLM gateway reported what the call cost. Real money. A measured+ ``0.0`` — what a local model genuinely costs — is a fact, not a gap.++``estimated``+ Re-priced from a public list price for a **concrete** model id. An+ approximation, and labelled one on every surface, including this one.++``unpriced``+ Neither. Reported as *not measured*.++The counts travel with the sums, so a zero can be told from an absence. This+follows the MTTR precedent in ``api/v1/endpoints/metrics.py``, where a mean+over zero rows shipped as a confident ``0.0`` until its sample count came+with it. Without that, this dashboard could not distinguish "the agents spent+nothing" from "nobody told us what the agents spent", and it rendered the+first — a free AI-SOC, for a tenant nobody had priced.++There is deliberately no field summing measured and estimated together. One+number cannot be labelled two ways, and adding a guess to a measurement is+how the guess stops looking like one.++BYOK savings are *imputed*: we re-price recorded prompt+completion token+pairs against the public list price for the model that handled them. Only+models this table actually knows a price for are imputed at all — there is no+default rate, because a default rate is how the tracker came to invent+$0.000999 for a free local run in the first place. The response carries+``is_byok_active`` plus the number of tokens that could not be priced, so the+UI can say how much of the estimate is missing rather than implying none is."""from __future__ import annotations@@ -66,21 +91,46 @@ _PUBLIC_PRICING: dict[str, tuple[float, float]] = {"gemini-1.5-flash": (0.000075, 0.0003),}-# Conservative default for unknown models so we don't claim massive-# savings on a bespoke local model that has no public list price.-_DEFAULT_PUBLIC_PRICING: tuple[float, float] = (0.001, 0.002)+# There is no default rate, on purpose. This table used to fall back to+# (0.001, 0.002) for anything it did not recognise, and what it did not+# recognise was *every* row: the agents service records the `aisoc-<role>`+# alias it requested, and an alias is not a model. So the "imputed list+# price" was a made-up rate applied to a made-up model, and the BYOK panel+# reported savings against it. A model with no known price now imputes+# nothing and is counted as unpriced instead.+_GATEWAY_ALIAS_PREFIX = "aisoc-"+++def _price_key(model: str | None) -> str | None:+ """The pricing-table key for ``model``, or ``None`` if it has no known price.++ Gateway-resolved names carry a provider segment (``openai/gpt-4o-mini``),+ which is stripped; a logical alias carries no price at all and is refused+ outright rather than allowed to miss the table and take a default.+ """+ name = (model or "").strip().lower()+ if not name or name.startswith(_GATEWAY_ALIAS_PREFIX):+ return None+ if name in _PUBLIC_PRICING:+ return name+ bare = name.rsplit("/", 1)[-1]+ return bare if bare in _PUBLIC_PRICING else Nonedef _impute_public_cost(- model: str,+ model: str | None,prompt_tokens: int,completion_tokens: int,-) -> float:- """Return what ``model`` would cost on its public list price."""- in_price, out_price = _PUBLIC_PRICING.get(- (model or "").lower(),- _DEFAULT_PUBLIC_PRICING,- )+) -> float | None:+ """What ``model`` would cost at list price, or ``None`` if unknown.++ ``None`` is the point: "this model lists at $X" and "we had to guess"+ were previously the same return type and therefore the same number.+ """+ key = _price_key(model)+ if key is None:+ return None+ in_price, out_price = _PUBLIC_PRICING[key]return round((max(prompt_tokens, 0) / 1000) * in_price + (max(completion_tokens, 0) / 1000) * out_price,6,@@ -100,10 +150,19 @@ class DashboardPeriod(BaseModel):class CostBucket(BaseModel):- """LLM spend bucketed by day."""+ """LLM spend bucketed by day.++ ``total_cost_usd`` is measured cost. ``measured_call_count`` says how much+ of the day's traffic that covers, so a bar of height zero can be read as+ "a free day" or "an unmeasured day" rather than silently as the first.+ """day: datetotal_cost_usd: float+ measured_call_count: int = 0+ estimated_cost_usd: float = 0.0+ estimated_call_count: int = 0+ unpriced_call_count: int = 0total_tokens: intcall_count: int@@ -112,12 +171,29 @@ class ModelBreakdown(BaseModel):"""Spend / volume rolled up per model over the window."""model: str+ #: What the gateway resolved ``model`` to, when it said. An `aisoc-<role>`+ #: row is a request label; this is the thing that was actually billed.+ resolved_model: str | None = Noneruns: intcalls: inttotal_prompt_tokens: inttotal_completion_tokens: inttotal_cost_usd: float+ measured_call_count: int = 0+ estimated_cost_usd: float = 0.0+ estimated_call_count: int = 0+ unpriced_call_count: int = 0+ #: List-price re-pricing of this model's tokens. ``0.0`` when nothing here+ #: has a published price, which ``imputed_is_estimable`` distinguishes from+ #: a genuine zero. Nullable would have been the obvious shape and is the+ #: wrong one: it breaks every generated SDK client, and the precedent set+ #: for MTTR is to keep the number and carry the thing that qualifies it.imputed_public_cost_usd: float+ #: False => the figure above is not an estimate of anything. Render "—".+ imputed_is_estimable: bool = False+ #: Tokens excluded from the imputation because nothing prices them. Without+ #: this the imputed figure looks complete when it covers part of the window.+ unpriced_tokens: int = 0avg_latency_ms: float | None@@ -133,6 +209,9 @@ class TopCostCase(BaseModel):case_id: strruns: inttotal_cost_usd: float+ measured_call_count: int = 0+ estimated_cost_usd: float = 0.0+ estimated_call_count: int = 0total_tokens: int@@ -144,24 +223,46 @@ class ActionCount(BaseModel):class ByokSavings(BaseModel):- """Imputed savings vs hosted pricing.+ """Imputed savings vs hosted pricing — an estimate, labelled everywhere.``is_byok_active`` is True when the live LLM provider (per``/llm/status``) is loopback or private — i.e. the operator isactually running their own model. When False, the savings are stillcomputed (so the UI can show "if you switched to BYOK, you'd save~X") but should be labelled "potential savings" in the UI.++ ``imputed_is_estimable`` is False when no row in the window names a model+ with a public list price, and then ``imputed_public_cost_usd`` and+ ``savings_usd`` are ``0.0`` because there is nothing to compute, not+ because the answer is zero. They used to be real-looking numbers in that+ case, built from a default rate applied to a gateway alias, and the BYOK+ panel announced savings against it — an invented saving on invented spend.+ ``unpriced_tokens`` says how much of the window the estimate omits."""is_byok_active: boolprovider: strrecorded_cost_usd: float+ recorded_is_measured: boolimputed_public_cost_usd: float+ imputed_is_estimable: bool = False+ unpriced_tokens: int = 0savings_usd: floatclass CostHeadline(BaseModel):+ """Window totals, each with the count of calls it was computed over.++ ``total_cost_usd`` is **measured** spend. When ``measured_call_count`` is+ zero it is not a total of anything and the console must render "not+ measured" — the same contract the MTTR tiles use.+ """+total_cost_usd: float+ measured_call_count: int = 0+ estimated_cost_usd: float = 0.0+ estimated_call_count: int = 0+ unpriced_call_count: int = 0total_tokens: inttotal_calls: inttotal_runs: int@@ -195,10 +296,19 @@ class CostRow:model: strprompt_tokens: intcompletion_tokens: int- cost_usd: float+ #: Measured (gateway-reported) cost, already zeroed by the query when+ #: ``measured_call_count`` is 0 — see ``_COST_QUERY``. The guard lives at+ #: the boundary rather than on this row so every sum below is plain+ #: arithmetic and no aggregator can forget to apply it.+ measured_cost_usd: floatlatency_ms: floatcall_count: intstarted_at: datetime+ measured_call_count: int = 0+ estimated_cost_usd: float = 0.0+ estimated_call_count: int = 0+ unpriced_call_count: int = 0+ resolved_model: str | None = None@dataclass(frozen=True)@@ -246,17 +356,35 @@ def _format_period_label(start: datetime, end: datetime) -> str:def _bucket_by_day(rows: list[CostRow]) -> list[CostBucket]:"""Group cost rows by UTC calendar date, ascending."""- buckets: dict[date, dict[str, float]] = defaultdict(lambda: {"cost": 0.0, "tokens": 0, "calls": 0})+ buckets: dict[date, dict[str, float]] = defaultdict(+ lambda: {+ "cost": 0.0,+ "measured_calls": 0,+ "estimated": 0.0,+ "estimated_calls": 0,+ "unpriced_calls": 0,+ "tokens": 0,+ "calls": 0,+ }+ )for r in rows:d = r.started_at.astimezone(UTC).date()b = buckets[d]- b["cost"] += r.cost_usd+ b["cost"] += r.measured_cost_usd+ b["measured_calls"] += r.measured_call_count+ b["estimated"] += r.estimated_cost_usd+ b["estimated_calls"] += r.estimated_call_count+ b["unpriced_calls"] += r.unpriced_call_countb["tokens"] += r.prompt_tokens + r.completion_tokensb["calls"] += r.call_countreturn [CostBucket(day=d,total_cost_usd=round(buckets[d]["cost"], 4),+ measured_call_count=int(buckets[d]["measured_calls"]),+ estimated_cost_usd=round(buckets[d]["estimated"], 4),+ estimated_call_count=int(buckets[d]["estimated_calls"]),+ unpriced_call_count=int(buckets[d]["unpriced_calls"]),total_tokens=int(buckets[d]["tokens"]),call_count=int(buckets[d]["calls"]),)@@ -264,6 +392,19 @@ def _bucket_by_day(rows: list[CostRow]) -> list[CostBucket]:]+def _imputed_for_row(r: CostRow) -> float | None:+ """List-price re-pricing of one row, preferring the model actually billed.++ The gateway-resolved name is tried first because that is the model a+ provider would have charged for; the requested name is usually an alias+ and carries no price. ``None`` when neither is priceable.+ """+ imputed = _impute_public_cost(r.resolved_model, r.prompt_tokens, r.completion_tokens)+ if imputed is None:+ imputed = _impute_public_cost(r.model, r.prompt_tokens, r.completion_tokens)+ return imputed++def _model_breakdown(rows: list[CostRow]) -> list[ModelBreakdown]:"""Aggregate rows per model, sorted by spend descending."""by_model: dict[str, dict[str, Any]] = defaultdict(@@ -273,7 +414,13 @@ def _model_breakdown(rows: list[CostRow]) -> list[ModelBreakdown]:"prompt": 0,"completion": 0,"cost": 0.0,- "imputed": 0.0,+ "measured_calls": 0,+ "estimated": 0.0,+ "estimated_calls": 0,+ "unpriced_calls": 0,+ "imputed": None,+ "unpriced_tokens": 0,+ "resolved": None,"latency_ms": 0.0,})@@ -284,19 +431,38 @@ def _model_breakdown(rows: list[CostRow]) -> list[ModelBreakdown]:agg["calls"] += r.call_countagg["prompt"] += r.prompt_tokensagg["completion"] += r.completion_tokens- agg["cost"] += r.cost_usd- agg["imputed"] += _impute_public_cost(m, r.prompt_tokens, r.completion_tokens)+ agg["cost"] += r.measured_cost_usd+ agg["measured_calls"] += r.measured_call_count+ agg["estimated"] += r.estimated_cost_usd+ agg["estimated_calls"] += r.estimated_call_count+ agg["unpriced_calls"] += r.unpriced_call_count+ imputed = _imputed_for_row(r)+ if imputed is None:+ # Counted, not silently dropped: an imputed total that quietly+ # skips half its rows reads as complete and is not.+ agg["unpriced_tokens"] += r.prompt_tokens + r.completion_tokens+ else:+ agg["imputed"] = (agg["imputed"] or 0.0) + imputed+ if r.resolved_model and not agg["resolved"]:+ agg["resolved"] = r.resolved_modelagg["latency_ms"] += r.latency_msbreakdowns = [ModelBreakdown(model=m,+ resolved_model=agg["resolved"],runs=len(agg["runs"]),calls=int(agg["calls"]),total_prompt_tokens=int(agg["prompt"]),total_completion_tokens=int(agg["completion"]),total_cost_usd=round(agg["cost"], 4),- imputed_public_cost_usd=round(agg["imputed"], 4),+ measured_call_count=int(agg["measured_calls"]),+ estimated_cost_usd=round(agg["estimated"], 4),+ estimated_call_count=int(agg["estimated_calls"]),+ unpriced_call_count=int(agg["unpriced_calls"]),+ imputed_public_cost_usd=round(agg["imputed"] or 0.0, 4),+ imputed_is_estimable=agg["imputed"] is not None,+ unpriced_tokens=int(agg["unpriced_tokens"]),avg_latency_ms=(round(agg["latency_ms"] / agg["calls"], 2) if agg["calls"] else None),)for m, agg in by_model.items()@@ -307,13 +473,18 @@ def _model_breakdown(rows: list[CostRow]) -> list[ModelBreakdown]:def _top_cases(rows: list[CostRow], *, limit: int = 10) -> list[TopCostCase]:"""The most expensive cases in the window."""- by_case: dict[str, dict[str, Any]] = defaultdict(lambda: {"runs": set(), "cost": 0.0, "tokens": 0})+ by_case: dict[str, dict[str, Any]] = defaultdict(+ lambda: {"runs": set(), "cost": 0.0, "measured_calls": 0, "estimated": 0.0, "estimated_calls": 0, "tokens": 0}+ )for r in rows:if not r.case_id:continueagg = by_case[r.case_id]agg["runs"].add(r.run_id)- agg["cost"] += r.cost_usd+ agg["cost"] += r.measured_cost_usd+ agg["measured_calls"] += r.measured_call_count+ agg["estimated"] += r.estimated_cost_usd+ agg["estimated_calls"] += r.estimated_call_countagg["tokens"] += r.prompt_tokens + r.completion_tokensitems = [@@ -321,11 +492,17 @@ def _top_cases(rows: list[CostRow], *, limit: int = 10) -> list[TopCostCase]:case_id=case_id,runs=len(agg["runs"]),total_cost_usd=round(agg["cost"], 4),+ measured_call_count=int(agg["measured_calls"]),+ estimated_cost_usd=round(agg["estimated"], 4),+ estimated_call_count=int(agg["estimated_calls"]),total_tokens=int(agg["tokens"]),)for case_id, agg in by_case.items()]- items.sort(key=lambda c: (-c.total_cost_usd, c.case_id))+ # Ranked on measured spend first, then the estimate, so a window with+ # nothing measured still ranks by the best information available rather+ # than collapsing into an arbitrary alphabetical order.+ items.sort(key=lambda c: (-c.total_cost_usd, -c.estimated_cost_usd, c.case_id))return items[:limit]@@ -336,46 +513,75 @@ def _action_counts(rows: list[AuditRow], *, limit: int = 20) -> list[ActionCountdef _byok_savings(rows: list[CostRow], llm: LlmContext) -> ByokSavings:- """Imputed savings vs hosted public pricing.-- The ``recorded_cost_usd`` reflects what the cost tracker actually- booked: on a hosted provider this is the public price, on a local- BYOK provider this is the *imputed* price (the agents service uses- the same pricing table when no upstream billing exists, so on- BYOK the recorded cost typically already matches imputed and the- delta is small or zero).-- Therefore on BYOK we report ``savings = imputed_public`` (i.e. the- operator avoided paying the hosted provider entirely). On a hosted- provider we report ``savings = max(imputed - recorded, 0)`` so the- UI can still surface a "you'd save X if you self-hosted" hint.+ """Imputed savings vs hosted public pricing — an estimate throughout.++ ``recorded_cost_usd`` is **measured** spend: what the gateway reported.+ It used to be whatever the tracker had booked, which on every deployment+ was a default list rate applied to a gateway alias — so on a local model+ the panel compared one invented number against another and called the+ difference a saving.++ On BYOK the saving is the whole imputed hosted cost (the operator avoided+ paying a provider at all). On a hosted provider it is+ ``max(imputed - measured, 0)``, a "you'd save X if you self-hosted" hint.+ Both read ``0.0`` with ``imputed_is_estimable`` False when nothing in the+ window has a public list price, because a saving computed over no+ priceable rows is not a small saving — it is no answer."""- recorded = sum(r.cost_usd for r in rows)- imputed = sum(_impute_public_cost(r.model, r.prompt_tokens, r.completion_tokens) for r in rows)- if llm.is_local:+ measured_rows = [r for r in rows if r.measured_call_count > 0]+ recorded = sum(r.measured_cost_usd for r in rows)++ imputed: float | None = None+ unpriced_tokens = 0+ for r in rows:+ row_imputed = _imputed_for_row(r)+ if row_imputed is None:+ unpriced_tokens += r.prompt_tokens + r.completion_tokens+ else:+ imputed = (imputed or 0.0) + row_imputed++ if imputed is None:+ savings = 0.0+ elif llm.is_local:savings = imputedelse:savings = max(imputed - recorded, 0.0)+return ByokSavings(is_byok_active=bool(llm.is_local),provider=llm.provider or "unknown",recorded_cost_usd=round(recorded, 4),- imputed_public_cost_usd=round(imputed, 4),+ recorded_is_measured=bool(measured_rows),+ imputed_public_cost_usd=round(imputed or 0.0, 4),+ imputed_is_estimable=imputed is not None,+ unpriced_tokens=unpriced_tokens,savings_usd=round(savings, 4),)def _headline(rows: list[CostRow]) -> CostHeadline:- total_cost = sum(r.cost_usd for r in rows)+ total_cost = sum(r.measured_cost_usd for r in rows)+ measured_calls = sum(r.measured_call_count for r in rows)+ estimated_cost = sum(r.estimated_cost_usd for r in rows)+ estimated_calls = sum(r.estimated_call_count for r in rows)+ unpriced_calls = sum(r.unpriced_call_count for r in rows)total_tokens = sum(r.prompt_tokens + r.completion_tokens for r in rows)total_calls = sum(r.call_count for r in rows)total_runs = len({r.run_id for r in rows if r.run_id})return CostHeadline(total_cost_usd=round(total_cost, 4),+ measured_call_count=int(measured_calls),+ estimated_cost_usd=round(estimated_cost, 4),+ estimated_call_count=int(estimated_calls),+ unpriced_call_count=int(unpriced_calls),total_tokens=int(total_tokens),total_calls=int(total_calls),total_runs=total_runs,- avg_cost_per_run_usd=(round(total_cost / total_runs, 4) if total_runs else None),+ # A mean of measured spend is only a mean when something was measured.+ # Dividing an unmeasured zero by the run count published "$0.0000 per+ # investigation", the most flattering number on the page, for a tenant+ # whose spend nobody knew.+ avg_cost_per_run_usd=(round(total_cost / total_runs, 4) if total_runs and measured_calls else None),)@@ -418,9 +624,22 @@ _COST_QUERY = text(SELECT c.run_id,r.case_id,c.model,+ c.resolved_model AS resolved_model,c.total_prompt_tokens AS prompt_tokens,c.total_completion_tokens AS completion_tokens,- c.total_cost_usd AS cost_usd,+ -- measured_cost_usd, not total_cost_usd: rows written before+ -- migration 063 hold a list-price guess in the latter, and+ -- measured_call_count = 0 is what marks them unmeasured.+ --+ -- The CASE is the guard, applied once here so no aggregator+ -- downstream has to remember it. A cost with no calls behind it is+ -- not a small cost, and must not enter a SUM as though it were.+ CASE WHEN c.measured_call_count > 0+ THEN c.measured_cost_usd ELSE 0 END AS measured_cost_usd,+ c.measured_call_count AS measured_call_count,+ c.estimated_cost_usd AS estimated_cost_usd,+ c.estimated_call_count AS estimated_call_count,+ c.unpriced_call_count AS unpriced_call_count,c.total_latency_ms AS latency_ms,c.call_count AS call_count,r.started_at AS started_at@@ -466,10 +685,15 @@ async def _fetch_cost_rows(model=str(r["model"] or "unknown"),prompt_tokens=int(r["prompt_tokens"] or 0),completion_tokens=int(r["completion_tokens"] or 0),- cost_usd=float(r["cost_usd"] or 0.0),+ measured_cost_usd=float(r["measured_cost_usd"] or 0.0),latency_ms=float(r["latency_ms"] or 0.0),call_count=int(r["call_count"] or 0),started_at=started_at or end,+ measured_call_count=int(r["measured_call_count"] or 0),+ estimated_cost_usd=float(r["estimated_cost_usd"] or 0.0),+ estimated_call_count=int(r["estimated_call_count"] or 0),+ unpriced_call_count=int(r["unpriced_call_count"] or 0),+ resolved_model=(str(r["resolved_model"]) if r["resolved_model"] else None),))return rows@@ -558,4 +782,6 @@ _internal_helpers: dict[str, Any] = {"_byok_savings": _byok_savings,"_headline": _headline,"_impute_public_cost": _impute_public_cost,+ "_imputed_for_row": _imputed_for_row,+ "_price_key": _price_key,}diff --git a/services/api/migrations/063_cost_provenance.sql b/services/api/migrations/063_cost_provenance.sqlnew file mode 100644index 000000000..2bcce8544--- /dev/null+++ b/services/api/migrations/063_cost_provenance.sql@@ -0,0 +1,72 @@+-- 063: how a recorded LLM cost is known, alongside the cost.+--+-- Until now a cost figure arrived with no provenance, and the only producer+-- guessed it: `CostTracker` looked the **model name** up in a table of hosted+-- list prices, and the name it looked up was an `aisoc-<role>` alias, which is+-- not a model. No alias was in the table, so every call took a `(0.001,+-- 0.002)` default — a price nobody charges, for a model nobody named. A+-- 903-token completion on an operator's own hardware was stored here as+-- $0.000999, and that figure fed the cost dashboard, the funnel insights, the+-- per-run ledger and the budget circuit breaker.+--+-- The gateway resolved the alias, so the gateway is the only party that knows+-- what ran and what it cost; it reports both on the response headers. This+-- migration gives both tables somewhere to put that, and — following the+-- precedent set for MTTR, where a mean over zero rows was shipping as a+-- confident 0.0 until the sample count travelled with it — somewhere to put+-- the count of calls each sum was computed over.+--+-- Three provenances, mutually exclusive per call:+--+-- measured the gateway reported the cost. Real money. A measured 0.0 (a+-- local model) is a fact, not a missing value.+-- estimated re-priced from a public list price for a **concrete** model id.+-- Labelled an estimate on every surface it reaches.+-- unpriced neither. Rendered "not measured", never as zero.+--+-- Back-compat and the existing rows+-- ---------------------------------+-- Every column is additive with a default, so nothing that reads these tables+-- today breaks. Crucially the new counters default to 0, which means every+-- pre-existing row reads as **not measured** on the new surfaces — which is+-- the truth about it. The historical `total_cost_usd` values are left in+-- place rather than deleted (they are the record of what was reported), but+-- no read path treats a figure as measured unless its counter says so.+--+-- From here on `total_cost_usd` carries **measured** cost only. It cannot also+-- carry the estimate: one column named for money cannot be labelled two ways,+-- and adding a guess to a measurement is how the guess stops looking like one.++ALTER TABLE aisoc_run_costs+ ADD COLUMN IF NOT EXISTS measured_cost_usd DOUBLE PRECISION NOT NULL DEFAULT 0,+ ADD COLUMN IF NOT EXISTS measured_call_count INTEGER NOT NULL DEFAULT 0,+ ADD COLUMN IF NOT EXISTS estimated_cost_usd DOUBLE PRECISION NOT NULL DEFAULT 0,+ ADD COLUMN IF NOT EXISTS estimated_call_count INTEGER NOT NULL DEFAULT 0,+ ADD COLUMN IF NOT EXISTS unpriced_call_count INTEGER NOT NULL DEFAULT 0,+ -- What the gateway resolved the requested alias to, e.g. `ollama/qwen2:1.5b`+ -- or `openai/gpt-4o-mini`. The alias asked for is not the model billed, and+ -- without this nothing downstream can say which it was.+ ADD COLUMN IF NOT EXISTS resolved_model TEXT;++COMMENT ON COLUMN aisoc_run_costs.total_cost_usd IS+ 'Measured (gateway-reported) cost only. Rows written before migration 063 '+ 'hold a list-price guess keyed on a gateway alias; measured_call_count = 0 '+ 'marks them as not measured.';+COMMENT ON COLUMN aisoc_run_costs.measured_call_count IS+ 'Calls the measured sum was computed over. 0 means not measured, which is '+ 'a different fact from a measured zero.';+COMMENT ON COLUMN aisoc_run_costs.estimated_cost_usd IS+ 'List-price estimate for calls the gateway did not price. Must be labelled '+ 'an estimate wherever it surfaces.';++ALTER TABLE investigation_runs+ ADD COLUMN IF NOT EXISTS measured_call_count INTEGER NOT NULL DEFAULT 0,+ ADD COLUMN IF NOT EXISTS estimated_cost_usd NUMERIC(10, 4) NOT NULL DEFAULT 0,+ ADD COLUMN IF NOT EXISTS estimated_call_count INTEGER NOT NULL DEFAULT 0,+ ADD COLUMN IF NOT EXISTS unpriced_call_count INTEGER NOT NULL DEFAULT 0;++COMMENT ON COLUMN investigation_runs.total_cost_usd IS+ 'Measured (gateway-reported) cost only; see measured_call_count. Deep '+ 'investigations never passed a value here at all before 063, so the column '+ 'held a hard-coded 0 that the console rendered as $0.0000 for runs that had '+ 'made real model calls.';diff --git a/services/api/tests/test_cost_dashboard.py b/services/api/tests/test_cost_dashboard.pyindex 5f143e974..14a2e3d86 100644--- a/services/api/tests/test_cost_dashboard.py+++ b/services/api/tests/test_cost_dashboard.py@@ -8,8 +8,8 @@ logic and not Postgres / SQLAlchemy plumbing.The tests deliberately cover:* daily bucketing across UTC midnight (timezone correctness)-* per-model aggregation, including unknown models that fall back to the- default public-list price+* per-model aggregation, including models with no public list price, which+ impute nothing rather than falling back to a default rate* top-cost case ranking with ties broken deterministically by ``case_id``* action-count ordering (most-common first) and the limit clamp* BYOK savings semantics:@@ -51,25 +51,39 @@ def _cost(latency_ms: float = 250.0,call_count: int = 1,started_at: datetime | None = None,+ measured_call_count: int | None = None,+ estimated_cost_usd: float = 0.0,+ estimated_call_count: int = 0,+ unpriced_call_count: int = 0,+ resolved_model: str | None = None,) -> CostRow:"""Builder that fills sensible defaults for a CostRow.When ``cost_usd`` is omitted we fall back to the imputed public cost so atest that wants "what a hosted call would have charged" can drop intothe constructor without recomputing pricing by hand.++ ``measured_call_count`` defaults to ``call_count``, i.e. these rows stand+ for gateway-measured spend. Pass ``0`` to build the row shape that every+ pre-migration-063 row has: a cost figure with nothing vouching for it."""if cost_usd is None:- cost_usd = _impute_public_cost(model, prompt_tokens, completion_tokens)+ cost_usd = _impute_public_cost(model, prompt_tokens, completion_tokens) or 0.0return CostRow(run_id=run_id or str(uuid.uuid4()),case_id=case_id,model=model,prompt_tokens=prompt_tokens,completion_tokens=completion_tokens,- cost_usd=cost_usd,+ measured_cost_usd=cost_usd,latency_ms=latency_ms,call_count=call_count,started_at=started_at or PERIOD_START + timedelta(hours=1),+ measured_call_count=(call_count if measured_call_count is None else measured_call_count),+ estimated_cost_usd=estimated_cost_usd,+ estimated_call_count=estimated_call_count,+ unpriced_call_count=unpriced_call_count,+ resolved_model=resolved_model,)@@ -84,11 +98,26 @@ def test_impute_public_cost_known_model() -> None:assert cost == pytest.approx(0.00015 + 0.0003, rel=1e-9)-def test_impute_public_cost_unknown_model_uses_default() -> None:- # Unknown model falls back to the conservative default, not zero, so we- # never silently report 100% savings on a bespoke local model.- cost = _impute_public_cost("super-secret-llm", 1000, 1000)- assert cost > 0+def test_impute_public_cost_unknown_model_imputes_nothing() -> None:+ """An unknown model has no price, and a default rate is not one.++ This test used to assert the opposite — ``cost > 0`` — on the reasoning+ that a default was "conservative" and stopped us reporting 100% savings+ on a bespoke local model. The reasoning had it backwards. The agents+ service records the ``aisoc-<role>`` alias it *requested*, and an alias+ is in no price table, so the default applied to essentially every row:+ the "imputed list price" was a made-up rate for a made-up model, and a+ 903-token local completion booked $0.000999 of spend that never existed.+ ``None`` is the honest answer and the caller counts the row as unpriced.+ """+ assert _impute_public_cost("super-secret-llm", 1000, 1000) is None+ assert _impute_public_cost("aisoc-triage", 1_000_000, 1_000_000) is None+ assert _impute_public_cost("ollama/qwen2:1.5b", 1_000_000, 1_000_000) is None+++def test_impute_public_cost_strips_a_provider_prefix() -> None:+ """The gateway names a resolved model ``openai/gpt-4o-mini``."""+ assert _impute_public_cost("openai/gpt-4o-mini", 1000, 500) == pytest.approx(_impute_public_cost("gpt-4o-mini", 1000, 500))def test_impute_public_cost_negative_token_counts_clamped() -> None:@@ -286,6 +315,11 @@ def test_byok_savings_empty_rows() -> None:savings_fn = _internal_helpers["_byok_savings"]result = savings_fn([], LlmContext(provider="none", is_local=False))assert result.recorded_cost_usd == 0.0+ # Nothing to measure and nothing to price: both are unknown, not zero.+ assert result.recorded_is_measured is False+ # 0.0 with the flag off, not None: nullable would break every generated+ # SDK client for a fact the flag already carries (the MTTR precedent).+ assert result.imputed_is_estimable is Falseassert result.imputed_public_cost_usd == 0.0assert result.savings_usd == 0.0@@ -335,12 +369,14 @@ def test_build_dashboard_empty_inputs_is_well_formed() -> None:assert dashboard.tenant_id == TENANT_IDassert dashboard.period.window_days == 7assert dashboard.headline.total_cost_usd == 0.0+ assert dashboard.headline.measured_call_count == 0, "zero rows measured nothing"assert dashboard.daily_costs == []assert dashboard.by_model == []assert dashboard.top_cases == []assert dashboard.action_counts == []# BYOK panel is always present so the UI doesn't have to special-case it.assert dashboard.byok_savings.is_byok_active is False+ assert dashboard.byok_savings.imputed_is_estimable is Falseassert dashboard.byok_savings.savings_usd == 0.0diff --git a/services/mcp/src/tools/investigations.ts b/services/mcp/src/tools/investigations.tsindex bef752950..919415223 100644--- a/services/mcp/src/tools/investigations.ts+++ b/services/mcp/src/tools/investigations.ts@@ -20,7 +20,17 @@ interface RunSummary {model_used: string | null;iterations: number;total_tokens: number;+ /**+ * Measured (gateway-reported) spend. Read it together with+ * `measured_call_count`: a zero there means the cost was never measured,+ * which an agent consuming this must not report as a free run.+ */total_cost_usd: number;+ measured_call_count: number;+ /** List-price estimate for calls the gateway did not price. Label it. */+ estimated_cost_usd: number;+ estimated_call_count: number;+ unpriced_call_count: number;started_at: string;completed_at: string | null;error: string | null;