Record and expose per-run model usage (tokens, split, cost)

Carry the usage a model stage already measures for its budget
(stage.Budget.Snapshot()) onto the step as typed evidence and total it in
one pass, rather than a second harness read, a transcript parse or an
output-length estimate. A shared budget across stage revisits records only
the visit's increment, and a revisit that observes no new report records no
usage instead of a fabricated known zero.

- protocol: StageUsage/RunUsage/TotalUsage and UsageTotals.
- pipeline: step_usage table + migration, COALESCEd into the one step
  projection, FinishStep persistence, one json_extract history aggregate,
  retention removes the rows with their run.
- server: stageUsage maps the budget snapshot, stamping per-stage model and
  usage for every model stage (including failures).
- cli: inspect/stats human and JSON output.
- budget/pi: retain the reported in/out split, mark a total-only (Pi) report
  split-unknown, and keep an unreported cost unknown (never zero).

Evidence and docs updated in the packaged skill references and docs/cli.md;
the live database has no step_usage rows yet (all history predates this), so
per-run figures are reported as unavailable, not zero.
This commit is contained in:
2026-10-17 20:40:56 +01:00
parent 1ae56b7d14
commit 3f5c11b7bf
16 changed files with 919 additions and 14 deletions
@@ -59,7 +59,8 @@ parallel/distributed task engine or a guarantee that model reports are correct.
SQLite retains pipelines/immutable versions, runs, recorded stage visits,
inputs/outputs, status/errors, audit transcripts, session ownership/references,
retry links, schedules/state, notification receipts and file changes. Not everything
reported per-stage model usage (tokens/cost), retry links, schedules/state,
notification receipts and file changes. Not everything
is in that database: drafts/settings are client files; complete OpenCode sessions
and credentials use OpenCode storage; repository artifacts are files; ntfy has its
own storage. A pipeline ZIP is not a full backup of these components.
@@ -98,6 +99,13 @@ Use the authoritative `CLI_PREFIX` from the prompt:
without changing its input or steps. The stored prompt is unchanged, and
listing/renaming never calls a model.
- `CLI_PREFIX inspect RUN_ID --json`: selected run, visits and retained evidence.
Each model step carries the usage its harness reported (`usage.tokens_total`,
`tokens_in`/`tokens_out` only when `split_known`, `cost_usd` only when
`cost_known`, plus the model the step actually ran with); the run carries the
totalled `usage` over those stages, so a mixed-model run shows what each stage
cost. An unreported cost or split is shown as unavailable, never as zero and
never inferred from output length or transcript text; a historical or
pre-upgrade run simply omits `usage`.
Exact stage outputs are authoritative; a transcript over the 32 KiB retained
bound is a valid, credential-redacted preview envelope (with preserved stage
limits, failure/format diagnostics and the retained session pointer), not the
@@ -34,6 +34,40 @@ Accounting failures stop budget-limited stages. In-flight calls can overshoot;
these are **not provider-side hard caps or a guaranteed bill ceiling**. Reported
USD may validly be zero; do not fabricate prices/accounting from output length.
Per-run usage is recorded as typed step evidence from the usage the stage already
measured for its budget (no second harness read and no transcript parse), and
totalled for the run and over all history. A stage revisited within a run shares
one budget, so each step records only that visit's increment of it and the run
total is not the cumulative stage budget counted again; a revisit that reports
nothing new (a failure or timeout before any usage poll, or a Pi visit that never
reaches a usage stat) records no usage for that visit rather than a known zero.
`CLI_PREFIX inspect RUN_ID --json`
exposes each model step's `tokens_total`, `tokens_in`/`tokens_out` (only when
`split_known`), `cost_usd` (only when `cost_known`) and the model it ran with,
plus the totalled `usage`; `CLI_PREFIX stats --json` adds the history-wide totals,
which equal the sum of the per-run totals. A stage that reported no cost exposes
its tokens and marks the cost unavailable rather than showing zero; a harness that
reports only a total (Pi) exposes the total and marks the in/out split
unavailable rather than presenting the total as input tokens. An upgraded or
historical database gains an empty usage table with no backfill, so old runs omit
`usage` instead of showing zero. This is current source, not deployment evidence.
Dated current-source evidence (2026-10-17, this machine). A throwaway read-only
reader (`internal` store API) over a scratch copy of
`~/.local/share/pipelines/data/pipelines.db`, taken with
`sqlite3 "file:$HOME/.local/share/pipelines/data/pipelines.db?mode=ro" ".backup <scratch>"`
so the live DB is never mutated, opened 228 runs and found **no** `step_usage`
rows: every stored run predates this change, so per-run figures are unavailable
rather than zero. Run 314 (this item's own run) and run 239 (whose implementer
step ran `opencode-go/kimi-k2.7-code`, a stage model different from the pinned
`opencode-go/deepseek-v4.1-flash`) both report `usage=(none recorded)`, and
`stats` omits the history-wide totals. The recorded figures themselves are
covered by the passing current-source round trips — `internal/pipeline/usage_test.go`,
`internal/server/usage_test.go` (including `inspect --json` over a websocket) and
the pre-upgrade/read-bounded/stats-sum cases — not by a live run, because the
deployed server predates this change and was not restarted. No live model call,
deploy or rebuild produced this evidence.
A live V2 trial found `/generate` returned text while its retained session had no
messages and zero counters. Current source uses tracked `/prompt` → bounded
active-session polling → message readback for **budgeted V2 text-only calls, with