# 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

| Record | Lives in | Answers | Written by |
| --- | --- | --- | --- |
| Message columns | Assistant message history | What did this message cost (per-message pill) | `persist_assistant_message` in `runtime/conversation/turn_runtime/persistence.py` |
| Last request | Session meta `_usage` | Real 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](https://fzkuji.github.io/OpenProgram/docs/reference/design/context/compaction.html#measuring)) | `UsageTracker.record_turn` in `runtime/context/token_accounting/usage.py` |
| Ledger | `~/.openprogram/usage.db`, profile-aware | Global spend across sessions, models, sources and time | `record_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

| Layer | Role |
| --- | --- |
| Consumers | Web 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` `UsageLedger` | SQLite, 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](https://fzkuji.github.io/OpenProgram/docs/reference/design/ui/chat/activity-panel.html#task-rows) |
| `recorder.py` | Model, final `AssistantMessage` and context become one `UsageEvent` |
| `context.py` | Contextvar plus `usage_scope()`, `current_usage_context()`, `snapshot()`, `apply_snapshot()` |
| `event.py` | The frozen `UsageEvent` schema |
| `reservation.py`, `request.py`, `goal_port.py` | Conservative 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`.

| Rule | Why |
| --- | --- |
| Here, not in `api_registry` | Each 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 `recorded` | `agent_loop` returns on the done event, suspending the generator at its `yield`; code after the loop never runs |
| Streaming is not blocked | Fires once, on done or error |
| A reply that failed is recorded too | An 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-effort | A metering failure logs and never interrupts the response. Callers that settle a budget or Goal receipt use strict event construction. |
| No new pricing | `calculate_cost` in `providers/catalog/models.py` |

## UsageEvent

One frozen row per call. `SCHEMA_VERSION` 2.

| Group | Fields |
| --- | --- |
| Identity | `event_id` (uuid; `INSERT OR IGNORE` makes retries idempotent), `ts` |
| Attribution | `session_id`, `parent_session_id`, `agent_id`, `call_kind`, `call_label`, `origin_pid` |
| Budget | `job_id`, `budget_scope_id`, `reservation_id`, `request_id`, `goal_id`, `goal_revision`, `goal_session_id`, `execution_id` |
| Model | `provider`, `api`, `model_id` |
| Tokens | `input_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 `SUM` | `cost_input`, `cost_output`, `cost_cache_read`, `cost_cache_write`, `cost_total`, `cost_source` (`model_catalog`, `configured`, `provider_reported`, `unknown`) |
| Latency | `first_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 cache | `prefix_hash`, `break_at`, `break_cause`, `expected`: where the request's cached prefix broke and why ([Prompt cache prefix](https://fzkuji.github.io/OpenProgram/docs/reference/design/context/cache-prefix.html)) |
| Provenance | `token_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

| Approach | For | Against |
| --- | --- | --- |
| Parameter `options.call_kind` | Explicit | Threads through every signature; a new caller touches the lower layer |
| `SimpleStreamOptions.metadata` | Field exists | Easy to miss in deep calls |
| **Contextvar (used)** | One `with usage_scope(...)`; asyncio Tasks inherit | Threads and spawned processes need an explicit snapshot |

| Boundary | Inherits scope? | Handling |
| --- | --- | --- |
| `create_task` | Yes | `copy_context()` by default |
| `run_in_executor`, raw `Thread` | No | `apply_snapshot` at the entry |
| Spawned process | No | `snapshot()` to `usage_ctx_snapshot`, `apply_snapshot()` in the child |

## Storage

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

| Table | Holds |
| --- | --- |
| `usage_events` | Append-only events. Indexes: time, model and time, session, kind and time, job, Goal, reservation, budget scope; unique on `request_id` |
| `usage_requests` | Goal request receipts: `prepared`, `started`, `settled`, `released` |
| `route_events` | Failover switches. Not usage; no aggregate reads it |
| `probe_events` | Requests sent on OpenProgram's own behalf: [the probe log](https://fzkuji.github.io/OpenProgram/docs/reference/design/providers/auth/credential-validation-unification.html). Not usage |
| `prefix_baselines` | The 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**

| Extension | State |
| --- | --- |
| Post-record hooks for budgets and alerts | Built: `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 user | Designed: `user_id` on the event, injected through `usage_scope` |
| Export | Designed: `export(format, filters)` on the backend |
