chain-rdeveloper portal
build

Cost Monitoring

Every call the platform makes to a language model — chat, embedding, judge, generation — is measured, priced, put on the usage ledger, and attributed to the resource that caused it. This guide is the map: how a call is measured, where each kind of call is recorded, how to read the figures, and what to do when you add a new way of calling a model.

The contract is enforced, not just described. modules/svc-core/app/services/llm_paths.py declares every path to a model, and modules/svc-core/tests/test_llm_paths.py fails if code and declaration drift — including if this page stops documenting a path.

Measuring: svc-ai meters every call

svc-ai is the only service with model egress, so it is where calls are counted (modules/svc-ai/app/services/metering.py).

  • One meter per HTTP request. LLMUsageMiddleware opens it; everything the request does records into it.

  • Every call is recorded where it happens. build_langchain_llm attaches a MeterCallback to every chat model it builds, bound to that model's provider and name — so tool loops, structured-output passes, retries, the pipeline's own system nodes (gate, planner, synthesis, evaluator) and per-node model pins are all counted without any node cooperating. LiteLLM direct calls (run_model, stream_model) and embeddings (services/embeddings.py, one metered call per chunk, priced on the embedding model's catalogue row) record themselves.

  • Every call is priced on every class of token its provider billed. Neither OpenAI nor Anthropic returns a cost per request — they return a usage breakdown, and each class in it has its own published, per-model rate. services/provider_usage.py reads the whole breakdown (TokenUsage) and prices it on the model's PriceCard:

    ClassOpenAIAnthropic
    Cache readscached_tokens — 0.1× input on GPT-5.6/GPT-6 (0.05× on GPT-6.1 Sol), 0.5× on GPT-4ocache_read_input_tokens — 0.1× (0.05× Opus 5.5, 0.025× Fable 5.1)
    Cache writescache_write_tokens — 1.25× on GPT-5.6+, none earliercache_creation_input_tokens — 1.25× (5-minute), 2× (1-hour)
    Outputcompletion total, reasoning includedoutput_tokens, thinking included
    Long contextpast 272K prompt tokens the whole request is repriced: input classes 2×, output 1.5×none on Claude 4.6+ (full window at standard rates)

    The card is the catalogue's (llm_models: input, output, cache read, cache write, 1-hour write, long-context threshold and multipliers — seeded from the providers' pricing pages, and cross-checked against LiteLLM's map by tests/services/test_provider_usage.py), then LiteLLM's for a model registered without one. A call is unpriced — counted in unpriced_calls, left out of the sum, never priced as zero — when the provider reported no usage, billed it at a non-standard tier (flex, priority, fast mode, server-tool charges, multi-attempt iterations), or used a class no card has a rate for. Each llm_invocation_calls row keeps the breakdown and pricing: the rates applied and their source, whether the long-context tier did, or unpriced_reason.

  • Usage the libraries drop is put back. langchain-openai maps cached_tokens but not cache_write_tokens, so GPT-5.6+ cache writes would fall into uncached input and bill at 1× rather than 1.25×; provider_usage.install_openai_cache_write_mapping() carries them through (a test fails when the package maps the field itself). Streamed OpenAI calls only report usage when asked, so build_langchain_llm sets stream_usage=True — langchain-openai does so by default only on the stock endpoint.

  • The answering agent's prompt is built to be cached (modules/svc-ai/app/services/prompt_cache.py). Its system message is the same on every call of that agent, and each request's own context (date, evidence, memory, plan) opens the task message instead. Anthropic receives the system message marked cache_control: ephemeral, which caches the tool definitions before it too. OpenAI receives a prompt_cache_key naming the prefix. A hit shows up here as cache-read tokens at the cache-read rate. A first call, or one after five idle minutes, writes the cache at the write rate. See agent-graph-review.md#phase-3-and-the-leftovers--shipped-october-2026.

  • An engine's own estimate never reaches the ledger. Under a meter, merge_into_usage takes cost from the meter alone; an engine's two-rate guess is dropped even when the meter saw nothing.

  • Every call's full prompt is billed. Graph runs used to report only the growth in input tokens between calls; providers bill each call's whole prompt, and the meter counts that. The stream's per-node trace figures now sum each call's full input too (_stream_graph, 18 October 2026): they had shown the quality check as "0 in". That was display only; the meter and the ledger were always right.

  • Every call keeps where it ran, how long it took and whether it failed. The graph node comes from LangGraph's run metadata (the outermost node, so a nested graph is credited to the node it was built as), the latency from the call's own start and end, and a call the provider refused is recorded against the model it went to — so a retry or a runtime fallback shows the attempt that failed as well as the one that answered. Failed calls are traced but left out of the billed summary.

Reconciling against the provider's bill. The per-call figure is exact against published rates; what it cannot see is anything negotiated (volume discounts, Priority Tier commitments, credits). OpenAI's Costs API and Anthropic's Usage & Cost Admin API report billed cost per day, model and key (admin keys required) — the place to reconcile the ledger's totals, not a source for per-request cost.

It leaves svc-ai three ways:

ResponseWhere the usage is
A batch executionalso folded into ExecuteResponse.usage
A streamthe terminal done or hitl_interrupt frame's usage — a paused run has spent what it spent

Tracing: which model made each call

svc-ai's own trace is llm_invocations — one row per execution, resumed segment or platform flow, which the Activity feed and the Stats page read through GET /app/stats/invocations. Each row claims the calls the meter saw while it was being served (UsageMeter.claim, so two rows in one request never share a call) and stores every one as an llm_invocation_calls row: provider, exact model, catalogue model_id when the catalogue lists it, graph node, tokens, latency, outcome and cost. The row's own tokens and cost are the sum of its calls.

  • A row names its model as text. provider / model_name are the model the request asked for (an agent's or a prompt's model, a generation flow's), or the one model every chat call used (for work with no chat call, like indexing, the one model every call used). They are null only when the request named none and its calls used several — the call rows then say which. Nothing depends on the catalogue: a model it never listed is still named.

  • Models are archived, never deleted (svc-ai migration 20). DELETE /models/{id} sets llm_models.archived_at; the row stays, so every trace, call and conversation keeps its model_id and its catalogue name. Archived models are left out of every catalogue read (list, lookup, get) unless the read passes include_archived, so nothing can select or run one. POST /models/{id}/restore puts one back under the same id, and registering an archived model's name again is refused with a pointer to it. A provider with models is not deleted (disable it), and no migration after 17 may delete catalogue rows (tests/routers/test_invocation_traces.py). fe-core's Stats and Activity name maps ask for archived models; pickers never do.

  • Every endpoint that reaches a model traces itself. The execute, stream and resume paths, every generation flow, and /knowledge/embed (knowledge_indexing), /knowledge/retrieve (knowledge_retrieval) and /simulate/run (simulation) through conversation.trace_invocation. svc-core names whose work it is in the request — for the paths deep in shared helpers (indexing, crawls, search) with ai_client.attributed(user_id, knowledge_id=…) around the block, the way it opens usage_capture(). A built-in source's crawl is attributed to nobody: its cost is the platform's.

  • Nothing a request metered goes untraced. Once a request is over, LLMUsageMiddleware hands any call no row claimed to conversation.trace_unclaimed, which records it as purpose untraced under the endpoint that made it (request_config.endpoint) and logs a warning — a new path that forgets to trace shows up in Activity as an "Untraced call" rather than vanishing.

  • By-model and by-provider figures count calls. fe-core reads them through util/invocationModels.ts: a skill whose planner ran on one model and whose drafting node pinned another is credited to both, each for its own tokens, cost and latency. A trace recorded before call rows existed (svc-ai migration 19) stands for its own model, or reads "Model not recorded".

  • Chat tokens by model or provider come from the chats' calls (chatModelUnits). svc-core stores a conversation's tokens as one total naming no provider, and an agent chat names no model at all (its turns run triage, the agent and the evaluator, often on different models), so grouping conversations filed every agent chat under "Unassigned". The Stats explorer and Token Usage tab take the calls each turn's trace recorded against the conversation, so the split adds up to the chats' own total. A refused call spent nothing and draws no series. That depends on every turn naming its conversation to svc-ai, the first one included: the WebSocket chat route sent none for a new chat until October 2026 and created the conversation afterwards, so first turns traced before then are not linked to their chat and are missing from these splits (svc-core tests/test_agent_chat_trace_link.py). Metering itself is exact on Bedrock for every vendor it serves (svc-ai tests/services/test_bedrock_metering.py).

  • A model reached without the meter is logged. A row reporting tokens with no metered call means a chat model was built outside build_langchain_llm; tests/services/test_metering.py fails on any chat-model constructor elsewhere in svc-ai.

  • Every row names the workspace it was made in (svc-ai migration 22, app/common/workspace.py). svc-core sends X-Workspace on every call — the request's workspace, or the one ai_client.in_workspace(...) names for work with no request (a skill run, an evaluation and each of its cells, a tile refresh, a crawl, a chat socket's turn) — and svc-ai stamps it on llm_invocations and tool_invocations (personal as user:<id>). /stats/*?workspace= counts only those rows, so a workspace's Overview cards, usage tiles and Activity feed are the work done there. Rows from before the column count as their user's Personal. A new background path that reaches svc-ai wraps its calls in in_workspace, or its rows land in nobody's workspace but Personal.

  • Every row names the turn it was part of (svc-ai migration 26, app/common/invocation.py). svc-core sends X-Invocation-Id around each governed turn's calls — an answer, a skill run, an evaluation or tile cell (ai_client.in_invocation / use_invocation) — and svc-ai stamps it as core_invocation_id on llm_invocations and tool_invocations. The turn's ledger row, messages, rules and flags carry the same id (svc-core migration 91), so one answer's spend reads back to the exact model and tool calls behind it. Generation, retrieval and indexing name no turn.

  • Every call says what it was for, and on which pass (svc-ai migration 27). The graph node alone could not say where a turn's tokens went: the query planner, the reranker and an agentic search all made their calls as __internal_retrieval__, and an answer and its revisions as the same skill node. (Since 26 October 2026 the planner calls as __knowledge_plan__, each lane's judge as its own node — __domain_retrieval__ and so on — and an agentic search as __retrieval_join__.) Each call now carries a step — a structured call's purpose (__gate__, __evaluator__, retrieval.query_planner, retrieval.reranker, <worker>.output (a typed worker without tools, since 20 October 2026), <worker>.output_repair, reply.format (an answer rewritten into the JSON shape its request asked for) — a structured step a native sibling made is metered under the sibling's model, with the step's own label (Agent graph), memory.extract, a generation flow's), or a metering.Step: respond (a worker answering — every round of its tool loop, and a direct model prompt), continuation (a reply cut off at the token cap, asked to carry on), memory_summary, memory_recall (embedding a request to find the memories it bears on), memory_index (embedding what memory keeps), route (an LLM router edge's structured choice). What memory costs a turn is in Memory. Code sets it with metering.step(...); the innermost label wins, and the meter reads it when the call starts, where the calling code set it. pass_index is the pass of the graph run the call was made on (metering.graph_pass, set by graph._span_node from eval_retry_count): 0 the first, 1 the first revision after the quality check. POST /stats/steps sums a set of turns' calls by node, step, pass and model — svc-core picks the turns (at most 2,000, ai_client.get_step_usage), so the answer is exactly those. Calls before migration 27 have neither label.

svc-core reads it through ai_client.usage_capture(): every ai_client function that reaches a model feeds the active capture (_capture for headers, _capture_summary for stream frames). A caller opens a capture around its svc-ai calls and hands it to the ledger.

Recording: the usage ledger

governance_usage (svc-core) has one row per invocation that reached a model, and it is what rate limits, cost caps and every spend figure read. With measured usage, record_usage(..., measured=capture) records svc-ai's figures — tokens summed over every call, cost priced per call — instead of estimating from the one model a request named. The estimate from model_info is the fallback when nothing was metered.

Two columns answer different questions:

ColumnQuestionExample: a dashboard tile running agent A
source_type / source_idWhose spend is it?dashboard / the board — so the board's cost card counts it

llm_calls and unpriced_calls say what svc-ai metered; unpriced_calls > 0 makes the row's cost a lower bound. unpriced_estimate_usd (migration 95) is what a limit takes those unpriced calls to have cost — their tokens at the catalogue's dearest rates, the rule the spending ceiling counts them by, reported by svc-ai on every usage summary — so a cost cap counts estimated_cost_usd + unpriced_estimate_usd and an unpriced model cannot spend round it. Spend figures keep showing the measured cost, marked "at least".

Every row also carries the workspace it happened in (app/services/workspace.py, migration 85): owner_project_id, owner_organisation_id — a project's row names its organisation too — and workspace_user_id for a person's personal workspace and personal projects. A caller that knows the workspace passes record_usage(..., workspace=ws) (agent chat, model chat, skill runs); otherwise usage.workspace_stamp completes it from the owner columns given. That is what lets an organisation's cost cap be one budget for the organisation and its projects, and a workspace's dashboard show the spend done in it by anyone (GET /stats/breakdown?workspace=). A direct model chat is governed, ledgered and listed in the workspace it is had in (?workspace=); until October 2026 it landed in the person's Personal workspace whatever page they were on.

A turn that does not finish is still paid for

A turn that fails, is refused or is stopped is ledgered as a failed attempt (outcome error) with what its calls cost before it ended. Three ways that figure arrives:

  • A refusal or a failure in svc-ai ends the stream with an error frame, which carries the meter's usage like done does (metering.TERMINAL_FRAMES). svc-core folds it into the capture before raising (ai_client._raise_stream_error).

  • Stop, or a failure on svc-core's side of the stream (the connection drops), leaves the leg that was running with no terminal frame at all. svc-ai still traces that leg as its stream unwinds, so svc-core reads svc-ai's trace of the turn (GET /stats/turns/{id}) and keeps whichever record saw more calls (ai_client.reconcile_turn_usage). It waits briefly (TURN_TRACE_WAITS, about 2.5 s at most) until the trace shows every leg the turn started — the stream and each resume after a pause. A trace that cannot be read leaves the captured figure.

  • A block svc-ai enforced after the run had already made calls is ledgered with those calls; a block that cost nothing writes no row, as before.

  • A batch call past the caller's wait (30 October 2026). An evaluation cell, a tile or a swarm's piece waits a set time for svc-ai's answer. Past it, svc-core used to hang up while svc-ai went on running the turn and spending, with nothing on the ledger. Now every batch request says how long svc-core waits, less a margin (time_limit_s, ai_client.time_limit: a tenth, at most 15 s). svc-ai cancels a run past it and answers 504 with the meter's usage (routers.agent.execute_and_persist), so the failed call is ledgered with what it spent. svc-core reads the 504, or its own read timeout from an svc-ai that could not stop in time, as AIServiceTimeout. A model call already in flight on a worker thread when the run is cancelled finishes unclaimed; the spending ceiling still counts it.

Until October 2026 every one of these turns was ledgered at $0 — the turns people stop are usually the expensive ones.

Sources

The resource a row's spend is attributed to (UsageEnum.Source):

SourceAttributed to
modelthe model prompted directly
skillthe skill run standalone
dashboardthe board a tile belongs to
experimentthe evaluation a cell, judge call or optimiser call belongs to (none for an unsaved Quick try)
generationthe GenerationRun of a generative setup flow
knowledgethe knowledge base searched or indexed
knowledge_repositorythe repository searched
simulationthe simulation run
swarmthe swarm a run's task belongs to, whichever of its agents did the task

Execution types

How the invocation was started (execution_type: UsageEnum.ExecutionType, labelled by llm_paths.EXECUTION_TYPE_LABELS). The rule builder's execution_type condition offers the same words, since svc-core governs every path under the word it ledgers it under — so a rule can single out evaluations or dashboard tiles. svc-ai's re-check of a forwarded rule inside a run reads its own request type (agent, model, skill), so a condition on the other words is enforced by svc-core alone.

Execution typeLabel
modelDirect prompt
skillSkill run
evaluationEvaluation run
dashboardDashboard tile
generationGeneration
retrievalKnowledge search
embeddingIndexing
simulationSimulation
swarmSwarm task

Every path to a model

The registry, LLM_PATHS. Each is metered, ledgered with its source, and covered by the tests.

PathWhat causes itExecution typeSourceLedgered in (app/)
model_promptA direct prompt from a model's chat pagemodelmodelrouter/app/models/router.py
skill_runA standalone skill run — one row per segment (before a pause, and each resume)skillskillservices/skill_runs/runner.py
evaluationEvaluation cells, the LLM judge grading them, the optimiser's proposals and candidate scoring, Quick try, and the platform benchmark's runs (ownerless, so not ledgered; see Limits). A run's cells and judge calls are ledgered as each finishes (runner.ledger_as_it_goes), so a cap sees a run's spend while it runsevaluationexperimentservices/evaluation/runner.py, services/evaluation/optimiser.py
dashboard_tileAn automation tile refreshing (on view, on demand, scheduled)dashboarddashboardservices/dashboards/widgets.py
generationAgent, skill, skillset, toolkit, knowledge, rule and dashboard generation (a skill generation may make a second, repair call)generationgenerationservices/generation.py (generation.metered)
knowledge_searchSearching a knowledge baseretrievalknowledgerouter/app/knowledge/router.py
repository_searchSearching a repositoryretrievalknowledge_repositoryrouter/app/repositories/router.py → router/app/knowledge/router.py
knowledge_indexingEmbedding an uploaded document (a row per document, the uploader's) or a website crawl (a row per crawl), and the knowledge_reindex rebuild after the embedding model changes (built-in knowledge is the platform's; a scheduled crawl of an organisation's or project's source is ledgered to no one, in its workspace)embeddingknowledgerouter/app/knowledge/router.py, services/knowledge/web_crawl.py
simulationA simulation runsimulationsimulationrouter/app/simulations/router.py
swarmA swarm run's tasks — the lead's plan, each piece of work, the review and the answer — each a governed agent turn held to its share of the run's budget, ledgered as each call finishes (tasks._ledger_as_it_goes); a call cut off by a restart is ledgered from svc-ai's trace when the run resumes (tasks.ledger_interrupted). A run an evaluation started is ledgered as the evaluation's — source experiment, execution type evaluation (tasks.LedgerAs) — and its cell is not ledgered againswarmswarmservices/swarms/tasks.py

Before this registry, the evaluation judge and the optimiser, all six generation flows, knowledge search, indexing and simulations reached a model with no ledger row at all — invisible to cost caps and spend figures.

A correction is the path's own call (20 October 2026). The judge, the optimiser's proposer, the dashboard generator and the comparison tile ask for a reply to a schema (targets.invoke_structured), and answer one that does not match once. That second call is governed, metered and ledgered under the same source as the first — the judge's and proposer's on their evaluation (every invocation goes to the ledger callback), the tile's on its board (_record_usage per call), the generator's inside its generation.metered run — so no new path or step label. The board designer may make one more (21 October 2026): a tile whose config failed its validator is sent back once with the validator's words, inside the same run, and only while the request has under 90 seconds behind it (generator.CORRECTION_CUTOFF_S). The run's spend limit now reaches svc-ai on all of them: an ungoverned target used to reset the limit generation.metered had set (targets._invoke_governed).

Knowledge generation is one run of several calls (22 October 2026). It plans web searches with a model, runs them, checks what they found and then designs the sources, in the background (services/knowledge/generation_job.py, Website knowledge). All of it sits inside one generation.metered: one budget question first, one ledger row for the run, and the design call's spend limit narrowed by what the plan has spent (SpendLimit.after). The plan is ai_client.plan_knowledge_discovery on /knowledge/discover/plan; the search and check endpoints reach no model (NON_LLM_ENDPOINTS). Finding sources for knowledge that exists or was proposed (the agent wizard's, an empty source's) is the same run with an assignment in place of the design (ai_client.assign_knowledge_sources, /knowledge/discover/assign, flow source_discovery), metered and narrowed the same way. Each search is recorded on svc-ai's trace as a web_search tool invocation, but not priced: Brave bills per request, the same gap an agent's web search has. Downloading a document into a file source (/knowledge/web/document) reaches no model; indexing it is the knowledge_indexing path, as an upload is.

Each path also names where its workspace's budgets are asked before the call (gated_in): a turn's Access rules (rule_engine.evaluate_input), or the budget gate for work that is not a turn (budgets.gate.check, below). tests/test_llm_paths.py fails on a path that names none, or a module that asks neither.

Reading it

  • GET /app/stats/cost — source_type, source_id, period (a periods key). Totals (cost, invocations, failures, tokens, calls, unpriced counts), splits by execution type and by source, and a daily series (up to 90 days). Omit source_id for every resource of a kind; omit both for everything. Counted in the request's workspace, by anyone in it, like a breakdown (workspace.stamped; an organisation's admins also count its projects). mine=true narrows it to the caller's own work there, and since / until replace the period with a range (reported as period custom). The response's mine says which it counted.

  • GET /app/stats/steps — where a resource's tokens go (below).

  • Each answer's cost — conversation reads serve every answer's cost_usd and unpriced_calls (and the conversation's total), the agent chat's response frame and both batch prompts' PromptResponse carry the turn's, all joined from the ledger by invocation_id (usage.turn_costs). A live answer shows the figure a reload will; no copy is kept on the message.

  • The source dimension of GET /app/stats/breakdown — "spend by source" on a dashboard breakdown tile, beside the execution_type, agent, model… dimensions (see statistics.md).

  • fe-core — a ResourceCostCard (components/cost) on the agent, skill, dashboard and evaluation pages reads /app/stats/cost for that resource; a skill run's page shows its own measured cost with a per-model breakdown.

One spend figure

Every figure of spend in fe-core reads the ledger. Overview's spend, the Stats page's headline, the stat tile's spend and Activity's total read GET /app/stats/cost?mine=true through one hook (components/cost/useSpend), so they agree with each other and with every cost card to the cent. Until October 2026 they summed svc-ai's traces: an unpriced call counted as nothing, and the Stats page summed only the newest 500 calls it had fetched. The Stats page's per-model and per-maker splits still read svc-ai's calls, because only svc-ai knows which model made each call in a turn.

Each figure says whose spend it counts (spendLabel): Your spend is the viewer's own work in the workspace; Workspace spend is everyone's. A resource's cost card counts the resource's spend whoever caused it, and is captioned Cost. Every amount is written by formatUsd / describeCost: "≥" for a floor and "Unknown" for nothing priced, never toFixed and never $0 for unknown.

In a chat, each answer's cost shows on hover beside its token count.

Where the tokens go

GET /app/stats/steps?source_type=&source_id=&period= (services/stats/step_usage.py) reads a resource's newest turns in the period (at most 1,000, as its cost card counts them in the request's workspace) and asks svc-ai for exactly those turns' calls (POST /stats/steps, svc-ai migration 27). It sums them by step: the graph node, what the node was doing (metering.Step, or a structured call's purpose), and the pass (0, then each revision after the quality check). Models are summed away: svc-ai's call rows name the route that served each call, and no user's page names the cloud. svc-ai unreachable is status: "unavailable", never an empty breakdown.

fe-core's Where the tokens go card (components/cost/TokenStepsCard) sits beside the cost card on agent and skill pages. It shows each step per answer, dearest first, with its tokens and the share of its prompt read from cache. Calls from before steps were recorded read as "Not recorded".

Evaluations show what an answer cost beside its score: the benchmark table, CHAINR Bot's benchmark panel and each Assurance row (cost_per_answer_usd, from the run's leaderboard, grading left out). An Assurance row's figure is the mean over its datasets, each weighted equally, and none unless every dataset's could be priced.

Reading a figure honestly:

  • A cost shown with "at least" has unpriced calls in it — a model neither price table knows. Add its prices to the model catalogue.

  • A failed invocation that never reached a model costs nothing and is not "unpriced". One that did — a refusal or a Stop after its first calls — carries what those calls cost.

  • cost_usd is null only when there was spend and none of it could be priced.

Output caps and what the checks read

Since 18 October 2026 (the "whats in the news" fix, Knowledge Retrieval). No new path or step label; each change moves the size of calls already on the ledger.

  • The retrieval steps are capped. In an agent's graph the query planner (retrieval.query_planner) runs with at most 4,096 output tokens and the relevance judge (retrieval.reranker) with 8,192, on the first pass and on corrective ones (graph._retrieval_step_llm). They had run at the system budget, which _ensure_system_token_budget raises towards 16,384, and gpt-oss-120b ran each to it: about 38 s and 17k output tokens, twice in one turn. Only max_tokens changes; the model, temperature and metering are the step's own. The agentic pass, synthesis, the quality check and the other system steps keep the raised budget. A reply cut off at a cap is now a failure, never salvaged, so a reasoning model that keeps thinking fails at about 4k or 8k tokens instead of succeeding slowly. Reasoning effort is not controlled (Known gap 18).

  • The raise is not faked on a wrapper. _ensure_system_token_budget leaves alone a model that does not declare max_tokens itself (_declares_max_tokens, the guard _retrieval_step_llm uses), such as a with_fallbacks wrapper. It used to log "raised" while every call kept the wrapped model's cap. Nothing builds fallbacks today.

  • Knowledge and repository search (svc-core app/services/retrieval.py, resolve_retrieval_model) give their planner and judge model max_tokens 8,192, where it was 1,024. Direct search runs both steps on one model, so it takes the judge's cap, and at 1,024 a reasoning model would be cut off while still thinking.

  • The judge's request names what was searched: each knowledge base's name and up to 300 characters of its description.

  • The agentic pass runs less, and shorter. It runs only when the pipeline's evidence falls short (no longer below three passages), for at most agentic_max_iterations model rounds (default 4, was 10) plus one call to write up.

  • The quality check reads more. Each tool result reaches it whole up to 3,000 characters, else abridged block by block to 3,000, where it saw the first 800: up to about 2,200 more characters per result. A five-result web search, about 2,700 characters, is now read whole.

  • So does every downstream call's tool ledger. <prior_tool_calls>, which the reviser and every skill node read, carries each result the same way (it was cut to 400), and the whole ledger is capped at about 12,000 characters. One five-result web search now adds about 2,700 characters where it added about 600. Before, 25 calls could reach about 15,000.

  • The evaluation judge sees each tool result whole up to 4,000 characters (scorers.JUDGE_TOOL_OUTPUT_CHARS, was 1,500 and unmarked), as much as a cell keeps (ai_client.TOOL_OUTPUT_CHARS, was 2,000). A cut is marked "[… N more characters not shown]". See Evaluation.

  • Knowledge-tool results are a little longer. search_knowledge and explore_graph name each source's knowledge base in their trailer, roughly 30–40 characters a source.

None of these figures is measured live. The platform benchmark's next round re-runs CHAINR Bot, since svc-ai's fingerprint and BOT_CODE_PATHS both moved, and its cost per answer is the first live reading.

Budgets

A budget is a cost_cap rule (see Governance): one enforcement path, with the rule machinery's versions, inheritance, Required and pinned rules, activity log and builder. GET /app/budgets (app/services/budgets) says where every one governing the request's workspace stands:

  • Which. Every active rule with a cost cap that governs work in the workspace, selected as the rule engine selects them (workspace.governing_rules): a project's own, and what it inherits from its organisation (Required, or pinned to it — an allocation). Each says why it is there (origin).

  • What it has spent. The cap's own reading (CostCapAction.reading) against the window the engine hands it (UsageWindows.for_rule): the same population, scope, period, member share and kinds of work, paid failures and the high estimate for unpriced calls included. So blocks is true exactly when the next turn the cap governs would be refused; tests/test_budgets.py pins it for every amount around the cap, both ways a cap can respond.

  • Where it stands (status, fe-core BUDGET_STATUS): reached (spent ≥ cap), projected_over (the forecast reaches the cap before it resets), near (80% or more spent), ok, or unavailable — figures that could not be read, never shown as zero. Also remaining_usd, used_share, period_start, resets_at and previous_spent_usd (the period before, counted the same way, Span.until).

  • The forecast (budgets/forecast.py, calendar periods only): the period's spend so far plus the trailing seven complete days' mean daily spend for each day left, and a range of one standard deviation of a day's spend times √(days left). It needs three complete days of spending history (not_enough_history), reads a day with nothing spent as zero, and gives the date the cap would be reached at that rate (reaches_cap_at) when that is before the reset. A projection, labelled as one.

  • Who sees what. Every member sees each budget's totals. members — what each colleague spent — is served only to those who govern the workspace (budgets.status.governs: the owner of a Personal one, an admin, or an editor of the governance area). A cap given to each member (share: per_member) shows the viewer their own (counts: "yours").

  • The month. overview is the workspace's calendar month so far, last month and the month's forecast, counted as a budget for the whole workspace would be (usage.rule_population).

fe-core's Governance → Spend tab (apps/user/pages/spend/Spend.tsx) shows the month, each budget (BudgetBar, a tick where the forecast lands) and where the spend went (/stats/breakdown by source, agent, kind of work and, in an organisation, project, this month or last; DailyCostBars). Add budget (governors only, as rules need a governance editor) writes the rule without the builder: an amount, a calendar period, in an organisation either the organisation and every project (Required) or an allocation to one project (pinned), each member's own amount, and stop or warn.

Budgets count everything the workspace's ledger counts, and a used-up budget stops all of it (below). Because a cap counts unpriced calls high, a budget can read a little above the measured spend beside it.

Every path stops at a used-up budget

A turn — a chat answer, a skill run, an evaluation cell, a dashboard tile — meets its workspace's Access rules before it starts, a used-up budget among them. Until October 2026 everything else that reached a model was counted by every budget and stopped by none: generation flows, knowledge search, indexing, crawls and simulations (Known gap 20). Now (cost-control plan A1.5) each asks the budget gate first (app/services/budgets/gate.py):

  • The same budgets, nothing else. rule_engine.evaluate_budgets runs the workspace's cost caps and the platform allowance — the same reading, conditions and execution_types a turn's caps have — and no other rule: a content rule is a prompt's, and a crawl has none. No "room to finish" reserve: that is a turn's typical cost.

  • Used up: refused. BudgetReached, which every route answers as a 403 with the shape a blocked prompt has ({rule, message, code: "budget", resets_at}, main.py): "Monthly budget is used up. It starts again on 1 November (UTC)." The refusal of a person's work is on the activity log; passes are not recorded (a row per indexed page would bury the turns the log is read for).

  • Something left: limited to it, as a turn is (ai_client.in_spend_limit); svc-ai stopping the work there ends it the same way.

  • The paths. A generation flow (generation.metered: the run is kept as failed, with why); knowledge and repository search; indexing an upload (the document waits, pending with index_refusal: "budget", and the knowledge_reindex job indexes it from the stored file once the budget starts again, knowledge/held.py); a crawl (a scheduled one is recorded held and runs on its cadence after; one started by hand is refused); a simulation run. The evaluation judge and the optimiser's proposer are governed like the cells they grade.

  • Not refused: the rebuild after an embedding-model change. It is the platform's doing and restores search a person already had, so it is ledgered but never asked.

  • Work no person started (a scheduled crawl of an organisation's source) is counted by the workspace's budgets and never by a member's own share (share: per_member).

A turn's own limit, and room to finish it

A cap is judged before a turn starts, and a long run — a skill graph, a tool loop, a revision — used to spend past whatever was left; the cap only noticed on the next turn. Now (cost-control plan A1.4):

  • The turn is given what is left. A cap that lets a turn through hands the rule engine its remaining amount (ActionOutcome.spend_limit); the engine returns the tightest, with the platform allowance's (RulePass.spend_limit, a rule_engine.SpendLimit naming the cap and its reset). A cap set to warn sets none.

  • svc-ai stops it there. Every governed path sends the limit on each of the turn's svc-ai calls (X-Spend-Limit, ai_client.in_turn_governance / use_turn_governance, which also send the web sources the turn's Tools rules set, X-Web-Policy; work that is not a turn uses in_spend_limit); svc-ai's request meter keeps a running count of what the turn has spent, as a cap counts it (UsageMeter.enforcement_usd: each call at its price, an unpriced one at the dearest catalogue rate), and refuses the next model call once it reaches the limit (metering.check_limits, on every path the ceiling is checked: the chat model's start event, LiteLLM's direct calls, embeddings). The refusal is a fatal model error (TurnSpendLimitReached, code spend_limit): one error frame carrying what the turn spent, or a 502 on the batch API.

  • The person is told which budget. svc-core turns the refusal into ai_client.SpendLimitReached, whose message names the budget and when it starts again ("This answer was stopped: it reached what was left of the budget “Monthly budget” ($0.42). It starts again on 1 November (UTC)."). The turn is stored with that message and ledgered with what it spent, and the stop goes on the activity log as an output-phase blocked row for the cap (rule_engine.record_turn_stop: stopped_mid_turn, limit_usd, spent_usd).

  • A later part of a turn (a resume after a pause) gets the limit its re-check gives, less what the turn has spent so far, since the ledger holds that only once the turn ends (spend_limits.for_resume). Nothing left, and the resume is refused before it is sent. A skill run ledgers each segment as it ends, so its re-check already counts the segments before.

  • Room to finish (reserve, on by default). Started with a few cents left, a turn would be cut off part-way through an answer: paid for, and of no use. So a cap starts a turn only when what is left covers what a turn like it usually costs: the 90th percentile of the same resource's newest 50 paid turns of the same kind in the same workspace (usage.typical_turn_cost), or $0.05 with fewer than five (DEFAULT_TURN_RESERVE_USD). Below it the turn is refused up front — "Not enough of this budget is left to finish an answer: $0.03 left, and a turn here usually costs about $0.12." — and the event records the reserve and whether it was read or the default (reserve_usd, reserve_basis). reserve: none starts any turn while anything is left. The budget page reads each cap with the workspace's typical turn as the reserve, so reached still means new turns are refused; its note says when that is the reserve rather than the cap (tests/test_budgets.py, tests/test_turn_spend_limit.py).

  • What it cannot do. The check runs before each call, so the last call can pass the limit by its own cost, bounded by its max_tokens. Turns running at the same time each see the whole of what is left; the reserve narrows that, the limit does not close it. tests/test_turn_spend_limit.py fails on any module that evaluates a turn's rules without passing the limit on.

Platform allowances

A workspace's budgets are its own. An allowance is CHAIN-R's: what the deployment lets each workspace spend on models per calendar month (UTC), whatever its budgets say (app/services/budgets/allowance.py):

  • PLATFORM_ALLOWANCE_PERSONAL_USD — each person's Personal workspace, with their personal projects.

  • PLATFORM_ALLOWANCE_ORGANISATION_USD — each organisation, with every project in it: one allowance for the lot.

Where it is set. Deployed, the SSM group billing/ (/chainr/dev/billing/…), which the deploy writes to dotenv/prod/billing.env for svc-core alone and tools/seed-ssm-params.sh seeds off; a new value takes effect on the next deploy. Locally, dotenv/dev/billing.env (template dotenv/example/billing.env.example). See Billing.

Unset is off — unlike the spending ceiling, whose missing setting is a fail-safe default. An allowance is a commercial term, and none applies until an amount is chosen; off / none also mean none (SSM cannot store an empty string). It is enforced exactly as a cost cap is — the same reading, the same room to finish a turn, the same limit on what a turn may spend — checked before any of the workspace's rules, recorded on the activity log as "Platform allowance" (no rule id: nobody wrote it), and refused with "This workspace has used its monthly platform allowance ($50.00)." GET /app/budgets serves it as allowance, and the Spend tab shows it beside the budgets, editable by nobody there.

Alerts and the inbox

A budget tells those who govern its workspace before it stops them (cost-control plan A2, app/services/budgets/alerts.py):

  • When. A cost cap's alert_at (QuotaAlert, catalogue quota_alerts): 50, 80, 100 (used up) and projected (at the trailing week's rate, used up before it starts again). A cap that names none — every cap written before alerts existed — alerts at 80, 100 and projected; an empty list sends none. The platform allowance alerts at 80% and used up.

  • How it is noticed. The budget_alerts scheduler job (every ten minutes) reads every active cap as its budget page would — the cap's own reading, and its forecast — and writes an inbox notification for the highest level crossed. So spend that jumps from 50% to 100% between two looks sends "used up", not 80% after it, and within a calendar period a level once sent is not sent again (dedupe_key: rule, action, period start — or the UTC day for a trailing window — and level). "Heading over" is sent once a period, never for a budget already reached. The job also deletes notifications past their retention.

  • To whom. Those who govern the rule's workspace (notifications.governors, the same people budgets.status.governs lets see each member's spend): the owner of a Personal workspace; an organisation's or project's admins and governance editors, and a project's admins by position. A cap given to each member (share: per_member) tells each member about their own share instead.

  • What it says. Figures and names only — "Monthly budget is 80% used: $80.10 of $100.00 this month in Acme. It starts again on 1 November (UTC)." — never a prompt, an answer, or what a named colleague spent. Used up says whether work is refused or, on a cap set to warn, let through.

The inbox (notifications, svc-core migration 98, app/services/notifications.py) is a person's, across every workspace they belong to — like their invites — since an organisation's budget alert should reach its admins wherever they are working. Each notification is one row per recipient, written at most once per dedupe_key (uq_notification_once), names its workspace, and links to a page written against /user/… that fe-core opens in that workspace (pathIn(workspaceFromKey(key), link)). Kinds are a registry: budget_threshold, budget_projected, allowance_threshold and statement_ready (sent when a month's statement closes). GET /app/notifications (newest first, with the unread count), POST /app/notifications/{id}/read (someone else's reads as not found) and /read-all. Read ones are deleted after 90 days, unread ones after a year; a person's inbox is in their data export. fe-core shows it as a bell beside the workspace menu (components/nav/NotificationBell), read again every minute. Nothing is emailed: the stack sends no email.

Monthly statements

A statement is one workspace's calendar month (UTC) as figures: what it spent and what governed it, aggregate only — no question, answer or person's name — for finance, or for a design partner as the usage evidence behind a pilot's success criteria (the monthly organisation statement of MVP-1). app/services/statements, one registered section each:

SectionWhat it holds
by_source, by_agent, by_model, by_kind, by_projectThe same figures by the stats dimensions, named when the month closed (a deleted agent keeps its name); the twentieth row onwards folded into one
dailyEach day's spend
budgetsEach cost cap governing the workspace and the platform allowance: its cap, what the month spent against it, and the turns it refused, stopped part-way and let through past it
governanceThe rules in force by type, and what every rule evaluated came to
reviewsFlags raised and decided, open at the month's end, the median hours to a decision
evaluationsRuns completed, regressions caught
decisionsGoverned decisions, the ones a person gave a verdict (by verdict), and corrections captured as dataset cases

An organisation's and a Personal workspace's statement count their projects, as their budgets do; a project's counts itself.

  • Closed once. The spend_statements scheduler job writes each workspace's statement an hour after its month ends (statements/store.py) — every workspace with a ledger row in the month — and catches up on any month of the last year that has none. A written statement is never written again (spend_statements, svc-core migration 97, unique per workspace and month), and is kept with the SHA-256 of its canonical JSON, so a copy can be checked against it. The current month is computed live as a draft.

  • Read at GET /app/statements (the month so far and every closed month), GET /app/statements/{YYYY-MM} and …/csv (one row per figure: section, item, label, figure, value; a name typed like a formula is kept as text). Any member of the workspace may read them. Governance → Spend lists them, and each opens as a page (apps/user/pages/spend/Statement.tsx) laid out to print.

  • Exported with a person's data for their Personal workspace; an organisation's or project's are theirs.

  • Its name and cost centres (schema 2). The workspace's name and cost centre, and each project's on the by-project table, are frozen with the statement when the month closes, so a rename or a new code never rewrites a month already filed. A statement closed at schema 1 reads as it was kept.

The finance export

A finance team files spend under its own codes. An organisation's or project's admin sets a cost centre in Settings → General (organisations.cost_centre, projects.cost_centre, svc-core migration 100: free text, at most 64 characters, in the edit history). GET /app/statements/export?from=YYYY-MM&to=YYYY-MM (cost-control plan A4.2) is the workspace's statements for that run of months — at most 24, a closed month as it was kept and the current one as a draft — as one CSV: month, closed, workspace, cost_centre, then the statement CSV's own columns. Every figure is filed under the workspace's cost centre, and a project's line of the by-project table under the project's own. An organisation's statement counts its projects, so they appear only as those lines and nothing is counted twice. For those who govern the workspace (budgets.status.governs), since it spans its projects. fe-core: Export for finance on the Statements card, with a month range.

Plan prices

Every figure of spend is a cost: what a model call cost the platform. A plan is the other side — what a workspace pays CHAIN-R (cost-control plan A3, app/services/plans.py) — set in the deployment's settings, one price per kind of workspace, as the platform allowances are:

  • PLAN_PERSONAL_* — each Personal workspace, with its personal projects;

  • PLAN_ORGANISATION_* — each organisation, with every project in it.

Each is …_FEE_USD (the platform fee, a calendar month), …_USAGE_MARKUP_PERCENT and …_INCLUDED_USAGE_USD, set where the allowances are (SSM billing/, locally dotenv/dev/billing.env). Unset is no plan: all three empty, off or none, and no charges are shown anywhere. A month's charges are the fee plus the measured usage past what it includes, at cost plus the markup, to the cent — model usage at cost plus a margin (go-to-market). A call no catalogue could price has no cost to charge on, so it is counted beside the charges and never charged. Every figure is in US dollars, as budgets are.

  • On the statement (charges, after spend; an organisation's or Personal statement only — a project pays through its parent): the fee, usage at cost, what is included, the usage charge and the total, as an estimate to invoice by hand, not an invoice. Frozen when the month closes, so a price change never rewrites a month already billed.

  • In the economics export (plans): each kind's plan in force that day, so Athena sets revenue against cost (gross-margin, below).

Adding a path

A new way of making a model do work is not finished until:

  1. The ai_client function feeds the capture — _capture(response) after the call (or _capture_summary from a stream's terminal frame). test_every_function_reaching_a_model_feeds_the_usage_capture checks it.

  2. Its svc-ai endpoint is classified — in an LLMPath or, if it never reaches a model, NON_LLM_ENDPOINTS. An unclassified endpoint fails test_every_svc_ai_endpoint_is_classified.

  3. The caller opens ai_client.usage_capture() and writes the ledger with a source — record_usage(..., source_type=, source_id=, measured=) for a governed invocation, record_measured(...) for one with no governed scope.

  4. It has an entry in LLM_PATHS, and a row in the table above. A new UsageEnum.Source or execution type also needs a label in llm_paths and a row in this page's tables.

The spending ceiling

Model spend is the platform's one open-ended cost, and nothing a provider or AWS offers stops it in time: their budgets alert hours after the money is spent. So svc-ai, the only service that reaches a model, refuses a call before it is sent once the deployment's spend reaches a ceiling (modules/svc-ai/app/services/spend_guard.py).

  • Two limits: a UTC day (LLM_DAILY_CEILING_USD) and a calendar month (LLM_MONTHLY_CEILING_USD). Unset means the default, $15 a day and $150 a month, never unlimited. Only an explicit off lifts one. A typo can't remove the only hard stop.

  • Every call counts. That means every call the meter records: chat, structured calls, generation, embeddings, the evaluation judge, the platform benchmark, built-in dashboard tiles and crawls. This includes the work no user's ledger records (see Limits). A refused call costs nothing and counts nothing. A call that can't be priced counts at the dearest input and output rates in the catalogue, so a model with no price on record can't spend round the ceiling.

  • Checked on every path to a model:

    • the meter callback's start event, for every LangChain chat model (MeterCallback.raise_error, so LangChain lets the refusal through);

    • LiteLLM's two direct calls (llm.run_model, llm.stream_model);

    • every embedding chunk (Embedder.embed_many, for both embedders).

    • tests/services/test_spend_guard.py drives each and checks nothing was sent.

  • What a person sees. The refusal is a fatal model error (FatalKind.BUDGET, code budget_reached). It ends a turn once, with a message naming the limit and when it resets: "This deployment has reached its daily AI spending limit (US$15.00). It resets at midnight UTC; an administrator can raise it." The batch API answers 502 with the same code.

  • The totals survive a restart. They are held in memory and written to svc-ai's spend_counters table (migration 24, one row per period) after every call. They are re-read every 30 seconds, and the higher of the two wins.

  • Operators read them at svc-ai's GET /spend: spent, ceiling, remaining and reset time for each period.

  • The benchmark keeps to half. The platform benchmark reads /spend before every run, and every minute while one is running. Once the day or the month has used half its ceiling (CEILING_SHARE), it starts nothing more and stops the running run between cases. People are never locked out by it. A run stopped this way is interrupted, not failed. It does not count against the deploy's interruptions (held_for_spend), and runs again after the reset.

What it does not do is stop a call already in flight. A call is checked before it starts, so the calls running when the limit is reached finish, and the total can pass the ceiling by what they cost. Each is bounded by its max_tokens. The AWS-side layers that guard against a fault in svc-ai itself come with the move to Bedrock (docs/system/deployment/bedrock-migration.md).

Watching it on AWS

The pages above show a workspace its own spend. The operator watches the deployment's: what inference costs, what the rest of AWS costs, and what either bought. There are three views, each labelled with where its figures come from.

ViewWhereFigures fromHow freshCosts
Unit economicsThe same dashboard, bottom half; Athena for per-workspace detailsvc-core's daily economics exportA day after it ends (from 01:00 UTC)Under $0.50 a month (25 metrics published once a day; Athena reads megabytes)
The billBilling and Cost Management dashboard chainr-costs (management account); AthenaAWS's own bill: Cost Explorer, and the cost and usage report (CUR 2.0)Up to a dayNothing (data exports and dashboards are free)

The live view is an estimate and the bill is the truth. They should agree to within a few percent on AI inference (ai-metered-vs-billed below says by how much).

The daily economics export

economics_export, an hourly scheduler job in svc-core (app/services/economics), writes each finished UTC day once, an hour after midnight. It writes to ECONOMICS_EXPORT_DIR, so nothing is written where that is unset (locally, in CI). A day is five tables plus the day's totals as a CloudWatch request:

TableFromOne row per
metersvc-ai's meter (GET /stats/meter)workspace × source × purpose × model × outcome: every call, platform work included. The deployment's whole spend
utilitysvc-coreworkspace: active users, answers (by their quality check), finished skill runs, evaluation runs, applied generations, blocked invocations
totalsbothday: the totals, the spending ceiling's count, the inference backend
plansthe deployment's settingskind of workspace with a plan: its monthly fee, markup and included usage (services/plans.py); none for a kind with no plan
  • Whose. A row's workspace is the one the work was done in: personal, an organisation, or a project. A project's row names its organisation, so an organisation's figures can include its projects, as its quotas do. Work no person started for a workspace (a scheduled crawl of an organisation's source) is that workspace's, and counts no active user; work no one started at all (the benchmark, built-in tiles, crawls of built-in sources) is platform.

  • What for. svc-ai records a purpose for each trace. economics/attribution.py maps it onto the ledger's sources, so usage and meter compare line by line. A purpose nobody mapped is other, never guessed. A test fails when svc-ai records a purpose the map lacks.

  • Ids and figures only. No prompt, answer or name anyone typed. Workspace ids are pseudonymous rather than anonymous, so the bucket keeps them for economics_retention_days (400) and no longer.

  • How it reaches AWS. svc-core never does. It has no AWS credentials, and its one way out (the feed network) is not for this. The host's chainr-economics-ship.timer ships each complete day every hour, as the instance role (infra/aws/economics). That role may add files under economics/ and publish to one CloudWatch namespace, nothing more. The tables go to S3, where Athena reads them; the totals go to CloudWatch (ChainR/Economics), where the dashboard draws cost per answer, cost per active user, the pass rate of checked answers, the platform's share, cache savings and wasted spend.

  • Catching up. A job that missed days writes them on its next runs, a week at a time, as far back as ECONOMICS_EXPORT_LOOKBACK_DAYS (30). CloudWatch refuses figures more than two weeks old, so older days reach S3 only.

Athena's tables are infra/terraform/envs/dev/economics-tables.json, which a test holds equal to the columns the export writes.

The bill by module

infra/aws/billing/modules.json says which module every line of the AWS bill belongs to: AI inference, Hosting, Delivery, Observability and security, Cost controls, Tax, or Other. The first matching rule wins:

  1. What a line is. Tax is Tax. Anything AWS Marketplace bills is AI inference: Claude and other third-party models on Bedrock are billed there, each model as its own product. So are the Bedrock services AWS bills itself (Qwen3, gpt-oss, reserved capacity).

  2. Its component tag. Every resource in infra/terraform/envs/dev that bills carries one (hosting, delivery, cost-controls, …), so a shared service's resource lands in its own module: the economics bucket is Cost controls, the artifacts bucket Delivery. tools/test_billing.py fails on a billable resource without one.

  3. Its service, for everything untagged.

Two things read those rules:

  • The cost category CHAIN-R module, for Cost Explorer, budgets and the chainr-costs dashboard. Only an Organization's management account may create a cost category or activate a cost allocation tag, and no Terraform or CloudFormation resource creates the dashboard, so infra/aws/billing/billing.py does all three, run with the management profile.

  • module_case.sql, the same rules as a SQL CASE that Athena groups the cost and usage report by. It is generated from modules.json, and a test fails when the two differ.

The dev account exports its own cost and usage report (CUR 2.0, daily, with the IAM principal behind each Bedrock call) into the economics bucket, under cur/ (billing.tf). A member account's export holds its own costs only.

Questions Athena answers

Saved queries in the chainr-dev-economics workgroup (Athena → Saved queries), one file each in infra/terraform/envs/dev/athena/:

QueryAnswers
ai-metered-vs-billedEach day's model spend as CHAIN-R metered it, as the ceiling counted it, and as AWS billed it
bedrock-by-callerWhich IAM principal each Bedrock line was billed to. Anything other than svc-ai's invoke role used the account's models outside CHAIN-R
spend-by-sourceEach day's model spend by what caused it, platform work apart
unit-costsSpend per answer and per active user, the pass rate, the platform's share, cache savings, wasted spend
organisation-costEach organisation's month, marginal (the model spend its work caused) beside fully loaded (plus a share of the platform's spend and the rest of the bill)
workspace-valueEach workspace's month: spend, what it bought, cost per answer
model-spendEach model's month: calls, failures, unpriced calls, spend, cache savings
attribution-coverageOwned spend svc-ai metered against what the ledger attributed. A gap is a path that skipped the ledger
gross-marginEach organisation's month: its plan's charges (plans, the fee plus usage past what it includes at cost plus the markup) against its marginal and fully loaded cost, and the gross margin. No plan, no row

organisation-cost shares the common costs by each organisation's part of all owned model spend. That is a choice, not a fact. Active users or seats are as defensible, and the query says where to change it.

What it does not do yet

  • Margin needs plan prices. gross-margin has no rows until a deployment sets its PLAN_* settings, and a plan is a price per kind of workspace — an instance whose organisations pay differently needs per-organisation prices, not built. A revenue forecast is not built either.

  • Budgets against actuals are on the Budgets page, not the dashboard. The dashboards API's budget widget is not in the AWS CLI yet.

  • Not checked against a live account. The Billing and Cost Management dashboard request follows AWS's documentation and examples, which disagree in places. If billing.py apply is refused, build one widget in the console, read it back with aws bcm-dashboards get-dashboard, and match dashboard_request to it.

  • Per-model live spend assumes Bedrock names a model as svc-ai calls it (an eu. profile id rather than the model behind it). The dashboard's "Tokens by model, as Bedrock reports them" widget shows whatever ids Bedrock uses, so a mismatch is visible as tokens with no priced line.

  • Tags apply forward. AWS lists a tag key for activation only once a resource carrying it has been billed, and activation does not reach back unless asked (billing.py apply --backfill, up to twelve months).

Limits

  • Rows written before migration 69 carry no source unless they were agent, model or skill rows (backfilled from their scope). Old dashboard and evaluation spend counts toward the account, not toward any one board or evaluation.

  • Multi-model runs have one ledger row with one ai_model_id (or none): "cost by model" on the model dimension attributes a skill run's spend to nothing. The per-model split of a run is on the run itself (skill_runs.cost_detail) and in svc-ai's per-call trace.

  • Work no person started. A scheduled crawl of a project's or organisation's source, or the rebuild of its index, has no person: it is ledgered to no one, stamped with its workspace (svc-core migration 99), so the workspace's budgets count it and no member's share or "your spend" does. Before migration 99 such work was not ledgered at all. CHAINR Bot's guide and the built-in News repository are indexed with no owner: platform cost, not anyone's. Every website crawl, these included, stores what it cost on its own row (knowledge_crawls.usage), so that spend is recorded even where the ledger cannot hold it (News). The built-in dashboards' generated tile (the Daily briefing's fun fact) is the same: it runs for nobody, ungoverned and unledgered, and every tile refresh — on any board — records what it cost on its background event (background_events.detail.usage), which is the only record for a built-in board. The platform benchmark (CHAINR Bot and each maker's strongest model on the gold datasets, run by CHAIN-R when something that decides a score changes) is the same again: its experiments have no owner, so its runs are ungoverned and unledgered. Each run stores its measured cost, agent turns and judge calls together, on its summary (experiment_batches.summary.usage, runner.measured_usage) and on its platform_benchmark background event. PLATFORM_BENCHMARK_BUDGET_USD caps its total per calendar month, and each target runs at most one round a month. Every evaluation run now carries that measured summary, owned ones included (Evaluation).

  • Work svc-ai does on its own — nothing svc-core asked for — is metered by svc-ai but has no svc-core caller to ledger it. Today there is none.

  • A stream that fails mid-way is ledgered with what its calls cost (see "A turn that does not finish is still paid for"), read back from svc-ai's trace when no terminal frame arrived.