fix: isolate task refusals and expose runner setup waits
7 files changed,
+287
−31
internal/equipo/runner_execution.go+59 −9internal/equipo/task_prepare.go+2 −0internal/equipo/task_views.go+1 −1internal/equipo/task_wait.go+81 −0internal/equipo/tasks.go+11 −16internal/equipotest/final_wait_test.go+123 −0internal/equipotest/tasks_test.go+10 −5
diff --git a/internal/equipo/runner_execution.go b/internal/equipo/runner_execution.go| index d0915420..570fe372 100644 |
| --- a/internal/equipo/runner_execution.go |
| +++ b/internal/equipo/runner_execution.go |
| @@ -228,6 +228,15 @@ func (e *Execution) Sync(ctx context.Context) error { |
| return storeError(err) |
| } |
| if _, err := e.store.StartBug(ctx, RunnerPrincipal{RunnerID: sel.RunnerID, Person: task.Requester, CredentialID: credential.ID}, task.ID, task.Revision); err != nil { |
| + if !taskRefusal(err) { |
| + return err |
| + } |
| + if err := taskWait(tx, task.ID, "task.wait.setup"); err != nil { |
| + return err |
| + } |
| + continue |
| + } |
| + if err := taskWait(tx, task.ID, ""); err != nil { |
| return err |
| } |
| } |
| @@ -240,6 +249,28 @@ func (e *Execution) Sync(ctx context.Context) error { |
| if err := tx.First(&out, "task_id=?", task.ID).Error; err != nil { |
| return storeError(err) |
| } |
| + var live int64 |
| + if err := tx.Model(&runnerAssignment{}).Where("task_id=? AND state IN ?", task.ID, []string{"claimed", "reconcile"}).Count(&live).Error; err != nil { |
| + return storeError(err) |
| + } |
| + if live == 0 { |
| + if err := e.store.refreshPendingPair(tx, task, &out); err != nil { |
| + if !taskRefusal(err) { |
| + return err |
| + } |
| + code, err := e.store.pairWait(tx, task.Requester, task.ProjectID) |
| + if err != nil { |
| + return err |
| + } |
| + if err := taskWait(tx, task.ID, code); err != nil { |
| + return err |
| + } |
| + continue |
| + } |
| + if err := taskWait(tx, task.ID, ""); err != nil { |
| + return err |
| + } |
| + } |
| var eng, rev Selection |
| if json.Unmarshal([]byte(out.Engineering), &eng) != nil || json.Unmarshal([]byte(out.Review), &rev) != nil { |
| return ErrUnavailable |
| @@ -286,7 +317,7 @@ func (e *Execution) Sync(ctx context.Context) error { |
| } |
| for _, key := range keys { |
| var count int64 |
| - if err := tx.Model(&runnerAssignment{}).Where("task_id=? AND step_key=? AND state!=?", task.ID, key, "contained").Count(&count).Error; err != nil { |
| + if err := tx.Model(&runnerAssignment{}).Where("task_id=? AND step_key=? AND state!='contained' AND NOT(state='fenced' AND claim_request='')", task.ID, key).Count(&count).Error; err != nil { |
| return storeError(err) |
| } |
| if count > 0 { |
| @@ -343,7 +374,16 @@ func (e *Execution) Poll(ctx context.Context, p RunnerPrincipal, after string) ( |
| for _, a := range rows { |
| value, err := e.assignmentCurrent(ctx, tx, p, a) |
| if err != nil { |
| - return err |
| + if !taskRefusal(err) { |
| + return err |
| + } |
| + if err := taskWait(tx, a.TaskID, "task.wait.setup"); err != nil { |
| + return err |
| + } |
| + if err := tx.Model(&runnerAssignment{}).Where("id=? AND state='pending'", a.ID).Select("State").Updates(&runnerAssignment{State: "fenced"}).Error; err != nil { |
| + return storeError(err) |
| + } |
| + continue |
| } |
| values = append(values, value) |
| } |
| @@ -435,14 +475,24 @@ func (e *Execution) Claim(ctx context.Context, p RunnerPrincipal, q ClaimRequest |
| if _, err := specialistAt(tx, specialistFor(a.StepKey)); err != nil { |
| return err |
| } |
| - // Preparation occupies the same specialist slot before it has a core attempt. |
| - var preparing int64 |
| - if err := tx.Model(&runnerAssignment{}).Where("kind='prepare' AND state!='contained' AND claim_request!=''").Count(&preparing).Error; err != nil { |
| - return storeError(err) |
| - } |
| - if preparing > 0 { |
| - return ErrUnavailable |
| + // Only live Engineering preparations occupy an Engineering slot. |
| + if specialistFor(a.StepKey) == "engineering" { |
| + var preparing, running int64 |
| + if err := tx.Model(&runnerAssignment{}).Where("team_id=? AND kind='prepare' AND state IN ('claimed','prepared') AND lease_deadline>?", task.TeamID, e.store.runnerClock.Now().UTC()).Count(&preparing).Error; err != nil { |
| + return storeError(err) |
| + } |
| + if err := tx.Table("attempts").Joins("JOIN steps ON steps.id=attempts.step_id").Where("attempts.containment='pending' AND steps.capability IN ?", []string{"reproduce", "implement", "reconcile"}).Count(&running).Error; err != nil { |
| + return storeError(err) |
| + } |
| + var sp Specialist |
| + if err := tx.First(&sp, "key='engineering'").Error; err != nil { |
| + return storeError(err) |
| + } |
| + if preparing+running >= int64(sp.MaxConcurrent) { |
| + return ErrUnavailable |
| + } |
| } |
| + |
| var project Project |
| if err := tx.First(&project, task.ProjectID).Error; err != nil { |
| return storeError(err) |
diff --git a/internal/equipo/task_prepare.go b/internal/equipo/task_prepare.go| index 5a15047a..54846919 100644 |
| --- a/internal/equipo/task_prepare.go |
| +++ b/internal/equipo/task_prepare.go |
| @@ -30,6 +30,8 @@ func samePreparationSelection(a, b Selection) bool { |
| a.AllowanceKnown = b.AllowanceKnown |
| a.AllowanceRemaining = b.AllowanceRemaining |
| a.AccountLabel = b.AccountLabel |
| + a.Isolation = b.Isolation |
| + a.Reason = b.Reason |
| return reflect.DeepEqual(a, b) |
| } |
| func (s *Store) bugPreparationAt(tx *gorm.DB, principal RunnerPrincipal, id string) (Task, taskOutbox, Project, error) { |
diff --git a/internal/equipo/task_views.go b/internal/equipo/task_views.go| index b9b79e2b..93412103 100644 |
| --- a/internal/equipo/task_views.go |
| +++ b/internal/equipo/task_views.go |
| @@ -452,7 +452,7 @@ func (s *Store) taskViewAt(tx *gorm.DB, actor Actor, task Task) (TaskViewData, e |
| } |
| func waitCopyKey(wait string) string { |
| switch wait { |
| - case "family", "different_family", "review_family": |
| + case "task.wait.family", "family", "different_family", "review_family": |
| return "task.wait.family" |
| default: |
| return "task.wait.setup" |
diff --git a/internal/equipo/task_wait.go b/internal/equipo/task_wait.go| new file mode 100644 |
| index 00000000..e5e5dcc0 |
| --- /dev/null |
| +++ b/internal/equipo/task_wait.go |
| @@ -0,0 +1,81 @@ |
| +package equipo |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "encoding/json" |
| + "errors" |
| + "gorm.io/gorm" |
| +) |
| + |
| +func taskRefusal(err error) bool { |
| + return err == ErrUnavailable || errors.Is(err, ErrConflict) || errors.Is(err, ErrForbidden) || errors.Is(err, ErrNotFound) || errors.Is(err, team.ErrBudget) || errors.Is(err, team.ErrGrantRevoked) || errors.Is(err, team.ErrGrantStale) |
| +} |
| +func taskWait(tx *gorm.DB, id, code string) error { |
| + return storeError(tx.Model(&Task{}).Where("id=? AND wait_code<>?", id, code).Select("WaitCode").Updates(&Task{WaitCode: code}).Error) |
| +} |
| + |
| +// A missing family and an ineligible connection need different setup actions. |
| +func (s *Store) pairWait(tx *gorm.DB, person string, project int64) (string, error) { |
| + _, ids, err := choiceAt(tx, person, project) |
| + if err != nil { |
| + if taskRefusal(err) { |
| + return "task.wait.setup", nil |
| + } |
| + return "", err |
| + } |
| + var rows []connectionRecord |
| + if err := tx.Where("person=? AND id IN ?", person, ids).Find(&rows).Error; err != nil { |
| + return "", storeError(err) |
| + } |
| + families := map[string]map[string]bool{} |
| + for _, c := range rows { |
| + if err := decodeConnection(&c); err != nil { |
| + return "", err |
| + } |
| + if families[c.RunnerID] == nil { |
| + families[c.RunnerID] = map[string]bool{} |
| + } |
| + for _, r := range c.Reports { |
| + if knownFamily(r.Family) { |
| + families[c.RunnerID][r.Family] = true |
| + } |
| + } |
| + } |
| + for _, f := range families { |
| + if len(f) >= 2 { |
| + return "task.wait.setup", nil |
| + } |
| + } |
| + return "task.wait.family", nil |
| +} |
| + |
| +func (s *Store) bugPair(tx *gorm.DB, person string, project int64) (Selection, Selection, error) { |
| + eng, err := s.selectConnectionAt(tx, person, project, "engineering", "") |
| + if err != nil { |
| + return eng, Selection{}, err |
| + } |
| + rev, err := s.selectConnectionOnRunnerAt(tx, person, project, "review", eng.Family, eng.RunnerID) |
| + if err != nil { |
| + return eng, rev, err |
| + } |
| + for _, sel := range []Selection{eng, rev} { |
| + if err := subscriptionSelection(tx, sel); err != nil { |
| + return eng, rev, err |
| + } |
| + } |
| + return eng, rev, nil |
| +} |
| + |
| +func (s *Store) refreshPendingPair(tx *gorm.DB, task Task, out *taskOutbox) error { |
| + if _, err := bugAuthority(tx, Actor{Address: task.Requester}, task.ProjectID); err != nil { |
| + return err |
| + } |
| + eng, rev, err := s.bugPair(tx, task.Requester, task.ProjectID) |
| + if err != nil { |
| + return err |
| + } |
| + a, _ := json.Marshal(eng) |
| + b, _ := json.Marshal(rev) |
| + out.Engineering, out.Review = string(a), string(b) |
| + return storeError(tx.Model(out).Where("task_id=?", task.ID).Select("Engineering", "Review").Updates(out).Error) |
| +} |
diff --git a/internal/equipo/tasks.go b/internal/equipo/tasks.go| index 5ca31d29..fc5e22de 100644 |
| --- a/internal/equipo/tasks.go |
| +++ b/internal/equipo/tasks.go |
| @@ -101,23 +101,18 @@ func (s *Store) CreateBug(ctx context.Context, actor Actor, projectID int64, des |
| if err != nil { |
| return err |
| } |
| - engineering, err := s.selectConnectionAt(tx, requester, projectID, "engineering", "") |
| + engineering, review, err := s.bugPair(tx, requester, projectID) |
| + wait := "" |
| if err != nil { |
| - return err |
| - } |
| - review, err := s.selectConnectionOnRunnerAt(tx, requester, projectID, "review", engineering.Family, engineering.RunnerID) |
| - if err != nil { |
| - return err |
| - } |
| - if engineering.RunnerID != review.RunnerID { |
| - return ErrUnavailable |
| - } |
| - if err := subscriptionSelection(tx, engineering); err != nil { |
| - return err |
| - } |
| - if err := subscriptionSelection(tx, review); err != nil { |
| - return err |
| + if !taskRefusal(err) { |
| + return err |
| + } |
| + wait, err = s.pairWait(tx, requester, projectID) |
| + if err != nil { |
| + return err |
| + } |
| } |
| + |
| var merge DecisionOwner |
| if err := tx.Where("project_id=? AND decision=?", projectID, "merge").First(&merge).Error; err != nil { |
| return storeError(err) |
| @@ -125,7 +120,7 @@ func (s *Store) CreateBug(ctx context.Context, actor Actor, projectID int64, des |
| if _, err := currentRunnerMember(tx, merge.Address); err != nil { |
| return err |
| } |
| - task = Task{ID: rand.Text(), Requester: requester, Description: description, RequestID: requestID, ProjectID: projectID, Revision: 1, State: "preparing", TeamID: instance.ID, MergeOwner: merge.Address} |
| + task = Task{ID: rand.Text(), Requester: requester, Description: description, RequestID: requestID, ProjectID: projectID, Revision: 1, State: "preparing", WaitCode: wait, TeamID: instance.ID, MergeOwner: merge.Address} |
| task.ReviewRef = "equipo/" + task.ID |
| eng, _ := json.Marshal(engineering) |
| rev, _ := json.Marshal(review) |
diff --git a/internal/equipotest/final_wait_test.go b/internal/equipotest/final_wait_test.go| new file mode 100644 |
| index 00000000..6efbfd58 |
| --- /dev/null |
| +++ b/internal/equipotest/final_wait_test.go |
| @@ -0,0 +1,123 @@ |
| +package equipotest |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| +) |
| + |
| +func TestBugWithoutPairWaits(t *testing.T) { |
| + for _, setup := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "family", true: "setup"}[setup], func(t *testing.T) { |
| + f := bugFixture(t) |
| + if setup { |
| + mustSQL(t, f.d, "DELETE FROM isolation_acknowledgements") |
| + } else { |
| + mustSQL(t, f.d, "DELETE FROM connections WHERE id=?", f.ids["codex"]) |
| + } |
| + task, err := f.s.CreateBug(connectionContext, ownerActor, f.project.ID, "waiting bug", "wait") |
| + executionMust(t, err) |
| + want := "task.wait.family" |
| + if setup { |
| + want = "task.wait.setup" |
| + } |
| + if task.WaitCode != want || task.JobID != 0 { |
| + t.Fatal("missing waiting task", task) |
| + } |
| + view, err := f.s.TaskView(connectionContext, ownerActor, task.ID) |
| + executionMust(t, err) |
| + if view.StateKey != want { |
| + t.Fatal("waiting reason absent from page data", view.StateKey) |
| + } |
| + if scalar(t, f.d, "SELECT count(*) FROM runner_assignments") != 0 { |
| + t.Fatal("waiting task dispatched") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestSyncSkipsStalePreparedTask(t *testing.T) { |
| + for _, change := range []string{"specialist", "budget", "project", "requester"} { |
| + t.Run(change, func(t *testing.T) { |
| + f := runnerFixtureNew(t, false) |
| + task, err := f.s.CreateBug(connectionContext, ownerActor, f.project.ID, "stale bug", "stale") |
| + executionMust(t, err) |
| + task, err = f.s.PrepareBug(connectionContext, f.principal, task.ID, task.Revision, bugPrepared(f.connectionFixture)) |
| + executionMust(t, err) |
| + switch change { |
| + case "specialist": |
| + mustSQL(t, f.d, "UPDATE specialists SET revision=revision+1 WHERE key='engineering'") |
| + case "budget": |
| + mustSQL(t, f.d, "UPDATE task_outboxes SET budget_revision=budget_revision-1 WHERE task_id=?", task.ID) |
| + case "project": |
| + mustSQL(t, f.d, "UPDATE task_outboxes SET project_revision=project_revision-1 WHERE task_id=?", task.ID) |
| + case "requester": |
| + mustSQL(t, f.d, "UPDATE tasks SET requester='removed@example.com' WHERE id=?", task.ID) |
| + } |
| + executionMust(t, f.x.Sync(connectionContext)) |
| + var wait string |
| + executionMust(t, f.d.Writer().QueryRow("SELECT wait_code FROM tasks WHERE id=?", task.ID).Scan(&wait)) |
| + if wait != "task.wait.setup" { |
| + t.Fatal("stale task has no setup wait", wait) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPollSkipsStaleAssignment(t *testing.T) { |
| + f := runnerFixtureNew(t, false) |
| + mustSQL(t, f.d, "UPDATE specialists SET revision=revision+1 WHERE key='engineering'") |
| + ctx, cancel := context.WithTimeout(connectionContext, 250*time.Millisecond) |
| + defer cancel() |
| + assignments, err := f.x.Poll(ctx, f.principal, "") |
| + if err != nil && !errors.Is(err, context.DeadlineExceeded) { |
| + t.Fatal("one stale task failed poll", err) |
| + } |
| + if len(assignments) != 0 { |
| + t.Fatal("stale assignment dispatched") |
| + } |
| + var wait string |
| + executionMust(t, f.d.Writer().QueryRow("SELECT wait_code FROM tasks WHERE id=?", f.a.TaskID).Scan(&wait)) |
| + if wait != "task.wait.setup" { |
| + t.Fatal("stale assignment has no wait", wait) |
| + } |
| + executionMust(t, f.x.Sync(connectionContext)) |
| + retryCtx, retryCancel := context.WithTimeout(connectionContext, time.Second) |
| + defer retryCancel() |
| + aa, err := f.x.Poll(retryCtx, f.principal, "") |
| + executionMust(t, err) |
| + if len(aa) != 1 || aa[0].ID == f.a.ID { |
| + t.Fatal("authorized fenced pending assignment not replaced", aa) |
| + } |
| +} |
| + |
| +func TestPreparationTaintDoesNotInvalidate(t *testing.T) { |
| + f := bugFixture(t) |
| + task := bugTask(t, f) |
| + mustSQL(t, f.d, `UPDATE task_outboxes SET engineering=json_set(engineering,'$.Isolation.runner_tainted',json('false'),'$.Isolation.acknowledgement_ids',json('[]')) WHERE task_id=?`, task.ID) |
| + _, err := f.s.PrepareBug(connectionContext, f.principal, task.ID, task.Revision, bugPrepared(f)) |
| + executionMust(t, err) |
| +} |
| + |
| +func TestExpiredPreparationDoesNotBlockClaim(t *testing.T) { |
| + for _, state := range []string{"claimed", "fenced"} { |
| + t.Run(state, func(t *testing.T) { |
| + f := runnerFixtureNew(t, false) |
| + mustSQL(t, f.d, `INSERT INTO runner_assignments(id,task_id,step_key,workspace_key,team_id,runner_id,person,selection,isolation,kind,state,revision,job_id,attempt_id,fence,claim_request,lease_deadline,brief) SELECT 'old-prepare',task_id,'prepare','old',team_id,runner_id,person,selection,isolation,'prepare',?,1,0,0,1,'old',?,'{}' FROM runner_assignments WHERE id=?`, state, f.clock.Now().Add(-time.Minute), f.a.ID) |
| + _, err := f.x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 1, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "claim"}) |
| + executionMust(t, err) |
| + }) |
| + } |
| +} |
| + |
| +func TestPreparationCapacityIsPerSpecialist(t *testing.T) { |
| + f := runnerFixtureNew(t, false) |
| + mustSQL(t, f.d, `UPDATE steps SET depends_on='[]' WHERE key='review'`) |
| + mustSQL(t, f.d, `UPDATE runner_assignments SET step_key='review',selection=(SELECT review FROM task_outboxes WHERE task_id=runner_assignments.task_id) WHERE id=?`, f.a.ID) |
| + mustSQL(t, f.d, `INSERT INTO runner_assignments(id,task_id,step_key,workspace_key,team_id,runner_id,person,selection,isolation,kind,state,revision,job_id,attempt_id,fence,claim_request,lease_deadline,brief) SELECT 'other-prepare',task_id,'prepare','other',team_id,runner_id,person,selection,isolation,'prepare','claimed',1,0,0,1,'other',?,'{}' FROM runner_assignments WHERE id=?`, f.clock.Now().Add(time.Minute), f.a.ID) |
| + _, err := f.x.Claim(connectionContext, f.principal, equipo.ClaimRequest{Version: 1, AssignmentID: f.a.ID, Revision: f.a.Revision, RequestID: "review"}) |
| + executionMust(t, err) |
| +} |
diff --git a/internal/equipotest/tasks_test.go b/internal/equipotest/tasks_test.go| index 9e29c335..5a9f4379 100644 |
| --- a/internal/equipotest/tasks_test.go |
| +++ b/internal/equipotest/tasks_test.go |
| @@ -375,11 +375,16 @@ func TestBugSubmissionWaitsForConnectionsAndBudget(t *testing.T) { |
| } |
| executionMust(t, f.s.SaveConnectionChoice(connectionContext, ownerActor, equipo.ConnectionChoice{ProjectID: f.project.ID, Revision: 1, ConnectionIDs: []string{f.ids["claude"], f.ids["codex"]}, PinnedID: f.ids["claude"]})) |
| } |
| - if _, err := f.s.CreateBug(connectionContext, ownerActor, f.project.ID, "bug", "refused"); err == nil { |
| - t.Fatal("unfunded or unavailable submission accepted", guard) |
| - } |
| - if scalar(t, f.d, "SELECT count(*) FROM tasks") != 0 { |
| - t.Fatal("refused submission persisted") |
| + task, err := f.s.CreateBug(connectionContext, ownerActor, f.project.ID, "bug", "refused") |
| + if guard == "budget" { |
| + if err == nil || scalar(t, f.d, "SELECT count(*) FROM tasks") != 0 { |
| + t.Fatal("unfunded submission accepted") |
| + } |
| + } else { |
| + executionMust(t, err) |
| + if task.WaitCode != "task.wait.setup" || task.JobID != 0 { |
| + t.Fatal("unavailable connection did not wait", task) |
| + } |
| } |
| }) |
| } |