Files
pipelines/internal/server/run_quota.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

412 lines
16 KiB
Go

package server
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"os"
"strings"
"sync"
"time"
"git.a-wan.net/alan/pipelines/internal/claude"
"git.a-wan.net/alan/pipelines/internal/claudeaccounts"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
"git.a-wan.net/alan/pipelines/internal/turn"
"git.a-wan.net/alan/pipelines/internal/workenv"
)
// Usage limits park runs instead of failing them.
//
// When a stage is refused for a provider usage limit the runner first tries
// the Claude account auto-switch chats use (the home's own setting decides);
// on a switch the same visit runs again at once on the new account. Otherwise
// the run is parked in waiting_quota with the reset time and resumes the same
// visit a minute after the reset (quotaResumeMargin). The parked state lives
// in the run row, so start-up re-arms the timers. Either way the visit that
// runs again is told, in a "# Previous attempt" note, that the limit
// interrupted it and partial edits may be in the worktree.
//
// A run or retry admitted while the account its Claude stages use is known
// to be out of usage is deferred the same way before its first stage (or
// refused, or started anyway: protocol.QuotaPolicy).
const (
// quotaResumeMargin is how long after the reset a parked run resumes.
quotaResumeMargin = time.Minute
// quotaFallbackHold is the wait when a refusal named no reset time.
quotaFallbackHold = time.Hour
// quotaBusyRetry is the wait before trying again when the run's
// workspace is held by another run at resume time.
quotaBusyRetry = time.Minute
)
// quotaState is the runner's usage-limit collaborators and timers.
type quotaState struct {
mu sync.Mutex
timers map[int64]*time.Timer
// switchAccount signs workspace's Claude home in to another saved
// account with usage left (the chats' auto-switch); nil means no switch
// is possible. It reports the accounts switched from and to.
switchAccount func(ctx context.Context, workspace string, resetsAt time.Time) (from, to string, err error)
// account names the Claude account a run in workspace uses; nil uses
// claudeAccountKey.
account func(ctx context.Context, workspace string) string
// now is the clock; nil is time.Now.
now func() time.Time
}
func (r *runner) quotaNow() time.Time {
if r.quota.now != nil {
return r.quota.now()
}
return time.Now()
}
// quotaAccount names the account a run in workspace uses for its Claude
// stages: its Claude home and the account signed in there.
func (r *runner) quotaAccount(ctx context.Context, workspace string) string {
if r.quota.account != nil {
return r.quota.account(ctx, workspace)
}
resolver := r.dirEnv
if resolver == nil {
resolver = workenv.Default
}
return claudeAccountKey(ctx, resolver, workspace)
}
// claudeAccountKey is "<home>|<email>": the CLAUDE_CONFIG_DIR a process in
// workspace runs with ("default" for the user's own ~/.claude) and the
// account signed in there when its files say.
func claudeAccountKey(ctx context.Context, resolver *workenv.Resolver, workspace string) string {
home, err := claude.AccountConfigDir(ctx, resolver, workspace, os.Environ())
if err != nil {
return "default|"
}
email, _, _, ok := claudeaccounts.Store{ConfigDir: home}.Identity()
if !ok {
email = ""
}
return home + "|" + strings.ToLower(strings.TrimSpace(email))
}
// quotaAccountLabel is the operator-facing name of an account key.
func quotaAccountLabel(account string) string {
home, email, _ := strings.Cut(account, "|")
switch {
case email != "":
return email
case home == "default" || home == "":
return "the server's Claude account"
}
return "the Claude account of " + home
}
// usesClaudeHarness reports whether any model stage of graph runs on the
// Claude harness (the only one whose usage windows reset on their own).
func usesClaudeHarness(graph protocol.Graph) bool {
for _, s := range graph.Stages {
if stage.EffectiveType(s.Type) == stage.ModelType && s.Configs["harness"] == stage.ClaudeBackend {
return true
}
}
return false
}
// quotaAdmission is what start does about a known usage limit.
type quotaAdmission struct {
account string
resetsAt time.Time
}
// knownQuotaLimit reports a known, unexpired usage limit of the account the
// graph's Claude stages would use in workspace.
func (r *runner) knownQuotaLimit(graph protocol.Graph, workspace string) (quotaAdmission, bool) {
if !usesClaudeHarness(graph) {
return quotaAdmission{}, false
}
ctx, cancel := context.WithTimeout(r.ctx, 10*time.Second)
defer cancel()
if any, err := r.store.AnyQuotaLimit(ctx, r.quotaNow()); err != nil || !any {
return quotaAdmission{}, false
}
account := r.quotaAccount(ctx, workspace)
resetsAt, ok, err := r.store.QuotaLimit(ctx, account, r.quotaNow())
if err != nil || !ok {
return quotaAdmission{}, false
}
return quotaAdmission{account: account, resetsAt: resetsAt}, true
}
// quotaRefusal is the error a refuse policy answers with.
func quotaRefusal(limit quotaAdmission) error {
return fmt.Errorf("the Claude usage limit of %s resets at %s; not starting into a known limit: queue the run to start at the reset (quota_policy=defer) or start it now anyway (quota_policy=now)", quotaAccountLabel(limit.account), limit.resetsAt.Local().Format("15:04 on 2 Jan"))
}
// deferredLaunch is the admitted request of a run deferred before its first
// stage, persisted so the start survives a restart.
type deferredLaunch struct {
Request protocol.Message `json:"request"`
RetrySource int64 `json:"retry_source,omitempty"`
}
// deferLaunch parks a just-created run before its first stage. Callers hold
// r.mu; the run is not in r.active.
func (r *runner) deferLaunch(id int64, workspace string, request protocol.Message, limit quotaAdmission) error {
data, err := json.Marshal(deferredLaunch{Request: request, RetrySource: request.RetrySource})
if err != nil {
return err
}
resumeAt := limit.resetsAt.Add(quotaResumeMargin)
diagnostic := fmt.Sprintf("Deferred: the Claude usage limit of %s resets at %s; the run starts at %s", quotaAccountLabel(limit.account), limit.resetsAt.Local().Format("15:04 on 2 Jan"), resumeAt.Local().Format("15:04"))
save, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := r.store.ParkRunForQuota(save, id, 0, "", quotaAccountLabel(limit.account), limit.resetsAt, resumeAt, diagnostic, string(data)); err != nil {
return err
}
r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: workspace, Status: protocol.RunStatusWaitingQuota, QuotaWait: quotaWaitFrame(0, "", limit.account, limit.resetsAt, resumeAt)}, false)
r.armQuotaResume(id, resumeAt)
return nil
}
func quotaWaitFrame(sequence int, stageKey, account string, resetsAt, resumeAt time.Time) *protocol.RunQuotaWait {
return &protocol.RunQuotaWait{ResetsAt: resetsAt.UTC().Format(time.RFC3339), ResumeAt: resumeAt.UTC().Format(time.RFC3339), Sequence: sequence, Stage: stageKey, Account: quotaAccountLabel(account)}
}
// quotaDecision is what the loop does about a visit refused for usage.
type quotaDecision struct {
// rerun: the home switched accounts; run the visit again now.
rerun bool
// park: wait for the reset.
park bool
account string
resetsAt time.Time
note string
}
// decideQuota handles a visit refused for a usage limit: it records the
// account's limit, then switches accounts or parks. An exhausted paid
// balance (no reset of its own) still fails the run.
func (r *runner) decideQuota(ctx context.Context, workspace string, err error) quotaDecision {
if !stage.SubscriptionQuota(err) {
return quotaDecision{}
}
now := r.quotaNow()
resetsAt, known := stage.QuotaResetsAt(err)
if !known || !resetsAt.After(now) {
resetsAt = now.Add(quotaFallbackHold)
}
lookup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
defer cancel()
account := r.quotaAccount(lookup, workspace)
if recordErr := r.store.RecordQuotaLimit(lookup, account, resetsAt); recordErr != nil {
log.Printf("record usage limit of %s: %v", quotaAccountLabel(account), recordErr)
}
if r.quota.switchAccount != nil {
switchCtx, switchCancel := context.WithTimeout(context.WithoutCancel(ctx), time.Minute)
from, to, switchErr := r.quota.switchAccount(switchCtx, workspace, resetsAt)
switchCancel()
if switchErr == nil && to != "" {
if from == "" {
from = "the previous account"
}
return quotaDecision{rerun: true, account: account, resetsAt: resetsAt, note: fmt.Sprintf("The Claude usage limit of %s interrupted this visit; Pipelines switched the Claude home to %s and runs the visit again.", from, to)}
}
if switchErr != nil && !errors.Is(switchErr, claude.ErrAutoSwitchOff) && !errors.Is(switchErr, claude.ErrNoAccountLeft) && !errors.Is(switchErr, claude.ErrNoConfigDir) && !errors.Is(switchErr, errNotClaudeChat) {
log.Printf("run workspace %s: Claude account auto-switch: %v", workspace, switchErr)
}
}
return quotaDecision{park: true, account: account, resetsAt: resetsAt, note: fmt.Sprintf("The Claude usage limit of %s interrupted this visit; the run waited for the limit to reset at %s and resumed the visit.", quotaAccountLabel(account), resetsAt.Local().Format("15:04 on 2 Jan"))}
}
// quotaPreviousAttempt is the note the visit that runs again receives.
func quotaPreviousAttempt(stageKey, note string) string {
return turn.RenderPreviousAttempt(turn.PreviousAttempt{Attempt: 2, Stage: stageKey, Interruption: note})
}
// parkForQuota parks the run after its interrupted visit was recorded.
func (r *runner) parkForQuota(id int64, workspace string, sequence int, stageKey string, completed int, decision quotaDecision) {
resumeAt := decision.resetsAt.Add(quotaResumeMargin)
diagnostic := fmt.Sprintf("Waiting for the Claude usage limit of %s to reset at %s; stage %s resumes at %s", quotaAccountLabel(decision.account), decision.resetsAt.Local().Format("15:04 on 2 Jan"), stageKey, resumeAt.Local().Format("15:04"))
r.mu.Lock()
save, cancel := context.WithTimeout(context.Background(), 10*time.Second)
err := r.store.ParkRunForQuota(save, id, sequence, stageKey, quotaAccountLabel(decision.account), decision.resetsAt, resumeAt, diagnostic, "")
cancel()
if err != nil {
r.mu.Unlock()
log.Printf("run %d: park for the usage limit: %v; finishing it failed", id, err)
r.finishRunStateClass(id, "", workspace, "failed", "error", diagnostic, completed, sequence, stageKey, nil, protocol.FailureQuota)
return
}
r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: workspace, Status: protocol.RunStatusWaitingQuota, CurrentStage: stageKey, CompletedSteps: completed, QuotaWait: quotaWaitFrame(sequence, stageKey, decision.account, decision.resetsAt, resumeAt)}, false)
// Like a human wait, a parked run holds no goroutine and no workspace
// reservation; the resume checks the workspace is free again.
delete(r.active, id)
r.mu.Unlock()
r.deliverRunNotificationBatch(time.Now(), 1)
r.armQuotaResume(id, resumeAt)
}
// armQuotaResume (re)schedules a parked run's resume.
func (r *runner) armQuotaResume(id int64, at time.Time) {
delay := max(at.Sub(r.quotaNow()), 0)
r.quota.mu.Lock()
defer r.quota.mu.Unlock()
if r.quota.timers == nil {
r.quota.timers = map[int64]*time.Timer{}
}
if old := r.quota.timers[id]; old != nil {
old.Stop()
}
r.quota.timers[id] = time.AfterFunc(delay, func() {
r.quota.mu.Lock()
delete(r.quota.timers, id)
r.quota.mu.Unlock()
if r.ctx.Err() != nil {
return
}
if _, err := r.resumeQuota(id); err != nil {
if errors.Is(err, errQuotaWorkspaceBusy) {
r.armQuotaResume(id, r.quotaNow().Add(quotaBusyRetry))
return
}
if !errors.Is(err, pipeline.ErrInvalidRunTransition) {
log.Printf("run %d: resume after the usage limit: %v", id, err)
}
}
})
}
// disarmQuotaResume drops a parked run's timer (canceled or deleted).
func (r *runner) disarmQuotaResume(id int64) {
r.quota.mu.Lock()
defer r.quota.mu.Unlock()
if timer := r.quota.timers[id]; timer != nil {
timer.Stop()
delete(r.quota.timers, id)
}
}
// stopQuotaTimers stops every pending resume (server shutdown).
func (r *runner) stopQuotaTimers() {
r.quota.mu.Lock()
defer r.quota.mu.Unlock()
for id, timer := range r.quota.timers {
timer.Stop()
delete(r.quota.timers, id)
}
}
// armParkedRuns re-arms the resume of every run a previous process parked.
func (r *runner) armParkedRuns() {
ctx, cancel := context.WithTimeout(r.ctx, 10*time.Second)
defer cancel()
parked, err := r.store.QuotaParkedRuns(ctx)
if err != nil {
log.Printf("list runs waiting for a usage limit: %v", err)
return
}
for _, p := range parked {
resumeAt := p.ResumeAt
if resumeAt.IsZero() {
resumeAt = r.quotaNow()
}
r.armQuotaResume(p.RunID, resumeAt)
}
}
var errQuotaWorkspaceBusy = errors.New("the run's workspace is held by another run")
// resumeQuota resumes a parked run now: the interrupted visit runs again, or
// a deferred run starts. Both the timer and the operator's "resume now" use
// it; the store's transition makes it happen at most once.
func (r *runner) resumeQuota(id int64) (*protocol.RunDetail, error) {
if id <= 0 {
return nil, fmt.Errorf("resume requires a positive run ID")
}
r.mu.Lock()
ctx, cancel := context.WithTimeout(r.ctx, 10*time.Second)
detail, err := r.store.GetRun(ctx, id)
if err != nil {
cancel()
r.mu.Unlock()
return nil, err
}
if detail.Status != protocol.RunStatusWaitingQuota {
cancel()
r.mu.Unlock()
return nil, fmt.Errorf("%w: run %d is not waiting for a usage limit (it is %s)", pipeline.ErrInvalidRunTransition, id, detail.Status)
}
if _, busy := r.active[id]; busy {
cancel()
r.mu.Unlock()
return nil, fmt.Errorf("run %d is still settling; try again in a moment", id)
}
if err := r.checkWorkspaceFree(detail.Workspace); err != nil {
cancel()
r.mu.Unlock()
return nil, fmt.Errorf("%w: %v", errQuotaWorkspaceBusy, err)
}
parking, err := r.store.UnparkQuotaRun(ctx, id)
cancel()
if err != nil {
r.mu.Unlock()
return nil, err
}
r.disarmQuotaResume(id)
r.rememberRunIdentity(id, identityOfRunSummary(detail.RunSummary))
workspace := detail.Workspace
if parking.Sequence == 0 {
var launch deferredLaunch
if err := json.Unmarshal([]byte(parking.Deferred), &launch); err != nil {
r.mu.Unlock()
r.finishRunStateClass(id, detail.Name, workspace, "failed", "error", "deferred launch request is unreadable: "+err.Error(), 0, 0, "", nil, protocol.FailureOther)
return r.getRun(id)
}
request := launch.Request
request.RetrySource = launch.RetrySource
d, err := r.store.Get(r.ctx, detail.PipelineID, detail.Version)
if err != nil {
r.mu.Unlock()
r.finishRunStateClass(id, detail.Name, workspace, "failed", "error", err.Error(), 0, 0, "", nil, protocol.FailureOther)
return r.getRun(id)
}
r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: workspace, Status: protocol.RunStatusQueued}, false)
r.launch(id, workspace, func(ctx context.Context) {
r.run(ctx, id, d, workspace, request)
})
r.mu.Unlock()
return r.getRun(id)
}
var interrupted *protocol.RunStep
for i := range detail.Steps {
if detail.Steps[i].Sequence == parking.Sequence {
interrupted = &detail.Steps[i]
}
}
if interrupted == nil {
r.mu.Unlock()
r.finishRunStateClass(id, detail.Name, workspace, "failed", "error", fmt.Sprintf("the visit interrupted by the usage limit (#%d) is missing", parking.Sequence), completedSteps(detail.Steps), parking.Sequence, parking.Stage, nil, protocol.FailureQuota)
return r.getRun(id)
}
step := *interrupted
r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: workspace, Status: protocol.RunStatusRunning, CurrentStage: step.Stage, CompletedSteps: completedSteps(detail.Steps)}, false)
note := fmt.Sprintf("The Claude usage limit of %s interrupted this visit; the run waited for the limit to reset at %s and resumed the visit.", parking.Account, parking.ResetsAt.Local().Format("15:04 on 2 Jan"))
r.launch(id, workspace, func(ctx context.Context) {
state := rebuildRunState(detail, protocol.RunStep{Target: step.Stage, Output: step.Input})
// The interrupted visit does not count against the stage's limits.
if state.visits[step.Stage] > 0 {
state.visits[step.Stage]--
}
state.previousAttempt = quotaPreviousAttempt(step.Stage, note)
r.runLoop(ctx, id, detail.Graph, detail.Name, workspace, protocol.Message{WritePaths: detail.WritePaths, AllowTools: detail.AllowTools, Model: detail.Model, StageModels: detail.StageModels}, state)
})
r.mu.Unlock()
return r.getRun(id)
}