chain-rdeveloper portal
build

Platform Statistics

Not to be confused with dashboard.md, which documents the CI/CD coverage portal. This is about the figures the product's own dashboards draw.

svc-ai's usage and trace statistics answer "what has this account spent?" — one number for everything. This is what answers "what has this agent spent?", and the same question of a model, a skill, a worker, a project or an organisation, over a chosen window, for any figure the governance usage ledger records.

Four registries and a query:

ModuleAnswers
app/services/stats/metrics.pywhat figure to report
app/services/stats/dimensions.pywhat to slice it by
app/services/stats/periods.pyover what window
app/services/stats/breakdown.pythe query that puts the four together

Adding a capability is adding one class to one registry — the same contract the rule vocabulary and the widget registry work to. GET /app/stats/catalogue serves all four, so a metric added as a class appears in the widget editor's pickers without a frontend release.

A knowledge source's and repository's own figures — what they hold, how they are kept, how often answers cite them — are not breakdowns over the ledger: they read the documents, crawls and citations record directly (the knowledge guide).

Four sources

svc-core keeps three audit tables, and a breakdown is the same shape over all of them — filter to an owner and a window, group by something, aggregate — so each source declares only the two columns that differ (who owns the row, and when it happened).

SourceOne row isTable
governanceone rule evaluated against one invocationgovernance_events
redactionsone kind of value one rule removedthe expansion below
reviewsone invocation a rule asked a person to look atreview_flags

A request never names a source. The metric determines it — asking for "blocks" is asking about the governance log — so there is no way to store a tile whose metric and table disagree, because there is nowhere to state the table separately.

A pairing across sources is refused, not ignored. "Blocks by redaction kind" asks a governance-event question of a column that exists only in the redaction expansion; dropping the axis would answer with an unlabelled total, which still reads as an answer to the question that was asked. The check runs at widget save time as well as at request time, because the generative flow will propose exactly this pairing.

Why svc-core and not svc-ai

svc-ai owns the authoritative per-invocation record, and it is the wrong place for this. llm_invocations carries a user, a purpose and the model of every call it made (llm_invocation_calls) — and no agent, no skill, no project, no organisation, because those are svc-core's resources and svc-ai has never needed to know them. A breakdown by agent cannot be built from that table without teaching svc-ai the whole ownership hierarchy.

governance_usage already knows. It was built for quotas, so it stamps the resource that ran, the project and organisation owning it, the model, the tokens, the estimated cost and the latency, on every governed invocation. The figures were already there; what was missing was a reader that grouped by anything. So the breakdown is computed in svc-core, and svc-ai's undimensioned stats stay exactly what they are.

One thing they are not is deployment-wide. GET /app/stats/usage and /app/stats/traces forward the session user's id, and svc-ai filters every aggregate — the flat counts and the per-conversation averages alike — on the user_id stamped on each trace row. Without the id svc-ai answers for the whole deployment, which is what the Overview page's Token Usage and Trace Counts cards showed until svc-core started sending it.

The ledger gained failures

A breakdown wants an error rate, and until now the ledger only held invocations that came back. governance_usage.outcome (ok / error, migration 56) is what makes one countable.

What a quota counts has not moved. UsageWindow filters every read to ok rows, on the shared base query rather than in each reader, so a reader added later cannot forget it. Letting a provider outage consume somebody's hourly allowance would be refusing a request on a number that was never real — precisely the failure app/services/usage.py is written to avoid.

A blocked invocation deliberately gets no ledger row. The rules that refused it are already recorded, one governance_events row each, with the rule, the reason and the invocation id. Recording it here as well would have one turn owned by two surfaces that both claim to be authoritative — the same double-counting the "enforcement inside a graph run is traced but not logged" gap avoids.

Existing rows are backfilled to ok by the column's server default. That is a real statement about the data rather than a convenient one: the ledger had no other kind of row to hold.

Metrics

