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:
+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")
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user