feat(statestore): record a usage row for every model call

Task agent runs and MCP sampling record against their task (billed to the
task's org); gateway chat turns, titles, sampling and curators record
against the system org. Rows carry source, workflow, step, alias,
provider/model and tokens for later chargeback.
This commit is contained in:
sam committed 2026-10-10 18:32:43 +11:00
1 parent 12b9a57404
commit e4ea2eaabc
31 files changed
+1068 -322

No files matched your search

@@ -0,0 +1,26 @@
-- One row per model call: who made it, for what, on which model, and the
-- tokens it used. Chargeback and usage reports aggregate these rows.
-- +goose Up
CREATE TABLE model_usage (
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
org_id text NOT NULL,
source text NOT NULL CHECK (source IN ('task', 'chat', 'curator')),
task_id bigint NOT NULL DEFAULT 0,
attempt bigint NOT NULL DEFAULT 0,
workflow text NOT NULL DEFAULT '',
step text NOT NULL DEFAULT '',
alias text NOT NULL DEFAULT '',
provider text NOT NULL,
model text NOT NULL,
input_tokens bigint NOT NULL DEFAULT 0,
output_tokens bigint NOT NULL DEFAULT 0,
cached_tokens bigint NOT NULL DEFAULT 0,
at timestamptz NOT NULL
);
CREATE INDEX idx_model_usage_org_at ON model_usage (org_id, at);
-- +goose Down
DROP TABLE model_usage;
@@ -260,6 +260,23 @@ type Message struct {
Media []byte
}
type ModelUsage struct {
ID int64
OrgID string
Source string
TaskID int64
Attempt int64
Workflow string
Step string
Alias string
Provider string
Model string
InputTokens int64
OutputTokens int64
CachedTokens int64
At time.Time
}
type Org struct {
ID string
Name string
@@ -0,0 +1,58 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: usage.sql
package postgresdb
import (
"context"
"time"
)
const insertModelUsage = `-- name: InsertModelUsage :exec
INSERT INTO model_usage (
org_id, source, task_id, attempt, workflow, step, alias, provider, model,
input_tokens, output_tokens, cached_tokens, at
) VALUES (
COALESCE((SELECT t.org_id FROM tasks t WHERE t.id = $1 AND $1 <> 0), $2::text),
$3, $1, $4, $5, $6, $7,
$8, $9, $10, $11, $12, $13
)
`
type InsertModelUsageParams struct {
TaskID int64
OrgID string
Source string
Attempt int64
Workflow string
Step string
Alias string
Provider string
Model string
InputTokens int64
OutputTokens int64
CachedTokens int64
At time.Time
}
// A task's usage belongs to the task's org, whatever the caller says.
func (q *Queries) InsertModelUsage(ctx context.Context, arg InsertModelUsageParams) error {
_, err := q.db.Exec(ctx, insertModelUsage,
arg.TaskID,
arg.OrgID,
arg.Source,
arg.Attempt,
arg.Workflow,
arg.Step,
arg.Alias,
arg.Provider,
arg.Model,
arg.InputTokens,
arg.OutputTokens,
arg.CachedTokens,
arg.At,
)
return err
}
@@ -0,0 +1,10 @@
-- name: InsertModelUsage :exec
-- A task's usage belongs to the task's org, whatever the caller says.
INSERT INTO model_usage (
org_id, source, task_id, attempt, workflow, step, alias, provider, model,
input_tokens, output_tokens, cached_tokens, at
) VALUES (
COALESCE((SELECT t.org_id FROM tasks t WHERE t.id = sqlc.arg(task_id) AND sqlc.arg(task_id) <> 0), sqlc.arg(org_id)::text),
sqlc.arg(source), sqlc.arg(task_id), sqlc.arg(attempt), sqlc.arg(workflow), sqlc.arg(step), sqlc.arg(alias),
sqlc.arg(provider), sqlc.arg(model), sqlc.arg(input_tokens), sqlc.arg(output_tokens), sqlc.arg(cached_tokens), sqlc.arg(at)
);
+17
View File
@@ -0,0 +1,17 @@
package postgres
import (
"context"
"github.com/samcharles93/archie-core/internal/domain/usage"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
// RecordUsage appends one model call's usage record.
func (s *Store) RecordUsage(ctx context.Context, r usage.Record) error {
return postgresdb.New(s.pool).InsertModelUsage(ctx, postgresdb.InsertModelUsageParams{
TaskID: r.TaskID, OrgID: r.Org, Source: string(r.Source), Attempt: int64(r.Attempt),
Workflow: r.Workflow, Step: r.Step, Alias: r.Alias, Provider: r.Provider, Model: r.Model,
InputTokens: r.InputTokens, OutputTokens: r.OutputTokens, CachedTokens: r.CachedTokens, At: r.At,
})
}
@@ -0,0 +1,45 @@
package postgres_test
import (
"testing"
"time"
"github.com/samcharles93/archie-core/internal/domain/usage"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
)
// A task's usage is billed to the task's org whatever org the caller names;
// usage with no task keeps the caller's org.
func TestRecordUsageBillsTheTaskOrg(t *testing.T) {
ctx := t.Context()
db := pgstore.Open(t)
var taskID int64
if err := db.Pool.QueryRow(ctx,
`INSERT INTO tasks (owner, repo, issue_number, identity, org_id, workspace_id) VALUES ('o', 'r', 1, 'sam', 'acme', 'default') RETURNING id`,
).Scan(&taskID); err != nil {
t.Fatal(err)
}
for _, tt := range []struct {
name string
record usage.Record
want string
}{
{"a task bills its own org", usage.Record{Org: "other", Source: usage.SourceTask, TaskID: taskID}, "acme"},
{"chat keeps the caller's org", usage.Record{Org: "org-sys", Source: usage.SourceChat}, "org-sys"},
} {
t.Run(tt.name, func(t *testing.T) {
tt.record.Step, tt.record.At = tt.name, time.Now()
tt.record = tt.record.WithRef("openai/gpt-6-luna")
if err := db.RecordUsage(ctx, tt.record); err != nil {
t.Fatal(err)
}
var got string
if err := db.Pool.QueryRow(ctx, "SELECT org_id FROM model_usage WHERE step = $1", tt.name).Scan(&got); err != nil {
t.Fatal(err)
}
if got != tt.want {
t.Fatalf("org = %q, want %q", got, tt.want)
}
})
}
}