Runs park on usage limits; failure classes, harness error policy, run budgets
- A stage refused for a Claude usage limit no longer fails its run: the runner tries the chats' Claude account auto-switch (per-home setting) and reruns the visit, else parks the run in the new waiting_quota status (persisted, with reset/resume time in run summaries, details and events) and resumes the same visit at reset + 1 min, also after a restart. resume_run / `pipelines resume` resumes now; cancel works on parked runs. The rerun visit gets a "# Previous attempt" interruption note. Subscription limits no longer say "top up the provider account". - run/retry into an account known to be limited are deferred (quota_policy defer/refuse/now; CLI refuses under --json/--yes unless --defer or --now). - failure_class on runs (quota, loop_exhausted, timeout, permission_denied, harness_error, blocked, environment, canceled, interrupted, budget, check_failed, other) in RunSummary/RunDetail/events, CLI inspect/runs/wait/ stats and the app failure line. - Claude permission denials (permission_denials / refused tool results) fail a blocked visit with permission_denied naming the tool use. - Harness failures are classified transient vs deterministic; deterministic ones (and a repeated empty readback) skip error self-loops; transient self-loops back off 15 s, 1 min, 4 min. - Whole-run USD budget: run --budget, server default (run-budget / get/set_run_settings); 80% warning notification, stop with class budget. - App: waiting_quota status/filter with resume time, Resume now and Cancel, failure class wording. Docs and skill references updated. Merges main (check stage, delivery gate, Claude stage restart survival, schedule changes). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -126,7 +126,7 @@ func TestChatTurnDiffMarksBoundedPatchesTruncated(t *testing.T) {
|
||||
dir := gitRepo(t, map[string]string{"a.txt": "x\n"})
|
||||
h := turnDiffHub(t, dir)
|
||||
h.startRoomTurnDiff("ses_1")
|
||||
writeTurnFile(t, dir, "big.txt", strings.Repeat("line\n", 6000))
|
||||
writeTurnFile(t, dir, "big.txt", strings.Repeat("line\n", 21000))
|
||||
endDiffTurn(h, "ses_1")
|
||||
turns := recordedTurns(t, h, "ses_1")
|
||||
if len(turns) != 1 || !turns[0].Truncated || turns[0].Files != 1 || turns[0].Status != "partial" {
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
"git.a-wan.net/alan/pipelines/internal/workenv"
|
||||
)
|
||||
|
||||
// errDeliveryChecksFailed marks a delivery check stage whose commands ran and
|
||||
// failed on the candidate: that is the stage's fail outcome, not an error.
|
||||
var errDeliveryChecksFailed = errors.New("delivery checks failed")
|
||||
|
||||
// runCheckStage executes a check stage. Without delivery its commands run in
|
||||
// place in the run workspace. With delivery=true it is the landing gate: the
|
||||
// server commits the run's leftovers, merges a moved main, runs the commands
|
||||
// in a fresh candidate worktree of the commit and fast-forwards main only when
|
||||
// every command passes. A failing command is the fail outcome (main is not
|
||||
// touched); a gate failure (dirty checkout, conflict, refused fast-forward) is
|
||||
// an error.
|
||||
func (r *runner) runCheckStage(ctx context.Context, def stage.Definition, workspace string, delivery bool, landing stage.LandingAccess, runID int64) (stage.Result, error) {
|
||||
spec, err := stage.CheckStageSpec(def)
|
||||
if err != nil {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
if !delivery {
|
||||
def.Workspace = workspace
|
||||
return stage.CheckStage{}.Run(ctx, def, nil)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, spec.Timeout)
|
||||
defer cancel()
|
||||
var report stage.CheckReport
|
||||
note, err := verifyDeliveryWith(ctx, workspace, landing, r.deliveryCommitMessage(runID), func(ctx context.Context, candidate string) error {
|
||||
report = stage.RunCheckCommands(ctx, candidate, spec)
|
||||
if report.Failed() {
|
||||
return errDeliveryChecksFailed
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil && !errors.Is(err, errDeliveryChecksFailed) {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
result := stage.CheckResult(def.Key, spec, report)
|
||||
markdown, _ := result.Output["markdown"].(string)
|
||||
gate := "Delivery gate: the checks ran on a fresh worktree of the committed item; main was not changed."
|
||||
if err == nil {
|
||||
gate = "Delivery gate: the checks passed on a fresh worktree of the committed item and main was fast-forwarded to it."
|
||||
}
|
||||
if note != "" {
|
||||
gate += " " + strings.TrimPrefix(note, "delivery gate: ") + "."
|
||||
}
|
||||
result.Output["markdown"] = strings.Replace(markdown, "\n## Commands\n", "\n"+gate+"\n\n## Commands\n", 1)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// checkVerdict is the check stage's one-line verdict: its own summary, never
|
||||
// a model's paraphrase of the command output.
|
||||
func checkVerdict(output stage.Values) *protocol.StageVerdict {
|
||||
summary, _ := output["summary"].(string)
|
||||
if strings.TrimSpace(summary) == "" {
|
||||
return nil
|
||||
}
|
||||
return &protocol.StageVerdict{Reason: summary, ReasonSource: protocol.VerdictReasonFallback}
|
||||
}
|
||||
|
||||
// readOnlyViolation reports the files a stage with shell but without edit
|
||||
// left changed in the run directory: its shell is for reading, testing and
|
||||
// committing, not for writing. A stage without shell cannot write at all (a
|
||||
// change during it is not its own), and a stage with edit may write. Paths
|
||||
// under the stage's artifacts directory, the run's shared public directory and
|
||||
// a harness state directory that lives inside the workspace (for example
|
||||
// CLAUDE_CONFIG_DIR) are the harness's or the run's own and are not counted.
|
||||
// It returns "" when the stage may change files or none changed.
|
||||
func readOnlyViolation(def stage.Definition, tools []string, explicitTools bool, changes *protocol.StageFileChanges, workspace string, ignored []string) string {
|
||||
if stage.EffectiveType(def.Type) != stage.ModelType || !explicitTools || def.Configs["allow_workspace_changes"] == "true" || changes == nil {
|
||||
return ""
|
||||
}
|
||||
shell := false
|
||||
for _, tool := range tools {
|
||||
if tool == "edit" {
|
||||
return ""
|
||||
}
|
||||
shell = shell || tool == "shell"
|
||||
}
|
||||
if !shell {
|
||||
return ""
|
||||
}
|
||||
var prefixes []string
|
||||
for _, dir := range ignored {
|
||||
if rel, ok := workspaceRelative(workspace, dir); ok {
|
||||
prefixes = append(prefixes, rel+"/")
|
||||
}
|
||||
}
|
||||
var changed []string
|
||||
for _, file := range changes.Files {
|
||||
skip := false
|
||||
for _, prefix := range prefixes {
|
||||
if prefix == "./" || strings.HasPrefix(file.Path+"/", prefix) {
|
||||
skip = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !skip {
|
||||
changed = append(changed, file.Kind+" "+file.Path)
|
||||
}
|
||||
}
|
||||
if len(changed) == 0 && changes.Omitted == 0 {
|
||||
return ""
|
||||
}
|
||||
listed := changed
|
||||
if len(listed) > 20 {
|
||||
listed = append(append([]string(nil), listed[:20]...), fmt.Sprintf("and %d more", len(changed)-20))
|
||||
}
|
||||
if changes.Omitted > 0 {
|
||||
listed = append(listed, fmt.Sprintf("%d more omitted from the capture", changes.Omitted))
|
||||
}
|
||||
return fmt.Sprintf("permission denied: stage %s has no edit tool but changed the workspace (%s); the visit fails. If this stage is meant to change files, add edit to its tools or set allow_workspace_changes=true", def.Key, strings.Join(listed, ", "))
|
||||
}
|
||||
|
||||
// workspaceEnv is the environment a command in workspace runs with: the run's
|
||||
// directory environment when one applies, else the server's.
|
||||
func workspaceEnv(ctx context.Context, workspace string) []string {
|
||||
if env := workenv.CommandEnv(ctx, workspace); env != nil {
|
||||
return env
|
||||
}
|
||||
return os.Environ()
|
||||
}
|
||||
|
||||
// workspaceRelative returns dir relative to workspace when dir is inside it.
|
||||
func workspaceRelative(workspace, dir string) (string, bool) {
|
||||
workspace = strings.TrimSuffix(workspace, "/")
|
||||
dir = strings.TrimSuffix(dir, "/")
|
||||
if workspace == "" || dir == "" {
|
||||
return "", false
|
||||
}
|
||||
if dir == workspace {
|
||||
return ".", true
|
||||
}
|
||||
rel, ok := strings.CutPrefix(dir, workspace+"/")
|
||||
return rel, ok && rel != ""
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"git.a-wan.net/alan/pipelines/internal/stage"
|
||||
)
|
||||
|
||||
func checkModelStage(key, tools, edges, configs string) string {
|
||||
return "# stage " + key + "\n\n```prompt\nDo the work.\n```\n\n```tools\n" + tools + "\n```\n\n```edges\n" + edges + "\n```\n\n```configs\nprovider=opencode-go\nmodel=deepseek-v4.1-flash\nretries=0\n" + configs + "\n```\n\n"
|
||||
}
|
||||
|
||||
func checkTypeStage(key, commands, edges, configs string) string {
|
||||
return "# stage " + key + "\n\n```limits\n{\"max_visits\":3}\n```\n\n```configs\ntype=check\n" + configs + "\n```\n\n```commands\n" + commands + "\n```\n\n```edges\n" + edges + "\n```\n\n"
|
||||
}
|
||||
|
||||
func startSource(t *testing.T, ctx context.Context, source, workspace string, execute func(context.Context, stage.Definition, stage.Values) (stage.Result, error)) (*protocol.RunDetail, *pipeline.Store) {
|
||||
t.Helper()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "runner.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { store.Close() })
|
||||
if _, err := store.Submit(ctx, "check", source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
items, _ := store.List(ctx)
|
||||
r, err := newRunner(ctx, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.execute = execute
|
||||
run, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: t.Name(), Workspace: workspace, Input: map[string]any{"prompt": "task"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.wg.Wait()
|
||||
detail, err := store.GetRun(ctx, run.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return detail, store
|
||||
}
|
||||
|
||||
// A failing check sends the run back to the implementer with the failing
|
||||
// output in its input; the reviewer only runs once the tree is green.
|
||||
func TestCheckStageRoutesFailureOutputBackToTheImplementer(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
workspace := t.TempDir()
|
||||
source := checkModelStage("implement", "read\nedit\nshell", "success -> verify\nerror -> #failure", "") +
|
||||
checkTypeStage("verify", "echo checking\ntest -f fixed || { echo 'FAIL: fixed is missing' >&2; exit 4; }", "pass -> review\nfail -> implement", "") +
|
||||
checkModelStage("review", "read\nglob\ngrep", "success -> #success\nerror -> #failure", "")
|
||||
var visits atomic.Int32
|
||||
var secondInput string
|
||||
detail, _ := startSource(t, ctx, source, workspace, func(_ context.Context, def stage.Definition, _ stage.Values) (stage.Result, error) {
|
||||
if def.Key == "implement" {
|
||||
if visits.Add(1) == 2 {
|
||||
data, _ := os.ReadFile(def.Turn.Input)
|
||||
secondInput = string(data)
|
||||
if err := os.WriteFile(filepath.Join(workspace, "fixed"), []byte("yes\n"), 0o600); err != nil {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "done"}}, nil
|
||||
})
|
||||
if detail.Status != "succeeded" {
|
||||
t.Fatalf("run %s: %s %+v", detail.Status, detail.Diagnostic, detail.Steps)
|
||||
}
|
||||
var stages []string
|
||||
for _, step := range detail.Steps {
|
||||
stages = append(stages, step.Stage+":"+step.Outcome)
|
||||
}
|
||||
if got := strings.Join(stages, " "); got != "implement:success verify:fail implement:success verify:pass review:success" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
for _, want := range []string{"1 of 2 checks failed", "exit code 4", "FAIL: fixed is missing"} {
|
||||
if !strings.Contains(secondInput, want) {
|
||||
t.Fatalf("implementer input lacks %q:\n%s", want, secondInput)
|
||||
}
|
||||
}
|
||||
failed := detail.Steps[1]
|
||||
if failed.Verdict == nil || !strings.HasPrefix(failed.Verdict.Reason, "1 of 2 checks failed") {
|
||||
t.Fatalf("verdict %+v", failed.Verdict)
|
||||
}
|
||||
checks, _ := failed.Output["checks"].([]any)
|
||||
if len(checks) != 2 || failed.Provider != "" || failed.SessionID != "" {
|
||||
t.Fatalf("check step %+v", failed)
|
||||
}
|
||||
}
|
||||
|
||||
// A delivery check stage is the landing gate: the run's uncommitted work is
|
||||
// committed, the commands run on a fresh candidate and main fast-forwards;
|
||||
// a failing command is the fail outcome and leaves main alone.
|
||||
func TestDeliveryCheckStageLandsOnlyAGreenCandidate(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name, command, status string
|
||||
landed bool
|
||||
}{
|
||||
{"pass", "test -f work", "succeeded", true},
|
||||
{"fail", "test -f absent", "failed", false},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
root := t.TempDir()
|
||||
main := filepath.Join(root, "main")
|
||||
runGit(t, root, "init", "-b", "main", main)
|
||||
runGit(t, main, "config", "user.email", "test@example.invalid")
|
||||
runGit(t, main, "config", "user.name", "test")
|
||||
if err := os.WriteFile(filepath.Join(main, "README"), []byte("base\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runGit(t, main, "add", "README")
|
||||
runGit(t, main, "commit", "-m", "base")
|
||||
item := filepath.Join(root, "item")
|
||||
runGit(t, main, "worktree", "add", "-b", "item", item)
|
||||
if err := os.WriteFile(filepath.Join(item, "work"), []byte("change\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runGit(t, item, "add", "work")
|
||||
runGit(t, item, "commit", "-m", "work")
|
||||
before := runGitOutput(t, main, "rev-parse", "HEAD")
|
||||
source := checkTypeStage("land", test.command, "pass -> #success\nfail -> #failure", "delivery=true")
|
||||
detail, _ := startSource(t, ctx, source, item, nil)
|
||||
if detail.Status != test.status || len(detail.Steps) != 1 {
|
||||
t.Fatalf("run %s %q %+v", detail.Status, detail.Diagnostic, detail.Steps)
|
||||
}
|
||||
step := detail.Steps[0]
|
||||
markdown, _ := step.Output["markdown"].(string)
|
||||
if !strings.Contains(markdown, "Delivery gate") || step.Output["delivery"] != true {
|
||||
t.Fatalf("gate evidence missing: %q", markdown)
|
||||
}
|
||||
landed := runGitOutput(t, main, "rev-parse", "HEAD") == runGitOutput(t, item, "rev-parse", "HEAD")
|
||||
if landed != test.landed || (!test.landed && runGitOutput(t, main, "rev-parse", "HEAD") != before) {
|
||||
t.Fatalf("landed = %v, want %v", landed, test.landed)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A stage without edit that changes the workspace fails its visit and names
|
||||
// the files; allow_workspace_changes=true opts a stage out.
|
||||
func TestReadOnlyStageThatChangesFilesFails(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
for _, test := range []struct {
|
||||
name, configs, status string
|
||||
}{
|
||||
{"enforced", "", "failed"},
|
||||
{"allowed", "allow_workspace_changes=true", "succeeded"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
workspace := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(workspace, "main.go"), []byte("package main\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
source := checkModelStage("review", "read\nglob\ngrep\nshell", "success -> #success\nerror -> #failure", test.configs)
|
||||
detail, _ := startSource(t, ctx, source, workspace, func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
|
||||
if err := os.Symlink("/etc", filepath.Join(workspace, "stray-link")); err != nil {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "looks fine"}}, nil
|
||||
})
|
||||
if detail.Status != test.status {
|
||||
t.Fatalf("run %s %q", detail.Status, detail.Diagnostic)
|
||||
}
|
||||
if test.status == "failed" {
|
||||
diagnostic := detail.Steps[0].Diagnostic
|
||||
if !strings.Contains(diagnostic, "permission denied") || !strings.Contains(diagnostic, "added stray-link") || !strings.Contains(diagnostic, "allow_workspace_changes") {
|
||||
t.Fatal(diagnostic)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadOnlyViolationIgnoresHarnessAndRunDirectories(t *testing.T) {
|
||||
def := stage.Definition{Key: "review", Type: stage.ModelType, Configs: map[string]string{}}
|
||||
changes := &protocol.StageFileChanges{Files: []protocol.FileChange{
|
||||
{Path: ".claude-profile/.claude.json", Kind: "modified"},
|
||||
{Path: "artifacts/x/out.md", Kind: "added"},
|
||||
}}
|
||||
ignored := []string{"/w/.claude-profile", "/w/artifacts/x"}
|
||||
if v := readOnlyViolation(def, []string{"read", "shell"}, true, changes, "/w", ignored); v != "" {
|
||||
t.Fatal(v)
|
||||
}
|
||||
changes.Files = append(changes.Files, protocol.FileChange{Path: "src/a.go", Kind: "modified"})
|
||||
if v := readOnlyViolation(def, []string{"read", "shell"}, true, changes, "/w", ignored); !strings.Contains(v, "modified src/a.go") || strings.Contains(v, ".claude.json") {
|
||||
t.Fatal(v)
|
||||
}
|
||||
for name, ok := range map[string]bool{
|
||||
"edit tool": readOnlyViolation(def, []string{"edit", "shell"}, true, changes, "/w", nil) == "",
|
||||
"no shell (cannot write)": readOnlyViolation(def, []string{"read"}, true, changes, "/w", nil) == "",
|
||||
"no tools block (legacy bundle)": readOnlyViolation(def, nil, false, changes, "/w", nil) == "",
|
||||
} {
|
||||
if !ok {
|
||||
t.Fatal(name, "was enforced")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,20 @@ const deliveryCleanupTimeout = 10 * time.Second
|
||||
// own `merge --ff-only`, which refuses without touching anything when a local
|
||||
// change or untracked file would be overwritten.
|
||||
func verifyDelivery(ctx context.Context, workspace string, access stage.LandingAccess, checks []string, commitMessage string) (string, error) {
|
||||
return verifyDeliveryWith(ctx, workspace, access, commitMessage, func(ctx context.Context, candidate string) error {
|
||||
for _, check := range checks {
|
||||
if err := runDeliveryCheck(ctx, candidate, check); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// verifyDeliveryWith is verifyDelivery with the candidate checks supplied as
|
||||
// a function of the fresh candidate worktree: a check stage records each
|
||||
// command's result there instead of stopping at the first error.
|
||||
func verifyDeliveryWith(ctx context.Context, workspace string, access stage.LandingAccess, commitMessage string, check func(context.Context, string) error) (string, error) {
|
||||
lock, err := acquireDeliveryLock(ctx, access.LockPath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -82,7 +96,7 @@ func verifyDelivery(ctx context.Context, workspace string, access stage.LandingA
|
||||
note = fmt.Sprintf("delivery gate: canonical main moved to %s; merged it into item %s as %s and re-ran checks on the merged tree", shortCommit(mainHead), shortCommit(itemHead), shortCommit(merged))
|
||||
itemHead = merged
|
||||
}
|
||||
if err := runDeliveryCandidate(ctx, workspace, itemHead, checks); err != nil {
|
||||
if err := runDeliveryCandidate(ctx, workspace, itemHead, check); err != nil {
|
||||
if note != "" {
|
||||
return note, fmt.Errorf("%s; %w", note, err)
|
||||
}
|
||||
@@ -199,7 +213,7 @@ func acquireDeliveryLock(ctx context.Context, path string) (*os.File, error) {
|
||||
}
|
||||
}
|
||||
|
||||
func runDeliveryCandidate(ctx context.Context, workspace, itemHead string, checks []string) error {
|
||||
func runDeliveryCandidate(ctx context.Context, workspace, itemHead string, check func(context.Context, string) error) error {
|
||||
candidate, err := os.MkdirTemp(filepath.Dir(workspace), ".pipelines-delivery-")
|
||||
if err != nil {
|
||||
return fmt.Errorf("create delivery candidate: %w", err)
|
||||
@@ -212,12 +226,7 @@ func runDeliveryCandidate(ctx context.Context, workspace, itemHead string, check
|
||||
return fmt.Errorf("create delivery candidate: %w: %s", err, strings.TrimSpace(string(output)))
|
||||
}
|
||||
defer cleanupDeliveryCandidate(workspace, candidate)
|
||||
for _, check := range checks {
|
||||
if err := runDeliveryCheck(ctx, candidate, check); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return check(ctx, candidate)
|
||||
}
|
||||
|
||||
// cleanupDeliveryCandidate always uses its own bounded context: the stage context
|
||||
|
||||
@@ -122,10 +122,13 @@ func TestCleanupUnconfirmedReservesWorkspaceAcrossRecovery(t *testing.T) {
|
||||
|
||||
func TestWorkspaceOverlapIncludesParentsDescendantsAndSymlinks(t *testing.T) {
|
||||
_, r, pipelineID := concurrentStore(t)
|
||||
// One repository: its folder and a folder inside it are one shared tree.
|
||||
workspace := t.TempDir()
|
||||
child := filepath.Join(workspace, "child")
|
||||
if err := os.Mkdir(child, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
for _, dir := range []string{filepath.Join(workspace, ".git"), child} {
|
||||
if err := os.Mkdir(dir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
alias := filepath.Join(t.TempDir(), "alias")
|
||||
if err := os.Symlink(child, alias); err != nil {
|
||||
@@ -176,3 +179,73 @@ func TestWorkspaceOverlapSeparatesNestedRepositories(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Two folders outside any repository (the operator's ~/caplens and a sibling
|
||||
// project folder under it) are not one tree merely because neither is in a
|
||||
// repository: nested, they overlap only where the outer run's declared write
|
||||
// paths reach the inner folder. The same folder always overlaps.
|
||||
func TestWorkspaceOverlapNonRepositoryFolders(t *testing.T) {
|
||||
hub := t.TempDir()
|
||||
brief := filepath.Join(hub, "brief")
|
||||
notes := filepath.Join(hub, "notes", "deep")
|
||||
for _, dir := range []string{brief, notes} {
|
||||
if err := os.MkdirAll(dir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
paths := func(p ...string) func() []string { return func() []string { return p } }
|
||||
for _, test := range []struct {
|
||||
a, b string
|
||||
aPaths, bPaths func() []string
|
||||
want bool
|
||||
}{
|
||||
{hub, hub, nil, nil, true},
|
||||
{brief, brief, nil, nil, true},
|
||||
{hub, brief, nil, nil, false},
|
||||
{brief, hub, nil, nil, false},
|
||||
{brief, notes, nil, nil, false},
|
||||
{hub, brief, paths("notes"), nil, false},
|
||||
{hub, brief, paths("brief"), nil, true},
|
||||
{hub, notes, paths("notes"), nil, true},
|
||||
{hub, notes, paths("notes/deep/file.md"), nil, true},
|
||||
{notes, hub, nil, paths("notes"), true},
|
||||
{notes, hub, paths("notes"), nil, false}, // The inner run's paths do not reach out.
|
||||
{hub, brief, paths("."), nil, true},
|
||||
} {
|
||||
if got := workspaceScopesOverlap(test.a, test.b, test.aPaths, test.bPaths); got != test.want {
|
||||
t.Errorf("overlap(%s, %s) = %v, want %v", test.a, test.b, got, test.want)
|
||||
}
|
||||
}
|
||||
// Nested repository rules stay: a repository inside a plain folder is its
|
||||
// own tree whatever the folder's write paths.
|
||||
repo := filepath.Join(hub, "repo")
|
||||
if err := os.MkdirAll(filepath.Join(repo, ".git"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if workspaceScopesOverlap(hub, repo, paths("repo"), nil) {
|
||||
t.Fatal("a repository inside a plain folder overlaps it")
|
||||
}
|
||||
|
||||
// End to end: a scheduled brief in the hub is admitted while a run works in
|
||||
// a sibling folder below it, and refused only when it declares a write
|
||||
// path reaching that folder.
|
||||
_, r, pipelineID := concurrentStore(t)
|
||||
release := make(chan struct{})
|
||||
defer close(release)
|
||||
r.execute = func(ctx context.Context, _ stage.Definition, _ stage.Values) (stage.Result, error) {
|
||||
select {
|
||||
case <-release:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
return stage.Result{Outcome: "success"}, nil
|
||||
}
|
||||
if _, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "notes", Workspace: notes, Input: map[string]any{"prompt": "task"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "brief-scoped", Workspace: hub, WritePaths: []string{"notes"}, Input: map[string]any{"prompt": "task"}}); err == nil || !strings.Contains(err.Error(), "already active") {
|
||||
t.Fatal("a hub run writing into the active folder was admitted:", err)
|
||||
}
|
||||
if _, err := r.start(protocol.Message{PipelineID: pipelineID, Version: 1, RequestKey: "brief", Workspace: hub, Input: map[string]any{"prompt": "task"}}); err != nil {
|
||||
t.Fatal("a hub run was refused for a sibling folder's run:", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -23,12 +23,19 @@ import (
|
||||
// re-enters that visit, attaches to the session, waits for it to settle (or
|
||||
// reads the result it reached while the server was down) and continues the
|
||||
// graph as if it had watched it;
|
||||
// - a running Claude Code visit is re-adopted the same way: its CLI runs in
|
||||
// its own session writing stream-json to a file (see
|
||||
// stage.ClaudeStageClient), so the next process keeps reading that file
|
||||
// where the CLI is, waits for it to exit, or reads the result it left
|
||||
// while the server was down (an interrupted outcome repair follow-up is
|
||||
// asked again);
|
||||
// - a visit begun but never handed to a harness is marked interrupted and the
|
||||
// same stage starts again (nothing was admitted, so nothing replays);
|
||||
// - a run between visits continues with its next stage;
|
||||
// - a session whose harness process is gone, or that belongs to a harness the
|
||||
// server owned as a child (Pi, OpenCode V1), falls back to the previous
|
||||
// behaviour: the run is interrupted, with the reason in its diagnostic.
|
||||
// - a session whose harness process is gone (a Claude Code CLI that ended
|
||||
// without a result), or that belongs to a harness the server owned as a
|
||||
// child (Pi, OpenCode V1), falls back to the previous behaviour: the run
|
||||
// is interrupted, with the reason in its diagnostic.
|
||||
//
|
||||
// Only an operator cancel (cancel_run) stops a stage session.
|
||||
|
||||
@@ -61,6 +68,10 @@ var stageServiceAlive = func(ctx context.Context, owner pipeline.SessionOwner) e
|
||||
return opencode.ReferenceAlive(ctx, owner.Reference)
|
||||
}
|
||||
|
||||
// claudeStageReattachable reports why a retained Claude Code stage session
|
||||
// cannot be re-adopted (nil when it can). It is a seam for tests.
|
||||
var claudeStageReattachable = stage.ClaudeStageReattachable
|
||||
|
||||
// interruptRecoveredSession stops a previously active session that start-up
|
||||
// recovery does not re-adopt. It is a seam for tests.
|
||||
var interruptRecoveredSession = func(ctx context.Context, owner pipeline.SessionOwner) error {
|
||||
@@ -126,14 +137,22 @@ func planReattach(ctx context.Context, s *pipeline.Store) ([]reattachPlan, map[i
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
owner.RunID = row.ID
|
||||
if owner.Backend == stage.ClaudeBackend {
|
||||
// Claude Code stage CLIs run detached from the server: re-adopt
|
||||
// one still running, or one that left its result while the
|
||||
// server was down.
|
||||
if reason := claudeStageReattachable(owner.Reference, owner.ID); reason != nil {
|
||||
reasons[row.ID] = fmt.Sprintf("the Claude Code session running stage %s could not be reattached: %v", last.Stage, reason)
|
||||
continue
|
||||
}
|
||||
plans = append(plans, reattachPlan{runID: row.ID, kind: reattachAdopt, step: last, owner: owner})
|
||||
continue
|
||||
}
|
||||
if owner.Backend != "v2" {
|
||||
name := "OpenCode V1"
|
||||
if owner.Backend == "pi" {
|
||||
name = "Pi"
|
||||
}
|
||||
if owner.Backend == stage.ClaudeBackend {
|
||||
name = "Claude Code"
|
||||
}
|
||||
reasons[row.ID] = fmt.Sprintf("%s stage sessions belong to the stopped server process, so stage %s could not be reattached", name, last.Stage)
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -294,3 +294,94 @@ func TestOperatorCancelStillStopsDetachingRun(t *testing.T) {
|
||||
t.Fatalf("operator cancel did not stop the run: detached=%v %+v", detached.Load(), final)
|
||||
}
|
||||
}
|
||||
|
||||
// ownedClaudeStage is a first-process stage one whose Claude Code CLI
|
||||
// (session claude-live) is still running, detached, at shutdown.
|
||||
func ownedClaudeStage(ctx context.Context, s *pipeline.Store, id int64) (stage.Result, error) {
|
||||
if err := s.RunSession(context.Background(), id, 1, "claude-live", true, stage.ClaudeBackend, "ref-claude"); err != nil {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
<-ctx.Done()
|
||||
if stage.Detached(ctx) {
|
||||
return stage.Result{}, stage.ErrDetached
|
||||
}
|
||||
return stage.Result{}, ctx.Err()
|
||||
}
|
||||
|
||||
func seamClaudeReattachable(t *testing.T, reason error) *atomic.Value {
|
||||
t.Helper()
|
||||
asked := &atomic.Value{}
|
||||
previous := claudeStageReattachable
|
||||
claudeStageReattachable = func(reference, session string) error {
|
||||
asked.Store(reference + " " + session)
|
||||
return reason
|
||||
}
|
||||
t.Cleanup(func() { claudeStageReattachable = previous })
|
||||
return asked
|
||||
}
|
||||
|
||||
// TestClaudeStageRunContinuesAfterRestart: a Claude Code stage in flight at a
|
||||
// restart is re-adopted from its retained session (never re-prompted, never
|
||||
// interrupted) and the run continues to the next stage.
|
||||
func TestClaudeStageRunContinuesAfterRestart(t *testing.T) {
|
||||
interrupts := seamRestartRecovery(t, fmt.Errorf("the OpenCode probe must not be used for Claude"))
|
||||
asked := seamClaudeReattachable(t, nil)
|
||||
f := stopMidStage(t, ownedClaudeStage)
|
||||
var resumed atomic.Value
|
||||
r, s := f.restart(t, func(ctx context.Context, s *pipeline.Store, def stage.Definition) (stage.Result, error) {
|
||||
if def.Key == "one" {
|
||||
resumed.Store(stage.TakeResumeSession(ctx))
|
||||
if err := s.RunSession(context.Background(), f.runID, 1, "claude-live", false, stage.ClaudeBackend, "ref-claude"); err != nil {
|
||||
return stage.Result{}, err
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "Claude finished"}}, nil
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "next"}}, nil
|
||||
})
|
||||
if interrupts.Load() != 0 {
|
||||
t.Fatal("start-up recovery interrupted a Claude Code stage that survived the restart")
|
||||
}
|
||||
if got, _ := asked.Load().(string); got != "ref-claude claude-live" {
|
||||
t.Fatalf("reattachability asked about %q", got)
|
||||
}
|
||||
r.reattachRuns()
|
||||
r.wg.Wait()
|
||||
d, err := s.GetRun(context.Background(), f.runID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, _ := resumed.Load().(string); got != "claude-live" {
|
||||
t.Fatalf("stage one was not re-adopted from its Claude session: %q", got)
|
||||
}
|
||||
if d.Status != "succeeded" || len(d.Steps) != 2 || d.Steps[0].Output["markdown"] != "Claude finished" {
|
||||
t.Fatalf("run did not continue after the re-adopted Claude stage: %+v", d)
|
||||
}
|
||||
}
|
||||
|
||||
// TestClaudeStageGoneWithoutResultIsInterruptedWithReason: a Claude Code CLI
|
||||
// that ended without a result while the server was down is not replayed; the
|
||||
// run is interrupted, saying why.
|
||||
func TestClaudeStageGoneWithoutResultIsInterruptedWithReason(t *testing.T) {
|
||||
interrupts := seamRestartRecovery(t, nil)
|
||||
seamClaudeReattachable(t, fmt.Errorf("Claude Code stopped while the server was restarting, before it reported a final result"))
|
||||
f := stopMidStage(t, ownedClaudeStage)
|
||||
r, s := f.restart(t, func(context.Context, *pipeline.Store, stage.Definition) (stage.Result, error) {
|
||||
t.Error("a Claude stage without a result executed again")
|
||||
return stage.Result{}, nil
|
||||
})
|
||||
r.reattachRuns()
|
||||
r.wg.Wait()
|
||||
d, err := s.GetRun(context.Background(), f.runID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if d.Status != "interrupted" || !strings.Contains(d.Diagnostic, "Claude Code session running stage one could not be reattached") || !strings.Contains(d.Diagnostic, "before it reported a final result") {
|
||||
t.Fatalf("lost Claude stage lacks a clear reason: status=%s run=%q", d.Status, d.Diagnostic)
|
||||
}
|
||||
if interrupts.Load() != 1 {
|
||||
t.Fatalf("the leftover Claude group was not confirmed stopped: %d", interrupts.Load())
|
||||
}
|
||||
if owners, _ := s.ActiveSessionOwners(context.Background()); len(owners) != 0 {
|
||||
t.Fatalf("the lost session still blocks recovery: %+v", owners)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
+289
-35
@@ -100,6 +100,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) {
|
||||
@@ -287,6 +289,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
|
||||
@@ -319,7 +347,7 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
|
||||
return nil, err
|
||||
}
|
||||
if existing == 0 {
|
||||
if err := r.checkWorkspaceFree(workspace); err != nil {
|
||||
if err := r.checkWorkspaceFree(workspace, request.WritePaths...); err != nil {
|
||||
r.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
@@ -343,7 +371,7 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
|
||||
// Another run may have reserved this workspace while the title was
|
||||
// generated, so re-check before reserving it; a race on the request key is
|
||||
// handled by the store's idempotent insert.
|
||||
if err := r.checkAdmissionWorkspace(workspace, existing); err != nil {
|
||||
if err := r.checkAdmissionWorkspace(workspace, existing, request.WritePaths...); err != nil {
|
||||
r.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
@@ -380,7 +408,7 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc
|
||||
request.Input["pwd"] = workspace
|
||||
recheck := r.ctx.Err()
|
||||
if recheck == nil {
|
||||
recheck = r.checkAdmissionWorkspace(workspace, existing)
|
||||
recheck = r.checkAdmissionWorkspace(workspace, existing, request.WritePaths...)
|
||||
}
|
||||
if recheck != nil {
|
||||
r.mu.Unlock()
|
||||
@@ -414,6 +442,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)
|
||||
if checkpointErr != nil {
|
||||
@@ -432,9 +465,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]
|
||||
@@ -510,7 +558,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
|
||||
@@ -543,9 +591,9 @@ var runSettleRead = func(r *runner, ctx context.Context, id int64) (*protocol.Ru
|
||||
// storage maintenance may have removed a clean inactive tree while an
|
||||
// admission was generating its title, so it is checked under the same lock
|
||||
// removal takes. Callers must hold r.mu.
|
||||
func (r *runner) checkAdmissionWorkspace(workspace string, existing int64) error {
|
||||
func (r *runner) checkAdmissionWorkspace(workspace string, existing int64, writePaths ...string) error {
|
||||
if existing == 0 {
|
||||
if err := r.checkWorkspaceFree(workspace); err != nil {
|
||||
if err := r.checkWorkspaceFree(workspace, writePaths...); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -557,14 +605,30 @@ func (r *runner) checkAdmissionWorkspace(workspace string, existing int64) error
|
||||
|
||||
// checkWorkspaceFree refuses a run when an active or cleanup-unconfirmed run
|
||||
// reserves an overlapping resolved workspace. Callers must hold r.mu.
|
||||
func (r *runner) checkWorkspaceFree(workspace string) error {
|
||||
return r.checkWorkspaceFreeExcept(workspace, 0)
|
||||
// writePaths are the new run's declared write paths (they decide an overlap
|
||||
// only between nested folders outside any repository).
|
||||
func (r *runner) checkWorkspaceFree(workspace string, writePaths ...string) error {
|
||||
return r.checkWorkspaceFreeExcept(workspace, 0, writePaths...)
|
||||
}
|
||||
|
||||
func (r *runner) checkWorkspaceFreeExcept(workspace string, ownGate int64) error {
|
||||
func (r *runner) checkWorkspaceFreeExcept(workspace string, ownGate int64, writePaths ...string) error {
|
||||
own := func() []string { return writePaths }
|
||||
// pathsOf reads a reserving run's declared write paths only when needed.
|
||||
pathsOf := func(id int64) func() []string {
|
||||
return func() []string {
|
||||
read, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 5*time.Second)
|
||||
defer cancel()
|
||||
paths, err := r.store.RunWritePaths(read, id)
|
||||
if err != nil {
|
||||
// Unknown scope: keep the whole folder reserved (fail closed).
|
||||
return []string{"."}
|
||||
}
|
||||
return paths
|
||||
}
|
||||
}
|
||||
for id, entry := range r.active {
|
||||
if workspacesOverlap(entry.workspace, workspace) {
|
||||
return fmt.Errorf("run %d is already active in %s, which overlaps this run's workspace %s; wait for run %d to finish or use a different workspace (for example another checkout of the repository)", id, entry.workspace, workspace, id)
|
||||
if workspaceScopesOverlap(entry.workspace, workspace, pathsOf(id), own) {
|
||||
return &workspaceBusyError{runID: id, message: fmt.Sprintf("run %d is already active in %s, which overlaps this run's workspace %s; wait for run %d to finish or use a different workspace (for example another checkout of the repository)", id, entry.workspace, workspace, id)}
|
||||
}
|
||||
}
|
||||
check, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 5*time.Second)
|
||||
@@ -574,35 +638,76 @@ func (r *runner) checkWorkspaceFreeExcept(workspace string, ownGate int64) error
|
||||
return fmt.Errorf("read pending export workspace reservations: %w", err)
|
||||
}
|
||||
for id, reserved := range reservations {
|
||||
if id != ownGate && workspacesOverlap(reserved, workspace) {
|
||||
return fmt.Errorf("run %d is awaiting its session export; workspace %s remains reserved", id, reserved)
|
||||
if id != ownGate && workspaceScopesOverlap(reserved, workspace, pathsOf(id), own) {
|
||||
return &workspaceBusyError{runID: id, message: fmt.Sprintf("run %d is awaiting its session export; workspace %s remains reserved", id, reserved)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// workspaceBusyError refuses an admission because another run (runID)
|
||||
// reserves an overlapping workspace; waiting can clear it.
|
||||
type workspaceBusyError struct {
|
||||
runID int64
|
||||
message string
|
||||
}
|
||||
|
||||
func (e *workspaceBusyError) Error() string { return e.message }
|
||||
|
||||
// workspacesOverlap reports whether two resolved workspaces are the same
|
||||
// tree or nested in one another within the same repository. A folder that
|
||||
// merely holds separate repositories (a hub such as ~/project with clones
|
||||
// under repos/) does not overlap a run inside one of those repositories, and
|
||||
// neither do two different repositories nested in one another: each run
|
||||
// works in its own repository.
|
||||
// works in its own repository. Two folders outside any repository are not one
|
||||
// shared tree either: nested, they overlap only where the outer run declared
|
||||
// write paths reaching the inner folder (see workspaceScopesOverlap).
|
||||
func workspacesOverlap(a, b string) bool {
|
||||
within := func(parent, child string) bool {
|
||||
rel, err := filepath.Rel(parent, child)
|
||||
return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator))
|
||||
}
|
||||
return workspaceScopesOverlap(a, b, nil, nil)
|
||||
}
|
||||
|
||||
// workspaceScopesOverlap is workspacesOverlap with each workspace's declared
|
||||
// write paths (relative to it). They matter only for two nested folders
|
||||
// outside any repository; a nil lookup means "declared none".
|
||||
func workspaceScopesOverlap(a, b string, aPaths, bPaths func() []string) bool {
|
||||
switch {
|
||||
case filepath.Clean(a) == filepath.Clean(b):
|
||||
return true
|
||||
case within(a, b):
|
||||
return repositoryRoot(b) == repositoryRoot(a)
|
||||
case within(b, a):
|
||||
return repositoryRoot(a) == repositoryRoot(b)
|
||||
case pathAtOrBelow(a, b):
|
||||
return nestedWorkspacesOverlap(a, b, aPaths)
|
||||
case pathAtOrBelow(b, a):
|
||||
return nestedWorkspacesOverlap(b, a, bPaths)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// nestedWorkspacesOverlap decides for an inner workspace below outer.
|
||||
func nestedWorkspacesOverlap(outer, inner string, outerPaths func() []string) bool {
|
||||
root := repositoryRoot(outer)
|
||||
if repositoryRoot(inner) != root {
|
||||
return false // Different repositories: each run works in its own.
|
||||
}
|
||||
if root != "" {
|
||||
return true // The same repository is one shared tree.
|
||||
}
|
||||
if outerPaths == nil {
|
||||
return false
|
||||
}
|
||||
for _, path := range outerPaths() {
|
||||
target := filepath.Join(outer, path)
|
||||
if pathAtOrBelow(target, inner) || pathAtOrBelow(inner, target) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// pathAtOrBelow reports whether child is parent or below it.
|
||||
func pathAtOrBelow(parent, child string) bool {
|
||||
rel, err := filepath.Rel(parent, child)
|
||||
return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator))
|
||||
}
|
||||
|
||||
// repositoryRoot is the nearest directory at or above dir holding a .git
|
||||
// entry (a repository or a linked worktree), or "" outside any repository.
|
||||
func repositoryRoot(dir string) string {
|
||||
@@ -988,7 +1093,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, 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, 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 {
|
||||
@@ -1001,10 +1111,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 {
|
||||
@@ -1020,6 +1132,7 @@ func (r *runner) cancel(id int64) error {
|
||||
FinishedAt: detail.FinishedAt,
|
||||
CancelRequested: detail.CancelRequested,
|
||||
CleanupUnconfirmed: detail.CleanupUnconfirmed,
|
||||
FailureClass: detail.FailureClass,
|
||||
}, !ok)
|
||||
}
|
||||
}
|
||||
@@ -1055,7 +1168,7 @@ func (r *runner) decide(request protocol.Message) (*protocol.RunDetail, error) {
|
||||
return nil, fmt.Errorf("run %d is awaiting session export, not a human decision", detail.ID)
|
||||
}
|
||||
if detail.Status == protocol.RunStatusWaiting {
|
||||
if err := r.checkWorkspaceFree(detail.Workspace); err != nil {
|
||||
if err := r.checkWorkspaceFree(detail.Workspace, detail.WritePaths...); err != nil {
|
||||
r.mu.Unlock()
|
||||
return nil, err
|
||||
}
|
||||
@@ -1291,6 +1404,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
|
||||
}
|
||||
|
||||
func newRunState(key string, input stage.Values) *runState {
|
||||
@@ -1689,6 +1810,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.
|
||||
@@ -1732,6 +1866,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()
|
||||
@@ -1883,7 +2018,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.
|
||||
@@ -1921,11 +2056,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 <= 30; 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
|
||||
@@ -1961,10 +2102,12 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
// stage must not begin work it can never execute.
|
||||
if !isHuman {
|
||||
if state.visits[key]+1 > 5 {
|
||||
state.failureClass = protocol.FailureLoopExhausted
|
||||
finish("failed", "error", "stage visit budget exceeded")
|
||||
return
|
||||
}
|
||||
if state.visits[key]+1 > maxVisits {
|
||||
state.failureClass = protocol.FailureLoopExhausted
|
||||
finish("failed", "error", fmt.Sprintf("stage %s visit limit reached (%d)", key, maxVisits))
|
||||
return
|
||||
}
|
||||
@@ -2190,9 +2333,12 @@ 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])
|
||||
}
|
||||
repairs := &stage.RepairCounter{}
|
||||
stageCtx = stage.WithRepairCounter(stageCtx, repairs)
|
||||
snapshotCtx, snapshotCancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
before := filediff.Capture(snapshotCtx, workspace)
|
||||
snapshotCancel()
|
||||
@@ -2209,7 +2355,11 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
err = ctx.Err()
|
||||
return
|
||||
}
|
||||
if r.execute != nil {
|
||||
if stage.EffectiveType(def.Type) == stage.CheckType {
|
||||
// The server runs a check stage's commands itself, in the run
|
||||
// workspace or, for delivery, in a fresh candidate worktree.
|
||||
result, err = r.runCheckStage(stageCtx, def, workspace, delivery, landing, id)
|
||||
} else if r.execute != nil {
|
||||
timeout, _ := stage.StageTimeout(def)
|
||||
executeCtx, cancel := context.WithTimeout(stageCtx, timeout)
|
||||
defer cancel()
|
||||
@@ -2237,6 +2387,10 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
client.Transcript = piClient.Transcript
|
||||
} else if modelConfig.Harness == stage.ClaudeBackend {
|
||||
claudeClient := &stage.ClaudeStageClient{Directory: workspace, Tools: tools, WritePaths: request.WritePaths, ArtifactsDir: artifactsDir, Skills: def.Skills}
|
||||
if adopted != nil {
|
||||
// Follow the CLI the previous process left (see run_reattach.go).
|
||||
claudeClient.Reference = adopted.owner.Reference
|
||||
}
|
||||
claudeClient.OnOwnership = func(session, reference string, active bool) error {
|
||||
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
@@ -2360,6 +2514,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 {
|
||||
@@ -2376,6 +2531,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()
|
||||
@@ -2383,7 +2539,26 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
step.Output = stage.Values{"error": err.Error(), "stage": key, "input": input}
|
||||
}
|
||||
}
|
||||
if err == nil && delivery && result.Outcome == "success" {
|
||||
if err == nil {
|
||||
// A stage without edit must leave the run directory as it found it;
|
||||
// a shell is not a licence to write (allow_workspace_changes opts out).
|
||||
ignored := append([]string{artifactsDir, visitTurn.PublicDir}, stage.HarnessStateDirs(workspaceEnv(stageCtx, workspace))...)
|
||||
if violation := readOnlyViolation(def, tools, explicitTools, changes, workspace, ignored); violation != "" {
|
||||
err = errors.New(violation)
|
||||
log.Printf("run %d stage %s #%d: %s", id, key, sequence, violation)
|
||||
step.Status = "failed"
|
||||
step.Diagnostic = violation
|
||||
step.Outcome = "error"
|
||||
step.Output = stage.Values{"error": violation, "stage": key, "input": input}
|
||||
if len(result.Output) > 0 {
|
||||
step.Output["salvage"] = result.Output
|
||||
}
|
||||
}
|
||||
}
|
||||
if err == nil && stage.EffectiveType(def.Type) == stage.CheckType {
|
||||
step.Verdict = checkVerdict(result.Output)
|
||||
}
|
||||
if err == nil && delivery && stage.EffectiveType(def.Type) == stage.ModelType && result.Outcome == "success" {
|
||||
checks, checksErr := stage.DeliveryChecks(def)
|
||||
if checksErr != nil {
|
||||
err = checksErr
|
||||
@@ -2392,6 +2567,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 != "" {
|
||||
@@ -2411,10 +2587,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.
|
||||
@@ -2427,7 +2638,10 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: workspace, Status: protocol.RunStatusRunning, CleanupUnconfirmed: true}, false)
|
||||
return
|
||||
}
|
||||
step.Control = &protocol.ControlEvidence{Visit: state.visits[key], MaxVisits: maxVisits, Memory: reads}
|
||||
step.Control = &protocol.ControlEvidence{Visit: state.visits[key], MaxVisits: maxVisits, Memory: reads, OutcomeRepairs: repairs.Count()}
|
||||
if step.Control.OutcomeRepairs > 0 {
|
||||
log.Printf("run %d stage %s #%d: outcome repair follow-up sent %d time(s)", id, key, sequence, step.Control.OutcomeRepairs)
|
||||
}
|
||||
if err == nil && selected.Limits != nil && state.visits[key] >= maxVisits {
|
||||
for _, outcome := range selected.Limits.On {
|
||||
if outcome == step.Outcome {
|
||||
@@ -2441,6 +2655,19 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
if panicked {
|
||||
step.Target = protocol.FailureEnd
|
||||
}
|
||||
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
|
||||
@@ -2474,7 +2701,7 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
// markdown body, which the field-map summariser reads as untrusted data and
|
||||
// answers with an invented rationale; those steps get the honest read-time
|
||||
// fallback instead.
|
||||
if r.verdict != nil && !turnOutputOnly(step.Output) {
|
||||
if r.verdict != nil && !turnOutputOnly(step.Output) && step.Verdict == nil {
|
||||
reasonCtx, reasonCancel := context.WithTimeout(context.Background(), summarise.DefaultTimeout)
|
||||
if line := r.verdict(reasonCtx, step.Output); line != "" && line != summarise.NoSummary {
|
||||
step.Verdict = &protocol.StageVerdict{Reason: line, ReasonSource: protocol.VerdictReasonModel}
|
||||
@@ -2490,6 +2717,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)
|
||||
@@ -2503,6 +2734,12 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
if artifactsDir != "" {
|
||||
state.artifactDirs = append(state.artifactDirs, strconv.Itoa(sequence))
|
||||
}
|
||||
} 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.
|
||||
@@ -2535,8 +2772,25 @@ func (r *runner) runLoop(ctx context.Context, id int64, graph protocol.Graph, na
|
||||
finish(status, outcome, diagnostic)
|
||||
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")
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"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"
|
||||
)
|
||||
|
||||
func (r *runner) scheduleLoop() {
|
||||
@@ -89,6 +93,10 @@ func (r *runner) claimSchedule(item protocol.SavedSchedule, now time.Time, recov
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if claimed && status == "skipped_missed" {
|
||||
name := scheduleLabel(item)
|
||||
go r.scheduleNotice(item, due, "skipped", "Scheduled run skipped: "+name, fmt.Sprintf("%s was due at %s while the server was not running, so that run was skipped.", name, due.Local().Format("15:04 on 2 Jan")), "")
|
||||
}
|
||||
if !claimed || status != "claimed" {
|
||||
return nil
|
||||
}
|
||||
@@ -100,21 +108,114 @@ func (r *runner) claimSchedule(item protocol.SavedSchedule, now time.Time, recov
|
||||
return nil
|
||||
}
|
||||
|
||||
// admitScheduled starts one claimed schedule's run and records the outcome.
|
||||
// scheduleBusyRetry is how often, and for how long after its due time, a
|
||||
// scheduled admission whose workspace another run holds is tried again
|
||||
// (the limit counts from the first attempt).
|
||||
// PIPELINES_SCHEDULE_BUSY_RETRY_EVERY and PIPELINES_SCHEDULE_BUSY_RETRY_FOR
|
||||
// (Go durations; FOR=0 disables waiting) override the defaults.
|
||||
var scheduleBusyRetry = func() (every, limit time.Duration) {
|
||||
every, limit = 5*time.Minute, 2*time.Hour
|
||||
if value, err := time.ParseDuration(os.Getenv("PIPELINES_SCHEDULE_BUSY_RETRY_EVERY")); err == nil && value > 0 {
|
||||
every = value
|
||||
}
|
||||
if value, err := time.ParseDuration(os.Getenv("PIPELINES_SCHEDULE_BUSY_RETRY_FOR")); err == nil && value >= 0 {
|
||||
limit = value
|
||||
}
|
||||
return every, limit
|
||||
}
|
||||
|
||||
// scheduleNoticePriority is ntfy's "low" priority.
|
||||
const scheduleNoticePriority = 2
|
||||
|
||||
// admitScheduled starts one claimed schedule's run and records the outcome in
|
||||
// the schedule's history. A workspace another run holds delays the admission
|
||||
// instead of skipping it: it is tried again every few minutes for a bounded
|
||||
// time, recorded as "delayed" meanwhile. The operator is told, at low
|
||||
// priority, when a scheduled run is delayed and when one is skipped.
|
||||
func (r *runner) admitScheduled(item protocol.SavedSchedule, due time.Time) {
|
||||
request := protocol.Message{PipelineID: item.PipelineID, Version: item.Version, RequestKey: fmt.Sprintf("saved-schedule:%d:%d", item.ID, due.UnixNano()), Input: item.Input, Workspace: item.Workspace, WritePaths: item.WritePaths, AllowTools: item.AllowTools, Model: item.Model, StageModels: item.StageModels, NotifyMode: item.NotifyMode, Title: item.Title, OutputFormat: item.OutputFormat}
|
||||
run, err := r.startWithSchedule(request, &pipeline.ScheduleAdmission{ID: item.ID, Revision: item.Revision, Due: due, Name: item.Name})
|
||||
every, limit := scheduleBusyRetry()
|
||||
started := time.Now()
|
||||
deadline := started.Add(limit)
|
||||
name := scheduleLabel(item)
|
||||
diagnostic := ""
|
||||
status := "started"
|
||||
var runID int64
|
||||
if err != nil {
|
||||
status = "skipped"
|
||||
diagnostic = err.Error()
|
||||
} else if run != nil {
|
||||
runID = run.ID
|
||||
for attempt := 1; ; attempt++ {
|
||||
run, err := r.startWithSchedule(request, &pipeline.ScheduleAdmission{ID: item.ID, Revision: item.Revision, Due: due, Name: item.Name})
|
||||
if err == nil {
|
||||
status, diagnostic = "started", ""
|
||||
if run != nil {
|
||||
runID = run.ID
|
||||
}
|
||||
if attempt > 1 {
|
||||
diagnostic = fmt.Sprintf("started after waiting %s for a busy workspace", time.Since(started).Round(time.Second))
|
||||
}
|
||||
break
|
||||
}
|
||||
status, diagnostic = "skipped", err.Error()
|
||||
var busy *workspaceBusyError
|
||||
if !errors.As(err, &busy) {
|
||||
break
|
||||
}
|
||||
if time.Now().Add(every).After(deadline) {
|
||||
if attempt > 1 {
|
||||
diagnostic = fmt.Sprintf("gave up after waiting %s for a busy workspace: %s", time.Since(started).Round(time.Second), diagnostic)
|
||||
}
|
||||
break
|
||||
}
|
||||
if attempt == 1 {
|
||||
r.scheduleNotice(item, due, "delayed", "Scheduled run delayed: "+name,
|
||||
fmt.Sprintf("%s is waiting for run #%d to free its workspace; it is tried again every %s until %s.", name, busy.runID, every, deadline.Local().Format("15:04")), runAttentionClick(busy.runID))
|
||||
}
|
||||
delayed := fmt.Sprintf("waiting for a busy workspace (attempt %d; retrying every %s until %s): %s", attempt, every, deadline.UTC().Format(time.RFC3339), err.Error())
|
||||
if err := r.store.FinishSavedSchedule(r.ctx, item.ID, due, "delayed", delayed); err != nil {
|
||||
log.Printf("schedule id=%d record delay: %v", item.ID, err)
|
||||
}
|
||||
log.Printf("schedule id=%d pipeline=%d due=%s delayed: %s", item.ID, item.PipelineID, due.Format(time.RFC3339), delayed)
|
||||
timer := time.NewTimer(every)
|
||||
select {
|
||||
case <-timer.C:
|
||||
continue
|
||||
case <-r.ctx.Done():
|
||||
timer.Stop()
|
||||
diagnostic = "the server stopped while this run waited for a busy workspace: " + diagnostic
|
||||
}
|
||||
break
|
||||
}
|
||||
if err := r.store.FinishSavedSchedule(r.ctx, item.ID, due, status, diagnostic); err != nil {
|
||||
save, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 10*time.Second)
|
||||
if err := r.store.FinishSavedSchedule(save, item.ID, due, status, diagnostic); err != nil {
|
||||
log.Printf("schedule id=%d record admission: %v", item.ID, err)
|
||||
}
|
||||
cancel()
|
||||
if status == "skipped" {
|
||||
r.scheduleNotice(item, due, "skipped", "Scheduled run skipped: "+name, name+" did not start: "+diagnostic, "")
|
||||
}
|
||||
log.Printf("schedule id=%d pipeline=%d version=%d due=%s status=%s run=%d %s", item.ID, item.PipelineID, item.Version, due.Format(time.RFC3339), status, runID, diagnostic)
|
||||
}
|
||||
|
||||
// scheduleLabel names a schedule in a notice.
|
||||
func scheduleLabel(item protocol.SavedSchedule) string {
|
||||
if name := singleLine(item.Name); name != "" {
|
||||
return truncateUTF8(name, 120)
|
||||
}
|
||||
return fmt.Sprintf("Schedule %d", item.ID)
|
||||
}
|
||||
|
||||
// scheduleNotice tells the operator, at low priority, through the app
|
||||
// notification stream and (when enabled) ntfy, that a scheduled run was
|
||||
// delayed or skipped.
|
||||
func (r *runner) scheduleNotice(item protocol.SavedSchedule, due time.Time, event, title, message, click string) {
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(r.ctx), 30*time.Second)
|
||||
defer cancel()
|
||||
title, message = truncateUTF8(singleLine(title), 256), truncateUTF8(singleLine(message), 2000)
|
||||
r.notes.record(ctx, pipeline.AppNotificationRecord{AppNotification: protocol.AppNotification{
|
||||
ID: fmt.Sprintf("schedule:%d:%d:%s", item.ID, due.UnixNano(), event), Kind: protocol.NotificationSchedule,
|
||||
Title: title, Message: message, Click: click, Priority: scheduleNoticePriority, Tags: []string{}, Group: fmt.Sprintf("schedule:%d", item.ID)}})
|
||||
if !chatAttentionConfigured() || !ntfyEnabled(ctx, r.settingsStore()) {
|
||||
return
|
||||
}
|
||||
if _, err := ntfyPublish(stage.WithNtfyPriority(ctx, scheduleNoticePriority), "system", title, message, "", nil, click); err != nil {
|
||||
log.Printf("schedule id=%d %s notice: %v", item.ID, event, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"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"
|
||||
)
|
||||
|
||||
func scheduleNotices(t *testing.T, s *pipeline.Store) []protocol.AppNotification {
|
||||
t.Helper()
|
||||
active, _, err := s.ActiveAppNotifications(context.Background(), "", time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var notices []protocol.AppNotification
|
||||
for _, n := range active {
|
||||
if n.Kind == protocol.NotificationSchedule {
|
||||
notices = append(notices, n)
|
||||
}
|
||||
}
|
||||
return notices
|
||||
}
|
||||
|
||||
func waitOccurrence(t *testing.T, s *pipeline.Store, id int64, due time.Time, want string) (string, int64) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for {
|
||||
status, diagnostic, run, err := s.SavedScheduleOccurrence(context.Background(), id, due)
|
||||
if err == nil && status == want {
|
||||
return diagnostic, run
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("occurrence status %q (%q, %v), want %q", status, diagnostic, err, want)
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// A scheduled run whose workspace another run holds is delayed, not skipped:
|
||||
// it is recorded as delayed, the operator is told at low priority, and it
|
||||
// starts once the workspace is free.
|
||||
func TestScheduledRunWaitsForABusyWorkspace(t *testing.T) {
|
||||
seamScheduleBusyRetry(t, 20*time.Millisecond, time.Hour)
|
||||
ctx, s, r, pid := scheduleFixture(t)
|
||||
r.notes = newAppNotifier(s)
|
||||
workspace := t.TempDir()
|
||||
busy := saveTestSchedule(t, ctx, s, pid, "busy", workspace, "1h", time.Now())
|
||||
brief := saveTestSchedule(t, ctx, s, pid, "Daily brief", workspace, "1h", time.Now())
|
||||
release := make(chan struct{})
|
||||
entered := make(chan struct{}, 2)
|
||||
r.execute = func(ctx context.Context, _ stage.Definition, input stage.Values) (stage.Result, error) {
|
||||
entered <- struct{}{}
|
||||
if prompt, _ := input["prompt"].(string); prompt == "busy" {
|
||||
<-release
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "# Done"}}, nil
|
||||
}
|
||||
if err := r.scheduleTick(dueOf(t, busy), false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
<-entered
|
||||
due := dueOf(t, brief)
|
||||
if err := r.scheduleTick(due, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
diagnostic, _ := waitOccurrence(t, s, brief.ID, due, "delayed")
|
||||
if !strings.Contains(diagnostic, "busy workspace") || !strings.Contains(diagnostic, "already active") {
|
||||
t.Fatalf("delay diagnostic %q", diagnostic)
|
||||
}
|
||||
notices := scheduleNotices(t, s)
|
||||
if len(notices) != 1 || notices[0].Priority != 2 || !strings.Contains(notices[0].Title, "delayed") || !strings.Contains(notices[0].Title, "Daily brief") {
|
||||
t.Fatalf("delay notices %+v", notices)
|
||||
}
|
||||
close(release)
|
||||
diagnostic, run := waitOccurrence(t, s, brief.ID, due, "started")
|
||||
r.scheduleAdmissions.Wait()
|
||||
r.wg.Wait()
|
||||
if run == 0 || !strings.Contains(diagnostic, "started after waiting") {
|
||||
t.Fatalf("delayed run not admitted: run=%d %q", run, diagnostic)
|
||||
}
|
||||
runs, err := s.ListRuns(ctx)
|
||||
if err != nil || len(runs) != 2 {
|
||||
t.Fatalf("runs %+v %v", runs, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Waiting is bounded: past the limit the occurrence is skipped, saying why,
|
||||
// and the operator is told.
|
||||
func TestScheduledRunGivesUpOnABusyWorkspace(t *testing.T) {
|
||||
seamScheduleBusyRetry(t, 20*time.Millisecond, 150*time.Millisecond)
|
||||
ctx, s, r, pid := scheduleFixture(t)
|
||||
r.notes = newAppNotifier(s)
|
||||
workspace := t.TempDir()
|
||||
busy := saveTestSchedule(t, ctx, s, pid, "busy", workspace, "1h", time.Now())
|
||||
brief := saveTestSchedule(t, ctx, s, pid, "Daily brief", workspace, "1h", time.Now())
|
||||
release := make(chan struct{})
|
||||
defer close(release)
|
||||
entered := make(chan struct{}, 2)
|
||||
r.execute = func(ctx context.Context, _ stage.Definition, _ stage.Values) (stage.Result, error) {
|
||||
entered <- struct{}{}
|
||||
select {
|
||||
case <-release:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "# Done"}}, nil
|
||||
}
|
||||
if err := r.scheduleTick(dueOf(t, busy), false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
<-entered
|
||||
due := dueOf(t, brief)
|
||||
if claimed, err := s.ClaimSavedSchedule(ctx, *brief, due, due.Add(time.Hour), "claimed"); err != nil || !claimed {
|
||||
t.Fatal(claimed, err)
|
||||
}
|
||||
r.admitScheduled(*brief, due)
|
||||
diagnostic, run := waitOccurrence(t, s, brief.ID, due, "skipped")
|
||||
if run != 0 || !strings.Contains(diagnostic, "gave up after waiting") {
|
||||
t.Fatalf("skip diagnostic %q run=%d", diagnostic, run)
|
||||
}
|
||||
notices := scheduleNotices(t, s)
|
||||
var titles []string
|
||||
for _, n := range notices {
|
||||
titles = append(titles, n.Title)
|
||||
if n.Priority != 2 {
|
||||
t.Fatalf("schedule notice is not low priority: %+v", n)
|
||||
}
|
||||
}
|
||||
if len(notices) != 2 || !strings.Contains(strings.Join(titles, "|"), "skipped") {
|
||||
t.Fatalf("notices %v", titles)
|
||||
}
|
||||
}
|
||||
@@ -201,7 +201,17 @@ func TestScheduleDeletionDoesNotCancelAdmittedRun(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// seamScheduleBusyRetry sets how a scheduled admission waits for a busy
|
||||
// workspace (limit 0: it is skipped at once, as before delays existed).
|
||||
func seamScheduleBusyRetry(t *testing.T, every, limit time.Duration) {
|
||||
t.Helper()
|
||||
previous := scheduleBusyRetry
|
||||
scheduleBusyRetry = func() (time.Duration, time.Duration) { return every, limit }
|
||||
t.Cleanup(func() { scheduleBusyRetry = previous })
|
||||
}
|
||||
|
||||
func TestSavedScheduleRecoveryAndOverlap(t *testing.T) {
|
||||
seamScheduleBusyRetry(t, time.Minute, 0)
|
||||
ctx, s, r, pid := scheduleFixture(t)
|
||||
item := saveTestSchedule(t, ctx, s, pid, "task", t.TempDir(), "1m", time.Now())
|
||||
due := dueOf(t, item)
|
||||
|
||||
@@ -35,7 +35,7 @@ func (r *runner) resumeExportGates(ctx context.Context) error {
|
||||
r.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
if err := r.checkWorkspaceFreeExcept(d.Workspace, id); err != nil {
|
||||
if err := r.checkWorkspaceFreeExcept(d.Workspace, id, d.WritePaths...); err != nil {
|
||||
r.mu.Unlock()
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -190,12 +190,15 @@ func TestUISkipRunsModelOnAnyRecordedChange(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestUISkipPartialCaptureNeverSkips proves a visit whose capture was partial
|
||||
// (here a protected .env file forces skipped>0) blocks the fallback even when
|
||||
// (here a protected secrets/ directory, which is never walked, forces skipped>0;
|
||||
// an untouched .env no longer does) blocks the fallback even when
|
||||
// it recorded no file changes, and that inspect carries a run-level warning.
|
||||
func TestUISkipPartialCaptureNeverSkips(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, ".env"), []byte("A=1\n"), 0o600); err != nil {
|
||||
if err := os.MkdirAll(filepath.Join(dir, "secrets"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "secrets", "token"), []byte("A=1\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
detail, visited, verdictCalls := runUISkipIn(t, uiReviewerSource(true), nil, dir)
|
||||
|
||||
@@ -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