runner: metered ledger, slot, price tables and recovery
internal/runner/metered is the soft budget of connectors spec 2.3: TensorX's price table (2026-11-12) in integer micro-units, usage normalised into billable components (unpriced model or component, or an incomplete row, is unknown), the budget ledger keyed by the usage row's key, one durable slot per connection claimed in the admission's transaction, release only after the termination proof with the charge or spend_unknown, restart recovery, and Resume bound to its pause. The Meter runs an attempt through the guard for a harness adapter (S2's Pi; a fake here). Tests with a fake harness cover the S1 finish line: held after the budget, a three-way race admits one, a crash before the charge ends spend_unknown, a stale Resume leaves the newer pause, a resent row charges once, an unpriced model is unknown.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5 files changed,
+1,254
−0
internal/runner/metered/ledger.go+394 −0internal/runner/metered/meter.go+214 −0internal/runner/metered/meter_test.go+393 −0internal/runner/metered/prices.go+177 −0internal/runner/metered/prices_test.go+76 −0
diff --git a/internal/runner/metered/ledger.go b/internal/runner/metered/ledger.go| new file mode 100644 |
| index 00000000..420ef515 |
| --- /dev/null |
| +++ b/internal/runner/metered/ledger.go |
| @@ -0,0 +1,394 @@ |
| +package metered |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "fmt" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// Schema is the metered tables in thin.db (§2.3). metered_connections |
| +// holds each metered connection (its home, model, price version, budget |
| +// and pause); metered_slot its one slot, which every attempt on it |
| +// claims in the transaction that admits it; budget_charge the ledger, |
| +// keyed by the usage row's key so a resent row charges once. |
| +const Schema = ` |
| +CREATE TABLE IF NOT EXISTS metered_connections (local_id TEXT PRIMARY KEY, person TEXT NOT NULL, provider TEXT NOT NULL, harness TEXT NOT NULL, upstream TEXT NOT NULL, billing TEXT NOT NULL, model TEXT NOT NULL DEFAULT '', home TEXT NOT NULL, currency TEXT NOT NULL, price_version TEXT NOT NULL, budget_day INTEGER NOT NULL, budget_month INTEGER NOT NULL, budget_revision INTEGER NOT NULL DEFAULT 0, spend_unknown INTEGER NOT NULL DEFAULT 0, pause_revision INTEGER NOT NULL DEFAULT 0, validated INTEGER NOT NULL DEFAULT 0, refused INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL); |
| +CREATE TABLE IF NOT EXISTS metered_slot (local_id TEXT PRIMARY KEY, holder TEXT NOT NULL DEFAULT '', role TEXT NOT NULL DEFAULT '', namespace TEXT NOT NULL DEFAULT '', claimed_at TEXT NOT NULL DEFAULT ''); |
| +CREATE TABLE IF NOT EXISTS budget_charge (turn TEXT NOT NULL, step TEXT NOT NULL, attempt INTEGER NOT NULL, connection TEXT NOT NULL, model TEXT NOT NULL, holder TEXT NOT NULL, cost_micros INTEGER, reported_micros INTEGER, currency TEXT NOT NULL, price_version TEXT NOT NULL, day TEXT NOT NULL, month TEXT NOT NULL, recorded_at TEXT NOT NULL, PRIMARY KEY (turn, step, attempt, connection, model)); |
| +CREATE INDEX IF NOT EXISTS budget_charge_period ON budget_charge(connection, day, month); |
| +` |
| + |
| +// Holds: why an attempt on a metered connection is not admitted. |
| +const ( |
| + HoldBusy = "busy" |
| + HoldBudget = "budget" |
| + HoldSpendUnknown = "spend_unknown" |
| +) |
| + |
| +// Roles an attempt holds the slot for. |
| +const ( |
| + RoleEngineering = "engineering" |
| + RoleReview = "review" |
| + RoleAsk = "ask" |
| + RoleProbe = wire.UsageProbe |
| +) |
| + |
| +// ErrNotMetered: the connection is not a metered one this runner holds. |
| +var ErrNotMetered = errors.New("metered: not a metered connection") |
| + |
| +// ErrNotProven: a slot is released only after its attempt's termination |
| +// proof. |
| +var ErrNotProven = errors.New("metered: the attempt's exit is not proven") |
| + |
| +// Conn is one metered connection as the runner holds it. |
| +type Conn struct { |
| + LocalID, Person, Provider, Harness, Upstream, Billing, Model, Home string |
| + Currency, PriceVersion string |
| + Budget wire.Budget |
| + SpendUnknown bool |
| + PauseRevision int64 |
| + // Validated: its one-token probe on the model succeeded once. |
| + // Refused: the provider refused the key at the last probe. |
| + Validated, Refused bool |
| +} |
| + |
| +// Holder is one attempt holding a slot: the usage row key's turn, step |
| +// and attempt (a question's id is its step; a probe's id too) and the |
| +// role it runs. |
| +type Holder struct { |
| + Turn, Step string |
| + Attempt int64 |
| + Role string |
| +} |
| + |
| +// Key is the holder's slot record. |
| +func (h Holder) Key() string { return fmt.Sprintf("%s|%s|%s|%d", h.Role, h.Turn, h.Step, h.Attempt) } |
| + |
| +// Admission is Admit's answer: admitted, or held with why and, for the |
| +// budget, when a new day or month starts. |
| +type Admission struct { |
| + Admitted bool |
| + Hold string |
| + WakeAt time.Time |
| +} |
| + |
| +type querier interface { |
| + QueryRowContext(context.Context, string, ...any) *sql.Row |
| + QueryContext(context.Context, string, ...any) (*sql.Rows, error) |
| +} |
| + |
| +const connColumns = "local_id, person, provider, harness, upstream, billing, model, home, currency, price_version, budget_day, budget_month, budget_revision, spend_unknown, pause_revision, validated, refused" |
| + |
| +func scanConn(scan func(...any) error) (Conn, error) { |
| + var c Conn |
| + var unknown, validated, refused int |
| + err := scan(&c.LocalID, &c.Person, &c.Provider, &c.Harness, &c.Upstream, &c.Billing, &c.Model, &c.Home, &c.Currency, &c.PriceVersion, &c.Budget.Day, &c.Budget.Month, &c.Budget.Revision, &unknown, &c.PauseRevision, &validated, &refused) |
| + c.Budget.Currency = c.Currency |
| + c.SpendUnknown, c.Validated, c.Refused = unknown == 1, validated == 1, refused == 1 |
| + return c, err |
| +} |
| + |
| +// Add records a new metered connection and its free slot. |
| +func Add(ctx context.Context, tx *sql.Tx, c Conn, now time.Time) error { |
| + if _, err := tx.ExecContext(ctx, "INSERT INTO metered_connections("+connColumns+", created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,0,0,0,0,?)", c.LocalID, c.Person, c.Provider, c.Harness, c.Upstream, c.Billing, c.Model, c.Home, c.Currency, c.PriceVersion, c.Budget.Day, c.Budget.Month, c.Budget.Revision, stamp(now)); err != nil { |
| + return err |
| + } |
| + _, err := tx.ExecContext(ctx, "INSERT INTO metered_slot(local_id) VALUES(?) ON CONFLICT DO NOTHING", c.LocalID) |
| + return err |
| +} |
| + |
| +// Get reads one metered connection. |
| +func Get(ctx context.Context, q querier, local string) (Conn, bool, error) { |
| + c, err := scanConn(q.QueryRowContext(ctx, "SELECT "+connColumns+" FROM metered_connections WHERE local_id=?", local).Scan) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return Conn{}, false, nil |
| + } |
| + return c, err == nil, err |
| +} |
| + |
| +// List reads every metered connection, oldest first. |
| +func List(ctx context.Context, q querier) ([]Conn, error) { |
| + rows, err := q.QueryContext(ctx, "SELECT "+connColumns+" FROM metered_connections ORDER BY created_at, local_id") |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var out []Conn |
| + for rows.Next() { |
| + c, err := scanConn(rows.Scan) |
| + if err != nil { |
| + return nil, err |
| + } |
| + out = append(out, c) |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| +// Remove forgets a signed-out connection: its record and slot. Its |
| +// charges stay until they age out with the day's and month's sums. |
| +func Remove(ctx context.Context, tx *sql.Tx, local string) error { |
| + if _, err := tx.ExecContext(ctx, "DELETE FROM metered_connections WHERE local_id=?", local); err != nil { |
| + return err |
| + } |
| + _, err := tx.ExecContext(ctx, "DELETE FROM metered_slot WHERE local_id=?", local) |
| + return err |
| +} |
| + |
| +// SetModel records the connection's one model. |
| +func SetModel(ctx context.Context, tx *sql.Tx, local, model string) error { |
| + _, err := tx.ExecContext(ctx, "UPDATE metered_connections SET model=? WHERE local_id=?", model, local) |
| + return err |
| +} |
| + |
| +// Checked records a probe's verdict: validated after a success, refused |
| +// after the provider refused the key. |
| +func Checked(ctx context.Context, tx *sql.Tx, local string, ok bool) error { |
| + q := "UPDATE metered_connections SET validated=1, refused=0 WHERE local_id=?" |
| + if !ok { |
| + q = "UPDATE metered_connections SET refused=1 WHERE local_id=?" |
| + } |
| + _, err := tx.ExecContext(ctx, q, local) |
| + return err |
| +} |
| + |
| +func stamp(t time.Time) string { return t.UTC().Format(time.RFC3339Nano) } |
| + |
| +// period is the budget day and month a time falls in: UTC until the |
| +// person's zone is known (§2.3). |
| +func period(t time.Time) (day, month string) { |
| + t = t.UTC() |
| + return t.Format("2006-01-02"), t.Format("2006-01") |
| +} |
| + |
| +// spent sums the connection's known charges in now's day and month. |
| +func spent(ctx context.Context, q querier, local string, now time.Time) (day, month int64, err error) { |
| + d, m := period(now) |
| + err = q.QueryRowContext(ctx, "SELECT coalesce(sum(CASE WHEN day=? THEN cost_micros END),0), coalesce(sum(cost_micros),0) FROM budget_charge WHERE connection=? AND month=?", d, local, m).Scan(&day, &month) |
| + return day, month, err |
| +} |
| + |
| +// Admit is the metered guard (§2.3, §7): in the caller's transaction, |
| +// the attempt claims the connection's one slot only when the slot is |
| +// free, the spend is known, and the reported spend is under both the |
| +// day's and the month's budget. The same holder asking again is |
| +// admitted (its claim stands). Every attempt on a metered connection |
| +// passes here: an Engineering or Review step, a question, a probe. |
| +func Admit(ctx context.Context, tx *sql.Tx, local string, h Holder, now time.Time) (Admission, error) { |
| + c, ok, err := Get(ctx, tx, local) |
| + if err != nil || !ok { |
| + return Admission{}, firstErr(err, ErrNotMetered) |
| + } |
| + var holder string |
| + if err := tx.QueryRowContext(ctx, "SELECT holder FROM metered_slot WHERE local_id=?", local).Scan(&holder); err != nil { |
| + return Admission{}, err |
| + } |
| + if holder == h.Key() { |
| + return Admission{Admitted: true}, nil |
| + } |
| + if holder != "" { |
| + return Admission{Hold: HoldBusy}, nil |
| + } |
| + if c.SpendUnknown { |
| + return Admission{Hold: HoldSpendUnknown}, nil |
| + } |
| + day, month, err := spent(ctx, tx, local, now) |
| + if err != nil { |
| + return Admission{}, err |
| + } |
| + if day >= c.Budget.Day || month >= c.Budget.Month { |
| + return Admission{Hold: HoldBudget, WakeAt: nextPeriod(now, month >= c.Budget.Month)}, nil |
| + } |
| + res, err := tx.ExecContext(ctx, "UPDATE metered_slot SET holder=?, role=?, namespace='', claimed_at=? WHERE local_id=? AND holder=''", h.Key(), h.Role, stamp(now), local) |
| + if err != nil { |
| + return Admission{}, err |
| + } |
| + if n, err := res.RowsAffected(); err != nil || n != 1 { |
| + return Admission{Hold: HoldBusy}, err |
| + } |
| + return Admission{Admitted: true}, nil |
| +} |
| + |
| +// nextPeriod is when the next budget day (or month) starts, UTC. |
| +func nextPeriod(now time.Time, month bool) time.Time { |
| + now = now.UTC() |
| + if month { |
| + return time.Date(now.Year(), now.Month()+1, 1, 0, 0, 0, 0, time.UTC) |
| + } |
| + return time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, time.UTC) |
| +} |
| + |
| +// SetNamespace records the namespace of the slot's attempt before its |
| +// harness starts, so a restart can prove it gone. |
| +func SetNamespace(ctx context.Context, tx *sql.Tx, local string, h Holder, ns string) error { |
| + res, err := tx.ExecContext(ctx, "UPDATE metered_slot SET namespace=? WHERE local_id=? AND holder=?", ns, local, h.Key()) |
| + if err != nil { |
| + return err |
| + } |
| + if n, err := res.RowsAffected(); err != nil || n != 1 { |
| + return firstErr(err, errors.New("metered: the slot is not this attempt's")) |
| + } |
| + return nil |
| +} |
| + |
| +// Charge prices the attempt's usage rows with the connection's table and |
| +// records each in the ledger once, keyed by the row's key (a resent row |
| +// charges once), in the period the charge is recorded in. It returns the |
| +// rows with their cost, to report in the same transaction. |
| +func Charge(ctx context.Context, tx *sql.Tx, local string, h Holder, rows []wire.Usage, now time.Time) ([]wire.Usage, error) { |
| + c, ok, err := Get(ctx, tx, local) |
| + if err != nil || !ok { |
| + return nil, firstErr(err, ErrNotMetered) |
| + } |
| + table, known := TableFor(c.PriceVersion) |
| + day, month := period(now) |
| + out := make([]wire.Usage, 0, len(rows)) |
| + for _, u := range rows { |
| + if u.Connection != local { |
| + out = append(out, u) |
| + continue |
| + } |
| + priced := u |
| + priced.Currency, priced.PriceVersion, priced.CostMicros = c.Currency, c.PriceVersion, nil |
| + if known { |
| + priced, _ = table.Price(u) |
| + } |
| + var cost, reported any |
| + if priced.CostMicros != nil { |
| + cost = *priced.CostMicros |
| + } |
| + if priced.CostReportedMicros != nil { |
| + reported = *priced.CostReportedMicros |
| + } |
| + if _, err := tx.ExecContext(ctx, "INSERT INTO budget_charge(turn, step, attempt, connection, model, holder, cost_micros, reported_micros, currency, price_version, day, month, recorded_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT DO NOTHING", h.Turn, h.Step, u.Attempt, local, u.Model, h.Key(), cost, reported, c.Currency, c.PriceVersion, day, month, stamp(now)); err != nil { |
| + return nil, err |
| + } |
| + out = append(out, priced) |
| + } |
| + return out, nil |
| +} |
| + |
| +// Ending is how an attempt ended, for Settle: Proven says its |
| +// namespace's exit is proven; NotStarted that no harness was started |
| +// for it at all, so nothing can have been spent. |
| +type Ending struct { |
| + Proven, NotStarted bool |
| +} |
| + |
| +// Settle releases the slot of an attempt whose exit is proven, in the |
| +// caller's transaction: with a committed, known charge for the attempt |
| +// the spend stands; otherwise (no usage figure, an incomplete or |
| +// unpriced one) the connection's spend becomes unknown, under a new |
| +// pause revision, in the same transaction. A slot another attempt holds |
| +// is left alone. |
| +func Settle(ctx context.Context, tx *sql.Tx, local string, h Holder, e Ending) error { |
| + return settle(ctx, tx, local, h.Key(), e) |
| +} |
| + |
| +func settle(ctx context.Context, tx *sql.Tx, local, key string, e Ending) error { |
| + if !e.Proven { |
| + return ErrNotProven |
| + } |
| + res, err := tx.ExecContext(ctx, "UPDATE metered_slot SET holder='', role='', namespace='', claimed_at='' WHERE local_id=? AND holder=?", local, key) |
| + if err != nil { |
| + return err |
| + } |
| + if n, err := res.RowsAffected(); err != nil || n != 1 { |
| + return err |
| + } |
| + if e.NotStarted { |
| + return nil |
| + } |
| + var rows, unknown int |
| + if err := tx.QueryRowContext(ctx, "SELECT count(*), coalesce(sum(cost_micros IS NULL),0) FROM budget_charge WHERE connection=? AND holder=?", local, key).Scan(&rows, &unknown); err != nil { |
| + return err |
| + } |
| + if rows > 0 && unknown == 0 { |
| + return nil |
| + } |
| + return pause(ctx, tx, local) |
| +} |
| + |
| +// pause marks the connection's spend unknown under a new pause revision. |
| +func pause(ctx context.Context, tx *sql.Tx, local string) error { |
| + _, err := tx.ExecContext(ctx, "UPDATE metered_connections SET spend_unknown=1, pause_revision=pause_revision+1 WHERE local_id=?", local) |
| + return err |
| +} |
| + |
| +// Resume consumes the person's Resume bound to the pause they saw: it |
| +// clears the unknown spend once, and only while pauseRevision is still |
| +// the connection's pause. A stale or repeated Resume changes nothing, |
| +// so a newer pause stays. It reports whether it cleared one. |
| +func Resume(ctx context.Context, tx *sql.Tx, local string, pauseRevision int64) (bool, error) { |
| + res, err := tx.ExecContext(ctx, "UPDATE metered_connections SET spend_unknown=0 WHERE local_id=? AND spend_unknown=1 AND pause_revision=?", local, pauseRevision) |
| + if err != nil { |
| + return false, err |
| + } |
| + n, err := res.RowsAffected() |
| + return n == 1, err |
| +} |
| + |
| +// ApplyBudget applies a budget change above the revision the runner |
| +// holds; an older or equal revision changes nothing. A running attempt |
| +// is not stopped: the budget is read at the next admission. |
| +func ApplyBudget(ctx context.Context, tx *sql.Tx, local string, b wire.Budget) (bool, error) { |
| + if !wire.ValidBudget(b) { |
| + return false, errors.New("metered: budget out of bounds") |
| + } |
| + res, err := tx.ExecContext(ctx, "UPDATE metered_connections SET budget_day=?, budget_month=?, budget_revision=? WHERE local_id=? AND budget_revision<?", b.Day, b.Month, b.Revision, local, b.Revision) |
| + if err != nil { |
| + return false, err |
| + } |
| + n, err := res.RowsAffected() |
| + return n == 1, err |
| +} |
| + |
| +// SpendOf is what the connection has spent today and this month, as |
| +// hello reports it, with its pause and whether its slot is held. |
| +func SpendOf(ctx context.Context, q querier, c Conn, now time.Time) (wire.Spend, error) { |
| + day, month, err := spent(ctx, q, c.LocalID, now) |
| + if err != nil { |
| + return wire.Spend{}, err |
| + } |
| + var holder string |
| + if err := q.QueryRowContext(ctx, "SELECT holder FROM metered_slot WHERE local_id=?", c.LocalID).Scan(&holder); err != nil && !errors.Is(err, sql.ErrNoRows) { |
| + return wire.Spend{}, err |
| + } |
| + return wire.Spend{Day: day, Month: month, Currency: c.Currency, Unknown: c.SpendUnknown, PauseRevision: c.PauseRevision, Running: holder != ""}, nil |
| +} |
| + |
| +// Claimed is a held slot: whose, and the namespace its attempt runs in. |
| +type Claimed struct { |
| + Local, Namespace string |
| + Holder string |
| +} |
| + |
| +// claimed lists every held slot. |
| +func claimed(ctx context.Context, q querier) ([]Claimed, error) { |
| + rows, err := q.QueryContext(ctx, "SELECT local_id, holder, namespace FROM metered_slot WHERE holder<>''") |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var out []Claimed |
| + for rows.Next() { |
| + var c Claimed |
| + if err := rows.Scan(&c.Local, &c.Holder, &c.Namespace); err != nil { |
| + return nil, err |
| + } |
| + out = append(out, c) |
| + } |
| + return out, rows.Err() |
| +} |
| + |
| +func firstErr(errs ...error) error { |
| + for _, e := range errs { |
| + if e != nil { |
| + return e |
| + } |
| + } |
| + return nil |
| +} |
diff --git a/internal/runner/metered/meter.go b/internal/runner/metered/meter.go| new file mode 100644 |
| index 00000000..9eebf2c6 |
| --- /dev/null |
| +++ b/internal/runner/metered/meter.go |
| @@ -0,0 +1,214 @@ |
| +package metered |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// Meter runs attempts on metered connections through the guard (§2.3): |
| +// admitted with the slot claimed in one transaction; the usage charged |
| +// and reported in one transaction; the slot released only after the |
| +// attempt's termination proof, with its charge or with the spend |
| +// unknown, in that same transaction. A harness (S2's Pi, a test's fake) |
| +// runs the attempt; the Meter never starts one itself. |
| +type Meter struct { |
| + DB *sql.DB |
| + // Gone proves an attempt's namespace gone (killed and its exit |
| + // verified, as the step recovery does). An attempt that recorded no |
| + // namespace started no harness. |
| + Gone func(ctx context.Context, namespace string) error |
| + Now func() time.Time |
| + // Changed is called when a slot was released or a pause, a budget or |
| + // a charge changed what hello reports. |
| + Changed func() |
| + // Fault, in tests, stops the process at a boundary ("exited": after |
| + // the harness ended, before its charge), as if it stopped there. |
| + Fault func(stage string) error |
| +} |
| + |
| +// ErrStopped is a test fault's stop. |
| +var ErrStopped = errors.New("metered: stopped") |
| + |
| +// Launch is what a harness gets for one admitted attempt: the connection |
| +// and the holder, and Namespace, which records the attempt's namespace |
| +// in its slot before the harness starts it. |
| +type Launch struct { |
| + Conn Conn |
| + Holder Holder |
| + Namespace func(ns string) error |
| +} |
| + |
| +// Result is how an attempt ended: the usage rows the harness reported, |
| +// and its Ending. |
| +type Result struct { |
| + Usage []wire.Usage |
| + Ending |
| +} |
| + |
| +func (m *Meter) now() time.Time { |
| + if m.Now != nil { |
| + return m.Now() |
| + } |
| + return time.Now() |
| +} |
| + |
| +func (m *Meter) tx(ctx context.Context, fn func(*sql.Tx) error) error { |
| + t, err := m.DB.BeginTx(ctx, nil) |
| + if err != nil { |
| + return err |
| + } |
| + defer t.Rollback() |
| + if err = fn(t); err != nil { |
| + return err |
| + } |
| + return t.Commit() |
| +} |
| + |
| +func (m *Meter) changed() { |
| + if m.Changed != nil { |
| + m.Changed() |
| + } |
| +} |
| + |
| +// Admit claims the slot for h when the guard allows it, in its own |
| +// transaction plus whatever admit adds to it (the caller's admission |
| +// record), so the claim and the admission commit together. |
| +func (m *Meter) Admit(ctx context.Context, local string, h Holder, admit func(*sql.Tx) error) (Admission, error) { |
| + var a Admission |
| + err := m.tx(ctx, func(t *sql.Tx) error { |
| + var err error |
| + if a, err = Admit(ctx, t, local, h, m.now()); err != nil || !a.Admitted || admit == nil { |
| + return err |
| + } |
| + return admit(t) |
| + }) |
| + if err == nil && a.Admitted { |
| + m.changed() |
| + } |
| + return a, err |
| +} |
| + |
| +// Run admits h on the connection, runs the attempt and settles it. |
| +// Held, it returns the hold and runs nothing. report, in the charge's |
| +// transaction, records the priced rows (the attempt's report or usage |
| +// frame). An attempt whose exit is not proven keeps its slot until |
| +// Recover proves it. |
| +func (m *Meter) Run(ctx context.Context, local string, h Holder, run func(context.Context, Launch) Result, report func(*sql.Tx, []wire.Usage) error) (Admission, Result, error) { |
| + a, err := m.Admit(ctx, local, h, nil) |
| + if err != nil || !a.Admitted { |
| + return a, Result{}, err |
| + } |
| + c, _, err := Get(ctx, m.DB, local) |
| + if err != nil { |
| + return a, Result{}, err |
| + } |
| + res := run(ctx, Launch{Conn: c, Holder: h, Namespace: func(ns string) error { |
| + return m.tx(ctx, func(t *sql.Tx) error { return SetNamespace(ctx, t, local, h, ns) }) |
| + }}) |
| + if m.Fault != nil { |
| + if err := m.Fault("exited"); err != nil { |
| + return a, res, err |
| + } |
| + } |
| + err = m.Finish(context.WithoutCancel(ctx), local, h, res, report) |
| + return a, res, err |
| +} |
| + |
| +// Finish charges an attempt's usage and, once its exit is proven, |
| +// releases its slot, in one transaction. |
| +func (m *Meter) Finish(ctx context.Context, local string, h Holder, res Result, report func(*sql.Tx, []wire.Usage) error) error { |
| + err := m.tx(ctx, func(t *sql.Tx) error { |
| + priced, err := Charge(ctx, t, local, h, res.Usage, m.now()) |
| + if err != nil { |
| + return err |
| + } |
| + if report != nil { |
| + if err := report(t, priced); err != nil { |
| + return err |
| + } |
| + } |
| + if !res.Proven { |
| + return nil |
| + } |
| + return Settle(ctx, t, local, h, res.Ending) |
| + }) |
| + if err == nil { |
| + m.changed() |
| + } |
| + return err |
| +} |
| + |
| +// Recover reconciles every claimed slot, at start-up before anything is |
| +// admitted and again whenever an exit could not be proven (§2.3): the |
| +// attempt's namespace is proven gone; a usage row it committed is |
| +// already charged (Charge commits with the report); otherwise the |
| +// connection's spend becomes unknown; then the slot is released, in one |
| +// transaction. A slot whose namespace cannot be proven gone stays held, |
| +// so nothing else is admitted to that connection. |
| +func (m *Meter) Recover(ctx context.Context) error { |
| + held, err := claimed(ctx, m.DB) |
| + if err != nil { |
| + return err |
| + } |
| + var first error |
| + for _, c := range held { |
| + if c.Namespace != "" { |
| + if m.Gone == nil { |
| + first = firstErr(first, ErrNotProven) |
| + continue |
| + } |
| + if err := m.Gone(ctx, c.Namespace); err != nil { |
| + first = firstErr(first, err) |
| + continue |
| + } |
| + } |
| + if err := m.tx(ctx, func(t *sql.Tx) error { return settle(ctx, t, c.Local, c.Holder, Ending{Proven: true}) }); err != nil { |
| + return err |
| + } |
| + m.changed() |
| + } |
| + return first |
| +} |
| + |
| +// Resume consumes a Resume for the pause it names (Resume). |
| +func (m *Meter) Resume(ctx context.Context, local string, pauseRevision int64, record func(*sql.Tx) error) (bool, error) { |
| + var cleared bool |
| + err := m.tx(ctx, func(t *sql.Tx) error { |
| + var err error |
| + if cleared, err = Resume(ctx, t, local, pauseRevision); err != nil { |
| + return err |
| + } |
| + if record != nil { |
| + return record(t) |
| + } |
| + return nil |
| + }) |
| + if err == nil && cleared { |
| + m.changed() |
| + } |
| + return cleared, err |
| +} |
| + |
| +// ApplyBudget applies a budget frame (ApplyBudget) with record, the |
| +// frame's own bookkeeping, in one transaction. |
| +func (m *Meter) ApplyBudget(ctx context.Context, local string, b wire.Budget, record func(*sql.Tx) error) (bool, error) { |
| + var applied bool |
| + err := m.tx(ctx, func(t *sql.Tx) error { |
| + var err error |
| + if applied, err = ApplyBudget(ctx, t, local, b); err != nil { |
| + return err |
| + } |
| + if record != nil { |
| + return record(t) |
| + } |
| + return nil |
| + }) |
| + if err == nil && applied { |
| + m.changed() |
| + } |
| + return applied, err |
| +} |
diff --git a/internal/runner/metered/meter_test.go b/internal/runner/metered/meter_test.go| new file mode 100644 |
| index 00000000..c815275f |
| --- /dev/null |
| +++ b/internal/runner/metered/meter_test.go |
| @@ -0,0 +1,393 @@ |
| +package metered |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "path/filepath" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| + _ "modernc.org/sqlite" |
| +) |
| + |
| +// The S1 finish line (connectors spec §11), with a fake harness: each |
| +// test runs attempts through the Meter the way a harness adapter does. |
| + |
| +const tx1 = "tensorx-1" |
| + |
| +func open(t *testing.T, dir string) *sql.DB { |
| + t.Helper() |
| + db, err := sql.Open("sqlite", "file:"+filepath.Join(dir, "thin.db")+"?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + db.SetMaxOpenConns(1) |
| + if _, err := db.Exec(Schema); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { db.Close() }) |
| + return db |
| +} |
| + |
| +type rig struct { |
| + t *testing.T |
| + dir string |
| + db *sql.DB |
| + m *Meter |
| + clock time.Time |
| +} |
| + |
| +func newRig(t *testing.T, day, month int64) *rig { |
| + r := &rig{t: t, dir: t.TempDir(), clock: time.Date(2026, 11, 12, 10, 0, 0, 0, time.UTC)} |
| + r.db = open(t, r.dir) |
| + r.m = r.meter() |
| + err := r.m.tx(context.Background(), func(tx *sql.Tx) error { |
| + return Add(context.Background(), tx, Conn{LocalID: tx1, Person: "p", Provider: wire.ProviderTensorX, Harness: wire.HarnessPi, Upstream: "https://api.tensorx.ai", Billing: wire.BillingMetered, Model: "z-ai/glm-5.3", Home: "/h", Currency: "USD", PriceVersion: Current[wire.ProviderTensorX], Budget: wire.Budget{Day: day, Month: month, Revision: 1}}, r.clock) |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return r |
| +} |
| + |
| +func (r *rig) meter() *Meter { |
| + return &Meter{DB: r.db, Now: func() time.Time { return r.clock }, Gone: func(context.Context, string) error { return nil }} |
| +} |
| + |
| +// usage is a fake harness's report: input and output tokens on model. |
| +func usage(model string, attempt, in, out int64) wire.Usage { |
| + return wire.Usage{Provider: wire.ProviderTensorX, Connection: tx1, Model: model, Attempt: attempt, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: &in, CachedInputTokens: new(int64), CacheWriteTokens: new(int64), OutputTokens: &out} |
| +} |
| + |
| +// harness is the fake: it reports rows and a proven exit. |
| +func harness(rows ...wire.Usage) func(context.Context, Launch) Result { |
| + return func(_ context.Context, l Launch) Result { |
| + if err := l.Namespace("ns-" + l.Holder.Step); err != nil { |
| + panic(err) |
| + } |
| + return Result{Usage: rows, Ending: Ending{Proven: true}} |
| + } |
| +} |
| + |
| +func (r *rig) run(h Holder, rows ...wire.Usage) Admission { |
| + r.t.Helper() |
| + a, _, err := r.m.Run(context.Background(), tx1, h, harness(rows...), nil) |
| + if err != nil { |
| + r.t.Fatal(err) |
| + } |
| + return a |
| +} |
| + |
| +func (r *rig) spend() wire.Spend { |
| + c, _, err := Get(context.Background(), r.db, tx1) |
| + if err != nil { |
| + r.t.Fatal(err) |
| + } |
| + s, err := SpendOf(context.Background(), r.db, c, r.clock) |
| + if err != nil { |
| + r.t.Fatal(err) |
| + } |
| + return s |
| +} |
| + |
| +func step(id string, role string) Holder { return Holder{Step: id, Attempt: 1, Role: role} } |
| + |
| +// (a) The attempt after the reported spend crosses the budget is held, |
| +// until the next budget day; one step can overshoot, never two. |
| +func TestMeteredBudgetHoldsTheNextAttempt(t *testing.T) { |
| + r := newRig(t, 1_000_000, 10_000_000) |
| + // 0.4M input at 1.75 and 0.05M output at 4.50: 0.925 of the day's 1. |
| + if a := r.run(step("s1", RoleEngineering), usage("z-ai/glm-5.3", 1, 400_000, 50_000)); !a.Admitted { |
| + t.Fatalf("first held: %+v", a) |
| + } |
| + if s := r.spend(); s.Day != 925_000 || s.Unknown || s.Running { |
| + t.Fatalf("spend %+v", s) |
| + } |
| + // Under the budget still: admitted, and it crosses it. |
| + if a := r.run(step("s2", RoleReview), usage("z-ai/glm-5.3", 1, 100_000, 10_000)); !a.Admitted { |
| + t.Fatalf("second held: %+v", a) |
| + } |
| + ran := false |
| + a, _, err := r.m.Run(context.Background(), tx1, step("s3", RoleEngineering), func(context.Context, Launch) Result { ran = true; return Result{} }, nil) |
| + if err != nil || a.Admitted || a.Hold != HoldBudget || ran { |
| + t.Fatalf("after the budget: %+v ran=%v %v", a, ran, err) |
| + } |
| + if want := time.Date(2026, 11, 13, 0, 0, 0, 0, time.UTC); !a.WakeAt.Equal(want) { |
| + t.Fatalf("wakes %v", a.WakeAt) |
| + } |
| + // A new day: admitted again; this month's spend carries on. |
| + r.clock = r.clock.Add(24 * time.Hour) |
| + if a := r.run(step("s3", RoleEngineering), usage("z-ai/glm-5.3", 1, 1, 1)); !a.Admitted { |
| + t.Fatalf("next day held: %+v", a) |
| + } |
| + if s := r.spend(); s.Day != 7 || s.Month != 925_000+220_000+7 { |
| + t.Fatalf("next day spend %+v", s) |
| + } |
| + // The month's budget holds until the first of next month. |
| + r2 := newRig(t, 1_000_000, 1_000_000) |
| + r2.run(step("s1", RoleEngineering), usage("z-ai/glm-5.3", 1, 600_000, 0)) |
| + r2.clock = r2.clock.Add(24 * time.Hour) |
| + r2.run(step("s2", RoleEngineering), usage("z-ai/glm-5.3", 1, 600_000, 0)) |
| + r2.clock = r2.clock.Add(24 * time.Hour) |
| + if a := r2.run(step("s3", RoleEngineering)); a.Admitted || a.Hold != HoldBudget || !a.WakeAt.Equal(time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC)) { |
| + t.Fatalf("month: %+v", a) |
| + } |
| + // A raised budget, applied, admits; an older revision changes nothing. |
| + if ok, err := r.m.ApplyBudget(context.Background(), tx1, wire.Budget{Day: 900_000, Month: 9_000_000, Revision: 1}, nil); err != nil || ok { |
| + t.Fatalf("same revision applied: %v %v", ok, err) |
| + } |
| + if ok, err := r2.m.ApplyBudget(context.Background(), tx1, wire.Budget{Day: 2_000_000, Month: 5_000_000, Revision: 2}, nil); err != nil || !ok { |
| + t.Fatalf("raise: %v %v", ok, err) |
| + } |
| + if a := r2.run(step("s3", RoleEngineering)); a.Hold == HoldBudget { |
| + t.Fatalf("raised budget still holds: %+v", a) |
| + } |
| +} |
| + |
| +// (b) A concurrent Engineering, Review and question race on one metered |
| +// connection admits exactly one; the others are held busy and nothing of |
| +// theirs runs. |
| +func TestMeteredRaceAdmitsExactlyOne(t *testing.T) { |
| + for round := 0; round < 8; round++ { |
| + r := newRig(t, 1_000_000, 10_000_000) |
| + release := make(chan struct{}) |
| + var mu sync.Mutex |
| + ran := map[string]bool{} |
| + holds := map[string]string{} |
| + var wg sync.WaitGroup |
| + start := make(chan struct{}) |
| + for _, h := range []Holder{step("eng", RoleEngineering), step("rev", RoleReview), {Step: "q1", Attempt: 1, Role: RoleAsk}} { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + <-start |
| + a, _, err := r.m.Run(context.Background(), tx1, h, func(ctx context.Context, l Launch) Result { |
| + mu.Lock() |
| + ran[h.Role] = true |
| + mu.Unlock() |
| + <-release |
| + return harness(usage("z-ai/glm-5.3", 1, 10, 1))(ctx, l) |
| + }, nil) |
| + if err != nil { |
| + t.Error(err) |
| + } |
| + mu.Lock() |
| + holds[h.Role] = a.Hold |
| + mu.Unlock() |
| + }() |
| + } |
| + close(start) |
| + // The two held return at once; the admitted one waits on release. |
| + deadline := time.Now().Add(5 * time.Second) |
| + for { |
| + mu.Lock() |
| + n := len(holds) |
| + mu.Unlock() |
| + if n == 2 || time.Now().After(deadline) { |
| + break |
| + } |
| + time.Sleep(time.Millisecond) |
| + } |
| + mu.Lock() |
| + if len(ran) != 1 || len(holds) != 2 { |
| + t.Fatalf("round %d: ran %v, held %v", round, ran, holds) |
| + } |
| + for role, hold := range holds { |
| + if hold != HoldBusy || ran[role] { |
| + t.Fatalf("round %d: %s held %q ran %v", round, role, hold, ran[role]) |
| + } |
| + } |
| + mu.Unlock() |
| + if s := r.spend(); !s.Running { |
| + t.Fatal("the slot is not held while the attempt runs") |
| + } |
| + close(release) |
| + wg.Wait() |
| + if s := r.spend(); s.Running || s.Unknown { |
| + t.Fatalf("after: %+v", s) |
| + } |
| + } |
| +} |
| + |
| +// (c) A crash between the harness's exit and its charge ends in |
| +// spend_unknown before anything else is admitted: until recovery the |
| +// slot is held; recovery proves the namespace gone, finds no charge and |
| +// pauses the connection, then releases the slot. |
| +func TestMeteredCrashBeforeChargeIsSpendUnknown(t *testing.T) { |
| + r := newRig(t, 1_000_000, 10_000_000) |
| + r.m.Fault = func(stage string) error { |
| + if stage == "exited" { |
| + return ErrStopped |
| + } |
| + return nil |
| + } |
| + if _, _, err := r.m.Run(context.Background(), tx1, step("s1", RoleEngineering), harness(usage("z-ai/glm-5.3", 1, 10, 1)), nil); !errors.Is(err, ErrStopped) { |
| + t.Fatalf("stopped: %v", err) |
| + } |
| + r.db.Close() |
| + // The next process, on the same thin.db. |
| + r.db = open(t, r.dir) |
| + var gone []string |
| + r.m = r.meter() |
| + r.m.Gone = func(_ context.Context, ns string) error { gone = append(gone, ns); return nil } |
| + if a := r.run(step("s2", RoleReview)); a.Admitted || a.Hold != HoldBusy { |
| + t.Fatalf("admitted before recovery: %+v", a) |
| + } |
| + // An exit that cannot be proven keeps the slot. |
| + r.m.Gone = func(context.Context, string) error { return errors.New("still running") } |
| + if err := r.m.Recover(context.Background()); err == nil { |
| + t.Fatal("recovered an unproven exit") |
| + } |
| + if a := r.run(step("s2", RoleReview)); a.Hold != HoldBusy { |
| + t.Fatalf("an unproven slot released: %+v", a) |
| + } |
| + r.m.Gone = func(_ context.Context, ns string) error { gone = append(gone, ns); return nil } |
| + if err := r.m.Recover(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(gone) != 1 || gone[0] != "ns-s1" { |
| + t.Fatalf("namespaces proven gone: %v", gone) |
| + } |
| + s := r.spend() |
| + if !s.Unknown || s.PauseRevision != 1 || s.Running || s.Day != 0 { |
| + t.Fatalf("after recovery %+v", s) |
| + } |
| + if a := r.run(step("s2", RoleReview)); a.Admitted || a.Hold != HoldSpendUnknown { |
| + t.Fatalf("admitted with spend unknown: %+v", a) |
| + } |
| + // A crash after the charge committed: recovery keeps the charge and |
| + // does not pause. |
| + r2 := newRig(t, 1_000_000, 10_000_000) |
| + h := step("s1", RoleEngineering) |
| + _, _, err := r2.m.Run(context.Background(), tx1, h, func(ctx context.Context, l Launch) Result { |
| + res := harness(usage("z-ai/glm-5.3", 1, 10, 1))(ctx, l) |
| + res.Proven = false |
| + return res |
| + }, nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if s := r2.spend(); !s.Running || s.Day != 23 { |
| + t.Fatalf("charged, unproven: %+v", s) |
| + } |
| + if err := r2.m.Recover(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if s := r2.spend(); s.Running || s.Unknown || s.Day != 23 { |
| + t.Fatalf("recovered after the charge: %+v", s) |
| + } |
| +} |
| + |
| +// (d) Resume is bound to its pause: consumed once, and a stale or |
| +// repeated Resume leaves a newer pause in place. |
| +func TestMeteredStaleResumeLeavesTheNewerPause(t *testing.T) { |
| + r := newRig(t, 1_000_000, 10_000_000) |
| + ctx := context.Background() |
| + // An attempt with no usage figure pauses (revision 1). |
| + r.run(step("s1", RoleEngineering)) |
| + if s := r.spend(); !s.Unknown || s.PauseRevision != 1 { |
| + t.Fatalf("pause 1: %+v", s) |
| + } |
| + if ok, err := r.m.Resume(ctx, tx1, 1, nil); err != nil || !ok { |
| + t.Fatalf("resume 1: %v %v", ok, err) |
| + } |
| + // Another unknown spend: pause 2. |
| + r.run(step("s2", RoleEngineering), wire.Usage{Provider: wire.ProviderTensorX, Connection: tx1, Model: "z-ai/glm-5.3", Attempt: 1, Outcome: wire.OutcomeFailed}) |
| + if s := r.spend(); !s.Unknown || s.PauseRevision != 2 { |
| + t.Fatalf("pause 2: %+v", s) |
| + } |
| + // The first Resume again, replayed or stale, changes nothing. |
| + if ok, err := r.m.Resume(ctx, tx1, 1, nil); err != nil || ok { |
| + t.Fatalf("stale resume cleared: %v %v", ok, err) |
| + } |
| + if a := r.run(step("s3", RoleEngineering)); a.Hold != HoldSpendUnknown { |
| + t.Fatalf("admitted after a stale resume: %+v", a) |
| + } |
| + if ok, _ := r.m.Resume(ctx, tx1, 2, nil); !ok { |
| + t.Fatal("the current resume did nothing") |
| + } |
| + if ok, _ := r.m.Resume(ctx, tx1, 2, nil); ok { |
| + t.Fatal("a resume was consumed twice") |
| + } |
| + if a := r.run(step("s3", RoleEngineering), usage("z-ai/glm-5.3", 1, 1, 1)); !a.Admitted { |
| + t.Fatalf("held after the current resume: %+v", a) |
| + } |
| +} |
| + |
| +// (e) A resent usage row charges once: the ledger is keyed by the row's |
| +// own key. |
| +func TestMeteredResentUsageChargesOnce(t *testing.T) { |
| + r := newRig(t, 1_000_000, 10_000_000) |
| + ctx := context.Background() |
| + h := step("s1", RoleEngineering) |
| + row := usage("z-ai/glm-5.3", 1, 100_000, 0) |
| + if a, err := r.m.Admit(ctx, tx1, h, nil); err != nil || !a.Admitted { |
| + t.Fatal(a, err) |
| + } |
| + for i := 0; i < 3; i++ { |
| + if err := r.m.Finish(ctx, tx1, h, Result{Usage: []wire.Usage{row}}, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if err := r.m.Finish(ctx, tx1, h, Result{Usage: []wire.Usage{row}, Ending: Ending{Proven: true}}, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if s := r.spend(); s.Day != 175_000 || s.Unknown { |
| + t.Fatalf("charged %+v", s) |
| + } |
| + // Another attempt of the same step is another row, charged too. |
| + h2 := Holder{Step: "s1", Attempt: 2, Role: RoleEngineering} |
| + r.run(h2, usage("z-ai/glm-5.3", 2, 100_000, 0)) |
| + if s := r.spend(); s.Day != 350_000 { |
| + t.Fatalf("second attempt %+v", s) |
| + } |
| +} |
| + |
| +// (f) An unpriced model gives spend unknown, and so does an unpriceable |
| +// component; the row is reported with no cost. |
| +func TestMeteredUnpricedModelIsSpendUnknown(t *testing.T) { |
| + r := newRig(t, 1_000_000, 10_000_000) |
| + var reported []wire.Usage |
| + _, _, err := r.m.Run(context.Background(), tx1, step("s1", RoleEngineering), harness(usage("vendor/unpriced-1", 1, 10, 1)), func(_ *sql.Tx, rows []wire.Usage) error { |
| + reported = rows |
| + return nil |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(reported) != 1 || reported[0].CostMicros != nil || reported[0].PriceVersion != "tensorx-2026-11-12" || reported[0].Currency != "USD" { |
| + t.Fatalf("reported %+v", reported) |
| + } |
| + if s := r.spend(); !s.Unknown || s.Day != 0 { |
| + t.Fatalf("spend %+v", s) |
| + } |
| + if a := r.run(step("s2", RoleEngineering)); a.Hold != HoldSpendUnknown { |
| + t.Fatalf("admitted %+v", a) |
| + } |
| + r2 := newRig(t, 1_000_000, 10_000_000) |
| + cw := usage("z-ai/glm-5.3", 1, 10, 1) |
| + cw.CacheWriteTokens = new(int64) |
| + *cw.CacheWriteTokens = 5 |
| + r2.run(step("s1", RoleEngineering), cw) |
| + if s := r2.spend(); !s.Unknown { |
| + t.Fatalf("unpriced cache write: %+v", s) |
| + } |
| + // A slot is never released before its attempt's proof. |
| + r3 := newRig(t, 1_000_000, 10_000_000) |
| + h := step("s1", RoleEngineering) |
| + r3.m.Admit(context.Background(), tx1, h, nil) |
| + err = r3.m.tx(context.Background(), func(tx *sql.Tx) error { return Settle(context.Background(), tx, tx1, h, Ending{}) }) |
| + if !errors.Is(err, ErrNotProven) || !r3.spend().Running { |
| + t.Fatalf("settled unproven: %v", err) |
| + } |
| + // An attempt that started no harness spends nothing and pauses nothing. |
| + r3.m.tx(context.Background(), func(tx *sql.Tx) error { |
| + return Settle(context.Background(), tx, tx1, h, Ending{Proven: true, NotStarted: true}) |
| + }) |
| + if s := r3.spend(); s.Running || s.Unknown { |
| + t.Fatalf("not started: %+v", s) |
| + } |
| +} |
diff --git a/internal/runner/metered/prices.go b/internal/runner/metered/prices.go| new file mode 100644 |
| index 00000000..9b4a89d6 |
| --- /dev/null |
| +++ b/internal/runner/metered/prices.go |
| @@ -0,0 +1,177 @@ |
| +// Package metered keeps the soft budget of metered connections |
| +// (connectors spec 2026-11-12, §2.3, slice S1): versioned price tables, |
| +// usage normalised into billable components and priced in integer |
| +// micro-units, the budget ledger, the one durable slot per connection, |
| +// its restart recovery, and the pause when spend is unknown. It decides |
| +// nothing about which connection runs a step; it admits an attempt to a |
| +// metered connection or says why it is held. |
| +package metered |
| + |
| +import ( |
| + "math" |
| + "math/bits" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// Components are an attempt's usage as billable parts (§2.3). Reasoning |
| +// is apart from Output only where the price table says the provider |
| +// bills it separately; otherwise it is part of Output and not added. |
| +type Components struct { |
| + UncachedInput, CachedInput, CacheWrite, Output, Reasoning int64 |
| +} |
| + |
| +// Price is one model's price per component, in micro-units of the |
| +// table's currency per million tokens. A nil component is one the table |
| +// cannot price: any use of it makes the attempt's spend unknown. |
| +// InputIncludesCached: the harness counts cached input inside input (as |
| +// Codex does), so the uncached part is input less cached. |
| +type Price struct { |
| + UncachedInput, CachedInput, CacheWrite, Output, Reasoning *int64 |
| + ReasoningSeparate bool |
| + InputIncludesCached bool |
| +} |
| + |
| +// Table is a provider's price table at one version (§2.3: versioned per |
| +// connection; a connection keeps the version it was made with). |
| +type Table struct { |
| + Provider, Version, Currency string |
| + Models map[string]Price |
| +} |
| + |
| +func micros(dollars float64) *int64 { |
| + v := int64(math.Round(dollars * 1_000_000)) |
| + return &v |
| +} |
| + |
| +// tensorx prices are TensorX's published per-million-token prices read |
| +// on 2026-11-12 (tensorx.ai/pricing, matching models.dev's TensorX |
| +// files). Cache writes and separate reasoning billing are not stated, so |
| +// cache writes are unpriced (any makes spend unknown) and reasoning is |
| +// part of output. |
| +func tensorx(in, cached, out float64) Price { |
| + return Price{UncachedInput: micros(in), CachedInput: micros(cached), Output: micros(out)} |
| +} |
| + |
| +// Tables are every price table this runner knows, by version. |
| +var Tables = map[string]Table{ |
| + "tensorx-2026-11-12": {Provider: wire.ProviderTensorX, Version: "tensorx-2026-11-12", Currency: "USD", Models: map[string]Price{ |
| + "z-ai/glm-5.3": tensorx(1.75, 0.44, 4.50), |
| + "z-ai/glm-5.3-flash": tensorx(0.20, 0.05, 0.50), |
| + "z-ai/glm-5.2": tensorx(1.50, 0.38, 4.50), |
| + "moonshotai/kimi-k3": tensorx(3.00, 0.75, 15.00), |
| + "moonshotai/kimi-k3.1-pro": tensorx(3.00, 0.75, 15.00), |
| + "deepseek/deepseek-v4.1-flash": tensorx(0.50, 0.13, 1.50), |
| + "deepseek/deepseek-v4-pro-0813": tensorx(2.00, 0.50, 4.00), |
| + "deepseek/deepseek-v4-flash-0731": tensorx(0.25, 0.06, 0.30), |
| + "minimax/minimax-m3.1-flash": tensorx(0.30, 0.08, 1.20), |
| + "qwen/qwen3.8-27b": tensorx(0.40, 0.10, 2.40), |
| + }}, |
| +} |
| + |
| +// Current is the price version a new connection to a provider takes. |
| +var Current = map[string]string{wire.ProviderTensorX: "tensorx-2026-11-12"} |
| + |
| +// TableFor is the table a connection's version names (false: none). |
| +func TableFor(version string) (Table, bool) { |
| + t, ok := Tables[version] |
| + return t, ok |
| +} |
| + |
| +// Priced reports whether the table prices model at all. |
| +func (t Table) Priced(model string) bool { |
| + _, ok := t.Models[model] |
| + return ok |
| +} |
| + |
| +// Normalise turns a usage row into components under price p. It is |
| +// false when the row cannot be priced: not complete, input or output not |
| +// reported, or a figure negative. A cached or cache-write figure the |
| +// harness did not report counts as none of that kind. |
| +func Normalise(u wire.Usage, p Price) (Components, bool) { |
| + if !u.Complete || u.InputTokens == nil || u.OutputTokens == nil { |
| + return Components{}, false |
| + } |
| + figure := func(v *int64) int64 { |
| + if v == nil { |
| + return 0 |
| + } |
| + return *v |
| + } |
| + c := Components{UncachedInput: *u.InputTokens, CachedInput: figure(u.CachedInputTokens), CacheWrite: figure(u.CacheWriteTokens), Output: *u.OutputTokens} |
| + if p.ReasoningSeparate { |
| + c.Reasoning = figure(u.ReasoningOutputTokens) |
| + } |
| + if p.InputIncludesCached { |
| + c.UncachedInput -= c.CachedInput |
| + } |
| + if c.UncachedInput < 0 || c.CachedInput < 0 || c.CacheWrite < 0 || c.Output < 0 || c.Reasoning < 0 { |
| + return Components{}, false |
| + } |
| + return c, true |
| +} |
| + |
| +// Cost prices components in micro-units, each part rounded up. It is |
| +// false when a used component has no price or the sum overflows. |
| +func Cost(c Components, p Price) (int64, bool) { |
| + var total int64 |
| + for _, part := range []struct { |
| + tokens int64 |
| + price *int64 |
| + }{{c.UncachedInput, p.UncachedInput}, {c.CachedInput, p.CachedInput}, {c.CacheWrite, p.CacheWrite}, {c.Output, p.Output}, {c.Reasoning, p.Reasoning}} { |
| + if part.tokens == 0 { |
| + continue |
| + } |
| + if part.price == nil || *part.price < 0 { |
| + return 0, false |
| + } |
| + v, ok := perMillion(part.tokens, *part.price) |
| + if !ok || total > math.MaxInt64-v { |
| + return 0, false |
| + } |
| + total += v |
| + } |
| + return total, true |
| +} |
| + |
| +// perMillion is ceil(tokens * price / 1e6) without overflow. |
| +func perMillion(tokens, price int64) (int64, bool) { |
| + hi, lo := bits.Mul64(uint64(tokens), uint64(price)) |
| + if hi >= 1_000_000 { |
| + return 0, false |
| + } |
| + q, r := bits.Div64(hi, lo, 1_000_000) |
| + if r > 0 { |
| + q++ |
| + } |
| + if q > math.MaxInt64 { |
| + return 0, false |
| + } |
| + return int64(q), true |
| +} |
| + |
| +// Price prices one usage row against the table: the row with its cost, |
| +// currency and version set, and whether the cost is known. Where the |
| +// harness reported its own cost, the larger figure is charged and the |
| +// reported one kept beside it. An unpriced model, an unpriceable |
| +// component or an incomplete row leaves the cost null (unknown). |
| +func (t Table) Price(u wire.Usage) (wire.Usage, bool) { |
| + u.Currency, u.PriceVersion, u.CostMicros = t.Currency, t.Version, nil |
| + p, ok := t.Models[u.Model] |
| + if !ok { |
| + return u, false |
| + } |
| + c, ok := Normalise(u, p) |
| + if !ok { |
| + return u, false |
| + } |
| + cost, ok := Cost(c, p) |
| + if !ok { |
| + return u, false |
| + } |
| + if u.CostReportedMicros != nil && *u.CostReportedMicros > cost { |
| + cost = *u.CostReportedMicros |
| + } |
| + u.CostMicros = &cost |
| + return u, true |
| +} |
diff --git a/internal/runner/metered/prices_test.go b/internal/runner/metered/prices_test.go| new file mode 100644 |
| index 00000000..892e2df7 |
| --- /dev/null |
| +++ b/internal/runner/metered/prices_test.go |
| @@ -0,0 +1,76 @@ |
| +package metered |
| + |
| +import ( |
| + "math" |
| + "os" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "amadan.net/rastrillo/rastrillo/budget" |
| +) |
| + |
| +func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } |
| + |
| +func n(v int64) *int64 { return &v } |
| + |
| +// TestPricesNormalisedComponents is §2.3's cost rule: components priced |
| +// in integer micro-units, each part rounded up; the larger of the priced |
| +// and the reported cost; an unpriced model, an unpriceable component, an |
| +// incomplete row or an overflow is unknown. |
| +func TestPricesNormalisedComponents(t *testing.T) { |
| + table := Tables[Current[wire.ProviderTensorX]] |
| + row := wire.Usage{Provider: wire.ProviderTensorX, Model: "z-ai/glm-5.3", Attempt: 1, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: n(1_000_000), CachedInputTokens: n(500_000), CacheWriteTokens: n(0), OutputTokens: n(100_000), ReasoningOutputTokens: n(40_000)} |
| + got, ok := table.Price(row) |
| + // 1.75 + 0.5 * 0.44 + 0.1 * 4.50 = 2.42; reasoning is part of output. |
| + if !ok || got.CostMicros == nil || *got.CostMicros != 2_420_000 || got.Currency != "USD" || got.PriceVersion != "tensorx-2026-11-12" { |
| + t.Fatalf("priced %+v %v", got, ok) |
| + } |
| + reported := row |
| + reported.CostReportedMicros = n(3_000_000) |
| + if got, _ := table.Price(reported); *got.CostMicros != 3_000_000 || *got.CostReportedMicros != 3_000_000 { |
| + t.Fatalf("the reported cost was larger: %d", *got.CostMicros) |
| + } |
| + lower := row |
| + lower.CostReportedMicros = n(1) |
| + if got, _ := table.Price(lower); *got.CostMicros != 2_420_000 { |
| + t.Fatalf("the priced cost was larger: %d", *got.CostMicros) |
| + } |
| + one := row |
| + one.InputTokens, one.CachedInputTokens, one.OutputTokens = n(1), n(0), n(1) |
| + if got, _ := table.Price(one); *got.CostMicros != 2+5 { |
| + t.Fatalf("parts round up: %d", *got.CostMicros) |
| + } |
| + for name, bad := range map[string]func(*wire.Usage){ |
| + "unpriced model": func(u *wire.Usage) { u.Model = "z-ai/glm-9" }, |
| + "cache write": func(u *wire.Usage) { u.CacheWriteTokens = n(10) }, |
| + "incomplete": func(u *wire.Usage) { u.Complete = false }, |
| + "no input figure": func(u *wire.Usage) { u.InputTokens = nil }, |
| + "no output figure": func(u *wire.Usage) { u.OutputTokens = nil }, |
| + "negative": func(u *wire.Usage) { u.OutputTokens = n(-1) }, |
| + "overflowing input": func(u *wire.Usage) { u.InputTokens = n(math.MaxInt64) }, |
| + } { |
| + u := row |
| + bad(&u) |
| + if got, ok := table.Price(u); ok || got.CostMicros != nil { |
| + t.Fatalf("%s: priced %v", name, got.CostMicros) |
| + } |
| + } |
| + separate := Price{UncachedInput: n(1_000_000), Output: n(2_000_000), ReasoningSeparate: true} |
| + if c, ok := Normalise(row, separate); !ok || c.Reasoning != 40_000 { |
| + t.Fatalf("separate reasoning %+v", c) |
| + } |
| + if _, ok := Cost(Components{Reasoning: 1}, separate); ok { |
| + t.Fatal("reasoning priced with no price") |
| + } |
| + codexLike := Price{UncachedInput: n(1), CachedInput: n(1), Output: n(1), InputIncludesCached: true} |
| + if c, _ := Normalise(row, codexLike); c.UncachedInput != 500_000 { |
| + t.Fatalf("cached counted twice: %+v", c) |
| + } |
| + for _, tb := range Tables { |
| + for model, p := range tb.Models { |
| + if p.UncachedInput == nil || p.Output == nil || *p.UncachedInput <= 0 || *p.Output <= 0 { |
| + t.Fatalf("%s %s has no input or output price", tb.Version, model) |
| + } |
| + } |
| + } |
| +} |