Usage

KeyUnitNotes
input_tokens / output_tokens / total_tokenstokens
estimated_cost_usdusdA lower bound — an unpriced model contributes nothing.
avg_latency_msmsMean over the invocations that were timed.
errorscountAttempted and failed.
error_ratepercentFailures over attempts, computed per bucket.

Every metric is a conditional aggregate over the same rows rather than a filter on the query. That is what keeps a breakdown honest about its denominators: if each metric filtered instead, a bucket with only failed invocations would be absent from a tokens chart and present in an errors one, and the two would disagree about which agents exist.

Token and cost metrics sum only successful rows — a call that errored produced no answer, so whatever partial token count came back with the failure is not work the user received. avg_latency_ms excludes failures too: a timeout's duration is not "how fast is this model".

error_rate sums float literals, not integers. Postgres divides integers as integers, and a rate reporting 0% for one failure in three would be worse than no rate at all. block_rate is written the same way for the same reason.

Governance

KeyUnitNotes
blockedcountThe rule refused the invocation.
appliedcountIt matched and changed something.
no_changecountIt matched, its actions ran, nothing needed doing.
not_matchedcountIts conditions did not hold.
block_ratepercentBlocks over evaluations, per bucket.

The four outcomes are separate metrics rather than one metric plus a filter somebody has to remember to apply. no_change is the reason the activity log exists: a redaction rule over a clean prompt is working, and before that table it was indistinguishable from a rule that had never been evaluated. A board that could only show blocks would have reintroduced exactly that blind spot.

Redactions

KeyUnitNotes
redaction_eventscountHow many prompts and answers had something removed.

Two figures because they are different questions: three emails removed from one response is three values across one response. redaction_events counts DISTINCT event ids, because the expansion repeats an event once per kind.

Reviews

KeyUnitNotes
pending_flagscountNobody has looked yet.
reviewed_flagscountLooked at and judged acceptable.
dismissed_flagscountLooked at and judged unwarranted.

All four are zero_is_meaningful, so an empty queue renders as 0. "Nothing is awaiting review" is a real answer; an em dash would read as "we could not tell", which is the opposite reassurance.

The redaction expansion

governance_events.detail is keyed by the action that ran, and a redaction holds {"redact_pii": {"redacted": {"email": 2, "card": 1}}} — kinds and counts, never the values, because the log of a redaction must not be a copy of what was redacted. The redactions source expands that map with a lateral join, so one event that removed two emails and a card number is two rows.

FROM governance_events
JOIN LATERAL json_each_text(
       COALESCE(detail -> 'redact_pii' -> 'redacted',
                detail -> 'filter_pii' -> 'redacted', '{}')::json
     ) AS kinds ON true

Until October 2026 it read detail -> 'redacted', a level no event has, so every redaction breakdown counted nothing. Both keys are read because an Input rule's redaction was filter_pii before migration 105, and an event keeps the key it was written with (stats/sources.REDACTION_ACTIONS).

COALESCE(..., '{}') carries the weight: most events have no redacted key at all — a rule that blocked, or matched and found nothing — and an empty object expands to no rows, which is the honest answer for an event that redacted nothing.

A source rather than a dimension on governance. The expansion changes what a row is, so bolting it onto an axis would silently change what every other metric counted: "blocks by redaction kind" would report each block once per kind it never had. Making it a source means only the metrics that make sense over the expansion are offered against it.

Because the expansion carries every one of the event's columns, the governance dimensions slice it too — so "what has this rule redacted, by kind?" and "how often has it blocked?" are the same two axes over two sources rather than four definitions.

Null is not zero

estimated_cost_usd over an unpriced model, and avg_latency_ms over untimed rows, are unmeasured rather than zero — the same distinction usage.estimate_cost draws, one surface further out. Metrics declare which they are with zero_is_meaningful, and the tile renders an em dash rather than $0.00, which would state something false.

