Merge branch 'worktree-agent-a5f621112ab3cad4f'
# Conflicts: # app/lib/features/chat/domain/chat_shown_run.dart
This commit is contained in:
@@ -0,0 +1,115 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"math"
|
||||
"regexp"
|
||||
"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"
|
||||
)
|
||||
|
||||
// Run budgets and the error-loop policy.
|
||||
//
|
||||
// A run's whole-run USD cap is the run's own budget_usd, else the server
|
||||
// default (run settings). Every model stage's budget also counts towards it:
|
||||
// at 80% the operator is warned once, at 100% the visit stops and the run
|
||||
// fails with failure class budget. The definition's per-stage budget_usd and
|
||||
// budget_tokens still cap each stage on their own.
|
||||
|
||||
// budgetWarnRatio is the share of the run cap that sends the warning.
|
||||
const budgetWarnRatio = 0.8
|
||||
|
||||
// errorLoopBackoff is the wait before the next visit of a stage whose
|
||||
// transient harness failure routed back to itself: 15 s, 1 min, then 4 min
|
||||
// for every further consecutive one. Tests shorten it.
|
||||
var errorLoopBackoff = []time.Duration{15 * time.Second, time.Minute, 4 * time.Minute}
|
||||
|
||||
// sleepOrDone waits delay; false when ctx ends first.
|
||||
func sleepOrDone(ctx context.Context, delay time.Duration) bool {
|
||||
if delay <= 0 {
|
||||
return ctx.Err() == nil
|
||||
}
|
||||
timer := time.NewTimer(delay)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-timer.C:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
var harnessSignatureDigits = regexp.MustCompile(`[0-9]+`)
|
||||
|
||||
// harnessSignature is a failure's text with its numbers (ids, times,
|
||||
// counts) removed, so the same failure on two visits compares equal.
|
||||
func harnessSignature(err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
text := harnessSignatureDigits.ReplaceAllString(err.Error(), "#")
|
||||
if len(text) > 400 {
|
||||
text = text[:400]
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
// resolveRunBudget is the cap a new run gets: its own request, else the
|
||||
// server default. It returns the source recorded with it.
|
||||
func (r *runner) resolveRunBudget(request protocol.Message) (float64, string, error) {
|
||||
if request.BudgetUSD < 0 || math.IsNaN(request.BudgetUSD) || math.IsInf(request.BudgetUSD, 0) {
|
||||
return 0, "", fmt.Errorf("budget_usd must be a positive USD amount")
|
||||
}
|
||||
if request.BudgetUSD > 0 {
|
||||
return request.BudgetUSD, "run", nil
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
settings, err := r.store.RunSettings(ctx)
|
||||
if err != nil || settings.DefaultBudgetUSD <= 0 {
|
||||
return 0, "", err
|
||||
}
|
||||
return settings.DefaultBudgetUSD, "server", nil
|
||||
}
|
||||
|
||||
// runBudget loads a run's cap and what it already spent (a resumed run).
|
||||
func (r *runner) runBudget(ctx context.Context, id int64) *stage.RunBudget {
|
||||
read, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
|
||||
defer cancel()
|
||||
detail, err := r.store.GetRun(read, id)
|
||||
if err != nil || detail == nil || detail.Budget == nil {
|
||||
return nil
|
||||
}
|
||||
spent := 0.0
|
||||
if detail.Usage != nil {
|
||||
spent = detail.Usage.CostUSD
|
||||
}
|
||||
return stage.NewRunBudget(detail.Budget.LimitUSD, spent)
|
||||
}
|
||||
|
||||
// checkRunBudget sends the one 80% warning of a run's cap.
|
||||
func (r *runner) checkRunBudget(id int64, name string, budget *stage.RunBudget) {
|
||||
if !budget.Enabled() || budget.Spent() < budget.Limit()*budgetWarnRatio {
|
||||
return
|
||||
}
|
||||
save, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
first, err := r.store.MarkRunBudgetWarned(save, id)
|
||||
if err != nil || !first {
|
||||
if err != nil {
|
||||
log.Printf("run %d: record the budget warning: %v", id, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
body := fmt.Sprintf("Run #%d · %s · spent $%.2f of its $%.2f budget; it stops at the cap", id, name, budget.Spent(), budget.Limit())
|
||||
if err := r.store.EnqueueRunNotification(save, pipeline.RunNotification{RunID: id, Sequence: 0, Event: "budget_warning", Channel: "system", Title: "Run budget 80% used", Body: body, Click: runAttentionClick(id)}); err != nil {
|
||||
log.Printf("run %d: queue the budget warning: %v", id, err)
|
||||
return
|
||||
}
|
||||
r.deliverRunNotificationBatch(time.Now(), 1)
|
||||
}
|
||||
@@ -0,0 +1,411 @@
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,406 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -537,6 +537,14 @@ func mergeRunEventFrame(into, in *protocol.RunEventFrame) {
|
||||
if in.Status != "" {
|
||||
into.Status = in.Status
|
||||
into.ExportPendingSequence = in.ExportPendingSequence
|
||||
// A status change carries its own usage-limit wait (or clears it).
|
||||
into.QuotaWait = in.QuotaWait
|
||||
}
|
||||
if in.FailureClass != "" {
|
||||
into.FailureClass = in.FailureClass
|
||||
}
|
||||
if in.FailureKind != "" {
|
||||
into.FailureKind, into.FailureReason = in.FailureKind, in.FailureReason
|
||||
}
|
||||
if in.Outcome != "" {
|
||||
into.Outcome = in.Outcome
|
||||
@@ -617,6 +625,8 @@ func handleRunEvents(request protocol.Message, events *runEventHub, runs *runner
|
||||
FinishedAt: summary.FinishedAt,
|
||||
FailureKind: summary.FailureKind,
|
||||
FailureReason: summary.FailureReason,
|
||||
FailureClass: summary.FailureClass,
|
||||
QuotaWait: summary.QuotaWait,
|
||||
CancelRequested: summary.CancelRequested,
|
||||
CleanupUnconfirmed: summary.CleanupUnconfirmed,
|
||||
ExportPendingSequence: summary.ExportPendingSequence,
|
||||
|
||||
+173
-9
@@ -101,6 +101,8 @@ type runner struct {
|
||||
// holds the runs start-up recovery kept for reattachRuns to continue.
|
||||
detach bool
|
||||
reattach []reattachPlan
|
||||
// quota parks runs refused for a usage limit (run_quota.go).
|
||||
quota quotaState
|
||||
}
|
||||
|
||||
func newRunner(ctx context.Context, s *pipeline.Store) (*runner, error) {
|
||||
@@ -288,6 +290,32 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
|
||||
}
|
||||
}
|
||||
}
|
||||
budgetUSD, budgetSource, err := r.resolveRunBudget(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// A known usage limit of the account the Claude stages would use: defer
|
||||
// the start to the reset, refuse, or start anyway (protocol.QuotaPolicy).
|
||||
// An idempotent replay returns its run as it is.
|
||||
var quotaLimit quotaAdmission
|
||||
quotaDeferred := false
|
||||
switch request.QuotaPolicy {
|
||||
case "", protocol.QuotaDefer, protocol.QuotaRefuse, protocol.QuotaNow:
|
||||
default:
|
||||
return nil, fmt.Errorf("quota_policy must be defer, refuse or now")
|
||||
}
|
||||
if request.QuotaPolicy != protocol.QuotaNow {
|
||||
if limit, limited := r.knownQuotaLimit(d.Graph, workspace); limited {
|
||||
if replay, err := r.store.RunByKey(r.ctx, request.RequestKey); err != nil {
|
||||
return nil, err
|
||||
} else if replay == 0 {
|
||||
if request.QuotaPolicy == protocol.QuotaRefuse {
|
||||
return nil, quotaRefusal(limit)
|
||||
}
|
||||
quotaLimit, quotaDeferred = limit, true
|
||||
}
|
||||
}
|
||||
}
|
||||
// Decide admission and idempotency under the lock, but generate the title
|
||||
// only for a request that will actually start a run: a rejected or replayed
|
||||
// request must not pay for a bounded model generation, and a live one must
|
||||
@@ -415,6 +443,11 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
|
||||
r.rememberRunIdentity(id, identityOfRunSummary(detail.RunSummary))
|
||||
}
|
||||
if created {
|
||||
if budgetUSD > 0 {
|
||||
if err := r.store.SetRunBudget(r.ctx, id, budgetUSD, budgetSource); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if request.RetrySource > 0 && request.RetryMode != "restart" {
|
||||
checkpoint, checkpointErr := r.retrySourceCheckpointSelected(request.RetrySource, d, request.RetryStage, request.RetryVisit, request.RetryInput, request.RetryExtraVisits)
|
||||
if checkpointErr != nil {
|
||||
@@ -433,9 +466,24 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
|
||||
Status: protocol.RunStatusQueued,
|
||||
CreatedAt: time.Now().UTC().Format(time.RFC3339),
|
||||
}, false)
|
||||
r.launch(id, workspace, func(ctx context.Context) {
|
||||
r.run(ctx, id, d, workspace, request)
|
||||
})
|
||||
deferred := false
|
||||
if quotaDeferred {
|
||||
if err := r.deferLaunch(id, workspace, request, quotaLimit); err != nil {
|
||||
log.Printf("run %d: defer to the usage-limit reset: %v; starting now", id, err)
|
||||
} else {
|
||||
deferred = true
|
||||
}
|
||||
}
|
||||
if !deferred {
|
||||
r.launch(id, workspace, func(ctx context.Context) {
|
||||
r.run(ctx, id, d, workspace, request)
|
||||
})
|
||||
}
|
||||
if budgetUSD > 0 || deferred {
|
||||
if reread, err := r.store.GetRun(r.ctx, id); err == nil && reread != nil {
|
||||
detail = reread
|
||||
}
|
||||
}
|
||||
}
|
||||
if detail != nil {
|
||||
_, detail.Executing = r.active[id]
|
||||
@@ -511,7 +559,7 @@ func (r *runner) settleLaunchOnce(id int64, generation *byte) (bool, error) {
|
||||
}
|
||||
r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: detail.Workspace, Status: protocol.RunStatusCanceled, CancelRequested: true, CurrentStage: detail.CurrentStage, FinishedAt: time.Now().UTC().Format(time.RFC3339)}, true)
|
||||
}
|
||||
if detail.FinishedAt != "" || detail.Status == protocol.RunStatusWaiting {
|
||||
if detail.FinishedAt != "" || detail.Status == protocol.RunStatusWaiting || detail.Status == protocol.RunStatusWaitingQuota {
|
||||
delete(r.active, id)
|
||||
}
|
||||
// A landed (or change-free) successful run's own worktree is no longer
|
||||
@@ -1070,7 +1118,12 @@ func (r *runner) retry(request protocol.Message) (*protocol.RunDetail, error) {
|
||||
if notifyMode == "" {
|
||||
notifyMode, _ = r.store.RunNotifyMode(r.ctx, original.ID)
|
||||
}
|
||||
return r.start(protocol.Message{PipelineID: original.PipelineID, Version: version, RequestKey: request.RequestKey, RetryMode: mode, RetrySource: original.ID, RetryStage: request.RetryStage, RetryVisit: request.RetryVisit, RetryInput: request.RetryInput, RetryExtraVisits: request.RetryExtraVisits, RetryExtraStage: request.RetryExtraStage, Workspace: original.Workspace, Input: original.Input, AllowTools: original.AllowTools, WritePaths: original.WritePaths, Model: original.Model, StageModels: original.StageModels, NotifyMode: notifyMode, OutputFormat: original.OutputFormat}, original.ID)
|
||||
// A retry keeps the source run's own budget unless it names one.
|
||||
budgetUSD := request.BudgetUSD
|
||||
if budgetUSD == 0 && original.Budget != nil && original.Budget.Source == "run" {
|
||||
budgetUSD = original.Budget.LimitUSD
|
||||
}
|
||||
return r.start(protocol.Message{PipelineID: original.PipelineID, Version: version, RequestKey: request.RequestKey, RetryMode: mode, RetrySource: original.ID, RetryStage: request.RetryStage, RetryVisit: request.RetryVisit, RetryInput: request.RetryInput, RetryExtraVisits: request.RetryExtraVisits, RetryExtraStage: request.RetryExtraStage, Workspace: original.Workspace, Input: original.Input, AllowTools: original.AllowTools, WritePaths: original.WritePaths, Model: original.Model, StageModels: original.StageModels, NotifyMode: notifyMode, OutputFormat: original.OutputFormat, QuotaPolicy: request.QuotaPolicy, BudgetUSD: budgetUSD}, original.ID)
|
||||
}
|
||||
|
||||
func (r *runner) cancel(id int64) error {
|
||||
@@ -1083,10 +1136,12 @@ func (r *runner) cancel(id int64) error {
|
||||
if ok {
|
||||
entry.cancel()
|
||||
} else {
|
||||
// Only a parked human run is known to have no live executor.
|
||||
// Only a parked run (a human decision or a usage limit) is known to
|
||||
// have no live executor.
|
||||
if err := r.store.CancelWaiting(r.ctx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
r.disarmQuotaResume(id)
|
||||
}
|
||||
r.forgetAttention(id)
|
||||
if r.events != nil {
|
||||
@@ -1102,6 +1157,7 @@ func (r *runner) cancel(id int64) error {
|
||||
FinishedAt: detail.FinishedAt,
|
||||
CancelRequested: detail.CancelRequested,
|
||||
CleanupUnconfirmed: detail.CleanupUnconfirmed,
|
||||
FailureClass: detail.FailureClass,
|
||||
}, !ok)
|
||||
}
|
||||
}
|
||||
@@ -1399,6 +1455,14 @@ type runState struct {
|
||||
// adopt names the visit to re-adopt from a previous server process instead
|
||||
// of starting it; it is consumed by the loop's first iteration.
|
||||
adopt *adoptedVisit
|
||||
// failureClass is the class the run finishes with if it fails now: the
|
||||
// latest visit's failure (protocol.Failure*), "" to let the store derive.
|
||||
failureClass string
|
||||
// errorLoops counts each stage's consecutive transient error self-loops
|
||||
// (the backoff step); lastHarness is its latest repeatable harness
|
||||
// failure, so the same one twice in a row stops the loop.
|
||||
errorLoops map[string]int
|
||||
lastHarness map[string]string
|
||||
// findings is the run's findings ledger; grants are extra visits per stage
|
||||
// (loop_state.go). sessions is each stage's latest harness session, which
|
||||
// a resume_session stage continues on its next visit.
|
||||
@@ -1826,6 +1890,19 @@ func (r *runner) emitRun(frame protocol.RunEventFrame, terminal bool) {
|
||||
}
|
||||
|
||||
func (r *runner) finishRunState(id int64, name, workspace, status, outcome, diagnostic string, completed, sequence int, currentStage string, input stage.Values) {
|
||||
r.finishRunStateClass(id, name, workspace, status, outcome, diagnostic, completed, sequence, currentStage, input, "")
|
||||
}
|
||||
|
||||
// finishRunStateClass finishes a run recording the runner's failure class
|
||||
// (empty lets the store derive one; a success records none).
|
||||
func (r *runner) finishRunStateClass(id int64, name, workspace, status, outcome, diagnostic string, completed, sequence int, currentStage string, input stage.Values, class string) {
|
||||
if class != "" && status != "succeeded" {
|
||||
save, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
if err := r.store.SetRunFailureClass(save, id, class); err != nil {
|
||||
log.Printf("run %d: record failure class: %v", id, err)
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
// The deliverable and the size walk touch files only: they run without r.mu,
|
||||
// so listings and details do not stall behind a large run finishing. The
|
||||
// run stays in r.active (its workspace reserved) until the launch teardown.
|
||||
@@ -1869,6 +1946,7 @@ func (r *runner) finishRunState(id int64, name, workspace, status, outcome, diag
|
||||
FinishedAt: detail.FinishedAt,
|
||||
FailureKind: detail.FailureKind,
|
||||
FailureReason: detail.FailureReason,
|
||||
FailureClass: detail.FailureClass,
|
||||
SizeBytes: size,
|
||||
}, true)
|
||||
r.kickSizes()
|
||||
@@ -2020,7 +2098,7 @@ func (r *runner) finishStage(id int64, name, workspace string, selected protocol
|
||||
|
||||
func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, name, workspace string, request protocol.Message, state *runState) {
|
||||
finish := func(status, outcome, diagnostic string) {
|
||||
r.finishRunState(id, name, workspace, status, outcome, diagnostic, state.completed, state.nextSequence-1, state.key, state.input)
|
||||
r.finishRunStateClass(id, name, workspace, status, outcome, diagnostic, state.completed, state.nextSequence-1, state.key, state.input, state.failureClass)
|
||||
}
|
||||
// canceled settles an operator cancel. A server shutdown is not a cancel:
|
||||
// the run is left exactly as persisted for the next process to continue.
|
||||
@@ -2058,11 +2136,17 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
}
|
||||
effectiveModels = resolved
|
||||
}
|
||||
runBudget := r.runBudget(ctx, id)
|
||||
for sequence := state.nextSequence; sequence <= state.stepLimit(graph); sequence++ {
|
||||
if ctx.Err() != nil {
|
||||
canceled()
|
||||
return
|
||||
}
|
||||
if budgetErr := runBudget.Check(); budgetErr != nil {
|
||||
state.failureClass = protocol.FailureBudget
|
||||
finish("failed", "error", budgetErr.Error())
|
||||
return
|
||||
}
|
||||
key := state.key
|
||||
var def stage.Definition
|
||||
var selected protocol.Stage
|
||||
@@ -2106,6 +2190,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
}
|
||||
return
|
||||
}
|
||||
state.failureClass = protocol.FailureLoopExhausted
|
||||
if state.visits[key]+1 > hardVisits {
|
||||
finish("failed", "error", "stage visit budget exceeded")
|
||||
return
|
||||
@@ -2362,6 +2447,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
// The budget is shared across every visit to this stage key, so capture
|
||||
// its cumulative usage before the visit and record only this visit's
|
||||
// increment on the step, never the cumulative total again.
|
||||
budgets[key].SetRun(runBudget)
|
||||
budgetBefore = budgets[key].Snapshot()
|
||||
stageCtx = stage.WithBudget(stageCtx, budgets[key])
|
||||
}
|
||||
@@ -2545,6 +2631,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
step.Output["salvage"] = result.Output
|
||||
}
|
||||
}
|
||||
checkFailed := false
|
||||
if err == nil && result.Outcome == "success" {
|
||||
target, targetErr := stage.VerificationTargetFor(def)
|
||||
if targetErr != nil {
|
||||
@@ -2561,6 +2648,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
}
|
||||
}
|
||||
}
|
||||
checkFailed = err != nil
|
||||
if err != nil {
|
||||
step.Status = "failed"
|
||||
step.Diagnostic = err.Error()
|
||||
@@ -2596,6 +2684,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
var catchUp string
|
||||
catchUp, err = verifyDelivery(gateCtx, workspace, landing, checks, r.deliveryCommitMessage(id))
|
||||
gateCancel()
|
||||
checkFailed = err != nil
|
||||
// A failed gate already carries the note in its diagnostic. A step
|
||||
// diagnostic on success renders as a stop, so success is logged.
|
||||
if catchUp != "" {
|
||||
@@ -2615,10 +2704,45 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
step.Transcript = stage.RetainSession(step.Transcript, stageSession)
|
||||
}
|
||||
step.Target = def.Edges[step.Outcome]
|
||||
var quota quotaDecision
|
||||
if errors.Is(err, opencode.ErrProviderQuota) {
|
||||
// Another visit would be refused the same way: stop the run on the
|
||||
// provider's refusal instead of following the error edge again.
|
||||
// Another visit would be refused the same way: never follow the
|
||||
// error edge. A usage window that resets switches accounts or
|
||||
// parks the run (run_quota.go); an empty balance stops it.
|
||||
step.Target = protocol.FailureEnd
|
||||
if !errors.Is(err, stage.ErrStageCleanup) {
|
||||
quota = r.decideQuota(ctx, workspace, err)
|
||||
}
|
||||
if quota.rerun || quota.park {
|
||||
step.Target = key
|
||||
if quota.rerun {
|
||||
step.Diagnostic += "; switched Claude account, running the visit again"
|
||||
} else {
|
||||
step.Diagnostic += fmt.Sprintf("; the run waits for the reset and resumes this stage at %s", quota.resetsAt.Add(quotaResumeMargin).Local().Format("15:04 on 2 Jan"))
|
||||
}
|
||||
}
|
||||
}
|
||||
harnessKind := stage.HarnessFailureKind(err)
|
||||
if err != nil && !quota.rerun && !quota.park && step.Target != protocol.FailureEnd {
|
||||
switch {
|
||||
case errors.Is(err, stage.ErrPermissionDenied), errors.Is(err, stage.ErrRunBudgetExceeded):
|
||||
// Another visit is refused the same way.
|
||||
step.Target = protocol.FailureEnd
|
||||
case step.Target == key && harnessKind == stage.HarnessDeterministic:
|
||||
step.Target = protocol.FailureEnd
|
||||
step.Diagnostic += "; this harness failure repeats on every attempt, so the error loop was not followed"
|
||||
case step.Target == key && harnessKind == stage.HarnessRepeatable && state.lastHarness[key] == harnessSignature(err):
|
||||
step.Target = protocol.FailureEnd
|
||||
step.Diagnostic += "; the same harness failure repeated, so the error loop was not followed"
|
||||
}
|
||||
}
|
||||
if state.lastHarness == nil {
|
||||
state.lastHarness = map[string]string{}
|
||||
}
|
||||
if harnessKind == stage.HarnessRepeatable {
|
||||
state.lastHarness[key] = harnessSignature(err)
|
||||
} else {
|
||||
delete(state.lastHarness, key)
|
||||
}
|
||||
if errors.Is(err, stage.ErrStageCleanup) {
|
||||
// Retain the partial evidence without pretending that the agent stopped.
|
||||
@@ -2643,6 +2767,19 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
step.Target = protocol.FailureEnd
|
||||
parkExhausted = false
|
||||
}
|
||||
switch {
|
||||
case step.Control.LimitReached:
|
||||
state.failureClass = protocol.FailureLoopExhausted
|
||||
case checkFailed, stage.EffectiveType(def.Type) == stage.CheckType && step.Target == protocol.FailureEnd && !errors.Is(err, opencode.ErrProviderQuota):
|
||||
// A delivery gate, verification target or check stage failed.
|
||||
state.failureClass = protocol.FailureCheckFailed
|
||||
case err != nil:
|
||||
state.failureClass = stage.FailureClassOf(err)
|
||||
case step.Target == protocol.FailureEnd:
|
||||
state.failureClass = protocol.FailureBlocked
|
||||
default:
|
||||
state.failureClass = ""
|
||||
}
|
||||
_, _, _, failedTerminal := terminalFinish(step.Target, step.Stage, step.Outcome, step.Diagnostic)
|
||||
if exportRequired && !completeSessionExport(sessionExport) && !(err != nil && failedTerminal && step.Target != protocol.SuccessEnd) {
|
||||
// Preserve the real computation, files, outcome and target. In
|
||||
@@ -2692,6 +2829,10 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
canceled()
|
||||
return
|
||||
}
|
||||
if quota.park && !terminal {
|
||||
r.parkForQuota(id, workspace, sequence, key, state.completed, quota)
|
||||
return
|
||||
}
|
||||
// Advance the in-memory UI-surface evidence only after the step is
|
||||
// persisted, so the skip guard agrees with what the store holds.
|
||||
state.recordChanges(step.FileChanges, step.Artifacts)
|
||||
@@ -2708,6 +2849,12 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
if stage.EffectiveType(def.Type) == stage.ModelType {
|
||||
r.recordFindings(id, state, step)
|
||||
}
|
||||
} else if quota.rerun {
|
||||
// The visit runs again on the switched account with its own
|
||||
// input, told that the limit interrupted it; it does not count.
|
||||
state.input = input
|
||||
state.visits[key]--
|
||||
state.previousAttempt = quotaPreviousAttempt(key, quota.note)
|
||||
} else if step.Status == "failed" && step.Target != "" &&
|
||||
step.Target != protocol.FailureEnd && step.Target != protocol.SuccessEnd {
|
||||
// The error edge leads to another stage: tell it what failed.
|
||||
@@ -2754,8 +2901,25 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
}
|
||||
return
|
||||
}
|
||||
r.checkRunBudget(id, name, runBudget)
|
||||
if step.Status == "completed" {
|
||||
delete(state.errorLoops, key)
|
||||
} else if step.Status == "failed" && step.Target == key && !quota.rerun && (harnessKind == stage.HarnessTransient || harnessKind == stage.HarnessRepeatable) {
|
||||
// A transient harness failure looping back to its own stage waits
|
||||
// before the next visit, longer each time (errorLoopBackoff).
|
||||
if state.errorLoops == nil {
|
||||
state.errorLoops = map[string]int{}
|
||||
}
|
||||
delay := errorLoopBackoff[min(state.errorLoops[key], len(errorLoopBackoff)-1)]
|
||||
state.errorLoops[key]++
|
||||
if !sleepOrDone(ctx, delay) {
|
||||
canceled()
|
||||
return
|
||||
}
|
||||
}
|
||||
state.key = step.Target
|
||||
}
|
||||
state.failureClass = protocol.FailureLoopExhausted
|
||||
finish("failed", "error", "total stage budget exceeded")
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"git.a-wan.net/alan/pipelines/examples"
|
||||
"git.a-wan.net/alan/pipelines/internal/buildinfo"
|
||||
"git.a-wan.net/alan/pipelines/internal/claude"
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/summarise"
|
||||
@@ -554,7 +555,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
|
||||
response.Error = err.Error()
|
||||
}
|
||||
}
|
||||
} else if runs != nil && (request.Type == protocol.RunPipeline || request.Type == protocol.RetryRun || request.Type == protocol.ListRuns || request.Type == protocol.GetRun || request.Type == protocol.CancelRun || request.Type == protocol.DecideRun || request.Type == protocol.SetRunTitle || request.Type == protocol.GetRunEvidence || request.Type == protocol.RepairSessionExport || request.Type == protocol.DeleteRuns) {
|
||||
} else if runs != nil && (request.Type == protocol.RunPipeline || request.Type == protocol.RetryRun || request.Type == protocol.ListRuns || request.Type == protocol.GetRun || request.Type == protocol.CancelRun || request.Type == protocol.DecideRun || request.Type == protocol.SetRunTitle || request.Type == protocol.GetRunEvidence || request.Type == protocol.RepairSessionExport || request.Type == protocol.DeleteRuns || request.Type == protocol.ResumeRun || request.Type == protocol.GetRunSettings || request.Type == protocol.SetRunSettings) {
|
||||
var err error
|
||||
switch request.Type {
|
||||
case protocol.DeleteRuns:
|
||||
@@ -598,6 +599,23 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
|
||||
} else {
|
||||
response.RunDetail, err = runs.getRun(request.RunID)
|
||||
}
|
||||
case protocol.ResumeRun:
|
||||
response.Type = protocol.Run
|
||||
response.RunDetail, err = runs.resumeQuota(request.RunID)
|
||||
case protocol.GetRunSettings:
|
||||
response.Type = protocol.RunSettingsReply
|
||||
var settings protocol.RunSettings
|
||||
settings, err = stores[0].RunSettings(connCtx)
|
||||
response.RunSettings = &settings
|
||||
case protocol.SetRunSettings:
|
||||
response.Type = protocol.RunSettingsReply
|
||||
if request.RunSettings == nil {
|
||||
err = fmt.Errorf("set_run_settings requires run_settings")
|
||||
} else {
|
||||
var settings protocol.RunSettings
|
||||
settings, err = stores[0].SetRunSettings(connCtx, *request.RunSettings)
|
||||
response.RunSettings = &settings
|
||||
}
|
||||
case protocol.CancelRun:
|
||||
response.Type = protocol.Run
|
||||
err = runs.cancel(request.RunID)
|
||||
@@ -657,9 +675,24 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
|
||||
hub.watchUsageRefusals(options.Chat)
|
||||
}
|
||||
if runs != nil {
|
||||
// A stage refused for a usage limit first tries the Claude account
|
||||
// auto-switch chats use (the home's own setting decides).
|
||||
if manager, ok := options.Chat.(*chatManager); ok {
|
||||
runs.quota.switchAccount = func(ctx context.Context, workspace string, resetsAt time.Time) (string, string, error) {
|
||||
switcher, ok := manager.harness(claude.Backend).(chatAutoSwitcher)
|
||||
if !ok {
|
||||
return "", "", errNotClaudeChat
|
||||
}
|
||||
result, err := switcher.AutoSwitchAccount(ctx, claude.UsageRefusal{Directory: workspace, ResetsAt: resetsAt})
|
||||
return result.From, result.To, err
|
||||
}
|
||||
}
|
||||
// Continue the runs a previous process left in flight, now that the
|
||||
// runner's collaborators are wired and before any request is served.
|
||||
runs.reattachRuns()
|
||||
// Re-arm the resume of runs parked for a usage limit.
|
||||
runs.armParkedRuns()
|
||||
context.AfterFunc(ctx, runs.stopQuotaTimers)
|
||||
}
|
||||
return &runHandler{Handler: guardRequests(mux, options.AccessToken), runner: runs, hub: hub}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user