Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Engine reference — generated from the canonical engineering source. Do not edit this page by hand.

Cost & Spend Enforcement

Cost-accounting scope. This page documents inference cost accounting from model-provider rate metadata. It is not a commercial offer; commercial terms are not announced. For licensing or evaluation, contact Spacebeam.

Decision: ENFORCE. The server has a real rate source and a per-principal daily ledger; inference admission is gated before upstream spend. The retired alternative (delete the cost API and keep the token-rate proxy as “truth”) was not taken.

What carries rates

The declarative model catalog (contract/model_catalog.yaml → server/priv/model_catalog.json) is the billing rate source ( ), read through sol_cost:price/1 / sol_cost:estimate/3. Aliases and local lane ids resolve through the same catalog lookup; a a zero-rate local entry is deliberate; a model with no catalog row or no numeric rate block is unknown_price — never silently zero. cost_unknown_price_total and inference_model_unpriced_total{model} are both counted on that path. sol_model_metadata is the fallback for operator-only rows/tests (and for dated ids the catalog does not list).

Ollama discovery rows are namespaced (source => dynamic, namespace => ollama): a refresh never overwrites a static/operator row and deletes its own stale rows. See catalog.md and the rate notes in api-reference.md.

Ledger

sol_spend_guard keeps one public ETS table (sol_spend_ledger) with two row families:

  • {daily, UserUuid, UTC-day} — input tokens, output tokens, USD micros (settled) plus pending columns for reservations;
  • {model, UserUuid, UTC-day, Model} — the same totals per model, used by GET /api/v1/usage.

Arithmetic. used, pending and remaining are disjoint: a reservation adds to pending only, settle/2 removes the pending amount and adds the actual usage, and release/1 removes pending without billing. The strict reserve/2 path serializes its check+reserve pair per principal/day (an ETS lock row); the pre-fix shape added an estimate to used and pending, so every reservation was double-counted and the ledger permanently inflated. GET /api/v1/usage reports pending_* and remaining_* alongside the settled totals.

Window. The day key is the UTC calendar date; a new UTC midnight starts at zero automatically (old days stay readable until the table is reset). Durability. The ledger is in-memory, anchored to a supervisor heir. When a fresh table is created (a VM/app restart; a heir-survived table is compared, never reset), the current UTC day is rebuilt from the tenant-attributed inference.complete events, deduped by request_id. The rebuild now PAGES the whole day with the until/until_id older-side cursor (sol_sync_event:get_all_events/1) until exhausted — the pre-fix shape read one newest-first 10k window with no truncation detection, so a busy day silently under-reported. The absolute page bound (inference_ledger_rebuild_max_events) turns a pathological log into a TYPED truncation: sol_billing_ledger_rebuild_truncated_total increments and neither rebuild_day/0 nor reconcile/0 reports success/match on an incomplete read. With sync_enabled=false there is no durable source at all: the rebuild refuses with sync_disabled and bumps sol_billing_ledger_rebuild_skipped_sync_disabled_total rather than claiming a successful empty rebuild. A mismatch between the ledger and the durable projection bumps sol_billing_ledger_reconcile_mismatch_total and logs CRITICAL; an event without a user_uuid bumps sol_billing_ledger_unattributed_total (it cannot be reconstructed for chargeback).

Bounded housekeeping. The one-shot settlement markers ({settlement_applied, RequestId} and {worker_turn, TaskId}) are idempotency latches, not history: they are TTL-pruned (inference_ledger_marker_ttl_ms) on a bounded cadence (inference_ledger_prune_interval_ms, a marker row claims the interval); sol_spend_ledger_markers_pruned_total counts the reclamation. Stale reservations are swept across EVERY principal/day older than inference_spend_reservation_ttl_ms (the pre-fix sweep matched only the caller’s current principal+day, so a request that crashed across UTC midnight held its pending estimate forever).