A bucket that aggregates to nothing measurable is dropped rather than charted as zero, for the same reason: "this agent spent nothing" and "this agent's models publish no price" are different statements, and a bar cannot tell them apart.

Dimensions

KeyBucketed on
project, organisationowner_project_id / owner_organisation_id
execution_type, outcomethe column itself

Governance and redactions:

KeyBucketed on
layeraccess / input / tools / output (was rule_type until migration 105, which rewrote the tiles that used it)
governance_outcomeblocked / applied / no change / stood aside
phaseprompt or response
enforced_insvc-core or svc-ai
governed_agent, governed_execution_typethe event's own columns
redaction_kindthe expansion's key — redactions only

Reviews:

KeyBucketed on

The same resource is a different dimension on each source — an agent is agent on usage rows, governed_agent on governance rows, flagged_agent on review rows — because each table records it in its own column. The editor maps all three onto the one list of agents.

A rule axis is named off the events, not the rules table. The log denormalises rule_name precisely so a deleted rule stays readable, and "a rule that was deleted after it blocked somebody is exactly the case the log is kept for". Resolving through rules would put a UUID on that bar — the one that matters most.

A dimension can only exist if the ledger records it. Adding one means the ledger learning a column first, not this module gaining a branch.

The resource dimensions are three lines each, because the rule scope registry already answers both questions they need: how to narrow the ledger to that kind of resource (Scope.usage_filter) and which table names it (Scope.target_model). A second description of "what an agent is" would be a thing to keep in sync for no gain.

Pinning scope_type matters. scope_id holds an agent id on one row and a model id on the next, so grouping or filtering on the id alone would mix two populations into one chart and name every bucket from the wrong table.

skill and worker return nothing today. A skill run through an agent is recorded against the agent, because that is the resource whose quota it consumes. They are registered anyway: they are real scopes with real rules written against them, and a dimension that returns nothing is an honest answer to "what has this skill spent?", where a missing dimension would look like the question cannot be asked.

Labels

Buckets are keyed by id and named on the way out, never denormalised onto the ledger row. The ledger is audit evidence that has to outlive the agent it describes — but while the agent exists, its current name is the one a reader recognises. That is the same trade the governance activity log makes.

A bucket whose resource has been deleted keeps its figure and its id, marked missing. Deleting an agent does not unspend its budget, and the id is the only handle a reader has for chasing the spend through the history trail, which outlives the resource by design.

Models are the exception: they are svc-ai's records, so the names come from list_models(). The activity log deliberately does not make that call — the execution type already says what ran — but a breakdown by model without names is a chart of UUIDs. The call is made once for the page, and a svc-ai outage costs the labels rather than the figures.

Source — whose spend it is

source is a categorical dimension over governance_usage.source_type: the resource an invocation's spend is attributed to, not the one that ran. A dashboard tile runs as the agent it borrows — its row is scoped to that agent, so the agent's quota counts it — and sourced to the dashboard, so the board's cost counts it. "Spend by source" is the first question a cost review asks. Rows written before migration 69 that could not be attributed fold into Unattributed. The vocabulary and the paths that write it are services/llm_paths.py; see cost-monitoring.md.

For one resource's cost — the card on its page — GET /app/stats/cost reads the same column by source_type + source_id, with a daily series.

Periods

last_24_hours, last_7_days, last_30_days, this_month, last_month, all_time.

last_month is the only one that ends before now: the whole previous calendar month (UTC), its end exclusive (Period.until), so Governance → Spend can set this month beside it. The breakdown, /app/stats/cost and its daily series all stop at that boundary.

A registry rather than a stored pair of timestamps, because a widget stores its period and has to mean the same thing next month. this_month written out as an explicit since would quietly become "since the first of whichever month the tile was created in" — the classic dashboard bug where a board built in January is still reporting January in March.

