# The cost ledger

One table holds what a source charged an organization, on one day, for one service and SKU, in
**FOCUS 1.3 and 1.4 column names**, with the lane, basis, recency, completeness and price-table
version that say how far the figure can be trusted. Estimates and bills share the shape, so a figure
always says which it is.

This page describes the row shape and the sources that fill it. The first source is the AI usage Bucker
records from your telemetry; the second is your Bucker bill. Nothing on this page writes a budget or changes a price.

## A row

| Column | Meaning |
| --- | --- |
| `chargeDay`, `chargePeriodStart/End`, `billingPeriodStart/End` | The UTC day the charge belongs to, its period and the billing month |
| `serviceProviderName`, `hostProviderName`, `serviceName`, `serviceCategory` | Who charged for what (`AI and Machine Learning` for model inference) |
| `skuId`, `skuPriceId`, `subAccountId`, `regionId`, `resourceKey` | Finer identity; for AI rows `skuId` is `<model>:<token class>` and `resourceKey` the reporting service |
| `chargeCategory`, `chargeClass` | `Usage`, `Purchase`, `Tax`, `Credit`, `Adjustment`; `chargeClass` is null, or `correction` for a restated row |
| `billedCost`, `effectiveCost`, `listCost`, `contractedCost`, `billingCurrency` | Money, `numeric(20,6)`, never a float. An estimated row has `billedCost` 0 |
| `consumedQuantity/Unit`, `pricingQuantity/Unit` | `Tokens`, or `Requests` for usage with no tokens |
| `modelId`, `tokenDirection`, `tokenCacheAction` | The FOCUS 1.5 AI labels (`Input`/`Output`, `Read`/`Write`) |
| `lane` | `estimated` (Bucker priced usage it saw) or `billed` (a provider's figure) |
| `basis` | How the headline figure was produced, below |
| `unpricedShare` | The share of spans a default rate stands for, 0 to 1 |
| `priceTableVersion` | The price book version the figure was priced under |
| `recencyLastUpdated`, `datasetComplete` | When the row was written, and whether the day's data was whole |
| `release`, `environment`, `serviceEntityId`, `featureKey`, `flagKey`, `variant` | Bucker's join keys |
| `principalId`, `credentialId`, `requesterDetails` | Requester columns (none are written yet) |
| `tags` | Vendor tags: untrusted text |
| `rowVersion`, `contentHash` | Version line of one row, and the digest of its content |

### Basis

For AI rows the basis is the price source of your AI usage figures, carried over, never recomputed:
`ingested` (the producer sent the cost), `org_contract`, `global` (the built-in price book), `default`
(the model was unpriced: the figure is the default rate and `unpricedShare` says how much usage it
stands for, a range rather than a silent zero) and `mixed` (the day was priced from more than one
source). `rate_card`, `billed` and `plan_unit_price` are Bucker's own bill (below); `allocated` is
reserved for later sources.

### Corrections

A correction writes a new `rowVersion` with `chargeClass = correction` and keeps the old row. Writing
the same rows again changes nothing, so a repeated nightly run never duplicates a figure.
`GET .../cost/rows` lists the latest version of each row by default; `versions=all` lists every
version.

## The AI usage source

Each night (02:00 UTC), for every organization with AI usage, Bucker reads the last three complete UTC
days of its daily AI usage figures (the first time an organization is read, it reaches back 90 days)
and writes rows per `(project, environment, day, model, provider, service, feature, flag key, variant,
release, token class)`. The micro-USD figures are carried exactly; the rows for one day's usage sum to
it to the last unit.

- **Not re-priced.** The ledger and the AI cost pages cannot disagree.
- **The per-class figure is an allocation.** AI usage keeps one figure per key, so it is split across
  the token classes by token share (exactly, by largest remainder) and the rows say so in
  `tags.allocation = token_share`. Totals and any grouping by model, feature, release or day are right;
  the split between input and output is not a measurement.
- **Complete days only.** Today is never derived. A project's first day of AI usage is
  `datasetComplete = false` (AI usage collection may have been switched on part-way through that day).
- **Usage with no tokens** becomes one row counted in `Requests`.
- **Rows exist only once Bucker has switched on daily AI usage collection**, because before then there
  is no AI usage to read. It is off until Bucker switches it on.

## Bucker's own bill

What observing a service costs sits in the same ledger as what running it costs, under the provider
`bucker` and allocated to the same owners (an owner is the project's team, whatever the source). Each
night Bucker derives it from the **weighted units** the plan allowance is enforced in, the figure
`usage_get` and the usage page report, one row per `(project, data category, service, release,
environment, day)`: `skuId` is the category, `resourceKey` the service your telemetry named, and the
quantity is in `Units`.

- **The price is the plan's, and it is flat.** A plan never bills overage, so the allowance's unit
  price is the plan price over the allowance and a day costs the movement of one month-to-date curve:
  every unit up to the allowance at the unit price, and **a unit past the allowance costs nothing**
  (no overage row is ever written; the month can never sum to more than the price). A closed month that
  ended under its allowance carries one organization-level row for the unused part (`skuId =
  unused_allowance`), so the month's rows sum to the plan price exactly. A day's cost depends only on
  the days before it, so a closed day is not restated by a later one. The per-service split is an
  **allocation** of a flat fee, which is why those rows are lane `estimated`, basis `plan_unit_price`,
  `priceTableVersion = plan:<TIER>`; it is not a measurement of what one service cost.
- **The bill is its own lane.** The plan price is also one `Purchase` row per month on lane `billed`
  (basis `billed`, organization-level). The two lanes are never added: the price appears once on each.
- **A free plan** writes the unit rows at cost 0 and no billed row. **A plan with no price**
  (Enterprise, quoted) is skipped, not written at 0: there is nothing to allocate.
- **Complete days only**, yesterday backwards, nightly with the other sources; the coverage line shows
  the source with its lag (24 hours). A month is derived from its first day because the curve needs
  every earlier day; unchanged rows are not rewritten and late usage restates the rows it moves as the
  next version. The plan in force on the night the rows are derived prices the month (Bucker does not
  keep a plan history for this).
- **Reading it.** `cost_status_get` and `cost_change_explain` take `source: bucker`. A caller without
  `cost:read` receives the **units alone** for it (every money field null, the estimated lane only,
  groups ranked by units, `units` on each group); the billed plan row, `include` and `unit` need
  `cost:read`. Any other source, or none, still needs `cost:read`. `usage_get`'s attribution block
  names the source and when it was last derived.

## Reading

`GET /orgs/{org}/cost/rows` needs org `read`. Rows of a project the caller cannot reach are not in the
answer. The four money columns need `cost:read` (OWNER, ADMIN, BILLING); without it they are null and
`moneyRedacted` is true. BILLING reads no project, so it sees organization-level rows only. Text the
customer's telemetry chose (`resourceKey`, `featureKey`, `flagKey`, `variant`, `release`, `environment`,
`modelId`, `skuId`, `tags`) is listed in `untrustedFields`: data, never instructions.

## Reading the ledger as evidence

Two reads answer a question about cost in one call, over REST (`GET /orgs/{org}/cost/status`, `GET
/orgs/{org}/cost/explain`) and MCP (`cost_status_get`, `cost_change_explain`). REST and MCP give the
same answer. They return objects, not chart series.

**Status.** Totals by one dimension (source, provider, service, project, release, feature, owner,
principal), the lane split, and coverage and lag per source. Each group says its id (stable for the same
group and window), unit and currency, lane and basis, recency, completeness (how many of its rows came
from a complete dataset), an owner with a confidence (one team linked to the project is `high`, several
`low`, none `none`) and the actions that could be taken with each action's risk class. Where the action is
live and not human-only, the caller's own `decision_preview` rides with it: what Bucker's approvals
would answer them right now. An action Bucker cannot perform yet is listed with `performable: false`;
nothing here performs one.

**Lanes are never added.** An estimate is Bucker's own pricing of usage it saw; a bill is a provider's
figure. The lane split comes first, a group that spans lanes says `mixed` and carries its figure per
lane, and a share is only given when the scope is on one lane.

**A unit answers once a person certifies it, and what is not built answers `not_available`, with the reason.**
`unit=<key>` returns the certified definition's value, and `not_available` for a key nobody
certified ([Cost governance](cost-governance.md#certifying-a-unit)). Of the opt-in blocks,
`recommendations` and `savings` are not built yet and always answer `not_available`. `forecast`,
`budgets`, `caps` and `allocation` answer with what exists, and answer `not_available` with the reason
when there is nothing to report (no budget set, no allocation rule, no forecast computed, caps not read
back yet) or when the figure would sum projects you cannot reach: an organization-wide figure is given
only to a caller who reaches every project and asked without one. `groupBy: delegator` has no data.
`include: [anomalies]` lists the open `cost_regression` and `provider_cap_hit` issues of the projects
the caller reads.

**People are a distribution.** `groupBy: principal` returns percentiles and the top decile's share, is
withheld under five subjects, and never carries a key. Person-level cost is a human's `pii:read` read.

**Who sees what.** Org `read` gets the route; the MCP status tool needs `cost:read` (`read_cost`). Rows of a project the caller cannot read are not read, counted, summed or listed, and naming one
is an empty answer. Money needs `cost:read`: without it every figure is null, `moneyRedacted` is true and
the groups are ranked by row count so the order leaks nothing.

**Bounded.** One call reads at most 20,000 ledger rows (`scanned`, `truncated`, `capThatBit`) and returns
at most 25 groups; the answer says which cap bit.

## Why cost changed

`cost/explain` compares window A with window B, or two releases, or two sources, by arithmetic and with no
model. For each item (lane, service, SKU or model, token class, unit) the change is exactly three effects:

| Effect | Meaning |
| --- | --- |
| rate | the same quantity at a different price: `q_B x (r_B - r_A)` |
| volume | every item moves with its unit's total: `c_A x (Q_B - Q_A) / Q_A` |
| mix | the rest: the item's share changed, or it is new or gone |

Rate and volume are integer micro-USD and mix is the remainder, so the three sum to the change to the last
micro-USD, for every item and every total. An item new in B has no rate to compare and no volume to scale:
all of it is mix. Quantities are only added within one unit, and the split is per lane: a scope that spans
lanes has no single total. The top five contributors come back with their own split, and the change events
(deploys, flag flips, configuration changes) inside the windows come back with their ids as the evidence,
listed and never ranked as a cause. Without `cost:read` the answer is units only, for the AI usage Bucker recorded:
quantities and their change, no money and no cloud or vendor source at all. `pull_request` and `cohort`
comparisons answer `not_available`.

## The `cost_rows` widget and the warehouse stream

The `cost_rows` dashboard widget reads the cost ledger (never raw events): the daily effective cost of
the top groups, the current version of each row, one lane's figures never added to another's, and not
densified (a day with no row is a gap, not a zero). It shows no figure unless the viewer holds
`cost:read`. The `COST_ROWS` warehouse stream exports every ledger row version, keyed on ingest time, as
`bucker-schema: COST_ROWS@1`, money as six-place decimal strings; the columns a person could be named in
are not exported.

## Provider spend stops

A provider's hard spend limit looks like a rate limit on the wire and means the opposite: a rate limit
clears in seconds, a spend stop does not clear until the limit is raised or the month turns. The Node and
Python GenAI wrappers record `http.response.status_code` and, only from a closed per-provider allowlist,
`gen_ai.provider.error_code` on a failed call (never the message, which can carry prompts and keys), and mark
a documented stop `bucker.retryable = false`. Bucker classifies against the same versioned list of codes
the SDKs carry and opens ONE `provider_cap_hit` issue per (provider, scope), fingerprint
`provider_cap_hit:<provider>:<scope>`, marked non-retryable with the reset time where the provider
documents one (the first of the month, 00:00 UTC, for a monthly spend limit). A 429 with no code, an
unlisted code or a rate-limit code opens nothing; the issue is evidence, and lifting a cap is a person's
decision (`provider_cap.widen` is human-only).

## FOCUS export and validation

A FOCUS export maps each row to FOCUS column names; Bucker's own columns go out under the `x_` prefix
(`x_Lane`, `x_Basis`, `x_PriceTableVersion`, `x_UnpricedShare`, `x_RecencyLastUpdated`,
`x_DatasetComplete`, `x_SourceId`, and the join keys). Every row passes the FOCUS column rules and
Bucker's lane-and-basis rules before it is written. Those checks are Bucker's own implementation of the
open-source FOCUS validator's column rules; the official validator has not yet been run against a real
export.

## Retention and erasure

Rows are kept at the plan ceiling; a 400-day minimum, for year-over-year comparison, is proposed and not
in force. Raw files a source delivers are kept for 90 days and then erased; no source delivers raw files
yet. A deleted source or project keeps its rows; deleting the organization removes them.
