Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7259: fix(server): stop reporting a failed workspace lookup as a deleted task (#8279)
Bohan Jiang51803b3b3bc0
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 20a42ab67a..064b8a5abd 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -140,7 +140,18 @@ func (h *Handler) requireDaemonTaskAccessWithWorkspace(w http.ResponseWriter, rreturn db.AgentTaskQueue{}, "", false}- wsID := h.TaskService.ResolveTaskWorkspaceID(r.Context(), task)+ // Same rule as the GetAgentTask branch above, one link further out: the+ // daemon kills a running agent on this 404, so only a lookup that actually+ // completed and found nothing may produce it. A DB timeout resolving the+ // issue / chat session / autopilot leaves us unable to tell whether the+ // task is reachable, and "I don't know" must not be reported as "deleted"+ // (MUL-7259 / GH #8272 — the branch #2127 hardened above, missed here).+ wsID, err := h.TaskService.ResolveTaskWorkspaceIDChecked(r.Context(), task)+ if err != nil {+ slog.Warn("resolve task workspace failed", "task_id", taskID, "error", err)+ writeError(w, http.StatusInternalServerError, "failed to load task")+ return db.AgentTaskQueue{}, "", false+ }if wsID == "" {writeError(w, http.StatusNotFound, "task not found")return db.AgentTaskQueue{}, "", false@@ -5391,12 +5402,27 @@ func (h *Handler) ListTaskMessagesByUser(w http.ResponseWriter, r *http.Request)task, err := h.Queries.GetAgentTask(r.Context(), taskUUID)if err != nil {+ if !isNotFound(err) {+ slog.Warn("get agent task failed", "task_id", taskID, "error", err)+ writeError(w, http.StatusInternalServerError, "failed to load task")+ return+ }writeError(w, http.StatusNotFound, "task not found")return}- // Verify the task belongs to the caller's workspace.- wsID := h.TaskService.ResolveTaskWorkspaceID(r.Context(), task)+ // Verify the task belongs to the caller's workspace. A failed lookup is a+ // 5xx here too: this endpoint does not drive the daemon's interrupt, but+ // telling a reader "this task does not exist" because the DB blinked is+ // the same lie, and it trains clients to give up on a retryable error.+ wsID, err := h.TaskService.ResolveTaskWorkspaceIDChecked(r.Context(), task)+ if err != nil {+ slog.Warn("resolve task workspace failed", "task_id", taskID, "error", err)+ writeError(w, http.StatusInternalServerError, "failed to load task")+ return+ }+ // Mismatch stays a 404 rather than a 403: a task in another workspace must+ // be indistinguishable from one that does not exist.if wsID == "" || wsID != middleware.WorkspaceIDFromContext(r.Context()) {writeError(w, http.StatusNotFound, "task not found")returndiff --git a/server/internal/handler/daemon_task_lookup_test.go b/server/internal/handler/daemon_task_lookup_test.gonew file mode 100644index 0000000000..73ad1f373d--- /dev/null+++ b/server/internal/handler/daemon_task_lookup_test.go@@ -0,0 +1,203 @@+package handler++import (+ "context"+ "net/http"+ "strings"+ "testing"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5"+ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// The daemon interrupts a running agent the moment a task-status poll answers+// `404 task not found` (shouldInterruptAgent → isTaskNotFoundError). So that+// body is a kill signal, and only a lookup that completed and found nothing may+// produce it. #2127 established this for GetAgentTask; these tests hold the same+// line for the workspace resolution three lines below it, which #2127 missed and+// GH #8272 hit in production.++// lookupFaultPool fails one named query and passes everything else through, so+// a single link in ResolveTaskWorkspaceIDChecked can be made to time out while+// the task row itself stays readable.+type lookupFaultPool struct {+ db.DBTX+ query string+ called bool+}++func (f *lookupFaultPool) QueryRow(ctx context.Context, query string, args ...any) pgx.Row {+ if strings.Contains(query, "-- name: "+f.query+" :one") {+ f.called = true+ return &mockRow{err: context.DeadlineExceeded}+ }+ return f.DBTX.QueryRow(ctx, query, args...)+}++// TestGetTaskStatus_WorkspaceLookupFailure_Returns500 covers every link kind the+// resolver walks. A timeout on any of them must be a 5xx the daemon retries, not+// a deletion it acts on.+func TestGetTaskStatus_WorkspaceLookupFailure_Returns500(t *testing.T) {+ ctx := context.Background()+ runtimeID := dbfx.Runtime(t, "MUL-7259 lookup runtime")+ agentID := dbfx.Agent(t, "MUL-7259 lookup agent", runtimeID)+ issueID := dbfx.Issue(t, "MUL-7259 lookup issue")+ chatID := dbfx.ChatSession(t, agentID)+ apID := dbfx.Insert(t, "autopilot", testutil.Cols{+ "workspace_id": testWorkspaceID, "title": "MUL-7259 lookup autopilot",+ "assignee_id": agentID, "status": "paused", "created_by_type": "member", "created_by_id": testUserID,+ })+ runID := dbfx.Insert(t, "autopilot_run", testutil.Cols{"autopilot_id": apID, "source": "manual", "status": "running"})++ for _, tc := range []struct{ query, column, id string }{+ {"GetIssue", "issue_id", issueID},+ {"GetChatSession", "chat_session_id", chatID},+ {"GetAutopilotRun", "autopilot_run_id", runID},+ {"GetAutopilot", "autopilot_run_id", runID},+ } {+ t.Run(tc.query, func(t *testing.T) {+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID, "status": "running", "started_at": testutil.Raw("now()"), tc.column: tc.id,+ })+ fault := &lookupFaultPool{DBTX: testPool, query: tc.query}+ h := &Handler{Queries: db.New(testPool), TaskService: &service.TaskService{Queries: db.New(fault)}}+ req := newDaemonTokenRequest(http.MethodGet, "/api/daemon/tasks/"+taskID+"/status", nil, testWorkspaceID, "test-daemon")+ req = withURLParam(req, "taskId", taskID)++ w := testutil.Call(t, h.GetTaskStatus, req).Want(http.StatusInternalServerError)+ if !fault.called {+ t.Fatal("fault was never exercised — the resolver did not reach the injected query")+ }+ // isTaskNotFoundError requires BOTH a 404 and this body, so the+ // 500 above is already enough to keep the daemon from+ // interrupting. The body is asserted too so the response never+ // carries the cancel-triggering string at all, should either half+ // of that check ever be relaxed.+ if strings.Contains(w.Body.String(), "task not found") {+ t.Fatalf("5xx body must not carry the daemon's cancel-triggering string: %s", w.Body.String())+ }++ task, err := testHandler.Queries.GetAgentTask(ctx, parseUUID(taskID))+ if err != nil || task.Status != "running" {+ t.Fatalf("task must be untouched and still running: status=%s err=%v", task.Status, err)+ }+ // Once the dependency recovers the identical request succeeds, so+ // the 5xx really was "ask again", not a masked permanent failure.+ testutil.Call(t, testHandler.GetTaskStatus, req).Want(http.StatusOK)+ })+ }+}++// TestGetTaskStatus_GenuinelyUnreachable_Returns404 is the other half of the+// contract: the 404 must survive for real absence, otherwise a deleted task+// would leave its agent running to its full timeout.+func TestGetTaskStatus_GenuinelyUnreachable_Returns404(t *testing.T) {+ runtimeID := dbfx.Runtime(t, "MUL-7259 absent runtime")+ agentID := dbfx.Agent(t, "MUL-7259 absent agent", runtimeID)++ t.Run("task row missing", func(t *testing.T) {+ missing := uuid.NewString()+ req := newDaemonTokenRequest(http.MethodGet, "/api/daemon/tasks/"+missing+"/status", nil, testWorkspaceID, "test-daemon")+ req = withURLParam(req, "taskId", missing)+ w := testutil.Call(t, testHandler.GetTaskStatus, req).Want(http.StatusNotFound)+ if !strings.Contains(w.Body.String(), "task not found") {+ t.Fatalf("a genuinely missing task must still interrupt the daemon: %s", w.Body.String())+ }+ })++ t.Run("link target missing", func(t *testing.T) {+ // agent_task_queue.issue_id is ON DELETE CASCADE, so an issue task can+ // never outlive its issue — that absence surfaces as ErrNoRows on the+ // task itself (covered above). chat_session_id is ON DELETE SET NULL,+ // so this is the shape where the resolver genuinely has nothing left to+ // resolve, and it must stay a 404 rather than becoming a 5xx the daemon+ // retries forever.+ chatID := dbfx.ChatSession(t, agentID)+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID, "status": "running",+ "started_at": testutil.Raw("now()"), "chat_session_id": chatID,+ })+ dbfx.Exec(t, "DELETE FROM chat_session WHERE id = $1", chatID)++ req := newDaemonTokenRequest(http.MethodGet, "/api/daemon/tasks/"+taskID+"/status", nil, testWorkspaceID, "test-daemon")+ req = withURLParam(req, "taskId", taskID)+ w := testutil.Call(t, testHandler.GetTaskStatus, req).Want(http.StatusNotFound)+ if !strings.Contains(w.Body.String(), "task not found") {+ t.Fatalf("a task whose only link is gone is unreachable: %s", w.Body.String())+ }+ })+}++// TestGetTaskStatus_ForeignWorkspace_Returns404 pins the permission boundary:+// splitting lookup failures out of the 404 must not turn a cross-workspace task+// into a distinguishable response. A foreign task and a missing one look alike.+func TestGetTaskStatus_ForeignWorkspace_Returns404(t *testing.T) {+ runtimeID := dbfx.Runtime(t, "MUL-7259 foreign runtime")+ agentID := dbfx.Agent(t, "MUL-7259 foreign agent", runtimeID)+ issueID := dbfx.Issue(t, "MUL-7259 foreign issue")+ taskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID, "issue_id": issueID,+ "status": "running", "started_at": testutil.Raw("now()"),+ })++ otherWorkspace := uuid.NewString()+ req := newDaemonTokenRequest(http.MethodGet, "/api/daemon/tasks/"+taskID+"/status", nil, otherWorkspace, "other-daemon")+ req = withURLParam(req, "taskId", taskID)+ testutil.Call(t, testHandler.GetTaskStatus, req).Want(http.StatusNotFound)+}++// TestResolveTaskWorkspaceIDChecked_SeparatesAbsenceFromFailure asserts the+// distinction at the service boundary, where the two callers now rely on it.+func TestResolveTaskWorkspaceIDChecked_SeparatesAbsenceFromFailure(t *testing.T) {+ ctx := context.Background()+ runtimeID := dbfx.Runtime(t, "MUL-7259 resolver runtime")+ agentID := dbfx.Agent(t, "MUL-7259 resolver agent", runtimeID)+ issueID := dbfx.Issue(t, "MUL-7259 resolver issue")++ t.Run("resolves", func(t *testing.T) {+ taskID := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "issue_id": issueID})+ task, err := testHandler.Queries.GetAgentTask(ctx, parseUUID(taskID))+ if err != nil {+ t.Fatal(err)+ }+ got, err := testHandler.TaskService.ResolveTaskWorkspaceIDChecked(ctx, task)+ if err != nil || got != testWorkspaceID {+ t.Fatalf("workspace=%q err=%v, want %q / nil", got, err, testWorkspaceID)+ }+ })++ t.Run("absent link is not an error", func(t *testing.T) {+ chatID := dbfx.ChatSession(t, agentID)+ taskID := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "chat_session_id": chatID})+ dbfx.Exec(t, "DELETE FROM chat_session WHERE id = $1", chatID)+ task, err := testHandler.Queries.GetAgentTask(ctx, parseUUID(taskID))+ if err != nil {+ t.Fatal(err)+ }+ got, err := testHandler.TaskService.ResolveTaskWorkspaceIDChecked(ctx, task)+ if got != "" || err != nil {+ t.Fatalf("workspace=%q err=%v, want \"\" / nil", got, err)+ }+ })++ t.Run("failed lookup is an error", func(t *testing.T) {+ taskID := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "issue_id": issueID})+ task, err := testHandler.Queries.GetAgentTask(ctx, parseUUID(taskID))+ if err != nil {+ t.Fatal(err)+ }+ svc := &service.TaskService{Queries: db.New(&lookupFaultPool{DBTX: testPool, query: "GetIssue"})}+ got, err := svc.ResolveTaskWorkspaceIDChecked(ctx, task)+ if got != "" || err == nil {+ t.Fatalf("workspace=%q err=%v, want \"\" / error", got, err)+ }+ // The best-effort wrapper keeps flattening both cases to "" — broadcast+ // callers depend on that and must not start panicking on a blip.+ if ws := svc.ResolveTaskWorkspaceID(ctx, task); ws != "" {+ t.Fatalf("best-effort resolver should still return \"\", got %q", ws)+ }+ })+}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex e6612c535c..a94eadeb7a 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -7004,27 +7004,74 @@ func (s *TaskService) broadcastTaskFailedEvent(ctx context.Context, task db.Agens.publishTaskFailedEvent(workspaceID, task, errMsg, failureReason, retryPending)}-// ResolveTaskWorkspaceID determines the workspace ID for a task.-// For issue tasks, it comes from the issue. For chat tasks, from the chat session.-// For autopilot tasks, from the autopilot via its run.-// Returns "" when none of the links resolve — callers treat that as "not found".+// ResolveTaskWorkspaceID determines the workspace ID for a task, best-effort.+// Returns "" when the workspace could not be determined, whether because the+// link target is genuinely gone or because a lookup failed.+//+// Use this only where "" is an acceptable answer — event broadcasts skip+// themselves rather than fabricating a workspace. Anything that turns the+// result into an HTTP status MUST use ResolveTaskWorkspaceIDChecked instead:+// collapsing both cases to "" is what let a transient DB error be reported to+// the daemon as `404 task not found`, which it acts on by killing a healthy+// run (MUL-7259 / GH #8272).func (s *TaskService) ResolveTaskWorkspaceID(ctx context.Context, task db.AgentTaskQueue) string {+ workspaceID, _ := s.ResolveTaskWorkspaceIDChecked(ctx, task)+ return workspaceID+}++// ResolveTaskWorkspaceIDChecked resolves a task's workspace and keeps the two+// failure modes apart:+//+// - ("", nil) — every link this task carries was looked up successfully and+// the target is genuinely absent. The task is unreachable; a 404 is honest.+// - ("", err) — a lookup could not be completed (DB timeout, pool exhaustion,+// …). We do not know whether the task is reachable, and the caller must NOT+// report absence. This is a 5xx.+//+// For issue tasks the workspace comes from the issue, for chat tasks from the+// chat session, for autopilot tasks from the autopilot via its run, and for+// quick-create tasks from the context JSONB (they carry no link at all).+//+// A failed lookup does not stop the walk. If a later link resolves, its+// workspace is returned and the earlier error is dropped, because that answer+// is still trustworthy; the error is surfaced only when nothing resolved. That+// keeps a task carrying several links working during a partial outage while+// still refusing to call an unknown state "not found".+func (s *TaskService) ResolveTaskWorkspaceIDChecked(ctx context.Context, task db.AgentTaskQueue) (string, error) {+ // isNotFound is the "genuinely absent" signal; every other error means the+ // lookup itself did not complete. pgx.ErrNoRows is the only error the+ // queries below use to say "this row does not exist".+ var lookupErr error+ note := func(err error) {+ if err != nil && !errors.Is(err, pgx.ErrNoRows) && lookupErr == nil {+ lookupErr = err+ }+ }+if task.IssueID.Valid {- if issue, err := s.Queries.GetIssue(ctx, task.IssueID); err == nil {- return util.UUIDToString(issue.WorkspaceID)+ issue, err := s.Queries.GetIssue(ctx, task.IssueID)+ if err == nil {+ return util.UUIDToString(issue.WorkspaceID), nil}+ note(err)}if task.ChatSessionID.Valid {- if cs, err := s.Queries.GetChatSession(ctx, task.ChatSessionID); err == nil {- return util.UUIDToString(cs.WorkspaceID)+ cs, err := s.Queries.GetChatSession(ctx, task.ChatSessionID)+ if err == nil {+ return util.UUIDToString(cs.WorkspaceID), nil}+ note(err)}if task.AutopilotRunID.Valid {- if run, err := s.Queries.GetAutopilotRun(ctx, task.AutopilotRunID); err == nil {- if ap, err := s.Queries.GetAutopilot(ctx, run.AutopilotID); err == nil {- return util.UUIDToString(ap.WorkspaceID)+ run, err := s.Queries.GetAutopilotRun(ctx, task.AutopilotRunID)+ if err == nil {+ ap, apErr := s.Queries.GetAutopilot(ctx, run.AutopilotID)+ if apErr == nil {+ return util.UUIDToString(ap.WorkspaceID), nil}+ note(apErr)}+ note(err)}// Quick-create tasks have no issue / chat / autopilot link — workspace// lives in the context JSONB. Returning "" here is what blocked@@ -7032,9 +7079,12 @@ func (s *TaskService) ResolveTaskWorkspaceID(ctx context.Context, task db.AgentT// for the daemon) and silently dropped task:dispatch / task:completed// broadcasts, which is why quick-create tasks appeared stuck queued.if qc, ok := s.parseQuickCreateContext(task); ok {- return qc.WorkspaceID+ return qc.WorkspaceID, nil}- return ""+ if lookupErr != nil {+ return "", fmt.Errorf("resolve task workspace: %w", lookupErr)+ }+ return "", nil}func (s *TaskService) broadcastChatDone(ctx context.Context, task db.AgentTaskQueue, msg *db.ChatMessage, quickActionsPending bool) {