Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(daemon): wake queued tasks after predecessor exits (#5379)
Multica Eveaf9d90bd837f
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 24b0864f07..552d104706 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -2735,10 +2735,7 @@ func (d *Daemon) pollLoop(ctx context.Context, taskWakeups <-chan taskWakeup) erwakeup := make(chan struct{}, 1)nudge := func() {- select {- case wakeup <- struct{}{}:- default:- }+ signalPollerWakeup(wakeup)}pollerCtx, pollerCancel := context.WithCancel(ctx)@@ -2787,7 +2784,7 @@ func (d *Daemon) pollLoop(ctx context.Context, taskWakeups <-chan taskWakeup) er// pollerCtx is cancelled on shutdown. parentCtx is the daemon root ctx passed to// handleTask so an in-flight task is not killed just because the poll loop is// stopping mid-flight.-func (d *Daemon) runBatchPoller(pollerCtx, parentCtx context.Context, sem chan int, wakeup <-chan struct{}, taskWG *sync.WaitGroup) {+func (d *Daemon) runBatchPoller(pollerCtx, parentCtx context.Context, sem chan int, wakeup chan struct{}, taskWG *sync.WaitGroup) {releaseSlots := func(slots []int) {for _, sl := range slots {sem <- sl@@ -2867,7 +2864,15 @@ func (d *Daemon) runBatchPoller(pollerCtx, parentCtx context.Context, sem chan igo func(t Task, slot int) {defer taskWG.Done()defer d.activeTasks.Add(-1)- defer func() { sem <- slot }()+ defer func() {+ // Release local capacity before waking the poller. The task's+ // terminal callback and local cleanup have both finished at this+ // point, so a successor that was previously blocked by agent+ // capacity or per-(issue, agent) serialization can be claimed+ // immediately instead of waiting for PollInterval.+ sem <- slot+ signalPollerWakeup(wakeup)+ }()d.handleTask(parentCtx, t, slot)}(t, slot)dispatched++@@ -2888,6 +2893,13 @@ func (d *Daemon) runBatchPoller(pollerCtx, parentCtx context.Context, sem chan i}}+func signalPollerWakeup(wakeup chan<- struct{}) {+ select {+ case wakeup <- struct{}{}:+ default:+ }+}+// drainAvailableSlots non-blockingly pulls up to max additional slots from the// semaphore, returning immediately when none are free.func drainAvailableSlots(sem chan int, max int) []int {diff --git a/server/internal/daemon/runtime_isolation_test.go b/server/internal/daemon/runtime_isolation_test.goindex cca8222d67..837aa54f06 100644--- a/server/internal/daemon/runtime_isolation_test.go+++ b/server/internal/daemon/runtime_isolation_test.go@@ -199,6 +199,141 @@ func TestRunBatchPollerClaimsAcrossRuntimes(t *testing.T) {taskWG.Wait()}+// TestRunBatchPollerWakesAfterTaskExit guards the gap where a queued task is+// temporarily unclaimable (for example, because the same agent/issue task is+// still running), the batch claim returns empty, and the poller goes to sleep+// for PollInterval. Finishing the active task must wake that sleep locally;+// relying only on the enqueue-time websocket hint can leave the successor+// queued for the full default 30 seconds.+func TestRunBatchPollerWakesAfterTaskExit(t *testing.T) {+ t.Parallel()+ testRunBatchPollerTaskExitWakeup(t, 2, 50*time.Millisecond)+}++// The max-concurrency=1 shape takes a different sleep branch: after the+// two-second slot wait expires, the poller parks on the five-second capacity+// backoff. A returned semaphore slot alone does not wake that sleep, so the+// explicit completion signal is required there too.+func TestRunBatchPollerWakesFromCapacityBackoffAfterTaskExit(t *testing.T) {+ t.Parallel()+ testRunBatchPollerTaskExitWakeup(t, 1, taskSlotWaitTimeout+250*time.Millisecond)+}++func testRunBatchPollerTaskExitWakeup(t *testing.T, maxConcurrent int, releaseDelay time.Duration) {+ t.Helper()++ var firstCompleted atomic.Bool+ var secondServed atomic.Bool+ var claimCalls atomic.Int64+ firstStarted := make(chan struct{})+ releaseFirst := make(chan struct{})+ secondStarted := make(chan struct{})++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ switch {+ case strings.HasSuffix(r.URL.Path, "/api/daemon/tasks/claim"):+ claimCalls.Add(1)+ switch {+ case !firstCompleted.Load():+ w.Write([]byte(`{"tasks":[{"id":"t1","runtime_id":"rt-1","issue_id":"i1","agent":{"name":"a"}}]}`))+ case secondServed.CompareAndSwap(false, true):+ w.Write([]byte(`{"tasks":[{"id":"t2","runtime_id":"rt-1","issue_id":"i1","agent":{"name":"a"}}]}`))+ default:+ w.Write([]byte(`{"tasks":[]}`))+ }+ case strings.HasSuffix(r.URL.Path, "/api/daemon/tasks/t1/complete"):+ firstCompleted.Store(true)+ w.Write([]byte(`{}`))+ default:+ w.Write([]byte(`{}`))+ }+ }))+ defer srv.Close()++ d := New(Config{+ ServerBaseURL: srv.URL,+ HeartbeatInterval: time.Hour,+ PollInterval: time.Hour,+ MaxConcurrentTasks: maxConcurrent,+ }, slog.New(slog.NewTextHandler(noopWriter{}, nil)))+ d.workspaces["ws-1"] = &workspaceState{workspaceID: "ws-1", runtimeIDs: []string{"rt-1"}}+ d.runtimeIndex["rt-1"] = Runtime{ID: "rt-1"}+ d.cancelPollInterval = time.Hour+ d.runner = taskRunnerFunc(func(ctx context.Context, task Task, provider string, slot int, log *slog.Logger) (TaskResult, error) {+ switch task.ID {+ case "t1":+ close(firstStarted)+ select {+ case <-releaseFirst:+ case <-ctx.Done():+ return TaskResult{Status: "cancelled"}, ctx.Err()+ }+ case "t2":+ close(secondStarted)+ }+ return TaskResult{Status: "completed"}, nil+ })++ sem := newTaskSlotSemaphore(d.cfg.MaxConcurrentTasks)+ wakeup := make(chan struct{}, 1)+ var taskWG sync.WaitGroup+ ctx, cancel := context.WithCancel(context.Background())+ pollDone := make(chan struct{})+ go func() {+ defer close(pollDone)+ d.runBatchPoller(ctx, ctx, sem, wakeup, &taskWG)+ }()++ select {+ case <-firstStarted:+ case <-time.After(2 * time.Second):+ cancel()+ <-pollDone+ t.Fatal("first task was not dispatched")+ }++ // Give the poller time to enter the sleep branch under test. No websocket+ // wakeup is sent; only the task-exit signal may resume the poller.+ time.Sleep(releaseDelay)+ close(releaseFirst)++ select {+ case <-secondStarted:+ case <-time.After(2 * time.Second):+ cancel()+ <-pollDone+ t.Fatalf("successor was not dispatched after predecessor exit; claim calls=%d", claimCalls.Load())+ }++ cancel()+ <-pollDone+ taskWG.Wait()+}++func TestSignalPollerWakeupCoalescesAndIsNilSafe(t *testing.T) {+ t.Parallel()+ wakeup := make(chan struct{}, 1)+ signalPollerWakeup(wakeup)+ signalPollerWakeup(wakeup)+ if got := len(wakeup); got != 1 {+ t.Fatalf("coalesced wakeup count = %d, want 1", got)+ }++ // A nil channel models a poller that has no local wakeup transport. The+ // non-blocking helper must return instead of hanging a finishing task.+ done := make(chan struct{})+ go func() {+ signalPollerWakeup(nil)+ close(done)+ }()+ select {+ case <-done:+ case <-time.After(time.Second):+ t.Fatal("nil poller wakeup blocked")+ }+}+// TestRunBatchPollerSkipsClaimWhenAtCapacity pins slot-before-claim for the// batch poller: with no free execution slots it must NOT claim, so tasks never// pile up server-side `dispatched` and race the dispatch-timeout sweeper.diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex dc675fc159..1e103fa9e5 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -2803,6 +2803,10 @@ func (h *Handler) CompleteTask(w http.ResponseWriter, r *http.Request) {// by the existing per-(issue, agent) dedup, and terminating because the// triggering comment always predates the follow-up run's started_at.h.reconcileCommentsOnCompletion(r.Context(), task)+ // The terminal transaction and completion reconciliation are committed.+ // Wake the owning runtime now so queued work that was blocked by this+ // task's agent capacity or serialization key is re-claimed immediately.+ h.TaskService.NotifyTaskFinished(*task)// Best-effort revoke of any agent task token minted at claim time.// The token would naturally expire at the 24h watermark and is also@@ -3383,6 +3387,7 @@ func (h *Handler) FailTask(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusBadRequest, err.Error())return}+ h.TaskService.NotifyTaskFinished(*task)// Best-effort revoke of the mat_ task token minted at claim. Same// rationale as CompleteTask — eager deletion shrinks the post-diff --git a/server/internal/handler/task_terminal_wakeup_test.go b/server/internal/handler/task_terminal_wakeup_test.gonew file mode 100644index 0000000000..f550798d83--- /dev/null+++ b/server/internal/handler/task_terminal_wakeup_test.go@@ -0,0 +1,126 @@+package handler++import (+ "context"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/go-chi/chi/v5"+)++type terminalWakeupRecorder struct {+ calls []struct{ runtimeID, taskID string }+}++func (r *terminalWakeupRecorder) NotifyTaskAvailable(runtimeID, taskID string) {+ r.calls = append(r.calls, struct{ runtimeID, taskID string }{runtimeID, taskID})+}++func failTaskViaHandler(t *testing.T, taskID string) *httptest.ResponseRecorder {+ t.Helper()+ w := httptest.NewRecorder()+ req := newDaemonTokenRequest("POST", "/api/daemon/tasks/"+taskID+"/fail",+ map[string]any{"error": "agent failed", "failure_reason": "agent_error"},+ testWorkspaceID, "legit-daemon")+ rctx := chi.NewRouteContext()+ rctx.URLParams.Add("taskId", taskID)+ req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))+ testHandler.FailTask(w, req)+ return w+}++// TestTerminalTransitionsNotifyRuntime verifies the server-side half of the+// queued-successor fix. Completion wakes only after reconciliation, while fail+// and cancel wake after their terminal side effects, so an old daemon can retry+// its normal atomic claim path without waiting for the 30-second fallback.+func TestTerminalTransitionsNotifyRuntime(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ var agentID, runtimeID string+ if err := testPool.QueryRow(ctx,+ `SELECT id, runtime_id FROM agent WHERE workspace_id = $1 AND runtime_id IS NOT NULL LIMIT 1`,+ testWorkspaceID).Scan(&agentID, &runtimeID); err != nil {+ t.Fatalf("setup: get agent: %v", err)+ }++ var issueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position, assignee_type, assignee_id)+ VALUES ($1, 'terminal wakeup fixture', 'in_progress', 'none', $2, 'member', 999099, 0, 'agent', $3)+ RETURNING id+ `, testWorkspaceID, testUserID, agentID).Scan(&issueID); err != nil {+ t.Fatalf("setup: create issue: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })++ var taskID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, created_at, started_at)+ VALUES ($1, $2, $3, 'running', 0, now() - interval '2 minutes', now() - interval '1 minute')+ RETURNING id+ `, agentID, runtimeID, issueID).Scan(&taskID); err != nil {+ t.Fatalf("setup: running task: %v", err)+ }++ recorder := &terminalWakeupRecorder{}+ previous := testHandler.TaskService.Wakeup+ testHandler.TaskService.Wakeup = recorder+ t.Cleanup(func() { testHandler.TaskService.Wakeup = previous })++ if w := completeTaskViaHandler(t, taskID, "done"); w.Code != http.StatusOK {+ t.Fatalf("CompleteTask: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if got := len(recorder.calls); got != 1 {+ t.Fatalf("expected 1 terminal runtime wakeup, got %d", got)+ }+ if recorder.calls[0].runtimeID != runtimeID {+ t.Fatalf("wakeup runtime = %q, want %q", recorder.calls[0].runtimeID, runtimeID)+ }+ if recorder.calls[0].taskID != "" {+ t.Fatalf("terminal wakeup must omit completed task id, got %q", recorder.calls[0].taskID)+ }++ // Failure uses the daemon callback handler, matching production. It must+ // send the same runtime-only hint after FailTask commits.+ recorder.calls = nil+ var failedTaskID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, created_at, started_at)+ VALUES ($1, $2, $3, 'running', 0, now() - interval '2 minutes', now() - interval '1 minute')+ RETURNING id+ `, agentID, runtimeID, issueID).Scan(&failedTaskID); err != nil {+ t.Fatalf("setup: failed task: %v", err)+ }+ if w := failTaskViaHandler(t, failedTaskID); w.Code != http.StatusOK {+ t.Fatalf("FailTask: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if got := len(recorder.calls); got != 1 || recorder.calls[0].runtimeID != runtimeID || recorder.calls[0].taskID != "" {+ t.Fatalf("unexpected failure wakeups: %#v", recorder.calls)+ }++ // Cancellation is finalized in TaskService because both issue and chat+ // handlers share that path.+ recorder.calls = nil+ var cancelledTaskID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, created_at, started_at)+ VALUES ($1, $2, $3, 'running', 0, now() - interval '2 minutes', now() - interval '1 minute')+ RETURNING id+ `, agentID, runtimeID, issueID).Scan(&cancelledTaskID); err != nil {+ t.Fatalf("setup: cancelled task: %v", err)+ }+ cancelled, err := testHandler.TaskService.CancelTask(ctx, parseUUID(cancelledTaskID))+ if err != nil {+ t.Fatalf("CancelTask: %v", err)+ }+ if cancelled.Status != "cancelled" {+ t.Fatalf("CancelTask status = %q, want cancelled", cancelled.Status)+ }+ if got := len(recorder.calls); got != 1 || recorder.calls[0].runtimeID != runtimeID || recorder.calls[0].taskID != "" {+ t.Fatalf("unexpected cancellation wakeups: %#v", recorder.calls)+ }+}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 3208d256c7..aefa6aa7a6 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -1236,6 +1236,7 @@ func (s *TaskService) CancelTasksForIssue(ctx context.Context, issueID pgtype.UUs.ReconcileAgentStatus(ctx, t.AgentID)s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, t)}+ s.notifyTasksFinished(cancelled)return nil}@@ -1258,6 +1259,7 @@ func (s *TaskService) CancelTasksForAgent(ctx context.Context, agentID pgtype.UU// working→available based on remaining task counts, no need to call// per row (the rows we just cancelled all belong to the same agent).s.ReconcileAgentStatus(ctx, agentID)+ s.notifyTasksFinished(cancelled)return cancelled, nil}@@ -1275,6 +1277,7 @@ func (s *TaskService) CancelTasksByTriggerComment(ctx context.Context, commentIDs.ReconcileAgentStatus(ctx, t.AgentID)s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, t)}+ s.notifyTasksFinished(cancelled)return cancelled, nil}@@ -1288,6 +1291,7 @@ func (s *TaskService) BroadcastCancelledTasks(ctx context.Context, cancelled []ds.ReconcileAgentStatus(ctx, t.AgentID)s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, t)}+ s.notifyTasksFinished(cancelled)}func (s *TaskService) CaptureCancelledTasks(ctx context.Context, cancelled []db.AgentTaskQueue) {@@ -1346,6 +1350,7 @@ func (s *TaskService) CancelTaskWithResult(ctx context.Context, taskID pgtype.UU// Broadcast cancellation as a task:failed event so frontends clear the live cards.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, task)+ s.NotifyTaskFinished(task)return &CancelTaskResult{Task: task,@@ -2872,6 +2877,7 @@ func (s *TaskService) HandleFailedTasks(ctx context.Context, tasks []db.AgentTasfor _, agentID := range affectedAgents {s.ReconcileAgentStatus(ctx, agentID)}+ s.notifyTasksFinished(tasks)return retried}@@ -3119,6 +3125,33 @@ func (s *TaskService) NotifyTaskEnqueued(ctx context.Context, task db.AgentTaskQs.notifyTaskAvailable(task)}+// NotifyTaskFinished invalidates a runtime's empty-claim verdict and emits a+// best-effort daemon wakeup after a task reaches a terminal state. The task ID+// is deliberately omitted from the wakeup payload: the completed task itself+// is not available; the hint only means that a queued successor may have+// become claimable because an agent-capacity or serialization barrier cleared.+func (s *TaskService) NotifyTaskFinished(task db.AgentTaskQueue) {+ s.notifyRuntimeMayHaveWork(task.RuntimeID, "")+}++// notifyTasksFinished is the batch form used by bulk terminal transitions.+// Coalesce by runtime so cancelling many tasks on one machine produces one+// cache bump and one websocket hint rather than a burst of identical work.+func (s *TaskService) notifyTasksFinished(tasks []db.AgentTaskQueue) {+ seen := make(map[string]struct{}, len(tasks))+ for _, task := range tasks {+ if !task.RuntimeID.Valid {+ continue+ }+ runtimeKey := util.UUIDToString(task.RuntimeID)+ if _, ok := seen[runtimeKey]; ok {+ continue+ }+ seen[runtimeKey] = struct{}{}+ s.notifyRuntimeMayHaveWork(task.RuntimeID, "")+ }+}+// notifyTaskAvailable runs after a task has been inserted: bumps the// runtime's invalidation version so any in-flight claim that is about// to write an "empty" verdict will have it rejected on read, then@@ -3127,10 +3160,16 @@ func (s *TaskService) NotifyTaskEnqueued(ctx context.Context, task db.AgentTaskQ// otherwise the wakeup-driven claim could read the still-current// empty verdict and return null.func (s *TaskService) notifyTaskAvailable(task db.AgentTaskQueue) {- if !task.RuntimeID.Valid {+ s.notifyRuntimeMayHaveWork(task.RuntimeID, util.UUIDToString(task.ID))+}++// notifyRuntimeMayHaveWork is the shared bump-before-wakeup primitive for both+// fresh enqueues and terminal transitions that can unblock queued work.+func (s *TaskService) notifyRuntimeMayHaveWork(runtimeID pgtype.UUID, taskID string) {+ if !runtimeID.Valid {return}- runtimeKey := util.UUIDToString(task.RuntimeID)+ runtimeKey := util.UUIDToString(runtimeID)// Use a background context: the cache bump / wakeup must outlive// the request that created the task, otherwise an early client// disconnect could leave the empty verdict in place and stall the@@ -3141,7 +3180,7 @@ func (s *TaskService) notifyTaskAvailable(task db.AgentTaskQueue) {if s.Wakeup == nil {return}- s.Wakeup.NotifyTaskAvailable(runtimeKey, util.UUIDToString(task.ID))+ s.Wakeup.NotifyTaskAvailable(runtimeKey, taskID)}func (s *TaskService) broadcastTaskDispatch(ctx context.Context, task db.AgentTaskQueue) {diff --git a/server/internal/service/task_notify_test.go b/server/internal/service/task_notify_test.goindex deda579637..4655ac9030 100644--- a/server/internal/service/task_notify_test.go+++ b/server/internal/service/task_notify_test.go@@ -101,3 +101,64 @@ func TestNotifyTaskAvailable_InvalidWithoutRuntimeIsNoOp(t *testing.T) {t.Fatalf("expected 0 wakeup calls when RuntimeID is invalid, got %d", got)}}++// TestNotifyTaskFinished_BumpsBeforeRuntimeWakeup pins the terminal-transition+// half of the wakeup contract. A prior empty verdict must not hide queued work+// that becomes claimable when another task releases agent capacity or a+// per-(issue, agent) serialization key.+func TestNotifyTaskFinished_BumpsBeforeRuntimeWakeup(t *testing.T) {+ rdb := newRedisTestClient(t)+ cache := NewEmptyClaimCache(rdb)+ wakeup := &stubWakeup{}+ svc := &TaskService{EmptyClaim: cache, Wakeup: wakeup}++ runtimeID := testUUID(10)+ runtimeKey := util.UUIDToString(runtimeID)+ ctx := context.Background()+ version := cache.CurrentVersion(ctx, runtimeKey)+ cache.MarkEmpty(ctx, runtimeKey, version)+ if !cache.IsEmpty(ctx, runtimeKey) {+ t.Fatal("precondition: cache should report empty")+ }++ svc.NotifyTaskFinished(db.AgentTaskQueue{ID: testUUID(11), RuntimeID: runtimeID})++ if cache.IsEmpty(ctx, runtimeKey) {+ t.Fatal("terminal wakeup must invalidate the prior empty verdict")+ }+ if got := len(wakeup.calls); got != 1 {+ t.Fatalf("expected 1 terminal wakeup, got %d", got)+ }+ if wakeup.calls[0].runtimeID != runtimeKey {+ t.Fatalf("wakeup runtime mismatch: got %q want %q", wakeup.calls[0].runtimeID, runtimeKey)+ }+ if wakeup.calls[0].taskID != "" {+ t.Fatalf("terminal wakeup must omit completed task id, got %q", wakeup.calls[0].taskID)+ }+}++func TestNotifyTasksFinished_CoalescesByRuntime(t *testing.T) {+ wakeup := &stubWakeup{}+ svc := &TaskService{Wakeup: wakeup}+ runtimeA := testUUID(12)+ runtimeB := testUUID(13)++ svc.notifyTasksFinished([]db.AgentTaskQueue{+ {ID: testUUID(14), RuntimeID: runtimeA},+ {ID: testUUID(15), RuntimeID: runtimeA},+ {ID: testUUID(16), RuntimeID: runtimeB},+ {ID: testUUID(17)}, // Invalid runtime is ignored.+ })++ if got := len(wakeup.calls); got != 2 {+ t.Fatalf("expected one wakeup per runtime, got %d", got)+ }+ if wakeup.calls[0].runtimeID != util.UUIDToString(runtimeA) || wakeup.calls[1].runtimeID != util.UUIDToString(runtimeB) {+ t.Fatalf("unexpected runtime wakeups: %#v", wakeup.calls)+ }+ for _, call := range wakeup.calls {+ if call.taskID != "" {+ t.Fatalf("terminal wakeup must omit completed task id, got %q", call.taskID)+ }+ }+}