Skip to content

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

Go

feat: complete issue status category upgrade (MUL-7365 PR3) (#8466)

Jiayuan Zhangd95c20aab2f8
diff --git a/docs/issue-status-lifecycle-rollout.md b/docs/issue-status-lifecycle-rollout.md
index 8e003485e5..b1ae43e1b6 100644
--- a/docs/issue-status-lifecycle-rollout.md
+++ b/docs/issue-status-lifecycle-rollout.md
@@ -40,7 +40,7 @@ instruction to start, finish or fail an agent. The built-in platform skill and
new daemon task briefs describe this distinction. This is not a workflow engine;
PR #7990 is subsequent work, not part of this release.
-## Migration and release (MUL-7365, phase 1)
+## Migration and release (MUL-7365)
The supported upgrade entrypoint is the **matching revision's migration runner**
(`cd server && go run ./cmd/migrate up`, with the approved target DATABASE_URL).
@@ -109,12 +109,63 @@ Set workload limits from the environment's API latency, lock wait, I/O, WAL and
replication budgets. Pausing the job must leave normal reads/writes working.
Do not treat a skipped or failed batch as completion.
-**Phase 3 is separately released after verification, never triggered by the job.**
-Require zero residual old values, no old writers, correct mapping and business
-invariants, and no unfinished batches. Add strict CHECKs NOT VALID in a short
-transaction, commit, then VALIDATE in a separate transaction/file. Only then
-retire old-storage readers. Keep the audited completion evidence. Do not put
-these strict migrations into the phase-1 automatic deployment path.
+**Phase 3 uses the normal upgrade entrypoint for both SaaS and self-host.**
+There is no new environment flag, automatic maintenance worker, or manual job
+requirement for self-host. The matching container entrypoint runs migrations
+before starting the API, as before. Do not edit/replay historical 469 or delete
+its ledger entry: it may have executed or been recorded as skipped.
+
+| Migration | Work and transaction boundary |
+| --- | --- |
+| 491 | UPDATE only the six legacy spellings, including system/custom/archived rows; preserve every other field. Commit data independently of DDL. |
+| 492 | Replace both category and canonical-system CHECKs atomically, NOT VALID, with a 2s lock timeout and 10s statement timeout. |
+| 493 | Validate both CHECKs in a separate transaction under SHARE UPDATE EXCLUSIVE, allowing ordinary reads/writes. |
+| 494 | Retire the old stored `cancelled` branch of `issue_effective_status`; built-in `cancelled` identity remains. |
+
+Application catalog/recovery queries now read the four stored values directly.
+The normalization function remains for historical migration replay and job code;
+installed-client adapters and accepted category aliases remain supported.
+
+For **SaaS**, deploy the compatible PR1/PR2 revision first, replace all old
+writers, complete an **apply** job and its verification, and retain its audit
+JSON. Before releasing PR3, check the actual target database again:
+
+```sql
+-- Must return 0. Do not infer this from migration 469's ledger entry.
+SELECT count(*) AS remaining_legacy FROM issue_status
+WHERE category IN ('backlog','todo','in_progress','in_review','blocked','cancelled');
+-- Must return 0.
+SELECT count(*) AS invalid_catalog_rows FROM issue_status
+WHERE category NOT IN ('unstarted','started','done','closed')
+ OR (is_system AND (key,category) NOT IN (
+ ('backlog','unstarted'),('todo','unstarted'),('in_progress','started'),
+ ('in_review','started'),('blocked','started'),('done','done'),('cancelled','closed')));
+```
+
+Block SaaS release until both counts are zero, old writers are gone, the apply
+job is completed, and no apply work remains active. This is an operator/release
+prerequisite, not a self-host startup setting; this repository does not establish
+which external SaaS CD pipeline enforces it. Migration 491 then updates zero
+rows, although the predicate and constraint validation can still scan the table.
+Schedule validation against the target's I/O budget. Never release this revision
+to a large unconverted SaaS database: startup would perform the bulk UPDATE.
+
+For **self-host**, upgrade normally, including when skipping PR1/PR2 releases.
+491 converts the local catalog automatically, then 492–494 converge the schema.
+A fresh install follows the same path. The accepted small-database tradeoff is
+an UPDATE/validation startup window; this is not a zero-downtime guarantee for
+large self-host installations. The default Helm startup probe budget is 10
+minutes. An operator with unusually large data can use the SaaS staged path.
+
+If 492 times out, 491 stays committed and retry resumes at 492. If 493 fails,
+strict checks already protect new writes and readiness remains failed. Identify
+and stop the stale writer, repair residual values forward, and rerun the same
+runner without deleting ledger rows. All new SQL files tolerate replay after
+an uncertain ledger acknowledgement; there is no data+DDL mega-transaction.
+After success, verify both CHECKs have `convalidated=true`, residual counts are
+zero, and API readiness passes. Keep job history; phase 3 never starts a job.
+The category v1 job intentionally fails preflight after contract because it
+requires the expanded schema. Existing job records remain readable.
Release policy is fix-forward. 478's down file preserves the compatible schema;
469 already refuses reversal. Do not roll back to code that only understands one
@@ -142,7 +193,7 @@ The retained `group.kind: status_category` and compound
`secondary: status_category` protocols default to seven-value **wire buckets**.
Built-ins keep their own bucket; custom statuses use the same bucket as their
per-row wire category. Headers, counts, secondary_values and row pagination share
-that mapping, including archived statuses and mixed storage. A category grouping
+that mapping, including archived statuses. A category grouping
request can explicitly set `category_format: lifecycle` to use four buckets;
other values or use with a non-category group are rejected. Both group and row
cursors bind the category format; stale or cross-format cursors return the
@@ -166,7 +217,8 @@ will succeed, especially during the accepted mixed-version window.
- Real runner upgrade tests with pending and applied 469, 478 lock timeout,
retry/replay, unchanged system/archived rows and released DDL locks. The
historical 332-to-469 test remains as coverage of the preserved historical SQL.
-- Old/mixed/new storage matrices for seven-value legacy groups, explicit
+- Real-runner old/mixed/already-backfilled upgrade matrices; contracted-storage
+ seven-value legacy groups, explicit
four-value groups, concrete status groups, per-bucket pagination and counts;
visible parent lanes, format-bound cursors, cross-workspace isolation and GC.
- 100 historical terminal signals cannot starve a live recovery in another
diff --git a/docs/maintenance-jobs.md b/docs/maintenance-jobs.md
index f448db4137..8604fb28ce 100644
--- a/docs/maintenance-jobs.md
+++ b/docs/maintenance-jobs.md
@@ -215,9 +215,16 @@ session log. Completed/cancelled rows are retained; repeated maintenance creates
new records rather than resetting history. Down migrations intentionally retain
state and indexes. Keep the compatible backend and fix forward on failures.
-PR3 remains separate: no strict CHECK, validation DDL, legacy-reader removal,
-or wire-protocol retirement is triggered by this job. Installed-client API
-compatibility remains after backfill completion.
+PR3 is a separate release; this job never triggers schema contraction. For SaaS,
+finish the apply/verify pass before deploying PR3. Self-host upgrades do not
+require this job: migration 491 automatically converts any residual old values
+through the ordinary upgrade entrypoint. See the [release sequence](issue-status-lifecycle-rollout.md).
+
+After 492/494, the category v1 processor intentionally fails its compatibility
+preflight. Do not start/resume it on the contracted schema or weaken the
+preflight. Completed/cancelled records remain readable for audit, and the generic
+maintenance framework remains available for future processors. Installed-client
+API compatibility remains after storage contraction.
## Adding a processor
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index 7d7b2f1164..e6a576e874 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -416,8 +416,8 @@ func refuseChannelChatRouteHistoryRollbackWith(ctx context.Context, query rowQue
var upMigrationConditions = map[string]migrationCondition{
// Preserve applied history; pending 469 is superseded by the bounded expand
- // migration. Backfill is an independent operator job, never startup work.
- "469_issue_status_lifecycle_categories": skipMigration("superseded by 478 compatibility expansion; backfill runs separately (MUL-7365)"),
+ // migration. SaaS backfills separately; self-host converges in 491.
+ "469_issue_status_lifecycle_categories": skipMigration("superseded by 478 expansion and 491 convergence (MUL-7365)"),
// Current search no longer consumes an issue-description GIN. Fresh installs
// should not build the historical fallback only to retire it at migration 464.
"139_issue_description_trgm_index": skipMigration("issue description search indexes are retired by migration 464"),
diff --git a/server/cmd/migrate/status_category_contract_test.go b/server/cmd/migrate/status_category_contract_test.go
new file mode 100644
index 0000000000..f9e410369a
--- /dev/null
+++ b/server/cmd/migrate/status_category_contract_test.go
@@ -0,0 +1,175 @@
+package main
+
+import (
+ "context"
+ "os"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/issuestatus"
+)
+
+var categoryContractVersions = []string{
+ "491_issue_status_category_backfill", "492_issue_status_category_contract",
+ "493_issue_status_category_validate", "494_issue_status_category_read_contract",
+}
+
+// Exercise historical data through the real runner, rather than inserting old
+// spellings into the current (strict) application schema.
+func TestStatusCategoryContractUpgradePaths(t *testing.T) {
+ for _, path := range []string{"fresh", "applied_469", "skipped_469", "mixed", "backfilled"} {
+ t.Run(path, func(t *testing.T) {
+ f := newFixture(t)
+ pool := openTestPoolWithSearchPath(t, f.schema)
+ ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
+ defer cancel()
+ execFile := func(version string) {
+ t.Helper()
+ b, err := os.ReadFile(realMigrationFiles(t, []string{version}, "up")[0])
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := pool.Exec(ctx, string(b)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ execFile("332_issue_status")
+ if path != "fresh" {
+ for _, key := range issuestatus.Canonical() {
+ if _, err := pool.Exec(ctx, `INSERT INTO issue_status(workspace_id,key,name,category,color,is_system,position,archived_at)
+ VALUES ('00000000-0000-0000-0000-000000000001',$1,'System',$1,'#123456',true,42,NULL),
+ ('00000000-0000-0000-0000-000000000001','custom_' || $1,'Custom',$1,'#123456',false,17,now())`, key); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ opts := f.opts()
+ opts.Files = realMigrationFiles(t, []string{"469_issue_status_lifecycle_categories"}, "up")
+ if path == "applied_469" {
+ if err := runMigrations(ctx, pool, opts); err != nil {
+ t.Fatal(err)
+ }
+ }
+ opts.Conditions = conditionsForDirection("up")
+ opts.Files = realMigrationFiles(t, []string{"469_issue_status_lifecycle_categories", "478_issue_status_category_expand"}, "up")
+ if err := runMigrations(ctx, pool, opts); err != nil {
+ t.Fatal(err)
+ }
+ if path == "mixed" || path == "backfilled" {
+ if _, err := pool.Exec(ctx, `UPDATE issue_status SET category=issue_status_category(category)
+ WHERE $1 OR key IN ('todo','custom_in_review','custom_cancelled')`, path == "backfilled"); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // Include the now-valid custom key triage and an archived terminal entry.
+ if _, err := pool.Exec(ctx, `INSERT INTO issue_status(workspace_id,key,name,category,color)
+ VALUES ('00000000-0000-0000-0000-000000000001','triage','Triage','closed','#123456')`); err != nil {
+ t.Fatal(err)
+ }
+ var before string
+ if err := pool.QueryRow(ctx, `SELECT jsonb_agg(to_jsonb(s)-'category' ORDER BY key)::text FROM issue_status s`).Scan(&before); err != nil {
+ t.Fatal(err)
+ }
+ opts.Files = realMigrationFiles(t, categoryContractVersions, "up")
+ if path == "skipped_469" {
+ reader, err := pool.Begin(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reader.Rollback(context.Background())
+ if _, err := reader.Exec(ctx, "SELECT * FROM issue_status"); err != nil {
+ t.Fatal(err)
+ }
+ // A reader allows the UPDATE to commit, but blocks constraint replacement.
+ err = runMigrations(ctx, pool, opts)
+ if err == nil || !strings.Contains(err.Error(), "lock timeout") {
+ t.Fatalf("expected bounded DDL failure: %v", err)
+ }
+ assertMigrationVersionRecorded(t, ctx, pool, f.schema, categoryContractVersions[0], true)
+ assertMigrationVersionRecorded(t, ctx, pool, f.schema, categoryContractVersions[1], false)
+ var remaining int
+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM issue_status WHERE category<>issue_status_category(category)`).Scan(&remaining); err != nil || remaining != 0 {
+ t.Fatalf("data transaction did not commit independently: %d %v", remaining, err)
+ }
+ if err := reader.Rollback(ctx); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if path == "mixed" {
+ // An old writer between data and DDL must be caught by validation.
+ opts.Files = realMigrationFiles(t, categoryContractVersions[:1], "up")
+ if err := runMigrations(ctx, pool, opts); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := pool.Exec(ctx, `UPDATE issue_status SET category='cancelled' WHERE key='custom_cancelled'`); err != nil {
+ t.Fatal(err)
+ }
+ opts.Files = realMigrationFiles(t, categoryContractVersions, "up")
+ if err := runMigrations(ctx, pool, opts); err == nil || !strings.Contains(err.Error(), "violated") {
+ t.Fatalf("expected validation failure: %v", err)
+ }
+ assertMigrationVersionRecorded(t, ctx, pool, f.schema, categoryContractVersions[1], true)
+ assertMigrationVersionRecorded(t, ctx, pool, f.schema, categoryContractVersions[2], false)
+ assertMigrationVersionRecorded(t, ctx, pool, f.schema, categoryContractVersions[3], false)
+ // Fix forward after eliminating the old writer; do not erase 491.
+ execFile(categoryContractVersions[0])
+ }
+ for range 2 {
+ if err := runMigrations(ctx, pool, opts); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // Lost ledger acknowledgement: every SQL file is safe to replay.
+ for _, version := range categoryContractVersions {
+ execFile(version)
+ }
+ var after string
+ if err := pool.QueryRow(ctx, `SELECT jsonb_agg(to_jsonb(s)-'category' ORDER BY key)::text FROM issue_status s`).Scan(&after); err != nil {
+ t.Fatal(err)
+ }
+ if before != after {
+ t.Fatal("identity, labels, positions, timestamps or archival changed")
+ }
+ var validated int
+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM pg_constraint WHERE conrelid='issue_status'::regclass
+ AND conname IN ('issue_status_category_check','issue_status_system_is_canonical') AND convalidated`).Scan(&validated); err != nil || validated != 2 {
+ t.Fatalf("validated=%d: %v", validated, err)
+ }
+ for _, key := range issuestatus.Canonical() {
+ category, _ := issuestatus.CategoryForBehavior(key)
+ if path != "fresh" {
+ var count int
+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM issue_status WHERE key IN ($1,'custom_' || $1) AND category=$2`, key, category).Scan(&count); err != nil || count != 2 {
+ t.Fatalf("mapping %s: %d %v", key, count, err)
+ }
+ }
+ if key != "done" {
+ if _, err := pool.Exec(ctx, `INSERT INTO issue_status(workspace_id,key,name,category,color) VALUES (gen_random_uuid(),'invalid','Invalid',$1,'#123456')`, key); err == nil {
+ t.Fatalf("accepted old category %s", key)
+ }
+ }
+ var got string
+ if err := pool.QueryRow(ctx, `SELECT issue_effective_status('00000000-0000-0000-0000-000000000001',$1)`, key).Scan(&got); err != nil || got != key {
+ t.Fatalf("built-in %s: %s %v", key, got, err)
+ }
+ if path != "fresh" {
+ want := "custom_" + key
+ if key == "done" || key == "cancelled" {
+ want = key
+ }
+ if err := pool.QueryRow(ctx, `SELECT issue_effective_status('00000000-0000-0000-0000-000000000001',$1)`, "custom_"+key).Scan(&got); err != nil || got != want {
+ t.Fatalf("custom %s: %s %v", key, got, err)
+ }
+ }
+ }
+ var effective string
+ if err := pool.QueryRow(ctx, `SELECT issue_effective_status('00000000-0000-0000-0000-000000000001','triage')`).Scan(&effective); err != nil || effective != "cancelled" {
+ t.Fatalf("triage custom resolution: %s %v", effective, err)
+ }
+ if _, err := pool.Exec(ctx, `INSERT INTO issue_status(workspace_id,key,name,category,color,is_system) VALUES (gen_random_uuid(),'cancelled','Invalid','started','#123456',true)`); err == nil {
+ t.Fatal("accepted noncanonical system pair")
+ }
+ })
+ }
+}
diff --git a/server/internal/handler/daemon_claim_issue_status_test.go b/server/internal/handler/daemon_claim_issue_status_test.go
index 24d61f81b4..98da61a00d 100644
--- a/server/internal/handler/daemon_claim_issue_status_test.go
+++ b/server/internal/handler/daemon_claim_issue_status_test.go
@@ -28,12 +28,7 @@ func TestClaimTaskByRuntime_PopulatesIssueStatusCatalog(t *testing.T) {
createTestCustomStatus(t, "awaiting_response", "started")
createTestCustomStatus(t, "accepted", "done")
createTestCustomStatus(t, "withdrawn", "closed")
- // The catalog remains mixed until the independent backfill runs. The wire
- // contract (and its ordering) must not depend on whether a row was converted.
- dbfx.Exec(t, `UPDATE issue_status SET category = CASE key
- WHEN 'rework' THEN 'todo' WHEN 'awaiting_response' THEN 'in_review'
- WHEN 'withdrawn' THEN 'cancelled' ELSE category END
- WHERE workspace_id = $1 AND key IN ('rework', 'awaiting_response', 'withdrawn')`, testWorkspaceID)
+ // Contracted storage must retain the installed daemon wire vocabulary.
dbfx.Exec(t, `UPDATE issue_status SET description = 'Custom guidance' WHERE workspace_id = $1 AND key IN ('awaiting_response', 'accepted', 'withdrawn')`, testWorkspaceID)
// A different workspace's catalog must never enter this claim.
otherWorkspace := dbfx.Workspace(t, "Other catalog", "other-claim-catalog")
diff --git a/server/internal/handler/issue_status.go b/server/internal/handler/issue_status.go
index 98e9685759..7d1125005d 100644
--- a/server/internal/handler/issue_status.go
+++ b/server/internal/handler/issue_status.go
@@ -597,7 +597,7 @@ func (h *Handler) ReorderIssueStatuses(w http.ResponseWriter, r *http.Request) {
}
active := make([]db.IssueStatus, 0, len(catalog))
for _, entry := range catalog {
- if normalized, _ := issuestatus.ParseCategory(entry.Category); normalized == category && (req.IncludeSystem || !entry.IsSystem) {
+ if entry.Category == category && (req.IncludeSystem || !entry.IsSystem) {
active = append(active, entry)
}
}
@@ -627,7 +627,7 @@ func (h *Handler) ReorderIssueStatuses(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusForbidden, "include_system is required to reorder built-in statuses")
case entry.ArchivedAt.Valid:
writeError(w, http.StatusConflict, "archived statuses cannot be reordered")
- case normalizedStatusCategory(entry.Category) != category:
+ case entry.Category != category:
writeError(w, http.StatusBadRequest, "ids must all belong to the requested category")
default:
writeError(w, http.StatusConflict, "issue status catalog changed during reorder")
@@ -698,8 +698,3 @@ func (h *Handler) ReorderIssueStatuses(w http.ResponseWriter, r *http.Request) {
"total": len(resp),
})
}
-
-func normalizedStatusCategory(category string) string {
- normalized, _ := issuestatus.ParseCategory(category)
- return normalized
-}
diff --git a/server/internal/handler/issue_status_compatibility_test.go b/server/internal/handler/issue_status_compatibility_test.go
index c0e1f4ec86..b82a637c8b 100644
--- a/server/internal/handler/issue_status_compatibility_test.go
+++ b/server/internal/handler/issue_status_compatibility_test.go
@@ -17,8 +17,10 @@ import (
// deliberately independent of the server's current category constants.
var installedStatusBuckets = []string{"backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled"}
-func TestStatusCompatibilityMixedStorageGroupsAndPagination(t *testing.T) {
- for _, storage := range []string{"old", "mixed", "new"} {
+// Historical storage matrices are exercised by TestStatusCategoryContractUpgradePaths.
+// API assertions here run against the fully migrated production schema.
+func TestStatusCompatibilityContractedStorageGroupsAndPagination(t *testing.T) {
+ for _, storage := range []string{"contracted"} {
t.Run(storage, func(t *testing.T) {
project := dbfx.Insert(t, "project", testutil.Cols{"workspace_id": testWorkspaceID, "title": "Compatibility " + storage})
suffix := uuid.NewString()[:8]
@@ -27,9 +29,6 @@ func TestStatusCompatibilityMixedStorageGroupsAndPagination(t *testing.T) {
for i, old := range installedStatusBuckets {
category, _ := issuestatus.CategoryForBehavior(old)
stored := category
- if storage == "old" || (storage == "mixed" && i%2 == 0) {
- stored = old
- }
key := fmt.Sprintf("compat_%s_%d", suffix, i)
cols := testutil.Cols{"workspace_id": testWorkspaceID, "key": key, "name": key, "category": stored, "color": "#123456"}
if old == "cancelled" {
@@ -135,8 +134,8 @@ func TestStatusCompatibilityMixedStorageGroupsAndPagination(t *testing.T) {
func TestStatusCompatibilityCatalogWritesAndTenantIsolation(t *testing.T) {
ctx := context.Background()
key := "legacy_" + uuid.NewString()[:8]
- id := dbfx.Insert(t, "issue_status", testutil.Cols{"workspace_id": testWorkspaceID, "key": key, "name": key, "category": "in_review", "color": "#123456", "position": 99999})
- // Position allocation includes the old spelling in the same lifecycle.
+ id := dbfx.Insert(t, "issue_status", testutil.Cols{"workspace_id": testWorkspaceID, "key": key, "name": key, "category": "started", "color": "#123456", "position": 99999})
+ // Position allocation and old API inputs share the contracted lifecycle.
created, err := testHandler.Queries.CreateIssueStatusEntry(ctx, db.CreateIssueStatusEntryParams{
WorkspaceID: parseUUID(testWorkspaceID), Key: key + "_new", Name: "New", Category: "started", Color: "#123456",
})
@@ -153,7 +152,7 @@ func TestStatusCompatibilityCatalogWritesAndTenantIsolation(t *testing.T) {
}
ids := []string{}
for _, entry := range catalog {
- if normalizedStatusCategory(entry.Category) == "started" && !entry.IsSystem {
+ if entry.Category == "started" && !entry.IsSystem {
ids = append(ids, uuid.UUID(entry.ID.Bytes).String())
}
}
@@ -161,11 +160,11 @@ func TestStatusCompatibilityCatalogWritesAndTenantIsolation(t *testing.T) {
var stored string
dbfx.QueryRow(t, "SELECT category FROM issue_status WHERE id=$1", id).Scan(&stored)
if stored != "started" {
- t.Fatalf("reorder retained old category %s", stored)
+ t.Fatalf("reorder changed lifecycle category %s", stored)
}
foreign := dbfx.Workspace(t, "Other", "compat-"+uuid.NewString()[:8])
foreignKey := "foreign_" + uuid.NewString()[:8]
- dbfx.Insert(t, "issue_status", testutil.Cols{"workspace_id": foreign, "key": foreignKey, "name": "Foreign", "category": "cancelled", "color": "#123456"})
+ dbfx.Insert(t, "issue_status", testutil.Cols{"workspace_id": foreign, "key": foreignKey, "name": "Foreign", "category": "closed", "color": "#123456"})
keys, err := issuestatus.ExpandCategories(ctx, testHandler.Queries, parseUUID(testWorkspaceID), []string{"closed"})
if err != nil || slices.Contains(keys, foreignKey) {
t.Fatalf("cross-workspace filter expansion: %v, %v", keys, err)
@@ -175,10 +174,10 @@ func TestStatusCompatibilityCatalogWritesAndTenantIsolation(t *testing.T) {
}
}
-func TestStatusCompatibilityGCBeforeAndAfterBackfill(t *testing.T) {
+func TestStatusCompatibilityGCAfterContract(t *testing.T) {
for _, old := range installedStatusBuckets {
category, _ := issuestatus.CategoryForBehavior(old)
- for _, stored := range []string{old, category} {
+ for _, stored := range []string{category} {
t.Run(old+"/"+stored, func(t *testing.T) {
key := "gc_" + uuid.NewString()[:8]
dbfx.Insert(t, "issue_status", testutil.Cols{"workspace_id": testWorkspaceID, "key": key, "name": key, "category": stored, "color": "#123456"})
@@ -228,7 +227,7 @@ func TestStatusCompatibilityCursorRejectsDifferentCategoryFormat(t *testing.T) {
func TestStatusCompatibilityParentLaneUsesExpandedVisibleKeys(t *testing.T) {
project := dbfx.Insert(t, "project", testutil.Cols{"workspace_id": testWorkspaceID, "title": "Category parent lane"})
key := "child_" + uuid.NewString()[:8]
- dbfx.Insert(t, "issue_status", testutil.Cols{"workspace_id": testWorkspaceID, "key": key, "name": key, "category": "in_review", "color": "#123456"})
+ dbfx.Insert(t, "issue_status", testutil.Cols{"workspace_id": testWorkspaceID, "key": key, "name": key, "category": "started", "color": "#123456"})
parent := dbfx.Issue(t, "Parent", testutil.Cols{"project_id": project, "status": "in_progress"})
dbfx.Issue(t, "Child", testutil.Cols{"project_id": project, "status": key, "parent_issue_id": parent})
group := issueTableGroupSpec{Kind: "compound", Primary: "parent", Secondary: "status_category", SecondaryValues: []string{"in_progress"}}
diff --git a/server/internal/issuestatus/issuestatus.go b/server/internal/issuestatus/issuestatus.go
index e98f96f0bc..e24f6d0d24 100644
--- a/server/internal/issuestatus/issuestatus.go
+++ b/server/internal/issuestatus/issuestatus.go
@@ -165,7 +165,7 @@ func BehaviorsForCategory(category string) []string {
}
}
-// ParseCategory normalizes API spellings and pre-backfill stored categories.
+// ParseCategory normalizes API spellings from installed and current clients.
func ParseCategory(value string) (string, bool) {
if IsCategory(value) {
return value, true
@@ -207,7 +207,6 @@ func WireCategory(status, category string) string {
// Custom statuses inherit only terminal lifecycle semantics, not parked, review,
// blocked or active-agent recovery behavior. Nonterminal keys stay distinct.
func customBehavior(status, category string) string {
- category, _ = ParseCategory(category)
switch category {
case CategoryDone:
return Done
@@ -453,8 +452,8 @@ func categoryAndName(ctx context.Context, q Querier, workspaceID pgtype.UUID, st
if err != nil {
return "", "", fmt.Errorf("resolve issue status %q category: %w", status, err)
}
- category, ok := ParseCategory(entry.Category)
- if !ok {
+ category := entry.Category
+ if !IsCategory(category) {
return "", entry.Name, fmt.Errorf("invalid category %q for issue status %q", entry.Category, status)
}
return category, entry.Name, nil
@@ -617,7 +616,7 @@ func (r *Resolver) load(ctx context.Context, q Querier) {
r.categories = make(map[string]string, len(entries))
r.names = make(map[string]string, len(entries))
for _, e := range entries {
- r.categories[e.Key], _ = ParseCategory(e.Category)
+ r.categories[e.Key] = e.Category
r.names[e.Key] = e.Name
}
}
@@ -768,8 +767,8 @@ func CustomKeyCategories(ctx context.Context, q Querier, workspaceID pgtype.UUID
}
out := make(map[string]string, len(entries))
for _, e := range entries {
- category, ok := ParseCategory(e.Category)
- if IsBuiltIn(e.Key) || !ok {
+ category := e.Category
+ if IsBuiltIn(e.Key) || !IsCategory(category) {
continue
}
out[e.Key] = category
diff --git a/server/internal/issuestatus/mixed_categories_test.go b/server/internal/issuestatus/mixed_categories_test.go
index b27ffa32c0..dba1beca1a 100644
--- a/server/internal/issuestatus/mixed_categories_test.go
+++ b/server/internal/issuestatus/mixed_categories_test.go
@@ -7,14 +7,15 @@ import (
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
-func TestPreBackfillCategoriesPreserveLifecycleAndWire(t *testing.T) {
+func TestConvertedCategoriesPreserveLifecycleAndWire(t *testing.T) {
ctx := context.Background()
for _, old := range Canonical() {
t.Run(old, func(t *testing.T) {
category, _ := CategoryForBehavior(old)
key := "custom_" + old
- // Do not use custom(): that fixture already normalizes its input.
- q := newFakeQuerier(db.IssueStatus{Key: key, Category: old, WorkspaceID: testWorkspace})
+ // Real-runner tests prove old storage converts to this lifecycle.
+ // API adapters below must still accept the original spelling.
+ q := newFakeQuerier(db.IssueStatus{Key: key, Category: category, WorkspaceID: testWorkspace})
behavior := key
if old == Done || old == Cancelled {
behavior = old
diff --git a/server/internal/maintenance/job_test.go b/server/internal/maintenance/job_test.go
index 6b208882dc..a74d9ca6b9 100644
--- a/server/internal/maintenance/job_test.go
+++ b/server/internal/maintenance/job_test.go
@@ -554,3 +554,31 @@ func TestSharedTableSupportsDifferentProcessorAndCursor(t *testing.T) {
t.Fatal("other job was modified")
}
}
+
+func TestContractPreservesAuditAndRejectsCategoryProcessor(t *testing.T) {
+ pool, s := fixture(t)
+ seed(t, pool, "old")
+ ctx := context.Background()
+ completed := finish(t, s, create(t, s, false))
+ pending := create(t, s, false)
+ for _, name := range []string{"491_issue_status_category_backfill", "492_issue_status_category_contract", "493_issue_status_category_validate", "494_issue_status_category_read_contract"} {
+ body, err := os.ReadFile(filepath.Join("..", "..", "migrations", name+".up.sql"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := pool.Exec(ctx, string(body)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ audit, err := s.Get(ctx, completed.ID)
+ if err != nil || string(audit.Result) != string(completed.Result) || audit.Status != "completed" || audit.Revision != completed.Revision {
+ t.Fatalf("audit changed: %+v %v", audit, err)
+ }
+ if _, err := s.Create(ctx, request(true)); err == nil {
+ t.Fatal("contracted schema accepted v1 category job")
+ }
+ failed, err := s.Mutate(ctx, pending.ID, pending.Revision, "advance")
+ if err == nil || failed.Status != "paused" {
+ t.Fatalf("pre-contract pending job did not fail closed: %+v %v", failed, err)
+ }
+}
diff --git a/server/internal/service/delegated_failure_mixed_categories_test.go b/server/internal/service/delegated_failure_mixed_categories_test.go
index 0bb8120eb5..68b8e45ae5 100644
--- a/server/internal/service/delegated_failure_mixed_categories_test.go
+++ b/server/internal/service/delegated_failure_mixed_categories_test.go
@@ -8,12 +8,12 @@ import (
"github.com/multica-ai/multica/server/internal/testutil"
)
-func TestPendingRecoveryLegacyTerminalHistoryDoesNotStarveAnotherWorkspace(t *testing.T) {
+func TestPendingRecoveryConvertedTerminalHistoryDoesNotStarveAnotherWorkspace(t *testing.T) {
ctx := context.Background()
history, historyService := seedDelegatedFailureFixture(t)
historyRows := testutil.New(history.pool, history.workspaceID, history.userID)
historyRows.Insert(t, "issue_status", testutil.Cols{
- "workspace_id": history.workspaceID, "key": "legacy_closed", "name": "Closed", "category": "cancelled", "color": "#123456",
+ "workspace_id": history.workspaceID, "key": "legacy_closed", "name": "Closed", "category": "closed", "color": "#123456",
})
signal := func(f *delegatedFailureFixture, svc *TaskService) pgtype.UUID {
t.Helper()
diff --git a/server/internal/service/delegated_failure_recovery_test.go b/server/internal/service/delegated_failure_recovery_test.go
index ed8be23e78..ca081eba85 100644
--- a/server/internal/service/delegated_failure_recovery_test.go
+++ b/server/internal/service/delegated_failure_recovery_test.go
@@ -589,8 +589,8 @@ func TestPendingDelegatedFailureSweepPrefiltersUnresumableSourceIssues(t *testin
{name: "built-in backlog", status: "backlog"},
{name: "built-in done", status: "done"},
{name: "custom closed-category status", status: "shelved", customCategory: "closed"},
- {name: "pre-backfill cancelled category", status: "legacy_shelved", customCategory: "cancelled"},
- {name: "pre-backfill custom backlog stays live", status: "legacy_later", customCategory: "backlog", wantScanned: true},
+ {name: "converted cancelled category", status: "legacy_shelved", customCategory: "closed"},
+ {name: "converted custom backlog stays live", status: "legacy_later", customCategory: "unstarted", wantScanned: true},
{name: "source issue still live", status: "in_progress", wantScanned: true},
} {
t.Run(tc.name, func(t *testing.T) {
diff --git a/server/migrations/491_issue_status_category_backfill.down.sql b/server/migrations/491_issue_status_category_backfill.down.sql
new file mode 100644
index 0000000000..41d6171c29
--- /dev/null
+++ b/server/migrations/491_issue_status_category_backfill.down.sql
@@ -0,0 +1,2 @@
+-- Lifecycle convergence is forward-only; never reopen legacy writes.
+DO $$ BEGIN RAISE EXCEPTION 'MUL-7365 is forward-only; apply a corrective migration'; END $$;
diff --git a/server/migrations/491_issue_status_category_backfill.up.sql b/server/migrations/491_issue_status_category_backfill.up.sql
new file mode 100644
index 0000000000..a1dfc1663f
--- /dev/null
+++ b/server/migrations/491_issue_status_category_backfill.up.sql
@@ -0,0 +1,6 @@
+-- Self-host upgrades converge automatically. SaaS must finish the bounded
+-- maintenance job BEFORE deploying this revision, so this updates zero rows.
+-- Keep data work separate from the ACCESS EXCLUSIVE constraint transaction.
+UPDATE issue_status
+SET category = issue_status_category(category)
+WHERE category IN ('backlog', 'todo', 'in_progress', 'in_review', 'blocked', 'cancelled');
diff --git a/server/migrations/492_issue_status_category_contract.down.sql b/server/migrations/492_issue_status_category_contract.down.sql
new file mode 100644
index 0000000000..41d6171c29
--- /dev/null
+++ b/server/migrations/492_issue_status_category_contract.down.sql
@@ -0,0 +1,2 @@
+-- Lifecycle convergence is forward-only; never reopen legacy writes.
+DO $$ BEGIN RAISE EXCEPTION 'MUL-7365 is forward-only; apply a corrective migration'; END $$;
diff --git a/server/migrations/492_issue_status_category_contract.up.sql b/server/migrations/492_issue_status_category_contract.up.sql
new file mode 100644
index 0000000000..cd24d72cdd
--- /dev/null
+++ b/server/migrations/492_issue_status_category_contract.up.sql
@@ -0,0 +1,18 @@
+-- All writers must already emit lifecycle categories. NOT VALID avoids a
+-- table scan while holding ACCESS EXCLUSIVE; 493 validates after commit.
+SET LOCAL lock_timeout = '2s';
+SET LOCAL statement_timeout = '10s';
+
+ALTER TABLE issue_status
+ DROP CONSTRAINT IF EXISTS issue_status_category_check,
+ DROP CONSTRAINT IF EXISTS issue_status_system_is_canonical,
+ ADD CONSTRAINT issue_status_category_check CHECK (
+ category IN ('unstarted', 'started', 'done', 'closed')
+ ) NOT VALID,
+ ADD CONSTRAINT issue_status_system_is_canonical CHECK (
+ NOT is_system OR (key, category) IN (
+ ('backlog', 'unstarted'), ('todo', 'unstarted'),
+ ('in_progress', 'started'), ('in_review', 'started'),
+ ('blocked', 'started'), ('done', 'done'), ('cancelled', 'closed')
+ )
+ ) NOT VALID;
diff --git a/server/migrations/493_issue_status_category_validate.down.sql b/server/migrations/493_issue_status_category_validate.down.sql
new file mode 100644
index 0000000000..41d6171c29
--- /dev/null
+++ b/server/migrations/493_issue_status_category_validate.down.sql
@@ -0,0 +1,2 @@
+-- Lifecycle convergence is forward-only; never reopen legacy writes.
+DO $$ BEGIN RAISE EXCEPTION 'MUL-7365 is forward-only; apply a corrective migration'; END $$;
diff --git a/server/migrations/493_issue_status_category_validate.up.sql b/server/migrations/493_issue_status_category_validate.up.sql
new file mode 100644
index 0000000000..1db6e3d7d8
--- /dev/null
+++ b/server/migrations/493_issue_status_category_validate.up.sql
@@ -0,0 +1,6 @@
+-- A separate transaction scans under SHARE UPDATE EXCLUSIVE, allowing normal
+-- reads/writes. No ACCESS EXCLUSIVE operation belongs in this file.
+SET LOCAL lock_timeout = '2s';
+ALTER TABLE issue_status
+ VALIDATE CONSTRAINT issue_status_category_check,
+ VALIDATE CONSTRAINT issue_status_system_is_canonical;
diff --git a/server/migrations/494_issue_status_category_read_contract.down.sql b/server/migrations/494_issue_status_category_read_contract.down.sql
new file mode 100644
index 0000000000..41d6171c29
--- /dev/null
+++ b/server/migrations/494_issue_status_category_read_contract.down.sql
@@ -0,0 +1,2 @@
+-- Lifecycle convergence is forward-only; never reopen legacy writes.
+DO $$ BEGIN RAISE EXCEPTION 'MUL-7365 is forward-only; apply a corrective migration'; END $$;
diff --git a/server/migrations/494_issue_status_category_read_contract.up.sql b/server/migrations/494_issue_status_category_read_contract.up.sql
new file mode 100644
index 0000000000..3ed0bf0606
--- /dev/null
+++ b/server/migrations/494_issue_status_category_read_contract.up.sql
@@ -0,0 +1,22 @@
+-- Storage is now validated. Keep built-in identity (including cancelled) and
+-- resolve archived custom terminal statuses; triage remains a custom key.
+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$;
+-- Retain issue_status_category for historical migration replay and maintenance
+-- audit tooling; application queries no longer normalize stored categories.
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 43b0e9d922..1871999886 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -5767,7 +5767,7 @@ WHERE recovery.author_type = 'system'
WHEN source_issue.status IN ('in_progress', 'in_review', 'blocked') THEN 'started'
WHEN source_issue.status = 'done' THEN 'done'
WHEN source_issue.status = 'cancelled' THEN 'closed'
- ELSE issue_status_category(source_status.category)
+ ELSE source_status.category
END IN ('unstarted', 'started')
AND source_agent.archived_at IS NULL
AND source_agent.runtime_id IS NOT NULL
diff --git a/server/pkg/db/generated/issue_status.sql.go b/server/pkg/db/generated/issue_status.sql.go
index 7cc6dbe271..fee3f783ba 100644
--- a/server/pkg/db/generated/issue_status.sql.go
+++ b/server/pkg/db/generated/issue_status.sql.go
@@ -13,7 +13,6 @@ import (
const archiveIssueStatusEntry = `-- name: ArchiveIssueStatusEntry :one
UPDATE issue_status SET
- category = issue_status_category(category),
archived_at = now(),
updated_at = now()
WHERE id = $1::uuid
@@ -88,7 +87,7 @@ VALUES (
COALESCE(
(SELECT MAX(position) + 1 FROM issue_status
WHERE workspace_id = $1::uuid
- AND issue_status_category(category) = $5::text),
+ AND category = $5::text),
0
)
)
@@ -213,7 +212,7 @@ func (q *Queries) GetIssueStatusEntryByKey(ctx context.Context, arg GetIssueStat
const listActiveCustomIssueStatusEntries = `-- name: ListActiveCustomIssueStatusEntries :many
SELECT id, workspace_id, key, name, description, category, color, is_system, position, archived_at, created_at, updated_at, icon FROM issue_status
WHERE workspace_id = $1::uuid
- AND issue_status_category(category) = $2::text
+ AND category = $2::text
AND is_system = FALSE
AND archived_at IS NULL
ORDER BY position, key
@@ -266,7 +265,7 @@ SELECT id, workspace_id, key, name, description, category, color, is_system, pos
WHERE workspace_id = $1::uuid
AND ($2::bool OR archived_at IS NULL)
ORDER BY
- CASE issue_status_category(category) WHEN 'unstarted' THEN 0 WHEN 'started' THEN 1 WHEN 'done' THEN 2 WHEN 'closed' THEN 3 ELSE 4 END,
+ CASE category WHEN 'unstarted' THEN 0 WHEN 'started' THEN 1 WHEN 'done' THEN 2 WHEN 'closed' THEN 3 ELSE 4 END,
position,
CASE WHEN is_system THEN 0 ELSE 1 END,
CASE key
@@ -326,7 +325,7 @@ func (q *Queries) ListIssueStatusEntries(ctx context.Context, arg ListIssueStatu
const listIssueStatusKeysByCategories = `-- name: ListIssueStatusKeysByCategories :many
SELECT key FROM issue_status
WHERE workspace_id = $1::uuid
- AND issue_status_category(category) = ANY($2::text[])
+ AND category = ANY($2::text[])
`
type ListIssueStatusKeysByCategoriesParams struct {
@@ -393,8 +392,7 @@ func (q *Queries) LockIssueStatusCatalogShared(ctx context.Context, workspaceID
const reorderIssueStatusEntries = `-- name: ReorderIssueStatusEntries :execrows
UPDATE issue_status s
-SET category = issue_status_category(s.category),
- position = ($1::float8[])[v.ordinality],
+SET position = ($1::float8[])[v.ordinality],
updated_at = now()
FROM unnest($4::uuid[]) WITH ORDINALITY AS v(id, ordinality)
WHERE s.id = v.id
@@ -457,7 +455,6 @@ func (q *Queries) SeedIssueStatusEntries(ctx context.Context, workspaceID pgtype
const updateIssueStatusEntry = `-- name: UpdateIssueStatusEntry :one
UPDATE issue_status SET
- category = issue_status_category(category),
name = COALESCE($1, name),
description = COALESCE($2, description),
color = COALESCE($3, color),
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index e36577fd1d..7e28bf7a52 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -2156,7 +2156,7 @@ WHERE recovery.author_type = 'system'
WHEN source_issue.status IN ('in_progress', 'in_review', 'blocked') THEN 'started'
WHEN source_issue.status = 'done' THEN 'done'
WHEN source_issue.status = 'cancelled' THEN 'closed'
- ELSE issue_status_category(source_status.category)
+ ELSE source_status.category
END IN ('unstarted', 'started')
AND source_agent.archived_at IS NULL
AND source_agent.runtime_id IS NOT NULL
diff --git a/server/pkg/db/queries/issue_status.sql b/server/pkg/db/queries/issue_status.sql
index 110f6b8ab8..dea2874044 100644
--- a/server/pkg/db/queries/issue_status.sql
+++ b/server/pkg/db/queries/issue_status.sql
@@ -24,7 +24,7 @@ SELECT * FROM issue_status
WHERE workspace_id = sqlc.arg('workspace_id')::uuid
AND (sqlc.arg('include_archived')::bool OR archived_at IS NULL)
ORDER BY
- CASE issue_status_category(category) WHEN 'unstarted' THEN 0 WHEN 'started' THEN 1 WHEN 'done' THEN 2 WHEN 'closed' THEN 3 ELSE 4 END,
+ CASE category WHEN 'unstarted' THEN 0 WHEN 'started' THEN 1 WHEN 'done' THEN 2 WHEN 'closed' THEN 3 ELSE 4 END,
position,
CASE WHEN is_system THEN 0 ELSE 1 END,
CASE key
@@ -64,7 +64,7 @@ VALUES (
COALESCE(
(SELECT MAX(position) + 1 FROM issue_status
WHERE workspace_id = sqlc.arg('workspace_id')::uuid
- AND issue_status_category(category) = sqlc.arg('category')::text),
+ AND category = sqlc.arg('category')::text),
0
)
)
@@ -75,7 +75,6 @@ RETURNING *;
-- The is_system guard is what enforces "built-in name and color are locked" at
-- the storage layer, so a handler bug cannot rename a built-in.
UPDATE issue_status SET
- category = issue_status_category(category),
name = COALESCE(sqlc.narg('name'), name),
description = COALESCE(sqlc.narg('description'), description),
color = COALESCE(sqlc.narg('color'), color),
@@ -96,7 +95,6 @@ RETURNING *;
-- it — Effective ignores archived_at, so their behavior is unchanged — while
-- Resolve rejects it, so nothing new can be assigned to it.
UPDATE issue_status SET
- category = issue_status_category(category),
archived_at = now(),
updated_at = now()
WHERE id = sqlc.arg('id')::uuid
@@ -144,7 +142,7 @@ SELECT pg_advisory_xact_lock_shared(hashtextextended(sqlc.arg('workspace_id')::u
-- still appear in their category's column.
SELECT key FROM issue_status
WHERE workspace_id = sqlc.arg('workspace_id')::uuid
- AND issue_status_category(category) = ANY(sqlc.arg('categories')::text[]);
+ AND category = ANY(sqlc.arg('categories')::text[]);
-- name: ListActiveCustomIssueStatusEntries :many
-- One category's ACTIVE custom statuses — the exact set a reorder must cover.
@@ -152,7 +150,7 @@ WHERE workspace_id = sqlc.arg('workspace_id')::uuid
-- archived concurrently cannot slip in or out between validation and write.
SELECT * FROM issue_status
WHERE workspace_id = sqlc.arg('workspace_id')::uuid
- AND issue_status_category(category) = sqlc.arg('category')::text
+ AND category = sqlc.arg('category')::text
AND is_system = FALSE
AND archived_at IS NULL
ORDER BY position, key;
@@ -166,8 +164,7 @@ ORDER BY position, key;
-- Legacy custom-only callers preserve the positions occupied by custom rows.
-- Archived rows remain frozen.
UPDATE issue_status s
-SET category = issue_status_category(s.category),
- position = (sqlc.arg('positions')::float8[])[v.ordinality],
+SET position = (sqlc.arg('positions')::float8[])[v.ordinality],
updated_at = now()
FROM unnest(sqlc.arg('ids')::uuid[]) WITH ORDINALITY AS v(id, ordinality)
WHERE s.id = v.id