Backstop
Reference

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

fieldtypemeaning
event_idstr32 lowercase hex characters, a version-4 UUID written directly into random bytes
occurred_atstrRFC 3339 UTC with exactly six fractional digits: 2026-09-26T13:01:46.964576Z. Fixed width, so string order is chronological order
schema_versionstr"1.0"
providerstropenai or anthropic, matched from the request host. A host that is neither is unknown, which is therefore unpriced
modelstrwhat the response reported, not what the request asked for — a measurement of what was billed
endpointstrthe 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
prioritystrcritical, default or background
outcomestrsuccess, 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_tokensintthe fresh, non-cached prompt tokens — the ones a rate card charges at the full input rate
output_tokensintcompletion tokens
cache_read_tokensintcached prompt tokens read
cache_write_tokensintprompt tokens written to the cache
latency_msfloatwall clock from entering the transport to this record
retriesintattempts after the first
estimatedboolTrue when the token counts are a local floor rather than a provider report. Read this before any total
attributionAttributionthirteen optional strings — see below
costCostBreakdown | NoneNone when no price is known. The absence is the record
request_idstr | Nonex-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.

dimensiontypical use
teamthe unit a chargeback is grouped by
agentwhich agent in a fleet
sessionone conversation or run
taskone unit of work inside a run
featurethe surface or product area
surfacewhere the call came from (chat, batch, eval)
customerwhich customer the spend is for
tenantwhich tenant, when you bill per tenant
environmentprod / staging
repowhich codebase
cost_centerthe finance-system field
gl_codethe general-ledger account
currencythe 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().team

current_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

fieldmeaning
input_usd, output_usd, cache_read_usd, cache_write_usdthe four component costs, as decimal strings
total_usdtheir sum, quantised to six places with ROUND_HALF_UP
currencyUSD
price_sourceoverride, user, bundled, or mixed
priced_componentswhich 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_tokensTrue 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:

  1. an explicit per-call price_overrides — price_source="override"
  2. your catalog file, config.price_catalog_path — price_source="user"
  3. 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 —

columnwhat it is
request_countrequests in the group
input_tokens, output_tokens, cache_read_tokens, cache_write_tokensthe four counts, summed
total_usdthe exact sum, rendered to 2 decimal places as a string
currencyUSD
price_sourcethe layer that billed the group, mixed if more than one, (none) if nothing was priced
unpriced_requestsrequests with cost=None. Their dollars are absent, not zero
estimated_requestsrequests whose tokens are a local floor. Same population as request_count; may overlap unpriced_requests — a request that is both is in each
unpriced_componentstoken components the group carried tokens for with no published rate. (none) when every component was priced
first_seen, last_seenRFC 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.

kindfires when
velocitypriced spend in the window over the minutes it spans exceeds detection_velocity_threshold_usd_per_min
driftmean tokens per request over the recent half of the window exceeds detection_baseline_multiplier × the older half
context_growththis request's input tokens exceed the rest of the window's median by detection_context_growth_threshold
retry_amplificationmean 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:

countermeaning
submittedevery call to writer.submit, including the ones refused
writtenwrites the sink returned from — an upper bound on records, not a count of them
landedwritten less the failures the sink counted itself. This is the number of records a reader of the file will find
dropped_eventssubmits refused because the bounded buffer was full, plus anything discarded at an unfinished close
sink_errorswrites that raised out of the sink
sink_reported_errorswrites the sink returned from without raising and did not record
sink_degradedthe sink says it has stopped appending
lostdropped_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

On this page