Files
pipelines/internal/server/run_quota_test.go
T
alan b3c9575fde 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>
2026-12-03 14:34:53 +00:00

407 lines
17 KiB
Go

package server
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
)
// quotaSource is a two-stage Claude pipeline whose stages loop on error, so a
// test sees the runner (not the definition) decide what a failure does.
const quotaSource = "# stage work\n\n```prompt\nDo the work.\n```\n\n```tools\nread\n```\n\n```edges\nsuccess -> review\nerror -> work\n```\n\n```limits\n{\"max_visits\":3,\"on\":[\"error\"]}\n```\n\n```configs\nharness=claude\nprovider=anthropic\nmodel=claude-haiku-5-5\nretries=0\n```\n\n" +
"# stage review\n\n```prompt\nReview the work.\n```\n\n```tools\nread\n```\n\n```edges\nsuccess -> #success\nblocked -> #failure\nerror -> work\n```\n\n```configs\nharness=claude\nprovider=anthropic\nmodel=claude-haiku-5-5\nretries=0\n```\n\n"
// quotaRunner submits quotaSource and returns a runner whose Claude account
// is fixed (no real Claude home is read) and whose clock the test controls.
func quotaRunner(t *testing.T) (context.Context, *runner, *pipeline.Store, int64, *atomic.Int64) {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
r, store, id := submitRunner(t, ctx, quotaSource)
t.Cleanup(func() {
cancel()
r.wg.Wait()
r.stopQuotaTimers()
store.Close()
})
clock := &atomic.Int64{}
clock.Store(time.Now().UnixNano())
r.quota.now = func() time.Time { return time.Unix(0, clock.Load()) }
r.quota.account = func(context.Context, string) string { return "/homes/a|a@example.com" }
return ctx, r, store, id, clock
}
func quotaLimited(resetsAt time.Time) error {
return fmt.Errorf("model stage work: HARNESS TRANSPORT: %w: %w", stage.ErrHarnessTransport, &stage.QuotaError{Subscription: true, ResetsAt: resetsAt})
}
func runStatus(t *testing.T, store *pipeline.Store, id int64) *protocol.RunDetail {
t.Helper()
detail, err := store.GetRun(context.Background(), id)
if err != nil {
t.Fatal(err)
}
return detail
}
func TestUsageLimitParksTheRunAndResumesTheSameVisit(t *testing.T) {
ctx, r, store, pipelineID, clock := quotaRunner(t)
reset := time.Unix(0, clock.Load()).Add(time.Hour).Truncate(time.Second)
var calls atomic.Int32
var resumedInput atomic.Value
r.execute = func(ctx context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
if def.Key == "work" && calls.Add(1) == 1 {
return stage.Result{}, quotaLimited(reset)
}
if def.Key == "work" {
data, _ := os.ReadFile(def.Turn.Input)
resumedInput.Store(string(data))
}
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
}
run := startRun(t, r, pipelineID, "quota-park")
parked := runStatus(t, store, run.ID)
if parked.Status != protocol.RunStatusWaitingQuota || parked.FinishedAt != "" || parked.QuotaWait == nil {
t.Fatalf("the run was not parked: %+v", parked.RunSummary)
}
wait := parked.QuotaWait
if wait.Sequence != 1 || wait.Stage != "work" || wait.ResetsAt != reset.UTC().Format(time.RFC3339) || wait.ResumeAt != reset.Add(time.Minute).UTC().Format(time.RFC3339) || wait.Account != "a@example.com" {
t.Fatalf("parking record %+v", wait)
}
if len(parked.Steps) != 1 || parked.Steps[0].Status != "failed" || parked.Steps[0].Target != "work" || strings.Contains(parked.Steps[0].Diagnostic, "top up") {
t.Fatalf("interrupted visit %+v", parked.Steps)
}
if parked.FailureClass != "" {
t.Fatalf("a parked run has no failure class: %q", parked.FailureClass)
}
r.quota.mu.Lock()
armed := r.quota.timers[run.ID] != nil
r.quota.mu.Unlock()
if !armed {
t.Fatal("no resume was scheduled")
}
// The account's limit is remembered for later admissions.
if at, ok, err := store.QuotaLimit(ctx, "/homes/a|a@example.com", time.Unix(0, clock.Load())); err != nil || !ok || !at.Equal(reset) {
t.Fatal("limit not recorded", at, ok, err)
}
// Resume now (the operator's action; the timer calls the same path).
if _, err := r.resumeQuota(run.ID); err != nil {
t.Fatal(err)
}
r.wg.Wait()
done := runStatus(t, store, run.ID)
if done.Status != "succeeded" || len(done.Steps) != 3 || done.QuotaWait != nil {
t.Fatalf("the resumed run did not finish: %+v %+v", done.RunSummary, done.Steps)
}
if done.Steps[1].Stage != "work" || done.Steps[1].Control == nil || done.Steps[1].Control.Visit != 1 {
t.Fatalf("the interrupted visit counted against the stage: %+v", done.Steps[1].Control)
}
input, _ := resumedInput.Load().(string)
if !strings.Contains(input, "# Previous attempt") || !strings.Contains(input, "interrupted") || !strings.Contains(input, "Partial edits") {
t.Fatalf("the resumed visit was not told about the interruption:\n%s", input)
}
if _, err := r.resumeQuota(run.ID); !errors.Is(err, pipeline.ErrInvalidRunTransition) {
t.Fatal("a second resume must be refused", err)
}
}
func TestUsageLimitSwitchesAccountAndRerunsAtOnce(t *testing.T) {
_, r, store, pipelineID, clock := quotaRunner(t)
var calls atomic.Int32
var switched atomic.Int32
r.quota.switchAccount = func(_ context.Context, workspace string, _ time.Time) (string, string, error) {
switched.Add(1)
return "a@example.com", "b@example.com", nil
}
r.execute = func(ctx context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
if def.Key == "work" && calls.Add(1) == 1 {
return stage.Result{}, quotaLimited(time.Unix(0, clock.Load()).Add(time.Hour))
}
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
}
run := startRun(t, r, pipelineID, "quota-switch")
done := runStatus(t, store, run.ID)
if done.Status != "succeeded" || len(done.Steps) != 3 || switched.Load() != 1 {
t.Fatalf("switch did not rerun the visit: %+v %+v", done.RunSummary, done.Steps)
}
if !strings.Contains(done.Steps[0].Diagnostic, "switched Claude account") || done.Steps[0].Target != "work" {
t.Fatalf("interrupted visit %+v", done.Steps[0])
}
}
func TestParkedRunSurvivesRestartAndCanBeCanceled(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "quota.db")
store, err := pipeline.Open(path)
if err != nil {
t.Fatal(err)
}
ctx, shutdown := context.WithCancel(context.Background())
if _, err := store.Submit(ctx, "quota", quotaSource); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
r, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
r.quota.account = func(context.Context, string) string { return "default|" }
reset := time.Now().Add(time.Hour)
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
return stage.Result{}, quotaLimited(reset)
}
parkedA := startRun(t, r, items[0].ID, "parked-a")
parkedB := startRun(t, r, items[0].ID, "parked-b")
shutdown()
r.wg.Wait()
r.stopQuotaTimers()
store.Close()
store, err = pipeline.Open(path)
if err != nil {
t.Fatal(err)
}
defer store.Close()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
r, err = newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
defer func() { r.wg.Wait(); r.stopQuotaTimers() }()
for _, id := range []int64{parkedA.ID, parkedB.ID} {
if status := runStatus(t, store, id).Status; status != protocol.RunStatusWaitingQuota {
t.Fatalf("run %d did not stay parked across the restart: %s", id, status)
}
}
// Cancel B while it waits: no goroutine holds it.
if err := r.cancel(parkedB.ID); err != nil {
t.Fatal(err)
}
canceled := runStatus(t, store, parkedB.ID)
if canceled.Status != protocol.RunStatusCanceled || canceled.FailureClass != protocol.FailureCanceled || canceled.FinishedAt == "" {
t.Fatalf("cancel of a parked run: %+v", canceled.RunSummary)
}
// The restarted server's clock is past A's resume time: it resumes.
r.quota.now = func() time.Time { return reset.Add(2 * time.Minute) }
r.quota.account = func(context.Context, string) string { return "default|" }
var mu sync.Mutex
var visits []string
r.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
mu.Lock()
visits = append(visits, def.Key)
mu.Unlock()
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
}
r.armParkedRuns()
deadline := time.Now().Add(10 * time.Second)
for runStatus(t, store, parkedA.ID).Status != "succeeded" {
if time.Now().After(deadline) {
t.Fatalf("the parked run was not resumed after the restart: %+v", runStatus(t, store, parkedA.ID).RunSummary)
}
time.Sleep(20 * time.Millisecond)
}
r.wg.Wait()
mu.Lock()
defer mu.Unlock()
if strings.Join(visits, ",") != "work,review" {
t.Fatalf("resumed visits %v", visits)
}
if status := runStatus(t, store, parkedB.ID).Status; status != protocol.RunStatusCanceled {
t.Fatalf("the canceled run came back: %s", status)
}
}
func TestKnownUsageLimitDefersOrRefusesNewRunsAndRetries(t *testing.T) {
ctx, r, store, pipelineID, clock := quotaRunner(t)
reset := time.Unix(0, clock.Load()).Add(30 * time.Minute)
if err := store.RecordQuotaLimit(ctx, "/homes/a|a@example.com", reset); err != nil {
t.Fatal(err)
}
var calls atomic.Int32
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
calls.Add(1)
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
}
workspace := t.TempDir()
request := func(key, policy string) protocol.Message {
return protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: key, Workspace: workspace, Input: map[string]any{"prompt": "task"}, QuotaPolicy: policy}
}
if _, err := r.start(request("refused", protocol.QuotaRefuse)); err == nil || !strings.Contains(err.Error(), "resets at") {
t.Fatal("refuse policy did not refuse", err)
}
deferred, err := r.start(request("deferred", ""))
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
if deferred.Status != protocol.RunStatusWaitingQuota || deferred.QuotaWait == nil || deferred.QuotaWait.Sequence != 0 || calls.Load() != 0 {
t.Fatalf("the run was not deferred: %+v", deferred.RunSummary)
}
// A replay of the same request returns the deferred run, not a new one.
if replay, err := r.start(request("deferred", "")); err != nil || replay.ID != deferred.ID {
t.Fatal("replay", replay, err)
}
// The deferred run starts (here: resume now) and runs from its entry.
if _, err := r.resumeQuota(deferred.ID); err != nil {
t.Fatal(err)
}
r.wg.Wait()
if done := runStatus(t, store, deferred.ID); done.Status != "succeeded" || calls.Load() != 2 {
t.Fatalf("the deferred run did not run: %+v", done.RunSummary)
}
// quota_policy=now starts at once anyway.
now, err := r.start(request("now", protocol.QuotaNow))
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
if done := runStatus(t, store, now.ID); done.Status != "succeeded" {
t.Fatalf("quota_policy=now did not start: %+v", done.RunSummary)
}
// A retry is deferred the same way.
r.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
if def.Key == "review" {
return stage.Result{Outcome: "blocked", Output: stage.Values{"summary": "no"}}, nil
}
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
}
failed, err := r.start(request("to-retry", protocol.QuotaNow))
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
if detail := runStatus(t, store, failed.ID); detail.Status != "failed" || detail.FailureClass != protocol.FailureBlocked {
t.Fatalf("blocked run: %+v", detail.RunSummary)
}
retried, err := r.retry(protocol.Message{RunID: failed.ID, RequestKey: "retry-1"})
if err != nil {
t.Fatal(err)
}
if retried.Status != protocol.RunStatusWaitingQuota {
t.Fatalf("the retry was not deferred: %+v", retried.RunSummary)
}
if _, err := r.retry(protocol.Message{RunID: failed.ID, RequestKey: "retry-2", QuotaPolicy: protocol.QuotaRefuse}); err == nil {
t.Fatal("a refuse-policy retry into a known limit was admitted")
}
stats, err := store.UsageStats(ctx)
if err != nil {
t.Fatal(err)
}
if stats.WaitingQuota != 1 || stats.FailureClasses[protocol.FailureBlocked] != 1 {
t.Fatalf("stats: waiting_quota %d, classes %v", stats.WaitingQuota, stats.FailureClasses)
}
}
func TestFailureClassesAndErrorLoopPolicy(t *testing.T) {
saved := errorLoopBackoff
errorLoopBackoff = []time.Duration{5 * time.Millisecond, 10 * time.Millisecond}
t.Cleanup(func() { errorLoopBackoff = saved })
for _, tc := range []struct {
name string
errs []error
status string
class string
visits int
reason string
}{
{name: "deterministic", errs: []error{fmt.Errorf("%w: invalid argument --tools", stage.ErrHarnessTransport)}, status: "failed", class: protocol.FailureHarnessError, visits: 1, reason: "repeats on every attempt"},
{name: "repeated-readback", errs: []error{fmt.Errorf("%w: final assistant readback contained no assistant message", stage.ErrHarnessTransport), fmt.Errorf("%w: final assistant readback contained no assistant message", stage.ErrHarnessTransport)}, status: "failed", class: protocol.FailureHarnessError, visits: 2, reason: "same harness failure repeated"},
{name: "transient", errs: []error{fmt.Errorf("%w: connection reset", stage.ErrHarnessTransport), fmt.Errorf("%w: 503 overloaded", stage.ErrHarnessTransport)}, status: "succeeded", visits: 3},
{name: "permission", errs: []error{fmt.Errorf("model stage work: %w", &stage.PermissionDeniedError{Denials: []string{"Bash(git push)"}})}, status: "failed", class: protocol.FailurePermissionDenied, visits: 1, reason: "Bash(git push)"},
{name: "loop", errs: []error{errors.New("a"), errors.New("b"), errors.New("c")}, status: "failed", class: protocol.FailureLoopExhausted, visits: 3},
{name: "timeout", errs: []error{fmt.Errorf("x: %w", context.DeadlineExceeded), fmt.Errorf("x: %w", context.DeadlineExceeded), fmt.Errorf("x: %w", context.DeadlineExceeded)}, status: "failed", class: protocol.FailureLoopExhausted, visits: 3},
} {
t.Run(tc.name, func(t *testing.T) {
_, r, store, pipelineID, _ := quotaRunner(t)
var calls atomic.Int32
r.execute = func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
if def.Key == "work" {
if n := int(calls.Add(1)); n <= len(tc.errs) {
return stage.Result{}, tc.errs[n-1]
}
}
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
}
run := startRun(t, r, pipelineID, "class-"+tc.name)
detail := runStatus(t, store, run.ID)
if detail.Status != tc.status || detail.FailureClass != tc.class {
t.Fatalf("status %s class %q, want %s %q (%s)", detail.Status, detail.FailureClass, tc.status, tc.class, detail.Diagnostic)
}
if got := int(calls.Load()); got != tc.visits {
t.Fatalf("%d visits of work, want %d", got, tc.visits)
}
if tc.reason != "" && !strings.Contains(detail.Diagnostic, tc.reason) {
t.Fatalf("diagnostic %q does not say %q", detail.Diagnostic, tc.reason)
}
})
}
}
func TestRunBudgetWarnsAndStops(t *testing.T) {
ctx, r, store, pipelineID, _ := quotaRunner(t)
r.execute = func(ctx context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
cost := 0.85
if def.Key == "review" {
cost = 0.30
}
if err := stage.BudgetFrom(ctx).ObserveCost("session-"+def.Key, cost); err != nil {
return stage.Result{}, err
}
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
}
run, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "budget", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}, BudgetUSD: 1})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
detail := runStatus(t, store, run.ID)
if detail.Status != "failed" || detail.FailureClass != protocol.FailureBudget || len(detail.Steps) != 2 {
t.Fatalf("budget stop: %+v %+v", detail.RunSummary, detail.Steps)
}
// review's error edge leads back to work; a spent run budget does not.
if detail.Steps[1].Target != protocol.FailureEnd {
t.Fatalf("budget stop followed the error edge: %+v", detail.Steps[1])
}
if detail.Budget == nil || detail.Budget.LimitUSD != 1 || detail.Budget.Source != "run" || !detail.Budget.Warned {
t.Fatalf("budget record %+v", detail.Budget)
}
notes, err := store.RunNotifications(ctx, run.ID)
if err != nil {
t.Fatal(err)
}
warned := false
for _, n := range notes {
warned = warned || n.Event == "budget_warning"
}
if !warned {
t.Fatalf("no 80%% warning was queued: %+v", notes)
}
}
func TestServerDefaultRunBudget(t *testing.T) {
ctx, r, store, pipelineID, _ := quotaRunner(t)
if _, err := store.SetRunSettings(ctx, protocol.RunSettings{DefaultBudgetUSD: -1}); err == nil {
t.Fatal("a negative default was accepted")
}
if _, err := store.SetRunSettings(ctx, protocol.RunSettings{DefaultBudgetUSD: 5}); err != nil {
t.Fatal(err)
}
r.execute = successExecute
run := startRun(t, r, pipelineID, "default-budget")
detail := runStatus(t, store, run.ID)
if detail.Budget == nil || detail.Budget.LimitUSD != 5 || detail.Budget.Source != "server" || detail.FailureClass != "" {
t.Fatalf("default budget %+v class %q", detail.Budget, detail.FailureClass)
}
}