Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(server): MUL-7364 decide issue GC and recovery prefilter on lifecycle category (#8405)

Bohan Jiang1b3137a00d61
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index c57e806ccf..1db5db8611 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -772,8 +772,14 @@ func (c *Client) usesLegacyWorkspaceEndpoint() bool {
}
// IssueGCStatus holds the minimal issue info returned by the GC check endpoint.
+//
+// Category is the issue's lifecycle (unstarted/started/done/closed) and is what
+// GC decides on. Status is the legacy seven-value enum, still populated by the
+// server for installed daemons and used here only when Category is absent —
+// a server predating MUL-7364 — or unrecognized. See issueGCLifecycle in gc.go.
type IssueGCStatus struct {
Status string `json:"status"`
+ Category string `json:"category,omitempty"`
UpdatedAt time.Time `json:"updated_at"`
}
@@ -785,6 +791,7 @@ type IssueGCCheckResult struct {
ID string `json:"id"`
Found bool `json:"found"`
Status string `json:"status,omitempty"`
+ Category string `json:"category,omitempty"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
Err error `json:"-"`
}
@@ -853,6 +860,7 @@ func (c *Client) getLegacyIssueGCChecks(ctx context.Context, issueIDs []string)
ID: issueID,
Found: true,
Status: status.Status,
+ Category: status.Category,
UpdatedAt: status.UpdatedAt,
}
}
diff --git a/server/internal/daemon/gc.go b/server/internal/daemon/gc.go
index d7c05e88ca..135bfa3b7a 100644
--- a/server/internal/daemon/gc.go
+++ b/server/internal/daemon/gc.go
@@ -15,6 +15,7 @@ import (
"github.com/multica-ai/multica/server/internal/daemon/execenv"
"github.com/multica-ai/multica/server/internal/daemon/processtree"
"github.com/multica-ai/multica/server/internal/daemon/repocache"
+ "github.com/multica-ai/multica/server/internal/issuestatus"
)
// reposDirName is the bare-repo cache directory inside the workspaces root.
@@ -572,6 +573,7 @@ func (d *Daemon) gcDecisionIssue(ctx context.Context, taskDir string, meta *exec
ID: meta.IssueID,
Found: true,
Status: status.Status,
+ Category: status.Category,
UpdatedAt: status.UpdatedAt,
})
}
@@ -581,11 +583,9 @@ func (d *Daemon) gcDecisionIssueResult(taskDir string, meta *execenv.GCMeta, res
return d.orphanByMTime(taskDir, "issue not accessible")
}
- // result.Status is a CATEGORY, normalized server-side, so this literal
- // comparison covers custom statuses too — an issue on a `done`-category
- // custom status is terminal here. (MUL-6243)
- if (result.Status == "done" || result.Status == "cancelled") &&
- time.Since(result.UpdatedAt) > d.cfg.GCTTL {
+ terminal, recognized := issueGCLifecycle(result)
+
+ if terminal && time.Since(result.UpdatedAt) > d.cfg.GCTTL {
d.logger.Info("gc: eligible for cleanup",
"dir", filepath.Base(taskDir),
"kind", "issue",
@@ -607,7 +607,7 @@ func (d *Daemon) gcDecisionIssueResult(taskDir string, meta *execenv.GCMeta, res
if d.cfg.GCCompletedTaskTTL > 0 &&
!meta.LocalDirectory &&
!meta.CompletedAt.IsZero() &&
- isKnownIssueStatus(result.Status) &&
+ recognized &&
time.Since(meta.CompletedAt) > d.cfg.GCCompletedTaskTTL {
d.logger.Info("gc: completed task eligible for full cleanup",
"dir", filepath.Base(taskDir),
@@ -652,17 +652,39 @@ func (d *Daemon) gcDecisionIssueResult(taskDir string, meta *execenv.GCMeta, res
return gcActionSkip
}
-// isKnownIssueStatus mirrors the issue status constraint enforced by the
-// server. Full task cleanup must fail closed when an older daemon receives a
-// future status or a malformed response from the GC check endpoint.
+// issueGCLifecycle answers the only two questions GC asks about a parent issue:
+// is it terminal, and was the answer well-formed? Everything else about a
+// status — parked, in review, blocked — is execution policy the daemon has no
+// business reading.
+//
+// `category` is the real answer and wins whenever it is one of the four: those
+// values cover a workspace's custom statuses too, so a `closed`-category custom
+// status is terminal here without this binary knowing the key exists.
+//
+// A missing or unrecognized category — a server predating MUL-7364, a
+// malformed response, a lifecycle value newer than this daemon — falls back to
+// the legacy seven-value `status` enum, which the server keeps populated for
+// exactly this reason and which fails closed on its own. Full cleanup is
+// irreversible, so a lookup that did not really answer must not read as one.
+func issueGCLifecycle(result IssueGCCheckResult) (terminal, recognized bool) {
+ if issuestatus.IsCategory(result.Category) {
+ return result.Category == issuestatus.CategoryDone || result.Category == issuestatus.CategoryClosed, true
+ }
+ return result.Status == issuestatus.Done || result.Status == issuestatus.Cancelled,
+ isKnownIssueStatus(result.Status)
+}
+
+// isKnownIssueStatus is the pre-MUL-7364 fallback vocabulary: the seven
+// built-in status keys, which is all the `status` field of a gc-check response
+// may ever contain.
//
-// The 7 names below stay correct after custom statuses (MUL-6243) because the
-// gc-check endpoints answer with the status's CATEGORY, not the stored key —
-// see BatchIssueGCCheck / GetIssueGCCheck, which resolve through
-// issuestatus.Effective. Do not teach this function about custom statuses: an
-// installed daemon has no catalog to resolve them against, and daemons
-// predating the feature must keep making correct decisions against an upgraded
-// server. Pinned by TestIssueGCChecksReportCategoryNotRawCustomStatus.
+// Do not teach it about custom statuses or about the four lifecycle categories.
+// An installed daemon has no catalog to resolve a custom key against, so the
+// server projects every status back onto these seven for this field
+// (issueGCWire in handler/daemon.go) precisely so daemons predating custom
+// statuses keep making correct decisions against an upgraded server. A daemon
+// that wants the lifecycle reads `category` instead — see issueGCLifecycle.
+// Pinned by TestIssueGCChecksReportWireStatusNotRawCustomStatus.
func isKnownIssueStatus(status string) bool {
switch status {
case "backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled":
diff --git a/server/internal/daemon/gc_test.go b/server/internal/daemon/gc_test.go
index 4f13f7062d..8e90b38c0a 100644
--- a/server/internal/daemon/gc_test.go
+++ b/server/internal/daemon/gc_test.go
@@ -1063,6 +1063,110 @@ func TestShouldCleanTaskDir_CompletedTaskTTLUnknownIssueStatusFailsClosed(t *tes
}
}
+// MUL-7240 collapsed issue_status.category to four values and stopped
+// projecting nonterminal custom statuses onto a built-in key, so the gc-check
+// response started carrying keys this binary has never heard of. The full
+// cleanup path required a status it recognized, which silently turned that path
+// off for any workspace using a custom status — environment skeletons pile up
+// for as long as the parent issue sits there. Deciding on the lifecycle
+// category instead keeps it alive without teaching the daemon about custom
+// keys. (MUL-7364)
+func TestShouldCleanTaskDir_CompletedTaskTTLAcceptsCustomStatusByCategory(t *testing.T) {
+ t.Parallel()
+ issueID := "88888888-8888-8888-8888-88888888886a"
+
+ mux := http.NewServeMux()
+ mux.HandleFunc(fmt.Sprintf("/api/daemon/issues/%s/gc-check", issueID), func(w http.ResponseWriter, r *http.Request) {
+ json.NewEncoder(w).Encode(map[string]any{
+ "status": "human_review", "category": "started", "updated_at": time.Now(),
+ })
+ })
+
+ d := newGCTestDaemon(t, mux)
+ d.cfg.GCCompletedTaskTTL = time.Hour
+ // Artifact cleanup does not consult the status at all, so switching it off
+ // leaves the full-cleanup decision as the only thing this can measure.
+ d.cfg.GCArtifactTTL = 0
+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "completed-custom-status", &execenv.GCMeta{
+ Kind: execenv.GCKindIssue,
+ IssueID: issueID,
+ WorkspaceID: "ws1",
+ CompletedAt: time.Now().Add(-2 * time.Hour),
+ })
+
+ if action := d.shouldCleanTaskDir(context.Background(), taskDir); action != gcActionClean {
+ t.Fatalf("expected full cleanup for a started-category custom status, got %d", action)
+ }
+}
+
+// A category the daemon does not recognize is not an answer. It falls back to
+// the legacy status enum, which fails closed on a raw custom key — data is kept
+// rather than deleted on a response this binary cannot read. (MUL-7364)
+func TestShouldCleanTaskDir_CompletedTaskTTLUnknownCategoryFallsBackAndFailsClosed(t *testing.T) {
+ t.Parallel()
+ issueID := "88888888-8888-8888-8888-88888888886b"
+
+ mux := http.NewServeMux()
+ mux.HandleFunc(fmt.Sprintf("/api/daemon/issues/%s/gc-check", issueID), func(w http.ResponseWriter, r *http.Request) {
+ json.NewEncoder(w).Encode(map[string]any{
+ "status": "human_review", "category": "lifecycle_from_the_future", "updated_at": time.Now(),
+ })
+ })
+
+ d := newGCTestDaemon(t, mux)
+ d.cfg.GCCompletedTaskTTL = time.Hour
+ d.cfg.GCArtifactTTL = 0
+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "completed-unknown-category", &execenv.GCMeta{
+ Kind: execenv.GCKindIssue,
+ IssueID: issueID,
+ WorkspaceID: "ws1",
+ CompletedAt: time.Now().Add(-2 * time.Hour),
+ })
+
+ if action := d.shouldCleanTaskDir(context.Background(), taskDir); action != gcActionSkip {
+ t.Fatalf("expected unknown category to fail closed, got %d", action)
+ }
+}
+
+// Terminality is a category question too: `closed` covers Cancelled and every
+// custom status a workspace parks cancelled work on, and neither key is
+// something this binary can enumerate. (MUL-7364)
+func TestShouldCleanTaskDir_TerminalCategoryReclaimsWorkdir(t *testing.T) {
+ t.Parallel()
+ for _, tc := range []struct {
+ name string
+ status string
+ category string
+ }{
+ {"custom done-category status", "gate_approved", "done"},
+ {"custom closed-category status", "wont_fix", "closed"},
+ {"built-in cancelled", "cancelled", "closed"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ issueID := "88888888-8888-8888-8888-88888888886c"
+
+ mux := http.NewServeMux()
+ mux.HandleFunc(fmt.Sprintf("/api/daemon/issues/%s/gc-check", issueID), func(w http.ResponseWriter, r *http.Request) {
+ json.NewEncoder(w).Encode(map[string]any{
+ "status": tc.status, "category": tc.category,
+ "updated_at": time.Now().Add(-30 * 24 * time.Hour),
+ })
+ })
+
+ d := newGCTestDaemon(t, mux)
+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "terminal-category", &execenv.GCMeta{
+ Kind: execenv.GCKindIssue, IssueID: issueID, WorkspaceID: "ws1",
+ CompletedAt: time.Now().Add(-30 * 24 * time.Hour),
+ })
+
+ if action := d.shouldCleanTaskDir(context.Background(), taskDir); action != gcActionClean {
+ t.Fatalf("expected terminal category to reclaim the workdir, got %d", action)
+ }
+ })
+ }
+}
+
func TestShouldCleanTaskDir_CompletedTaskTTLRequiresCompletionTime(t *testing.T) {
t.Parallel()
issueID := "88888888-8888-8888-8888-888888888881"
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 9e5a0ceb83..479f0f27a6 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -5542,9 +5542,33 @@ type batchIssueGCCheckItem struct {
ID string `json:"id"`
Found bool `json:"found"`
Status string `json:"status,omitempty"`
+ Category string `json:"category,omitempty"`
UpdatedAt *time.Time `json:"updated_at,omitempty"`
}
+// issueGCWire encodes an issue's lifecycle for both GC check endpoints: the
+// four-value `category` a current daemon decides on, and the legacy
+// seven-value `status` enum installed daemons still match literally.
+//
+// `status` predates custom statuses — the daemon tests it against the 7
+// built-in keys and fails closed on anything else (isKnownIssueStatus in
+// daemon/gc.go) — so the stored key cannot be handed back raw. A nonterminal
+// custom key silently disables the GCCompletedTaskTTL full-cleanup path, and a
+// four-value category is not in that vocabulary either. GC consumes exactly one
+// lifecycle fact ("is this issue terminal?"), which is why projecting a custom
+// status onto a built-in key here grants it no built-in behavior anywhere else.
+//
+// A status with no lifecycle category — an unresolvable key after a failed
+// catalog read or a status created since the resolver's snapshot, and Triage,
+// which is deliberately outside the four — is returned raw with no category, so
+// every daemon fails closed and reclaims artifacts only. (MUL-7364)
+func issueGCWire(status, category string) (wireStatus, wireCategory string) {
+ if !issuestatus.IsCategory(category) {
+ return status, ""
+ }
+ return issuestatus.WireCategory(status, category), category
+}
+
// BatchIssueGCCheck returns one explicit result for every requested issue ID.
// The query is workspace-scoped at the SQL layer; missing rows and IDs owned by
// another workspace both become found=false so the endpoint is not an
@@ -5600,8 +5624,8 @@ func (h *Handler) BatchIssueGCCheck(w http.ResponseWriter, r *http.Request) {
}
// ONE resolver for the whole batch, not a point lookup per row. The
- // package-level Effective issues a GetIssueStatusEntryByKey for every custom
- // key it sees, so resolving inside this loop cost up to maxIssueGCBatchSize
+ // package-level helpers issue a GetIssueStatusEntryByKey for every custom
+ // key they see, so resolving inside this loop cost up to maxIssueGCBatchSize
// catalog queries per request — on an endpoint whose entire purpose is to
// replace per-issue requests, and which every installed daemon runs on a
// timer. The resolver reads the catalog lazily and at most once, so an
@@ -5614,10 +5638,11 @@ func (h *Handler) BatchIssueGCCheck(w http.ResponseWriter, r *http.Request) {
if found {
// The daemon consumes this purely as a machine signal ("is this
// issue terminal, so its workdir can be reclaimed?") and has no
- // database of its own, so the canonical status is resolved here.
+ // database of its own, so the lifecycle is resolved here.
// Normalizing server-side also means daemons that predate custom
// statuses keep making correct GC decisions. (MUL-6243)
- item.Status = resolver.Effective(r.Context(), h.issueStatusCatalog(), row.Status)
+ item.Status, item.Category = issueGCWire(row.Status,
+ resolver.Category(r.Context(), h.issueStatusCatalog(), row.Status))
updatedAt := row.UpdatedAt.Time
item.UpdatedAt = &updatedAt
}
@@ -5643,10 +5668,13 @@ func (h *Handler) GetIssueGCCheck(w http.ResponseWriter, r *http.Request) {
if !h.requireDaemonWorkspaceAccess(w, r, uuidToString(issue.WorkspaceID)) {
return
}
+ // Same reasoning as BatchIssueGCCheck: normalize server-side so the
+ // daemon's terminal-status test stays correct. (MUL-6243)
+ status, category := issueGCWire(issue.Status,
+ issuestatus.Category(r.Context(), h.issueStatusCatalog(), issue.WorkspaceID, issue.Status))
writeJSON(w, http.StatusOK, map[string]any{
- // Same reasoning as BatchIssueGCCheck: normalize server-side so the
- // daemon's terminal-status test stays correct. (MUL-6243)
- "status": issuestatus.Effective(r.Context(), h.issueStatusCatalog(), issue.WorkspaceID, issue.Status),
+ "status": status,
+ "category": category,
"updated_at": issue.UpdatedAt.Time,
})
}
diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.go
index ee7abc9230..937deaa629 100644
--- a/server/internal/handler/daemon_test.go
+++ b/server/internal/handler/daemon_test.go
@@ -4507,21 +4507,22 @@ func TestAckTaskCancelled(t *testing.T) {
}
}
-// The daemon GC decides whether a task workdir can be reclaimed by testing the
-// issue status against the terminal set — `gc.go:509` compares it to
-// "done"/"cancelled", and `isKnownIssueStatus` is a hardcoded switch over the 7
-// built-ins. Neither knows custom statuses exist, and it must stay that way: an
-// installed daemon has no database, and daemons predating MUL-6243 keep running
-// against upgraded servers.
+// The daemon GC decides whether a task workdir can be reclaimed from two fields
+// of the gc-check response, and the SERVER owns what goes in both.
//
-// So the normalization is the SERVER's job. Both gc-check endpoints resolve the
-// stored key to its category before answering. Without that:
+// - `category` is the real answer: the four-value lifecycle a current daemon
+// tests for terminality (issueGCLifecycle in daemon/gc.go).
+// - `status` is the legacy seven-value enum. Installed daemons match it
+// literally against the built-ins and fail closed on anything else, so a
+// custom status has to be projected back onto that vocabulary here.
+//
+// Handing back the raw stored key instead breaks both kinds of daemon:
//
// - an issue parked on a `done`-category custom status is never terminal, so
// its workdir is retained forever, and
// - `isKnownIssueStatus` rejects the raw key, silently disabling the
-// GCCompletedTaskTTL full-cleanup path for that issue.
-func TestIssueGCChecksReportCategoryNotRawCustomStatus(t *testing.T) {
+// GCCompletedTaskTTL full-cleanup path for that issue (MUL-7364).
+func TestIssueGCChecksReportWireStatusNotRawCustomStatus(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
}
@@ -4537,6 +4538,20 @@ func TestIssueGCChecksReportCategoryNotRawCustomStatus(t *testing.T) {
"status": humanReview.Key, "priority": "medium", "number": 92502,
})
+ // An installed daemon rejects anything outside the 7 built-in keys, so a
+ // status it cannot recognize disables full cleanup however correct it looks.
+ wantLegacyEnum := func(t *testing.T, status string) {
+ t.Helper()
+ for _, key := range issuestatus.Canonical() {
+ if status == key {
+ return
+ }
+ }
+ t.Errorf("status %q is outside the legacy seven-value enum — isKnownIssueStatus rejects it, silently disabling the GCCompletedTaskTTL full-cleanup path", status)
+ }
+
+ type wire struct{ status, category string }
+
t.Run("batch endpoint", func(t *testing.T) {
req := newDaemonTokenRequest("POST", "/api/daemon/workspaces/"+testWorkspaceID+"/issues/gc-check",
map[string]any{"issue_ids": []string{doneID, openID}}, testWorkspaceID, "legit-daemon")
@@ -4544,44 +4559,56 @@ func TestIssueGCChecksReportCategoryNotRawCustomStatus(t *testing.T) {
var resp struct {
Issues []struct {
- ID string `json:"id"`
- Found bool `json:"found"`
- Status string `json:"status"`
+ ID string `json:"id"`
+ Found bool `json:"found"`
+ Status string `json:"status"`
+ Category string `json:"category"`
} `json:"issues"`
}
testutil.Call(t, testHandler.BatchIssueGCCheck, req).Want(http.StatusOK).JSON(&resp)
- byID := map[string]string{}
+ byID := map[string]wire{}
for _, issue := range resp.Issues {
if !issue.Found {
t.Fatalf("issue %s not found", issue.ID)
}
- byID[issue.ID] = issue.Status
+ wantLegacyEnum(t, issue.Status)
+ byID[issue.ID] = wire{issue.Status, issue.Category}
}
- // The category, never the stored key — the daemon's terminal test is a
- // literal string comparison and has no way to resolve one.
- if byID[doneID] != issuestatus.Done {
- t.Errorf("done-category custom status reported as %q, want %q — the daemon would keep this workdir forever",
- byID[doneID], issuestatus.Done)
+ if got, want := byID[doneID], (wire{issuestatus.Done, issuestatus.CategoryDone}); got != want {
+ t.Errorf("done-category custom status reported as %+v, want %+v — the daemon would keep this workdir forever", got, want)
}
- if byID[openID] != "gc_human_review" {
- t.Errorf("nonterminal custom status reported as %q, want gc_human_review", byID[openID])
+ if got, want := byID[openID], (wire{issuestatus.InProgress, issuestatus.CategoryStarted}); got != want {
+ t.Errorf("nonterminal custom status reported as %+v, want %+v", got, want)
}
})
// The per-issue endpoint is the fallback older daemons still call, so it
// carries the same obligation.
t.Run("legacy per-issue endpoint", func(t *testing.T) {
- req := newDaemonTokenRequest("GET", "/api/daemon/issues/"+doneID+"/gc-check", nil, testWorkspaceID, "legit-daemon")
- req = withURLParam(req, "issueId", doneID)
-
- var resp struct {
- Status string `json:"status"`
- }
- testutil.Call(t, testHandler.GetIssueGCCheck, req).Want(http.StatusOK).JSON(&resp)
-
- if resp.Status != issuestatus.Done {
- t.Errorf("status = %q, want %q", resp.Status, issuestatus.Done)
+ for _, tc := range []struct {
+ name string
+ issueID string
+ want wire
+ }{
+ {"terminal custom status", doneID, wire{issuestatus.Done, issuestatus.CategoryDone}},
+ {"nonterminal custom status", openID, wire{issuestatus.InProgress, issuestatus.CategoryStarted}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ req := newDaemonTokenRequest("GET", "/api/daemon/issues/"+tc.issueID+"/gc-check", nil, testWorkspaceID, "legit-daemon")
+ req = withURLParam(req, "issueId", tc.issueID)
+
+ var resp struct {
+ Status string `json:"status"`
+ Category string `json:"category"`
+ }
+ testutil.Call(t, testHandler.GetIssueGCCheck, req).Want(http.StatusOK).JSON(&resp)
+
+ wantLegacyEnum(t, resp.Status)
+ if got := (wire{resp.Status, resp.Category}); got != tc.want {
+ t.Errorf("status/category = %+v, want %+v", got, tc.want)
+ }
+ })
}
})
}
@@ -4620,9 +4647,10 @@ func TestBatchIssueGCCheckReadsCatalogOnceForManyCustomStatuses(t *testing.T) {
var resp struct {
Issues []struct {
- ID string `json:"id"`
- Found bool `json:"found"`
- Status string `json:"status"`
+ ID string `json:"id"`
+ Found bool `json:"found"`
+ Status string `json:"status"`
+ Category string `json:"category"`
} `json:"issues"`
}
testutil.Call(t, testHandler.BatchIssueGCCheck, req).Want(http.StatusOK).JSON(&resp)
@@ -4631,16 +4659,16 @@ func TestBatchIssueGCCheckReadsCatalogOnceForManyCustomStatuses(t *testing.T) {
// also score zero on the counters below.
byID := map[string]string{}
for _, issue := range resp.Issues {
- byID[issue.ID] = issue.Status
+ byID[issue.ID] = issue.Status + "/" + issue.Category
}
for _, id := range ids[:2] {
- if byID[id] != issuestatus.Done {
- t.Fatalf("issue %s reported %q, want %q", id, byID[id], issuestatus.Done)
+ if want := issuestatus.Done + "/" + issuestatus.CategoryDone; byID[id] != want {
+ t.Fatalf("issue %s reported %q, want %q", id, byID[id], want)
}
}
for _, id := range ids[2:4] {
- if byID[id] != "gc_batch_review" {
- t.Fatalf("issue %s reported %q, want gc_batch_review", id, byID[id])
+ if want := issuestatus.InProgress + "/" + issuestatus.CategoryStarted; byID[id] != want {
+ t.Fatalf("issue %s reported %q, want %q", id, byID[id], want)
}
}
diff --git a/server/internal/service/delegated_failure_recovery_test.go b/server/internal/service/delegated_failure_recovery_test.go
index 92179e7dac..55bbedbd0e 100644
--- a/server/internal/service/delegated_failure_recovery_test.go
+++ b/server/internal/service/delegated_failure_recovery_test.go
@@ -302,6 +302,106 @@ func TestPendingDelegatedFailureSweepSkipsCustomTerminalSourceIssue(t *testing.T
}
}
+// The SQL prefilter is what keeps the recovery outbox scan from growing with
+// history. A signal whose source issue can never resume has to be dropped
+// THERE: the Go gate downstream discards it without stamping
+// recovery_settled_at, so anything that reaches Go stays in the scan forever
+// and spends part of maxPerTick on every tick.
+//
+// MUL-7240 disabled most of it silently. The predicate read
+// issue_status.category but compared it against the old seven-value key
+// vocabulary, and once a workspace's catalog is seeded — every production
+// workspace, per migration 469 — COALESCE returns that category: 'cancelled'
+// arrives as 'closed' and 'backlog' as 'unstarted', leaving only 'done' still
+// excluded. An unseeded workspace falls back to the raw key, so both are
+// covered here: the two vocabularies are each only reachable in one of them.
+// (MUL-7364)
+func TestPendingDelegatedFailureSweepPrefiltersUnresumableSourceIssues(t *testing.T) {
+ ctx := context.Background()
+ for _, catalog := range []struct {
+ name string
+ seeded bool
+ }{
+ {"seeded catalog", true},
+ {"unseeded catalog", false},
+ } {
+ t.Run(catalog.name, func(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ // status the source issue ends up on. customCategory, when set,
+ // makes it a custom key created with that lifecycle first.
+ status string
+ customCategory string
+ wantScanned bool
+ }{
+ {name: "built-in cancelled", status: "cancelled"},
+ {name: "built-in backlog", status: "backlog"},
+ {name: "built-in done", status: "done"},
+ {name: "custom closed-category status", status: "shelved", customCategory: "closed"},
+ {name: "source issue still live", status: "in_progress", wantScanned: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ f, svc := seedDelegatedFailureFixture(t)
+ workspaceUUID, err := util.ParseUUID(f.workspaceID)
+ if err != nil {
+ t.Fatalf("parse workspace id: %v", err)
+ }
+ if catalog.seeded {
+ if err := svc.Queries.SeedIssueStatusEntries(ctx, workspaceUUID); err != nil {
+ t.Fatalf("seed status catalog: %v", err)
+ }
+ }
+ if tc.customCategory != "" {
+ if _, err := f.pool.Exec(ctx, `
+ INSERT INTO issue_status (
+ workspace_id, key, name, description, category, color, is_system, position
+ ) VALUES ($1, $2, 'Shelved', '', $3, '#6b7280', false, 1)`,
+ f.workspaceID, tc.status, tc.customCategory); err != nil {
+ t.Fatalf("insert custom status: %v", err)
+ }
+ }
+
+ failedID := f.insertWorkerTask(t, "failed", "comment", 1, 2)
+ if _, err := f.pool.Exec(ctx, `
+ UPDATE agent_task_queue
+ SET failure_reason = 'agent_error.process_failure', error = 'worker exited', completed_at = now()
+ WHERE id = $1`, failedID); err != nil {
+ t.Fatalf("stamp failed task: %v", err)
+ }
+ // The signal has to exist before the source issue moves:
+ // creating it runs the same Go gate being bypassed here.
+ target, created, err := svc.ensureDelegatedFailureRecoveryComment(ctx, failedID)
+ if err != nil || target == nil || !created {
+ t.Fatalf("ensure recovery comment = target %v created %v err %v", target != nil, created, err)
+ }
+ if _, err := f.pool.Exec(ctx, `UPDATE issue SET status = $2 WHERE id = $1`, f.issueID, tc.status); err != nil {
+ t.Fatalf("move source issue to %q: %v", tc.status, err)
+ }
+
+ // Asserted against this fixture's own signal rather than the
+ // sweep's totals: the scan is not workspace-scoped.
+ pending, err := svc.Queries.ListPendingDelegatedFailureRecoveries(ctx, 1000)
+ if err != nil {
+ t.Fatalf("list pending recoveries: %v", err)
+ }
+ scanned := false
+ for _, comment := range pending {
+ if comment.ID == target.comment.ID {
+ scanned = true
+ break
+ }
+ }
+ if scanned != tc.wantScanned {
+ t.Fatalf("recovery signal scanned = %v, want %v — a source issue on %q %s",
+ scanned, tc.wantScanned, tc.status,
+ map[bool]string{true: "must stay in the outbox scan", false: "can never resume, so the row is rescanned and re-discarded forever"}[tc.wantScanned])
+ }
+ })
+ }
+ })
+ }
+}
+
func TestPendingDelegatedFailureSweepRequeuesTerminalUndeliveredTask(t *testing.T) {
for _, terminalStatus := range []string{"failed", "cancelled"} {
t.Run(terminalStatus, func(t *testing.T) {
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 9be8361030..cd2cae8394 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -5728,7 +5728,16 @@ WHERE recovery.author_type = 'system'
AND source.autopilot_run_id IS NULL
AND source.issue_id IS NOT NULL
AND source.agent_id <> failed.agent_id
- AND COALESCE(source_status.category, source_issue.status) NOT IN ('done', 'cancelled', 'backlog')
+ -- The source issue must still be live -- the same gate the Go side applies in
+ -- loadDelegatedFailureRecoveryTarget. Two vocabularies, on purpose: status
+ -- holds the built-in keys and is the only signal a workspace whose catalog
+ -- was never seeded has, while category is the four-value lifecycle a custom
+ -- status carries. One coalesced comparison cannot cover both -- since
+ -- MUL-7240 a seeded built-in coalesces to its category, so 'cancelled' and
+ -- 'backlog' stopped matching at all. 'backlog' stays a key test: parking is
+ -- built-in behavior a custom unstarted status does not inherit. (MUL-7364)
+ AND source_issue.status NOT IN ('done', 'cancelled', 'backlog')
+ AND COALESCE(source_status.category, '') NOT IN ('done', 'closed')
AND source_agent.archived_at IS NULL
AND source_agent.runtime_id IS NOT NULL
AND source_agent.workspace_id = source_issue.workspace_id
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 2ff6594ece..2af1f0cafa 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -2124,7 +2124,16 @@ WHERE recovery.author_type = 'system'
AND source.autopilot_run_id IS NULL
AND source.issue_id IS NOT NULL
AND source.agent_id <> failed.agent_id
- AND COALESCE(source_status.category, source_issue.status) NOT IN ('done', 'cancelled', 'backlog')
+ -- The source issue must still be live -- the same gate the Go side applies in
+ -- loadDelegatedFailureRecoveryTarget. Two vocabularies, on purpose: status
+ -- holds the built-in keys and is the only signal a workspace whose catalog
+ -- was never seeded has, while category is the four-value lifecycle a custom
+ -- status carries. One coalesced comparison cannot cover both -- since
+ -- MUL-7240 a seeded built-in coalesces to its category, so 'cancelled' and
+ -- 'backlog' stopped matching at all. 'backlog' stays a key test: parking is
+ -- built-in behavior a custom unstarted status does not inherit. (MUL-7364)
+ AND source_issue.status NOT IN ('done', 'cancelled', 'backlog')
+ AND COALESCE(source_status.category, '') NOT IN ('done', 'closed')
AND source_agent.archived_at IS NULL
AND source_agent.runtime_id IS NOT NULL
AND source_agent.workspace_id = source_issue.workspace_id