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) }