An unrecognised period falls back to a window, not to everything: a tile whose period was mistyped should show a figure the user can sanity-check against the rest of the board, not the account's lifetime total under a label claiming otherwise.

The API

EndpointPurpose
GET /app/stats/breakdownOne metric, over one window, optionally sliced and filtered.
GET /app/stats/breakdown
      ?metric=estimated_cost_usd
      &dimension=agent
      &period=this_month
      &filter=project:<uuid>
      &limit=10

Scoped to the calling user, like the activity log and the reviewer queue: the ledger row records whose invocation it was, which is the only scope it can answer on its own. A project-wide figure is a project: filter, not a different caller.

Omitting dimension returns the figure alone — what a single-number tile shows. It is the same query without a GROUP BY, which is why a tile and the chart beside it can never disagree about what "this month" means.

Terms that do not resolve are refused

A malformed filter, an unknown dimension, an unknown metric: 422, never ignored. A filter that silently fell off would widen a tile from one project to the whole account while its caption still named the project — a dashboard stating something false, which is the failure the provenance marker on every widget exists to prevent. The same check runs at widget save time, so a tile cannot be stored in a shape that would be dropped on every refresh.

The tail is folded, not dropped

Buckets are ranked and truncated to limit, with the remainder in one __other__ bucket. A chart that silently omitted the tail would make its bars look like the whole of the spend, and the first question anyone asks of a cost breakdown is whether it adds up.

total is computed over the whole filtered set, never by summing the page — for the same reason, and because an average or a rate cannot be summed at all. Metrics declare which they are (additive); a non-additive metric reports its figure over all rows and gets no other bucket, because an "other" bucket averaging the tail's latencies would be a number no invocation ever took.

Rows whose dimension value is absent — an invocation belonging to no project — are their own __unassigned__ bucket, which is a different statement from being in a tail that was truncated away.

The tile

The stat tile's spend (estimated_cost_usd) reads the ledger too, as the viewer's own (GET /app/stats/cost?mine=true, captioned "Your spend"), so it equals Overview's and the Stats page's figure. Its token and call metrics still read svc-ai's usage and trace summaries. See Cost monitoring.

breakdown is one widget type with three shapes, chosen by display:

displayDraws
listLabel and figure per row.
valueThe total alone.

Deliberately not three widget types. They are one question asked three ways, and splitting them would mean a user who wanted the same figure as a bar instead of a row had to rebuild the tile.

Its config is validated against the same registries the query reads, rather than a list of literals restated in the renderer — a metric the widget would accept but the breakdown could not compute is a tile that saves cleanly and then shows an error, which is the worst of both.

The filter picker is served by GET /app/rules/targets, the endpoint the rule builder already uses to answer "which of these may this user pin to?". Six of the eight dimensions are rule scopes, so a second listing of the user's agents and projects would be a thing to keep in sync for no gain.

The Governance board

The built-in Governance board (below) gives the Phase 1 surfaces a place on a dashboard: blocks and block rate, values redacted, the review queue depth, the full outcome split, the busiest rules, and redactions by kind — plus links into Governance → Rules / Activity / Reviews / Evaluation. It was a template until the built-in boards replaced it.

It leads with the outcome split rather than with blocks alone, deliberately. A board that showed only blocks would reintroduce the blind spot the activity log was built to remove: a rule that matched and found nothing to do is working, and it should be visible doing so.

Built-in boards

Six boards ship with the platform (app/services/system_resources/dashboards.py, migration 80: is_system on dashboards): Daily briefing, Agent fleet, Governance, Knowledge, Usage & spend and Model & agent assurance. They are provisioned at startup with fixed ids (boards …000000000501 onwards, tiles …0000000501NN), and each release that changes one writes a version with no actor.

