Runs list carries per-run token usage; app shows tokens beside size, Most tokens sort, Summary and stage tokens
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// loadRunUsage fills each listed run's Usage with one grouped aggregate query
|
||||
// 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
|
||||
// database without the step_usage table lists runs without usage.
|
||||
func loadRunUsage(ctx context.Context, tx runGraphQuerier, runs []protocol.RunSummary) error {
|
||||
const batchSize = 100
|
||||
for start := 0; start < len(runs); start += batchSize {
|
||||
end := min(start+batchSize, len(runs))
|
||||
args := make([]any, 0, end-start)
|
||||
byID := make(map[int64]*protocol.RunSummary, end-start)
|
||||
for i := start; i < end; i++ {
|
||||
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...)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "no such table") {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
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 {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
if u.Stages == 0 || byID[id] == nil {
|
||||
continue
|
||||
}
|
||||
u.CostUnknownStages = u.Stages - u.CostKnownStages
|
||||
u.SplitKnown = u.TokensKnownStages > 0 && u.SplitUnknownStages == 0
|
||||
byID[id].Usage = &u
|
||||
}
|
||||
err = rows.Err()
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// TestListRunsCarriesRunUsageAggregate proves the run list carries each run's
|
||||
// usage total from the grouped aggregate, equal to the detail's TotalUsage over
|
||||
// the same rows, marks a partial total by its stage counts, leaves a run with
|
||||
// no recorded usage absent rather than zero, and stays correct across list
|
||||
// batches.
|
||||
func TestListRunsCarriesRunUsageAggregate(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store, err := Open(filepath.Join(t.TempDir(), "list-usage.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
if _, err := store.Submit(ctx, "list-usage", Template([]string{"one"}, true)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ := store.List(ctx)
|
||||
definition, _ := store.Get(ctx, items[0].ID, 1)
|
||||
create := func(key string) int64 {
|
||||
id, _, err := store.CreateRun(ctx, definition, key, "/repo", false, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
full := create("full")
|
||||
finishUsageStep(t, store, full, 1, "one", &protocol.StageUsage{TokensIn: 20_000_000, TokensOut: 2_400_000, TokensTotal: 22_400_000, TokensKnown: true, SplitKnown: true, CostUSD: 1.5, CostKnown: true})
|
||||
finishUsageStep(t, store, full, 2, "one", &protocol.StageUsage{TokensIn: 10, TokensOut: 5, TokensTotal: 15, TokensKnown: true, SplitKnown: true, CostUSD: .25, CostKnown: true})
|
||||
partial := create("partial")
|
||||
finishUsageStep(t, store, partial, 1, "one", &protocol.StageUsage{TokensTotal: 9, TokensKnown: true})
|
||||
finishUsageStep(t, store, partial, 2, "one", &protocol.StageUsage{CostUSD: .1, CostKnown: true})
|
||||
none := create("none")
|
||||
finishUsageStep(t, store, none, 1, "one", nil)
|
||||
// Enough further runs to push the first ones past one list batch.
|
||||
const fillerRuns = 105
|
||||
for i := range fillerRuns {
|
||||
filler := create(fmt.Sprintf("filler-%d", i))
|
||||
finishUsageStep(t, store, filler, 1, "one", &protocol.StageUsage{TokensTotal: int64(i + 1), TokensKnown: true})
|
||||
}
|
||||
|
||||
runs, err := store.ListRuns(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
byID := map[int64]protocol.RunSummary{}
|
||||
for _, run := range runs {
|
||||
byID[run.ID] = run
|
||||
}
|
||||
for _, id := range []int64{full, partial} {
|
||||
detail, err := store.GetRun(ctx, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
listed := byID[id].Usage
|
||||
if listed == nil || detail.Usage == nil || *listed != *detail.Usage {
|
||||
t.Fatalf("run %d list usage %+v != detail usage %+v", id, listed, detail.Usage)
|
||||
}
|
||||
}
|
||||
if got := byID[full].Usage; got.TokensTotal != 22_400_015 || got.TokensIn != 20_000_010 || got.TokensOut != 2_400_005 || !got.SplitKnown || got.CostUSD != 1.75 || got.TokensKnownStages != 2 || got.Stages != 2 {
|
||||
t.Fatalf("full run usage = %+v", got)
|
||||
}
|
||||
if got := byID[partial].Usage; got.TokensTotal != 9 || got.TokensKnownStages != 1 || got.Stages != 2 || got.SplitKnown || got.CostKnownStages != 1 || got.CostUnknownStages != 1 {
|
||||
t.Fatalf("partial run usage = %+v", got)
|
||||
}
|
||||
if got := byID[none].Usage; got != nil {
|
||||
t.Fatalf("run without usage listed a total: %+v", got)
|
||||
}
|
||||
var fillers int64
|
||||
for _, run := range runs {
|
||||
if run.ID == full || run.ID == partial || run.ID == none {
|
||||
continue
|
||||
}
|
||||
if run.Usage == nil {
|
||||
t.Fatalf("filler run %d lost its usage", run.ID)
|
||||
}
|
||||
fillers += run.Usage.TokensTotal
|
||||
}
|
||||
if fillers != fillerRuns*(fillerRuns+1)/2 {
|
||||
t.Fatalf("filler totals = %d", fillers)
|
||||
}
|
||||
}
|
||||
@@ -76,6 +76,9 @@ func (s *Store) ListRuns(ctx context.Context) ([]protocol.RunSummary, error) {
|
||||
if err := loadRunGraphEvidence(ctx, tx, items); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := loadRunUsage(ctx, tx, items); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -64,6 +64,20 @@ func (s *Store) UsageStats(ctx context.Context) (*protocol.UsageStats, error) {
|
||||
return stats, tx.Commit()
|
||||
}
|
||||
|
||||
// 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
|
||||
// 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),
|
||||
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.tokens_known') THEN json_extract(usage_json,'$.tokens_total') ELSE 0 END),0),
|
||||
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.tokens_known') THEN 1 ELSE 0 END),0),
|
||||
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.split_known') THEN json_extract(usage_json,'$.tokens_in') ELSE 0 END),0),
|
||||
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)`
|
||||
|
||||
// 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
|
||||
// with json_extract, counts token/cost-reporting stages and leaves a stage that
|
||||
@@ -71,15 +85,7 @@ func (s *Store) UsageStats(ctx context.Context) (*protocol.UsageStats, error) {
|
||||
// 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
|
||||
COALESCE(COUNT(*),0),
|
||||
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.tokens_known') THEN json_extract(usage_json,'$.tokens_total') ELSE 0 END),0),
|
||||
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.tokens_known') THEN 1 ELSE 0 END),0),
|
||||
COALESCE(SUM(CASE WHEN json_extract(usage_json,'$.split_known') THEN json_extract(usage_json,'$.tokens_in') ELSE 0 END),0),
|
||||
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)
|
||||
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)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "no such table") {
|
||||
|
||||
@@ -197,6 +197,14 @@ type RunSummary struct {
|
||||
// session directories and an estimate of its database rows. It is cached
|
||||
// server-side; 0 means not measured yet (a background backfill fills it).
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
// Usage is the totalled reported usage of the run's model stages. The run
|
||||
// list sums it with one SQL aggregate per batch over the stored per-stage
|
||||
// usage rows; the run detail sums the same rows in one pass over its loaded
|
||||
// steps (TotalUsage). It is absent for a run with no model usage recorded
|
||||
// (including historical runs and servers predating the list aggregate), so
|
||||
// a client shows nothing rather than zero. A total is partial when
|
||||
// TokensKnownStages < Stages.
|
||||
Usage *RunUsage `json:"usage,omitempty"`
|
||||
}
|
||||
|
||||
// RunGraphVisit contains only routing and lifecycle facts, never private step
|
||||
@@ -433,10 +441,6 @@ type RunDetail struct {
|
||||
Input map[string]any `json:"input"`
|
||||
Output map[string]any `json:"output"`
|
||||
Steps []RunStep `json:"steps"`
|
||||
// Usage is the totalled reported usage of the run's model stages, summed in
|
||||
// one pass over Steps. It is absent for a run with no model usage recorded
|
||||
// (including historical runs).
|
||||
Usage *RunUsage `json:"usage,omitempty"`
|
||||
// TitleSource is "model" when Title came from the shared summariser or
|
||||
// "fallback" when it was derived from the prompt; TitleModel names the model
|
||||
// that produced a model title. They are retained so a diagnosis can tell the
|
||||
|
||||
Reference in New Issue
Block a user