OpenProgram Docs

Usage metering

Every LLM call records tokens, model and cost with its source, aggregated by model, source, session and time. The module is openprogram/models/usage/.

Three records, three questions

RecordLives inAnswersWritten by
Message columnsAssistant message historyWhat did this message cost (per-message pill)persist_assistant_message in runtime/conversation/turn_runtime/persistence.py
Last requestSession meta _usageReal input tokens of the last turn, per branch, and cache hit rate. Whether to compact reads the request size of token_accounting/measure.py instead (How large a request is)UsageTracker.record_turn in runtime/context/token_accounting/usage.py
Ledger~/.openprogram/usage.db, profile-awareGlobal spend across sessions, models, sources and timerecord_message in models/usage/recorder.py

They have different consumers and lifecycles, and do not read or write each other. Session meta is a cumulative git-backed snapshot: it cannot aggregate across sessions, query by time or index per model, and a subprocess writing it would contend for the git lock.

Layers

LayerRole
ConsumersWeb panel through /api/usage/summary, /api/usage/trend, /api/usage/tuning (interfaces/server/routes/settings/usage.py). The panel draws a trend line, by-source bars, a per-model table and a cost card. No usage CLI command exists.
ledger.py UsageLedgerSQLite, append and query(since, until, group_by, filters); day and hour are group_by buckets; session_costs(session_id) lists a conversation's priced calls for the cost of each scheduled run
recorder.pyModel, final AssistantMessage and context become one UsageEvent
context.pyContextvar plus usage_scope(), current_usage_context(), snapshot(), apply_snapshot()
event.pyThe frozen UsageEvent schema
reservation.py, request.py, goal_port.pyConservative request bounds, Goal request receipts, the port to the Goal tool

Under models/, which sits below Programs and the runtime, so everything can depend on it without a cycle.

Collection point

models/providers/streaming/stream.py wraps stream() and stream_simple(); complete_simple() runs through them. Going through it and being accounted for mean the same thing. Memory, compaction summaries, mixture_of_agents and Agent-method subprocesses use the same point with their own usage_scope.

RuleWhy
Here, not in api_registryEach provider implements its own stream_simple behind a Protocol. Collecting there means changing the Protocol or scattering wrappers. stream.py already holds the model with pricing and the final usage.
At the terminal event, before the yield, guarded by recordedagent_loop returns on the done event, suspending the generator at its yield; code after the loop never runs
Streaming is not blockedFires once, on done or error
A reply that failed is recorded tooAn attempt that reached the provider and ended without a final message may be billed. record_failed_request records the tokens its last partial reported, or one event with tokens_known false and cost unknown. The sign of reaching it is streamed content, reported tokens, or a reply silent for the idle bound; the adapter's start event is not. A refusal or a connection that failed before any content is not recorded.
Best-effortA metering failure logs and never interrupts the response. Callers that settle a budget or Goal receipt use strict event construction.
No new pricingcalculate_cost in providers/catalog/models.py

UsageEvent

One frozen row per call. SCHEMA_VERSION 2.

GroupFields
Identityevent_id (uuid; INSERT OR IGNORE makes retries idempotent), ts
Attributionsession_id, parent_session_id, agent_id, call_kind, call_label, origin_pid
Budgetjob_id, budget_scope_id, reservation_id, request_id, goal_id, goal_revision, goal_session_id, execution_id
Modelprovider, api, model_id
Tokensinput_tokens, output_tokens, cache_read_tokens, cache_write_tokens, total_tokens (never less than the four parts summed; aggregates sum the parts, so cached tokens always count); tokens_known separates an absent report from zero
Cost, USD, flat for SUMcost_input, cost_output, cost_cache_read, cost_cache_write, cost_total, cost_source (model_catalog, configured, provider_reported, unknown)
Latencyfirst_token_ms to the first content of any kind; first_text_ms to the first visible text. Measured in streaming/first_token.py, carried on Usage, None if absent. After magpie's TTFT (yetone/magpie, MIT).
Prompt cacheprefix_hash, break_at, break_cause, expected: where the request's cached prefix broke and why (Prompt cache prefix)
Provenancetoken_source (provider_usage, anthropic_count_api, estimate), so the panel can mark estimates; schema_version

call_kind is a string so a new caller needs no change here: chat, exec, compaction, summarize, memory, subagent, tool, title, prediction, permission, direct (the default).

Passing the source label

ApproachForAgainst
Parameter options.call_kindExplicitThreads through every signature; a new caller touches the lower layer
SimpleStreamOptions.metadataField existsEasy to miss in deep calls
Contextvar (used)One with usage_scope(...); asyncio Tasks inheritThreads and spawned processes need an explicit snapshot
BoundaryInherits scope?Handling
create_taskYescopy_context() by default
run_in_executor, raw ThreadNoapply_snapshot at the entry
Spawned processNosnapshot() to usage_ctx_snapshot, apply_snapshot() in the child

Storage

SQLite from the standard library, WAL mode for concurrent appends from subprocesses.

TableHolds
usage_eventsAppend-only events. Indexes: time, model and time, session, kind and time, job, Goal, reservation, budget scope; unique on request_id
usage_requestsGoal request receipts: prepared, started, settled, released
route_eventsFailover switches. Not usage; no aggregate reads it
probe_eventsRequests sent on OpenProgram's own behalf: the probe log. Not usage
prefix_baselinesThe last answered request on each prompt-cache lane, which the next one is compared with. Not usage

A step changing both an event and a reservation commits the event first, so a stop in between leaves exposure held and an event to recognise it by, never spend without a record.

Agent-method subprocesses
  • The subprocess writes the shared database directly, stamped with origin_pid. The ledger is the source of truth; the parent does not count again and the result pickle carries no usage.
  • process_runner.py uses spawn: the parent has loaded PyTorch, libomp and Cocoa, which SIGSEGV after fork. Spawn does not copy contextvars, so run_agentic_in_subprocess passes snapshot() as usage_ctx_snapshot and the child applies it after os.setpgrp().
  • _connect() reopens on a changed os.getpid(), because a handle is unusable across processes.
  • On SIGKILL, appended events stay and are true. A call the kill cut off is not recorded: nothing is fabricated.
Implementation status
ExtensionState
Post-record hooks for budgets and alertsBuilt: register_usage_hook, non-blocking, a throwing hook is contained
Other backends (JSONL, remote OTLP)Designed: replace the append and query interface; event schema unchanged
Per userDesigned: user_id on the event, injected through usage_scope
ExportDesigned: export(format, filters) on the backend
Last updated · 2026-11-25