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)
}
})
}
}
@@ -17,6 +17,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/storepkg"
"github.com/samcharles93/archie-core/internal/domain/usage"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/logging"
@@ -125,6 +126,12 @@ func (c *Client) Transition(ctx context.Context, taskID int64, from, to, detail
return unmapError(err)
}
// RecordUsage appends one model call's usage record.
func (c *Client) RecordUsage(ctx context.Context, r usage.Record) error {
_, err := c.client.RecordUsage(ctx, &pb.RecordUsageRequest{Record: usageProto(r)})
return unmapError(err)
}
// StartStep and FinishStep record step executions and return the persisted
// event.
func (c *Client) StartStep(ctx context.Context, s task.StepStart) (int64, events.Event, error) {
@@ -25,6 +25,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/storepkg"
"github.com/samcharles93/archie-core/internal/domain/usage"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/logging"
"github.com/samcharles93/archie-core/internal/taskstate"
@@ -104,6 +105,9 @@ type Deps struct {
// workflow engine's run credential calls. Optional: nil answers both RPCs
// with codes.Unavailable.
Steps storecontract.StepRecorder
// Usage appends model usage records. Optional: nil answers RecordUsage
// with codes.Unavailable.
Usage usage.Recorder
// Canceller is the one cancel path:
// an operator action's guarded write over the execution and its steps.
// Optional: nil answers the RPC with codes.Unavailable.
@@ -249,6 +253,20 @@ func (s *server) StartStep(ctx context.Context, r *pb.StartStepRequest) (*pb.Sta
return &pb.StartStepResponse{StepId: stepID, Event: eventProto(event)}, nil
}
// RecordUsage appends one model call's usage record.
func (s *server) RecordUsage(ctx context.Context, r *pb.RecordUsageRequest) (*pb.RecordUsageResponse, error) {
if s.deps.Usage == nil {
return nil, status.Error(codes.Unavailable, "usage recorder unavailable")
}
if r.Record == nil {
return nil, status.Error(codes.InvalidArgument, "record is required")
}
if err := s.deps.Usage.RecordUsage(ctx, usageValue(r.Record)); err != nil {
return nil, s.logErr("RecordUsage", err)
}
return &pb.RecordUsageResponse{}, nil
}
// CancelExecution is the one cancel path:
// the store records the cancellation and returns the steps it cancelled; the
// caller delivers it by cancelling the run's in-memory context afterwards.
@@ -128,6 +128,13 @@ var taskScopedTargets = map[string]func(any) int64{
}
return r.ExecutionId
},
pb.StateStoreService_RecordUsage_FullMethodName: func(req any) int64 {
r, ok := req.(*pb.RecordUsageRequest)
if !ok || r.Record == nil {
return 0
}
return r.Record.TaskId
},
pb.StateStoreService_FinishStep_FullMethodName: func(req any) int64 {
r, ok := req.(*pb.FinishStepRequest)
if !ok {
@@ -0,0 +1,29 @@
package staterpc
import (
"testing"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
)
// A run credential records usage only against its own task, so one tenant's
// task cannot bill another's.
func TestRecordUsageAuthority(t *testing.T) {
for _, tt := range []struct {
name string
record *pb.UsageRecord
allowed bool
}{
{"own task", &pb.UsageRecord{TaskId: 7}, true},
{"another task", &pb.UsageRecord{TaskId: 8}, false},
{"no task", &pb.UsageRecord{OrgId: "org-sys"}, false},
{"no record", nil, false},
} {
t.Run(tt.name, func(t *testing.T) {
req := &pb.RecordUsageRequest{Record: tt.record}
if got := authorizesTaskScopedCall(pb.StateStoreService_RecordUsage_FullMethodName, req, 7); got != tt.allowed {
t.Fatalf("authorized = %v, want %v", got, tt.allowed)
}
})
}
}
@@ -0,0 +1,26 @@
package staterpc
import (
"google.golang.org/protobuf/types/known/timestamppb"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
"github.com/samcharles93/archie-core/internal/domain/usage"
)
func usageProto(r usage.Record) *pb.UsageRecord {
return &pb.UsageRecord{
OrgId: r.Org, Source: string(r.Source), TaskId: r.TaskID, 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: timestamppb.New(r.At),
}
}
func usageValue(r *pb.UsageRecord) usage.Record {
return usage.Record{
Org: r.GetOrgId(), Source: usage.Source(r.GetSource()), TaskID: r.GetTaskId(), Attempt: int(r.GetAttempt()),
Workflow: r.GetWorkflow(), Step: r.GetStep(), Alias: r.GetAlias(), Provider: r.GetProvider(), Model: r.GetModel(),
InputTokens: r.GetInputTokens(), OutputTokens: r.GetOutputTokens(), CachedTokens: r.GetCachedTokens(),
At: r.GetAt().AsTime(),
}
}