Merge branch 'worktree-agent-a5f621112ab3cad4f'

# Conflicts:
#	app/lib/features/chat/domain/chat_shown_run.dart
This commit is contained in:
2026-12-03 14:43:11 +00:00
66 changed files with 3326 additions and 68 deletions
+3
View File
@@ -42,6 +42,9 @@ FROM pipeline_runs r JOIN pipelines p ON p.id=r.pipeline_id
case "waiting":
title = "Run needs your decision"
body = "waiting for a human decision"
case protocol.RunStatusWaitingQuota:
title = "Run paused for a usage limit"
body = "waiting for the usage limit to reset"
case "failed", "interrupted", "succeeded":
if status == "failed" && failureKind == "expected" && mode != "on" {
settings, err := readNotificationSettings(ctx, tx)
+266
View File
@@ -0,0 +1,266 @@
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)
}
+3
View File
@@ -46,6 +46,9 @@ WHERE u.run_id IN (`+strings.TrimSuffix(strings.Repeat("?,", len(args)), ",")+`)
u.SplitKnown = u.TokensKnownStages > 0 && u.SplitUnknownStages == 0
u.CacheKnown = u.TokensKnownStages > 0 && u.CacheKnownStages == u.TokensKnownStages
byID[id].Usage = &u
if byID[id].Budget != nil {
byID[id].Budget.SpentUSD = u.CostUSD
}
}
err = rows.Err()
rows.Close()
+18 -2
View File
@@ -27,14 +27,27 @@ CASE WHEN r.status='waiting' THEN COALESCE((SELECT sequence FROM session_export_
EXISTS(SELECT 1 FROM run_schedule_origin WHERE run_id=r.id),
COALESCE((SELECT schedule_id FROM run_schedule_origin WHERE run_id=r.id),0),
COALESCE((SELECT name FROM run_schedule_origin WHERE run_id=r.id),''),
MAX(r.size_bytes,0)
MAX(r.size_bytes,0),
r.failure_class,r.quota_resets_at,r.quota_resume_at,r.quota_sequence,r.quota_stage,r.quota_account,r.budget_usd,r.budget_source,r.budget_warned
` + runFrom + ` JOIN pipeline_versions v ON v.pipeline_id=r.pipeline_id AND v.version=r.version`
func scanRun(row interface{ Scan(...any) error }, r *protocol.RunSummary) error {
var output, stageModels string
if err := row.Scan(&r.ID, &r.PipelineID, &r.Name, &r.Version, &r.ContentHash, &r.Status, &r.Outcome, &r.CurrentStage, &r.CreatedAt, &r.FinishedAt, &r.Diagnostic, &r.FailureKind, &r.FailureReason, &output, &r.CompletedSteps, &r.Workspace, &r.Title, &r.Model, &stageModels, &r.NotifyMode, &r.CancelRequested, &r.CleanupUnconfirmed, &r.OutputFormat, &r.ExportPendingSequence, &r.Scheduled, &r.ScheduleID, &r.ScheduleName, &r.SizeBytes); err != nil {
var quota protocol.RunQuotaWait
var budget protocol.RunBudget
if err := row.Scan(&r.ID, &r.PipelineID, &r.Name, &r.Version, &r.ContentHash, &r.Status, &r.Outcome, &r.CurrentStage, &r.CreatedAt, &r.FinishedAt, &r.Diagnostic, &r.FailureKind, &r.FailureReason, &output, &r.CompletedSteps, &r.Workspace, &r.Title, &r.Model, &stageModels, &r.NotifyMode, &r.CancelRequested, &r.CleanupUnconfirmed, &r.OutputFormat, &r.ExportPendingSequence, &r.Scheduled, &r.ScheduleID, &r.ScheduleName, &r.SizeBytes, &r.FailureClass, &quota.ResetsAt, &quota.ResumeAt, &quota.Sequence, &quota.Stage, &quota.Account, &budget.LimitUSD, &budget.Source, &budget.Warned); err != nil {
return err
}
if r.Status == protocol.RunStatusWaitingQuota {
r.QuotaWait = &quota
}
if budget.LimitUSD > 0 {
r.Budget = &budget
}
if r.FailureClass == "" {
// Rows that predate the column still say why they stopped.
r.FailureClass = defaultFailureClass(r.Status, r.FailureKind)
}
if stageModels != "" && stageModels != "{}" {
if err := json.Unmarshal([]byte(stageModels), &r.StageModels); err != nil {
return err
@@ -316,6 +329,9 @@ strftime('%Y-%m-%dT%H:%M:%SZ',started_at),COALESCE(strftime('%Y-%m-%dT%H:%M:%SZ'
// The run total is one pass over the steps already loaded above: it adds no
// query and no transcript parse.
r.Usage = protocol.TotalUsage(r.Steps)
if r.Budget != nil && r.Usage != nil {
r.Budget.SpentUSD = r.Usage.CostUSD
}
r.Warnings = protocol.RunWarnings(r.Steps)
if r.Environment != nil {
for _, warning := range r.Environment.Warnings {
+10 -4
View File
@@ -386,8 +386,9 @@ func (s *Store) CancelWaiting(ctx context.Context, id int64) error {
}
defer tx.Rollback()
res, err := tx.ExecContext(ctx, `UPDATE pipeline_runs SET status='canceled',cancel_requested=1,
diagnostic=CASE WHEN EXISTS(SELECT 1 FROM session_export_gates g WHERE g.run_id=pipeline_runs.id) THEN 'Canceled while awaiting session export; computed visit retained' ELSE 'Canceled while waiting for a decision' END,
finished_at=CURRENT_TIMESTAMP WHERE id=? AND (status=? OR (status IN ('failed','interrupted') AND EXISTS(SELECT 1 FROM session_export_gates g WHERE g.run_id=pipeline_runs.id)))`, id, protocol.RunStatusWaiting)
diagnostic=CASE WHEN EXISTS(SELECT 1 FROM session_export_gates g WHERE g.run_id=pipeline_runs.id) THEN 'Canceled while awaiting session export; computed visit retained' WHEN status=? THEN 'Canceled while waiting for the usage limit to reset' ELSE 'Canceled while waiting for a decision' END,
failure_class='canceled',quota_resets_at='',quota_resume_at='',deferred_json='',
finished_at=CURRENT_TIMESTAMP WHERE id=? AND (status IN (?,?) OR (status IN ('failed','interrupted') AND EXISTS(SELECT 1 FROM session_export_gates g WHERE g.run_id=pipeline_runs.id)))`, protocol.RunStatusWaitingQuota, id, protocol.RunStatusWaiting, protocol.RunStatusWaitingQuota)
if err != nil {
return err
}
@@ -408,7 +409,7 @@ finished_at=CURRENT_TIMESTAMP WHERE id=? AND (status=? OR (status IN ('failed','
func (s *Store) Cancel(ctx context.Context, id int64) error {
return affected(s.db.ExecContext(ctx, `UPDATE pipeline_runs SET cancel_requested=1,
diagnostic=CASE WHEN cleanup_unconfirmed=1 THEN diagnostic ELSE 'Stop requested; waiting for execution and cleanup to stop' END
WHERE id=? AND (status IN ('queued','running','waiting') OR (status IN ('failed','interrupted') AND EXISTS(SELECT 1 FROM session_export_gates g WHERE g.run_id=pipeline_runs.id)))`, id))
WHERE id=? AND (status IN ('queued','running','waiting','waiting_quota') OR (status IN ('failed','interrupted') AND EXISTS(SELECT 1 FROM session_export_gates g WHERE g.run_id=pipeline_runs.id)))`, id))
}
func (s *Store) FinishRun(ctx context.Context, id int64, status, outcome, diagnostic string, output map[string]any) error {
@@ -422,14 +423,19 @@ func (s *Store) FinishRun(ctx context.Context, id int64, status, outcome, diagno
}
defer tx.Rollback()
failureKind, failureReason := classifyRunFailure(ctx, tx, id, status, diagnostic)
// A class the runner recorded for this run (SetRunFailureClass) wins over
// the derived default; a success carries none.
derivedClass := defaultFailureClass(status, failureKind)
if err := affected(tx.ExecContext(ctx, `UPDATE pipeline_runs SET
status=CASE WHEN cancel_requested=1 THEN 'canceled' ELSE ? END,
outcome=CASE WHEN cancel_requested=1 THEN '' ELSE ? END,
diagnostic=CASE WHEN cancel_requested=1 THEN 'Canceled by operator; execution stopped' ELSE ? END,
failure_kind=CASE WHEN cancel_requested=1 THEN '' ELSE ? END,
failure_reason=CASE WHEN cancel_requested=1 THEN '' ELSE ? END,
failure_class=CASE WHEN cancel_requested=1 THEN 'canceled' WHEN ?='' THEN '' WHEN failure_class<>'' THEN failure_class ELSE ? END,
quota_resets_at='',quota_resume_at='',deferred_json='',
output_json=?,finished_at=CURRENT_TIMESTAMP WHERE id=? AND status IN ('queued','running') AND cleanup_unconfirmed=0
AND NOT EXISTS(SELECT 1 FROM run_steps WHERE run_id=pipeline_runs.id AND agent_active=1)`, status, outcome, diagnostic, failureKind, failureReason, string(data), id)); err != nil {
AND NOT EXISTS(SELECT 1 FROM run_steps WHERE run_id=pipeline_runs.id AND agent_active=1)`, status, outcome, diagnostic, failureKind, failureReason, derivedClass, derivedClass, string(data), id)); err != nil {
return err
}
if err := enqueueRunTransitionNotification(ctx, tx, id); err != nil {
+5 -2
View File
@@ -85,6 +85,9 @@ CREATE TABLE IF NOT EXISTS retry_checkpoints (
return err
}
}
if err := s.initRunQuota(); err != nil {
return err
}
if err := s.dropResourceSchema(); err != nil {
return err
}
@@ -245,11 +248,11 @@ func (s *Store) RecoverRunsKeeping(ctx context.Context, keep map[int64]bool, rea
if _, err := tx.ExecContext(ctx, "UPDATE run_steps SET diagnostic=? WHERE run_id=? AND status='interrupted' AND sequence=(SELECT MAX(sequence) FROM run_steps WHERE run_id=?)", "Server restarted; "+reason, id, id); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET status='interrupted',diagnostic=?,failure_kind='unexpected',failure_reason=?,finished_at=CURRENT_TIMESTAMP WHERE id=? AND status IN ('queued','running') AND cancel_requested=0 AND cleanup_unconfirmed=0", "Server restarted; "+reason+"; run was not resumed", "Server restarted; "+reason+"; run was not resumed", id); err != nil {
if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET status='interrupted',diagnostic=?,failure_kind='unexpected',failure_reason=?,failure_class='interrupted',finished_at=CURRENT_TIMESTAMP WHERE id=? AND status IN ('queued','running') AND cancel_requested=0 AND cleanup_unconfirmed=0", "Server restarted; "+reason+"; run was not resumed", "Server restarted; "+reason+"; run was not resumed", id); err != nil {
return err
}
}
if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET status=CASE WHEN cancel_requested=1 THEN 'canceled' ELSE 'interrupted' END,diagnostic='Server stopped; owned sessions stopped; run was not resumed',failure_kind=CASE WHEN cancel_requested=1 THEN '' ELSE 'unexpected' END,failure_reason=CASE WHEN cancel_requested=1 THEN '' ELSE 'Server stopped; owned sessions stopped; run was not resumed' END,finished_at=CURRENT_TIMESTAMP WHERE status IN ('queued','running') AND status<>? AND cleanup_unconfirmed=0"+runFilter, append([]any{protocol.RunStatusWaiting}, keptArgs...)...); err != nil {
if _, err := tx.ExecContext(ctx, "UPDATE pipeline_runs SET status=CASE WHEN cancel_requested=1 THEN 'canceled' ELSE 'interrupted' END,diagnostic='Server stopped; owned sessions stopped; run was not resumed',failure_kind=CASE WHEN cancel_requested=1 THEN '' ELSE 'unexpected' END,failure_reason=CASE WHEN cancel_requested=1 THEN '' ELSE 'Server stopped; owned sessions stopped; run was not resumed' END,failure_class=CASE WHEN cancel_requested=1 THEN 'canceled' ELSE 'interrupted' END,finished_at=CURRENT_TIMESTAMP WHERE status IN ('queued','running') AND status<>? AND cleanup_unconfirmed=0"+runFilter, append([]any{protocol.RunStatusWaiting}, keptArgs...)...); err != nil {
return err
}
// An export checkpoint is a paused handoff, not an interrupted model call.
+6
View File
@@ -61,6 +61,12 @@ func (s *Store) UsageStats(ctx context.Context) (*protocol.UsageStats, error) {
return nil, err
}
stats.Usage = usage
if stats.FailureClasses, err = failureClassCounts(ctx, tx); err != nil {
return nil, err
}
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM pipeline_runs WHERE status=?`, protocol.RunStatusWaitingQuota).Scan(&stats.WaitingQuota); err != nil {
return nil, err
}
return stats, tx.Commit()
}