fix: fail task outcomes and back off refused runner claims
8 files changed,
+296
−15
internal/equipo/team/residual_release_test.go+61 −0internal/equipo/team/scheduler.go+22 −0internal/runner/attempt_error.go+65 −0internal/runner/final_infrastructure_test.go+1 −0internal/runner/residual_backoff_test.go+56 −0internal/runner/residual_outcome_test.go+68 −0internal/runner/service.go+14 −2internal/runner/supervisor.go+9 −13
diff --git a/internal/equipo/team/residual_release_test.go b/internal/equipo/team/residual_release_test.go| new file mode 100644 |
| index 00000000..af335873 |
| --- /dev/null |
| +++ b/internal/equipo/team/residual_release_test.go |
| @@ -0,0 +1,61 @@ |
| +package team |
| + |
| +import "testing" |
| + |
| +func TestBugReleaseCannotRetryTaskOutcome(t *testing.T) { |
| + for _, outcome := range []string{"refusal", "receipt", "artifact", "complete"} { |
| + t.Run(outcome, func(t *testing.T) { |
| + e := newEnv(t) |
| + spec := softwareSpec(SoftwareSteps(false)) |
| + spec.Evidence.RequireBugFreeze = true |
| + _, scope := e.createJob(spec) |
| + h := e.claim(scope, "reproduce", "runner", "workspace") |
| + reason := WaitRunnerUnavailable |
| + switch outcome { |
| + case "refusal": |
| + reason = WaitProviderLimit |
| + case "receipt": |
| + id, err := e.store.Intend(e.ctx, scope, h, intent("turn", Usage{})) |
| + must(t, err) |
| + _, err = e.store.Admit(e.ctx, scope, id) |
| + must(t, err) |
| + must(t, e.store.Record(e.ctx, scope, id, Receipt{ID: "failed", Outcome: OutcomeFailure})) |
| + case "artifact": |
| + _, err := e.store.Register(e.ctx, scope, h, reproSpec(h)) |
| + must(t, err) |
| + } |
| + if outcome == "complete" { |
| + must(t, e.store.Complete(e.ctx, scope, h, AttemptResult{Outcome: OutcomeFailure, Detail: "runner.identity"})) |
| + } else { |
| + must(t, e.store.Release(e.ctx, scope, h, reason, "task outcome")) |
| + } |
| + must(t, e.store.Contain(e.ctx, scope, h.Attempt, "contained")) |
| + if j := e.job(scope); j.State != JobFailed { |
| + t.Fatalf("task outcome remains retryable: %s", j.State) |
| + } |
| + if _, err := e.store.Claim(e.ctx, scope, "reproduce", "runner", "new-workspace"); err == nil { |
| + t.Fatal("task outcome received another attempt") |
| + } |
| + }) |
| + } |
| +} |
| +func TestBugInfrastructureReleaseHasBoundedRetry(t *testing.T) { |
| + e := newEnv(t) |
| + spec := softwareSpec(SoftwareSteps(false)) |
| + spec.Evidence.RequireBugFreeze = true |
| + spec.Policy.MaxAttemptsPerStep = 2 |
| + _, scope := e.createJob(spec) |
| + for i := 0; i < 2; i++ { |
| + h := e.claim(scope, "reproduce", "runner", "workspace-"+itoa(i)) |
| + must(t, e.store.Release(e.ctx, scope, h, WaitRunnerUnavailable, "transport")) |
| + if i == 0 { |
| + if _, err := e.store.Claim(e.ctx, scope, "reproduce", "runner", "too-early"); err == nil { |
| + t.Fatal("retry before containment") |
| + } |
| + } |
| + must(t, e.store.Contain(e.ctx, scope, h.Attempt, "contained")) |
| + } |
| + if j := e.job(scope); j.State != JobFailed { |
| + t.Fatalf("exhausted infrastructure retries left job %s", j.State) |
| + } |
| +} |
diff --git a/internal/equipo/team/scheduler.go b/internal/equipo/team/scheduler.go| index 2743042e..9391d3d6 100644 |
| --- a/internal/equipo/team/scheduler.go |
| +++ b/internal/equipo/team/scheduler.go |
| @@ -356,6 +356,28 @@ func (s *Store) Release(ctx context.Context, scope Scope, h Handle, reason WaitR |
| if open > 0 { |
| return fail(CodeState, "attempt %d has %d actions in flight", hd.attempt.ID, open) |
| } |
| + var outcomes int |
| + if hd.job.Evidence.RequireBugFreeze { |
| + if err := tx.QueryRowContext(ctx, `SELECT (SELECT COUNT(*) FROM actions WHERE attempt_id=? AND state IN ('succeeded','failed')) + (SELECT COUNT(*) FROM artifacts WHERE attempt_id=?)`, int64(hd.attempt.ID), int64(hd.attempt.ID)).Scan(&outcomes); err != nil { |
| + return fail(CodeInvalid, "attempt outcomes: %v", err) |
| + } |
| + } |
| + if hd.step.Attempts >= hd.job.Policy.MaxAttemptsPerStep || hd.job.Evidence.RequireBugFreeze && (reason != WaitRunnerUnavailable || outcomes > 0) { |
| + if err := revokeIntents(ctx, tx, hd.attempt.ID, now); err != nil { |
| + return err |
| + } |
| + if _, err := tx.ExecContext(ctx, `UPDATE attempts SET state='failed',outcome=?,updated_at=? WHERE id=?`, detail, ts(now), int64(hd.attempt.ID)); err != nil { |
| + return err |
| + } |
| + if _, err := tx.ExecContext(ctx, `UPDATE steps SET state='failed',holder=0 WHERE id=? AND fence=?`, int64(hd.step.ID), h.Fence); err != nil { |
| + return err |
| + } |
| + if err := appendEvent(ctx, tx, scope, "attempt.failed", h.Runner, map[string]any{"step": hd.step.Key, "attempt": hd.attempt.ID, "detail": detail}, now); err != nil { |
| + return err |
| + } |
| + _, err := terminate(ctx, tx, hd.job, JobFailed, h.Runner, detail, now) |
| + return err |
| + } |
| if err := revokeIntents(ctx, tx, hd.attempt.ID, now); err != nil { |
| return err |
| } |
diff --git a/internal/runner/attempt_error.go b/internal/runner/attempt_error.go| new file mode 100644 |
| index 00000000..30633cc8 |
| --- /dev/null |
| +++ b/internal/runner/attempt_error.go |
| @@ -0,0 +1,65 @@ |
| +package runner |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| + "context" |
| + "errors" |
| +) |
| + |
| +func infrastructureOnly(err error, r *attemptState) bool { |
| + if joined, ok := err.(interface{ Unwrap() []error }); ok { |
| + for _, cause := range joined.Unwrap() { |
| + if !infrastructureOnly(cause, r) { |
| + return false |
| + } |
| + } |
| + return true |
| + } |
| + if wrapped, ok := err.(interface{ Unwrap() error }); ok { |
| + return infrastructureOnly(wrapped.Unwrap(), r) |
| + } |
| + switch err { |
| + case context.Canceled, context.DeadlineExceeded: |
| + return r.ServiceInterrupted |
| + case ErrTransient: |
| + return true |
| + case paseo.ErrClosed: |
| + switch r.Phase { |
| + case "claimed", "creating-workspace", "workspace", "creating-socket", "creating-agent", "tracking-agent", "agent": |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +func attemptFailureReason(err error) string { |
| + var refusal *RefusalError |
| + if errors.As(err, &refusal) { |
| + return refusal.Reason |
| + } |
| + for _, item := range []struct { |
| + err error |
| + reason string |
| + }{ |
| + {ErrPromptTooLarge, "runner.prompt_too_large"}, {team.ErrEvidence, "runner.evidence"}, |
| + {team.ErrBudget, "runner.budget"}, {team.ErrQuota, "runner.quota"}, {team.ErrReplayUnsafe, "runner.replay"}, |
| + } { |
| + if errors.Is(err, item.err) { |
| + return item.reason |
| + } |
| + } |
| + if joined, ok := err.(interface{ Unwrap() []error }); ok { |
| + for _, cause := range joined.Unwrap() { |
| + if !errors.Is(cause, context.Canceled) && !errors.Is(cause, context.DeadlineExceeded) { |
| + return attemptFailureReason(cause) |
| + } |
| + } |
| + causes := joined.Unwrap() |
| + if len(causes) > 0 { |
| + return attemptFailureReason(causes[0]) |
| + } |
| + } |
| + reason, _ := Diagnostic(err) |
| + return reason |
| +} |
diff --git a/internal/runner/final_infrastructure_test.go b/internal/runner/final_infrastructure_test.go| index e86854c6..b6b1df32 100644 |
| --- a/internal/runner/final_infrastructure_test.go |
| +++ b/internal/runner/final_infrastructure_test.go |
| @@ -17,6 +17,7 @@ func TestInfrastructureFailureReleasesAttempt(t *testing.T) { |
| for _, cause := range []error{context.Canceled, context.DeadlineExceeded, ErrTransient, team.ErrEvidence} { |
| t.Run(cause.Error(), func(t *testing.T) { |
| s, r, _, order := cleanupFixture(t) |
| + r.ServiceInterrupted = errors.Is(cause, context.Canceled) || errors.Is(cause, context.DeadlineExceeded) |
| _ = s.finishAttempt(context.Background(), r, cause) |
| if errors.Is(cause, team.ErrEvidence) { |
| if !slices.Contains(*order, "complete") { |
diff --git a/internal/runner/residual_backoff_test.go b/internal/runner/residual_backoff_test.go| new file mode 100644 |
| index 00000000..921f96ae |
| --- /dev/null |
| +++ b/internal/runner/residual_backoff_test.go |
| @@ -0,0 +1,56 @@ |
| +package runner |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "context" |
| + "errors" |
| + "testing" |
| + "time" |
| +) |
| + |
| +type refusedSource struct { |
| + claims []time.Time |
| + cancel context.CancelFunc |
| +} |
| + |
| +func (s *refusedSource) Poll(context.Context) ([]runnerproto.Assignment, error) { |
| + return []runnerproto.Assignment{{ID: "refused", Revision: 1}}, nil |
| +} |
| +func (s *refusedSource) Claim(context.Context, runnerproto.ClaimRequest) (runnerproto.ClaimResponse, error) { |
| + s.claims = append(s.claims, time.Now()) |
| + if len(s.claims) == 3 { |
| + s.cancel() |
| + } |
| + return runnerproto.ClaimResponse{}, ErrClaimRefused |
| +} |
| +func TestClaimRefusalsBackOff(t *testing.T) { |
| + s, _, _, _ := cleanupFixture(t) |
| + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) |
| + defer cancel() |
| + source := &refusedSource{cancel: cancel} |
| + service := Service{Supervisor: s, Source: source} |
| + err := service.Run(ctx) |
| + if !errors.Is(err, context.Canceled) || len(source.claims) != 3 { |
| + t.Fatalf("refusal loop: %v %d", err, len(source.claims)) |
| + } |
| + for i, want := range []time.Duration{time.Second, 2 * time.Second} { |
| + if got := source.claims[i+1].Sub(source.claims[i]); got < want { |
| + t.Fatalf("claim refusal did not back off: delay=%s want>=%s", got, want) |
| + } |
| + } |
| +} |
| + |
| +func TestClaimBackoffBounds(t *testing.T) { |
| + for failures := 1; failures <= 20; failures++ { |
| + base := time.Second * time.Duration(1<<min(failures-1, 5)) |
| + if base > 30*time.Second { |
| + base = 30 * time.Second |
| + } |
| + for range 20 { |
| + got := claimBackoffDelay(failures) |
| + if got < base || got > min(30*time.Second, base+base/4) { |
| + t.Fatalf("backoff %d = %s outside bounded exponential jitter", failures, got) |
| + } |
| + } |
| + } |
| +} |
diff --git a/internal/runner/residual_outcome_test.go b/internal/runner/residual_outcome_test.go| new file mode 100644 |
| index 00000000..8c5f95ab |
| --- /dev/null |
| +++ b/internal/runner/residual_outcome_test.go |
| @@ -0,0 +1,68 @@ |
| +package runner |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "context" |
| + "errors" |
| + "slices" |
| + "testing" |
| +) |
| + |
| +type outcomeAPI struct { |
| + supervisorAPI |
| + result *team.AttemptResult |
| +} |
| + |
| +func (a *outcomeAPI) Call(ctx context.Context, op string, q runnerproto.RunnerRequest, out any) error { |
| + if op == "complete" { |
| + a.result = q.Result |
| + } |
| + return a.supervisorAPI.Call(ctx, op, q, out) |
| +} |
| +func TestDeterministicAttemptErrorsFailWithReason(t *testing.T) { |
| + cases := []struct { |
| + err error |
| + reason string |
| + }{ |
| + {context.Canceled, "runner.cancelled"}, {context.DeadlineExceeded, "runner.timeout"}, |
| + {paseo.ErrIdentity, "runner.identity"}, {ErrPromptTooLarge, "runner.prompt_too_large"}, |
| + {team.ErrEvidence, "runner.evidence"}, {team.ErrQuota, "runner.quota"}, |
| + {team.ErrBudget, "runner.budget"}, {team.ErrReplayUnsafe, "runner.replay"}, |
| + {paseo.ErrContract, "runner.contract"}, {paseo.ErrUncertain, "runner.unavailable"}, |
| + {paseo.ErrClosed, "runner.unavailable"}, |
| + } |
| + for _, key := range []string{"form.invalid", "runner.replay", "runner.budget", "runner.quota", "runner.evidence"} { |
| + cases = append(cases, struct { |
| + err error |
| + reason string |
| + }{&RefusalError{Reason: key, Status: 422}, key}) |
| + } |
| + for _, tc := range cases { |
| + t.Run(tc.err.Error(), func(t *testing.T) { |
| + for _, cancelled := range []bool{false, true} { |
| + s, r, _, order := cleanupFixture(t) |
| + api := &outcomeAPI{supervisorAPI: supervisorAPI{order: order}} |
| + s.api = api |
| + err := tc.err |
| + if cancelled { |
| + r.ServiceInterrupted = tc.err != context.Canceled && tc.err != context.DeadlineExceeded |
| + err = errors.Join(err, context.Canceled) |
| + } |
| + _ = s.finishAttempt(context.Background(), r, err) |
| + if slices.Contains(*order, "release") || api.result == nil || api.result.Outcome != team.OutcomeFailure || api.result.Detail != tc.reason || r.FailureReason != tc.reason { |
| + t.Fatalf("task error released or reason lost: order=%v result=%+v reason=%s", *order, api.result, r.FailureReason) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| +func TestDaemonClosedBeforeDispatchReleases(t *testing.T) { |
| + s, r, _, order := cleanupFixture(t) |
| + r.Phase = "creating-agent" |
| + _ = s.finishAttempt(context.Background(), r, paseo.ErrClosed) |
| + if !slices.Contains(*order, "release") || slices.Contains(*order, "complete") { |
| + t.Fatal("pre-dispatch daemon outage failed job", *order) |
| + } |
| +} |
diff --git a/internal/runner/service.go b/internal/runner/service.go| index d96a3bbc..af2f2e95 100644 |
| --- a/internal/runner/service.go |
| +++ b/internal/runner/service.go |
| @@ -7,6 +7,7 @@ import ( |
| "crypto/rand" |
| "encoding/json" |
| "errors" |
| + jitter "math/rand/v2" |
| "time" |
| ) |
| @@ -26,6 +27,7 @@ func (s *Service) Run(ctx context.Context) error { |
| return paseo.ErrContract |
| } |
| needsRecovery := true |
| + claimRefusals := 0 |
| for { |
| if ctx.Err() != nil { |
| return ctx.Err() |
| @@ -79,11 +81,16 @@ func (s *Service) Run(ctx context.Context) error { |
| if err = s.clearClaim(ctx, request); err != nil { |
| return err |
| } |
| + claimRefusals++ |
| + if err := waitService(ctx, claimBackoffDelay(claimRefusals)); err != nil { |
| + return err |
| + } |
| continue |
| } |
| if err != nil { |
| return err |
| } |
| + claimRefusals = 0 |
| if s.BeforeRun != nil { |
| s.BeforeRun(RunClaim{Assignment: a, ClaimResponse: claim}) |
| } |
| @@ -166,8 +173,13 @@ func (s *Service) clearClaim(ctx context.Context, q runnerproto.ClaimRequest) er |
| return err |
| } |
| -func serviceBackoff(ctx context.Context) error { |
| - timer := time.NewTimer(500 * time.Millisecond) |
| +func claimBackoffDelay(failures int) time.Duration { |
| + base := time.Second * time.Duration(1<<min(max(failures-1, 0), 5)) |
| + return min(30*time.Second, base+time.Duration(jitter.Int64N(int64(base/4)+1))) |
| +} |
| +func serviceBackoff(ctx context.Context) error { return waitService(ctx, 500*time.Millisecond) } |
| +func waitService(ctx context.Context, delay time.Duration) error { |
| + timer := time.NewTimer(delay) |
| defer timer.Stop() |
| select { |
| case <-ctx.Done(): |
diff --git a/internal/runner/supervisor.go b/internal/runner/supervisor.go| index 37beba69..45d695c2 100644 |
| --- a/internal/runner/supervisor.go |
| +++ b/internal/runner/supervisor.go |
| @@ -36,6 +36,7 @@ type attemptState struct { |
| FailurePhase string |
| FailureDetail string |
| FailureReason string |
| + ServiceInterrupted bool |
| StopError string |
| SocketPath, CapabilityPath string |
| Proof *ContainmentProof |
| @@ -155,6 +156,7 @@ func (s *Supervisor) Run(ctx context.Context, claim RunClaim) error { |
| r.FailurePhase = r.Phase |
| r.FailureDetail = err.Error() |
| } |
| + r.ServiceInterrupted = ctx.Err() != nil |
| cancel(nil) |
| <-done |
| cleanupCtx, cleanupCancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second) |
| @@ -163,12 +165,8 @@ func (s *Supervisor) Run(ctx context.Context, claim RunClaim) error { |
| } |
| func (s *Supervisor) finishAttempt(cleanupCtx context.Context, r *attemptState, err error) error { |
| - if errors.Is(err, ErrPromptTooLarge) { |
| - r.FailureReason = "runner.prompt_too_large" |
| - } |
| - var refusal *RefusalError |
| - if errors.As(err, &refusal) { |
| - r.FailureReason = refusal.Reason |
| + if err != nil { |
| + r.FailureReason = attemptFailureReason(err) |
| } |
| outcome := "unprocessed" |
| @@ -177,16 +175,14 @@ func (s *Supervisor) finishAttempt(cleanupCtx context.Context, r *attemptState, |
| } |
| bookkeepingErr := s.journal.finishTools(cleanupCtx, r.Claim, outcome) |
| if err != nil { |
| - var refusal *RefusalError |
| - taskFailure := errors.Is(err, team.ErrEvidence) || (errors.As(err, &refusal) && refusal.Reason == "runner.evidence") |
| - if taskFailure { |
| - q := r.request("failed") |
| - q.Result = &team.AttemptResult{Outcome: team.OutcomeFailure} |
| - err = errors.Join(err, s.api.Call(cleanupCtx, "complete", q, nil)) |
| - } else { |
| + if infrastructureOnly(err, r) { |
| q := r.request("release") |
| q.Reason = team.WaitRunnerUnavailable |
| err = errors.Join(err, s.api.Call(cleanupCtx, "release", q, nil)) |
| + } else { |
| + q := r.request("failed") |
| + q.Result = &team.AttemptResult{Outcome: team.OutcomeFailure, Detail: r.FailureReason} |
| + err = errors.Join(err, s.api.Call(cleanupCtx, "complete", q, nil)) |
| } |
| } |
| _, cleanupErr := s.cleanup(cleanupCtx, r) |