One row for everybody. Unlike a template, which seeds a board of the user's own, a built-in board is read by every user. That works because of where each tile's data comes from:

  • The viewer's own. stat, chart, breakdown, resource_list and the network views fetch their data in the browser with the viewer's session, so the same row shows each user their own figures. Every resource id in a built-in tile is empty, which these tiles read as "all of mine" or "my newest".

  • Everybody's. The platform benchmark is the same for every user (CHAIN-R runs CHAINR Bot and each maker's strongest model on the gold datasets), so the assurance tile's benchmark views show everyone one picture, read live from GET /app/evaluations/benchmark.

  • Nobody's. A dynamic tile caches one payload on its row for everyone. The only one on a built-in board is the Daily briefing's fun fact: an automation on {"type": "model", "default": true}, the deployment's default model resolved at run time (targets._default_model_record). Not an agent: an agent's run writes memory, and with no user that memory would be nobody's. It runs ungoverned (no owner, no rules) and unledgered, and its cost is on the refresh's background event (detail.usage), which every tile refresh now records.

  • Never one user's. A renderer that keeps a user's content on its row declares stores_user_content (pinned_message, message_list) and may not appear on a built-in board.

tests/test_built_in_dashboards.py holds every built-in tile to those rules and to its renderer's validate_config (returned unchanged), checks the layouts do not overlap, and checks each shortcut's path still exists in fe-core's APP_ROUTES.

API. GET /app/dashboards?include_system=true appends them after the caller's boards (the Dashboards page only; the Overview counts the plain listing). GET /{id} and the history routes use verify_resource_read; every write, including refresh and saving a message, refuses a built-in board (403). Any viewer's load may queue a stale tile's refresh; mark_refreshing stops two loads queueing it twice.

Copying. fe-core's Copy to my dashboards posts the board's tiles to POST /app/dashboards (copyOfBoard), so each is validated as if the user had added it. The copy is an ordinary board: its fun fact runs as the user, governed and ledgered.

Provisioning reconciles each board's tiles by fixed id. A tile that only moved or was retitled keeps its cache; one whose type or config changed has its cache cleared, because it answered a different question; one a release drops is deleted.

The Model & agent assurance board