Shipped posture. The rebuild’s source is the durable event log, which only exists when the sync forwarder is installed (sync_enabled=true, the shipped default in both sys.config and sys.prod.config). While sync_enabled=false the forwarder is not installed, inference.complete never reaches the store, and the boot rebuild reads an empty source — the previous shipped shape that made this doc’s rebuild claim vacuous. sol_event_sync_forwarder_installed (absent = disabled, 0 = install failed) and the SolSyncForwarderPosture alert are the operator-visible truth. The shipped posture is asserted by ci/release_posture_lint.py and the release-artifact CI job; a config flip back to false is a loud failure, not a silent degradation.

Admission gate

All four streaming ingress paths — local OpenAI, remote OpenAI, local Anthropic, remote Anthropic (and the provider/registry variants that share the remote start functions) — call sol_spend_http:admission/5 (sol_spend_guard:reserve/2) before the pipeline starts, i.e. before any upstream request. The FIM lane and Lua child inference (sol_lua_inference:complete/2) use the same reservation funnel. A refusal is dialect-typed:

ConditionStatusCode
Daily token or USD cap crossed429 + Retry-After (seconds to UTC midnight)inference_budget_exceeded
Model has no rate while a USD cap is enabled and the policy is deny400model_unpriced
Guard infrastructure failure, USD cap enabled503 + inference_budget_unavailable—
Guard infrastructure failure, no USD capadmission continues (fail-open), logged—

Worker/fleet scope. The per-principal USD/token ADMISSION axes cover the Sol-side provider paths and Lua child inference — every HTTP ingress and inference.complete from Lua reserves/settles through the same funnel. Worker-plane admission remains TASK-CAP-ONLY in this window: no USD or token reservation is made at ZMQ/stdio dispatch. A worker turn that reports a usage rider IS settled into this same day ledger after the fact (sol_billing_worker:settle_result_frame/3 → inference.complete → sol_spend_guard:settle_worker_turn/3, ), so worker spend is visible and chargeback-true — it is just not ADMITTED against before the work runs. The central worker admission/sidecar decision is owned by ADR-0005 stage 1 and is NOT implemented here; do not read this ledger as a fleet-wide pre-dispatch USD cap. The worker plane’s enforced budget is its own per-principal daily task cap at the ZMQ dispatch funnel (sol_zmq_task_dispatcher:dispatch/4 → sol_spend_guard:admit_worker/1):

ConditionStatusCode
Daily worker-task cap crossed429 on HTTP chat/worker surfaces; typed {error, {inference_budget_exceeded, #{axis => worker_tasks, …}}} on the ZMQ dispatch/background-spawn planesinference_budget_exceeded

The cap is enforced at EVERY worker-send funnel — ZMQ dispatch, the stdio sol_worker:send_task/2 path used by chat REST/WS/worker REST, the one-shot sol_worker_bg background worker, and ZMQ background child spawn — so changing transport cannot bypass it. It counts Admitted placements (including tasks queued behind a busy worker); a refused placement (overload/queue-full/send failure) refunds the slot. sol_inference_budget_exceeded_total{axis="worker_tasks"} counts refusals; 0 disables the axis. A worker result that carries a provider usage rider lifts tokens_used/input_tokens/output_tokens onto task.completed and is settled idempotently per task id (the marker is TTL-pruned). A Luna client that omits usage settles nothing for that turn (skip, never a fabricated zero) — the documented residual until every client stamps usage.

Overshoot semantics. This is check-before-dispatch, not a distributed lock: the admission test includes the day’s settled total plus this request’s projected input estimate (bytes/4) and the effective max_tokens — a caller-supplied value, or the configured default_max_tokens (4096 fallback) when omitted, never 0 ( / PRV-08). Requests already in flight when a cap is reached are not interrupted, so the overshoot is bounded by the summed usage of concurrently admitted requests (each bounded by its max_tokens, plus input-estimate error). New requests are refused once the settled/pending total reaches the cap. reserve/2 is the strict form (parks the estimate in pending only); a successful reservation MUST be settle/2-ed (actual usage) or release/1-d (never ran). The HTTP ingress paths, the FIM lane and Lua child inference all use reserve/2 — concurrent children cannot overshoot the cap; the pre-fix Lua path used the check-only snapshot.

Configuration

KeyTypeDefaultMeaning
inference_daily_budget_usdnumber0Per-principal daily USD cap; 0 disables the USD axis.
inference_daily_token_budgetinteger0Per-principal daily token cap (input + output); 0 disables.
inference_worker_daily_task_budgetinteger0Per-principal daily worker-task cap at every worker-send funnel (ZMQ dispatch, stdio chat/WS/REST, one-shot background worker, ZMQ background child spawn); counts admitted placements, not tokens; refused placements refund; 0 disables.
inference_unknown_price_policyatom/binarydenyWhen a USD cap is enabled: deny refuses unpriced models (model_unpriced); allow admits them and records cost 0 (counted).
inference_daily_budget_overridesmap#{}Optional per-user overrides: #{<<"user-uuid">> => #{daily_budget_usd => N, daily_token_budget => N, daily_worker_task_budget => N}}. A missing axis falls back to the global value.
inference_ledger_rebuild_on_bootbooleantrueRebuild the current UTC day ledger from the durable inference.complete events when the ETS table is first created. Test VMs/ledger fixtures disable it and drive sol_spend_guard:rebuild_day/0 explicitly.
inference_ledger_rebuild_page_sizeinteger10000Durable-event page size for the boot rebuild/reconcile walk.
inference_ledger_rebuild_max_eventsinteger1000000Hard bound on a rebuild; exceeding it is a typed rebuild_truncated (never a silent short rebuild).
inference_ledger_marker_ttl_msinteger86400000Retention of the one-shot settlement markers before the bounded prune may delete them (must exceed the settlement retry horizon).
inference_ledger_prune_interval_msinteger60000Minimum cadence between marker-prune / cross-day reservation sweeps.
inference_spend_reservation_ttl_msinteger600000A parked reservation older than this is reclaimed on ANY principal/day (crash across midnight included).

The caps are per user_uuid (the authenticated principal; identity-loss flows use the server’s system/internal principal). Configure via the Sol app env (or SOL_CONFIG_FILE); the keys are also documented in configuration-reference.md.

Read surface

GET /api/v1/usage — self by default; an admin may pass ?user_uuid=<uuid>. Optional ?from=YYYY-MM-DD&to=YYYY-MM-DD (UTC, inclusive; to defaults to today, from is unbounded). Scope: inference:use. Response:

{
  "user_uuid": "…",
  "days": [
    {"day": "2026-10-17", "input_tokens": 1200, "output_tokens": 800,
     "total_tokens": 2000, "cost_usd": 0.0123,
     "pending_input_tokens": 0, "pending_output_tokens": 0,
     "pending_total_tokens": 0, "pending_cost_usd": 0.0,
     "remaining_tokens": 98000, "remaining_cost_usd": 4.9877,
     "models": [{"model": "gpt-4o", "input_tokens": 1200,
                  "output_tokens": 800, "cost_usd": 0.0123}]}
  ],
  "totals": {"input_tokens": 1200, "output_tokens": 800, "total_tokens": 2000,
             "cost_usd": 0.0123, "pending_input_tokens": 0,
             "pending_output_tokens": 0, "pending_total_tokens": 0,
             "pending_cost_usd": 0.0, "remaining_tokens": 98000,
             "remaining_cost_usd": 4.9877},
  "budget": {"daily_budget_usd": 0, "daily_token_budget": 0,
             "unknown_price_policy": "deny"}
}

Events and the workflow ledger

Every inference terminal — success, interrupted, cancel, caller DOWN, inference DOWN, parse error, crash — settles exactly once through sol_pipeline:settle_terminal/2 (the terminate/3 flush is the crash backstop; a settlement failure is CRITICAL and counted). The settlement:

  • uses the provider’s four billed counters (sol_anthropic_stream:usage_full_from_wire/1: input, output, cache creation, cache read);
  • treats the provider’s usage as AUTHORITATIVE for each side it reports; the delivered bytes/4 estimate is the floor only for an unreported side, so an omitted usage chunk never settles 0;
  • floors the INPUT side with the request estimate (the admission reservation’s estimate, or the same bytes/4 projection over the request messages for direct/FIM callers) when the provider reports no input tokens, and marks the settlement input_estimated=true ( / WF-10) — a usage-less provider no longer bills input 0;
  • never drops a partial usage report: an input-only or cache-only chunk is carried, rated and settled (the Anthropic egress emits the known sides with absent sides null);
  • rates input/output and the catalog’s cache_read_per_mtok / cache_write_per_mtok (cache tokens without a declared cache rate are marked unpriced + counted, never silently 0);
  • attributes the SERVING model (a lane id/alias resolves to the lane’s actual model row; catalog aliases resolve to the canonical id) and adds request_id, user_uuid, provider, provider_key_id, the four token counters, cost_usd, currency and outcome to the inference.complete event.

Wire usage vs settled usage

The client-facing stream carries the provider’s raw usage counters (absence marked, never invented): an OpenAI chunk’s prompt_tokens/completion_tokens, or an Anthropic message_delta usage object. The Anthropic message_start intentionally omits usage until the provider total is known — the previous shape fabricated input_tokens: 0.

The settlement is the authoritative billing figure and is a superset of the wire usage: a side the provider reported is used verbatim; an unreported input side is floored by the request estimate and marked input_estimated=true; an unreported output side is floored by the delivered bytes/4 estimate. Every difference between wire usage and settlement is therefore one of the named floors (input_estimate, delivered_bytes), never an invented side.

Rates come from the model catalog only. sol_model_metadata carries a legacy bundled table behind cost_legacy_metadata_price=true (default off); the price_parity lint pins every shared id to equal rates, and dated variants (-20250514) are the only prefix matches.

sol_billing (ETS, sol_billing_settlements) is the exactly-once latch keyed by request_id; the durable record is the event payload. A cancelled-with-delivered-tokens request therefore appears in the ledger and the event log, and a restart rebuilds the per-tenant day from those events (see Ledger above). The sync-event forwarder also lifts input_tokens/output_tokens/model onto task.completed while keeping the historical tokens_used sum.

The workflow cost_usd ledger remains passive by this decision: it accrues only when an event explicitly carries cost_usd, and it is not a workflow budget axis. Enforcement lives in sol_spend_guard, not in workflow state.

Metrics and alerts

FamilyTypeMeaning
sol_inference_spend_usd_total{model}counterSettled USD per model
sol_inference_tokens_input_total{model}counterSettled input tokens
sol_inference_tokens_output_total{model}counterSettled output tokens
sol_inference_spend_today_usdgaugeSettled USD today (UTC, all principals)
sol_inference_spend_today_tokensgaugeSettled tokens today
sol_inference_daily_budget_usd / …_token_budgetgaugeConfigured caps (0 = disabled)
sol_inference_budget_exceeded_total{axis}counterAdmission refusals by axis (tokens, usd, unpriced)
sol_inference_model_unpriced_total{model}counterUnpriced settlements
sol_billing_cache_write_tokens_totalcounterSettled Anthropic cache-write tokens
sol_billing_cache_read_tokens_totalcounterSettled Anthropic cache-read tokens
sol_billing_cache_unpriced_totalcounterCache tokens with no catalog cache rate
sol_billing_settlement_duplicate_totalcounterDuplicate terminal settlements (latch)
sol_billing_settlement_failed_totalcounterSettlement write failures
sol_billing_terminate_flush_failed_totalcounterCrash-terminate flush failures
sol_billing_ledger_rebuild_events_totalcounterDurable events replayed at boot rebuild
sol_billing_ledger_rebuild_truncated_totalcounterA rebuild stopped at the hard page bound (typed, never match)
sol_billing_ledger_rebuild_skipped_sync_disabled_totalcounterRebuild refused because sync_enabled=false (no durable source)
sol_billing_ledger_reconcile_mismatch_totalcounterLedger vs durable projection mismatches
sol_billing_ledger_unattributed_totalcounterBilled events with no user_uuid
sol_spend_ledger_markers_pruned_totalcounterOne-shot settlement markers reclaimed by the TTL prune
sol_billing_input_estimated_totalcounterSettlements whose input figure is the request estimate (usage-less/partial provider report)
sol_spend_ledger_lock_timeout_totalcounterReservation-lock timeouts (fail-closed)

Alerts: SolCostBurnRate now reads the real USD family; new SolInferenceBudgetExceeded and SolInferenceModelUnpriced rules page on the refusal/unpriced families. See observability.md.