feat: account for subscription turns and index period usage
17 files changed,
+1,084
−150
internal/equipo/execution_models.go+33 −28internal/equipo/migrations/0009_runner_policy.sql+31 −0internal/equipo/migrations/schema.sql+11 −0internal/equipo/team/actions.go+25 −0internal/equipo/team/budget.go+148 −14internal/equipo/team/harness_test.go+9 −0internal/equipo/team/jobs.go+17 −8internal/equipo/team/model.go+11 −5internal/equipo/team/periodbudget.go+101 −68internal/equipo/team/periodquery_test.go+142 −0internal/equipo/team/policy.go+55 −16internal/equipo/team/shared.go+7 −2internal/equipo/team/shared_test.go+1 −1internal/equipo/team/store.go+42 −2internal/equipo/team/subscription_test.go+329 −0internal/equipotest/budget_sync_test.go+60 −0internal/equipotest/execution_schema_test.go+62 −6
CI failed — run details
diff --git a/internal/equipo/execution_models.go b/internal/equipo/execution_models.go| index 9edd55ae..99d06c9d 100644 |
| --- a/internal/equipo/execution_models.go |
| +++ b/internal/equipo/execution_models.go |
| @@ -109,33 +109,38 @@ type executionJobs struct { |
| func (executionJobs) TableName() string { return "jobs" } |
| type executionPeriodBudgets struct { |
| - Account string `gorm:"column:account;type:text;primaryKey;autoIncrement:false"` |
| - Revision int64 `gorm:"column:revision;type:integer;not null"` |
| - Config string `gorm:"column:config;type:text;not null"` |
| + ContentHash string `gorm:"type:text;not null;default:''"` |
| + Account string `gorm:"column:account;type:text;primaryKey;autoIncrement:false"` |
| + Revision int64 `gorm:"column:revision;type:integer;not null"` |
| + Config string `gorm:"column:config;type:text;not null"` |
| } |
| func (executionPeriodBudgets) TableName() string { return "period_budgets" } |
| type executionReservations struct { |
| - ID int64 `gorm:"column:id;type:integer;primaryKey;autoIncrement:false"` |
| - Account string `gorm:"column:account;type:text;not null;index:reservations_account,priority:1"` |
| - JobID int64 `gorm:"column:job_id;type:integer;not null;index:reservations_job,priority:1"` |
| - StepID int64 `gorm:"column:step_id;type:integer;not null"` |
| - AttemptID int64 `gorm:"column:attempt_id;type:integer;not null"` |
| - ActionID int64 `gorm:"column:action_id;type:integer;not null"` |
| - RCalls int64 `gorm:"column:r_calls;type:integer;not null"` |
| - RInput int64 `gorm:"column:r_input;type:integer;not null"` |
| - ROutput int64 `gorm:"column:r_output;type:integer;not null"` |
| - RCost int64 `gorm:"column:r_cost;type:integer;not null"` |
| - SCalls int64 `gorm:"column:s_calls;type:integer;not null"` |
| - SInput int64 `gorm:"column:s_input;type:integer;not null"` |
| - SOutput int64 `gorm:"column:s_output;type:integer;not null"` |
| - SCost int64 `gorm:"column:s_cost;type:integer;not null"` |
| - State string `gorm:"column:state;type:text;not null;index:reservations_job,priority:2;index:reservations_account,priority:2"` |
| - ReceiptID string `gorm:"column:receipt_id;type:text;not null"` |
| - SettledBy string `gorm:"column:settled_by;type:text;not null"` |
| - CreatedAt string `gorm:"column:created_at;type:text;not null"` |
| - SettledAt string `gorm:"column:settled_at;type:text;not null"` |
| + ProjectID int64 `gorm:"type:integer;not null;default:0;index:reservations_period_project,priority:2"` |
| + Period string `gorm:"type:text;not null;default:'';index:reservations_period_account,priority:3;index:reservations_period_project,priority:4"` |
| + CostUnavailable int64 `gorm:"type:integer;not null;default:0"` |
| + SCached int64 `gorm:"type:integer;not null;default:0"` |
| + ID int64 `gorm:"column:id;type:integer;primaryKey;autoIncrement:false"` |
| + Account string `gorm:"column:account;type:text;not null;index:reservations_account,priority:1;index:reservations_period_account,priority:1;index:reservations_period_project,priority:1"` |
| + JobID int64 `gorm:"column:job_id;type:integer;not null;index:reservations_job,priority:1"` |
| + StepID int64 `gorm:"column:step_id;type:integer;not null"` |
| + AttemptID int64 `gorm:"column:attempt_id;type:integer;not null"` |
| + ActionID int64 `gorm:"column:action_id;type:integer;not null"` |
| + RCalls int64 `gorm:"column:r_calls;type:integer;not null"` |
| + RInput int64 `gorm:"column:r_input;type:integer;not null"` |
| + ROutput int64 `gorm:"column:r_output;type:integer;not null"` |
| + RCost int64 `gorm:"column:r_cost;type:integer;not null"` |
| + SCalls int64 `gorm:"column:s_calls;type:integer;not null"` |
| + SInput int64 `gorm:"column:s_input;type:integer;not null"` |
| + SOutput int64 `gorm:"column:s_output;type:integer;not null"` |
| + SCost int64 `gorm:"column:s_cost;type:integer;not null"` |
| + State string `gorm:"column:state;type:text;not null;index:reservations_job,priority:2;index:reservations_account,priority:2;index:reservations_period_account,priority:2;index:reservations_period_project,priority:3"` |
| + ReceiptID string `gorm:"column:receipt_id;type:text;not null"` |
| + SettledBy string `gorm:"column:settled_by;type:text;not null"` |
| + CreatedAt string `gorm:"column:created_at;type:text;not null"` |
| + SettledAt string `gorm:"column:settled_at;type:text;not null"` |
| } |
| func (executionReservations) TableName() string { return "reservations" } |
| @@ -175,13 +180,13 @@ func (executionSteps) TableName() string { return "steps" } |
| type executionTimeReservations struct { |
| ElapsedUnknown int64 `gorm:"type:integer;not null;default:0"` |
| AttemptID int64 `gorm:"column:attempt_id;type:integer;primaryKey;autoIncrement:false"` |
| - Account string `gorm:"column:account;type:text;not null;index:time_reservations_account,priority:1"` |
| - ProjectID int64 `gorm:"column:project_id;type:integer;not null;index:time_reservations_account,priority:2"` |
| + Account string `gorm:"column:account;type:text;not null;index:time_reservations_account,priority:1;index:time_period_account,priority:1;index:time_period_project,priority:1"` |
| + ProjectID int64 `gorm:"column:project_id;type:integer;not null;index:time_reservations_account,priority:2;index:time_period_project,priority:2"` |
| JobID int64 `gorm:"column:job_id;type:integer;not null"` |
| - Period string `gorm:"column:period;type:text;not null;index:time_reservations_account,priority:4"` |
| + Period string `gorm:"column:period;type:text;not null;index:time_reservations_account,priority:4;index:time_period_account,priority:3;index:time_period_project,priority:4"` |
| ReservedSeconds int64 `gorm:"column:reserved_seconds;type:integer;not null"` |
| SettledSeconds int64 `gorm:"column:settled_seconds;type:integer;not null"` |
| - State string `gorm:"column:state;type:text;not null;index:time_reservations_account,priority:3"` |
| + State string `gorm:"column:state;type:text;not null;index:time_reservations_account,priority:3;index:time_period_account,priority:2;index:time_period_project,priority:3"` |
| SettledAt string `gorm:"column:settled_at;type:text;not null"` |
| } |
| @@ -199,8 +204,8 @@ func (executionGrantFences) TableName() string { return "grant_fences" } |
| type executionRecoveryCharges struct { |
| Key string `gorm:"type:text;primaryKey"` |
| - Account string `gorm:"type:text;not null"` |
| - ProjectID int64 `gorm:"type:integer;not null"` |
| + Account string `gorm:"type:text;not null;index:recovery_charges_scope,priority:1"` |
| + ProjectID int64 `gorm:"type:integer;not null;index:recovery_charges_scope,priority:2"` |
| Reserved string `gorm:"type:text;not null"` |
| Actor string `gorm:"type:text;not null"` |
| Reason string `gorm:"type:text;not null"` |
diff --git a/internal/equipo/migrations/0009_runner_policy.sql b/internal/equipo/migrations/0009_runner_policy.sql| new file mode 100644 |
| index 00000000..3f891917 |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0009_runner_policy.sql |
| @@ -0,0 +1,31 @@ |
| +ALTER TABLE reservations ADD COLUMN project_id INTEGER NOT NULL DEFAULT 0; |
| +ALTER TABLE reservations ADD COLUMN period TEXT NOT NULL DEFAULT ""; |
| +ALTER TABLE reservations ADD COLUMN cost_unavailable INTEGER NOT NULL DEFAULT 0; |
| +ALTER TABLE reservations ADD COLUMN s_cached INTEGER NOT NULL DEFAULT 0; |
| +ALTER TABLE period_budgets ADD COLUMN content_hash TEXT NOT NULL DEFAULT ""; |
| +CREATE TABLE runner_policy_validation (valid INTEGER NOT NULL CHECK(valid=1)); |
| +INSERT INTO runner_policy_validation SELECT CASE WHEN EXISTS ( |
| + SELECT 1 FROM reservations r LEFT JOIN jobs j ON j.id=r.job_id |
| + WHERE j.id IS NULL OR j.account!=r.account OR j.project_id<0 |
| + OR length(r.created_at)<20 OR substr(r.created_at,-1)!='Z' |
| + OR substr(r.created_at,1,19) NOT GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9]' |
| + OR substr(r.created_at,12,2)>'23' OR substr(r.created_at,15,2)>'59' OR substr(r.created_at,18,2)>'59' |
| + OR date(substr(r.created_at,1,10),'+0 days')!=substr(r.created_at,1,10) |
| + OR (length(r.created_at)!=20 AND (length(r.created_at)<22 OR length(r.created_at)>30 |
| + OR substr(r.created_at,20,1)!='.' OR substr(r.created_at,21,length(r.created_at)-21) GLOB '*[^0-9]*')) |
| + OR strftime('%Y-%m',substr(r.created_at,1,19)||'Z') IS NULL |
| + OR r.state NOT IN ('open','settled','settled_audited','released') |
| +) OR EXISTS ( |
| + SELECT 1 FROM time_reservations r LEFT JOIN jobs j ON j.id=r.job_id |
| + WHERE j.id IS NULL OR j.account!=r.account OR j.project_id!=r.project_id |
| + OR r.project_id<0 OR length(r.period)!=7 OR strftime('%Y-%m',r.period||'-01') IS NULL |
| + OR r.state NOT IN ('open','settled') |
| +) THEN 0 ELSE 1 END; |
| +DROP TABLE runner_policy_validation; |
| +UPDATE reservations SET project_id=(SELECT project_id FROM jobs WHERE id=reservations.job_id), period=substr(created_at,1,7); |
| +CREATE INDEX reservations_period_account ON reservations(account,state,period); |
| +CREATE INDEX reservations_period_project ON reservations(account,project_id,state,period); |
| +CREATE INDEX time_period_account ON time_reservations(account,state,period); |
| +CREATE INDEX time_period_project ON time_reservations(account,project_id,state,period); |
| +CREATE INDEX recovery_charges_scope ON recovery_charges(account,project_id); |
| +UPDATE service SET schema_version=5 WHERE id=1; |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index cc8259d4..5071539b 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -108,6 +108,7 @@ CREATE TABLE jobs ( |
| CREATE TABLE members (address text, role text, revision integer, active numeric, session_epoch integer, PRIMARY KEY (address)); |
| CREATE TABLE period_budgets ( |
| + content_hash TEXT NOT NULL DEFAULT "", |
| account TEXT PRIMARY KEY, revision INTEGER NOT NULL, config TEXT NOT NULL |
| ); |
| @@ -117,6 +118,10 @@ CREATE TABLE projects ( |
| grant_version INTEGER NOT NULL DEFAULT 1,id integer PRIMARY KEY AUTOINCREMENT, account_id integer, name text, repository text NOT NULL, app_name text NOT NULL, default_branch text, kind text, revision integer); |
| CREATE TABLE reservations ( |
| + project_id INTEGER NOT NULL DEFAULT 0, |
| + period TEXT NOT NULL DEFAULT "", |
| + cost_unavailable INTEGER NOT NULL DEFAULT 0, |
| + s_cached INTEGER NOT NULL DEFAULT 0, |
| id INTEGER PRIMARY KEY, |
| account TEXT NOT NULL, |
| job_id INTEGER NOT NULL REFERENCES jobs(id), |
| @@ -199,3 +204,9 @@ CREATE INDEX time_reservations_account ON time_reservations(account, project_id, |
| CREATE TABLE grant_fences (ref TEXT PRIMARY KEY, version INTEGER NOT NULL, epoch INTEGER NOT NULL); |
| CREATE TABLE recovery_charges (key TEXT PRIMARY KEY, account TEXT NOT NULL, project_id INTEGER NOT NULL, reserved TEXT NOT NULL, actor TEXT NOT NULL, reason TEXT NOT NULL, incarnation INTEGER NOT NULL, created_at TEXT NOT NULL); |
| CREATE TABLE recovery_events (revision INTEGER PRIMARY KEY, kind TEXT NOT NULL, actor TEXT NOT NULL, reason TEXT NOT NULL, snapshot_hash TEXT NOT NULL); |
| + |
| +CREATE INDEX reservations_period_account ON reservations(account,state,period); |
| +CREATE INDEX reservations_period_project ON reservations(account,project_id,state,period); |
| +CREATE INDEX time_period_account ON time_reservations(account,state,period); |
| +CREATE INDEX time_period_project ON time_reservations(account,project_id,state,period); |
| +CREATE INDEX recovery_charges_scope ON recovery_charges(account,project_id); |
diff --git a/internal/equipo/team/actions.go b/internal/equipo/team/actions.go| index 314a8d58..f778eb32 100644 |
| --- a/internal/equipo/team/actions.go |
| +++ b/internal/equipo/team/actions.go |
| @@ -197,6 +197,11 @@ func (s *Store) Intend(ctx context.Context, scope Scope, h Handle, in IntentSpec |
| case !errors.Is(err, sql.ErrNoRows): |
| return fail(CodeInvalid, "action lookup: %v", err) |
| } |
| + if hd.job.Policy.Version == 2 { |
| + if err := unresolvedTurn(ctx, tx, hd.job.ID, 0); err != nil { |
| + return err |
| + } |
| + } |
| resID, priced, err := reserve(ctx, tx, hd.job, hd.step.ID, hd.attempt.ID, in.Operation, in.Reserve, now) |
| if err != nil { |
| return err |
| @@ -325,6 +330,11 @@ func (s *Store) Admit(ctx context.Context, scope Scope, id ActionID) (Dispatch, |
| if err != nil { |
| return err |
| } |
| + if j.Policy.Version == 2 { |
| + if err := unresolvedTurn(ctx, tx, j.ID, a.ID); err != nil { |
| + return err |
| + } |
| + } |
| r, err := loadReservation(ctx, tx, a.Reservation) |
| if err != nil { |
| return err |
| @@ -398,6 +408,10 @@ func (s *Store) Record(ctx context.Context, scope Scope, id ActionID, rc Receipt |
| if err := appendEvent(ctx, tx, scope, "action."+string(state), "adapter", map[string]any{"action": a.ID, "key": a.Key, "receipt": rc.ID, "usage": rc.Usage}, now); err != nil { |
| return err |
| } |
| + j, err = loadJob(ctx, tx, scope) |
| + if err != nil { |
| + return err |
| + } |
| return resumeIfResolved(ctx, tx, j, now) |
| }) |
| } |
| @@ -567,3 +581,14 @@ func (s *Store) Actions(ctx context.Context, scope Scope) ([]Action, error) { |
| }) |
| return out, err |
| } |
| + |
| +func unresolvedTurn(ctx context.Context, tx *sql.Tx, job JobID, except ActionID) error { |
| + var n int |
| + if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM actions WHERE job_id=? AND id!=? AND state IN ('dispatching','uncertain')`, job, except).Scan(&n); err != nil { |
| + return err |
| + } |
| + if n != 0 { |
| + return fail(CodeUncertain, "prior outcome unavailable") |
| + } |
| + return nil |
| +} |
diff --git a/internal/equipo/team/budget.go b/internal/equipo/team/budget.go| index dd5de755..abd4196a 100644 |
| --- a/internal/equipo/team/budget.go |
| +++ b/internal/equipo/team/budget.go |
| @@ -11,7 +11,7 @@ import ( |
| // reserved maximum, settled rows at their settled usage, released rows at |
| // nothing. Charged is the sum both limits are checked against. |
| func ledgerSum(ctx context.Context, tx *sql.Tx, where string, args ...any) (LedgerSummary, error) { |
| - rows, err := tx.QueryContext(ctx, `SELECT state, r_calls, r_input, r_output, r_cost, s_calls, s_input, s_output, s_cost FROM reservations WHERE `+where, args...) |
| + rows, err := tx.QueryContext(ctx, `SELECT state, r_calls, r_input, r_output, r_cost, s_calls, s_input, s_output, s_cost, s_cached, cost_unavailable FROM reservations WHERE `+where, args...) |
| if err != nil { |
| return LedgerSummary{}, fail(CodeInvalid, "ledger: %v", err) |
| } |
| @@ -20,9 +20,10 @@ func ledgerSum(ctx context.Context, tx *sql.Tx, where string, args ...any) (Ledg |
| for rows.Next() { |
| var state string |
| var r, st Usage |
| - if err := rows.Scan(&state, &r.Calls, &r.InputTokens, &r.OutputTokens, &r.CostMicros, &st.Calls, &st.InputTokens, &st.OutputTokens, &st.CostMicros); err != nil { |
| + if err := rows.Scan(&state, &r.Calls, &r.InputTokens, &r.OutputTokens, &r.CostMicros, &st.Calls, &st.InputTokens, &st.OutputTokens, &st.CostMicros, &st.CachedInputTokens, &r.CostUnavailable); err != nil { |
| return sum, fail(CodeInvalid, "ledger: %v", err) |
| } |
| + st.CostUnavailable = r.CostUnavailable |
| switch ReservationState(state) { |
| case ReservationOpen: |
| if sum.Reserved, err = sum.Reserved.add(r); err != nil { |
| @@ -99,10 +100,33 @@ func reserve(ctx context.Context, tx *sql.Tx, j jobRow, step StepID, attempt Att |
| if err := want.validate(); err != nil { |
| return 0, want, err |
| } |
| - account, err := accountPolicy(ctx, tx, j.Account) |
| + account := j.Policy |
| + _, configured, err := loadBudgets(ctx, tx, j.Account) |
| if err != nil { |
| return 0, want, err |
| } |
| + if !configured { |
| + account, err = accountPolicy(ctx, tx, j.Account) |
| + if err != nil { |
| + return 0, want, err |
| + } |
| + } |
| + if j.Policy.Version == 2 { |
| + if j.Wait == WaitBudget { |
| + return 0, want, fail(CodeBudget, "job stopped for budget overrun") |
| + } |
| + if err := checkActionSlots(ctx, tx, j, op); err != nil { |
| + return 0, want, err |
| + } |
| + if op == OpProviderCall { |
| + fixedCost := want.CostMicros |
| + want, err = boundedTurn(ctx, tx, j, now) |
| + if err != nil { |
| + return 0, want, err |
| + } |
| + want.CostMicros = fixedCost |
| + } |
| + } |
| priced, err := account.price(op, want) |
| if err != nil { |
| return 0, want, err |
| @@ -117,9 +141,9 @@ func reserve(ctx context.Context, tx *sql.Tx, j jobRow, step StepID, attempt Att |
| return 0, want, err |
| } |
| res, err := tx.ExecContext(ctx, `INSERT INTO reservations(account, job_id, step_id, attempt_id, action_id, r_calls, r_input, r_output, r_cost, |
| - s_calls, s_input, s_output, s_cost, state, receipt_id, settled_by, created_at, settled_at) |
| - VALUES (?,?,?,?,0,?,?,?,?,0,0,0,0,'open','','',?,'')`, |
| - string(j.Account), int64(j.ID), int64(step), int64(attempt), priced.Calls, priced.InputTokens, priced.OutputTokens, priced.CostMicros, ts(now)) |
| + s_calls, s_input, s_output, s_cost, state, receipt_id, settled_by, created_at, settled_at, project_id,period,cost_unavailable) |
| + VALUES (?,?,?,?,0,?,?,?,?,0,0,0,0,'open','','',?,'',?,?,?)`, |
| + string(j.Account), int64(j.ID), int64(step), int64(attempt), priced.Calls, priced.InputTokens, priced.OutputTokens, priced.CostMicros, ts(now), j.Project, period(now), priced.CostUnavailable) |
| if err != nil { |
| return 0, want, fail(CodeInvalid, "reserve: %v", err) |
| } |
| @@ -142,24 +166,32 @@ func settle(ctx context.Context, tx *sql.Tx, id ReservationID, rc Receipt, now t |
| if rc.Usage == nil { |
| return nil |
| } |
| - u := *rc.Usage |
| + u := settlementUsage(r, *rc.Usage) |
| if err := u.validate(); err != nil { |
| return err |
| } |
| if u.Calls == 0 { |
| u.Calls = 1 |
| } |
| - _, err := tx.ExecContext(ctx, `UPDATE reservations SET s_calls=?, s_input=?, s_output=?, s_cost=?, state='settled', receipt_id=?, settled_by=?, settled_at=? WHERE id=? AND state='open'`, |
| - u.Calls, u.InputTokens, u.OutputTokens, u.CostMicros, rc.ID, "adapter:"+rc.Provider, ts(now), int64(id)) |
| + _, err := tx.ExecContext(ctx, `UPDATE reservations SET s_calls=?, s_input=?, s_output=?, s_cost=?, s_cached=?, state='settled', receipt_id=?, settled_by=?, settled_at=? WHERE id=? AND state='open'`, |
| + u.Calls, u.InputTokens, u.OutputTokens, u.CostMicros, u.CachedInputTokens, rc.ID, "adapter:"+rc.Provider, ts(now), int64(id)) |
| if err != nil { |
| return fail(CodeInvalid, "settle: %v", err) |
| } |
| + j, err := loadJob(ctx, tx, Scope{r.Account, r.Job}) |
| + if err != nil { |
| + return err |
| + } |
| + if j.Policy.Version == 2 && !j.State.Terminal() && (u.Calls > r.Reserved.Calls || u.InputTokens > r.Reserved.InputTokens || u.OutputTokens > r.Reserved.OutputTokens || u.CostMicros > r.Reserved.CostMicros) { |
| + _, err = bumpJob(ctx, tx, j, JobWaiting, WaitBudget, j.Outcome, now) |
| + return err |
| + } |
| return nil |
| case ReservationSettled: |
| if rc.Usage == nil { |
| return nil |
| } |
| - u := *rc.Usage |
| + u := settlementUsage(r, *rc.Usage) |
| if u.Calls == 0 { |
| u.Calls = 1 |
| } |
| @@ -178,15 +210,16 @@ func settle(ctx context.Context, tx *sql.Tx, id ReservationID, rc Receipt, now t |
| func loadReservation(ctx context.Context, tx *sql.Tx, id ReservationID) (Reservation, error) { |
| var r Reservation |
| var state, created, settled string |
| - err := tx.QueryRowContext(ctx, `SELECT id, account, job_id, step_id, attempt_id, action_id, r_calls, r_input, r_output, r_cost, s_calls, s_input, s_output, s_cost, state, receipt_id, settled_by, created_at, settled_at FROM reservations WHERE id=?`, int64(id)). |
| + err := tx.QueryRowContext(ctx, `SELECT id, account, job_id, step_id, attempt_id, action_id, r_calls, r_input, r_output, r_cost, s_calls, s_input, s_output, s_cost, state, receipt_id, settled_by, created_at, settled_at, s_cached, cost_unavailable FROM reservations WHERE id=?`, int64(id)). |
| Scan(&r.ID, &r.Account, &r.Job, &r.Step, &r.Attempt, &r.Action, &r.Reserved.Calls, &r.Reserved.InputTokens, &r.Reserved.OutputTokens, &r.Reserved.CostMicros, |
| - &r.Settled.Calls, &r.Settled.InputTokens, &r.Settled.OutputTokens, &r.Settled.CostMicros, &state, &r.ReceiptID, &r.SettledBy, &created, &settled) |
| + &r.Settled.Calls, &r.Settled.InputTokens, &r.Settled.OutputTokens, &r.Settled.CostMicros, &state, &r.ReceiptID, &r.SettledBy, &created, &settled, &r.Settled.CachedInputTokens, &r.Reserved.CostUnavailable) |
| if errors.Is(err, sql.ErrNoRows) { |
| return r, fail(CodeScope, "reservation %d", id) |
| } |
| if err != nil { |
| return r, fail(CodeInvalid, "reservation: %v", err) |
| } |
| + r.Settled.CostUnavailable = r.Reserved.CostUnavailable |
| r.State = ReservationState(state) |
| if !r.State.Valid() { |
| return r, fail(CodeUnknownKind, "reservation %d state %q", id, state) |
| @@ -243,11 +276,16 @@ func (s *Store) SettleAudited(ctx context.Context, scope Scope, id ReservationID |
| func (s *Store) Ledger(ctx context.Context, scope Scope) (LedgerSummary, error) { |
| var sum LedgerSummary |
| err := s.read(ctx, func(tx *sql.Tx) error { |
| - if _, err := loadJob(ctx, tx, scope); err != nil { |
| + j, err := loadJob(ctx, tx, scope) |
| + if err != nil { |
| return err |
| } |
| - var err error |
| sum, err = ledgerSum(ctx, tx, `job_id IN (SELECT id FROM jobs WHERE id=? OR parent=?)`, int64(scope.Job), int64(scope.Job)) |
| + if j.Policy.UsageMode == "subscription" { |
| + sum.Reserved.CostUnavailable = true |
| + sum.Spent.CostUnavailable = true |
| + sum.Charged.CostUnavailable = true |
| + } |
| return err |
| }) |
| return sum, err |
| @@ -299,3 +337,99 @@ func (s *Store) Reservations(ctx context.Context, scope Scope) ([]Reservation, e |
| }) |
| return out, err |
| } |
| + |
| +func settlementUsage(r Reservation, u Usage) Usage { |
| + u.CostUnavailable = r.Reserved.CostUnavailable |
| + if u.CostUnavailable { |
| + u.CostMicros = 0 |
| + u.Calls = 1 |
| + } |
| + return u |
| +} |
| + |
| +func checkActionSlots(ctx context.Context, tx *sql.Tx, j jobRow, op Operation) error { |
| + var count int64 |
| + if op == OpProviderCall { |
| + if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM actions a JOIN reservations r ON r.id=a.reservation_id WHERE a.job_id=? AND a.operation=? AND r.state!='released'`, j.ID, OpProviderCall).Scan(&count); err != nil { |
| + return err |
| + } |
| + if count >= min(int64(23), j.Policy.Job.Calls-1) { |
| + return fail(CodeBudget, "provider turn ceiling reached") |
| + } |
| + } else { |
| + if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM actions a JOIN reservations r ON r.id=a.reservation_id WHERE a.job_id=? AND a.operation IN (?,?) AND r.state!='released'`, j.ID, OpForgePublish, OpTrackerPublish).Scan(&count); err != nil { |
| + return err |
| + } |
| + if count >= 1 { |
| + return fail(CodeBudget, "publication slot occupied") |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +func boundedTurn(ctx context.Context, tx *sql.Tx, j jobRow, now time.Time) (Usage, error) { |
| + want := Usage{Calls: 1, InputTokens: j.Policy.PerCall.InputTokens, OutputTokens: j.Policy.PerCall.OutputTokens} |
| + clip := func(charged Usage, cap Limits) error { |
| + if charged.Calls >= cap.Calls || charged.InputTokens >= cap.InputTokens || charged.OutputTokens >= cap.OutputTokens { |
| + return fail(CodeBudget, "no positive turn headroom") |
| + } |
| + want.InputTokens = min(want.InputTokens, cap.InputTokens-charged.InputTokens) |
| + want.OutputTokens = min(want.OutputTokens, cap.OutputTokens-charged.OutputTokens) |
| + return nil |
| + } |
| + for cur := j; ; { |
| + sum, err := ledgerSum(ctx, tx, `job_id IN (SELECT id FROM jobs WHERE id=? OR parent=?)`, cur.ID, cur.ID) |
| + if err != nil { |
| + return want, err |
| + } |
| + if err = clip(sum.Charged, cur.Policy.Job); err != nil { |
| + return want, err |
| + } |
| + if cur.Parent == 0 { |
| + break |
| + } |
| + cur, err = loadJob(ctx, tx, Scope{cur.Account, cur.Parent}) |
| + if err != nil { |
| + return want, err |
| + } |
| + } |
| + b, configured, err := loadBudgets(ctx, tx, j.Account) |
| + if err != nil { |
| + return want, err |
| + } |
| + if configured { |
| + project, ok := b.Projects[j.Project] |
| + if !ok { |
| + return want, fail(CodeBudget, "project budget unavailable") |
| + } |
| + for _, c := range []struct { |
| + id ProjectID |
| + cap PeriodLimits |
| + }{{0, b.Team}, {j.Project, project}} { |
| + sum, err := periodSum(ctx, tx, j.Account, c.id, now) |
| + if err != nil { |
| + return want, err |
| + } |
| + total, err := sum.Reserved.add(sum.Spent) |
| + if err != nil { |
| + return want, err |
| + } |
| + if err = clip(Usage{Calls: total.Calls, InputTokens: total.InputTokens, OutputTokens: total.OutputTokens}, Limits{Calls: c.cap.Calls, InputTokens: c.cap.InputTokens, OutputTokens: c.cap.OutputTokens}); err != nil { |
| + return want, err |
| + } |
| + } |
| + } else { |
| + sum, err := ledgerSum(ctx, tx, `account=?`, string(j.Account)) |
| + if err != nil { |
| + return want, err |
| + } |
| + p, err := accountPolicy(ctx, tx, j.Account) |
| + if err != nil { |
| + return want, err |
| + } |
| + if err = clip(sum.Charged, p.Account); err != nil { |
| + return want, err |
| + } |
| + } |
| + return want, nil |
| +} |
diff --git a/internal/equipo/team/harness_test.go b/internal/equipo/team/harness_test.go| index 46b708c3..1aa359b1 100644 |
| --- a/internal/equipo/team/harness_test.go |
| +++ b/internal/equipo/team/harness_test.go |
| @@ -166,8 +166,17 @@ var _ = errors.Is |
| func dropRecoverySchema(t *testing.T, db *sql.DB) { |
| t.Helper() |
| + dropRunnerPolicySchema(t, db) |
| for _, q := range []string{`DROP TABLE recovery_events`, `DROP TABLE recovery_charges`, `DROP TABLE grant_fences`, `ALTER TABLE service DROP COLUMN release_required`, `ALTER TABLE service DROP COLUMN recovery_revision`, `ALTER TABLE service DROP COLUMN reconciled_revision`, `ALTER TABLE service DROP COLUMN clock_high_water`, `ALTER TABLE jobs DROP COLUMN grant_stale`, `ALTER TABLE time_reservations DROP COLUMN elapsed_unknown`} { |
| _, err := db.Exec(q) |
| must(t, err) |
| } |
| } |
| + |
| +func dropRunnerPolicySchema(t *testing.T, db *sql.DB) { |
| + t.Helper() |
| + for _, q := range []string{"DROP INDEX reservations_period_account", "DROP INDEX reservations_period_project", "DROP INDEX time_period_account", "DROP INDEX time_period_project", "DROP INDEX recovery_charges_scope", "ALTER TABLE reservations DROP COLUMN project_id", "ALTER TABLE reservations DROP COLUMN period", "ALTER TABLE reservations DROP COLUMN cost_unavailable", "ALTER TABLE reservations DROP COLUMN s_cached", "ALTER TABLE period_budgets DROP COLUMN content_hash"} { |
| + _, err := db.Exec(q) |
| + must(t, err) |
| + } |
| +} |
diff --git a/internal/equipo/team/jobs.go b/internal/equipo/team/jobs.go| index 51c3bc88..67ce8019 100644 |
| --- a/internal/equipo/team/jobs.go |
| +++ b/internal/equipo/team/jobs.go |
| @@ -134,15 +134,21 @@ func (s *Store) CreateJob(ctx context.Context, spec JobSpec) (Job, error) { |
| if err := checkGrantFence(ctx, tx, adm); err != nil { |
| return err |
| } |
| - account, err := accountPolicy(ctx, tx, spec.Account) |
| - if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| + _, configuredAccount, err := loadBudgets(ctx, tx, spec.Account) |
| + if err != nil { |
| return err |
| } |
| - if err == nil && spec.Policy.Account != account.Account { |
| - return fail(CodeConflict, "job cannot change the account budget") |
| - } |
| - if err == nil && (spec.Policy.Rates != account.Rates || spec.Policy.PerCall != account.PerCall) { |
| - return fail(CodeConflict, "job cannot change account prices or per-call ceilings") |
| + if !configuredAccount { |
| + account, err := accountPolicy(ctx, tx, spec.Account) |
| + if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| + return err |
| + } |
| + if err == nil && spec.Policy.Account != account.Account { |
| + return fail(CodeConflict, "job cannot change the account budget") |
| + } |
| + if err == nil && (spec.Policy.Rates != account.Rates || spec.Policy.PerCall != account.PerCall || spec.Policy.UsageMode != account.UsageMode) { |
| + return fail(CodeConflict, "job cannot change account prices or per-call ceilings") |
| + } |
| } |
| depth := 0 |
| if spec.Parent != 0 { |
| @@ -245,7 +251,7 @@ func scanJob(r rowScanner) (jobRow, error) { |
| if !j.State.Valid() || !j.Wait.Valid() { |
| return j, fail(CodeUnknownKind, "job %d stored state %q/%q", j.ID, state, wait) |
| } |
| - if j.PolicyVersion != PolicyVersion { |
| + if j.PolicyVersion != 1 && j.PolicyVersion != PolicyVersion { |
| return j, fail(CodeUnknownKind, "job %d policy version %d", j.ID, j.PolicyVersion) |
| } |
| if err := strictJSON([]byte(target), &j.Target); err != nil { |
| @@ -264,6 +270,9 @@ func scanJob(r rowScanner) (jobRow, error) { |
| if err != nil { |
| return j, err |
| } |
| + if p.Version != j.PolicyVersion { |
| + return j, fail(CodeInvalid, "policy version mismatch") |
| + } |
| j.Policy = p |
| j.Grant.ObservedAt = parseTS(observed) |
| j.CreatedAt, j.UpdatedAt = parseTS(created), parseTS(updated) |
diff --git a/internal/equipo/team/model.go b/internal/equipo/team/model.go| index b0ff34e5..c21ef6d6 100644 |
| --- a/internal/equipo/team/model.go |
| +++ b/internal/equipo/team/model.go |
| @@ -807,14 +807,16 @@ type Discrepancy struct { |
| // configured currency. All fields are non-negative; arithmetic on them is |
| // checked and refuses overflow. |
| type Usage struct { |
| - Calls int64 `json:"calls"` |
| - InputTokens int64 `json:"input_tokens"` |
| - OutputTokens int64 `json:"output_tokens"` |
| - CostMicros int64 `json:"cost_micros"` |
| + CachedInputTokens int64 `json:"cached_input_tokens,omitempty"` |
| + CostUnavailable bool `json:"cost_unavailable,omitempty"` |
| + Calls int64 `json:"calls"` |
| + InputTokens int64 `json:"input_tokens"` |
| + OutputTokens int64 `json:"output_tokens"` |
| + CostMicros int64 `json:"cost_micros"` |
| } |
| func (u Usage) validate() error { |
| - if u.Calls < 0 || u.InputTokens < 0 || u.OutputTokens < 0 || u.CostMicros < 0 { |
| + if u.CachedInputTokens < 0 || u.Calls < 0 || u.InputTokens < 0 || u.OutputTokens < 0 || u.CostMicros < 0 { |
| return fail(CodeInvalid, "negative usage") |
| } |
| return nil |
| @@ -822,7 +824,11 @@ func (u Usage) validate() error { |
| func (u Usage) add(v Usage) (Usage, error) { |
| var out Usage |
| + out.CostUnavailable = u.CostUnavailable || v.CostUnavailable |
| var err error |
| + if out.CachedInputTokens, err = addChecked(u.CachedInputTokens, v.CachedInputTokens); err != nil { |
| + return out, err |
| + } |
| if out.Calls, err = addChecked(u.Calls, v.Calls); err != nil { |
| return out, err |
| } |
diff --git a/internal/equipo/team/periodbudget.go b/internal/equipo/team/periodbudget.go| index c4bbf522..b78f23e7 100644 |
| --- a/internal/equipo/team/periodbudget.go |
| +++ b/internal/equipo/team/periodbudget.go |
| @@ -89,9 +89,9 @@ CREATE INDEX IF NOT EXISTS time_reservations_account ON time_reservations(accoun |
| func loadBudgets(ctx context.Context, tx *sql.Tx, account AccountID) (BudgetSet, bool, error) { |
| var b BudgetSet |
| - var raw string |
| + var raw, hash string |
| var revision int64 |
| - err := tx.QueryRowContext(ctx, `SELECT revision, config FROM period_budgets WHERE account=?`, string(account)).Scan(&revision, &raw) |
| + err := tx.QueryRowContext(ctx, `SELECT revision, config, content_hash FROM period_budgets WHERE account=?`, string(account)).Scan(&revision, &raw, &hash) |
| if errors.Is(err, sql.ErrNoRows) { |
| return b, false, nil |
| } |
| @@ -101,6 +101,9 @@ func loadBudgets(ctx context.Context, tx *sql.Tx, account AccountID) (BudgetSet, |
| if err := strictJSON([]byte(raw), &b); err != nil { |
| return b, false, fail(CodeInvalid, "stored budgets: %v", err) |
| } |
| + if hash != "" && hash != hashBytes([]byte(raw)) { |
| + return b, false, fail(CodeInvalid, "budget content hash mismatch") |
| + } |
| if b.Revision != revision || revision <= 0 { |
| return b, false, fail(CodeInvalid, "stored budget revision") |
| } |
| @@ -138,7 +141,7 @@ func (s *Store) ConfigureBudgetsTx(ctx context.Context, tx *sql.Tx, account Acco |
| if err != nil { |
| return err |
| } |
| - _, err = tx.ExecContext(ctx, `INSERT INTO period_budgets(account,revision,config) VALUES(?,?,?) ON CONFLICT(account) DO UPDATE SET revision=excluded.revision, config=excluded.config`, string(account), budgets.Revision, string(raw)) |
| + _, err = tx.ExecContext(ctx, `INSERT INTO period_budgets(account,revision,config,content_hash) VALUES(?,?,?,?) ON CONFLICT(account) DO UPDATE SET revision=excluded.revision, config=excluded.config,content_hash=excluded.content_hash`, string(account), budgets.Revision, string(raw), hashBytes(raw)) |
| if err != nil { |
| return err |
| } |
| @@ -149,7 +152,13 @@ func period(at time.Time) string { return at.UTC().Format("2006-01") } |
| func periodSum(ctx context.Context, tx *sql.Tx, account AccountID, project ProjectID, at time.Time) (PeriodUsage, error) { |
| var sum PeriodUsage |
| - charges, err := tx.QueryContext(ctx, `SELECT reserved FROM recovery_charges WHERE account=? AND (?=0 OR project_id=?)`, string(account), project, project) |
| + chargeQuery := "SELECT reserved FROM recovery_charges WHERE account=?" |
| + chargeArgs := []any{string(account)} |
| + if project != 0 { |
| + chargeQuery += " AND project_id=?" |
| + chargeArgs = append(chargeArgs, project) |
| + } |
| + charges, err := tx.QueryContext(ctx, chargeQuery, chargeArgs...) |
| if err != nil { |
| return sum, err |
| } |
| @@ -178,73 +187,72 @@ func periodSum(ctx context.Context, tx *sql.Tx, account AccountID, project Proje |
| if err != nil { |
| return sum, err |
| } |
| - rows, err := tx.QueryContext(ctx, `SELECT r.state,r.created_at,r.r_calls,r.r_input,r.r_output,r.s_calls,r.s_input,r.s_output FROM reservations r JOIN jobs j ON j.id=r.job_id WHERE r.account=? AND (?=0 OR j.project_id=?)`, string(account), project, project) |
| - if err != nil { |
| - return sum, err |
| - } |
| - for rows.Next() { |
| - var state, created string |
| - var r, spent PeriodLimits |
| - if err = rows.Scan(&state, &created, &r.Calls, &r.InputTokens, &r.OutputTokens, &spent.Calls, &spent.InputTokens, &spent.OutputTokens); err != nil { |
| - break |
| - } |
| - stamp := parseTS(created) |
| - if stamp.IsZero() { |
| - err = fail(CodeInvalid, "invalid reservation timestamp") |
| - break |
| - } |
| - switch ReservationState(state) { |
| - case ReservationOpen: |
| - sum.Reserved, err = sum.Reserved.add(r) |
| - case ReservationSettled, ReservationSettledAudited: |
| - if period(stamp) == period(at) { |
| - sum.Spent, err = sum.Spent.add(spent) |
| + for _, table := range []string{"reservations", "time_reservations"} { |
| + for _, settled := range []bool{false, true} { |
| + q, args := periodQuery(table, account, project, at, settled) |
| + rows, err := tx.QueryContext(ctx, q, args...) |
| + if err != nil { |
| + return sum, err |
| } |
| - case ReservationReleased: |
| - default: |
| - err = fail(CodeUnknownKind, "reservation state %q", state) |
| - } |
| - if err != nil { |
| - break |
| - } |
| - } |
| - if err == nil { |
| - err = rows.Err() |
| - } |
| - rows.Close() |
| - if err != nil { |
| - return sum, err |
| - } |
| - rows, err = tx.QueryContext(ctx, `SELECT state,period,reserved_seconds,settled_seconds FROM time_reservations WHERE account=? AND (?=0 OR project_id=?)`, string(account), project, project) |
| - if err != nil { |
| - return sum, err |
| - } |
| - defer rows.Close() |
| - for rows.Next() { |
| - var state, month string |
| - var r, spent int64 |
| - if err := rows.Scan(&state, &month, &r, &spent); err != nil { |
| - return sum, err |
| - } |
| - if _, err := time.Parse("2006-01", month); err != nil { |
| - return sum, fail(CodeInvalid, "invalid time reservation period") |
| - } |
| - switch state { |
| - case "open": |
| - sum.Reserved, err = sum.Reserved.add(PeriodLimits{Seconds: r}) |
| - case "settled": |
| - if month == period(at) { |
| - sum.Spent, err = sum.Spent.add(PeriodLimits{Seconds: spent}) |
| + for rows.Next() { |
| + var u PeriodLimits |
| + if table == "reservations" { |
| + err = rows.Scan(&u.Calls, &u.InputTokens, &u.OutputTokens) |
| + } else { |
| + err = rows.Scan(&u.Seconds) |
| + } |
| + if err != nil { |
| + break |
| + } |
| + if settled { |
| + sum.Spent, err = sum.Spent.add(u) |
| + } else { |
| + sum.Reserved, err = sum.Reserved.add(u) |
| + } |
| + if err != nil { |
| + break |
| + } |
| + } |
| + if err == nil { |
| + err = rows.Err() |
| + } |
| + rows.Close() |
| + if err != nil { |
| + return sum, err |
| } |
| - default: |
| - err = fail(CodeUnknownKind, "time reservation state %q", state) |
| - } |
| - if err != nil { |
| - return sum, err |
| } |
| } |
| - return sum, rows.Err() |
| + return sum, nil |
| } |
| + |
| +func periodQuery(table string, account AccountID, project ProjectID, at time.Time, settled bool) (string, []any) { |
| + columns := "r_calls,r_input,r_output" |
| + states := "state='open'" |
| + if settled { |
| + columns = "s_calls,s_input,s_output" |
| + states = "state IN ('settled','settled_audited')" |
| + } |
| + if table == "time_reservations" { |
| + columns = "reserved_seconds" |
| + if settled { |
| + columns = "settled_seconds" |
| + states = "state='settled'" |
| + } |
| + } |
| + q := "SELECT " + columns + " FROM " + table + " WHERE account=?" |
| + args := []any{string(account)} |
| + if project != 0 { |
| + q += " AND project_id=?" |
| + args = append(args, project) |
| + } |
| + q += " AND " + states |
| + if settled { |
| + q += " AND period=?" |
| + args = append(args, period(at)) |
| + } |
| + return q, args |
| +} |
| + |
| func (s *Store) PeriodUsage(ctx context.Context, account AccountID, project ProjectID, at time.Time) (PeriodUsage, error) { |
| var sum PeriodUsage |
| if account == "" || project < 0 || at.IsZero() { |
| @@ -414,12 +422,37 @@ func (s *Store) SyncBudgetsTx(ctx context.Context, tx *sql.Tx, account AccountID |
| return err |
| } |
| if string(previous) == string(raw) { |
| - return nil |
| + _, err = tx.ExecContext(ctx, `UPDATE period_budgets SET config=?,content_hash=? WHERE account=? AND content_hash=''`, string(raw), hashBytes(raw), string(account)) |
| + return err |
| } |
| return fail(CodeRevision, "budget revision changed") |
| } |
| - if _, err = tx.ExecContext(ctx, `INSERT INTO period_budgets(account,revision,config) VALUES(?,?,?) ON CONFLICT(account) DO UPDATE SET revision=excluded.revision,config=excluded.config`, string(account), budgets.Revision, string(raw)); err != nil { |
| + if _, err = tx.ExecContext(ctx, `INSERT INTO period_budgets(account,revision,config,content_hash) VALUES(?,?,?,?) ON CONFLICT(account) DO UPDATE SET revision=excluded.revision,config=excluded.config,content_hash=excluded.content_hash`, string(account), budgets.Revision, string(raw), hashBytes(raw)); err != nil { |
| return err |
| } |
| return advanceRecovery(ctx, tx) |
| } |
| + |
| +// ConfiguredBudgets returns saved limits, or ErrBudget when none are configured. |
| +func (s *Store) ConfiguredBudgets(ctx context.Context, account AccountID) (BudgetSet, error) { |
| + var b BudgetSet |
| + if account == "" { |
| + return b, fail(CodeScope, "empty account") |
| + } |
| + err := s.read(ctx, func(tx *sql.Tx) error { |
| + var ok bool |
| + var err error |
| + b, ok, err = loadBudgets(ctx, tx, account) |
| + if err != nil { |
| + return err |
| + } |
| + if !ok { |
| + return fail(CodeBudget, "period budgets unavailable") |
| + } |
| + return nil |
| + }) |
| + if err != nil { |
| + return BudgetSet{}, err |
| + } |
| + return b, nil |
| +} |
diff --git a/internal/equipo/team/periodquery_test.go b/internal/equipo/team/periodquery_test.go| new file mode 100644 |
| index 00000000..399274ff |
| --- /dev/null |
| +++ b/internal/equipo/team/periodquery_test.go |
| @@ -0,0 +1,142 @@ |
| +package team |
| + |
| +import ( |
| + "database/sql" |
| + "math" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestPeriodQueriesBoundedHistory(t *testing.T) { |
| + e := newEnv(t) |
| + must(t, e.store.ConfigureBudgets(e.ctx, acctA, 0, periodSet())) |
| + s, h := periodJob(e, 1) |
| + id, err := e.store.Intend(e.ctx, s, h, intent("seed", Usage{InputTokens: 7, OutputTokens: 3})) |
| + must(t, err) |
| + a, err := e.store.GetAction(e.ctx, s, id) |
| + must(t, err) |
| + _, err = e.store.Intend(e.ctx, s, h, intent("current", Usage{InputTokens: 2, OutputTokens: 1})) |
| + must(t, err) |
| + must(t, e.store.tx(e.ctx, func(tx *sql.Tx) error { |
| + _, err := tx.Exec(`UPDATE reservations SET period='2020-01',created_at='2020-01-01T00:00:00Z' WHERE id=?`, a.Reservation) |
| + if err != nil { |
| + return err |
| + } |
| + _, err = tx.Exec(`WITH RECURSIVE n(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM n WHERE x<100000) |
| + INSERT INTO reservations(account,job_id,step_id,attempt_id,action_id,r_calls,r_input,r_output,r_cost,s_calls,s_input,s_output,s_cost,state,receipt_id,settled_by,created_at,settled_at,project_id,period) |
| + SELECT account,job_id,step_id,attempt_id,0,1,7,3,0,1,7,3,0,'settled','','','2020-01-01T00:00:00Z','2020-01-01T00:00:00Z',1,'2020-01' FROM reservations,n WHERE id=?`, a.Reservation) |
| + if err != nil { |
| + return err |
| + } |
| + _, err = tx.Exec(`UPDATE reservations SET state='settled_audited',s_calls=1,s_input=2,s_output=1 WHERE period!='2020-01'`) |
| + if err != nil { |
| + return err |
| + } |
| + _, err = tx.Exec(`UPDATE time_reservations SET period='2020-01'`) |
| + return err |
| + })) |
| + for _, project := range []ProjectID{0, 1} { |
| + must(t, e.store.read(e.ctx, func(tx *sql.Tx) error { |
| + for _, table := range []string{"reservations", "time_reservations"} { |
| + for _, settled := range []bool{false, true} { |
| + q, args := periodQuery(table, acctA, project, e.clock.Now(), settled) |
| + rows, err := tx.QueryContext(e.ctx, "EXPLAIN QUERY PLAN "+q, args...) |
| + if err != nil { |
| + return err |
| + } |
| + var plan string |
| + for rows.Next() { |
| + var a, b, c int |
| + var detail string |
| + if err := rows.Scan(&a, &b, &c, &detail); err != nil { |
| + return err |
| + } |
| + plan += detail |
| + } |
| + err = rows.Err() |
| + rows.Close() |
| + if err != nil { |
| + return err |
| + } |
| + if !strings.Contains(plan, "SEARCH") || !strings.Contains(plan, "state=?") || (settled && !strings.Contains(plan, "period=?")) || (project != 0 && !strings.Contains(plan, "project_id=?")) { |
| + t.Fatalf("bounded-history query plan: %s", plan) |
| + } |
| + var count int |
| + if err := tx.QueryRowContext(e.ctx, "SELECT count(*) FROM ("+q+")", args...).Scan(&count); err != nil { |
| + return err |
| + } |
| + if count > 2 { |
| + t.Fatalf("bounded-history query visited %d rows", count) |
| + } |
| + } |
| + } |
| + return nil |
| + })) |
| + u := periodUsage(e, project) |
| + if u.Reserved.Calls != 1 || u.Reserved.InputTokens != 7 || u.Spent.Calls != 1 || u.Spent.InputTokens != 2 || u.Reserved.Seconds != 1200 { |
| + t.Fatal("old open rows lost or old settled rows charged", u) |
| + } |
| + } |
| + must(t, e.store.tx(e.ctx, func(tx *sql.Tx) error { |
| + _, err := tx.Exec(`UPDATE reservations SET state='settled',s_calls=1,s_input=?,period=? WHERE id IN (?,(SELECT max(id) FROM reservations))`, math.MaxInt64, period(e.clock.Now()), a.Reservation) |
| + return err |
| + })) |
| + _, err = e.store.PeriodUsage(e.ctx, acctA, 0, e.clock.Now()) |
| + wantCode(t, err, CodeOverflow) |
| +} |
| + |
| +func TestPeriodQueriesBackfill(t *testing.T) { |
| + for _, tc := range []struct { |
| + name, stamp, month string |
| + bad bool |
| + }{{"valid", "2026-11-01T00:00:00Z", "2026-11", false}, {"fraction at month end", "2026-10-31T23:59:59.999999999Z", "2026-10", false}, {"invalid", "invalid", "", true}, {"invalid date", "2026-02-31T00:00:00Z", "", true}, {"missing time", "2026-11-01", "", true}} { |
| + t.Run(tc.name, func(t *testing.T) { |
| + e := newEnv(t) |
| + s, h := periodJob(e, 1) |
| + _, err := e.store.Intend(e.ctx, s, h, intent("old", Usage{InputTokens: 2})) |
| + must(t, err) |
| + must(t, e.store.Close()) |
| + e.store = nil |
| + db, err := sql.Open("sqlite", e.path) |
| + must(t, err) |
| + defer db.Close() |
| + dropRunnerPolicySchema(t, db) |
| + _, err = db.Exec("UPDATE service SET schema_version=4") |
| + must(t, err) |
| + _, err = db.Exec(`UPDATE reservations SET created_at=?`, tc.stamp) |
| + must(t, err) |
| + core, err := Open(e.ctx, e.path, e.options()) |
| + if tc.bad { |
| + if err == nil { |
| + core.Close() |
| + t.Fatal("invalid timestamp backfilled") |
| + } |
| + return |
| + } |
| + must(t, err) |
| + defer core.Close() |
| + var project int |
| + var month string |
| + must(t, db.QueryRow(`SELECT project_id,period FROM reservations`).Scan(&project, &month)) |
| + if project != 1 || month != tc.month { |
| + t.Fatal("wrong backfill", project, month) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPeriodQueriesSharedIndexes(t *testing.T) { |
| + for _, index := range []string{"reservations_period_account", "reservations_period_project", "time_period_account", "time_period_project", "recovery_charges_scope"} { |
| + t.Run(index, func(t *testing.T) { |
| + e, writer := sharedFixture(t) |
| + _, err := writer.Exec("DROP INDEX " + index) |
| + must(t, err) |
| + core, err := OpenShared(e.ctx, writer, e.path, e.options()) |
| + if err == nil { |
| + core.Close() |
| + t.Fatal("attachment accepted missing period index") |
| + } |
| + wantCode(t, err, CodeStaleStore) |
| + }) |
| + } |
| +} |
diff --git a/internal/equipo/team/policy.go b/internal/equipo/team/policy.go| index 0aa37c43..af0ce60e 100644 |
| --- a/internal/equipo/team/policy.go |
| +++ b/internal/equipo/team/policy.go |
| @@ -4,9 +4,8 @@ import ( |
| "time" |
| ) |
| -// PolicyVersion is the one policy shape this binary understands. A stored |
| -// policy with another version, or any field outside Policy, fails closed. |
| -const PolicyVersion = 1 |
| +// PolicyVersion is the current policy version. Version 1 remains readable. |
| +const PolicyVersion = 2 |
| // Byte limits. Payloads, events and artifacts above these are refused |
| // before any state changes. |
| @@ -20,10 +19,11 @@ const ( |
| // Policy is a job's finite execution policy. It is bound at creation, |
| // stored with the job, and compared by version at every admission. The |
| // Rates make the currency reservation explicit: a reservation's cost is |
| -// computed from its token and call maxima at these rates, and a policy |
| -// without a positive cost cap is refused. |
| +// computed from its token and call maxima. Subscription currency is unavailable. |
| type Policy struct { |
| - Version int `json:"version"` |
| + Version int `json:"version"` |
| + UsageMode string `json:"usage_mode,omitempty"` |
| + RequireDistinctReviewFamily bool `json:"require_distinct_review_family,omitempty"` |
| // Job caps the job's own ledger (its reservations plus its children's). |
| Job Limits `json:"job"` |
| // Account caps the account's ledger across all its jobs. |
| @@ -63,7 +63,7 @@ type Rates struct { |
| // are the caller's: there is no default currency ceiling. |
| func DefaultPolicy(costCapMicros int64, rates Rates) Policy { |
| return Policy{ |
| - Version: PolicyVersion, |
| + Version: 1, |
| Job: Limits{Calls: 24, InputTokens: 200_000, OutputTokens: 40_000, CostMicros: costCapMicros}, |
| Account: Limits{Calls: 24, InputTokens: 200_000, OutputTokens: 40_000, CostMicros: costCapMicros}, |
| PerCall: Limits{Calls: 1, InputTokens: 32_000, OutputTokens: 4_000, CostMicros: costCapMicros}, |
| @@ -79,24 +79,38 @@ func DefaultPolicy(costCapMicros int64, rates Rates) Policy { |
| } |
| } |
| -// Validate checks the policy is finite, explicit and the known version. |
| +// Validate checks finite limits and the accounting rules for each version. |
| func (p Policy) Validate() error { |
| - if p.Version != PolicyVersion { |
| + if p.Version != 1 && p.Version != PolicyVersion { |
| return fail(CodeUnknownKind, "policy version %d", p.Version) |
| } |
| - if err := p.Job.validate("job"); err != nil { |
| - return err |
| + if p.Version == 1 && (p.UsageMode != "" || p.RequireDistinctReviewFamily) { |
| + return fail(CodeInvalid, "v2 fields in v1 policy") |
| } |
| - if err := p.Account.validate("account"); err != nil { |
| - return err |
| + if p.Version == 2 && p.UsageMode != "metered" && p.UsageMode != "subscription" { |
| + return fail(CodeUnknownKind, "usage mode %q", p.UsageMode) |
| } |
| - if err := p.PerCall.validate("per_call"); err != nil { |
| - return err |
| + for name, l := range map[string]Limits{"job": p.Job, "account": p.Account, "per_call": p.PerCall} { |
| + if p.UsageMode == "subscription" { |
| + if l.CostMicros != 0 { |
| + return fail(CodeInvalid, "subscription currency must be unavailable") |
| + } |
| + l.CostMicros = 1 |
| + } |
| + if err := l.validate(name); err != nil { |
| + return err |
| + } |
| + } |
| + if p.Version == 2 && p.UsageMode == "metered" && (p.Rates.InputMicrosPer <= 0 || p.Rates.OutputMicrosPer <= 0 || p.Rates.CallMicrosPer <= 0) { |
| + return fail(CodeInvalid, "metered rates must be positive") |
| + } |
| + if p.UsageMode == "subscription" && p.Rates != (Rates{}) { |
| + return fail(CodeInvalid, "subscription has no currency rates") |
| } |
| if p.PerCall.Calls != 1 { |
| return fail(CodeInvalid, "per_call.calls must be 1") |
| } |
| - if p.Rates.Version <= 0 || p.Rates.InputMicrosPer < 0 || p.Rates.OutputMicrosPer < 0 || p.Rates.CallMicrosPer < 0 || p.Rates.ForgeMicrosPer < 0 || p.Rates.TrackerMicrosPer < 0 { |
| + if p.UsageMode != "subscription" && (p.Rates.Version <= 0 || p.Rates.InputMicrosPer < 0 || p.Rates.OutputMicrosPer < 0 || p.Rates.CallMicrosPer < 0 || p.Rates.ForgeMicrosPer < 0 || p.Rates.TrackerMicrosPer < 0) { |
| return fail(CodeInvalid, "rates need a positive version and non-negative prices") |
| } |
| if p.MaxAttemptsPerStep <= 0 || p.MaxConcurrentAttempts <= 0 || p.MaxDepth < 0 || p.LeaseSeconds <= 0 || p.AdmissionSeconds <= 0 || p.AdmissionSeconds > 5 || p.JobSeconds <= 0 || p.AttemptSeconds <= 0 { |
| @@ -138,6 +152,15 @@ func (p Policy) admission() time.Duration { return time.Duration(p.AdmissionSeco |
| // reservation at the policy's rates, with overflow checks. The caller's own |
| // CostMicros is added on top (an adapter-declared fixed charge). |
| func (p Policy) price(op Operation, u Usage) (Usage, error) { |
| + if p.UsageMode == "subscription" { |
| + if !op.external() { |
| + return Usage{}, fail(CodeUnknownKind, "unpriced operation") |
| + } |
| + u.CostMicros = 0 |
| + u.CostUnavailable = true |
| + return u, nil |
| + } |
| + u.CostUnavailable = false |
| var perCall int64 |
| switch op { |
| case OpProviderCall: |
| @@ -182,3 +205,19 @@ func (p Policy) reserveLimits(op Operation) Limits { |
| return Limits{Calls: 1, InputTokens: 0, OutputTokens: 0, CostMicros: p.PerCall.CostMicros} |
| } |
| } |
| + |
| +// RunnerPolicy requires explicit token limits calibrated for the runner. |
| +func RunnerPolicy(mode string, limits, perTurn Limits, rates Rates) (Policy, error) { |
| + p := Policy{ |
| + Version: PolicyVersion, UsageMode: mode, |
| + Job: limits, Account: limits, PerCall: perTurn, Rates: rates, |
| + MaxAttemptsPerStep: 2, MaxConcurrentAttempts: 2, MaxDepth: 0, |
| + LeaseSeconds: 60, AdmissionSeconds: 5, JobSeconds: 2700, AttemptSeconds: 1200, |
| + RequireDistinctReviewProvider: true, RequireDistinctReviewFamily: true, |
| + } |
| + p.Job.Calls = min(p.Job.Calls, 24) |
| + if err := p.Validate(); err != nil { |
| + return Policy{}, err |
| + } |
| + return p, nil |
| +} |
diff --git a/internal/equipo/team/shared.go b/internal/equipo/team/shared.go| index 80bd7e7b..97152b19 100644 |
| --- a/internal/equipo/team/shared.go |
| +++ b/internal/equipo/team/shared.go |
| @@ -206,7 +206,7 @@ var sharedSchemaQueries = []string{ |
| `SELECT |
| period_budgets."account", |
| period_budgets."revision", |
| - period_budgets."config" |
| + period_budgets."config", period_budgets."content_hash" |
| FROM period_budgets LIMIT 0`, |
| `SELECT |
| reservations."id", |
| @@ -227,7 +227,7 @@ var sharedSchemaQueries = []string{ |
| reservations."receipt_id", |
| reservations."settled_by", |
| reservations."created_at", |
| - reservations."settled_at" |
| + reservations."settled_at", reservations."project_id", reservations."period", reservations."cost_unavailable", reservations."s_cached" |
| FROM reservations LIMIT 0`, |
| `SELECT |
| service."id", |
| @@ -265,6 +265,11 @@ var sharedSchemaQueries = []string{ |
| } |
| var sharedSchemaIndexes = []string{ |
| + "reservations_period_account", |
| + "reservations_period_project", |
| + "time_period_account", |
| + "time_period_project", |
| + "recovery_charges_scope", |
| "actions_state", |
| "artifacts_job", |
| "attempts_job", |
diff --git a/internal/equipo/team/shared_test.go b/internal/equipo/team/shared_test.go| index fa86f295..be7bd18d 100644 |
| --- a/internal/equipo/team/shared_test.go |
| +++ b/internal/equipo/team/shared_test.go |
| @@ -165,7 +165,7 @@ func TestExecutionSharedCrashHelper(t *testing.T) { |
| return nil |
| } |
| must(t, s.WithTransaction(context.Background(), func(tx *sql.Tx) error { |
| - _, err := tx.Exec(`INSERT INTO period_budgets VALUES ('crash-payload', 1, '{}')`) |
| + _, err := tx.Exec(`INSERT INTO period_budgets(account,revision,config) VALUES ('crash-payload', 1, '{}')`) |
| return err |
| })) |
| t.Fatal("crash boundary not reached") |
diff --git a/internal/equipo/team/store.go b/internal/equipo/team/store.go| index dd3dce57..f67b542e 100644 |
| --- a/internal/equipo/team/store.go |
| +++ b/internal/equipo/team/store.go |
| @@ -19,7 +19,7 @@ import ( |
| // SchemaVersion is the one schema this binary writes. A database with a |
| // newer version is refused (ErrStaleStore): the binary would not know the |
| // rows it was reading. |
| -const SchemaVersion = 4 |
| +const SchemaVersion = 5 |
| // Adapter executes one operation class against an external system. Execute |
| // runs an admitted dispatch and returns its receipt; an error from Execute |
| @@ -310,7 +310,7 @@ func (s *Store) migrate(ctx context.Context) error { |
| return err |
| } |
| v = 2 |
| - case v != 2 && v != 3 && v != SchemaVersion: |
| + case v != 2 && v != 3 && v != 4 && v != SchemaVersion: |
| return fail(CodeStaleStore, "unsupported schema %d", v) |
| } |
| rows, err := tx.QueryContext(ctx, `PRAGMA table_info(jobs)`) |
| @@ -359,6 +359,12 @@ func (s *Store) migrate(ctx context.Context) error { |
| } |
| _, err = tx.ExecContext(ctx, `UPDATE service SET schema_version=4 WHERE id=1`) |
| } |
| + if err != nil { |
| + return err |
| + } |
| + if v < 5 { |
| + _, err = tx.ExecContext(ctx, runnerPolicySchema) |
| + } |
| return err |
| }) |
| } |
| @@ -617,3 +623,37 @@ func parseTS(s string) time.Time { |
| } |
| return t |
| } |
| + |
| +const runnerPolicySchema = ` |
| +ALTER TABLE reservations ADD COLUMN project_id INTEGER NOT NULL DEFAULT 0; |
| +ALTER TABLE reservations ADD COLUMN period TEXT NOT NULL DEFAULT ""; |
| +ALTER TABLE reservations ADD COLUMN cost_unavailable INTEGER NOT NULL DEFAULT 0; |
| +ALTER TABLE reservations ADD COLUMN s_cached INTEGER NOT NULL DEFAULT 0; |
| +ALTER TABLE period_budgets ADD COLUMN content_hash TEXT NOT NULL DEFAULT ""; |
| +CREATE TABLE runner_policy_validation (valid INTEGER NOT NULL CHECK(valid=1)); |
| +INSERT INTO runner_policy_validation SELECT CASE WHEN EXISTS ( |
| + SELECT 1 FROM reservations r LEFT JOIN jobs j ON j.id=r.job_id |
| + WHERE j.id IS NULL OR j.account!=r.account OR j.project_id<0 |
| + OR length(r.created_at)<20 OR substr(r.created_at,-1)!='Z' |
| + OR substr(r.created_at,1,19) NOT GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9]' |
| + OR substr(r.created_at,12,2)>'23' OR substr(r.created_at,15,2)>'59' OR substr(r.created_at,18,2)>'59' |
| + OR date(substr(r.created_at,1,10),'+0 days')!=substr(r.created_at,1,10) |
| + OR (length(r.created_at)!=20 AND (length(r.created_at)<22 OR length(r.created_at)>30 |
| + OR substr(r.created_at,20,1)!='.' OR substr(r.created_at,21,length(r.created_at)-21) GLOB '*[^0-9]*')) |
| + OR strftime('%Y-%m',substr(r.created_at,1,19)||'Z') IS NULL |
| + OR r.state NOT IN ('open','settled','settled_audited','released') |
| +) OR EXISTS ( |
| + SELECT 1 FROM time_reservations r LEFT JOIN jobs j ON j.id=r.job_id |
| + WHERE j.id IS NULL OR j.account!=r.account OR j.project_id!=r.project_id |
| + OR r.project_id<0 OR length(r.period)!=7 OR strftime('%Y-%m',r.period||'-01') IS NULL |
| + OR r.state NOT IN ('open','settled') |
| +) THEN 0 ELSE 1 END; |
| +DROP TABLE runner_policy_validation; |
| +UPDATE reservations SET project_id=(SELECT project_id FROM jobs WHERE id=reservations.job_id), period=substr(created_at,1,7); |
| +CREATE INDEX reservations_period_account ON reservations(account,state,period); |
| +CREATE INDEX reservations_period_project ON reservations(account,project_id,state,period); |
| +CREATE INDEX time_period_account ON time_reservations(account,state,period); |
| +CREATE INDEX time_period_project ON time_reservations(account,project_id,state,period); |
| +CREATE INDEX recovery_charges_scope ON recovery_charges(account,project_id); |
| +UPDATE service SET schema_version=5 WHERE id=1; |
| +` |
diff --git a/internal/equipo/team/subscription_test.go b/internal/equipo/team/subscription_test.go| new file mode 100644 |
| index 00000000..56c67105 |
| --- /dev/null |
| +++ b/internal/equipo/team/subscription_test.go |
| @@ -0,0 +1,329 @@ |
| +package team |
| + |
| +import ( |
| + "database/sql" |
| + "encoding/json" |
| + "math" |
| + "testing" |
| +) |
| + |
| +func runnerPolicy(t *testing.T, mode string) Policy { |
| + t.Helper() |
| + limits := Limits{Calls: 24, InputTokens: 1000, OutputTokens: 500} |
| + perTurn := Limits{Calls: 1, InputTokens: 100, OutputTokens: 50} |
| + rates := Rates{} |
| + if mode == "metered" { |
| + limits.CostMicros = 100000 |
| + perTurn.CostMicros = 10000 |
| + rates = testRates() |
| + } |
| + p, err := RunnerPolicy(mode, limits, perTurn, rates) |
| + must(t, err) |
| + return p |
| +} |
| +func runnerJob(e *env, p Policy) (Scope, Handle) { |
| + e.t.Helper() |
| + spec := softwareSpec(SoftwareSteps(false)) |
| + spec.Project = 1 |
| + spec.Policy = p |
| + _, s := e.createJob(spec) |
| + return s, e.claim(s, "reproduce", "runner", "workspace") |
| +} |
| +func TestSubscriptionPolicy(t *testing.T) { |
| + p := runnerPolicy(t, "subscription") |
| + if p.Version != 2 || p.UsageMode != "subscription" || !p.RequireDistinctReviewFamily || p.AdmissionSeconds != 5 || p.LeaseSeconds != 60 || p.AttemptSeconds != 1200 || p.JobSeconds != 2700 || p.MaxAttemptsPerStep != 2 || p.MaxConcurrentAttempts != 2 || p.MaxDepth != 0 || p.Job.Calls != 24 { |
| + t.Fatalf("runner policy: %+v", p) |
| + } |
| + u, err := p.price(OpProviderCall, Usage{Calls: 1, InputTokens: 10, CostMicros: 900}) |
| + must(t, err) |
| + if u.CostMicros != 0 || !u.CostUnavailable { |
| + t.Fatal("subscription currency fabricated", u) |
| + } |
| + raw, _ := json.Marshal(p) |
| + _, err = ParsePolicy(raw) |
| + must(t, err) |
| + legacy := testPolicy() |
| + if legacy.Version != 1 { |
| + t.Fatal("legacy policy version changed") |
| + } |
| + must(t, legacy.Validate()) |
| + for _, change := range []func(*Policy){func(p *Policy) { p.UsageMode = "unknown" }, func(p *Policy) { p.PerCall.InputTokens = 0 }, func(p *Policy) { p.Job.OutputTokens = 0 }, func(p *Policy) { p.Job.CostMicros = 1 }} { |
| + q := p |
| + change(&q) |
| + if q.Validate() == nil { |
| + t.Fatal("invalid subscription accepted", q) |
| + } |
| + } |
| + metered := runnerPolicy(t, "metered") |
| + metered.Rates.InputMicrosPer = 0 |
| + if metered.Validate() == nil { |
| + t.Fatal("unpriced metered policy accepted") |
| + } |
| + _, err = RunnerPolicy("subscription", Limits{}, Limits{}, Rates{}) |
| + wantCode(t, err, CodeInvalid) |
| +} |
| +func TestMixedConnectionPolicies(t *testing.T) { |
| + for _, first := range []string{"subscription", "metered"} { |
| + t.Run(first, func(t *testing.T) { |
| + e := newEnv(t) |
| + must(t, e.store.ConfigureBudgets(e.ctx, acctA, 0, periodSet())) |
| + second := "metered" |
| + if first == second { |
| + second = "subscription" |
| + } |
| + for _, mode := range []string{first, second} { |
| + p := runnerPolicy(t, mode) |
| + if mode == "metered" { |
| + p.PerCall.InputTokens = 80 |
| + p.PerCall.OutputTokens = 40 |
| + } |
| + s, h := runnerJob(e, p) |
| + id, err := e.store.Intend(e.ctx, s, h, intent("turn", Usage{CostMicros: 75})) |
| + must(t, err) |
| + a, err := e.store.GetAction(e.ctx, s, id) |
| + must(t, err) |
| + var r Reservation |
| + must(t, e.store.read(e.ctx, func(tx *sql.Tx) error { var err error; r, err = loadReservation(e.ctx, tx, a.Reservation); return err })) |
| + if r.Reserved.InputTokens != p.PerCall.InputTokens || r.Reserved.OutputTokens != p.PerCall.OutputTokens || r.Reserved.CostUnavailable != (mode == "subscription") { |
| + t.Fatal("job policy ignored", r) |
| + } |
| + if mode == "metered" && r.Reserved.CostMicros != 1915 { |
| + t.Fatal("wrong job price", r) |
| + } |
| + } |
| + }) |
| + } |
| + e := newEnv(t) |
| + _, _ = runnerJob(e, runnerPolicy(t, "subscription")) |
| + spec := softwareSpec(SoftwareSteps(false)) |
| + spec.Policy = runnerPolicy(t, "metered") |
| + _, err := e.store.CreateJob(e.ctx, spec) |
| + wantCode(t, err, CodeConflict) |
| +} |
| +func TestLoweredBudgetBlocksReservedAdmission(t *testing.T) { |
| + e := newEnv(t) |
| + b := periodSet() |
| + must(t, e.store.ConfigureBudgets(e.ctx, acctA, 0, b)) |
| + s, h := runnerJob(e, runnerPolicy(t, "subscription")) |
| + id, err := e.store.Intend(e.ctx, s, h, intent("turn", Usage{})) |
| + must(t, err) |
| + b.Revision = 1 |
| + b.Team.InputTokens = 99 |
| + for id, p := range b.Projects { |
| + p.InputTokens = 99 |
| + b.Projects[id] = p |
| + } |
| + must(t, e.store.ConfigureBudgets(e.ctx, acctA, 1, b)) |
| + _, err = e.store.Admit(e.ctx, s, id) |
| + wantCode(t, err, CodeBudget) |
| +} |
| +func TestUnknownUsageStillCharged(t *testing.T) { |
| + e := newEnv(t) |
| + s, h := runnerJob(e, runnerPolicy(t, "subscription")) |
| + id, err := e.store.Intend(e.ctx, s, h, intent("first", Usage{})) |
| + must(t, err) |
| + _, err = e.store.Admit(e.ctx, s, id) |
| + must(t, err) |
| + _, err = e.store.Intend(e.ctx, s, h, intent("premature", Usage{})) |
| + wantCode(t, err, CodeUncertain) |
| + must(t, e.store.Lost(e.ctx, s, id, "missing reply")) |
| + _, err = e.store.Intend(e.ctx, s, h, intent("first", Usage{})) |
| + wantCode(t, err, CodeUncertain) |
| + _, err = e.store.Intend(e.ctx, s, h, intent("after lost", Usage{})) |
| + wantCode(t, err, CodeUncertain) |
| + must(t, e.store.Record(e.ctx, s, id, Receipt{ID: "done", Outcome: OutcomeSuccess})) |
| + _, err = e.store.Intend(e.ctx, s, h, intent("follow-up", Usage{})) |
| + must(t, err) |
| + sum, err := e.store.Ledger(e.ctx, s) |
| + must(t, err) |
| + if sum.Reserved.Calls != 2 || sum.Reserved.InputTokens != 200 || !sum.Charged.CostUnavailable { |
| + t.Fatal("unknown usage refunded", sum) |
| + } |
| +} |
| +func TestBoundedTurnReservation(t *testing.T) { |
| + t.Run("job headroom", func(t *testing.T) { |
| + e := newEnv(t) |
| + p := runnerPolicy(t, "subscription") |
| + p.Job.InputTokens = 150 |
| + p.Job.OutputTokens = 70 |
| + s, h := runnerJob(e, p) |
| + for _, key := range []string{"first", "second"} { |
| + _, err := e.store.Intend(e.ctx, s, h, intent(key, Usage{InputTokens: 1})) |
| + must(t, err) |
| + } |
| + rows, err := e.store.Reservations(e.ctx, s) |
| + must(t, err) |
| + if rows[0].Reserved.InputTokens != 100 || rows[1].Reserved.InputTokens != 50 || rows[1].Reserved.OutputTokens != 20 { |
| + t.Fatal("unbounded or unclipped turn", rows) |
| + } |
| + _, err = e.store.Intend(e.ctx, s, h, intent("zero", Usage{})) |
| + wantCode(t, err, CodeBudget) |
| + }) |
| + t.Run("period headroom", func(t *testing.T) { |
| + e := newEnv(t) |
| + b := periodSet() |
| + b.Team.InputTokens = 130 |
| + for id, p := range b.Projects { |
| + p.InputTokens = 130 |
| + b.Projects[id] = p |
| + } |
| + must(t, e.store.ConfigureBudgets(e.ctx, acctA, 0, b)) |
| + s, h := runnerJob(e, runnerPolicy(t, "subscription")) |
| + for _, key := range []string{"a", "b"} { |
| + _, err := e.store.Intend(e.ctx, s, h, intent(key, Usage{})) |
| + must(t, err) |
| + } |
| + rows, err := e.store.Reservations(e.ctx, s) |
| + must(t, err) |
| + if rows[1].Reserved.InputTokens != 30 { |
| + t.Fatal("period not clipped", rows) |
| + } |
| + _, err = e.store.Intend(e.ctx, s, h, intent("c", Usage{})) |
| + wantCode(t, err, CodeBudget) |
| + }) |
| + t.Run("publication slot", func(t *testing.T) { |
| + e := newEnv(t) |
| + p := runnerPolicy(t, "subscription") |
| + p.Job.InputTokens = 10000 |
| + p.Job.OutputTokens = 10000 |
| + p.Account = p.Job |
| + spec := softwareSpec([]StepSpec{{Key: "producer", Capability: CapImplement, Version: 1}, {Key: "reviewer", Capability: CapReview, Version: 1}}) |
| + spec.Policy = p |
| + _, s := e.createJob(spec) |
| + h := e.claim(s, "producer", "runner", "produce") |
| + review := e.claim(s, "reviewer", "runner", "review") |
| + for i := 0; i < 23; i++ { |
| + turn := h |
| + if i%2 == 1 { |
| + turn = review |
| + } |
| + _, err := e.store.Intend(e.ctx, s, turn, intent(itoa(i), Usage{})) |
| + must(t, err) |
| + } |
| + _, err := e.store.Intend(e.ctx, s, h, intent("24th provider", Usage{})) |
| + wantCode(t, err, CodeBudget) |
| + must(t, e.store.tx(e.ctx, func(tx *sql.Tx) error { |
| + j, err := loadJob(e.ctx, tx, s) |
| + if err != nil { |
| + return err |
| + } |
| + _, _, err = reserve(e.ctx, tx, j, 0, h.Attempt, OpForgePublish, Usage{Calls: 1}, e.clock.Now()) |
| + return err |
| + })) |
| + sum, err := e.store.Ledger(e.ctx, s) |
| + must(t, err) |
| + if sum.Charged.Calls != 24 { |
| + t.Fatal("publication slot lost", sum) |
| + } |
| + }) |
| + t.Run("overrun", func(t *testing.T) { |
| + e := newEnv(t) |
| + s, h := runnerJob(e, runnerPolicy(t, "subscription")) |
| + id, err := e.store.Intend(e.ctx, s, h, intent("a", Usage{})) |
| + must(t, err) |
| + _, err = e.store.Admit(e.ctx, s, id) |
| + must(t, err) |
| + must(t, e.store.Record(e.ctx, s, id, Receipt{ID: "done", Outcome: OutcomeSuccess, Usage: &Usage{Calls: 1, InputTokens: 101, OutputTokens: 1, CostMicros: 999}})) |
| + sum, err := e.store.Ledger(e.ctx, s) |
| + must(t, err) |
| + if sum.Spent.InputTokens != 101 || sum.Spent.CostMicros != 0 { |
| + t.Fatal("overrun not persisted", sum) |
| + } |
| + if _, err = e.store.Intend(e.ctx, s, h, intent("b", Usage{})); err == nil { |
| + t.Fatal("overrun allowed another turn") |
| + } |
| + }) |
| +} |
| +func TestCachedUsageSeparate(t *testing.T) { |
| + e := newEnv(t) |
| + s, h := runnerJob(e, runnerPolicy(t, "subscription")) |
| + id, err := e.store.Intend(e.ctx, s, h, intent("a", Usage{})) |
| + must(t, err) |
| + _, err = e.store.Admit(e.ctx, s, id) |
| + must(t, err) |
| + rc := Receipt{ID: "done", Outcome: OutcomeSuccess, Usage: &Usage{Calls: 7, InputTokens: 20, OutputTokens: 2, CachedInputTokens: 15}} |
| + must(t, e.store.Record(e.ctx, s, id, rc)) |
| + must(t, e.store.Record(e.ctx, s, id, rc)) |
| + sum, err := e.store.Ledger(e.ctx, s) |
| + must(t, err) |
| + if sum.Spent.Calls != 1 || sum.Spent.InputTokens != 20 || sum.Spent.CachedInputTokens != 15 { |
| + t.Fatal("cached input merged", sum) |
| + } |
| + _, err = (Usage{CachedInputTokens: math.MaxInt64}).add(Usage{CachedInputTokens: 1}) |
| + wantCode(t, err, CodeOverflow) |
| +} |
| + |
| +func TestSubscriptionCurrencyAvailability(t *testing.T) { |
| + e := newEnv(t) |
| + s, _ := runnerJob(e, runnerPolicy(t, "subscription")) |
| + sum, err := e.store.Ledger(e.ctx, s) |
| + must(t, err) |
| + if !sum.Reserved.CostUnavailable || !sum.Spent.CostUnavailable || !sum.Charged.CostUnavailable { |
| + t.Fatal("empty subscription ledger claims currency availability") |
| + } |
| + p := runnerPolicy(t, "metered") |
| + u, err := p.price(OpForgePublish, Usage{Calls: 1, CostUnavailable: true}) |
| + must(t, err) |
| + if u.CostUnavailable { |
| + t.Fatal("caller can mark metered currency unavailable") |
| + } |
| +} |
| + |
| +func TestBudgetSyncCommittedRetry(t *testing.T) { |
| + e := newEnv(t) |
| + b := periodSet() |
| + b.Revision = 1 |
| + e.store.commitHook = func(stage string) error { |
| + if stage == "after_commit" { |
| + return ErrUncertain |
| + } |
| + return nil |
| + } |
| + err := e.store.tx(e.ctx, func(tx *sql.Tx) error { return e.store.SyncBudgetsTx(e.ctx, tx, acctA, b) }) |
| + if err == nil { |
| + t.Fatal("lost commit reply not injected") |
| + } |
| + e.crash() |
| + e.openNoResume() |
| + got, err := e.store.ConfiguredBudgets(e.ctx, acctA) |
| + must(t, err) |
| + if got.Revision != 1 { |
| + t.Fatal("committed budget lost") |
| + } |
| + before, err := e.store.RecoverySnapshot(e.ctx) |
| + must(t, err) |
| + for i := 0; i < 2; i++ { |
| + must(t, e.store.tx(e.ctx, func(tx *sql.Tx) error { return e.store.SyncBudgetsTx(e.ctx, tx, acctA, b) })) |
| + } |
| + after, err := e.store.RecoverySnapshot(e.ctx) |
| + must(t, err) |
| + if before.Revision != after.Revision || before.Hash != after.Hash { |
| + t.Fatal("retry advanced budget recovery twice") |
| + } |
| + b.Team.Calls++ |
| + err = e.store.tx(e.ctx, func(tx *sql.Tx) error { return e.store.SyncBudgetsTx(e.ctx, tx, acctA, b) }) |
| + wantCode(t, err, CodeRevision) |
| + _, err = e.store.db.Exec(`UPDATE period_budgets SET content_hash='corrupted'`) |
| + must(t, err) |
| + _, err = e.store.ConfiguredBudgets(e.ctx, acctA) |
| + wantCode(t, err, CodeInvalid) |
| +} |
| + |
| +func TestBoundedTurnReservationPublicationOnce(t *testing.T) { |
| + e := newEnv(t) |
| + spec := softwareSpec([]StepSpec{{Key: "publish", Capability: CapPublish, Version: 1}}) |
| + spec.Policy = runnerPolicy(t, "subscription") |
| + _, s := e.createJob(spec) |
| + h := e.claim(s, "publish", "runner", "workspace") |
| + in := IntentSpec{Key: "publication", Operation: OpTrackerPublish, Payload: []byte(`{}`)} |
| + id, err := e.store.Intend(e.ctx, s, h, in) |
| + must(t, err) |
| + same, err := e.store.Intend(e.ctx, s, h, in) |
| + must(t, err) |
| + if same != id { |
| + t.Fatal("publication replay duplicated") |
| + } |
| + in.Key = "second publication" |
| + _, err = e.store.Intend(e.ctx, s, h, in) |
| + wantCode(t, err, CodeBudget) |
| +} |
diff --git a/internal/equipotest/budget_sync_test.go b/internal/equipotest/budget_sync_test.go| new file mode 100644 |
| index 00000000..7ad7156f |
| --- /dev/null |
| +++ b/internal/equipotest/budget_sync_test.go |
| @@ -0,0 +1,60 @@ |
| +package equipotest |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "context" |
| + "errors" |
| + "gorm.io/gorm" |
| + "testing" |
| +) |
| + |
| +func TestBudgetSyncCrash(t *testing.T) { |
| + s, d, x, _, _, req := recoveryRuntime(t) |
| + ctx := context.Background() |
| + l := team.PeriodLimits{Calls: 24, InputTokens: 1000, OutputTokens: 1000, Seconds: 10000} |
| + executionMust(t, s.SaveBudgets(ctx, equipo.Actor{Address: ownerAddress}, equipo.BudgetConfig{Team: l, Projects: map[team.ProjectID]team.PeriodLimits{req.Project: l}})) |
| + b, err := x.Core.ConfiguredBudgets(ctx, req.Account) |
| + executionMust(t, err) |
| + before := scalar(t, d, "SELECT recovery_revision FROM service") |
| + executionMust(t, x.Core.Close()) |
| + var seq int |
| + var name, path string |
| + executionMust(t, d.Writer().QueryRow(`PRAGMA database_list`).Scan(&seq, &name, &path)) |
| + s = equipo.NewStore(d) |
| + x, err = s.AttachExecution(ctx, path, executionOptions()) |
| + executionMust(t, err) |
| + defer x.Core.Close() |
| + after := scalar(t, d, "SELECT recovery_revision FROM service") |
| + if after != before+1 { |
| + t.Fatal("sync advanced recovery twice", before, after) |
| + } |
| + got, err := x.Core.ConfiguredBudgets(ctx, req.Account) |
| + executionMust(t, err) |
| + if got.Revision != b.Revision { |
| + t.Fatal("reopen advanced budget revision") |
| + } |
| + executionMust(t, d.G.Callback().Create().Before("gorm:create").Register("task3_fail_audit", func(tx *gorm.DB) { |
| + if tx.Statement.Table == "audit_events" { |
| + tx.AddError(errors.New("injected crash before commit")) |
| + } |
| + })) |
| + cfg, err := s.Budgets(ctx) |
| + executionMust(t, err) |
| + cfg.Team.Calls++ |
| + if err = s.SaveBudgets(ctx, equipo.Actor{Address: ownerAddress}, cfg); err == nil { |
| + t.Fatal("injected failure did not abort") |
| + } |
| + executionMust(t, d.G.Callback().Create().Remove("task3_fail_audit")) |
| + got, err = x.Core.ConfiguredBudgets(ctx, req.Account) |
| + executionMust(t, err) |
| + if got.Revision != b.Revision || got.Team != b.Team { |
| + t.Fatal("partial budget commit", got) |
| + } |
| + executionMust(t, s.SaveBudgets(ctx, equipo.Actor{Address: ownerAddress}, cfg)) |
| + got, err = x.Core.ConfiguredBudgets(ctx, req.Account) |
| + executionMust(t, err) |
| + if got.Revision != b.Revision+1 || got.Team != cfg.Team { |
| + t.Fatal("retry failed", got) |
| + } |
| +} |
diff --git a/internal/equipotest/execution_schema_test.go b/internal/equipotest/execution_schema_test.go| index e6bea07c..a3de2831 100644 |
| --- a/internal/equipotest/execution_schema_test.go |
| +++ b/internal/equipotest/execution_schema_test.go |
| @@ -84,7 +84,7 @@ func TestExecutionSharedPool(t *testing.T) { |
| t.Fatal("GORM is not using core SQL transaction") |
| } |
| executionMust(t, tx.Create(&equipo.Account{Label: "rollback"}).Error) |
| - executionMust(t, tx.Exec(`INSERT INTO period_budgets VALUES ('rollback',1,'{}')`).Error) |
| + executionMust(t, tx.Exec(`INSERT INTO period_budgets(account,revision,config) VALUES ('rollback',1,'{}')`).Error) |
| executionMust(t, tx.Create(&equipo.AuditEvent{Actor: ownerAddress, Kind: "rollback", At: time.Now()}).Error) |
| var count int64 |
| executionMust(t, tx.Clauses(dbresolver.Read).Model(&equipo.Account{}).Where("label = ?", "rollback").Count(&count).Error) |
| @@ -145,7 +145,7 @@ func TestExecutionSchemaParity(t *testing.T) { |
| defer old.Close() |
| before := &migrate.Set{} |
| for _, m := range equipo.BootSchema.All() { |
| - if m.ID != "equipo/0007_execution" && m.ID != "equipo/0008_recovery" { |
| + if m.ID != "equipo/0007_execution" && m.ID != "equipo/0008_recovery" && m.ID != "equipo/0009_runner_policy" { |
| before.Add(m) |
| } |
| } |
| @@ -154,7 +154,7 @@ func TestExecutionSchemaParity(t *testing.T) { |
| executionMust(t, old.G.Create(&equipo.Account{Label: "existing account"}).Error) |
| result, err := migrate.Apply(ctx, old, equipo.BootSchema) |
| executionMust(t, err) |
| - if !reflect.DeepEqual(result.Applied, []string{"equipo/0007_execution", "equipo/0008_recovery"}) { |
| + if !reflect.DeepEqual(result.Applied, []string{"equipo/0007_execution", "equipo/0008_recovery", "equipo/0009_runner_policy"}) { |
| t.Fatalf("upgrade migrations: %v", result.Applied) |
| } |
| var account equipo.Account |
| @@ -174,7 +174,7 @@ func TestExecutionSchemaParity(t *testing.T) { |
| defer old.Close() |
| before := &migrate.Set{} |
| for _, m := range equipo.BootSchema.All() { |
| - if m.ID != "equipo/0008_recovery" { |
| + if m.ID != "equipo/0008_recovery" && m.ID != "equipo/0009_runner_policy" { |
| before.Add(m) |
| } |
| } |
| @@ -185,7 +185,7 @@ func TestExecutionSchemaParity(t *testing.T) { |
| executionMust(t, err) |
| result, err := migrate.Apply(ctx, old, equipo.BootSchema) |
| executionMust(t, err) |
| - if !reflect.DeepEqual(result.Applied, []string{"equipo/0008_recovery"}) { |
| + if !reflect.DeepEqual(result.Applied, []string{"equipo/0008_recovery", "equipo/0009_runner_policy"}) { |
| t.Fatalf("task one upgrade migrations: %v", result.Applied) |
| } |
| var evidence string |
| @@ -200,6 +200,56 @@ func TestExecutionSchemaParity(t *testing.T) { |
| } |
| }) |
| + for _, bad := range []bool{false, true} { |
| + t.Run(fmt.Sprintf("task two upgrade bad=%v", bad), func(t *testing.T) { |
| + old, err := db.Open(filepath.Join(t.TempDir(), "task2.db"), slog.New(slog.NewTextHandler(io.Discard, nil))) |
| + executionMust(t, err) |
| + defer old.Close() |
| + before := &migrate.Set{} |
| + for _, m := range equipo.BootSchema.All() { |
| + if m.ID != "equipo/0009_runner_policy" { |
| + before.Add(m) |
| + } |
| + } |
| + _, err = migrate.Apply(ctx, old, before) |
| + executionMust(t, err) |
| + executionMust(t, seedExecutionJob(old.Writer())) |
| + stamp := "2026-10-31T23:59:59.999999999Z" |
| + if bad { |
| + stamp = "2026-02-31T00:00:00Z" |
| + } |
| + _, err = old.Writer().Exec(`UPDATE jobs SET project_id=7`) |
| + executionMust(t, err) |
| + _, err = old.Writer().Exec(`INSERT INTO reservations(account,job_id,step_id,attempt_id,action_id,r_calls,r_input,r_output,r_cost,s_calls,s_input,s_output,s_cost,state,receipt_id,settled_by,created_at,settled_at) VALUES('team',1,0,0,0,1,13,5,99,0,0,0,0,'open','','',?,'')`, stamp) |
| + executionMust(t, err) |
| + result, err := migrate.Apply(ctx, old, equipo.BootSchema) |
| + if bad { |
| + if err == nil { |
| + t.Fatal("app migration accepted invalid timestamp") |
| + } |
| + if scalar(t, old, "SELECT schema_version FROM service") != 4 { |
| + t.Fatal("failed migration advanced schema") |
| + } |
| + return |
| + } |
| + executionMust(t, err) |
| + if !reflect.DeepEqual(result.Applied, []string{"equipo/0009_runner_policy"}) { |
| + t.Fatal("wrong task two upgrade", result.Applied) |
| + } |
| + var project, input, cost int |
| + var month string |
| + executionMust(t, old.Writer().QueryRow(`SELECT project_id,period,r_input,r_cost FROM reservations`).Scan(&project, &month, &input, &cost)) |
| + if project != 7 || month != "2026-10" || input != 13 || cost != 99 { |
| + t.Fatal("migration changed reservation", project, month, input, cost) |
| + } |
| + got, err := migrate.Read(ctx, old.Writer()) |
| + executionMust(t, err) |
| + if diff := expected.Diff(got); len(diff) != 0 { |
| + t.Fatal("task two schema", diff) |
| + } |
| + }) |
| + } |
| + |
| coreNames := map[string]bool{"grant_fences": true, "recovery_charges": true, "recovery_events": true, "service": true, "jobs": true, "steps": true, "attempts": true, "reservations": true, "actions": true, "events": true, "artifacts": true, "period_budgets": true, "time_reservations": true} |
| var appCore migrate.Snapshot |
| for _, table := range expected.Tables { |
| @@ -210,7 +260,7 @@ func TestExecutionSchemaParity(t *testing.T) { |
| if len(appCore.Tables) != len(coreNames) { |
| t.Fatalf("execution tables = %d, want %d", len(appCore.Tables), len(coreNames)) |
| } |
| - for _, version := range []int{1, 2, 3, 4} { |
| + for _, version := range []int{1, 2, 3, 4, 5} { |
| t.Run(fmt.Sprint(version), func(t *testing.T) { |
| standalonePath := filepath.Join(t.TempDir(), "core.db") |
| core, err := team.Open(ctx, standalonePath, executionOptions()) |
| @@ -221,6 +271,12 @@ func TestExecutionSchemaParity(t *testing.T) { |
| defer raw.Close() |
| raw.SetMaxOpenConns(1) |
| executionMust(t, seedExecutionJob(raw)) |
| + if version < 5 { |
| + for _, q := range []string{"DROP INDEX reservations_period_account", "DROP INDEX reservations_period_project", "DROP INDEX time_period_account", "DROP INDEX time_period_project", "DROP INDEX recovery_charges_scope", "ALTER TABLE reservations DROP COLUMN project_id", "ALTER TABLE reservations DROP COLUMN period", "ALTER TABLE reservations DROP COLUMN cost_unavailable", "ALTER TABLE reservations DROP COLUMN s_cached", "ALTER TABLE period_budgets DROP COLUMN content_hash"} { |
| + _, err = raw.Exec(q) |
| + executionMust(t, err) |
| + } |
| + } |
| if version < 4 { |
| for _, q := range []string{`DROP TABLE recovery_events`, `DROP TABLE recovery_charges`, `DROP TABLE grant_fences`, `ALTER TABLE service DROP COLUMN release_required`, `ALTER TABLE service DROP COLUMN recovery_revision`, `ALTER TABLE service DROP COLUMN reconciled_revision`, `ALTER TABLE service DROP COLUMN clock_high_water`, `ALTER TABLE jobs DROP COLUMN grant_stale`, `ALTER TABLE time_reservations DROP COLUMN elapsed_unknown`} { |
| _, err = raw.Exec(q) |