Skip to content

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

Go

MUL-5983 fix(workspace): stop workspace delete from hanging on advisory lock 4246 (#6710)

Bohan Jiang6bce42b84a50
diff --git a/server/internal/handler/resource_label_cascade_test.go b/server/internal/handler/resource_label_cascade_test.go
index 8c58e3fc3d..5e4d170693 100644
--- a/server/internal/handler/resource_label_cascade_test.go
+++ b/server/internal/handler/resource_label_cascade_test.go
@@ -5,9 +5,9 @@ import (
"net/http"
"net/http/httptest"
"testing"
+ "time"
"github.com/google/uuid"
- "github.com/jackc/pgx/v5"
)
// Resource-label junction tables (agent_to_label / skill_to_label) deliberately
@@ -290,22 +290,6 @@ func TestDeleteWorkspace_CleansResourceLabelAssignments(t *testing.T) {
}
}
-type lockTimeoutTxStarter struct {
- delegate txStarter
-}
-
-func (s lockTimeoutTxStarter) Begin(ctx context.Context) (pgx.Tx, error) {
- tx, err := s.delegate.Begin(ctx)
- if err != nil {
- return nil, err
- }
- if _, err := tx.Exec(ctx, `SET LOCAL lock_timeout = '100ms'`); err != nil {
- _ = tx.Rollback(ctx)
- return nil, err
- }
- return tx, nil
-}
-
// TestDeleteWorkspace_RollsBackResourceLabelCleanup verifies the resource-label
// sweep and the later administration cleanup share one transaction. Locking the
// workspace's member row makes that late step time out; both junction rows must
@@ -315,6 +299,9 @@ func TestDeleteWorkspace_RollsBackResourceLabelCleanup(t *testing.T) {
t.Skip("database not available")
}
ctx := context.Background()
+ // The teardown transaction sets its own lock_timeout (MUL-5983); shorten
+ // it so the blocked administration step fails while the test is young.
+ setWorkspaceDeleteLockTimeoutForTest(t, 100*time.Millisecond)
wsID, agentID, skillID := seedWorkspaceResourceLabelFixture(t, ctx, "handler-tests-delete-labels-rollback")
blocker, err := testPool.Begin(ctx)
@@ -328,15 +315,14 @@ func TestDeleteWorkspace_RollsBackResourceLabelCleanup(t *testing.T) {
t.Fatalf("lock workspace member: %v", err)
}
- handler := *testHandler
- handler.TxStarter = lockTimeoutTxStarter{delegate: testHandler.TxStarter}
-
w := httptest.NewRecorder()
req := newRequest("DELETE", "/api/workspaces/"+wsID, nil)
req = withURLParam(req, "id", wsID)
- handler.DeleteWorkspace(w, req)
- if w.Code != http.StatusInternalServerError {
- t.Fatalf("DeleteWorkspace: expected 500, got %d: %s", w.Code, w.Body.String())
+ testHandler.DeleteWorkspace(w, req)
+ // A lock the teardown cannot get is transient, so the handler reports it
+ // as a retryable 503 rather than a generic failure.
+ if w.Code != http.StatusServiceUnavailable {
+ t.Fatalf("DeleteWorkspace: expected 503, got %d: %s", w.Code, w.Body.String())
}
if err := blocker.Rollback(ctx); err != nil {
t.Fatalf("release member blocker: %v", err)
diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.go
index bf1638c353..db30bb39fd 100644
--- a/server/internal/handler/workspace.go
+++ b/server/internal/handler/workspace.go
@@ -2,13 +2,16 @@ package handler
import (
"encoding/json"
+ "errors"
"fmt"
"log/slog"
"net/http"
"regexp"
"strings"
+ "time"
"github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/logger"
@@ -729,6 +732,69 @@ func (h *Handler) LeaveWorkspace(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}
+// workspaceDeleteLockTimeout bounds every lock wait inside the workspace
+// teardown transaction.
+//
+// The teardown waits on three kinds of lock: the workspace row (FOR UPDATE),
+// every chat_session row in the workspace (FOR UPDATE), and the global
+// advisory lock 4246 that serialises it against the task_usage_hourly rollup.
+// The advisory lock is the dangerous one — it is global and batch-held. A
+// rollup tick may hold it for as long as its 25 min scheduler RunTimeout, the
+// backfill commands (cmd/backfill_task_usage_hourly, cmd/backfill_codex_usage_cache)
+// hold it for an entire run, and before migration 272 a tick whose query was
+// cancelled leaked it for the remaining life of its pooled connection.
+//
+// Waiting on that lock without a cap is what the user sees as "delete does
+// nothing": the request never returns, and no layer above it times out — the
+// browser/Electron fetch in packages/core/api/client.ts has no deadline and
+// the delete dialog stays in its "Deleting…" state forever (MUL-5983). A
+// bounded wait turns the same contention into a retryable error.
+//
+// 10 s is far above the millisecond-scale waits an uncontended teardown sees,
+// and short enough to fail while the user is still watching the dialog.
+const workspaceDeleteLockTimeout = 10 * time.Second
+
+// workspaceDeleteLockTimeoutOverride, when non-zero, replaces
+// workspaceDeleteLockTimeout for the duration of a test. Never read outside
+// effectiveWorkspaceDeleteLockTimeout — see workspace_delete_lock_test.go.
+var workspaceDeleteLockTimeoutOverride time.Duration
+
+func effectiveWorkspaceDeleteLockTimeout() time.Duration {
+ if workspaceDeleteLockTimeoutOverride > 0 {
+ return workspaceDeleteLockTimeoutOverride
+ }
+ return workspaceDeleteLockTimeout
+}
+
+// isLockTimeout reports whether err is Postgres' lock_not_available
+// (SQLSTATE 55P03), which is what `SET LOCAL lock_timeout` raises when a lock
+// wait exceeds its budget. It says nothing about the workspace itself: the row
+// is untouched and the caller can retry once the other holder is done.
+func isLockTimeout(err error) bool {
+ if err == nil {
+ return false
+ }
+ var pgErr *pgconn.PgError
+ if errors.As(err, &pgErr) {
+ return pgErr.Code == "55P03"
+ }
+ return false
+}
+
+// failWorkspaceDelete logs a failed teardown step and writes the response for
+// it. A lock timeout is transient and retryable, so it answers 503 with a
+// message the delete dialog can show; every other failure stays a 500.
+func failWorkspaceDelete(w http.ResponseWriter, r *http.Request, workspaceID, step string, err error) {
+ attrs := append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID, "step", step)
+ if isLockTimeout(err) {
+ slog.Warn("workspace delete blocked by lock timeout", attrs...)
+ writeError(w, http.StatusServiceUnavailable, "workspace deletion is temporarily blocked by another operation, please try again")
+ return
+ }
+ slog.Warn("workspace delete step failed", attrs...)
+ writeError(w, http.StatusInternalServerError, "failed to delete workspace")
+}
+
func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {
workspaceID := workspaceIDFromURL(r, "id")
@@ -782,15 +848,23 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {
defer tx.Rollback(r.Context())
qtx := h.Queries.WithTx(tx)
+ // SET LOCAL is transaction-scoped, so pgxpool hands this connection back
+ // out with the default (unbounded) lock_timeout after COMMIT / ROLLBACK.
+ // It caps waiting for a lock, not the teardown work itself — deleting a
+ // large workspace is allowed to take as long as it takes.
+ lockTimeoutMs := int(effectiveWorkspaceDeleteLockTimeout() / time.Millisecond)
+ if _, err := tx.Exec(r.Context(), fmt.Sprintf("SET LOCAL lock_timeout = %d", lockTimeoutMs)); err != nil {
+ failWorkspaceDelete(w, r, workspaceID, "set lock timeout", err)
+ return
+ }
+
if _, err := qtx.LockWorkspaceForDelete(r.Context(), requester.WorkspaceID); err != nil {
- slog.Warn("lock workspace for delete failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)
- writeError(w, http.StatusInternalServerError, "failed to delete workspace")
+ failWorkspaceDelete(w, r, workspaceID, "lock workspace", err)
return
}
if _, err := qtx.LockChatSessionsByWorkspace(r.Context(), requester.WorkspaceID); err != nil {
- slog.Warn("lock workspace chat sessions failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)
- writeError(w, http.StatusInternalServerError, "failed to delete workspace")
+ failWorkspaceDelete(w, r, workspaceID, "lock chat sessions", err)
return
}
@@ -817,7 +891,9 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {
{
// This is the first stage that touches usage rollups. Keep the
// global rollup lock out of relationship preparation so unrelated
- // workspaces skip the shortest possible rollup window.
+ // workspaces skip the shortest possible rollup window. This wait
+ // is bounded by workspaceDeleteLockTimeout — 4246 is held by
+ // batch jobs, so an unbounded wait here is what hangs the delete.
name: "lock task usage rollup",
run: func() error { return qtx.LockTaskUsageRollupForWorkspaceDelete(ctx) },
},
@@ -891,13 +967,7 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {
}
for _, step := range deleteSteps {
if err := step.run(); err != nil {
- slog.Warn("workspace delete step failed", append(
- logger.RequestAttrs(r),
- "error", err,
- "workspace_id", workspaceID,
- "step", step.name,
- )...)
- writeError(w, http.StatusInternalServerError, "failed to delete workspace")
+ failWorkspaceDelete(w, r, workspaceID, step.name, err)
return
}
}
diff --git a/server/internal/handler/workspace_delete_lock_test.go b/server/internal/handler/workspace_delete_lock_test.go
new file mode 100644
index 0000000000..f4982a4248
--- /dev/null
+++ b/server/internal/handler/workspace_delete_lock_test.go
@@ -0,0 +1,177 @@
+package handler
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+ "testing"
+ "time"
+)
+
+// setWorkspaceDeleteLockTimeoutForTest is a package-private hook used only by
+// the tests below to keep them fast.
+func setWorkspaceDeleteLockTimeoutForTest(t *testing.T, v time.Duration) {
+ t.Helper()
+ workspaceDeleteLockTimeoutOverride = v
+ t.Cleanup(func() { workspaceDeleteLockTimeoutOverride = 0 })
+}
+
+// TestDeleteWorkspace_FailsFastWhenRollupLockHeld is the regression test for
+// MUL-5983: "clicking delete workspace does nothing".
+//
+// The teardown transaction takes global advisory lock 4246 so the
+// task_usage_hourly rollup cannot write aggregates for a workspace that is
+// being torn down. That lock is batch-held — a rollup tick, a backfill run, or
+// (before migration 272) a cancelled tick that leaked it — and nothing above
+// this handler has a deadline: the desktop client's fetch has no timeout, so
+// an unbounded wait leaves the delete dialog spinning on "Deleting…" until the
+// app is force quit, and the workspace is never deleted.
+//
+// With SET LOCAL lock_timeout in place the same contention has to surface as a
+// bounded, retryable 503 while the workspace stays intact.
+func TestDeleteWorkspace_FailsFastWhenRollupLockHeld(t *testing.T) {
+ if testPool == nil {
+ t.Skip("DATABASE_URL not set; skipping live-Postgres workspace delete lock test")
+ }
+ ctx := context.Background()
+
+ // Taking 4246 by hand is exactly what the rollup family's cross-binary
+ // guard exists to serialise: internal/scheduler runs in parallel against
+ // the same database, and its own 4246 tests read the lock's state (MUL-3980).
+ lockRollupSingleton(t)
+
+ setWorkspaceDeleteLockTimeoutForTest(t, 500*time.Millisecond)
+
+ // Hold 4246 on a pinned connection for the duration of the request, the
+ // way a running rollup tick (or a leaked one) holds it in production.
+ holder, err := testPool.Acquire(ctx)
+ if err != nil {
+ t.Fatalf("acquire advisory lock holder: %v", err)
+ }
+ if _, err := holder.Exec(ctx, `SELECT pg_advisory_lock(4246)`); err != nil {
+ holder.Release()
+ t.Fatalf("hold advisory lock 4246: %v", err)
+ }
+ // Idempotent: the deadline branch below releases the holder early to
+ // unblock the handler, and the defer still runs afterwards. A second
+ // Exec/Release on a returned pgxpool connection panics, which would
+ // replace the assertion failure with a stack trace.
+ var releaseOnce sync.Once
+ releaseHolder := func() {
+ releaseOnce.Do(func() {
+ _, _ = holder.Exec(context.Background(), `SELECT pg_advisory_unlock(4246)`)
+ holder.Release()
+ })
+ }
+ defer releaseHolder()
+
+ const slug = "handler-tests-delete-lock"
+ _, _ = testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, slug)
+
+ var wsID string
+ if err := testPool.QueryRow(ctx, `
+INSERT INTO workspace (name, slug, description)
+VALUES ($1, $2, $3)
+RETURNING id
+`, "Handler Test Delete Lock", slug, "DeleteWorkspace lock timeout test").Scan(&wsID); err != nil {
+ t.Fatalf("create workspace: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, wsID)
+ })
+
+ if _, err := testPool.Exec(ctx, `
+INSERT INTO member (workspace_id, user_id, role)
+VALUES ($1, $2, 'owner')
+`, wsID, testUserID); err != nil {
+ t.Fatalf("create owner member: %v", err)
+ }
+
+ // The handler runs on its own goroutine so a regression shows up as a
+ // failed deadline here instead of hanging the whole test binary.
+ w := httptest.NewRecorder()
+ req := newRequest("DELETE", "/api/workspaces/"+wsID, nil)
+ req = withURLParam(req, "id", wsID)
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ testHandler.DeleteWorkspace(w, req)
+ }()
+
+ select {
+ case <-done:
+ case <-time.After(15 * time.Second):
+ // Unblock the handler so the test binary can still shut down cleanly.
+ releaseHolder()
+ <-done
+ t.Fatal("DeleteWorkspace blocked on advisory lock 4246 instead of timing out — this is the hang users see as 'delete workspace does nothing' (MUL-5983)")
+ }
+
+ if w.Code != http.StatusServiceUnavailable {
+ t.Fatalf("expected 503 while advisory lock 4246 is held, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var exists bool
+ if err := testPool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM workspace WHERE id = $1)`, wsID).Scan(&exists); err != nil {
+ t.Fatalf("verify workspace: %v", err)
+ }
+ if !exists {
+ t.Fatal("workspace must survive a teardown that never got its locks")
+ }
+}
+
+// TestDeleteWorkspace_SucceedsWhenRollupLockIsFree is the counterpart: the
+// lock timeout must not make an uncontended delete flaky.
+func TestDeleteWorkspace_SucceedsWhenRollupLockIsFree(t *testing.T) {
+ if testPool == nil {
+ t.Skip("DATABASE_URL not set; skipping live-Postgres workspace delete lock test")
+ }
+ ctx := context.Background()
+
+ // The teardown itself waits on 4246 under a 500 ms budget, so a rollup
+ // test holding that lock in the parallel internal/scheduler binary would
+ // turn this "uncontended" delete into a 503. Same guard, same reason.
+ lockRollupSingleton(t)
+
+ setWorkspaceDeleteLockTimeoutForTest(t, 500*time.Millisecond)
+
+ const slug = "handler-tests-delete-lock-free"
+ _, _ = testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, slug)
+
+ var wsID string
+ if err := testPool.QueryRow(ctx, `
+INSERT INTO workspace (name, slug, description)
+VALUES ($1, $2, $3)
+RETURNING id
+`, "Handler Test Delete Lock Free", slug, "DeleteWorkspace lock timeout test").Scan(&wsID); err != nil {
+ t.Fatalf("create workspace: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, wsID)
+ })
+
+ if _, err := testPool.Exec(ctx, `
+INSERT INTO member (workspace_id, user_id, role)
+VALUES ($1, $2, 'owner')
+`, wsID, testUserID); err != nil {
+ t.Fatalf("create owner member: %v", err)
+ }
+
+ w := httptest.NewRecorder()
+ req := newRequest("DELETE", "/api/workspaces/"+wsID, nil)
+ req = withURLParam(req, "id", wsID)
+ testHandler.DeleteWorkspace(w, req)
+
+ if w.Code != http.StatusNoContent {
+ t.Fatalf("expected 204 from an uncontended delete, got %d: %s", w.Code, w.Body.String())
+ }
+
+ var exists bool
+ if err := testPool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM workspace WHERE id = $1)`, wsID).Scan(&exists); err != nil {
+ t.Fatalf("verify workspace: %v", err)
+ }
+ if exists {
+ t.Fatal("workspace still exists after a successful delete")
+ }
+}
diff --git a/server/internal/scheduler/pgcron_concurrent_test.go b/server/internal/scheduler/pgcron_concurrent_test.go
index c4962aba30..3026cc5b38 100644
--- a/server/internal/scheduler/pgcron_concurrent_test.go
+++ b/server/internal/scheduler/pgcron_concurrent_test.go
@@ -99,36 +99,53 @@ func TestPgCronConcurrentNoDoubleWrite(t *testing.T) {
}
const callers = 6
- results := make([]int64, callers)
- errs := make([]error, callers)
- var wg sync.WaitGroup
- gate := make(chan struct{})
- for i := range callers {
- i := i
- wg.Add(1)
- go func() {
- defer wg.Done()
- <-gate
- err := pool.QueryRow(ctx, `SELECT rollup_task_usage_hourly()`).Scan(&results[i])
- errs[i] = err
- }()
- }
- close(gate) // start everyone simultaneously
- wg.Wait()
-
- winners := 0
- losers := 0
- var winningRowCount int64
- for i, err := range errs {
- if err != nil {
- t.Fatalf("caller %d: %v", i, err)
+ burst := func() (winners, losers int, winningRowCount int64) {
+ results := make([]int64, callers)
+ errs := make([]error, callers)
+ var wg sync.WaitGroup
+ gate := make(chan struct{})
+ for i := range callers {
+ i := i
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ <-gate
+ err := pool.QueryRow(ctx, `SELECT rollup_task_usage_hourly()`).Scan(&results[i])
+ errs[i] = err
+ }()
+ }
+ close(gate) // start everyone simultaneously
+ wg.Wait()
+
+ for i, err := range errs {
+ if err != nil {
+ t.Fatalf("caller %d: %v", i, err)
+ }
+ if results[i] > 0 {
+ winners++
+ winningRowCount = results[i]
+ } else {
+ losers++
+ }
}
- if results[i] > 0 {
- winners++
- winningRowCount = results[i]
- } else {
- losers++
+ return winners, losers, winningRowCount
+ }
+
+ // The singleton guard serialises the rollup tests against each other, but
+ // 4246 belongs to the whole rollup family and every workspace teardown
+ // takes it too (server/internal/handler, running in a parallel binary
+ // against the same database). If such a delete owns the lock for the whole
+ // burst, all six callers correctly report "no work" — winners=0 is a lost
+ // round, not a broken invariant, so retry it. Anything other than 0 or 1
+ // winners is a real double-write and fails immediately.
+ var winners, losers int
+ var winningRowCount int64
+ for attempt := 0; attempt < 10; attempt++ {
+ winners, losers, winningRowCount = burst()
+ if winners != 0 {
+ break
}
+ time.Sleep(100 * time.Millisecond)
}
if winners != 1 {
t.Fatalf("advisory lock 4246 must serialise rollup; got winners=%d losers=%d", winners, losers)
diff --git a/server/internal/scheduler/rollup_advisory_lock_test.go b/server/internal/scheduler/rollup_advisory_lock_test.go
new file mode 100644
index 0000000000..691fd56b3f
--- /dev/null
+++ b/server/internal/scheduler/rollup_advisory_lock_test.go
@@ -0,0 +1,131 @@
+package scheduler
+
+import (
+ "context"
+ "testing"
+ "time"
+)
+
+// TestRollupTaskUsageHourlyDoesNotLeakAdvisoryLockOnCancel pins the failure
+// mode behind MUL-5983: a cancelled rollup tick used to keep advisory lock
+// 4246 forever.
+//
+// Migration 102 took the lock with the SESSION-scoped pg_try_advisory_lock and
+// released it from an `EXCEPTION WHEN OTHERS` handler. plpgsql's OTHERS does
+// not match query_canceled, and a session-level advisory lock survives the
+// rollback that follows — so a tick killed by a statement timeout, an operator
+// cancel, or pgx cancelling the query when the Go context is done handed its
+// pooled connection back to pgxpool still holding 4246. Every later tick then
+// lost pg_try_advisory_lock and reported "no work", and DeleteWorkspace —
+// which waits on pg_advisory_xact_lock(4246) — blocked forever.
+//
+// The cancel is forced deterministically: another session holds the
+// rollup-state row the function updates first, so the tick blocks there long
+// enough for its own statement_timeout to fire.
+func TestRollupTaskUsageHourlyDoesNotLeakAdvisoryLockOnCancel(t *testing.T) {
+ pool := integrationPool(t)
+ ctx := context.Background()
+
+ // The tick mutates the shared rollup singleton; serialise with every
+ // other test that touches it (MUL-3980).
+ lockRollupSingleton(t, pool)
+
+ // Blocker: hold task_usage_hourly_rollup_state row 1 so the tick's first
+ // UPDATE waits instead of completing.
+ blocker, err := pool.Acquire(ctx)
+ if err != nil {
+ t.Fatalf("acquire blocker connection: %v", err)
+ }
+ defer blocker.Release()
+ blockerTx, err := blocker.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin blocker tx: %v", err)
+ }
+ blockerDone := false
+ defer func() {
+ if !blockerDone {
+ _ = blockerTx.Rollback(context.Background())
+ }
+ }()
+ if _, err := blockerTx.Exec(ctx, `
+ SELECT 1 FROM task_usage_hourly_rollup_state WHERE id = 1 FOR UPDATE
+ `); err != nil {
+ t.Fatalf("lock rollup state row: %v", err)
+ }
+
+ // Runner: a pinned connection so we can inspect the advisory locks it
+ // still holds after its statement is cancelled. This is the pgxpool
+ // connection whose session state outlives the aborted transaction.
+ runner, err := pool.Acquire(ctx)
+ if err != nil {
+ t.Fatalf("acquire runner connection: %v", err)
+ }
+ defer func() {
+ // Leave nothing behind for the next test even if the assertion below
+ // fails, and reset the session settings this test changed.
+ _, _ = runner.Exec(context.Background(), `SELECT pg_advisory_unlock_all()`)
+ _, _ = runner.Exec(context.Background(), `SET statement_timeout = DEFAULT`)
+ runner.Release()
+ }()
+
+ if _, err := runner.Exec(ctx, `SET statement_timeout = 500`); err != nil {
+ t.Fatalf("set statement_timeout: %v", err)
+ }
+ // The singleton guard serialises the rollup tests, but 4246 is also taken
+ // by every workspace teardown, so internal/handler's delete tests can hold
+ // it for a moment in the binary running alongside this one. A tick that
+ // loses that race returns 0 immediately instead of blocking on the row
+ // lock, which is a lost attempt rather than a result — retry it.
+ var rows int64
+ for attempt := 0; attempt < 20; attempt++ {
+ err = runner.QueryRow(ctx, `SELECT rollup_task_usage_hourly()`).Scan(&rows)
+ if err != nil {
+ break
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+ if err == nil {
+ t.Fatalf("expected the rollup tick to be cancelled, got rows=%d", rows)
+ }
+
+ _ = blockerTx.Rollback(ctx)
+ blockerDone = true
+ if _, err := runner.Exec(ctx, `SET statement_timeout = DEFAULT`); err != nil {
+ t.Fatalf("reset statement_timeout: %v", err)
+ }
+
+ // The cancelled tick must not still own 4246.
+ var held bool
+ if err := runner.QueryRow(ctx, `
+ SELECT EXISTS (
+ SELECT 1
+ FROM pg_locks
+ WHERE locktype = 'advisory'
+ AND pid = pg_backend_pid()
+ AND ((classid::bigint << 32) | objid::bigint) = 4246
+ )
+ `).Scan(&held); err != nil {
+ t.Fatalf("inspect advisory locks: %v", err)
+ }
+ if held {
+ t.Fatal("cancelled rollup tick leaked advisory lock 4246 — every later tick reports no work and DeleteWorkspace blocks forever (MUL-5983)")
+ }
+
+ // And the lock must become available to the next waiter, which is what the
+ // workspace teardown actually needs. Bounded retry for the same reason as
+ // above: a delete test in the parallel binary may hold 4246 right now.
+ var acquired bool
+ deadline := time.Now().Add(5 * time.Second)
+ for {
+ if err := pool.QueryRow(ctx, `SELECT pg_try_advisory_xact_lock(4246)`).Scan(&acquired); err != nil {
+ t.Fatalf("probe advisory lock 4246: %v", err)
+ }
+ if acquired || time.Now().After(deadline) {
+ break
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+ if !acquired {
+ t.Fatal("advisory lock 4246 is still held after a cancelled rollup tick")
+ }
+}
diff --git a/server/migrations/272_rollup_task_usage_hourly_xact_lock.down.sql b/server/migrations/272_rollup_task_usage_hourly_xact_lock.down.sql
new file mode 100644
index 0000000000..22dece8c28
--- /dev/null
+++ b/server/migrations/272_rollup_task_usage_hourly_xact_lock.down.sql
@@ -0,0 +1,56 @@
+-- Restore migration 102's session-scoped advisory lock. Note that this
+-- reintroduces the leak described in the up migration: a cancelled tick keeps
+-- lock 4246 for the life of its pooled connection.
+CREATE OR REPLACE FUNCTION rollup_task_usage_hourly()
+RETURNS BIGINT
+LANGUAGE plpgsql
+AS $$
+DECLARE
+ v_lock_ok BOOLEAN;
+ v_from TIMESTAMPTZ;
+ v_to TIMESTAMPTZ;
+ v_rows BIGINT := 0;
+BEGIN
+ SELECT pg_try_advisory_lock(4246) INTO v_lock_ok;
+ IF NOT v_lock_ok THEN
+ RETURN 0;
+ END IF;
+
+ BEGIN
+ UPDATE task_usage_hourly_rollup_state
+ SET last_run_started_at = now(),
+ last_error = NULL
+ WHERE id = 1
+ RETURNING watermark_at INTO v_from;
+
+ v_to := LEAST(now() - INTERVAL '5 minutes', v_from + INTERVAL '1 day');
+
+ IF v_from < v_to THEN
+ v_rows := rollup_task_usage_hourly_window(v_from, v_to);
+
+ UPDATE task_usage_hourly_rollup_state
+ SET watermark_at = v_to,
+ last_run_finished_at = now(),
+ last_run_rows = v_rows
+ WHERE id = 1;
+ ELSE
+ UPDATE task_usage_hourly_rollup_state
+ SET last_run_finished_at = now(),
+ last_run_rows = 0
+ WHERE id = 1;
+ END IF;
+
+ PERFORM pg_advisory_unlock(4246);
+ EXCEPTION WHEN OTHERS THEN
+ UPDATE task_usage_hourly_rollup_state
+ SET last_error = SQLERRM,
+ last_run_finished_at = now()
+ WHERE id = 1;
+ PERFORM pg_advisory_unlock(4246);
+ RAISE;
+ END;
+
+ PERFORM prune_task_usage_hourly_dirty();
+ RETURN v_rows;
+END;
+$$;
diff --git a/server/migrations/272_rollup_task_usage_hourly_xact_lock.up.sql b/server/migrations/272_rollup_task_usage_hourly_xact_lock.up.sql
new file mode 100644
index 0000000000..3f78482f71
--- /dev/null
+++ b/server/migrations/272_rollup_task_usage_hourly_xact_lock.up.sql
@@ -0,0 +1,97 @@
+-- Make the hourly rollup's advisory lock transaction-scoped.
+--
+-- Migration 102 took lock 4246 with the SESSION-scoped pg_try_advisory_lock
+-- and released it explicitly on both the success path and an
+-- `EXCEPTION WHEN OTHERS` path. Two PostgreSQL rules combine to make that
+-- leak the lock forever:
+--
+-- 1. OTHERS does not match query_canceled. A cancelled tick — statement
+-- timeout, pg_cancel_backend, or pgx cancelling the query when the Go
+-- context is done (the scheduler caps a tick at 25 min) — skips the
+-- handler entirely, so pg_advisory_unlock never runs.
+-- 2. A session-level advisory lock does not honour transaction semantics:
+-- it survives the rollback that follows.
+--
+-- pgxpool then hands the connection back to the pool still holding 4246, and
+-- nothing releases it until that connection is recycled or the process exits.
+--
+-- The consequences are silent and unbounded: every later tick loses
+-- pg_try_advisory_lock and returns 0 ("no work to do"), so usage aggregation
+-- stops, and DeleteWorkspace — which waits on pg_advisory_xact_lock(4246) to
+-- keep the rollup out of a workspace it is tearing down — blocks forever, so
+-- deleting a workspace appears to do nothing at all (MUL-5983).
+--
+-- pg_try_advisory_xact_lock is released by the transaction end, including a
+-- rollback from a cancelled statement, so no failure mode can leak it. The
+-- function is called as a plain `SELECT rollup_task_usage_hourly()`, i.e. its
+-- own implicit transaction, so the lock still covers exactly one tick.
+--
+-- The one behaviour change: the TTL prune at the end used to run after an
+-- explicit unlock and now runs inside the locked transaction, so whatever it
+-- costs is added to the window in which 4246 is unavailable — to the next
+-- tick, to a backfill run, and to a workspace delete, which now waits on 4246
+-- under a 10 s budget and answers 503 when it runs out. The prune is an
+-- index-driven DELETE (task_usage_hourly_dirty.enqueued_at) with no row cap:
+-- in steady state each tick already drains the queue and it deletes nothing,
+-- but after a long pause it has a real backlog to clear. Watch rollup duration
+-- and workspace-delete 503s together if that ever happens.
+CREATE OR REPLACE FUNCTION rollup_task_usage_hourly()
+RETURNS BIGINT
+LANGUAGE plpgsql
+AS $$
+DECLARE
+ v_lock_ok BOOLEAN;
+ v_from TIMESTAMPTZ;
+ v_to TIMESTAMPTZ;
+ v_rows BIGINT := 0;
+BEGIN
+ SELECT pg_try_advisory_xact_lock(4246) INTO v_lock_ok;
+ IF NOT v_lock_ok THEN
+ RETURN 0;
+ END IF;
+
+ BEGIN
+ UPDATE task_usage_hourly_rollup_state
+ SET last_run_started_at = now(),
+ last_error = NULL
+ WHERE id = 1
+ RETURNING watermark_at INTO v_from;
+
+ -- Cap each tick at a one-day window. In steady state v_from is
+ -- recent, so LEAST picks `now() - 5 min` and nothing changes. But
+ -- if the worker was paused (incident, migration freeze) the
+ -- watermark can fall far behind; without the cap a single catch-up
+ -- tick would recompute a multi-week window in one statement while
+ -- holding lock 4246, blocking every other tick. Capped, catch-up
+ -- advances in bounded one-day steps over successive ticks.
+ v_to := LEAST(now() - INTERVAL '5 minutes', v_from + INTERVAL '1 day');
+
+ IF v_from < v_to THEN
+ v_rows := rollup_task_usage_hourly_window(v_from, v_to);
+
+ UPDATE task_usage_hourly_rollup_state
+ SET watermark_at = v_to,
+ last_run_finished_at = now(),
+ last_run_rows = v_rows
+ WHERE id = 1;
+ ELSE
+ UPDATE task_usage_hourly_rollup_state
+ SET last_run_finished_at = now(),
+ last_run_rows = 0
+ WHERE id = 1;
+ END IF;
+ EXCEPTION WHEN OTHERS THEN
+ UPDATE task_usage_hourly_rollup_state
+ SET last_error = SQLERRM,
+ last_run_finished_at = now()
+ WHERE id = 1;
+ RAISE;
+ END;
+
+ -- TTL prune. Idempotent, and in steady state a no-op because each tick
+ -- already drains the queue. It runs under the transaction-scoped lock —
+ -- see the note at the top for what that costs after a long pause.
+ PERFORM prune_task_usage_hourly_dirty();
+ RETURN v_rows;
+END;
+$$;
diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.go
index 9c75c72881..efd68053f2 100644
--- a/server/pkg/db/generated/workspace_delete.sql.go
+++ b/server/pkg/db/generated/workspace_delete.sql.go
@@ -473,9 +473,12 @@ const lockTaskUsageRollupForWorkspaceDelete = `-- name: LockTaskUsageRollupForWo
SELECT pg_advisory_xact_lock(4246)
`
-// The hourly rollup uses session advisory lock 4246. The transaction-scoped
-// lock shares that namespace: an in-flight rollup finishes first, then no new
-// rollup can write the workspace's aggregates until this delete commits.
+// Advisory lock 4246 is the hourly rollup family's key: the rollup function
+// takes it per transaction (migration 272) and the backfill commands take it
+// per session. An in-flight rollup finishes first, then no new rollup can
+// write the workspace's aggregates until this delete commits. The caller
+// bounds this wait with SET LOCAL lock_timeout — batch jobs hold 4246 for
+// minutes, and an unbounded wait here hangs the delete request (MUL-5983).
func (q *Queries) LockTaskUsageRollupForWorkspaceDelete(ctx context.Context) error {
_, err := q.db.Exec(ctx, lockTaskUsageRollupForWorkspaceDelete)
return err
diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sql
index eedff86a9b..05deef869a 100644
--- a/server/pkg/db/queries/workspace_delete.sql
+++ b/server/pkg/db/queries/workspace_delete.sql
@@ -8,9 +8,12 @@
SELECT set_config('multica.workspace_teardown', 'on', true);
-- name: LockTaskUsageRollupForWorkspaceDelete :exec
--- The hourly rollup uses session advisory lock 4246. The transaction-scoped
--- lock shares that namespace: an in-flight rollup finishes first, then no new
--- rollup can write the workspace's aggregates until this delete commits.
+-- Advisory lock 4246 is the hourly rollup family's key: the rollup function
+-- takes it per transaction (migration 272) and the backfill commands take it
+-- per session. An in-flight rollup finishes first, then no new rollup can
+-- write the workspace's aggregates until this delete commits. The caller
+-- bounds this wait with SET LOCAL lock_timeout — batch jobs hold 4246 for
+-- minutes, and an unbounded wait here hangs the delete request (MUL-5983).
SELECT pg_advisory_xact_lock(4246);
-- name: PrepareWorkspaceDeletionLinks :exec