# 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 is the row shape. The first source is Bucker's own AI usage rollup. Budgets, anomalies,
forecasts and the agent reads are later cards; nothing here 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 written yet; a person in `requesterDetails` joins erasure with COST-19) |
| `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 rollup's price source, 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. The same
rows written again change nothing, so the nightly pass is idempotent. `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 rollup rows, the pass reads the last three complete
UTC days of `ai_usage_days` (the first derivation of an organization reaches back 90) and writes rows per
`(project, environment, day, model, provider, service, feature, flag key, variant, release, token class)`.
The rollup's micro-USD is carried exactly; a rollup row's rows 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.** The rollup stores 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 rollup day is `datasetComplete = false`
  (the pillar may have been switched on mid-day).
- **Usage with no tokens** becomes one row counted in `Requests`.
- **Rows exist only once `pillar.ai_usage_rollup` is on**, because the rollup has nothing before then.

## Bucker's own bill (COST-09)

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). The
nightly pass 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 when the pass runs prices the month (plan history is not recorded).
- **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 (COST-03)

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`), from one computation:
`domain/modules/cost/reads.ts` and `change-explain.ts`. 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 the approvals engine
would answer them right now. An action no door performs 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.

**What no card has built answers `not_available`, naming the card.** `unit=<key>` (COST-12) and the opt-in
blocks `forecast` (COST-15), `budgets` (COST-13), `caps` (COST-16), `recommendations` (COST-17),
`allocation` (COST-11) and `savings` (COST-20). `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 is held (`read_cost`, `cost:read`,
SG-059). 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-03, COST-06)

`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 Bucker's own AI usage:
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 `cost_rows` (never `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 (COST-08)

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`. The server classifies against the same table
(`domain/modules/cost/provider-codes.json`, versioned; a test holds the SDK copies equal) 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

`toFocusRecord` maps a 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. The checks are Bucker's re-implementation of the
open-source validator's column rules; running the Python validator on a real export is a human item.

## Retention and erasure

Rows are kept at the plan ceiling, with a 400-day floor proposed for year-over-year comparison. Raw
files a source delivers are kept under `cost/raw/<org>/<source>/<day>/` for 90 days and then erased
(the object first, then its catalogue row); nothing writes raw files yet. `cost_rows` is partitioned by
month. A deleted source or project keeps its rows; deleting the organization removes them.
