Skip to content

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

Go

revert(server): withdraw the reserved triage status key (#8450)

Bohan Jiangc7f259c70a60
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.md
index 16f6d7b475..b5cf40e00a 100644
--- a/CLI_AND_DAEMON.md
+++ b/CLI_AND_DAEMON.md
@@ -601,7 +601,7 @@ multica issue status <id> in_progress
Built-in statuses: `backlog`, `todo`, `in_progress`, `in_review`, `done`, `blocked`,
`cancelled`. A workspace can define custom statuses on top of these; their keys are
shown in **Settings → Issue Statuses**, and passing an unknown value returns the full
-list. The key `triage` is reserved and cannot be set here.
+list.
### Comments
diff --git a/server/cmd/migrate/status_category_expand_test.go b/server/cmd/migrate/status_category_expand_test.go
index 616ffdeee3..b3b37e2b1e 100644
--- a/server/cmd/migrate/status_category_expand_test.go
+++ b/server/cmd/migrate/status_category_expand_test.go
@@ -52,7 +52,7 @@ func TestStatusCategoryExpandUpgradePaths(t *testing.T) {
if err := pool.QueryRow(ctx, `SELECT jsonb_agg(to_jsonb(s) ORDER BY key)::text FROM issue_status s`).Scan(&before); err != nil {
t.Fatal(err)
}
- opts.Files = realMigrationFiles(t, []string{"469_issue_status_lifecycle_categories", "477_issue_effective_status_triage", "478_issue_status_category_expand"}, "up")
+ opts.Files = realMigrationFiles(t, []string{"469_issue_status_lifecycle_categories", "478_issue_status_category_expand"}, "up")
opts.Conditions = conditionsForDirection("up")
if !applied {
// A normal reader prevents the expand DDL. The real runner must time out,
diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.go
index 3b2dc8263a..2173c4413b 100644
--- a/server/cmd/multica/cmd_issue.go
+++ b/server/cmd/multica/cmd_issue.go
@@ -223,9 +223,7 @@ var issueStatusCmd = &cobra.Command{
Long: "Change an issue's status. The argument is a status KEY, not its display name.\n" +
"Built-in keys: backlog, todo, in_progress, in_review, done, blocked, cancelled.\n" +
"A workspace may define custom statuses on top of these; their keys are shown in\n" +
- "Workspace Settings > Issue Statuses, and an unknown value errors with the full list.\n" +
- "The key triage is reserved and cannot be set: Triage is not a status, so an\n" +
- "issue enters and leaves it through Triage itself rather than a status write.",
+ "Workspace Settings > Issue Statuses, and an unknown value errors with the full list.",
Args: exactArgs(2),
RunE: runIssueStatus,
}
@@ -395,9 +393,7 @@ var issueSearchCmd = &cobra.Command{
// validIssueStatuses are the 7 BUILT-IN status keys, present in every
// workspace. Since MUL-6243 a workspace may define additional custom statuses,
// so this is the list shown in help text and error messages, not the set of
-// accepted values — see validateIssueStatus. The reserved `triage` key is left
-// out on purpose: Triage is not a status an issue can hold, so it is never a
-// value a write may set.
+// accepted values — see validateIssueStatus.
var validIssueStatuses = []string{
"backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled",
}
diff --git a/server/internal/featureflags/keys.go b/server/internal/featureflags/keys.go
index d84db107f8..7c97c3b0f8 100644
--- a/server/internal/featureflags/keys.go
+++ b/server/internal/featureflags/keys.go
@@ -28,8 +28,7 @@ const (
// targeting has no production wiring — which is enough because a
// workspace with no triager configured and no Triage issues sees nothing
// either way. Turning it off stops new intake and triage runs but leaves
- // existing Triage issues workable; the reserved `triage` status itself is
- // not gated.
+ // existing Triage issues workable.
TriageV1 = "triage_v1"
// agentBuilderCompat is no longer a release flag. Keep publishing the key
// as enabled so installed desktop clients that still gate the AI creation
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 7c0a685dbb..963fda3bbb 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -132,9 +132,7 @@ var validIssueStatusCategories = issuestatus.Categories()
// issueTableStatusOrder is the same "board order" the status GROUPING path
// already builds, so sorting and grouping now share one source of truth instead
// of drifting apart. Archived statuses are included because issues stay on them
-// after archival and still have to rank somewhere real. Triage leads: it has no
-// catalog row and no board column, matching the rank statusOrderExpression
-// gives it.
+// after archival and still have to rank somewhere real.
//
// Keeping the indexed column bare avoids the per-row issue_effective_status()
// call that would otherwise turn a bounded page into a workspace scan.
@@ -150,10 +148,9 @@ func (h *Handler) issueStatusSortExpression(
if err != nil {
return "", err
}
- order := append([]string{issuestatus.Triage}, issueTableStatusOrder(entries)...)
return fmt.Sprintf(
"COALESCE(array_position(%s::text[], i.status), 100000)",
- addArg(order),
+ addArg(issueTableStatusOrder(entries)),
), nil
}
@@ -179,10 +176,6 @@ func (h *Handler) resolveIssueStatusKey(w http.ResponseWriter, r *http.Request,
func (h *Handler) resolveIssueStatusKeyKind(w http.ResponseWriter, r *http.Request, workspaceID pgtype.UUID, status string) (string, bool, bool) {
entry, err := issuestatus.Resolve(r.Context(), h.Queries, workspaceID, status)
if err != nil {
- if errors.Is(err, issuestatus.ErrReservedStatus) {
- writeStatusReservedForTriage(w)
- return "", false, false
- }
if errors.Is(err, issuestatus.ErrUnknownStatus) {
// Labels, not bare keys: a derived key says nothing about what the
// status means, so listing `in_review_2` alone leaves the caller no
@@ -3182,10 +3175,6 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {
"the target status was archived while this request was in flight; reload the status list and retry")
return
}
- if errors.Is(err, service.ErrStatusReservedForTriage) {
- writeStatusReservedForTriage(w)
- return
- }
if writeIssueLimitReached(w, err) {
return
}
diff --git a/server/internal/handler/issue_triage_guard.go b/server/internal/handler/issue_triage_guard.go
index 2b0787fdae..b3ddaa945f 100644
--- a/server/internal/handler/issue_triage_guard.go
+++ b/server/internal/handler/issue_triage_guard.go
@@ -46,14 +46,6 @@ func writeIssueInTriage(w http.ResponseWriter, field string) {
"the issue is in Triage, so its "+field+" cannot be set; accept it out of Triage first")
}
-// writeStatusReservedForTriage renders issuestatus.Resolve's refusal of the
-// reserved `triage` key. The catalog carries the same rule as a CHECK
-// (migration 475), so no custom status can take the name either.
-func writeStatusReservedForTriage(w http.ResponseWriter) {
- writeErrorCode(w, http.StatusBadRequest, "status_reserved_for_triage",
- `status "triage" is reserved: Triage is not a status, so no issue can be moved into or out of it by a status write`)
-}
-
// validateBatchTriageLocks rejects a batch that would set a Triage-locked field
// on any issue in Triage, before anything is written. A silent per-issue skip
// would report a short `{"updated": N}` with no reason attached.
diff --git a/server/internal/handler/issue_triage_guard_test.go b/server/internal/handler/issue_triage_guard_test.go
index 0485e321df..c580270750 100644
--- a/server/internal/handler/issue_triage_guard_test.go
+++ b/server/internal/handler/issue_triage_guard_test.go
@@ -2,22 +2,19 @@ package handler
import (
"context"
- "errors"
"net/http"
"testing"
"github.com/jackc/pgx/v5/pgtype"
- "github.com/multica-ai/multica/server/internal/issuestatus"
- "github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/testutil"
)
-// The reserved `triage` status key (MUL-7212, narrowed by MUL-7213).
+// Write protection for an issue in Triage (MUL-7189 §2.2).
//
-// Triage itself lives in issue.triage_state, so there is no "issue in Triage is
-// read-only" rule left here — what remains is that no status may be named
-// `triage`. A Triage entry can only be made by Triage intake, which does not
-// exist yet, so these tests set the column directly.
+// Triage lives in issue.triage_state, not in the status, so the only rule left
+// here is the one parent field a triager may not set. A Triage entry can only
+// be made by Triage intake, which does not exist yet, so these tests set the
+// column directly.
// The number comes from the workspace counter, not the fixture's MAX+1, so an
// HTTP create later in the same test cannot be handed the same number.
@@ -50,76 +47,36 @@ func wantErrorCode(t *testing.T, resp *testutil.Response, code string) {
}
}
-func TestIssueWritesRefuseTheReservedTriageStatus(t *testing.T) {
+// `triage` is an ordinary status key again (MUL-7400). It was reserved while
+// the server read `status = 'triage'` as "in Triage"; since Triage moved to its
+// own column nothing reads the key that way, so a workspace may name a custom
+// status with it and issues may be moved onto it like any other.
+func TestTriageIsAnOrdinaryCustomStatusKey(t *testing.T) {
seedTestCatalog(t)
- t.Run("create", func(t *testing.T) {
- for _, status := range []string{"triage", " TRIAGE "} {
- resp := testutil.Call(t, testHandler.CreateIssue, newRequest(http.MethodPost, "/api/issues", map[string]any{
- "title": "create into triage", "status": status,
- }))
- wantErrorCode(t, resp, "status_reserved_for_triage")
- }
- })
-
- t.Run("update", func(t *testing.T) {
- issueID := dbfx.Issue(t, "update into triage")
- resp := testutil.Call(t, testHandler.UpdateIssue, withURLParam(
- newRequest(http.MethodPut, "/api/issues/"+issueID, map[string]any{"status": "triage"}),
- "id", issueID))
- wantErrorCode(t, resp, "status_reserved_for_triage")
- if got := issueStatusOf(t, issueID); got != "todo" {
- t.Errorf("status after refused update = %q, want todo", got)
- }
- })
-
- t.Run("batch", func(t *testing.T) {
- issueID := dbfx.Issue(t, "batch into triage")
- resp := testutil.Call(t, testHandler.BatchUpdateIssues, newRequest(http.MethodPatch,
- "/api/issues/batch?workspace_id="+testWorkspaceID, map[string]any{
- "issue_ids": []string{issueID},
- "updates": map[string]any{"status": "triage"},
- }))
- wantErrorCode(t, resp, "status_reserved_for_triage")
- if got := issueStatusOf(t, issueID); got != "todo" {
- t.Errorf("status after refused batch = %q, want todo", got)
- }
- })
-
- // Every create entry shares the rule, not only the HTTP handler that
- // resolves the status first.
- t.Run("service create", func(t *testing.T) {
- _, err := testHandler.IssueService.Create(context.Background(), service.IssueCreateParams{
- WorkspaceID: parseUUID(testWorkspaceID),
- Title: "service create into triage",
- Status: issuestatus.Triage,
- Priority: "none",
- CreatorType: "member",
- CreatorID: parseUUID(testUserID),
- }, service.IssueCreateOpts{})
- if !errors.Is(err, service.ErrStatusReservedForTriage) {
- t.Fatalf("IssueService.Create(triage) = %v, want ErrStatusReservedForTriage", err)
- }
- })
-}
+ var created IssueStatusResponse
+ testutil.Call(t, testHandler.CreateIssueStatus, newRequest(http.MethodPost, "/api/issue-statuses", map[string]any{
+ "name": "Triage", "category": "unstarted", "color": "#123456",
+ })).Want(http.StatusCreated).JSON(&created)
+ if created.Key != "triage" {
+ t.Fatalf("custom status key = %q, want triage — the name no longer needs disambiguating", created.Key)
+ }
+ dbfx.Cleanup(t, `DELETE FROM issue_status WHERE id = $1`, parseUUID(created.ID))
-// A custom status can neither take the key nor claim Triage as its category:
-// either would give the catalog a row that resolves to the reserved status.
-func TestCustomStatusCannotClaimTriage(t *testing.T) {
- seedTestCatalog(t)
- cases := map[string]map[string]any{
- "triage category": {"name": "Foo", "key": "foo", "category": "triage", "color": "#123456"},
- "triage key": {"name": "Mine", "key": "triage", "category": "todo", "color": "#123456"},
- "name slugging onto triage": {"name": "Triage", "category": "backlog", "color": "#123456"},
+ issueID := dbfx.Issue(t, "moved onto the custom triage status")
+ var updated IssueResponse
+ testutil.Call(t, testHandler.UpdateIssue, withURLParam(
+ newRequest(http.MethodPut, "/api/issues/"+issueID, map[string]any{"status": "triage"}),
+ "id", issueID)).Want(http.StatusOK).JSON(&updated)
+ if updated.Status != "triage" {
+ t.Fatalf("status after update = %q, want triage", updated.Status)
}
- for name, body := range cases {
- t.Run(name, func(t *testing.T) {
- testutil.Call(t, testHandler.CreateIssueStatus,
- newRequest(http.MethodPost, "/api/issue-statuses", body)).Want(http.StatusBadRequest)
- })
+ if got := issueStatusOf(t, issueID); got != "triage" {
+ t.Fatalf("stored status = %q, want triage", got)
}
- if n := dbfx.Count(t, `SELECT count(*) FROM issue_status WHERE workspace_id = $1 AND (key IN ('foo', 'triage') OR category = 'triage')`, testWorkspaceID); n != 0 {
- t.Fatalf("%d catalog row(s) claimed triage", n)
+ // The status write is not Triage intake: the marker stays untouched.
+ if got := triageStateOf(t, issueID); got != "" {
+ t.Fatalf("triage_state after a status write = %q, want empty", got)
}
}
diff --git a/server/internal/handler/source_context.go b/server/internal/handler/source_context.go
index c86c9e60d2..6f687fb488 100644
--- a/server/internal/handler/source_context.go
+++ b/server/internal/handler/source_context.go
@@ -893,9 +893,6 @@ func (h *Handler) writeSourceContextError(w http.ResponseWriter, err error, limi
case errors.Is(err, service.ErrParentIssueNotFound), errors.Is(err, service.ErrProjectNotFound):
status = http.StatusBadRequest
message = err.Error()
- case errors.Is(err, service.ErrStatusReservedForTriage):
- status, code = http.StatusBadRequest, "status_reserved_for_triage"
- message = err.Error()
case errors.Is(err, errSourceContextBadRequest):
status, code = http.StatusBadRequest, "invalid_request"
message = err.Error()
diff --git a/server/internal/issuestatus/issuestatus.go b/server/internal/issuestatus/issuestatus.go
index 82af88228d..e98f96f0bc 100644
--- a/server/internal/issuestatus/issuestatus.go
+++ b/server/internal/issuestatus/issuestatus.go
@@ -8,8 +8,6 @@
// to done/cancelled; nonterminal custom keys remain distinct. Category resolves
// lifecycle independently. WireCategory adapts response enums for installed
// clients without persisting or granting legacy behavior.
-//
-// One key is reserved and belongs to no category: Triage — see Triage.
package issuestatus
import (
@@ -36,19 +34,6 @@ const (
Cancelled = "cancelled"
)
-// Triage is a RESERVED status key, and nothing more (MUL-7189).
-//
-// Triage itself is NOT a status — an issue in Triage is marked by
-// issue.triage_state, because "is this work at all" is a different question
-// from "how far along is this work", and answering the first inside the second
-// field makes every reader of status re-answer it.
-//
-// What survives here is the name: no workspace may mint a custom status keyed
-// `triage`, so the word means one thing. The catalog carries the same rule as a
-// CHECK (migration 475), and Resolve refuses the key so a write is turned away
-// by the resolver rather than by the database.
-const Triage = "triage"
-
// The four stored lifecycle categories.
const (
CategoryUnstarted = "unstarted"
@@ -97,10 +82,6 @@ var categoryRank = func() map[string]int {
// catalog, or present but archived.
var ErrUnknownStatus = errors.New("unknown issue status")
-// ErrReservedStatus is returned by Resolve for Triage: the name is reserved, so
-// no status write may name it.
-var ErrReservedStatus = errors.New("issue status is reserved for triage")
-
// keyPattern mirrors the issue_status.key CHECK constraint. Keys are lowercase
// so `multica issue status <id> human_review` is unambiguous to type.
var keyPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9_]{0,31}$`)
@@ -114,19 +95,18 @@ type Querier interface {
ListIssueStatusKeysByCategories(ctx context.Context, arg db.ListIssueStatusKeysByCategoriesParams) ([]string, error)
}
-// Canonical returns the 7 canonical status keys in display order. Triage is
-// not among them: it is not a board column and not a settings row.
+// Canonical returns the 7 canonical status keys in display order.
func Canonical() []string {
out := make([]string, len(canonicalOrder))
copy(out, canonicalOrder)
return out
}
-// IsBuiltIn reports whether key is platform-owned: one of the 7 canonical
-// statuses, or the reserved Triage name. None can be reused as a custom key.
+// IsBuiltIn reports whether key is one of the 7 canonical, platform-owned
+// statuses. None of them can be reused as a custom key.
func IsBuiltIn(key string) bool {
_, ok := canonicalRank[key]
- return ok || key == Triage
+ return ok
}
// Categories returns the four lifecycle categories in display order.
@@ -338,22 +318,18 @@ func DeriveKey(name, category string, taken map[string]bool) (string, error) {
//
// The scan is bounded by the CATALOG, not by a policy number. Every candidate
// it tests is distinct, and only len(taken) plus the reserved names (the 7
-// canonical keys, the 4 category names and Triage) can be occupied, so by the
-// pigeonhole
-// principle a free one has to turn up within that many attempts plus one.
+// canonical keys and the 4 category names) can be occupied, so by the
+// pigeonhole principle a free one has to turn up within that many attempts
+// plus one.
// Picking a round constant instead would invent a cap on custom statuses that
// exists nowhere else in the product, and would fail with "provide one
// explicitly" — the very error this package was changed to stop showing a UI
// that has no key field.
-//
-// Migration 476 applies this same rule in SQL to rename a pre-existing custom
-// `triage` key; keep the two in step.
func firstFreeKey(base string, taken map[string]bool) (string, error) {
if !keyOccupied(base, taken) {
return ValidateKey(base)
}
- // +1 for Triage, which keyOccupied also treats as taken.
- limit := len(taken) + len(canonicalOrder) + len(categoryOrder) + 1 + 2
+ limit := len(taken) + len(canonicalOrder) + len(categoryOrder) + 2
for n := 2; n <= limit; n++ {
suffix := "_" + strconv.Itoa(n)
candidate := truncateForSuffix(base, len(suffix)) + suffix
@@ -400,8 +376,7 @@ func Ensure(ctx context.Context, q Querier, workspaceID pgtype.UUID) error {
// carries. This is THE function that keeps existing logic correct:
//
// - a built-in key returns itself, unchanged, WITHOUT touching the database,
-// so no existing code path gains a query or changes behavior. Triage
-// takes that path too: it has no catalog row to read;
+// so no existing code path gains a query or changes behavior;
// - a custom terminal key returns done/cancelled; other custom keys stay raw.
//
// On an unresolvable key it returns the key unchanged. That is the fail-safe
@@ -456,7 +431,7 @@ func Category(ctx context.Context, q Querier, workspaceID pgtype.UUID, status st
// CategoryWithError resolves lifecycle for side-effect decisions. Unlike
// Category, it preserves catalog failures so a caller can defer work and retry.
-// Built-ins, including Triage, still resolve without reading the catalog.
+// Built-ins still resolve without reading the catalog.
func CategoryWithError(ctx context.Context, q Querier, workspaceID pgtype.UUID, status string) (string, error) {
category, _, err := categoryAndName(ctx, q, workspaceID, status)
return category, err
@@ -496,18 +471,11 @@ func categoryAndName(ctx context.Context, q Querier, workspaceID pgtype.UUID, st
// feature, or mid-rollout before migration 339 runs — could not create or
// update an issue at all. Failing open here is limited precisely to the set
// that was valid before this feature existed; anything else still needs a row.
-//
-// Triage never reaches the catalog: it resolves to ErrReservedStatus, so every
-// write path that validates through here refuses it without having to know
-// about it.
func Resolve(ctx context.Context, q Querier, workspaceID pgtype.UUID, status string) (db.IssueStatus, error) {
key := strings.ToLower(strings.TrimSpace(status))
if key == "" {
return db.IssueStatus{}, ErrUnknownStatus
}
- if key == Triage {
- return db.IssueStatus{}, ErrReservedStatus
- }
entry, err := q.GetIssueStatusEntryByKey(ctx, db.GetIssueStatusEntryByKeyParams{
WorkspaceID: workspaceID,
Key: key,
diff --git a/server/internal/issuestatus/issuestatus_test.go b/server/internal/issuestatus/issuestatus_test.go
index 67e1ebe2af..a15e3714ca 100644
--- a/server/internal/issuestatus/issuestatus_test.go
+++ b/server/internal/issuestatus/issuestatus_test.go
@@ -246,87 +246,49 @@ func TestCategoriesCollapseBuiltInsIntoFourLifecycleGroups(t *testing.T) {
}
}
-// Triage is reserved like a built-in but is not one of the four lifecycle
-// categories. Were it one, `{key: "foo", category: "triage"}` would pass
-// custom-status validation and give the catalog a row that resolves to it,
-// breaking the equivalence of `status = 'triage'` with the Go check. (MUL-7212)
-func TestTriageIsReservedButNotACategory(t *testing.T) {
- if !IsBuiltIn(Triage) {
- t.Error("triage must be built-in so no custom status can reuse the key")
- }
- if IsCategory(Triage) {
- t.Error("triage must not be a stored category a custom status can declare")
- }
- if slices.Contains(Canonical(), Triage) {
- t.Error("triage must not be a canonical status: it is not a board column or a settings row")
- }
- if slices.Contains(Categories(), Triage) {
- t.Error("triage must not appear among the four lifecycle categories")
- }
- if _, err := ValidateKey("Triage"); err == nil {
- t.Error("ValidateKey must refuse triage as a custom key")
- }
- if _, err := DeriveKey("Triage", CategoryUnstarted, takenSet()); err == nil {
- t.Error("DeriveKey must refuse a name that slugs onto triage")
- }
- if _, err := DeriveKey("待分诊", Triage, takenSet()); err == nil {
- t.Error("DeriveKey must refuse triage as the fallback category")
- }
- // A name that merely starts with it is unrelated and keeps its slug.
- if got, err := DeriveKey("Triage Later", CategoryUnstarted, takenSet()); err != nil || got != "triage_later" {
- t.Errorf("DeriveKey(Triage Later) = %q, %v; want triage_later", got, err)
- }
-}
-
-// Triage resolves to itself on every read path without a catalog read, and is
-// never a write target. (MUL-7212)
-func TestTriageIsAReservedNameNotAStatus(t *testing.T) {
+// `triage` is an ordinary custom status key (MUL-7400). The name was reserved
+// while the server read `status = 'triage'` as "in Triage"; since Triage moved
+// to issue.triage_state nothing reads it that way, so nothing here may treat
+// the key as platform-owned — a workspace that names a status Triage keeps the
+// obvious key instead of being pushed onto triage_2.
+func TestTriageIsNotReserved(t *testing.T) {
ctx := context.Background()
- q := newFakeQuerier(custom("human_review", InReview))
+ const triage = "triage"
- // Triage is not a status an issue can hold, so nothing resolves it to a
- // category. What the name still does is refuse: no status write may take it
- // and no custom status may claim it.
- if got, ok := CategoryForBehavior(Triage); ok {
- t.Errorf("CategoryForBehavior(triage) = %q, %v; want refused — triage is not a category", got, ok)
+ if IsBuiltIn(triage) {
+ t.Error("IsBuiltIn(triage) = true; the key is not platform-owned")
}
- if got, ok := ParseCategory(Triage); ok {
- t.Errorf("ParseCategory(triage) = %q, %v; want refused", got, ok)
+ if IsCategory(triage) {
+ t.Error("IsCategory(triage) = true; it was never a lifecycle category")
}
- if IsCategory(Triage) {
- t.Error("IsCategory(triage) = true, want false")
+ if slices.Contains(Canonical(), triage) {
+ t.Error("triage must not be a canonical status")
}
- if !IsBuiltIn(Triage) {
- t.Error("IsBuiltIn(triage) = false; the name stays reserved against custom keys")
+ if got, err := ValidateKey("Triage"); err != nil || got != triage {
+ t.Errorf("ValidateKey(Triage) = %q, %v; want triage", got, err)
}
- for _, input := range []string{Triage, " TRIAGE "} {
- if _, err := Resolve(ctx, q, testWorkspace, input); !errors.Is(err, ErrReservedStatus) {
- t.Errorf("Resolve(%q) = %v, want ErrReservedStatus", input, err)
- }
+ if got, err := DeriveKey("Triage", CategoryUnstarted, takenSet()); err != nil || got != triage {
+ t.Errorf("DeriveKey(Triage) = %q, %v; want triage", got, err)
}
- if q.lookups != 0 || q.lists != 0 {
- t.Errorf("refusing triage touched the catalog: %d lookup(s), %d list(s)", q.lookups, q.lists)
+ if got, err := firstFreeKey(triage, takenSet()); err != nil || got != triage {
+ t.Errorf("firstFreeKey(triage) = %q, %v; want triage", got, err)
}
-
- // A key that merely starts with triage still needs a catalog row: the
- // reservation covers the exact key, not a prefix.
- if _, err := Resolve(ctx, q, testWorkspace, "triage_2"); !errors.Is(err, ErrUnknownStatus) {
- t.Errorf("Resolve(triage_2) with no row = %v, want ErrUnknownStatus", err)
+ // Only a workspace that already owns the key gets a derived one, by the
+ // same rule as any other name.
+ if got, err := firstFreeKey(triage, takenSet(triage)); err != nil || got != "triage_2" {
+ t.Errorf("firstFreeKey(triage) with triage taken = %q, %v; want triage_2", got, err)
}
-}
-// With Triage occupying its key, disambiguation lands on triage_2 — the same
-// replacement migration 476 picks for a workspace that already owned a custom
-// `triage`. The two must agree, or a renamed status and a newly derived one
-// could disagree about which key is next.
-func TestFirstFreeKeySkipsTriage(t *testing.T) {
- got, err := firstFreeKey(Triage, takenSet())
- if err != nil || got != "triage_2" {
- t.Errorf("firstFreeKey(triage) = %q, %v; want triage_2", got, err)
+ // And it resolves like any custom key: unknown without a catalog row,
+ // itself with one.
+ q := newFakeQuerier(custom("human_review", InReview))
+ if _, err := Resolve(ctx, q, testWorkspace, triage); !errors.Is(err, ErrUnknownStatus) {
+ t.Errorf("Resolve(triage) with no row = %v, want ErrUnknownStatus", err)
}
- got, err = firstFreeKey(Triage, takenSet("triage_2"))
- if err != nil || got != "triage_3" {
- t.Errorf("firstFreeKey(triage) with triage_2 taken = %q, %v; want triage_3", got, err)
+ withRow := newFakeQuerier(custom(triage, CategoryUnstarted))
+ entry, err := Resolve(ctx, withRow, testWorkspace, triage)
+ if err != nil || entry.Key != triage {
+ t.Errorf("Resolve(triage) with a row = %q, %v; want the custom entry", entry.Key, err)
}
}
@@ -702,24 +664,16 @@ func TestExpandCategories(t *testing.T) {
}
})
- // Triage is not a category, so naming it expands to nothing. Callers that
- // need Triage entries filter on issue.triage_state instead.
- t.Run("triage is not a category to expand", func(t *testing.T) {
+ // A non-category mixed in with real ones drops out; the rest still expand.
+ t.Run("drops a non-category alongside real ones", func(t *testing.T) {
q := newFakeQuerier(custom("shipped", CategoryDone))
- got, err := ExpandCategories(ctx, q, testWorkspace, []string{Triage})
- if err != nil {
- t.Fatalf("expand: %v", err)
- }
- if got != nil {
- t.Errorf("expand(triage) = %v, want nil", got)
- }
- alongside, err := ExpandCategories(ctx, q, testWorkspace, []string{CategoryDone, CategoryClosed, Triage})
+ alongside, err := ExpandCategories(ctx, q, testWorkspace, []string{CategoryDone, CategoryClosed, "not_a_category"})
if err != nil {
t.Fatalf("expand: %v", err)
}
slices.Sort(alongside)
if want := []string{Cancelled, Done, "shipped"}; !slices.Equal(alongside, want) {
- t.Errorf("expand(done, closed, triage) = %v, want %v", alongside, want)
+ t.Errorf("expand(done, closed, not_a_category) = %v, want %v", alongside, want)
}
})
}
diff --git a/server/internal/migrations/reserve_triage_status_key_migration_test.go b/server/internal/migrations/reserve_triage_status_key_migration_test.go
deleted file mode 100644
index afaa66781a..0000000000
--- a/server/internal/migrations/reserve_triage_status_key_migration_test.go
+++ /dev/null
@@ -1,355 +0,0 @@
-package migrations
-
-import (
- "context"
- "os"
- "slices"
- "testing"
- "time"
-
- "github.com/jackc/pgx/v5/pgxpool"
-)
-
-const (
- triageWSBoth = "00000000-0000-0000-0000-00000000a001" // owns triage and triage_2
- triageWSOnly = "00000000-0000-0000-0000-00000000a002" // owns triage only
- triageWSClean = "00000000-0000-0000-0000-00000000a003" // owns neither
-)
-
-// triageMigrationSandbox holds a pool whose connections all work in one
-// isolated schema, holding only the columns migrations 475-476 read or write.
-type triageMigrationSandbox struct {
- pool *pgxpool.Pool
- schema string
-}
-
-func newTriageMigrationSandbox(t *testing.T, schema string) *triageMigrationSandbox {
- t.Helper()
- dbURL := os.Getenv("DATABASE_URL")
- if dbURL == "" {
- t.Skip("integration test requires Postgres at DATABASE_URL")
- }
- ctx := context.Background()
- cfg, err := pgxpool.ParseConfig(dbURL)
- if err != nil {
- t.Fatalf("parse DATABASE_URL: %v", err)
- }
- // Every pooled connection, not just the first, must resolve the
- // migrations' unqualified table names inside the sandbox.
- cfg.ConnConfig.RuntimeParams["search_path"] = schema
- pool, err := pgxpool.NewWithConfig(ctx, cfg)
- if err != nil {
- t.Fatalf("connect to Postgres: %v", err)
- }
- cleanup := func() {
- _, _ = pool.Exec(context.Background(), "DROP SCHEMA IF EXISTS "+schema+" CASCADE")
- }
- cleanup()
- t.Cleanup(func() {
- cleanup()
- pool.Close()
- })
- if _, err := pool.Exec(ctx, "CREATE SCHEMA "+schema); err != nil {
- t.Fatalf("create isolated migration schema: %v", err)
- }
- if _, err := pool.Exec(ctx, `
- CREATE TABLE issue_status (
- id UUID NOT NULL DEFAULT gen_random_uuid(),
- workspace_id UUID NOT NULL,
- key TEXT NOT NULL,
- category TEXT NOT NULL,
- archived_at TIMESTAMPTZ,
- updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
- UNIQUE (workspace_id, key)
- );
- CREATE TABLE issue (
- id UUID NOT NULL DEFAULT gen_random_uuid(),
- workspace_id UUID NOT NULL,
- title TEXT NOT NULL,
- status TEXT NOT NULL,
- revision BIGINT NOT NULL DEFAULT 1
- );
- CREATE TABLE issue_view (
- id UUID NOT NULL DEFAULT gen_random_uuid(),
- workspace_id UUID NOT NULL,
- name TEXT NOT NULL,
- query JSONB NOT NULL,
- revision INTEGER NOT NULL DEFAULT 1,
- updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
- );
- `); err != nil {
- t.Fatalf("create status tables: %v", err)
- }
- return &triageMigrationSandbox{pool: pool, schema: schema}
-}
-
-// reserve applies the two reservation migrations the way the runner does: each
-// file on its own, so 475's barrier commits before 476 scans.
-func (s *triageMigrationSandbox) reserve(t *testing.T, ctx context.Context) {
- t.Helper()
- applyMigrationFile(t, ctx, s.pool, "475_issue_status_key_not_reserved.up.sql")
- applyMigrationFile(t, ctx, s.pool, "476_reserve_triage_status_key.up.sql")
-}
-
-func (s *triageMigrationSandbox) catalog(t *testing.T, ctx context.Context, workspaceID string) []string {
- t.Helper()
- var keys []string
- if err := s.pool.QueryRow(ctx, `
- SELECT array_agg(key ORDER BY key) FROM issue_status WHERE workspace_id = $1
- `, workspaceID).Scan(&keys); err != nil {
- t.Fatalf("read catalog: %v", err)
- }
- return keys
-}
-
-func (s *triageMigrationSandbox) constraintValidated(t *testing.T, ctx context.Context) bool {
- t.Helper()
- var validated bool
- if err := s.pool.QueryRow(ctx, `
- SELECT convalidated FROM pg_constraint
- WHERE conname = 'issue_status_key_not_reserved'
- AND conrelid = (quote_ident($1) || '.issue_status')::regclass
- `, s.schema).Scan(&validated); err != nil {
- t.Fatalf("read reservation constraint: %v", err)
- }
- return validated
-}
-
-// TestReserveTriageStatusKeyMigration covers the upgrade conflict of MUL-7212:
-// a workspace that already owns a custom `triage` status must come out with a
-// replacement key picked like issuestatus.firstFreeKey, and its catalog, issues
-// and saved views must all agree on it afterwards.
-func TestReserveTriageStatusKeyMigration(t *testing.T) {
- ctx := context.Background()
- s := newTriageMigrationSandbox(t, "reserve_triage_status_key_migration_test")
-
- for _, seed := range []string{`
- INSERT INTO issue_status (workspace_id, key, category, archived_at) VALUES
- ($1, 'triage', 'backlog', NULL),
- -- Archived rows still own their key, so triage_2 is not free.
- ($1, 'triage_2', 'todo', now()),
- ($2, 'triage', 'in_review', NULL),
- ($3, 'todo_later', 'todo', NULL)
- `, `
- INSERT INTO issue (workspace_id, title, status, revision) VALUES
- ($1, 'on triage A', 'triage', 3),
- ($1, 'on triage B', 'triage', 1),
- ($1, 'on triage_2', 'triage_2', 1),
- ($2, 'on triage C', 'triage', 1),
- ($3, 'clean todo', 'todo', 1)
- `, `
- INSERT INTO issue_view (workspace_id, name, query) VALUES
- ($1, 'mixed', '{"statusFilters": ["todo", "triage", "triage_2"], "priorityFilters": ["high"]}'),
- ($1, 'no status filter', '{"priorityFilters": ["high"]}'),
- ($2, 'only triage', '{"statusFilters": ["triage"]}'),
- -- A workspace without a custom triage never had a status by that
- -- key, so its views are not the migration's to reinterpret.
- ($3, 'stale value', '{"statusFilters": ["triage"]}')
- `} {
- if _, err := s.pool.Exec(ctx, seed, triageWSBoth, triageWSOnly, triageWSClean); err != nil {
- t.Fatalf("seed conflicting workspaces: %v", err)
- }
- }
-
- s.reserve(t, ctx)
-
- if got, want := s.catalog(t, ctx, triageWSBoth), []string{"triage_2", "triage_3"}; !slices.Equal(got, want) {
- t.Errorf("catalog with triage and archived triage_2 = %v, want %v", got, want)
- }
- if got, want := s.catalog(t, ctx, triageWSOnly), []string{"triage_2"}; !slices.Equal(got, want) {
- t.Errorf("catalog with triage only = %v, want %v", got, want)
- }
- if !s.constraintValidated(t, ctx) {
- t.Error("476 left the reservation NOT VALID")
- }
-
- type issueState struct {
- status string
- revision int64
- }
- issues := map[string]issueState{}
- rows, err := s.pool.Query(ctx, `SELECT title, status, revision FROM issue`)
- if err != nil {
- t.Fatalf("read issues: %v", err)
- }
- for rows.Next() {
- var title string
- var state issueState
- if err := rows.Scan(&title, &state.status, &state.revision); err != nil {
- t.Fatalf("scan issue: %v", err)
- }
- issues[title] = state
- }
- rows.Close()
- for title, want := range map[string]issueState{
- // Moved issues bump their revision so a stale editor conflicts.
- "on triage A": {"triage_3", 4},
- "on triage B": {"triage_3", 2},
- "on triage_2": {"triage_2", 1},
- "on triage C": {"triage_2", 2},
- "clean todo": {"todo", 1},
- } {
- if got := issues[title]; got != want {
- t.Errorf("issue %q = %+v, want %+v", title, got, want)
- }
- }
-
- type viewState struct {
- query string
- revision int
- }
- views := map[string]viewState{}
- rows, err = s.pool.Query(ctx, `SELECT name, query::text, revision FROM issue_view`)
- if err != nil {
- t.Fatalf("read views: %v", err)
- }
- for rows.Next() {
- var name string
- var state viewState
- if err := rows.Scan(&name, &state.query, &state.revision); err != nil {
- t.Fatalf("scan view: %v", err)
- }
- views[name] = state
- }
- rows.Close()
- for name, want := range map[string]viewState{
- "mixed": {`{"statusFilters": ["todo", "triage_3", "triage_2"], "priorityFilters": ["high"]}`, 2},
- "no status filter": {`{"priorityFilters": ["high"]}`, 1},
- "only triage": {`{"statusFilters": ["triage_2"]}`, 2},
- "stale value": {`{"statusFilters": ["triage"]}`, 1},
- } {
- if got := views[name]; got != want {
- t.Errorf("view %q = %+v, want %+v", name, got, want)
- }
- }
-
- // The reservation now holds in storage: an old pod that still accepts
- // `triage` as a custom key cannot recreate the conflict.
- assertInsertCheckViolation(t, ctx, s.pool,
- `INSERT INTO issue_status (workspace_id, key, category) VALUES ($1, 'triage', 'todo')`, triageWSClean)
-
- applyMigrationFile(t, ctx, s.pool, "476_reserve_triage_status_key.down.sql")
- applyMigrationFile(t, ctx, s.pool, "475_issue_status_key_not_reserved.down.sql")
- if _, err := s.pool.Exec(ctx,
- `INSERT INTO issue_status (workspace_id, key, category) VALUES ($1, 'triage', 'todo')`, triageWSClean); err != nil {
- t.Fatalf("insert after rollback dropped the reservation: %v", err)
- }
- // Re-applying handles the row the rollback window let in.
- s.reserve(t, ctx)
- if got, want := s.catalog(t, ctx, triageWSClean), []string{"todo_later", "triage_2"}; !slices.Equal(got, want) {
- t.Errorf("catalog after re-apply = %v, want %v", got, want)
- }
-}
-
-// TestReserveTriageStatusKeySurvivesAConcurrentCreate is the rollout race: an
-// old pod, which still accepts `triage` as a custom key, creates one in a
-// workspace that had no conflict while the migrations run. Scanning first and
-// adding the CHECK last let that row fail the final validation and abort the
-// deploy. With the barrier committed before the scan, the in-flight create is
-// either repaired by 476 or refused outright — the deploy never fails on it.
-func TestReserveTriageStatusKeySurvivesAConcurrentCreate(t *testing.T) {
- ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
- s := newTriageMigrationSandbox(t, "reserve_triage_status_key_race_test")
-
- migrator, err := s.pool.Acquire(ctx)
- if err != nil {
- t.Fatalf("acquire migrator connection: %v", err)
- }
- defer migrator.Release()
- oldPod, err := s.pool.Acquire(ctx)
- if err != nil {
- t.Fatalf("acquire old-pod connection: %v", err)
- }
- defer oldPod.Release()
- var migratorPID int32
- if err := migrator.QueryRow(ctx, `SELECT pg_backend_pid()`).Scan(&migratorPID); err != nil {
- t.Fatalf("read migrator pid: %v", err)
- }
-
- // The old pod is mid-create when the migration starts.
- tx, err := oldPod.Begin(ctx)
- if err != nil {
- t.Fatalf("begin old-pod create: %v", err)
- }
- defer tx.Rollback(context.Background())
- if _, err := tx.Exec(ctx,
- `INSERT INTO issue_status (workspace_id, key, category) VALUES ($1, 'triage', 'todo')`, triageWSClean); err != nil {
- t.Fatalf("old-pod create: %v", err)
- }
-
- barrierSQL := readMigrationFile(t, "475_issue_status_key_not_reserved.up.sql")
- barrier := make(chan error, 1)
- go func() {
- _, err := migrator.Exec(ctx, barrierSQL)
- barrier <- err
- }()
-
- // The barrier needs the table to itself, so it waits for the create.
- for {
- var waiting bool
- if err := s.pool.QueryRow(ctx,
- `SELECT wait_event_type = 'Lock' FROM pg_stat_activity WHERE pid = $1`, migratorPID).Scan(&waiting); err != nil {
- t.Fatalf("watch migrator: %v", err)
- }
- if waiting {
- break
- }
- select {
- case err := <-barrier:
- t.Fatalf("barrier finished before the in-flight create committed: %v", err)
- case <-ctx.Done():
- t.Fatal("migrator never waited on the in-flight create")
- case <-time.After(20 * time.Millisecond):
- }
- }
- if err := tx.Commit(ctx); err != nil {
- t.Fatalf("commit old-pod create: %v", err)
- }
- if err := <-barrier; err != nil {
- t.Fatalf("apply barrier after a concurrent create: %v", err)
- }
-
- // From here on the old pod cannot create another one anywhere.
- assertInsertCheckViolation(t, ctx, oldPod,
- `INSERT INTO issue_status (workspace_id, key, category) VALUES ($1, 'triage', 'todo')`, triageWSOnly)
-
- applyMigrationFile(t, ctx, migrator, "476_reserve_triage_status_key.up.sql")
- if got, want := s.catalog(t, ctx, triageWSClean), []string{"triage_2"}; !slices.Equal(got, want) {
- t.Errorf("catalog after the race = %v, want the in-flight create renamed to [triage_2]", got)
- }
- if !s.constraintValidated(t, ctx) {
- t.Error("476 left the reservation NOT VALID")
- }
-}
-
-// TestIssueEffectiveStatusTriageMigration pins the SQL mirror of
-// issuestatus.Effective: `triage` resolves to itself on the fast path, and
-// custom keys still resolve through the catalog.
-func TestIssueEffectiveStatusTriageMigration(t *testing.T) {
- ctx := context.Background()
- s := newTriageMigrationSandbox(t, "issue_effective_status_triage_migration_test")
- if _, err := s.pool.Exec(ctx,
- `INSERT INTO issue_status (workspace_id, key, category) VALUES ($1, 'shipped', 'done')`, triageWSBoth); err != nil {
- t.Fatalf("seed catalog: %v", err)
- }
-
- applyMigrationFile(t, ctx, s.pool, "477_issue_effective_status_triage.up.sql")
-
- cases := map[string]string{"triage": "triage", "todo": "todo", "shipped": "done", "ghost": "ghost"}
- for status, want := range cases {
- var got string
- if err := s.pool.QueryRow(ctx, `SELECT issue_effective_status($1, $2)`, triageWSBoth, status).Scan(&got); err != nil {
- t.Fatalf("issue_effective_status(%q): %v", status, err)
- }
- if got != want {
- t.Errorf("issue_effective_status(%q) = %q, want %q", status, got, want)
- }
- }
-
- applyMigrationFile(t, ctx, s.pool, "477_issue_effective_status_triage.down.sql")
- var got string
- if err := s.pool.QueryRow(ctx, `SELECT issue_effective_status($1, 'shipped')`, triageWSBoth).Scan(&got); err != nil || got != "done" {
- t.Fatalf("after rollback issue_effective_status(shipped) = %q, %v; want done", got, err)
- }
-}
diff --git a/server/internal/migrations/triage_status_key_reservation_test.go b/server/internal/migrations/triage_status_key_reservation_test.go
new file mode 100644
index 0000000000..57f975d3ab
--- /dev/null
+++ b/server/internal/migrations/triage_status_key_reservation_test.go
@@ -0,0 +1,223 @@
+package migrations
+
+import (
+ "context"
+ "os"
+ "slices"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+const (
+ triageWSOwner = "00000000-0000-0000-0000-00000000a001" // owns a custom `triage` status
+ triageWSClean = "00000000-0000-0000-0000-00000000a003" // owns neither
+)
+
+// triageMigrationSandbox holds a pool whose connections all work in one
+// isolated schema, holding only the columns these migrations read or write.
+type triageMigrationSandbox struct {
+ pool *pgxpool.Pool
+ schema string
+}
+
+func newTriageMigrationSandbox(t *testing.T, schema string) *triageMigrationSandbox {
+ t.Helper()
+ dbURL := os.Getenv("DATABASE_URL")
+ if dbURL == "" {
+ t.Skip("integration test requires Postgres at DATABASE_URL")
+ }
+ ctx := context.Background()
+ cfg, err := pgxpool.ParseConfig(dbURL)
+ if err != nil {
+ t.Fatalf("parse DATABASE_URL: %v", err)
+ }
+ // Every pooled connection, not just the first, must resolve the
+ // migrations' unqualified table names inside the sandbox.
+ cfg.ConnConfig.RuntimeParams["search_path"] = schema
+ pool, err := pgxpool.NewWithConfig(ctx, cfg)
+ if err != nil {
+ t.Fatalf("connect to Postgres: %v", err)
+ }
+ cleanup := func() {
+ _, _ = pool.Exec(context.Background(), "DROP SCHEMA IF EXISTS "+schema+" CASCADE")
+ }
+ cleanup()
+ t.Cleanup(func() {
+ cleanup()
+ pool.Close()
+ })
+ if _, err := pool.Exec(ctx, "CREATE SCHEMA "+schema); err != nil {
+ t.Fatalf("create isolated migration schema: %v", err)
+ }
+ if _, err := pool.Exec(ctx, `
+ CREATE TABLE issue_status (
+ id UUID NOT NULL DEFAULT gen_random_uuid(),
+ workspace_id UUID NOT NULL,
+ key TEXT NOT NULL,
+ category TEXT NOT NULL,
+ archived_at TIMESTAMPTZ,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ UNIQUE (workspace_id, key)
+ );
+ CREATE TABLE issue (
+ id UUID NOT NULL DEFAULT gen_random_uuid(),
+ workspace_id UUID NOT NULL,
+ title TEXT NOT NULL,
+ status TEXT NOT NULL,
+ revision BIGINT NOT NULL DEFAULT 1
+ );
+ CREATE TABLE issue_view (
+ id UUID NOT NULL DEFAULT gen_random_uuid(),
+ workspace_id UUID NOT NULL,
+ name TEXT NOT NULL,
+ query JSONB NOT NULL,
+ revision INTEGER NOT NULL DEFAULT 1,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+ );
+ `); err != nil {
+ t.Fatalf("create status tables: %v", err)
+ }
+ return &triageMigrationSandbox{pool: pool, schema: schema}
+}
+
+func (s *triageMigrationSandbox) catalog(t *testing.T, ctx context.Context, workspaceID string) []string {
+ t.Helper()
+ var keys []string
+ if err := s.pool.QueryRow(ctx, `
+ SELECT array_agg(key ORDER BY key) FROM issue_status WHERE workspace_id = $1
+ `, workspaceID).Scan(&keys); err != nil {
+ t.Fatalf("read catalog: %v", err)
+ }
+ return keys
+}
+
+func (s *triageMigrationSandbox) reservationExists(t *testing.T, ctx context.Context) bool {
+ t.Helper()
+ var exists bool
+ if err := s.pool.QueryRow(ctx, `
+ SELECT EXISTS (
+ SELECT 1 FROM pg_constraint
+ WHERE conname = 'issue_status_key_not_reserved'
+ AND conrelid = (quote_ident($1) || '.issue_status')::regclass
+ )
+ `, s.schema).Scan(&exists); err != nil {
+ t.Fatalf("read reservation constraint: %v", err)
+ }
+ return exists
+}
+
+// The reservation of the `triage` status key is withdrawn (MUL-7400). What it
+// protected — `status = 'triage'` meaning "in Triage" — ended when migration
+// 483 gave Triage a column of its own, so 475-477 are emptied rather than
+// shipped: no CHECK, and above all no rewrite of a workspace's status keys,
+// issues and saved views in the deploy path.
+func TestTriageStatusKeyReservationIsNotApplied(t *testing.T) {
+ ctx := context.Background()
+ s := newTriageMigrationSandbox(t, "triage_status_key_reservation_test")
+
+ for _, seed := range []string{`
+ INSERT INTO issue_status (workspace_id, key, category) VALUES
+ ($1, 'triage', 'backlog'),
+ ($2, 'todo_later', 'todo')
+ `, `
+ INSERT INTO issue (workspace_id, title, status, revision) VALUES
+ ($1, 'on triage', 'triage', 3),
+ ($2, 'clean todo', 'todo', 1)
+ `, `
+ INSERT INTO issue_view (workspace_id, name, query) VALUES
+ ($1, 'only triage', '{"statusFilters": ["triage"]}'),
+ ($2, 'stale value', '{"statusFilters": ["triage"]}')
+ `} {
+ if _, err := s.pool.Exec(ctx, seed, triageWSOwner, triageWSClean); err != nil {
+ t.Fatalf("seed a workspace that owns a custom triage status: %v", err)
+ }
+ }
+
+ for _, file := range []string{
+ "475_issue_status_key_not_reserved.up.sql",
+ "476_reserve_triage_status_key.up.sql",
+ "477_issue_effective_status_triage.up.sql",
+ "490_drop_triage_status_key_reservation.up.sql",
+ } {
+ applyMigrationFile(t, ctx, s.pool, file)
+ }
+
+ if got, want := s.catalog(t, ctx, triageWSOwner), []string{"triage"}; !slices.Equal(got, want) {
+ t.Errorf("catalog = %v, want %v — the custom status must keep its key", got, want)
+ }
+ var status string
+ var revision int64
+ if err := s.pool.QueryRow(ctx,
+ `SELECT status, revision FROM issue WHERE title = 'on triage'`).Scan(&status, &revision); err != nil {
+ t.Fatalf("read issue: %v", err)
+ }
+ if status != "triage" || revision != 3 {
+ t.Errorf("issue = {status:%q revision:%d}, want {triage 3} — untouched", status, revision)
+ }
+ var query string
+ var viewRevision int
+ if err := s.pool.QueryRow(ctx,
+ `SELECT query::text, revision FROM issue_view WHERE name = 'only triage'`).Scan(&query, &viewRevision); err != nil {
+ t.Fatalf("read view: %v", err)
+ }
+ if query != `{"statusFilters": ["triage"]}` || viewRevision != 1 {
+ t.Errorf("view = {query:%s revision:%d}, want the seeded filter at revision 1", query, viewRevision)
+ }
+ if n := countRows(t, ctx, s.pool, `SELECT count(*) FROM issue_view WHERE query -> 'statusFilters' @> '["triage"]'::jsonb`); n != 2 {
+ t.Errorf("%d saved view(s) still filter on triage, want 2", n)
+ }
+
+ if s.reservationExists(t, ctx) {
+ t.Error("the barrier CHECK was installed; nothing may reserve the key")
+ }
+ if _, err := s.pool.Exec(ctx,
+ `INSERT INTO issue_status (workspace_id, key, category) VALUES ($1, 'triage', 'todo')`, triageWSClean); err != nil {
+ t.Fatalf("another workspace could not take the key: %v", err)
+ }
+}
+
+// Emptying 475-477 covers every database that has not run them, production
+// included. A database that did migrate off main already has the CHECK, and
+// would refuse a custom status keyed `triage` that the server now accepts —
+// so migration 490 drops it there.
+func TestDropTriageStatusKeyReservationRepairsAMigratedDatabase(t *testing.T) {
+ ctx := context.Background()
+ s := newTriageMigrationSandbox(t, "triage_status_key_reservation_repair_test")
+
+ // The state the original 475 + 476 left behind: a validated barrier.
+ if _, err := s.pool.Exec(ctx, `
+ ALTER TABLE issue_status
+ ADD CONSTRAINT issue_status_key_not_reserved CHECK (key <> 'triage')
+ `); err != nil {
+ t.Fatalf("recreate the shipped barrier: %v", err)
+ }
+ assertInsertCheckViolation(t, ctx, s.pool,
+ `INSERT INTO issue_status (workspace_id, key, category) VALUES ($1, 'triage', 'todo')`, triageWSOwner)
+
+ applyMigrationFile(t, ctx, s.pool, "490_drop_triage_status_key_reservation.up.sql")
+
+ if s.reservationExists(t, ctx) {
+ t.Fatal("490 left the barrier in place")
+ }
+ if _, err := s.pool.Exec(ctx,
+ `INSERT INTO issue_status (workspace_id, key, category) VALUES ($1, 'triage', 'todo')`, triageWSOwner); err != nil {
+ t.Fatalf("insert after 490: %v", err)
+ }
+
+ // Rolling 490 back must not hand the barrier back: a row it forbids now
+ // exists, and the server no longer reads the key as anything special.
+ applyMigrationFile(t, ctx, s.pool, "490_drop_triage_status_key_reservation.down.sql")
+ if s.reservationExists(t, ctx) {
+ t.Error("490 down restored a barrier the catalog would violate")
+ }
+}
+
+func countRows(t *testing.T, ctx context.Context, pool *pgxpool.Pool, query string, args ...any) int64 {
+ t.Helper()
+ var n int64
+ if err := pool.QueryRow(ctx, query, args...).Scan(&n); err != nil {
+ t.Fatalf("count rows: %v", err)
+ }
+ return n
+}
diff --git a/server/internal/service/issue.go b/server/internal/service/issue.go
index f4f2033dec..45a9346349 100644
--- a/server/internal/service/issue.go
+++ b/server/internal/service/issue.go
@@ -164,11 +164,6 @@ var ErrIssueLabelNotFound = errors.New("issue label not found in this workspace"
// it arrived, so retrying against the refreshed catalog is the remedy.
var ErrIssueStatusUnavailable = errors.New("issue status is no longer available")
-// ErrStatusReservedForTriage signals a create that asked for the reserved
-// `triage` status. An issue enters Triage only through Triage intake, never
-// through an ordinary create; callers translate this into a 400.
-var ErrStatusReservedForTriage = errors.New("status triage is reserved for Triage intake")
-
var ErrSourceContextAlreadyAttached = errors.New("source context is already attached")
// IssueCreateResult is the typed return from IssueService.Create.
@@ -216,11 +211,6 @@ type IssueCreateResult struct {
// Caller-owned validation is limited to transport-shaped checks: title
// required, RFC3339 date format, assignee pair sanity.
func (s *IssueService) Create(ctx context.Context, p IssueCreateParams, opts IssueCreateOpts) (IssueCreateResult, error) {
- // Checked here as well as at the transport so every create entry shares
- // the rule; the built-in skip below would otherwise let the key through.
- if p.Status == issuestatus.Triage {
- return IssueCreateResult{}, ErrStatusReservedForTriage
- }
issueCountPolicy := ResolveIssueCountPolicy(ctx, s.Entitlements, p.WorkspaceID)
tx, err := s.TxStarter.Begin(ctx)
if err != nil {
diff --git a/server/migrations/475_issue_status_key_not_reserved.down.sql b/server/migrations/475_issue_status_key_not_reserved.down.sql
index 30230ca04f..93a889077e 100644
--- a/server/migrations/475_issue_status_key_not_reserved.down.sql
+++ b/server/migrations/475_issue_status_key_not_reserved.down.sql
@@ -1 +1,2 @@
-ALTER TABLE issue_status DROP CONSTRAINT IF EXISTS issue_status_key_not_reserved;
+-- Intentionally empty: the up migration is a no-op. Migration 490 owns dropping
+-- the constraint on any database that applied the original 475.
diff --git a/server/migrations/475_issue_status_key_not_reserved.up.sql b/server/migrations/475_issue_status_key_not_reserved.up.sql
index 4a827770f5..9de6820129 100644
--- a/server/migrations/475_issue_status_key_not_reserved.up.sql
+++ b/server/migrations/475_issue_status_key_not_reserved.up.sql
@@ -1,21 +1,12 @@
--- Reserve the `triage` status key, step 1 of 2: the write barrier (MUL-7212).
+-- Intentionally empty (MUL-7400).
--
--- `triage` becomes a platform-reserved key: the status of an issue waiting in
--- Triage. It has no catalog row, it is not a category, and the server refuses
--- it as a custom key. Before this change nothing reserved it, so a workspace
--- may already own a CUSTOM status keyed `triage`; migration 476 renames those.
+-- This file reserved the `triage` status key: a CHECK that no issue_status row
+-- may be keyed `triage`, so the server could read `status = 'triage'` as "in
+-- Triage". Migration 483 moved Triage onto issue.triage_state, after which
+-- nothing reads that key as Triage and the name protects nothing. The Go side
+-- of the reservation is gone with it.
--
--- The CHECK lands first, NOT VALID and in a file of its own, so it commits
--- before 476 scans for conflicts. From then on no pod — including an old one
--- still running during the rollout, which accepts `triage` as a custom key —
--- can create or keep writing a `triage` row, and the conflict set 476 scans
--- cannot grow behind its back. A single migration that scanned first and added
--- the CHECK last left that window open: a row created in between failed the
--- final validation and aborted the deploy.
---
--- NOT VALID skips the existing rows, which still hold the key until 476
--- renames them and validates the constraint. Until then an old pod updating one
--- of those rows (rename, archive, reorder) is refused by the CHECK; the window
--- is the gap between two files of one migration run.
-ALTER TABLE issue_status
- ADD CONSTRAINT issue_status_key_not_reserved CHECK (key <> 'triage') NOT VALID;
+-- Emptied rather than reverted with a new migration because 475-477 have never
+-- run outside development and CI: releases deploy from tags, and the newest tag
+-- predates them. Migration 490 drops the constraint wherever a database did run
+-- this file from main.
diff --git a/server/migrations/476_reserve_triage_status_key.down.sql b/server/migrations/476_reserve_triage_status_key.down.sql
index 866e9dfcea..a9b145b995 100644
--- a/server/migrations/476_reserve_triage_status_key.down.sql
+++ b/server/migrations/476_reserve_triage_status_key.down.sql
@@ -1,4 +1 @@
--- Intentionally empty. Workspaces whose custom `triage` status was renamed keep
--- the replacement key: restoring `triage` would hand their issues back to a key
--- the Triage feature owns. The constraint this migration validated is dropped
--- by 475's down migration.
+-- Intentionally empty: the up migration is a no-op.
diff --git a/server/migrations/476_reserve_triage_status_key.up.sql b/server/migrations/476_reserve_triage_status_key.up.sql
index 7c3ee7153f..aa5db366b9 100644
--- a/server/migrations/476_reserve_triage_status_key.up.sql
+++ b/server/migrations/476_reserve_triage_status_key.up.sql
@@ -1,90 +1,12 @@
--- Reserve the `triage` status key, step 2 of 2: repair the conflicts and
--- validate the barrier (MUL-7212, design MUL-7189 §2.1).
---
--- Migration 475 already refuses any new `triage` row, so the set of workspaces
--- that own a custom `triage` is fixed by the time this file scans for it. Once
--- the new server reads that key as "in Triage", every issue on such a custom
--- status would silently change meaning, so this migration runs before any
--- server that reserves the key starts (the entrypoint finishes migrations
--- first). The file executes as one implicit transaction, and for every
--- workspace that owns a custom `triage` it:
---
--- 1. picks a replacement key with the same rule as issuestatus.firstFreeKey:
--- `triage_2`, `triage_3`, ... — the first one this workspace does not own,
--- counting archived rows, because the (workspace_id, key) index is not
--- partial. A fixed name such as `triage_legacy` could collide;
--- 2. renames the catalog row, moves the workspace's issues on `triage` to
--- the replacement, and rewrites `triage` inside saved views'
--- query.statusFilters — the only other place a status key is stored as
--- live configuration. activity_log / inbox_item details are history and
--- are left as written;
--- 3. reports the counts for the workspace in the migration log.
---
--- Each workspace's catalog is taken under the same EXCLUSIVE advisory lock
--- that archive holds. Old pods still running during the rollout take the
--- SHARED side and re-resolve a custom status before writing an issue onto it,
--- so an in-flight write either commits before the rename (and is moved with
--- the rest) or re-resolves after it and is refused. No issue can be left on
--- the old key.
---
--- VALIDATE then proves no `triage` row is left. It takes SHARE UPDATE
--- EXCLUSIVE, so it does not block reads or writes of the catalog.
---
--- issue.revision is bumped on the moved issues, so a client editing with the
--- old status in hand gets a revision conflict instead of writing it back.
--- The rename is not reversed by the down migration; the replacement key is an
--- ordinary custom key the admin can keep or rename.
-
-DO $$
-DECLARE
- legacy RECORD;
- n INT;
- replacement TEXT;
- moved_issues BIGINT;
- rewritten_views BIGINT;
-BEGIN
- FOR legacy IN
- SELECT id, workspace_id FROM issue_status WHERE key = 'triage' ORDER BY workspace_id
- LOOP
- PERFORM pg_advisory_xact_lock(hashtextextended(legacy.workspace_id::text || ':issue_status', 0));
-
- n := 2;
- WHILE EXISTS (
- SELECT 1 FROM issue_status
- WHERE workspace_id = legacy.workspace_id AND key = 'triage_' || n
- ) LOOP
- n := n + 1;
- END LOOP;
- replacement := 'triage_' || n;
-
- UPDATE issue_status
- SET key = replacement, updated_at = now()
- WHERE id = legacy.id;
-
- UPDATE issue
- SET status = replacement, revision = revision + 1
- WHERE workspace_id = legacy.workspace_id AND status = 'triage';
- GET DIAGNOSTICS moved_issues = ROW_COUNT;
-
- UPDATE issue_view
- SET query = jsonb_set(query, '{statusFilters}', (
- SELECT jsonb_agg(
- CASE WHEN f.value = to_jsonb('triage'::text) THEN to_jsonb(replacement) ELSE f.value END
- ORDER BY f.ordinality)
- FROM jsonb_array_elements(query -> 'statusFilters') WITH ORDINALITY AS f(value, ordinality)
- )),
- revision = revision + 1,
- updated_at = now()
- WHERE workspace_id = legacy.workspace_id
- AND jsonb_typeof(query -> 'statusFilters') = 'array'
- AND query -> 'statusFilters' @> '["triage"]'::jsonb;
- GET DIAGNOSTICS rewritten_views = ROW_COUNT;
-
- -- The "migration report: " prefix is what cmd/migrate forwards to its
- -- log; other server notices are dropped.
- RAISE NOTICE 'migration report: reserve triage status key: workspace % renamed custom status triage to %, moved % issue(s), rewrote % saved view(s)',
- legacy.workspace_id, replacement, moved_issues, rewritten_views;
- END LOOP;
-END $$;
-
-ALTER TABLE issue_status VALIDATE CONSTRAINT issue_status_key_not_reserved;
+-- Intentionally empty (MUL-7400).
+--
+-- This file was step 2 of reserving the `triage` status key: it renamed any
+-- pre-existing custom `triage` status to `triage_2`, moved that workspace's
+-- issues onto the new key, rewrote saved views, and validated 475's CHECK. All
+-- of it existed to protect an equivalence — `status = 'triage'` means "in
+-- Triage" — that migration 483 retired by giving Triage a column of its own.
+--
+-- What is left without that equivalence is a rewrite of live customer data
+-- (status keys, issue rows, saved views) in the deploy path, buying nothing.
+-- The key reservation is gone from the server as well, so a workspace that
+-- already owns a custom `triage` status simply keeps it.
diff --git a/server/migrations/477_issue_effective_status_triage.down.sql b/server/migrations/477_issue_effective_status_triage.down.sql
index 12c410cb20..a9b145b995 100644
--- a/server/migrations/477_issue_effective_status_triage.down.sql
+++ b/server/migrations/477_issue_effective_status_triage.down.sql
@@ -1,12 +1 @@
--- Restore migration 469's body, whose fast path knows only the 7 built-in keys.
-CREATE OR REPLACE FUNCTION issue_effective_status(p_workspace_id UUID, p_status TEXT)
-RETURNS TEXT LANGUAGE sql STABLE PARALLEL SAFE AS $function$
- SELECT CASE
- WHEN p_status IN ('backlog', 'todo', 'in_progress', 'in_review', 'done', 'blocked', 'cancelled') THEN p_status
- ELSE COALESCE((SELECT CASE s.category
- WHEN 'done' THEN 'done'
- WHEN 'closed' THEN 'cancelled'
- ELSE p_status END
- FROM issue_status s WHERE s.workspace_id = p_workspace_id AND s.key = p_status), p_status)
- END
-$function$;
+-- Intentionally empty: the up migration is a no-op.
diff --git a/server/migrations/477_issue_effective_status_triage.up.sql b/server/migrations/477_issue_effective_status_triage.up.sql
index 471a835188..b778c121a7 100644
--- a/server/migrations/477_issue_effective_status_triage.up.sql
+++ b/server/migrations/477_issue_effective_status_triage.up.sql
@@ -1,17 +1,9 @@
--- Teach the SQL mirror of issuestatus.Effective about the reserved `triage`
--- key (MUL-7212, design MUL-7189 §2.1). Like the Go resolver, it is its own
--- category and never looked up: migrations 475-476 guarantee no catalog row can
--- hold it, so the fast path is exact rather than a guess. The rest of the body
--- is migration 469's, which projects custom terminal categories onto
--- done/cancelled.
-CREATE OR REPLACE FUNCTION issue_effective_status(p_workspace_id UUID, p_status TEXT)
-RETURNS TEXT LANGUAGE sql STABLE PARALLEL SAFE AS $function$
- SELECT CASE
- WHEN p_status IN ('backlog', 'todo', 'in_progress', 'in_review', 'done', 'blocked', 'cancelled', 'triage') THEN p_status
- ELSE COALESCE((SELECT CASE s.category
- WHEN 'done' THEN 'done'
- WHEN 'closed' THEN 'cancelled'
- ELSE p_status END
- FROM issue_status s WHERE s.workspace_id = p_workspace_id AND s.key = p_status), p_status)
- END
-$function$;
+-- Intentionally empty (MUL-7400).
+--
+-- This file added `triage` to the fast path of issue_effective_status(), the
+-- SQL mirror of issuestatus.Effective, on the premise that no catalog row could
+-- ever hold the key. That premise was migrations 475-476, which this change
+-- also empties. Without the fast-path entry the key falls through to the
+-- catalog lookup and, finding no row, returns unchanged — the same answer.
+--
+-- Migration 478 owns the current definition of the function.
diff --git a/server/migrations/478_issue_status_category_expand.up.sql b/server/migrations/478_issue_status_category_expand.up.sql
index fd57bbfa0d..78e51bb705 100644
--- a/server/migrations/478_issue_status_category_expand.up.sql
+++ b/server/migrations/478_issue_status_category_expand.up.sql
@@ -35,7 +35,7 @@ ALTER TABLE issue_status
CREATE OR REPLACE FUNCTION issue_effective_status(p_workspace_id UUID, p_status TEXT)
RETURNS TEXT LANGUAGE sql STABLE PARALLEL SAFE AS $function$
SELECT CASE
- WHEN p_status IN ('backlog', 'todo', 'in_progress', 'in_review', 'done', 'blocked', 'cancelled', 'triage') THEN p_status
+ WHEN p_status IN ('backlog', 'todo', 'in_progress', 'in_review', 'done', 'blocked', 'cancelled') THEN p_status
ELSE COALESCE((SELECT CASE s.category
WHEN 'done' THEN 'done'
WHEN 'cancelled' THEN 'cancelled'
diff --git a/server/migrations/490_drop_triage_status_key_reservation.down.sql b/server/migrations/490_drop_triage_status_key_reservation.down.sql
new file mode 100644
index 0000000000..d5e5fcc728
--- /dev/null
+++ b/server/migrations/490_drop_triage_status_key_reservation.down.sql
@@ -0,0 +1,3 @@
+-- Intentionally empty. Re-adding the reservation would fail on any workspace
+-- that has since created a custom status keyed `triage`, and the server no
+-- longer reads that key as anything but an ordinary custom status.
diff --git a/server/migrations/490_drop_triage_status_key_reservation.up.sql b/server/migrations/490_drop_triage_status_key_reservation.up.sql
new file mode 100644
index 0000000000..ec47892a6f
--- /dev/null
+++ b/server/migrations/490_drop_triage_status_key_reservation.up.sql
@@ -0,0 +1,22 @@
+-- Drop the `triage` status-key reservation wherever it was applied (MUL-7400).
+--
+-- Migrations 475-477 are emptied by this change, which is enough for every
+-- database that has not run them yet — production included, since releases
+-- deploy from tags and no tag carries them. A database that did migrate off
+-- main keeps the CHECK, and would refuse a custom status keyed `triage` that
+-- the server now accepts: the reservation is gone from issuestatus, so the
+-- write would fail on the constraint instead of being answered.
+--
+-- IF EXISTS makes this a no-op on the first group and the repair on the second.
+-- Dropping a constraint is catalog-only; the timeouts bound the lock the same
+-- way migration 478 does, in the same implicit transaction the runner gives
+-- this file.
+--
+-- 476's rename is not reversed: a workspace whose custom `triage` became
+-- `triage_2` keeps it, because the replacement is an ordinary custom key its
+-- admin may already have seen, and handing `triage` back would rewrite live
+-- data a second time to undo the first.
+SET LOCAL lock_timeout = '2s';
+SET LOCAL statement_timeout = '10s';
+
+ALTER TABLE issue_status DROP CONSTRAINT IF EXISTS issue_status_key_not_reserved;