| 1 | package team |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "time" |
| 9 | ) |
| 10 | |
| 11 | type ProjectID int64 |
| 12 | |
| 13 | type PeriodLimits struct { |
| 14 | Calls int64 |
| 15 | InputTokens int64 |
| 16 | OutputTokens int64 |
| 17 | Seconds int64 |
| 18 | } |
| 19 | type BudgetSet struct { |
| 20 | Revision int64 |
| 21 | Team PeriodLimits |
| 22 | Projects map[ProjectID]PeriodLimits |
| 23 | } |
| 24 | type PeriodUsage struct{ Reserved, Spent PeriodLimits } |
| 25 | |
| 26 | func (p PeriodLimits) within(l PeriodLimits) bool { |
| 27 | return p.Calls <= l.Calls && p.InputTokens <= l.InputTokens && p.OutputTokens <= l.OutputTokens && p.Seconds <= l.Seconds |
| 28 | } |
| 29 | func (p PeriodLimits) add(q PeriodLimits) (PeriodLimits, error) { |
| 30 | var out PeriodLimits |
| 31 | for _, v := range []struct { |
| 32 | a, b int64 |
| 33 | dst *int64 |
| 34 | }{{p.Calls, q.Calls, &out.Calls}, {p.InputTokens, q.InputTokens, &out.InputTokens}, {p.OutputTokens, q.OutputTokens, &out.OutputTokens}, {p.Seconds, q.Seconds, &out.Seconds}} { |
| 35 | n, err := addChecked(v.a, v.b) |
| 36 | if err != nil { |
| 37 | return PeriodLimits{}, err |
| 38 | } |
| 39 | *v.dst = n |
| 40 | } |
| 41 | return out, nil |
| 42 | } |
| 43 | func (p PeriodLimits) validate() error { |
| 44 | if p.Calls <= 0 || p.InputTokens <= 0 || p.OutputTokens <= 0 || p.Seconds <= 0 { |
| 45 | return fail(CodeInvalid, "period limits must be positive and explicit") |
| 46 | } |
| 47 | return nil |
| 48 | } |
| 49 | |
| 50 | // ProjectLimits inherits the team ceiling until a project has an explicit limit. |
| 51 | func (b BudgetSet) ProjectLimits(id ProjectID) PeriodLimits { |
| 52 | if p, ok := b.Projects[id]; ok { |
| 53 | return p |
| 54 | } |
| 55 | return b.Team |
| 56 | } |
| 57 | func (b BudgetSet) Validate() error { |
| 58 | if b.Revision < 0 { |
| 59 | return fail(CodeInvalid, "negative budget revision") |
| 60 | } |
| 61 | if err := b.Team.validate(); err != nil { |
| 62 | return err |
| 63 | } |
| 64 | var rollup PeriodLimits |
| 65 | for id, p := range b.Projects { |
| 66 | if id <= 0 { |
| 67 | return fail(CodeInvalid, "project must be positive") |
| 68 | } |
| 69 | if err := p.validate(); err != nil { |
| 70 | return err |
| 71 | } |
| 72 | if !p.within(b.Team) { |
| 73 | return fail(CodeInvalid, "project limits exceed team limits") |
| 74 | } |
| 75 | var err error |
| 76 | rollup, err = rollup.add(p) |
| 77 | if err != nil { |
| 78 | return err |
| 79 | } |
| 80 | } |
| 81 | return nil |
| 82 | } |
| 83 | |
| 84 | const periodSchema = ` |
| 85 | CREATE TABLE IF NOT EXISTS period_budgets ( |
| 86 | account TEXT PRIMARY KEY, revision INTEGER NOT NULL, config TEXT NOT NULL |
| 87 | ); |
| 88 | CREATE TABLE IF NOT EXISTS time_reservations ( |
| 89 | attempt_id INTEGER PRIMARY KEY REFERENCES attempts(id), |
| 90 | account TEXT NOT NULL, project_id INTEGER NOT NULL, |
| 91 | job_id INTEGER NOT NULL REFERENCES jobs(id), period TEXT NOT NULL, |
| 92 | reserved_seconds INTEGER NOT NULL, settled_seconds INTEGER NOT NULL, |
| 93 | state TEXT NOT NULL, settled_at TEXT NOT NULL |
| 94 | ); |
| 95 | CREATE INDEX IF NOT EXISTS time_reservations_account ON time_reservations(account, project_id, state, period); |
| 96 | ` |
| 97 | |
| 98 | func loadBudgets(ctx context.Context, tx *sql.Tx, account AccountID) (BudgetSet, bool, error) { |
| 99 | var b BudgetSet |
| 100 | var raw, hash string |
| 101 | var revision int64 |
| 102 | err := tx.QueryRowContext(ctx, `SELECT revision, config, content_hash FROM period_budgets WHERE account=?`, string(account)).Scan(&revision, &raw, &hash) |
| 103 | if errors.Is(err, sql.ErrNoRows) { |
| 104 | return b, false, nil |
| 105 | } |
| 106 | if err != nil { |
| 107 | return b, false, err |
| 108 | } |
| 109 | if err := strictJSON([]byte(raw), &b); err != nil { |
| 110 | return b, false, fail(CodeInvalid, "stored budgets: %v", err) |
| 111 | } |
| 112 | if hash != "" && hash != hashBytes([]byte(raw)) { |
| 113 | return b, false, fail(CodeInvalid, "budget content hash mismatch") |
| 114 | } |
| 115 | if b.Revision != revision || revision <= 0 { |
| 116 | return b, false, fail(CodeInvalid, "stored budget revision") |
| 117 | } |
| 118 | if err := b.Validate(); err != nil { |
| 119 | return b, false, err |
| 120 | } |
| 121 | return b, true, nil |
| 122 | } |
| 123 | func (s *Store) ConfigureBudgets(ctx context.Context, account AccountID, expectedRevision int64, budgets BudgetSet) error { |
| 124 | s.recoveryMu.Lock() |
| 125 | defer s.recoveryMu.Unlock() |
| 126 | return s.tx(ctx, func(tx *sql.Tx) error { return s.ConfigureBudgetsTx(ctx, tx, account, expectedRevision, budgets) }) |
| 127 | } |
| 128 | |
| 129 | func (s *Store) ConfigureBudgetsTx(ctx context.Context, tx *sql.Tx, account AccountID, expectedRevision int64, budgets BudgetSet) error { |
| 130 | if account == "" || expectedRevision < 0 || budgets.Revision != expectedRevision { |
| 131 | return fail(CodeInvalid, "budget account or revision") |
| 132 | } |
| 133 | if err := budgets.Validate(); err != nil { |
| 134 | return err |
| 135 | } |
| 136 | |
| 137 | old, _, err := loadBudgets(ctx, tx, account) |
| 138 | if err != nil { |
| 139 | return err |
| 140 | } |
| 141 | if old.Revision != expectedRevision { |
| 142 | return fail(CodeRevision, "budget revision changed") |
| 143 | } |
| 144 | budgets.Revision, err = addChecked(expectedRevision, 1) |
| 145 | if err != nil { |
| 146 | return err |
| 147 | } |
| 148 | raw, err := json.Marshal(budgets) |
| 149 | if err != nil { |
| 150 | return err |
| 151 | } |
| 152 | _, 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)) |
| 153 | if err != nil { |
| 154 | return err |
| 155 | } |
| 156 | return advanceRecovery(ctx, tx) |
| 157 | } |
| 158 | |
| 159 | func period(at time.Time) string { return at.UTC().Format("2006-01") } |
| 160 | |
| 161 | func periodSum(ctx context.Context, tx *sql.Tx, account AccountID, project ProjectID, at time.Time) (PeriodUsage, error) { |
| 162 | return periodSumFor(ctx, tx, account, project, "", at) |
| 163 | } |
| 164 | func periodSumFor(ctx context.Context, tx *sql.Tx, account AccountID, project ProjectID, person string, at time.Time) (PeriodUsage, error) { |
| 165 | var sum PeriodUsage |
| 166 | chargeQuery := "SELECT reserved FROM recovery_charges WHERE account=? AND substr(created_at,1,7)=?" |
| 167 | chargeArgs := []any{string(account), period(at)} |
| 168 | if project != 0 { |
| 169 | chargeQuery += " AND project_id=?" |
| 170 | chargeArgs = append(chargeArgs, project) |
| 171 | } |
| 172 | if person != "" { |
| 173 | chargeQuery += " AND project_id=0" |
| 174 | } |
| 175 | charges, err := tx.QueryContext(ctx, chargeQuery, chargeArgs...) |
| 176 | if err != nil { |
| 177 | return sum, err |
| 178 | } |
| 179 | for charges.Next() { |
| 180 | var raw string |
| 181 | var r PeriodLimits |
| 182 | if err = charges.Scan(&raw); err != nil { |
| 183 | break |
| 184 | } |
| 185 | if err = json.Unmarshal([]byte(raw), &r); err != nil { |
| 186 | break |
| 187 | } |
| 188 | if r.Calls < 0 || r.InputTokens < 0 || r.OutputTokens < 0 || r.Seconds < 0 { |
| 189 | err = fail(CodeInvalid, "negative recovery charge") |
| 190 | break |
| 191 | } |
| 192 | sum.Spent, err = sum.Spent.add(r) |
| 193 | if err != nil { |
| 194 | break |
| 195 | } |
| 196 | } |
| 197 | if err == nil { |
| 198 | err = charges.Err() |
| 199 | } |
| 200 | charges.Close() |
| 201 | if err != nil { |
| 202 | return sum, err |
| 203 | } |
| 204 | for _, table := range []string{"reservations", "time_reservations"} { |
| 205 | for _, settled := range []bool{false, true} { |
| 206 | q, args := periodQuery(table, account, project, at, settled) |
| 207 | if person != "" { |
| 208 | q += " AND job_id IN (SELECT id FROM jobs WHERE account=? AND requester=? AND json_extract(target,'$.kind')='conversation')" |
| 209 | args = append(args, string(account), person) |
| 210 | } |
| 211 | rows, err := tx.QueryContext(ctx, q, args...) |
| 212 | if err != nil { |
| 213 | return sum, err |
| 214 | } |
| 215 | for rows.Next() { |
| 216 | var u PeriodLimits |
| 217 | if table == "reservations" { |
| 218 | err = rows.Scan(&u.Calls, &u.InputTokens, &u.OutputTokens) |
| 219 | } else { |
| 220 | err = rows.Scan(&u.Seconds) |
| 221 | } |
| 222 | if err != nil { |
| 223 | break |
| 224 | } |
| 225 | if settled { |
| 226 | sum.Spent, err = sum.Spent.add(u) |
| 227 | } else { |
| 228 | sum.Reserved, err = sum.Reserved.add(u) |
| 229 | } |
| 230 | if err != nil { |
| 231 | break |
| 232 | } |
| 233 | } |
| 234 | if err == nil { |
| 235 | err = rows.Err() |
| 236 | } |
| 237 | rows.Close() |
| 238 | if err != nil { |
| 239 | return sum, err |
| 240 | } |
| 241 | } |
| 242 | } |
| 243 | return sum, nil |
| 244 | } |
| 245 | |
| 246 | func periodQuery(table string, account AccountID, project ProjectID, at time.Time, settled bool) (string, []any) { |
| 247 | columns := "r_calls,r_input,r_output" |
| 248 | states := "state='open'" |
| 249 | if settled { |
| 250 | columns = "s_calls,s_input,s_output" |
| 251 | states = "state IN ('settled','settled_audited')" |
| 252 | } |
| 253 | if table == "time_reservations" { |
| 254 | columns = "reserved_seconds" |
| 255 | if settled { |
| 256 | columns = "settled_seconds" |
| 257 | states = "state='settled'" |
| 258 | } |
| 259 | } |
| 260 | q := "SELECT " + columns + " FROM " + table + " WHERE account=?" |
| 261 | args := []any{string(account)} |
| 262 | if project != 0 { |
| 263 | q += " AND project_id=?" |
| 264 | args = append(args, project) |
| 265 | } |
| 266 | q += " AND " + states |
| 267 | q += " AND period=?" |
| 268 | args = append(args, period(at)) |
| 269 | return q, args |
| 270 | } |
| 271 | |
| 272 | func (s *Store) PeriodUsage(ctx context.Context, account AccountID, project ProjectID, at time.Time) (PeriodUsage, error) { |
| 273 | var sum PeriodUsage |
| 274 | if account == "" || project < 0 || at.IsZero() { |
| 275 | return sum, fail(CodeInvalid, "period usage scope") |
| 276 | } |
| 277 | err := s.read(ctx, func(tx *sql.Tx) error { |
| 278 | _, configured, err := loadBudgets(ctx, tx, account) |
| 279 | if err != nil { |
| 280 | return err |
| 281 | } |
| 282 | if !configured { |
| 283 | return fail(CodeBudget, "period budgets unavailable") |
| 284 | } |
| 285 | sum, err = periodSum(ctx, tx, account, project, at) |
| 286 | return err |
| 287 | }) |
| 288 | if err != nil { |
| 289 | return PeriodUsage{}, err |
| 290 | } |
| 291 | return sum, nil |
| 292 | } |
| 293 | func checkPeriodBudget(ctx context.Context, tx *sql.Tx, j jobRow, want PeriodLimits, now time.Time) (bool, error) { |
| 294 | b, configured, err := loadBudgets(ctx, tx, j.Account) |
| 295 | if err != nil || !configured { |
| 296 | if err == nil && j.Target.Kind == TargetConversation { |
| 297 | err = ErrBudget |
| 298 | } |
| 299 | return configured, err |
| 300 | } |
| 301 | if j.Target.Kind == TargetConversation { |
| 302 | return true, checkCoordinatorBudget(ctx, tx, j, b, want, now) |
| 303 | } |
| 304 | return true, CheckPlanBudgetTx(ctx, tx, j.Account, j.Project, b, want, now) |
| 305 | } |
| 306 | |
| 307 | // CheckPlanBudgetTx reads the existing ledger without reserving or granting work. |
| 308 | func CheckPlanBudgetTx(ctx context.Context, tx *sql.Tx, account AccountID, project ProjectID, b BudgetSet, want PeriodLimits, now time.Time) error { |
| 309 | if err := b.Validate(); err != nil { |
| 310 | return err |
| 311 | } |
| 312 | p := b.ProjectLimits(project) |
| 313 | if project <= 0 { |
| 314 | return fail(CodeBudget, "job has no configured project") |
| 315 | } |
| 316 | for _, limit := range []struct { |
| 317 | project ProjectID |
| 318 | cap PeriodLimits |
| 319 | }{{0, b.Team}, {project, p}} { |
| 320 | sum, err := periodSum(ctx, tx, account, limit.project, now) |
| 321 | if err != nil { |
| 322 | return err |
| 323 | } |
| 324 | charged, err := sum.Reserved.add(sum.Spent) |
| 325 | if err != nil { |
| 326 | return err |
| 327 | } |
| 328 | charged, err = charged.add(want) |
| 329 | if err != nil { |
| 330 | return err |
| 331 | } |
| 332 | if !charged.within(limit.cap) { |
| 333 | return fail(CodeBudget, "period ceiling exceeded for project %d", limit.project) |
| 334 | } |
| 335 | } |
| 336 | return nil |
| 337 | } |
| 338 | func reserveTime(ctx context.Context, tx *sql.Tx, j jobRow, id AttemptID, now time.Time) error { |
| 339 | _, err := checkPeriodBudget(ctx, tx, j, PeriodLimits{Seconds: int64(j.Policy.AttemptSeconds)}, now) |
| 340 | if err != nil { |
| 341 | return err |
| 342 | } |
| 343 | _, err = tx.ExecContext(ctx, `INSERT INTO time_reservations(attempt_id,account,project_id,job_id,period,reserved_seconds,settled_seconds,state,settled_at) VALUES(?,?,?,?,?,?,0,'open','')`, id, string(j.Account), j.Project, j.ID, period(now), j.Policy.AttemptSeconds) |
| 344 | return err |
| 345 | } |
| 346 | func settleTime(ctx context.Context, tx *sql.Tx, a Attempt, now time.Time) error { |
| 347 | if a.CreatedAt.IsZero() { |
| 348 | return fail(CodeInvalid, "invalid containment time") |
| 349 | } |
| 350 | var unknown int |
| 351 | if err := tx.QueryRowContext(ctx, `SELECT elapsed_unknown FROM time_reservations WHERE attempt_id=? AND state='open'`, a.ID).Scan(&unknown); err != nil { |
| 352 | return fail(CodeState, "attempt has no open time reservation") |
| 353 | } |
| 354 | if unknown != 0 || now.Before(a.CreatedAt) { |
| 355 | _, err := tx.ExecContext(ctx, `UPDATE time_reservations SET elapsed_unknown=1, settled_seconds=reserved_seconds, state='settled', settled_at=? WHERE attempt_id=?`, ts(now), a.ID) |
| 356 | return err |
| 357 | } |
| 358 | seconds := max(int64(0), now.Unix()-a.CreatedAt.Unix()) |
| 359 | if !now.Before(a.CreatedAt) && now.Nanosecond() > a.CreatedAt.Nanosecond() { |
| 360 | var err error |
| 361 | seconds, err = addChecked(seconds, 1) |
| 362 | if err != nil { |
| 363 | return err |
| 364 | } |
| 365 | } |
| 366 | result, err := tx.ExecContext(ctx, `UPDATE time_reservations SET settled_seconds=?, state='settled', settled_at=? WHERE attempt_id=? AND state='open'`, seconds, ts(now), a.ID) |
| 367 | if err != nil { |
| 368 | return err |
| 369 | } |
| 370 | rows, err := result.RowsAffected() |
| 371 | if err != nil { |
| 372 | return err |
| 373 | } |
| 374 | if rows != 1 { |
| 375 | return fail(CodeState, "attempt %d has no open time reservation", a.ID) |
| 376 | } |
| 377 | return nil |
| 378 | } |
| 379 | |
| 380 | func migrateTimeReservations(ctx context.Context, tx *sql.Tx) error { |
| 381 | rows, err := tx.QueryContext(ctx, `SELECT id, job_id FROM attempts WHERE id NOT IN (SELECT attempt_id FROM time_reservations)`) |
| 382 | if err != nil { |
| 383 | return err |
| 384 | } |
| 385 | type ref struct { |
| 386 | attempt AttemptID |
| 387 | job JobID |
| 388 | } |
| 389 | var refs []ref |
| 390 | for rows.Next() { |
| 391 | var r ref |
| 392 | if err = rows.Scan(&r.attempt, &r.job); err != nil { |
| 393 | break |
| 394 | } |
| 395 | refs = append(refs, r) |
| 396 | } |
| 397 | if err == nil { |
| 398 | err = rows.Err() |
| 399 | } |
| 400 | rows.Close() |
| 401 | if err != nil { |
| 402 | return err |
| 403 | } |
| 404 | for _, r := range refs { |
| 405 | j, err := scanJob(tx.QueryRowContext(ctx, `SELECT `+jobColumns+` FROM jobs WHERE id=?`, r.job)) |
| 406 | if err != nil { |
| 407 | return err |
| 408 | } |
| 409 | a, err := loadAttempt(ctx, tx, r.job, r.attempt) |
| 410 | if err != nil { |
| 411 | return err |
| 412 | } |
| 413 | if a.CreatedAt.IsZero() { |
| 414 | return fail(CodeInvalid, "invalid migrated attempt time") |
| 415 | } |
| 416 | _, err = tx.ExecContext(ctx, `INSERT INTO time_reservations(attempt_id,account,project_id,job_id,period,reserved_seconds,settled_seconds,state,settled_at) VALUES(?,?,?,?,?,?,0,'open','')`, a.ID, string(j.Account), j.Project, j.ID, period(a.CreatedAt), j.Policy.AttemptSeconds) |
| 417 | if err != nil { |
| 418 | return err |
| 419 | } |
| 420 | if a.Containment == ContainmentContained { |
| 421 | if err := settleTime(ctx, tx, a, a.StopAcked); err != nil { |
| 422 | return err |
| 423 | } |
| 424 | } |
| 425 | } |
| 426 | return nil |
| 427 | } |
| 428 | |
| 429 | func (s *Store) SyncBudgetsTx(ctx context.Context, tx *sql.Tx, account AccountID, budgets BudgetSet) error { |
| 430 | if account == "" || budgets.Revision <= 0 { |
| 431 | return fail(CodeInvalid, "budget account or revision") |
| 432 | } |
| 433 | if err := budgets.Validate(); err != nil { |
| 434 | return err |
| 435 | } |
| 436 | old, exists, err := loadBudgets(ctx, tx, account) |
| 437 | if err != nil { |
| 438 | return err |
| 439 | } |
| 440 | raw, err := json.Marshal(budgets) |
| 441 | if err != nil { |
| 442 | return err |
| 443 | } |
| 444 | if exists && old.Revision >= budgets.Revision { |
| 445 | previous, err := json.Marshal(old) |
| 446 | if err != nil { |
| 447 | return err |
| 448 | } |
| 449 | if string(previous) == string(raw) { |
| 450 | _, err = tx.ExecContext(ctx, `UPDATE period_budgets SET config=?,content_hash=? WHERE account=? AND content_hash=''`, string(raw), hashBytes(raw), string(account)) |
| 451 | return err |
| 452 | } |
| 453 | return fail(CodeRevision, "budget revision changed") |
| 454 | } |
| 455 | 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 { |
| 456 | return err |
| 457 | } |
| 458 | return advanceRecovery(ctx, tx) |
| 459 | } |
| 460 | |
| 461 | // ConfiguredBudgets returns saved limits, or ErrBudget when none are configured. |
| 462 | func (s *Store) ConfiguredBudgets(ctx context.Context, account AccountID) (BudgetSet, error) { |
| 463 | var b BudgetSet |
| 464 | if account == "" { |
| 465 | return b, fail(CodeScope, "empty account") |
| 466 | } |
| 467 | err := s.read(ctx, func(tx *sql.Tx) error { |
| 468 | var ok bool |
| 469 | var err error |
| 470 | b, ok, err = loadBudgets(ctx, tx, account) |
| 471 | if err != nil { |
| 472 | return err |
| 473 | } |
| 474 | if !ok { |
| 475 | return fail(CodeBudget, "period budgets unavailable") |
| 476 | } |
| 477 | return nil |
| 478 | }) |
| 479 | if err != nil { |
| 480 | return BudgetSet{}, err |
| 481 | } |
| 482 | return b, nil |
| 483 | } |
| 484 | |