Token usage: keep cache/reasoning split, count only recorded steps, cost only when positive; captures fixture, docs and notes

This commit is contained in:
2026-11-03 22:16:49 +00:00
parent aa948bdfe4
commit 3227d61caf
19 changed files with 447 additions and 61 deletions
+1 -1
View File
@@ -52,7 +52,7 @@ var notes = map[string]string{
"submit": "Confirm publication at the prompt, or use --yes for explicit automation; schedules activate on acceptance. Managed drafts provide the name and base-version guard. --force never bypasses validation.",
"run": "Runs in your current directory after action confirmation (--yes skips it). Select a pipeline and compose a multiline task with Ctrl+S. Stage tools are enabled automatically; no file list or typed RUN confirmation. Cancellation does not undo edits. --title sets an explicit run title; without it the title is derived from the prompt. --model PROVIDER/MODEL overrides the model for every stage of that run; --stage-model STAGE=PROVIDER/MODEL overrides one stage and is repeatable, with a repeated key last-wins. Precedence is per-stage > whole-run > the model pinned in the pipeline version; overrides apply to that run only and never change the pinned definition. An unknown stage key or a malformed provider/model is refused before the run starts, naming the valid stage keys. In JSON mode --wait polls until terminal; --wait-timeout bounds only the client wait after admission and is independent of per-request --timeout. A reached wait limit leaves the run active: inspect read-only with `inspect <run-id> --json`, or reattach with --wait reusing the original --request-key (never an automatic replay or cancel).",
"retry": "Resume a failed stage by default, restoring the completed prefix handoff; use --mode=restart to start at entry. --stage selects a recorded stage (use --visit for repeated stages). --input-file accepts a bounded JSON object, merged with replacement at the selected stage; '-' reads stdin. Original history and pinned identity are retained; --version selects an explicit published version of the same pipeline only. --wait-timeout leaves an active retry for later read-only inspection or reattachment with the original --request-key, rather than starting a duplicate retry.",
"runs": "Lists runs newest first; --json includes each run's size_bytes (bytes on disk: artifacts, session exports, server-created Pi session directories and an estimate of its database rows; 0 until first measured). `runs rm <id...>` permanently deletes finished runs (succeeded, failed, canceled, interrupted) with every database row and server-owned file for them, after confirmation (--yes for scripts). Active runs, runs an unfinished retry depends on and unknown ids are refused individually with a reason, and the command then exits 1. User workspaces are never touched. Database pages are reused by SQLite; `retention apply` additionally VACUUMs to shrink the file.",
"runs": "Lists runs newest first; --json includes each run's size_bytes (bytes on disk: artifacts, session exports, server-created Pi session directories and an estimate of its database rows; 0 until first measured) and, when any model stage recorded usage, its usage total (tokens_total, split and cache components, cost). `runs rm <id...>` permanently deletes finished runs (succeeded, failed, canceled, interrupted) with every database row and server-owned file for them, after confirmation (--yes for scripts). Active runs, runs an unfinished retry depends on and unknown ids are refused individually with a reason, and the command then exits 1. User workspaces are never touched. Database pages are reused by SQLite; `retention apply` additionally VACUUMs to shrink the file.",
"title": "Rename a run's operator-facing title after the fact without touching its input, steps or execution. The title is collapsed to a single bounded line and recorded as explicitly set. `pipelines runs` and `pipelines inspect` then show it.",
"wait": "Block until each named run reaches a terminal status - succeeded, failed, canceled or interrupted, and also through a run waiting on a person - then print one line per run with its id, status and outcome, its stage and how long it took, and exit 0 even for a run that finished unsuccessfully. Several ids wait together in one command. The exit is non-zero only for a client-side failure: an unknown run id, a connection that could not be established, or --timeout expiring while a run is still active; a timeout says so plainly, never cancels, retries or otherwise touches a run, and is never reported as its outcome. Read-only: it needs no workspace, is not refused by the workspace guard and writes nothing. --json prints the final run envelope instead of the line (one envelope for one id, an array for several).",
"decide": "Choose an option for a run waiting on a human stage. The run must be `waiting`; the option must be one of that stage's non-error edges. The stage is inferred from the run's current stage unless named. The choice and optional --feedback are recorded as the step's evidence (visible in inspect and the TUI) and the run resumes along the chosen edge. An unknown option is refused with the valid list; a repeated decision for an already-decided visit does not double-apply. Works across a server restart because the wait is persisted.",
+6 -4
View File
@@ -11,7 +11,8 @@ import (
// per bounded batch over the stored per-stage usage rows: no GetRun, step load
// or transcript parse per row. It uses the same column sums as the
// history-wide totals, so a listed run's total equals its detail's TotalUsage
// over the same rows. A run with no recorded usage keeps Usage nil, and a
// over the same rows; a usage row without its recorded step is never counted.
// A run with no recorded usage keeps Usage nil, and a
// database without the step_usage table lists runs without usage.
func loadRunUsage(ctx context.Context, tx runGraphQuerier, runs []protocol.RunSummary) error {
const batchSize = 100
@@ -23,8 +24,8 @@ func loadRunUsage(ctx context.Context, tx runGraphQuerier, runs []protocol.RunSu
byID[runs[i].ID] = &runs[i]
args = append(args, runs[i].ID)
}
rows, err := tx.QueryContext(ctx, `SELECT run_id,`+usageSumColumns+`
FROM step_usage WHERE run_id IN (`+strings.TrimSuffix(strings.Repeat("?,", len(args)), ",")+`) GROUP BY run_id`, args...)
rows, err := tx.QueryContext(ctx, `SELECT u.run_id,`+usageSumColumns+` `+usageFrom+`
WHERE u.run_id IN (`+strings.TrimSuffix(strings.Repeat("?,", len(args)), ",")+`) GROUP BY u.run_id`, args...)
if err != nil {
if strings.Contains(err.Error(), "no such table") {
return nil
@@ -34,7 +35,7 @@ FROM step_usage WHERE run_id IN (`+strings.TrimSuffix(strings.Repeat("?,", len(a
for rows.Next() {
var id int64
var u protocol.RunUsage
if err := rows.Scan(&id, &u.Stages, &u.TokensTotal, &u.TokensKnownStages, &u.TokensIn, &u.TokensOut, &u.CostUSD, &u.CostKnownStages, &u.SplitUnknownStages); err != nil {
if err := rows.Scan(&id, &u.Stages, &u.TokensTotal, &u.TokensKnownStages, &u.TokensIn, &u.TokensOut, &u.CostUSD, &u.CostKnownStages, &u.SplitUnknownStages, &u.TokensReasoning, &u.CacheRead, &u.CacheWrite, &u.CacheKnownStages); err != nil {
rows.Close()
return err
}
@@ -43,6 +44,7 @@ FROM step_usage WHERE run_id IN (`+strings.TrimSuffix(strings.Repeat("?,", len(a
}
u.CostUnknownStages = u.Stages - u.CostKnownStages
u.SplitKnown = u.TokensKnownStages > 0 && u.SplitUnknownStages == 0
u.CacheKnown = u.TokensKnownStages > 0 && u.CacheKnownStages == u.TokensKnownStages
byID[id].Usage = &u
}
err = rows.Err()
+85
View File
@@ -89,3 +89,88 @@ func TestListRunsCarriesRunUsageAggregate(t *testing.T) {
t.Fatalf("filler totals = %d", fillers)
}
}
// TestRunUsageCountsCacheAndOnlyRecordedSteps proves the cache/reasoning
// components are summed per run (equal in list, detail and stats), a run mixing
// a pre-cache row with a cache-reporting one keeps CacheKnown false, and a usage
// row whose step or run no longer exists (an old history wipe) is counted
// nowhere and left in place.
func TestRunUsageCountsCacheAndOnlyRecordedSteps(t *testing.T) {
ctx := context.Background()
store, err := Open(filepath.Join(t.TempDir(), "cache-usage.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
if _, err := store.Submit(ctx, "cache-usage", Template([]string{"one"}, true)); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
definition, _ := store.Get(ctx, items[0].ID, 1)
cached, _, err := store.CreateRun(ctx, definition, "cached", "/repo", false, nil, nil)
if err != nil {
t.Fatal(err)
}
finishUsageStep(t, store, cached, 1, "one", &protocol.StageUsage{TokensIn: 900_000, TokensOut: 150_000, TokensTotal: 22_400_000, TokensKnown: true, SplitKnown: true, TokensReasoning: 50_000, CacheRead: 21_250_000, CacheWrite: 50_000, CacheKnown: true})
mixed, _, err := store.CreateRun(ctx, definition, "mixed", "/repo", false, nil, nil)
if err != nil {
t.Fatal(err)
}
finishUsageStep(t, store, mixed, 1, "one", &protocol.StageUsage{TokensIn: 3, TokensOut: 4, TokensTotal: 7, TokensKnown: true, SplitKnown: true})
finishUsageStep(t, store, mixed, 2, "one", &protocol.StageUsage{TokensIn: 1, TokensOut: 1, TokensTotal: 10, TokensKnown: true, SplitKnown: true, CacheRead: 8, CacheKnown: true})
// Orphans: one for a run that no longer exists and one for a step the
// listed run never recorded. Foreign keys are off only on this connection.
conn, err := store.db.Conn(ctx)
if err != nil {
t.Fatal(err)
}
if _, err := conn.ExecContext(ctx, "PRAGMA foreign_keys=OFF"); err != nil {
t.Fatal(err)
}
orphan := `{"tokens_total":1000000000,"tokens_known":true,"cost_usd":15.67,"cost_known":true}`
for _, key := range [][2]int64{{9999, 1}, {cached, 99}} {
if _, err := conn.ExecContext(ctx, "INSERT INTO step_usage(run_id,sequence,usage_json) VALUES(?,?,?)", key[0], key[1], orphan); err != nil {
t.Fatal(err)
}
}
if _, err := conn.ExecContext(ctx, "PRAGMA foreign_keys=ON"); err != nil {
t.Fatal(err)
}
conn.Close()
runs, err := store.ListRuns(ctx)
if err != nil {
t.Fatal(err)
}
listed := map[int64]*protocol.RunUsage{}
for _, run := range runs {
listed[run.ID] = run.Usage
}
for _, id := range []int64{cached, mixed} {
detail, err := store.GetRun(ctx, id)
if err != nil {
t.Fatal(err)
}
if listed[id] == nil || detail.Usage == nil || *listed[id] != *detail.Usage {
t.Fatalf("run %d list usage %+v != detail usage %+v", id, listed[id], detail.Usage)
}
}
if got := listed[cached]; got.TokensTotal != 22_400_000 || got.CacheRead != 21_250_000 || got.CacheWrite != 50_000 || got.TokensReasoning != 50_000 || !got.CacheKnown || got.CacheKnownStages != 1 || got.Stages != 1 || got.CostKnownStages != 0 {
t.Fatalf("cached run usage counted an orphan or lost the cache split: %+v", got)
}
if got := listed[mixed]; got.CacheKnown || got.CacheKnownStages != 1 || got.CacheRead != 8 || got.TokensTotal != 17 {
t.Fatalf("mixed run presented a partial cache split as complete: %+v", got)
}
stats, err := store.UsageStats(ctx)
if err != nil || stats.Usage == nil {
t.Fatalf("stats = %+v err=%v", stats, err)
}
if got := stats.Usage; got.Stages != 3 || got.TokensTotal != 22_400_017 || got.CostUSD != 0 || got.CostKnownStages != 0 || got.CacheRead != 21_250_008 || got.CacheKnown {
t.Fatalf("history totals counted orphan rows: %+v", got)
}
var remaining int
if err := store.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM step_usage").Scan(&remaining); err != nil || remaining != 5 {
t.Fatalf("usage rows were deleted: %d %v", remaining, err)
}
}
+15 -4
View File
@@ -66,7 +66,8 @@ func (s *Store) UsageStats(ctx context.Context) (*protocol.UsageStats, error) {
// usageSumColumns sums step_usage rows into the RunUsage/UsageTotals shape:
// stages, reported total, token-reporting stages, split in/out, cost,
// cost-reporting stages and token stages without a split, in that order. It is
// cost-reporting stages, token stages without a split, then reasoning, cache
// read and cache write sums and the stages that recorded them, in that order. It is
// the one SQL definition of the sum, shared by the history-wide totals and the
// per-run list aggregate, and mirrors protocol.TotalUsage over the same rows.
const usageSumColumns = `COALESCE(COUNT(*),0),
@@ -76,7 +77,17 @@ COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.split_known') THEN json_extrac
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.split_known') THEN json_extract(usage_json,'$.tokens_out') ELSE 0 END),0),
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.cost_known') THEN json_extract(usage_json,'$.cost_usd') ELSE 0 END),0),
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.cost_known') THEN 1 ELSE 0 END),0),
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.tokens_known') AND NOT COALESCE(json_extract(usage_json,'$.split_known'),0) THEN 1 ELSE 0 END),0)`
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.tokens_known') AND NOT COALESCE(json_extract(usage_json,'$.split_known'),0) THEN 1 ELSE 0 END),0),
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.tokens_known') AND json_extract(usage_json,'$.cache_known') THEN COALESCE(json_extract(usage_json,'$.tokens_reasoning'),0) ELSE 0 END),0),
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.tokens_known') AND json_extract(usage_json,'$.cache_known') THEN COALESCE(json_extract(usage_json,'$.cache_read'),0) ELSE 0 END),0),
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.tokens_known') AND json_extract(usage_json,'$.cache_known') THEN COALESCE(json_extract(usage_json,'$.cache_write'),0) ELSE 0 END),0),
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.tokens_known') AND json_extract(usage_json,'$.cache_known') THEN 1 ELSE 0 END),0)`
// usageFrom is the step_usage rows that belong to a recorded step. A usage row
// whose step (or run) no longer exists, such as one left behind by an old
// history wipe, is never counted, and is not deleted here either. It is the
// same row set the run detail reads through its step loop.
const usageFrom = `FROM step_usage u JOIN run_steps s ON s.run_id=u.run_id AND s.sequence=u.sequence`
// usageTotals is the one extra aggregate query the history-wide usage totals add,
// over the same step_usage rows the per-run figures read. It sums reported totals
@@ -85,8 +96,7 @@ COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.tokens_known') AND NOT COALESC
// read-only database with no step_usage table yields no totals, not an error.
func usageTotals(ctx context.Context, tx *sql.Tx) (*protocol.UsageTotals, error) {
var totals protocol.UsageTotals
err := tx.QueryRowContext(ctx, `SELECT `+usageSumColumns+`
FROM step_usage`).Scan(&totals.Stages, &totals.TokensTotal, &totals.TokensKnownStages, &totals.TokensIn, &totals.TokensOut, &totals.CostUSD, &totals.CostKnownStages, &totals.SplitUnknownStages)
err := tx.QueryRowContext(ctx, `SELECT `+usageSumColumns+` `+usageFrom).Scan(&totals.Stages, &totals.TokensTotal, &totals.TokensKnownStages, &totals.TokensIn, &totals.TokensOut, &totals.CostUSD, &totals.CostKnownStages, &totals.SplitUnknownStages, &totals.TokensReasoning, &totals.CacheRead, &totals.CacheWrite, &totals.CacheKnownStages)
if err != nil {
if strings.Contains(err.Error(), "no such table") {
return nil, nil
@@ -98,5 +108,6 @@ FROM step_usage`).Scan(&totals.Stages, &totals.TokensTotal, &totals.TokensKnownS
}
totals.CostUnknownStages = totals.Stages - totals.CostKnownStages
totals.SplitKnown = totals.TokensKnownStages > 0 && totals.SplitUnknownStages == 0
totals.CacheKnown = totals.TokensKnownStages > 0 && totals.CacheKnownStages == totals.TokensKnownStages
return &totals, nil
}
+24
View File
@@ -325,6 +325,14 @@ type StageUsage struct {
SplitKnown bool `json:"split_known,omitempty"`
CostUSD float64 `json:"cost_usd,omitempty"`
CostKnown bool `json:"cost_known"`
// TokensReasoning, CacheRead and CacheWrite are the remaining components of
// a split report (TokensTotal = in + out + reasoning + cache read + cache
// write). They are recorded only when CacheKnown; a row stored before they
// were kept has CacheKnown=false, so its absent counts are unknown, not zero.
TokensReasoning int64 `json:"tokens_reasoning,omitempty"`
CacheRead int64 `json:"cache_read,omitempty"`
CacheWrite int64 `json:"cache_write,omitempty"`
CacheKnown bool `json:"cache_known,omitempty"`
}
// RunUsage is the totalled reported usage of a run's model stages. It is summed
@@ -344,6 +352,15 @@ type RunUsage struct {
SplitUnknownStages int `json:"split_unknown_stages,omitempty"`
CostKnownStages int `json:"cost_known_stages"`
CostUnknownStages int `json:"cost_unknown_stages,omitempty"`
// TokensReasoning, CacheRead and CacheWrite sum the stages that recorded the
// component split (CacheKnownStages). CacheKnown is true only when every
// token-reporting stage did, so fresh (total minus cache read) versus cached
// is never presented from a partial split.
TokensReasoning int64 `json:"tokens_reasoning,omitempty"`
CacheRead int64 `json:"cache_read,omitempty"`
CacheWrite int64 `json:"cache_write,omitempty"`
CacheKnown bool `json:"cache_known,omitempty"`
CacheKnownStages int `json:"cache_known_stages,omitempty"`
}
// TotalUsage sums the per-stage usage of a run's steps into one run total. It is
@@ -368,6 +385,12 @@ func TotalUsage(steps []RunStep) *RunUsage {
splitComplete = false
total.SplitUnknownStages++
}
if usage.CacheKnown {
total.CacheKnownStages++
total.TokensReasoning += usage.TokensReasoning
total.CacheRead += usage.CacheRead
total.CacheWrite += usage.CacheWrite
}
}
if usage.CostKnown {
total.CostKnownStages++
@@ -380,6 +403,7 @@ func TotalUsage(steps []RunStep) *RunUsage {
return nil
}
total.SplitKnown = total.TokensKnownStages > 0 && splitComplete
total.CacheKnown = total.TokensKnownStages > 0 && total.CacheKnownStages == total.TokensKnownStages
return total
}
+6
View File
@@ -37,6 +37,12 @@ type UsageTotals struct {
SplitUnknownStages int `json:"split_unknown_stages,omitempty"`
CostKnownStages int `json:"cost_known_stages"`
CostUnknownStages int `json:"cost_unknown_stages,omitempty"`
// The cache/reasoning components, as in RunUsage.
TokensReasoning int64 `json:"tokens_reasoning,omitempty"`
CacheRead int64 `json:"cache_read,omitempty"`
CacheWrite int64 `json:"cache_write,omitempty"`
CacheKnown bool `json:"cache_known,omitempty"`
CacheKnownStages int `json:"cache_known_stages,omitempty"`
}
type UsageStats struct {
+4
View File
@@ -1448,6 +1448,10 @@ func stageUsage(snapshot stage.BudgetSnapshot) *protocol.StageUsage {
usage.TokensTotal = snapshot.UsedTokens
if snapshot.SplitKnown {
usage.TokensIn, usage.TokensOut, usage.SplitKnown = snapshot.TokensInput, snapshot.TokensOutput, true
// The rest of the component split is kept too: for a caching harness
// most of the total is cache reads, which a client shows as cached
// rather than fresh tokens.
usage.TokensReasoning, usage.CacheRead, usage.CacheWrite, usage.CacheKnown = snapshot.TokensReasoning, snapshot.CacheRead, snapshot.CacheWrite, true
}
}
if snapshot.USDKnown {
+4 -2
View File
@@ -31,11 +31,13 @@ func TestStageUsageCarriesHonestUnknowns(t *testing.T) {
}{
{"no usage stays absent", stage.BudgetSnapshot{}, nil},
{"split and cost", stage.BudgetSnapshot{UsedTokens: 7, TokensKnown: true, SplitKnown: true, TokensInput: 3, TokensOutput: 4, UsedUSD: .5, USDKnown: true},
&protocol.StageUsage{TokensIn: 3, TokensOut: 4, TokensTotal: 7, TokensKnown: true, SplitKnown: true, CostUSD: .5, CostKnown: true}},
&protocol.StageUsage{TokensIn: 3, TokensOut: 4, TokensTotal: 7, TokensKnown: true, SplitKnown: true, CostUSD: .5, CostKnown: true, CacheKnown: true}},
{"cache and reasoning components carry through", stage.BudgetSnapshot{UsedTokens: 22_400_000, TokensKnown: true, SplitKnown: true, TokensInput: 900_000, TokensOutput: 150_000, TokensReasoning: 50_000, CacheRead: 21_250_000, CacheWrite: 50_000},
&protocol.StageUsage{TokensIn: 900_000, TokensOut: 150_000, TokensTotal: 22_400_000, TokensKnown: true, SplitKnown: true, TokensReasoning: 50_000, CacheRead: 21_250_000, CacheWrite: 50_000, CacheKnown: true}},
{"total only (Pi)", stage.BudgetSnapshot{UsedTokens: 17, TokensKnown: true},
&protocol.StageUsage{TokensTotal: 17, TokensKnown: true}},
{"no cost", stage.BudgetSnapshot{UsedTokens: 5, TokensKnown: true, SplitKnown: true, TokensInput: 5},
&protocol.StageUsage{TokensIn: 5, TokensTotal: 5, TokensKnown: true, SplitKnown: true}},
&protocol.StageUsage{TokensIn: 5, TokensTotal: 5, TokensKnown: true, SplitKnown: true, CacheKnown: true}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {