Runs park on usage limits; failure classes, harness error policy, run budgets
- A stage refused for a Claude usage limit no longer fails its run: the runner tries the chats' Claude account auto-switch (per-home setting) and reruns the visit, else parks the run in the new waiting_quota status (persisted, with reset/resume time in run summaries, details and events) and resumes the same visit at reset + 1 min, also after a restart. resume_run / `pipelines resume` resumes now; cancel works on parked runs. The rerun visit gets a "# Previous attempt" interruption note. Subscription limits no longer say "top up the provider account". - run/retry into an account known to be limited are deferred (quota_policy defer/refuse/now; CLI refuses under --json/--yes unless --defer or --now). - failure_class on runs (quota, loop_exhausted, timeout, permission_denied, harness_error, blocked, environment, canceled, interrupted, budget, check_failed, other) in RunSummary/RunDetail/events, CLI inspect/runs/wait/ stats and the app failure line. - Claude permission denials (permission_denials / refused tool results) fail a blocked visit with permission_denied naming the tool use. - Harness failures are classified transient vs deterministic; deterministic ones (and a repeated empty readback) skip error self-loops; transient self-loops back off 15 s, 1 min, 4 min. - Whole-run USD budget: run --budget, server default (run-budget / get/set_run_settings); 80% warning notification, stop with class budget. - App: waiting_quota status/filter with resume time, Resume now and Cancel, failure class wording. Docs and skill references updated. Merges main (check stage, delivery gate, Claude stage restart survival, schedule changes). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
)
|
||||
|
||||
func checkStageSource(key, commands, configs, edges string) string {
|
||||
return "# stage " + key + "\n\n```configs\ntype=check\n" + configs + "\n```\n\n```commands\n" + commands + "\n```\n\n```edges\n" + edges + "\n```\n"
|
||||
}
|
||||
|
||||
// A check stage sits between implement and review: a red tree goes back to
|
||||
// the implementer with the failing output, never to the reviewer.
|
||||
func TestParseCheckStageBeforeReview(t *testing.T) {
|
||||
source := lintSource(
|
||||
modelStage("implement", "Make the change.", "read\nedit\nshell", "success -> verify\nerror -> #failure", "```checks\nnone: the verify stage runs the suite\n```"),
|
||||
checkStageSource("verify", "go vet ./...\ngo test ./...", "command_timeout=15m", "pass -> review\nfail -> implement"),
|
||||
modelStage("review", "Review the diff.", "read\nglob\ngrep", "success -> #success\nerror -> #failure", ""),
|
||||
)
|
||||
g, err := ParseDefinition(source)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
verify := g.Stages[1]
|
||||
if verify.Type != stage.CheckType || verify.Blocks["commands"] != "go vet ./...\ngo test ./..." || verify.Configs["command_timeout"] != "15m" {
|
||||
t.Fatalf("parsed %+v", verify)
|
||||
}
|
||||
if verify.Edges["error"] != "#failure" || !verify.FallbackError {
|
||||
t.Fatal("check stage error edge", verify.Edges)
|
||||
}
|
||||
def := StageDefinition(verify)
|
||||
if _, err := stage.CheckStageSpec(def); err != nil {
|
||||
t.Fatal("stored definition no longer validates:", err)
|
||||
}
|
||||
errs, _ := Lint(g)
|
||||
var rules []string
|
||||
for _, finding := range errs {
|
||||
rules = append(rules, finding.String())
|
||||
}
|
||||
// fail -> implement loops back: the existing loop rule asks for a limit.
|
||||
if len(errs) != 1 || errs[0].Rule != "limits" {
|
||||
t.Fatalf("lint %v", rules)
|
||||
}
|
||||
limited := strings.Replace(source, "```configs\ntype=check", "```limits\n{\"max_visits\":3}\n```\n\n```configs\ntype=check", 1)
|
||||
if g, err = ParseDefinition(limited); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if errs, _ := Lint(g); len(errs) != 0 {
|
||||
t.Fatal(errs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckStageRejectsModelBlocksAndSilentGuards(t *testing.T) {
|
||||
if _, err := ParseDefinition(checkStageSource("verify", "go test ./...", "model=x", "pass -> #success\nfail -> #failure")); err == nil {
|
||||
t.Fatal("model config accepted on a check stage")
|
||||
}
|
||||
if _, err := ParseDefinition(checkStageSource("verify", "", "", "pass -> #success\nfail -> #failure")); err == nil {
|
||||
t.Fatal("empty commands accepted")
|
||||
}
|
||||
g, err := ParseDefinition(checkStageSource("verify", "ruff check . || true", "", "pass -> #success\nfail -> #failure"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
errs, _ := Lint(g)
|
||||
if len(errs) != 1 || errs[0].Rule != "commands" {
|
||||
t.Fatal(errs)
|
||||
}
|
||||
}
|
||||
|
||||
// A delivery check stage is the landing gate: its commands are the checks the
|
||||
// server runs on the committed candidate before fast-forwarding main.
|
||||
func TestCheckStageAsLandingGateSatisfiesDeliveryLint(t *testing.T) {
|
||||
source := lintSource(
|
||||
modelStage("implement", "Make the change; the delivery gate lands it.", "read\nedit\nshell", "success -> land\nerror -> #failure", "```checks\nnone: the land gate runs the suite\n```"),
|
||||
checkStageSource("land", "go test ./...", "delivery=true", "pass -> #success\nfail -> #failure"),
|
||||
)
|
||||
g, err := ParseDefinition(source)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if errs, _ := Lint(g); len(errs) != 0 {
|
||||
t.Fatal(errs)
|
||||
}
|
||||
if enabled, err := stage.DeliveryEnabled(StageDefinition(g.Stages[1])); err != nil || !enabled {
|
||||
t.Fatal(enabled, err)
|
||||
}
|
||||
}
|
||||
@@ -90,6 +90,13 @@ func Lint(g Graph) (errs, warnings []LintFinding) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if stage.EffectiveType(s.Type) == stage.CheckType {
|
||||
for _, line := range strings.Split(s.Blocks["commands"], "\n") {
|
||||
if guard := silentGuard(line); guard != "" {
|
||||
add(&errs, s, "commands", "command %q can pass without running anything (%s); a missing tool must fail the check, so remove the guard", strings.TrimSpace(line), guard)
|
||||
}
|
||||
}
|
||||
}
|
||||
if stage.EffectiveType(s.Type) == stage.HumanType {
|
||||
continue // a person bounds a human stage's loop
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
// RunWritePaths returns the write paths a run declared (relative to its
|
||||
// workspace; empty when it declared none). The workspace reservation check
|
||||
// reads it only when two runs' workspaces nest outside any repository.
|
||||
func (s *Store) RunWritePaths(ctx context.Context, id int64) ([]string, error) {
|
||||
var encoded string
|
||||
if err := s.db.QueryRowContext(ctx, "SELECT write_paths FROM pipeline_runs WHERE id=?", id).Scan(&encoded); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var paths []string
|
||||
if encoded == "" {
|
||||
return nil, nil
|
||||
}
|
||||
if err := json.Unmarshal([]byte(encoded), &paths); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return paths, nil
|
||||
}
|
||||
@@ -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, "a.ResetsAt, "a.ResumeAt, "a.Sequence, "a.Stage, "a.Account, &budget.LimitUSD, &budget.Source, &budget.Warned); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.Status == protocol.RunStatusWaitingQuota {
|
||||
r.QuotaWait = "a
|
||||
}
|
||||
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
|
||||
@@ -313,6 +326,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 {
|
||||
|
||||
@@ -99,7 +99,7 @@ func (s *Store) CreateRunTitled(ctx context.Context, d *protocol.PipelineDetail,
|
||||
// Acquire the SQLite writer lock while checking the original saved
|
||||
// revision and occurrence. Edits/deletes between claim and admission
|
||||
// invalidate admission, including while a title was being generated.
|
||||
result, err := tx.ExecContext(ctx, `UPDATE saved_schedule_events SET status='admitted' WHERE schedule_id=? AND due=? AND revision=? AND status='claimed' AND run_id IS NULL AND EXISTS(SELECT 1 FROM saved_schedules WHERE id=? AND revision=? AND enabled=1 AND deleted=0)`, origin.ID, origin.Due.UTC().Format(time.RFC3339Nano), origin.Revision, origin.ID, origin.Revision)
|
||||
result, err := tx.ExecContext(ctx, `UPDATE saved_schedule_events SET status='admitted' WHERE schedule_id=? AND due=? AND revision=? AND status IN ('claimed','delayed') AND run_id IS NULL AND EXISTS(SELECT 1 FROM saved_schedules WHERE id=? AND revision=? AND enabled=1 AND deleted=0)`, origin.ID, origin.Due.UTC().Format(time.RFC3339Nano), origin.Revision, origin.ID, origin.Revision)
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
|
||||
@@ -355,8 +355,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
|
||||
}
|
||||
@@ -377,7 +378,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 {
|
||||
@@ -391,14 +392,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 {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -409,6 +409,15 @@ func (s *Store) FinishSavedSchedule(ctx context.Context, id int64, due time.Time
|
||||
return err
|
||||
}
|
||||
|
||||
// SavedScheduleOccurrence reads one occurrence's history entry: its status
|
||||
// (claimed, delayed, admitted, started, skipped, skipped_missed, skipped_day),
|
||||
// diagnostic and admitted run (0 when none).
|
||||
func (s *Store) SavedScheduleOccurrence(ctx context.Context, id int64, due time.Time) (status, diagnostic string, runID int64, err error) {
|
||||
var run sql.NullInt64
|
||||
err = s.db.QueryRowContext(ctx, `SELECT status,diagnostic,run_id FROM saved_schedule_events WHERE schedule_id=? AND due=?`, id, due.UTC().Format(time.RFC3339Nano)).Scan(&status, &diagnostic, &run)
|
||||
return status, diagnostic, run.Int64, err
|
||||
}
|
||||
|
||||
// ScheduleAdmission is an internal capability, never decoded from public messages.
|
||||
type ScheduleAdmission struct {
|
||||
ID, Revision int64
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user