package pipeline import ( "context" "database/sql" "fmt" "strings" "time" "git.a-wan.net/alan/pipelines/internal/protocol" ) // Usage-limit parking, failure classes and run budgets (see protocol // run_quota.go). A parked run keeps everything it needs to continue in its // own row, so it survives a restart without a goroutine: the reset and resume // times, the interrupted visit (0 for a run deferred before its first stage), // and for a deferred run its admitted launch request. func (s *Store) initRunQuota() error { for _, column := range []string{"failure_class", "quota_resets_at", "quota_resume_at", "quota_stage", "quota_account", "deferred_json", "budget_source"} { if err := s.addColumnIfMissing("pipeline_runs", column, "TEXT NOT NULL DEFAULT ''"); err != nil { return err } } for _, column := range []string{"quota_sequence", "budget_warned"} { if err := s.addColumnIfMissing("pipeline_runs", column, "INTEGER NOT NULL DEFAULT 0"); err != nil { return err } } if err := s.addColumnIfMissing("pipeline_runs", "budget_usd", "REAL NOT NULL DEFAULT 0"); err != nil { return err } // quota_limits remembers, per Claude account, until when a stage was // refused for usage, so a new run or retry is not launched into it. _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS quota_limits (account TEXT PRIMARY KEY, resets_at TEXT NOT NULL)`) return err } // defaultFailureClass is the class of a run that stopped without the runner // naming one: a cancel, an interruption, a deliberate #failure route // (blocked) or anything else. func defaultFailureClass(status, failureKind string) string { switch status { case protocol.RunStatusCanceled: return protocol.FailureCanceled case "interrupted": return protocol.FailureInterrupted case "failed": if failureKind == "expected" { return protocol.FailureBlocked } return protocol.FailureOther } return "" } // failureClassCounts counts finished unsuccessful runs by failure class. func failureClassCounts(ctx context.Context, tx *sql.Tx) (map[string]int, error) { rows, err := tx.QueryContext(ctx, `SELECT status,failure_kind,failure_class,COUNT(*) FROM pipeline_runs WHERE status IN ('failed','canceled','interrupted') GROUP BY status,failure_kind,failure_class`) if err != nil { return nil, err } defer rows.Close() counts := map[string]int{} for rows.Next() { var status, kind, class string var n int if err := rows.Scan(&status, &kind, &class, &n); err != nil { return nil, err } if class == "" { class = defaultFailureClass(status, kind) } counts[class] += n } if err := rows.Err(); err != nil { return nil, err } if len(counts) == 0 { return nil, nil } return counts, nil } // SetRunFailureClass records the runner's classification of an unfinished // run just before it is finished; FinishRun keeps it for a failure and // clears it for a success. func (s *Store) SetRunFailureClass(ctx context.Context, id int64, class string) error { _, err := s.db.ExecContext(ctx, `UPDATE pipeline_runs SET failure_class=? WHERE id=? AND finished_at IS NULL`, class, id) return err } func quotaTime(t time.Time) string { if t.IsZero() { return "" } return t.UTC().Format(time.RFC3339) } // ParkRunForQuota parks an executing run in waiting_quota. sequence is the // interrupted visit (its step is already finished as failed) or 0 for a run // deferred before its first stage, whose launch request is deferred. func (s *Store) ParkRunForQuota(ctx context.Context, id int64, sequence int, stageKey, account string, resetsAt, resumeAt time.Time, diagnostic, deferred string) error { tx, err := s.db.BeginTx(ctx, nil) if err != nil { return err } defer tx.Rollback() if err := affected(tx.ExecContext(ctx, `UPDATE pipeline_runs SET status=?,quota_resets_at=?,quota_resume_at=?,quota_sequence=?,quota_stage=?,quota_account=?,deferred_json=?,diagnostic=?,current_stage=CASE WHEN ?<>'' THEN ? ELSE current_stage END WHERE id=? AND status IN ('queued','running') AND cancel_requested=0 AND cleanup_unconfirmed=0 AND NOT EXISTS(SELECT 1 FROM run_steps WHERE run_id=pipeline_runs.id AND agent_active=1)`, protocol.RunStatusWaitingQuota, quotaTime(resetsAt), quotaTime(resumeAt), sequence, stageKey, account, deferred, diagnostic, stageKey, stageKey, id)); err != nil { return fmt.Errorf("%w: %v", ErrInvalidRunTransition, err) } if err := enqueueRunTransitionNotification(ctx, tx, id); err != nil { return err } return tx.Commit() } // QuotaParking is a parked run's resume record. type QuotaParking struct { RunID int64 Sequence int Stage string Account string ResetsAt time.Time ResumeAt time.Time Deferred string } func scanQuotaParking(row interface{ Scan(...any) error }) (QuotaParking, error) { var p QuotaParking var resets, resume string if err := row.Scan(&p.RunID, &p.Sequence, &p.Stage, &p.Account, &resets, &resume, &p.Deferred); err != nil { return p, err } p.ResetsAt, _ = time.Parse(time.RFC3339, resets) p.ResumeAt, _ = time.Parse(time.RFC3339, resume) return p, nil } // QuotaParkedRuns lists every run parked in waiting_quota. func (s *Store) QuotaParkedRuns(ctx context.Context) ([]QuotaParking, error) { rows, err := s.db.QueryContext(ctx, `SELECT id,quota_sequence,quota_stage,quota_account,quota_resets_at,quota_resume_at,deferred_json FROM pipeline_runs WHERE status=? AND cancel_requested=0 ORDER BY id`, protocol.RunStatusWaitingQuota) if err != nil { return nil, err } defer rows.Close() var parked []QuotaParking for rows.Next() { p, err := scanQuotaParking(rows) if err != nil { return nil, err } parked = append(parked, p) } return parked, rows.Err() } // UnparkQuotaRun moves a parked run back to running and returns its resume // record. It fails with ErrInvalidRunTransition when the run is not parked // (already resumed, canceled or deleted), so a resume happens at most once. func (s *Store) UnparkQuotaRun(ctx context.Context, id int64) (QuotaParking, error) { tx, err := s.db.BeginTx(ctx, nil) if err != nil { return QuotaParking{}, err } defer tx.Rollback() p, err := scanQuotaParking(tx.QueryRowContext(ctx, `SELECT id,quota_sequence,quota_stage,quota_account,quota_resets_at,quota_resume_at,deferred_json FROM pipeline_runs WHERE id=? AND status=? AND cancel_requested=0`, id, protocol.RunStatusWaitingQuota)) if err == sql.ErrNoRows { return QuotaParking{}, fmt.Errorf("%w: run %d is not waiting for a usage limit", ErrInvalidRunTransition, id) } if err != nil { return QuotaParking{}, err } status := protocol.RunStatusRunning if p.Sequence == 0 { status = protocol.RunStatusQueued } if err := affected(tx.ExecContext(ctx, `UPDATE pipeline_runs SET status=?,quota_resets_at='',quota_resume_at='',quota_sequence=0,quota_stage='',deferred_json='',diagnostic='' WHERE id=? AND status=?`, status, id, protocol.RunStatusWaitingQuota)); err != nil { return QuotaParking{}, err } return p, tx.Commit() } // RecordQuotaLimit remembers that account is out of usage until resetsAt. func (s *Store) RecordQuotaLimit(ctx context.Context, account string, resetsAt time.Time) error { if strings.TrimSpace(account) == "" || resetsAt.IsZero() { return nil } _, err := s.db.ExecContext(ctx, `INSERT INTO quota_limits(account,resets_at) VALUES(?,?) ON CONFLICT(account) DO UPDATE SET resets_at=CASE WHEN excluded.resets_at>resets_at THEN excluded.resets_at ELSE resets_at END`, account, quotaTime(resetsAt)) return err } // QuotaLimit reports until when account is known to be out of usage; ok is // false when no limit is known or it has already reset. func (s *Store) QuotaLimit(ctx context.Context, account string, now time.Time) (time.Time, bool, error) { var value string err := s.db.QueryRowContext(ctx, `SELECT resets_at FROM quota_limits WHERE account=?`, account).Scan(&value) if err == sql.ErrNoRows { return time.Time{}, false, nil } if err != nil { return time.Time{}, false, err } at, err := time.Parse(time.RFC3339, value) if err != nil || !at.After(now) { return time.Time{}, false, nil } return at, true, nil } // AnyQuotaLimit reports whether any account is known to be limited past now, // so admission resolves a run's account only when it can matter. func (s *Store) AnyQuotaLimit(ctx context.Context, now time.Time) (bool, error) { var any bool err := s.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM quota_limits WHERE resets_at>?)`, quotaTime(now)).Scan(&any) return any, err } // SetRunBudget records a run's whole-run USD cap and where it came from. func (s *Store) SetRunBudget(ctx context.Context, id int64, limitUSD float64, source string) error { _, err := s.db.ExecContext(ctx, `UPDATE pipeline_runs SET budget_usd=?,budget_source=? WHERE id=?`, limitUSD, source, id) return err } // MarkRunBudgetWarned records the 80% warning once; it reports whether this // call was the first. func (s *Store) MarkRunBudgetWarned(ctx context.Context, id int64) (bool, error) { res, err := s.db.ExecContext(ctx, `UPDATE pipeline_runs SET budget_warned=1 WHERE id=? AND budget_warned=0`, id) if err != nil { return false, err } n, err := res.RowsAffected() return n == 1, err } // runDefaultBudgetSetting is the server_settings key of the default run cap. const runDefaultBudgetSetting = "run.default_budget_usd" // RunSettings reads the server-wide run defaults. func (s *Store) RunSettings(ctx context.Context) (protocol.RunSettings, error) { var settings protocol.RunSettings value, found, err := s.ServerSetting(ctx, runDefaultBudgetSetting) if err != nil || !found { return settings, err } _, _ = fmt.Sscanf(value, "%g", &settings.DefaultBudgetUSD) if settings.DefaultBudgetUSD < 0 { settings.DefaultBudgetUSD = 0 } return settings, nil } // SetRunSettings records the server-wide run defaults. func (s *Store) SetRunSettings(ctx context.Context, settings protocol.RunSettings) (protocol.RunSettings, error) { if settings.DefaultBudgetUSD < 0 || settings.DefaultBudgetUSD != settings.DefaultBudgetUSD || settings.DefaultBudgetUSD > 1e6 { return protocol.RunSettings{}, fmt.Errorf("default_budget_usd must be 0 (no cap) or a positive USD amount") } if err := s.SetServerSetting(ctx, runDefaultBudgetSetting, fmt.Sprintf("%g", settings.DefaultBudgetUSD)); err != nil { return protocol.RunSettings{}, err } return s.RunSettings(ctx) }