Ledger Schema Reference
The SpendEvent 1.0 wire schema — 18 fields — and the 13 attribution dimensions, as a dictionary.
One SpendEvent per completed provider request. The dataclass is frozen,
validated on construction, and round-trippable:
SpendEvent.from_dict(SpendEvent(...).to_dict()) == SpendEvent(...).
schema_version is the literal "1.0".
A persisted line must carry exactly the 18 fields below. An unknown key and a
missing key are both ValueErrors naming every offender, so a typo or a
truncation cannot reload as plausible-looking data.
Fields
| field | type | meaning |
|---|---|---|
event_id | str | 32 lowercase hex characters, a version-4 UUID written directly into random bytes |
occurred_at | str | RFC 3339 UTC with exactly six fractional digits: 2026-09-26T13:01:46.964576Z. Fixed width, so string order is chronological order |
schema_version | str | "1.0" |
provider | str | openai or anthropic, matched from the request host. A host that is neither is unknown, which is therefore unpriced |
model | str | what the response reported, not what the request asked for — a measurement of what was billed |
endpoint | str | the full request URL, normalised: no query string, no fragment, no user:pass@. A credential-shaped query parameter is recorded as ?<redacted> so the reader can see one was there without the value being stored |
priority | str | critical, default or background |
outcome | str | success, error or fallback. circuit_open, budget_denied and queue_timeout are reserved and are not emitted today — those requests never reached a provider, so they have no usage report and no dollars |
input_tokens | int | the fresh, non-cached prompt tokens — the ones a rate card charges at the full input rate |
output_tokens | int | completion tokens |
cache_read_tokens | int | cached prompt tokens read |
cache_write_tokens | int | prompt tokens written to the cache |
latency_ms | float | wall clock from entering the transport to this record |
retries | int | attempts after the first |
estimated | bool | True when the token counts are a local floor rather than a provider report. Read this before any total |
attribution | Attribution | thirteen optional strings — see below |
cost | CostBreakdown | None | None when no price is known. The absence is the record |
request_id | str | None | x-request-id or request-id off the response, so a row joins to a provider dashboard |
The four token counts are validated as int and >= 0 on construction — True
is refused by name, because bool is an int subclass.
Every money value crosses the wire as a string ("0.010000"), never a JSON
number. A JSON number is read back as a binary float, and a finance export that
loses cents is worse than one that is awkward to parse.
Attribution — the 13 dimensions
All optional. A value of None, or an empty or whitespace-only string, means
unset; an unset field never erases one an outer scope set. group_by on the
export accepts any of these names, and rejects an unknown one as an argparse
usage error listing the legal dimensions.
| dimension | typical use |
|---|---|
team | the unit a chargeback is grouped by |
agent | which agent in a fleet |
session | one conversation or run |
task | one unit of work inside a run |
feature | the surface or product area |
surface | where the call came from (chat, batch, eval) |
customer | which customer the spend is for |
tenant | which tenant, when you bill per tenant |
environment | prod / staging |
repo | which codebase |
cost_center | the finance-system field |
gl_code | the general-ledger account |
currency | the currency the group is billed in |
Set them with a context manager, a decorator, or read them back:
from backstop import attribution, current_attribution, with_attribution
with attribution(team="payments", feature="checkout-v2", customer="acme"):
client.chat.completions.create(...)
@with_attribution(agent="refund-bot")
def handle_refund(ticket):
...
current_attribution().teamcurrent_attribution() never returns None; in a process that has declared
nothing it returns an all-None Attribution, which is a valid record. Nesting
merges and the outer value is restored on exit, including when the body raises.
An unknown field name, or a non-string value, raises TypeError at the call
rather than being dropped from the ledger.
with_attribution refuses a deferred body — a generator function, an async
generator function, or a plain function returning a coroutine or generator is
refused with TypeError rather than leaving the ledger silently unattributed. An
asyncio.Future/Task is allowed through, because the work was scheduled inside
the scope and the task copied the context there.
CostBreakdown
| field | meaning |
|---|---|
input_usd, output_usd, cache_read_usd, cache_write_usd | the four component costs, as decimal strings |
total_usd | their sum, quantised to six places with ROUND_HALF_UP |
currency | USD |
price_source | override, user, bundled, or mixed |
priced_components | which components actually got a rate. A component the rate card publishes nothing for is charged zero and named here, so the row can say its line is a floor instead of presenting a zero as a measurement |
estimated_tokens | True when the token counts behind these numbers are a local floor |
A component absent from priced_components is not free. It is unpriced.
Price resolution
PriceCatalog.resolve(provider, model) returns a PriceEntry or None.
Precedence, highest wins:
- an explicit per-call
price_overrides—price_source="override" - your catalog file,
config.price_catalog_path—price_source="user" - the bundled table —
price_source="bundled"
Each layer is searched in full, across every name tier, before the next is
consulted. A user price for gpt-4o beats a bundled price for the exact string
gpt-4o-2024-08-06, because your layer is the higher one.
Name resolution is three tiers: the exact string, then the name with a
trailing snapshot marker stripped repeatedly (-2024-08-06 OpenAI, -20241022
Anthropic, -latest), then a fixed alias map. So a dated snapshot, an -latest
alias and claude-3.5-sonnet all resolve.
An unknown model is None, not a guess. compute_cost returns None, the
event is recorded with cost=None, and the export counts it in
unpriced_requests. There is no default rate and no neighbouring-model fallback.
Rates are in USD per million tokens. The arithmetic runs under the ledger's own
decimal context — 28 significant digits, ROUND_HALF_UP, every field named —
never the host process's, because a decimal context is process-global and a
library cannot ask the host to leave it alone.
Export columns
build_chargeback(events, group_by=("team", "feature")) aggregates events into
one row per group, largest total first. In export order: the group keys, then —
| column | what it is |
|---|---|
request_count | requests in the group |
input_tokens, output_tokens, cache_read_tokens, cache_write_tokens | the four counts, summed |
total_usd | the exact sum, rendered to 2 decimal places as a string |
currency | USD |
price_source | the layer that billed the group, mixed if more than one, (none) if nothing was priced |
unpriced_requests | requests with cost=None. Their dollars are absent, not zero |
estimated_requests | requests whose tokens are a local floor. Same population as request_count; may overlap unpriced_requests — a request that is both is in each |
unpriced_components | token components the group carried tokens for with no published rate. (none) when every component was priced |
first_seen, last_seen | RFC 3339 UTC, the group's window |
An unset group key renders as (unattributed), never as a blank cell. There is no
totals row in the CSV.
revenue_join(rows, revenue_map) emits a second CSV keyed on the same group
tuple: request_count, total_usd, revenue_usd, margin_usd, match,
currency. match is both, cost_only or revenue_only, and a group missing
on either side carries (none) — because margin_usd is absent unless both
sides are present.
Detection signals
detection_enabled=True builds a RunawayDetector over a bounded window of the
last detection_window_size events per attribution key. A signal is a
frozen record: kind, severity, key, observed, threshold, detail,
occurred_at. It cannot block a request, cancel work, kill an agent, or raise.
| kind | fires when |
|---|---|
velocity | priced spend in the window over the minutes it spans exceeds detection_velocity_threshold_usd_per_min |
drift | mean tokens per request over the recent half of the window exceeds detection_baseline_multiplier × the older half |
context_growth | this request's input tokens exceed the rest of the window's median by detection_context_growth_threshold |
retry_amplification | mean retries per request exceeds detection_retry_ratio_threshold |
An unpriced event contributes zero to the velocity numerator while still being observed for tokens and retries — padding it with a guessed rate would make a finance-facing figure look measured.
detection_shadow=True is the default: the same signals are produced and also
filed in a bounded log with a per-kind counter, so a threshold can be tuned
against evidence before it can interrupt anybody.
BACKSTOP_DETECTION_SHADOW overrides the config in both directions.
A nonsense threshold is refused at wrap() rather than discovered on the first
request: a negative or non-finite threshold, a baseline_multiplier below 1.0
(which inverts the comparison rather than alerting earlier), a non-positive
window, and min_samples > window_size — a detector that can never speak, and
looks exactly like a healthy one. detection_max_keys (default 1,024) bounds the
number of keys; eviction is LRU and counted in evictions, because a
silently evicted key is a key whose baseline silently restarts.
Delivery counters
Two reports, and they do not answer the same question.
From a live writer — state.close(), or delivery_report(writer) — the only
place the process-local counters exist:
| counter | meaning |
|---|---|
submitted | every call to writer.submit, including the ones refused |
written | writes the sink returned from — an upper bound on records, not a count of them |
landed | written less the failures the sink counted itself. This is the number of records a reader of the file will find |
dropped_events | submits refused because the bounded buffer was full, plus anything discarded at an unfinished close |
sink_errors | writes that raised out of the sink |
sink_reported_errors | writes the sink returned from without raising and did not record |
sink_degraded | the sink says it has stopped appending |
lost | dropped_events + sink_errors + sink_reported_errors, through one shared function so the shutdown and live paths cannot disagree |
The accounting invariant is submitted == written + dropped_events + sink_errors, asserted only when the report says drained.
From a file — backstop ledger show --path ... — a JSONL line records an event,
never a counter. So a file read reports dropped_events: unknown and
sink_errors: unknown with the reason, rather than as 0, because a zero is
a claim about a process it cannot see. The one loss a file can prove is a torn
final line: a final line that will not parse is reported as a torn write and the
rest is read (exit 0); a final line that is unterminated but parses is reported
and kept, because dropping a complete event loses a dollar; an unparseable
line anywhere other than the end is real corruption, and export writes
nothing.
— Edit this page on GitHub