The evaluation evidence the platform holds, on one board (migration 90 adds the assurance widget type; AssuranceWidget in app/services/dashboards/widgets.py, drawn by fe-core's components/dashboard/widgets/AssuranceWidgets.tsx). The tile has one setting, view, and five views. Each reads the same query as the page it summarises, so the board and that page cannot disagree:

ViewShowsReads
risk_returnThe Average against risk chart from CHAINR Bot's page, and where the bot stands.benchmark targets
scoresA heatmap of every target on every gold dataset: the newest score on the dataset's current version, green when it reaches the pass mark, amber within ten points of it, red further off or regressed, with ✓ or ✗ in each cell so it never relies on colour alone.benchmark datasets
bot_trendCHAINR Bot's runs on each dataset as a sparkline with the pass mark dashed. A dotted break marks a new dataset version, and the change shown is only against a run on the same version, since runs either side asked different questions.benchmark bot_history
fleetThe viewer's own agents in this workspace: how many have passing evidence for the version in force, a bar by status (the ASSURANCE_STATUS scale), and the ones that need attention, linked.GET /app/evaluations/assurance

Provenance. The four benchmark views are marked CHAIN-R benchmark where a platform tile otherwise says Your data (VIEWS[view].source, read by DashboardCanvas's sourceNameOf), because their figures are CHAIN-R's measurements, the same for everyone. fleet keeps Your data. The built-in board's note explains both.

On a narrow tile the leaderboard's average and risk wrap under the bar, and the heatmap scrolls sideways with the model column pinned. Checked at 390 and 1440 px, light and dark.

The views are a registry on both sides. The generator's prompt renders them from AssuranceWidget.VIEWS, and a svc-core test holds fe-core's VIEWS equal to it, so a view added on one side and not the other fails. tests/test_built_in_dashboards.py checks the board shows every view. The tile names no resource and keeps nothing, so it may go on any board, built-in or a user's own.

New dashboard widget types are frozen for the MVP (docs/business/mvp-roadmap.md) because feed tiles dilute the governance story in a demo. This one is the governance story (October 2026, at the user's request), and the freeze stands for everything else.

Generated tiles and boards

Two tiles are a model's work (data_kind generated): automation (a prompt on a schedule, its answer as markdown) and comparison (subjects placed on axes, a schema-filled reply). Each runs through the evaluation execution targets (widgets._target_for), governed, routed and ledgered as the board's owner, with no memory and nobody to ask (may_ask off), for up to TILE_TIMEOUT_S.

How a tile is asked (21 October 2026). An agent answers in its own instructions: the tile's — where it is shown, that nobody can be asked, the answer's shape, the owner's extra instructions, and for an automation the gist of its last answer so a refresh says what changed — ride after the task (widgets._steered). A system prompt sent with an agent replaces the agent's (agent_spec.Overrides), and a tile's "You are a dashboard automation" had been doing exactly that. A model, with no instructions of its own, takes them as its system prompt, and answers as chat does (temperature and output budget), not as an evaluation cell. system_prompt in an automation's config is extra instructions, added to the tile's. An automation's pdf decides whether every refresh can be downloaded (see documents.md). Each payload names what answered (runs_on) and when (generated_at).

How a board is designed (services/dashboards/generator.py, POST /app/dashboards/generate). One structured call on the deployment's default model fills a schema built for the request (proposal_schema). It is shown:

  • only the types it may propose here (offered_renderers): never one that keeps a user's content (a pinned answer it wrote would read as the user's), never one the deployment cannot draw (a market tile with no vendor), and a model-backed one only when something can run it;

  • each type's fields, bounds and defaults, without the fields the server fills (a tile's target, resource ids) — never "OMIT THIS";

  • the workspace's agents a tile can run on (its own and the built-in ones, exactly what a tile's target admits), each with its purpose, skillsets and knowledge, by handle (workspace_agents);

  • the platform's own licence-checked publisher feeds, and the deployment's feed allowlist when it has one (feeds_prompt).

What comes back is re-validated tile by tile: a handle mapped to its agent (none, or an unknown one, falls back to the workspace's oldest agent, else the model that designed the board, else a built-in agent), ids the model wrote stripped (a breakdown's id filters included), each type's minimum cadence applied (a market tile's 6 hours protects the vendor's quota). A tile its validator refuses is sent back once with what was wrong, and dropped if it fails again. The review step shows what each model-backed tile runs on, and creating the board passes its generation_id, so the board is stamped as generated and its page shows the invocation behind it. A call that failed is a 502 (a refusal's own message, or "could not reach the model service"), a budget's stop a 403, and a board with nothing usable a 422.

What this does not do yet

  • No time series. A breakdown slices one window by a dimension; it does not yet slice by time, so "spend per day this month" is still the chart widget's undimensioned per-user view. Adding a bucket_by period to the same query is the way in.

  • Redaction kinds are whatever the redactors emit. Nothing here enumerates them, so a redactor added later appears on the chart by itself — and equally, a kind renamed in the redactor splits one bar into two with no warning.

  • A tile does not deep-link into the activity log. Clicking a rule's bar ought to open Governance → Rules → Activity filtered to that rule; the log's page already filters by rule_id, so this is a link, not a feature.

  • Nothing alerts. The stack now has a scheduler (scheduler.md), which was the missing loop — but a threshold needs somewhere to send its result, and there is no notification channel yet. That is the next decision.

  • Ownership columns are not backfilled. owner_project_id and owner_organisation_id arrived with migration 51, so a project or organisation breakdown counts from there forward. The ledger does not record what a resource's ownership was at the time, and inventing it from today's graph would put figures in an audit ledger that were never observed.

See also: governance.md (the rules, the ledger, the activity log and the reviewer queue these count), frontend-components.md (the widget kits).