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
fix(metering): classify every tier the worker stamps, not just the deterministic one (fix-pass 4.4) (#1292)
Beenu Arora5b090cdb6dc5
diff --git a/FIX_PASS_PROGRESS.md b/FIX_PASS_PROGRESS.mdindex dc8cad182..225476c47 100644--- a/FIX_PASS_PROGRESS.md+++ b/FIX_PASS_PROGRESS.md@@ -106,7 +106,8 @@ conditional `numpy` pins collide into an unresolvable install. Parse with- [x] **4.2** Console MFA- Reproduced first: ten of eleven assertions against the real login route and real Postgres failed with `{"detail":"Not Found"}` — the surface did not exist. TOTP (RFC 6238, in-tree, pinned to the spec's own vectors rather than to a round trip), ten single-use recovery codes, a vault-encrypted secret, a `last_used_step` high-water mark so a code cannot be replayed inside its own 30-second window, per-tenant enforcement with **no backfill row** (absence means not required), and audited enrolment, disable, recovery-code use, policy change and administrative reset. A correct password for an enrolled account now answers **202** with a challenge instead of a session — 202 rather than a widened 200 body, because `access_token` is a required field and making it optional breaks every generated client. An unenrolled member of a newly-enforcing tenant enrols from that challenge rather than being locked out; the trade-off is stated in the module and the docs. Migration `096`. 28 offline tests, 13 live, and a CI negative control that deletes the challenge branch and requires the suite to go red.- [ ] **4.3** White-label reaches every surface it claims-- [ ] **4.4** Metering counts what happened+- [x] **4.4** Metering counts what happened+ - All five bullets fixed rather than narrowed. `triages_model` and `triages_deterministic` read `investigation_runs.model_used` — the path auto-triage records for itself — instead of `alerts.ai_summary`/`ai_score`, which `persist_auto_triage` writes from one statement on **both** paths, so a deployment with no model configured reported 100% AI triage; `investigations` now excludes auto-triage runs, which had made it a second alert count wearing a different label; `events_ingested` is a real ClickHouse meter, grouped per day in one scan, reported as **not measured** rather than `0` when the lake is absent *or* deployed-and-unreachable; actions split into `automatic` / `human_gated` / `tier_unrecorded` behind migration `095`, which also adds `approval_tier` and repairs a `status` column that had held `'ActionStatus.COMPLETED'` since the table was added — the repr of a `(str, Enum)` member, which no query and no index could ever match; and `GET /usage/organization/export.csv` exports a portfolio, scoped by `resolve_portfolio_scope` and refusing a non-member rather than quietly falling back to their own tenant. The audit found one defect the branch had introduced: the path meters discriminated on `model_used <> 'kafka:auto_triage:deterministic'`, which reads as "the model path" only while `deterministic` is the sole alternative, and the worker stamps **four** tiers — `memory` (institutional-memory suppression) and `cached` (a deduplicated replay) place no LLM call and were both counted as AI triages, by the meter *and* by the `triages_per_month` quota that shares the definition. That is the same false sentence reached by another route, and it was live on `main`. `MODEL_TIERS`/`NON_MODEL_TIERS` now enumerate the vocabulary, and an AST pin reads the worker's own tier literals and fails on any tier no meter classifies — the fixture could not have caught it, having seeded only the two tiers that already worked. 35 offline tests, every assertion against rows counted independently in the test; the two new cases were confirmed to fail against the pre-fix predicate and the pin to fail with a tier removed. `tests/isolation/test_usage_lake_meter_live.py` was run against a real ClickHouse carrying the shipped `001_init.sql` — six cases pass, and dropping the tenant predicate makes the suite red, as its CI negative control requires.- [ ] **4.5** SCIM live coverage and the console token claim- [ ] **4.6** Maturity evidence names tests that exercise the rowdiff --git a/apps/docs/docs/operations/usage-metering.md b/apps/docs/docs/operations/usage-metering.mdindex dc211be38..bcc764c49 100644--- a/apps/docs/docs/operations/usage-metering.md+++ b/apps/docs/docs/operations/usage-metering.md@@ -48,10 +48,16 @@ columns from the same statement the model path does. A meter reading themreported a deployment with no model configured at all as 100% AI-triaged.What does record the path is `investigation_runs.model_used`, which-auto-triage stamps as `kafka:auto_triage:llm` or-`kafka:auto_triage:deterministic`. That is what these meters read, and it is-also what `triages_per_month` counts against your plan limit, so the usage-screen and the quota screen cannot disagree about the same rows.+auto-triage stamps as `kafka:auto_triage:<tier>`. There are four tiers and+only `llm` reaches a model: `deterministic` is the rule path, `memory` is+institutional-memory suppression, and `cached` is a deduplicated replay of a+verdict an earlier run already reached. `triages_model` counts the first and+`triages_deterministic` counts the other three, named individually rather+than inferred as "not deterministic" — a tier added later would otherwise+land in the AI count by default, which is how the meter was wrong before.++That is also what `triages_per_month` counts against your plan limit, so the+usage screen and the quota screen cannot disagree about the same rows.`active_connectors` and `seats` are point-in-time rather than windowed.Counting them per day would report today's value against every historicaldiff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex 99921f225..bbcc6e6db 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -228,7 +228,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| No principal can confer a role, scope or organisation membership beyond the authority it was itself admitted on, and the wildcard roles are unreachable from any request | `apps/docs/docs/operations/security.md` (Role grants are scoped to the granter); GHSA-pm3f-h6gc-rvgp; GHSA-4gx4-x7gm-4xq8 | `isolation.yml` (`check_role_grant_scope.py` asks of every handler binding a request model that declares `role`, `org_role`, `granted_role`, `scopes`, `role_id` or `permission_ids` whether it reaches `app.core.role_grants`, checks each waiver still covers a live handler, and derives the refused set from `ROLE_PERMISSIONS` so a role declared with the wildcard later is un-grantable the moment it is declared; and asks of every call to `authorize_role_grant`, `authorize_role_change` or `authorize_permission_grant` whether it passes `granter_permissions=`, since reaching the chokepoint while handing it the caller's *static* role measures the grant against an authority the caller was not admitted on; seven injected drifts prove it fails, and run against the pre-fix tree it names all nine handlers and all six under-authorised call sites) + `ci.yml` api job (`test_role_grant_scope.py` calls the shipped handlers and asserts both directions per call site — the escalating request is refused and nothing is written, a legitimate grant still lands; 16 of its 28 tests fail against the vulnerable tree, every one of them for the grant succeeding rather than for a missing symbol) + `ci.yml` api job (`test_role_grant_effective_permissions.py` drives the same handlers with a principal whose database permissions are narrower than its static role; 7 of its 10 tests fail against the pre-fix tree, each for the escalation landing, and the other 3 hold the positive direction so a tenant with no RBAC rows keeps conferring what its role confers) | core | GATED | Scoped to grants a *request* makes. `scripts/bootstrap_admin.py` still mints a wildcard role out of band with database credentials, which is deliberate: it is the only path left, and it is not reachable over HTTP || An uploaded brand asset cannot execute, and is never fetched from a third party | `plans/aisoc_gap_closure_plan.plan.md` (13.2); `apps/docs/docs/operations/white-label.md` (SVG uploads are sanitised) | `ci.yml` api job (`test_svg_sanitizer.py`, 29 cases written as attacks rather than round trips: `<script>`, a namespace-qualified `<svg:script>` that a bare-name comparison misses, event handlers, `<foreignObject>` in well-formed XML, `<animate attributeName="href">`, `<set>`, an external `<use xlink:href>`, a remote `<image>`, `@import`, a `fill="url(https://…)"` paint server, `javascript:` in an `<a>`, a billion-laughs DTD, an XXE entity and a bare DOCTYPE. A benign logo is asserted to survive **intact**, because a sanitiser that removes everything is safe and useless) + `isolation.yml` (`check_whitelabel_metering.py` refuses any script-capable element or `on*` attribute entering the allowlist, and refuses a remote scheme in the logo reference; proven able to fail by injecting each) | core | GATED | Allowlist rather than denylist: a denylist of `<script>` passes while `<foreignObject>` renders arbitrary HTML. DTD and entity declarations are refused on a byte scan before parsing, which removes the expansion class rather than bounding it || A white-labelled organisation's console and PDF report carry its branding | `plans/aisoc_gap_closure_plan.plan.md` (13.2, Done when); `apps/docs/docs/operations/white-label.md` | `ci.yml` api job (`test_branding.py` renders the digest HTML that becomes the PDF and asserts the product name, the palette and the logo are present **and** that the platform wordmark is gone, since a report showing both is co-branded by accident; a separate case asserts the rendered report contains **no** external URL at all) + `web` job (`SidebarBranding.test.tsx` renders the real console shell against a branded API response and reads the wordmark out of the DOM, mocking the API client rather than the hook so the wiring is inside the test) | core | GATED | The PDF is this HTML through WeasyPrint, so asserting on the HTML asserts on the PDF without requiring the native stack in CI. Email approvals and ChatOps read the same resolved `sender_name` and are **not** covered end to end; the doc says so rather than implying they are |-| Usage metering equals the rows it summarises | `plans/aisoc_gap_closure_plan.plan.md` (13.3, Done when); `apps/docs/docs/operations/usage-metering.md` (Checking the numbers) | `ci.yml` api job (`test_usage_metering.py`, 32 cases. Every assertion counts rows **independently in the test** and compares, rather than comparing a producer against a copy of itself, which is how two console figures in this repository were wrong on real data while passing. The daily series summed is asserted equal to one query over the whole window; an alert seeded at exactly midnight is asserted counted once; another tenant's rows sit inside the window and are asserted never counted; `triages_model` + `triages_deterministic` + `investigations` is asserted to equal the **run** count exactly, and the three action tiers to equal the action count, so nothing is unaccounted for or double-counted; the quota's own count and the meter are asserted to agree on the same rows) | core | GATED | Computed from source tables on request rather than kept in a counter table. A counter can only be tested against itself; a query cannot drift from the rows because it is the rows. Equalling the rows was never sufficient on its own: `triages_model` satisfied it for four releases while reading `alerts.ai_summary`, which the **deterministic** path writes too, so a deployment with no model reported 100% AI triage. The meters read `investigation_runs.model_used`, the path auto-triage records for itself, pinned against that producer by an AST check. `GET /usage/reconciliation` exposes the same comparison so an operator can run it on their own data |+| Usage metering equals the rows it summarises | `plans/aisoc_gap_closure_plan.plan.md` (13.3, Done when); `apps/docs/docs/operations/usage-metering.md` (Checking the numbers) | `ci.yml` api job (`test_usage_metering.py`, 32 cases. Every assertion counts rows **independently in the test** and compares, rather than comparing a producer against a copy of itself, which is how two console figures in this repository were wrong on real data while passing. The daily series summed is asserted equal to one query over the whole window; an alert seeded at exactly midnight is asserted counted once; another tenant's rows sit inside the window and are asserted never counted; `triages_model` + `triages_deterministic` + `investigations` is asserted to equal the **run** count exactly, and the three action tiers to equal the action count, so nothing is unaccounted for or double-counted; the quota's own count and the meter are asserted to agree on the same rows) | core | GATED | Computed from source tables on request rather than kept in a counter table. A counter can only be tested against itself; a query cannot drift from the rows because it is the rows. Equalling the rows was never sufficient on its own: `triages_model` satisfied it for four releases while reading `alerts.ai_summary`, which the **deterministic** path writes too, so a deployment with no model reported 100% AI triage. The meters read `investigation_runs.model_used`, the path auto-triage records for itself, pinned against that producer by an AST check — including the *vocabulary*, because the worker stamps four tiers and discriminating on "not the deterministic literal" counted institutional-memory suppression and deduplicated replays as AI triages, reaching the same false sentence by another route. `GET /usage/reconciliation` exposes the same comparison so an operator can run it on their own data || Metering reports "not measured" rather than zero, and carries no pricing logic | `plans/aisoc_gap_closure_plan.plan.md` (13.3, "No pricing logic"); `apps/docs/docs/operations/usage-metering.md` (What is not measured) | `ci.yml` api job (`test_usage_metering.py::TestHonesty` asserts `events_ingested` is named by `unmeasured()` with a reason on a deployment with no lake, and is **not** a Postgres meter, so it can never be reported as a number by one; the matching case asserts the gap disappears on a deployment that *can* take it, since announcing "not measured" over a running lake is the same lie reversed; asserts no meter key, label or SQL carries pricing vocabulary; asserts every meter binds its tenant as a parameter and formats nothing) + `isolation.yml` (`check_whitelabel_metering.py` re-checks all three against the declarations and was proven able to fail by removing a tenant binding) | core | GATED | The pricing check reads key, label and SQL only. `llm_cost_usd` is a measured provider charge and its description has to be able to say "not a price"; a gate forbidding the word would forbid the disclaimer with it. The lake meter itself is unit-covered on both branches; **it has not been run against a live ClickHouse**, and `lake-live.yml` is where that would land || Auto-triage reads the tenant's knowledge-base runbooks and cites the chunks it was given | `apps/docs/docs/console/triage-context.md` (Knowledge-base runbooks) | `ci.yml` agents job (`test_triage_knowledge_base.py`: the block reaches the prompt ahead of the telemetry, every chunk carries a marker resolving to a document id **and chunk index**, the prompt names the markers the model may cite, and a marker no retrieved chunk carries is reported on the verdict's basis rather than left reading like one that resolves; an empty retrieval renders nothing at all, because "Runbooks: none" is a claim about the tenant) + `ci.yml` api job (`test_kb_triage_retrieval_route.py`: service-token only, a valid console session refused, tenant and query bound rather than interpolated) | core | GATED | The agents service had never read the knowledge base. Retrieval is the API's own full-text query and ranking rather than a second implementation, so a chunk triage was given is one an analyst searching by hand would have found || Retrieved knowledge-base text is contained as untrusted evidence, not as first-party guidance | `apps/docs/docs/console/triage-context.md` (How runbook text is contained) | `ci.yml` agents job (`test_triage_knowledge_base.py::TestContainment`: the block is nonce-fenced with the boundary sentence stated inline; a chunk echoing the fence is refused; **a leaked nonce is stripped even for a chunk the guard passes**, which is the property that matters because the guard's own held-out rate is 2 of 28; a high-severity chunk is dropped rather than demoting the alert, and the refusal is published on the verdict's basis. The scan runs on the raw text, pinned by a payload the *sanitiser* also recognises: sanitising first rewrites it to a redaction marker, the guard then reads a clean string, and the whole "ignore previous" family would score zero forever while the counter reported a clean library) | core | GATED | More containment than tenant-skill text gets, because a runbook is long, often imported in bulk, edited by more people, and reaches the prompt as prose that routinely quotes attacker output. Dropping the chunk rather than demoting the case is deliberate: demoting would let anyone who can write a runbook switch off auto-close for the tenant |diff --git a/services/api/app/services/entitlements.py b/services/api/app/services/entitlements.pyindex 863467010..6b1d2cbfb 100644--- a/services/api/app/services/entitlements.py+++ b/services/api/app/services/entitlements.py@@ -31,11 +31,11 @@ from dataclasses import dataclassfrom datetime import UTC, datetime, timedeltafrom typing import Any, Final-from sqlalchemy import DateTime, String, Uuid, bindparam, text+from sqlalchemy import DateTime, Uuid, bindparam, textfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.core.config import settings-from app.services.usage_metering import AUTO_TRIAGE_PREFIX, DETERMINISTIC_RUN+from app.services.usage_metering import MODEL_RUNSlogger = logging.getLogger("aisoc.entitlements")@@ -96,8 +96,7 @@ LIMIT_KEYS: Final[tuple[LimitKey, ...]] = ("Auto-triage runs that reached a model this calendar month.",("SELECT count(*) FROM investigation_runs "- "WHERE tenant_id = :tenant_id AND created_at >= :month_start "- "AND model_used LIKE :auto_triage_prefix || '%' AND model_used <> :deterministic_run"+ "WHERE tenant_id = :tenant_id AND created_at >= :month_start AND model_used IN :model_runs"),),)@@ -216,10 +215,13 @@ _BIND_TYPES: Final[dict[str, Any]] = {"tenant_id": Uuid(as_uuid=True),"since": DateTime(timezone=True),"month_start": DateTime(timezone=True),- "auto_triage_prefix": String(),- "deterministic_run": String(),}+#: Bound as a list, and imported rather than rebuilt here: a quota that+#: decides "which runs are AI triages" for itself is a second definition,+#: and the two drift in front of a customer who is being throttled.+_EXPANDING: Final[tuple[str, ...]] = ("model_runs",)+async def measure_usage(db: AsyncSession, tenant_id: uuid.UUID) -> dict[str, int]:"""Count current usage of every limit key for one tenant."""@@ -230,14 +232,17 @@ async def measure_usage(db: AsyncSession, tenant_id: uuid.UUID) -> dict[str, int"month_start": now.replace(day=1, hour=0, minute=0, second=0, microsecond=0),# Imported rather than repeated, so "which runs are AI triages" has# one definition shared with the usage meters.- "auto_triage_prefix": AUTO_TRIAGE_PREFIX,- "deterministic_run": DETERMINISTIC_RUN,+ "model_runs": list(MODEL_RUNS),}usage: dict[str, int] = {}for key in LIMIT_KEYS:present = [name for name in _BIND_TYPES if f":{name}" in key.usage_sql]- statement = text(key.usage_sql).bindparams(*[bindparam(name, type_=_BIND_TYPES[name]) for name in present])- result = await db.execute(statement, {name: params[name] for name in present})+ expanding = [name for name in _EXPANDING if f":{name}" in key.usage_sql]+ statement = text(key.usage_sql).bindparams(+ *[bindparam(name, type_=_BIND_TYPES[name]) for name in present],+ *[bindparam(name, expanding=True) for name in expanding],+ )+ result = await db.execute(statement, {name: params[name] for name in (*present, *expanding)})usage[key.name] = int(result.scalar_one() or 0)return usagediff --git a/services/api/app/services/usage_metering.py b/services/api/app/services/usage_metering.pyindex 2c4fde377..0080c8ce8 100644--- a/services/api/app/services/usage_metering.py+++ b/services/api/app/services/usage_metering.py@@ -60,14 +60,38 @@ from app.db.clickhouse import LakeQueryError, LakeQueryNotConfiguredError, execulogger = logging.getLogger("aisoc.usage_metering")#: What `services/agents` stamps into `investigation_runs.model_used` for a-#: run the Kafka auto-triage worker started: `kafka:auto_triage:<tier>`,-#: where the tier is `llm` or `deterministic`+#: run the Kafka auto-triage worker started: `kafka:auto_triage:<tier>`#: (`services/agents/app/investigator/ledger.py`, `persist_auto_triage`).#:#: Pinned against that producer by#: `TestTheProducerStillWritesWhatTheseMetersRead`, because the two services#: both name their top-level package `app` and cannot import each other.AUTO_TRIAGE_PREFIX: Final[str] = "kafka:auto_triage:"++#: The tiers on which a model answered. One, today.+MODEL_TIERS: Final[tuple[str, ...]] = ("llm",)++#: The tiers that answered without placing a model call, enumerated rather+#: than inferred as "everything else".+#:+#: Inferring was the first version of this fix and it reproduced the defect+#: it was closing. `model_used <> 'kafka:auto_triage:deterministic'` reads+#: as "the model path" only if `deterministic` is the sole non-model tier,+#: and the worker has four: it also answers from the dedup cache and from+#: institutional memory, neither of which places a call. Both would have+#: been counted as AI triages — on a deployment with no model configured at+#: all, which is the exact sentence this item exists to make false.+#:+#: `cached` is a deduplicated replay of a verdict some earlier run reached.+#: It is counted here because the meter answers "what did this run spend",+#: and a replay spent nothing; charging a tenant's AI-triage quota for it+#: would bill them twice for one verdict.+NON_MODEL_TIERS: Final[tuple[str, ...]] = ("cached", "deterministic", "memory")++MODEL_RUNS: Final[tuple[str, ...]] = tuple(f"{AUTO_TRIAGE_PREFIX}{tier}" for tier in MODEL_TIERS)+NON_MODEL_RUNS: Final[tuple[str, ...]] = tuple(f"{AUTO_TRIAGE_PREFIX}{tier}" for tier in NON_MODEL_TIERS)++#: Kept because `replay_redaction` and the entitlement limit both name it.DETERMINISTIC_RUN: Final[str] = f"{AUTO_TRIAGE_PREFIX}deterministic"#: The approval tier `services/actions` grades a submission at, recorded on@@ -132,18 +156,17 @@ METERS: Final[tuple[Meter, ...]] = ("investigation_runs",("SELECT count(*) FROM investigation_runs WHERE tenant_id = :tenant_id "- "AND created_at >= :start AND created_at < :end "- "AND model_used LIKE :auto_triage_prefix || '%' AND model_used <> :deterministic_run"+ "AND created_at >= :start AND created_at < :end AND model_used IN :model_runs"),),Meter("triages_deterministic","Deterministic triages",- "Auto-triage runs answered without a model: rule verdicts and institutional-memory suppression.",+ "Auto-triage runs answered without a model: rule verdicts, institutional-memory suppression, and deduplicated replays.","investigation_runs",("SELECT count(*) FROM investigation_runs WHERE tenant_id = :tenant_id "- "AND created_at >= :start AND created_at < :end AND model_used = :deterministic_run"+ "AND created_at >= :start AND created_at < :end AND model_used IN :non_model_runs"),),Meter(@@ -421,19 +444,24 @@ _BIND_TYPES: Final[dict[str, Any]] = {# meter whose discriminator is a string literal in SQL is one a reader# has to diff against the producer by eye."auto_triage_prefix": String(),- "deterministic_run": String(),"automatic_tier": String(),"executed_status": String(),}+#: Parameters bound as a list rather than a scalar. `IN :model_runs` names+#: the tiers it counts, so the set a meter discriminates on is readable in+#: one place instead of being the complement of a literal somewhere else.+_EXPANDING: Final[tuple[str, ...]] = ("model_runs", "non_model_runs")+#: Every discriminator the windowed meters bind, beside the tenant and the#: window. Constant per deployment, so they are assembled once here rather#: than threaded through each call site.-_DISCRIMINATORS: Final[dict[str, str]] = {+_DISCRIMINATORS: Final[dict[str, Any]] = {"auto_triage_prefix": AUTO_TRIAGE_PREFIX,- "deterministic_run": DETERMINISTIC_RUN,"automatic_tier": AUTOMATIC_TIER,"executed_status": EXECUTED_STATUS,+ "model_runs": list(MODEL_RUNS),+ "non_model_runs": list(NON_MODEL_RUNS),}@@ -441,6 +469,7 @@ def _statement(sql: str) -> Any:"""A ``text()`` clause with every parameter it uses explicitly typed."""clause = text(sql)present = [bindparam(name, type_=kind) for name, kind in _BIND_TYPES.items() if f":{name}" in sql]+ present += [bindparam(name, expanding=True) for name in _EXPANDING if f":{name}" in sql]return clause.bindparams(*present) if present else clausediff --git a/services/api/tests/test_usage_metering.py b/services/api/tests/test_usage_metering.pyindex 5c0546ace..42cfecf58 100644--- a/services/api/tests/test_usage_metering.py+++ b/services/api/tests/test_usage_metering.py@@ -164,6 +164,12 @@ async def _alert(db, *, tenant: uuid.UUID, when: datetime, ai: bool) -> None:#: two literals honest.DETERMINISTIC_RUN = "kafka:auto_triage:deterministic"MODEL_RUN = "kafka:auto_triage:llm"+#: The two tiers the worker also stamps, both of which answer without+#: placing a model call. Seeded because a fixture holding only the first two+#: cannot tell "the model path" from "not the deterministic path", and the+#: meters read the second for four days of this branch's life.+MEMORY_RUN = "kafka:auto_triage:memory"+CACHED_RUN = "kafka:auto_triage:cached"def _run(db, *, tenant: uuid.UUID, when: datetime, case: str, model_used: str | None) -> None:@@ -200,10 +206,11 @@ async def seeded(session_factory):for hour in (2, 3, 4, 5):await _alert(db, tenant=OTHER_TENANT, when=_at(DAY_ONE, hour), ai=True)- # Seven runs for this tenant across the three days, in the three- # shapes `investigation_runs` actually holds: auto-triage that- # reached a model, auto-triage that did not, and an analyst-driven- # investigation. All three counts differ, so a meter that collapsed+ # Nine runs for this tenant across the three days, covering every+ # tier the worker stamps plus the analyst-driven shape: auto-triage+ # that reached a model, auto-triage answered on each of the three+ # paths that did not, and an investigation that is not auto-triage+ # at all. All three meter counts differ, so a meter that collapsed# any two of them cannot pass by coincidence._run(db, tenant=TENANT, when=_at(DAY_ONE, 0), case="a1", model_used=DETERMINISTIC_RUN)_run(db, tenant=TENANT, when=_at(DAY_ONE, 13), case="a2", model_used=MODEL_RUN)@@ -211,6 +218,9 @@ async def seeded(session_factory):_run(db, tenant=TENANT, when=_at(DAY_ONE + timedelta(days=1), 9), case="a3", model_used=DETERMINISTIC_RUN)_run(db, tenant=TENANT, when=_at(DAY_ONE + timedelta(days=1), 10), case="a4", model_used=DETERMINISTIC_RUN)_run(db, tenant=TENANT, when=_at(DAY_ONE + timedelta(days=2), 1), case="a5", model_used=MODEL_RUN)+ # Auto-triage that answered without a model on the other two tiers.+ _run(db, tenant=TENANT, when=_at(DAY_ONE, 15), case="a6", model_used=MEMORY_RUN)+ _run(db, tenant=TENANT, when=_at(DAY_ONE + timedelta(days=1), 11), case="a7", model_used=CACHED_RUN)# `start_run` leaves `model_used` null when the caller names no# model, and `replay_redaction` already reads that as deterministic.# It is still an investigation, so it belongs in that meter.@@ -388,6 +398,33 @@ class TestThePathMetersReadTheRecordedPath:assert values["triages_model"] == 0, "a deterministic triage was counted as a model triage"assert values["triages_deterministic"] == 1+ @pytest.mark.parametrize("tier", ["memory", "cached"])+ async def test_a_run_that_placed_no_call_is_not_a_model_triage(self, session_factory, tier):+ """The worker has four tiers, and only one of them reaches a model.++ `memory` is institutional-memory suppression and `cached` is a+ deduplicated replay. Neither places an LLM call — the worker says+ so in as many words — so neither is an AI triage, and on a+ deployment with no model configured both can still happen.++ Discriminating on "not the deterministic literal" counted both as+ AI triages, which is the same sentence this item exists to make+ false, reached by a different route.+ """+ async with session_factory() as db:+ _run(db, tenant=TENANT, when=_at(DAY_ONE, 9), case="alert-1", model_used=f"kafka:auto_triage:{tier}")+ await db.commit()++ async with session_factory() as db:+ values = (await usage_metering.measure_day(db, TENANT, DAY_ONE)).values+ quota = await measure_usage(db, TENANT)++ assert values["triages_model"] == 0, f"a `{tier}` run was counted as a model triage"+ assert values["triages_deterministic"] == 1, f"a `{tier}` run went unaccounted for"+ assert values["investigations"] == 0, f"a `{tier}` run was counted as an analyst investigation"+ # The quota shares the definition, so it has to share the fix.+ assert quota["triages_per_month"] == 0, f"a `{tier}` run burned the tenant's AI-triage quota"+async def test_a_model_triage_is_counted_as_one(self, session_factory):"""The other half of the control.@@ -466,6 +503,56 @@ class TestTheProducerStillWritesWhatTheseMetersRead:f"the ledger no longer stamps `kafka:auto_triage:<tier>`; it writes {stamps!r}")+ #: Where the tier literals are decided, as opposed to where they are+ #: written. `persist_auto_triage` interpolates whatever its caller+ #: passed, so reading the ledger alone proves the *prefix* and says+ #: nothing about the vocabulary.+ WORKER = pathlib.Path(__file__).resolve().parents[3] / "services" / "agents" / "app" / "workers" / "fused_alert_consumer.py"++ def test_every_tier_the_worker_can_stamp_is_classified(self):+ """A new tier must red this, not land silently in `triages_model`.++ The vocabulary lives in the worker and the classification lives+ here, in another service that cannot import it. Nothing connected+ the two, which is how `memory` and `cached` came to be counted as+ AI triages: the meters discriminated on "not the deterministic+ literal", and that reads as "the model path" only while+ `deterministic` is the sole alternative.++ Read from source rather than imported for the usual reason — both+ services call their top-level package `app`.+ """+ assert self.WORKER.exists(), f"{self.WORKER} has moved; the tier vocabulary is no longer pinned"+ tree = ast.parse(self.WORKER.read_text())++ stamped: set[str] = set()+ for node in ast.walk(tree):+ # `tier = "cached"` and `tier: str = "..."`.+ targets = [node.target] if isinstance(node, ast.AnnAssign) else list(node.targets) if isinstance(node, ast.Assign) else []+ if any(isinstance(t, ast.Name) and t.id == "tier" for t in targets):+ if isinstance(node.value, ast.Constant) and isinstance(node.value.value, str):+ stamped.add(node.value.value)+ # `tier="memory"` passed to `_record` / `persist_auto_triage`.+ if isinstance(node, ast.Call):+ for kw in node.keywords:+ if kw.arg == "tier" and isinstance(kw.value, ast.Constant) and isinstance(kw.value.value, str):+ stamped.add(kw.value.value)+ # `return state, "llm"` out of `_llm_triage`, whose contract is+ # `tuple[InvestigationState, str]` — the str is the tier.+ if isinstance(node, ast.AsyncFunctionDef | ast.FunctionDef) and node.name == "_llm_triage":+ for inner in ast.walk(node):+ if isinstance(inner, ast.Return) and isinstance(inner.value, ast.Tuple):+ stamped |= {e.value for e in inner.value.elts if isinstance(e, ast.Constant) and isinstance(e.value, str)}++ assert stamped, "no tier literals found in the worker; this pin has stopped reading the vocabulary"+ classified = set(usage_metering.MODEL_TIERS) | set(usage_metering.NON_MODEL_TIERS)+ assert stamped <= classified, (+ f"the auto-triage worker stamps {sorted(stamped - classified)!r}, which no meter classifies. "+ "Add each to MODEL_TIERS or NON_MODEL_TIERS in usage_metering — a tier in neither is a run "+ "missing from every triage meter, and the usage screen will not add up."+ )+ assert not set(usage_metering.MODEL_TIERS) & set(usage_metering.NON_MODEL_TIERS), "a tier cannot be both"+def test_the_alert_columns_are_written_on_both_paths(self):"""Which is why the meters cannot read them.diff --git a/tests/isolation/test_usage_lake_meter_live.py b/tests/isolation/test_usage_lake_meter_live.pyindex 446c13ac3..82b4be970 100644--- a/tests/isolation/test_usage_lake_meter_live.py+++ b/tests/isolation/test_usage_lake_meter_live.py@@ -89,7 +89,18 @@ def _at(day: date, hour: int) -> datetime:@pytest.fixture(scope="module")def lake():"""A ClickHouse carrying the product's own schema and a known corpus."""- driver = pytest.importorskip("clickhouse_driver")+ # Not `importorskip`. The module-level guard above has already decided+ # this is a live run, so a missing driver is a broken job and not an+ # absent store — and a skip here would leave `pytest` exiting 0 with+ # nothing measured, which is the shape that let a weekly evaluation+ # report success for ten weeks having graded nothing.+ try:+ import clickhouse_driver as driver # noqa: PLC0415 — live-only dependency+ except ImportError as exc: # pragma: no cover — only on a misconfigured runner+ pytest.fail(+ f"ISOLATION_CLICKHOUSE_HOST is set, so this is a live run, but clickhouse_driver is missing ({exc}). "+ "Install it in the job rather than letting the suite skip."+ )client = driver.Client(host=os.environ["ISOLATION_CLICKHOUSE_HOST"],port=int(os.environ.get("ISOLATION_CLICKHOUSE_PORT", "9000")),