Skip to content

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

Go

MUL-9644 fix(inbox): keep a woken issue's return rank without waiting on the trimmer (#10973)

Multica Evec08ba8fc2d42
diff --git a/server/internal/handler/inbox_limit_test.go b/server/internal/handler/inbox_limit_test.go
index 551dc2f5c2..87517cc913 100644
--- a/server/internal/handler/inbox_limit_test.go
+++ b/server/internal/handler/inbox_limit_test.go
@@ -374,3 +374,201 @@ func TestBulkArchiveClearsReturn(t *testing.T) {
t.Fatalf("archive all: archived=%v returned_at=%v", isArchived(t, allID), returnedAtOf(t, allID))
}
}
+
+// The trimmer's startup backfill gives a snooze set before returned_at
+// existed its return rank, so the woken issue is in the very first list read
+// of a full inbox.
+func TestReturnedAtBackfillRanksLegacySnooze(t *testing.T) {
+ workspaceID := limitInboxWorkspace(t, "Inbox limit backfill")
+ seedInboxRows(t, workspaceID, testUserID, inbox.ActiveLimit, time.Now().UTC().Add(-time.Hour), time.Millisecond)
+ issueID := dbfx.Issue(t, "Legacy snooze", testutil.Cols{"workspace_id": workspaceID})
+ wake := time.Now().Add(-time.Minute).UTC().Truncate(time.Microsecond)
+ legacy := testutil.Cols{"issue_id": issueID, "snoozed_until": wake, "snoozed_at": wake.Add(-24 * time.Hour)}
+ olderID := insertOldInboxRow(t, workspaceID, "legacy-older", legacy)
+ legacy["created_at"] = time.Now().Add(-47 * time.Hour)
+ newestID := insertOldInboxRow(t, workspaceID, "legacy-newest", legacy)
+
+ trimmer := inbox.NewTrimmer(testHandler.Queries, nil)
+ if n, err := trimmer.Backfill(context.Background(), parseUUID(workspaceID)); err != nil || n != 1 {
+ t.Fatalf("Backfill = %d, %v; want the one snoozed issue ranked", n, err)
+ }
+
+ if at := returnedAtOf(t, newestID); at == nil || !at.Equal(wake) || returnedAtOf(t, olderID) != nil {
+ t.Fatalf("newest returned_at=%v older=%v; want only the newest at the wake time", at, returnedAtOf(t, olderID))
+ }
+ var items []InboxItemResponse
+ testutil.Call(t, inboxWorkspaceHandler(testHandler.ListInbox),
+ inboxRequest(http.MethodGet, "/api/inbox", workspaceID)).
+ Want(http.StatusOK).
+ JSON(&items)
+ if len(items) == 0 || items[0].ID != newestID {
+ t.Fatal("the woken issue is missing from the first read of a full inbox")
+ }
+}
+
+// Even before its rank is settled, the archive never takes a woken issue's
+// newest row on that stale rank.
+func TestArchiveInboxOverflowSparesUnsettledReturn(t *testing.T) {
+ workspaceID := limitInboxWorkspace(t, "Inbox limit archive guard")
+ seedInboxRows(t, workspaceID, testUserID, inbox.ActiveLimit, time.Now().UTC().Add(-time.Hour), time.Millisecond)
+ issueID := dbfx.Issue(t, "Unsettled snooze", testutil.Cols{"workspace_id": workspaceID})
+ wake := time.Now().Add(-time.Minute)
+ newestID := insertOldInboxRow(t, workspaceID, "unsettled", testutil.Cols{
+ "issue_id": issueID, "snoozed_until": wake, "snoozed_at": wake.Add(-24 * time.Hour),
+ })
+
+ archived, err := testHandler.Queries.ArchiveInboxOverflow(context.Background(), db.ArchiveInboxOverflowParams{
+ WorkspaceID: parseUUID(workspaceID), RecipientType: "member", RecipientID: parseUUID(testUserID),
+ Keep: inbox.ActiveLimit, BatchSize: 500,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if isArchived(t, newestID) || archived != 0 {
+ t.Fatalf("archived=%d, woken row archived=%v; want the woken issue's newest row spared", archived, isArchived(t, newestID))
+ }
+}
+
+// A notification that joins a running snooze takes the issue's return rank
+// when it is written, not only once the trimmer settles it.
+func TestDeliverIntoSnoozeHandsReturnToNewRow(t *testing.T) {
+ workspaceID := limitInboxWorkspace(t, "Inbox limit join snooze")
+ issueID := dbfx.Issue(t, "Snoozed issue", testutil.Cols{"workspace_id": workspaceID})
+ until := time.Now().Add(time.Hour).UTC().Truncate(time.Microsecond)
+ holderID := insertOldInboxRow(t, workspaceID, "holder", testutil.Cols{
+ "issue_id": issueID, "snoozed_until": until, "snoozed_at": time.Now(), "returned_at": until,
+ })
+
+ item, inserted, err := inbox.Deliver(context.Background(), testHandler.Queries, nil, inbox.Notification{
+ Params: db.CreateInboxItemParams{
+ WorkspaceID: parseUUID(workspaceID), RecipientType: "member", RecipientID: parseUUID(testUserID),
+ Type: "new_comment", Severity: "info", IssueID: parseUUID(issueID), Title: "joined",
+ Details: []byte(`{}`),
+ },
+ IgnorePreferences: true,
+ })
+ if err != nil || !inserted {
+ t.Fatalf("Deliver = inserted %v, err %v", inserted, err)
+ }
+ joinedID := uuidToString(item.ID)
+ if at := returnedAtOf(t, joinedID); at == nil || !at.Equal(until) || returnedAtOf(t, holderID) != nil {
+ t.Fatalf("joined returned_at=%v holder=%v; want the rank handed to the joining row", at, returnedAtOf(t, holderID))
+ }
+}
+
+// NormalizeInboxReturns skips rows another write holds instead of waiting on
+// them, and settles them on a later call.
+func TestNormalizeInboxReturnsSkipsLockedRows(t *testing.T) {
+ workspaceID := limitInboxWorkspace(t, "Inbox limit normalize lock")
+ issueID := dbfx.Issue(t, "Unsettled snooze", testutil.Cols{"workspace_id": workspaceID})
+ wake := time.Now().Add(-time.Minute)
+ newestID := insertOldInboxRow(t, workspaceID, "unsettled", testutil.Cols{
+ "issue_id": issueID, "snoozed_until": wake, "snoozed_at": wake.Add(-24 * time.Hour),
+ })
+ params := db.NormalizeInboxReturnsParams{
+ WorkspaceID: parseUUID(workspaceID), RecipientType: "member", RecipientID: parseUUID(testUserID), BatchSize: 500,
+ }
+
+ ctx := context.Background()
+ tx, err := dbfx.Pool.Begin(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := tx.Exec(ctx, `SELECT 1 FROM inbox_item WHERE id = $1 FOR UPDATE`, newestID); err != nil {
+ t.Fatal(err)
+ }
+ callCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ n, err := testHandler.Queries.NormalizeInboxReturns(callCtx, params)
+ cancel()
+ if rbErr := tx.Rollback(ctx); rbErr != nil {
+ t.Fatal(rbErr)
+ }
+ if err != nil || n != 0 {
+ t.Fatalf("normalize under a held lock = %d, %v; want 0 without waiting", n, err)
+ }
+
+ if n, err := testHandler.Queries.NormalizeInboxReturns(ctx, params); err != nil || n != 1 {
+ t.Fatalf("normalize after the lock = %d, %v; want the row settled", n, err)
+ }
+ if at := returnedAtOf(t, newestID); at == nil {
+ t.Fatal("the woken row still has no return rank")
+ }
+}
+
+// Two rows joining a snooze hand the rank over in either order and leave it
+// on the newer one.
+func TestHandInboxReturnToRowInReverseOrder(t *testing.T) {
+ workspaceID := limitInboxWorkspace(t, "Inbox limit handoff order")
+ issueID := dbfx.Issue(t, "Snoozed issue", testutil.Cols{"workspace_id": workspaceID})
+ until := time.Now().Add(time.Hour).UTC().Truncate(time.Microsecond)
+ holderID := insertOldInboxRow(t, workspaceID, "holder", testutil.Cols{
+ "issue_id": issueID, "snoozed_until": until, "snoozed_at": time.Now(), "returned_at": until,
+ })
+ ctx := context.Background()
+ create := func(title string) db.InboxItem {
+ item, err := testHandler.Queries.CreateInboxItem(ctx, db.CreateInboxItemParams{
+ WorkspaceID: parseUUID(workspaceID), RecipientType: "member", RecipientID: parseUUID(testUserID),
+ Type: "new_comment", Severity: "info", IssueID: parseUUID(issueID), Title: title, Details: []byte(`{}`),
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ return item
+ }
+ hand := func(item db.InboxItem) {
+ if err := testHandler.Queries.HandInboxReturnToRow(ctx, db.HandInboxReturnToRowParams{
+ WorkspaceID: item.WorkspaceID, RecipientType: item.RecipientType, RecipientID: item.RecipientID,
+ IssueID: item.IssueID, KeepID: item.ID,
+ }); err != nil {
+ t.Fatal(err)
+ }
+ }
+ a := create("a")
+ b := create("b")
+ hand(b)
+ hand(a)
+
+ if at := returnedAtOf(t, uuidToString(b.ID)); at == nil || !at.Equal(until) {
+ t.Fatalf("newer row returned_at = %v, want %v", at, until)
+ }
+ if returnedAtOf(t, uuidToString(a.ID)) != nil || returnedAtOf(t, holderID) != nil {
+ t.Fatal("an older row kept the issue's return rank")
+ }
+}
+
+// While a duplicate rank is held by another write, the trim archives
+// nothing; once it is settled, it keeps exactly the newest ActiveLimit rows.
+func TestInboxTrimmerWaitsForHeldDuplicateRank(t *testing.T) {
+ workspaceID := limitInboxWorkspace(t, "Inbox limit held rank")
+ seedInboxRows(t, workspaceID, testUserID, inbox.ActiveLimit, time.Now().UTC().Add(-time.Hour), time.Millisecond)
+ issueID := dbfx.Issue(t, "Duplicate rank", testutil.Cols{"workspace_id": workspaceID})
+ now := time.Now()
+ staleID := insertOldInboxRow(t, workspaceID, "stale-holder", testutil.Cols{"issue_id": issueID, "returned_at": now})
+ insertOldInboxRow(t, workspaceID, "newest", testutil.Cols{
+ "issue_id": issueID, "returned_at": now, "created_at": now.Add(-47 * time.Hour),
+ })
+ plain := func() int {
+ return dbfx.Count(t, `SELECT count(*) FROM inbox_item WHERE workspace_id = $1 AND issue_id IS NULL AND NOT archived`, workspaceID)
+ }
+
+ ctx := context.Background()
+ tx, err := dbfx.Pool.Begin(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := tx.Exec(ctx, `SELECT 1 FROM inbox_item WHERE id = $1 FOR UPDATE`, staleID); err != nil {
+ t.Fatal(err)
+ }
+ trimInbox(t, workspaceID)
+ if err := tx.Rollback(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if n := plain(); n != inbox.ActiveLimit {
+ t.Fatalf("plain rows = %d while the rank was held, want all %d kept", n, inbox.ActiveLimit)
+ }
+
+ trimInbox(t, workspaceID)
+ if n := plain(); n != inbox.ActiveLimit-1 || !isArchived(t, staleID) {
+ t.Fatalf("plain rows = %d, stale holder archived=%v; want %d kept beside the issue", n, isArchived(t, staleID), inbox.ActiveLimit-1)
+ }
+}
diff --git a/server/internal/inbox/create.go b/server/internal/inbox/create.go
index a1c80f67a1..800676272a 100644
--- a/server/internal/inbox/create.go
+++ b/server/internal/inbox/create.go
@@ -40,6 +40,22 @@ func createIfEligible(ctx context.Context, queries *db.Queries, params db.Create
}
item.SnoozedUntil = pgtype.Timestamptz{}
item.SnoozedAt = pgtype.Timestamptz{}
+ return item, true, nil
+ }
+ if item.SnoozedUntil.Valid {
+ // The joining row took the issue's return rank (CreateInboxItem).
+ // Failing here leaves two rows ranked by the return until the inbox
+ // limit's NormalizeInboxReturns settles it; the row itself is fine.
+ if err := queries.HandInboxReturnToRow(ctx, db.HandInboxReturnToRowParams{
+ WorkspaceID: item.WorkspaceID,
+ RecipientType: item.RecipientType,
+ RecipientID: item.RecipientID,
+ IssueID: item.IssueID,
+ KeepID: item.ID,
+ }); err != nil {
+ slog.Warn("inbox: failed to hand the snooze's return rank to a joining row",
+ "type", item.Type, "error", err)
+ }
}
return item, true, nil
}
diff --git a/server/internal/inbox/trim.go b/server/internal/inbox/trim.go
index 9ada8f82c9..2f6b6f4908 100644
--- a/server/internal/inbox/trim.go
+++ b/server/internal/inbox/trim.go
@@ -31,13 +31,23 @@ const (
// into one trim, and one inbox:batch-archived, per round.
trimInterval = 30 * time.Second
trimRoundBudget = 25 * time.Second
+
+ // backfillReruns are when, after start, Run gives snoozes written without
+ // a return rank their rank (BackfillInboxSnoozeReturns): at once for
+ // snoozes that predate the column, and again once a rolling deploy's
+ // older servers, which still write them without one, are gone.
+ backfillBudget = 2 * time.Minute
)
+var backfillReruns = []time.Duration{0, 15 * time.Minute}
+
// TrimQueries is the slice of db.Queries a Trimmer uses.
type TrimQueries interface {
InboxOverflows(ctx context.Context, arg db.InboxOverflowsParams) (bool, error)
ArchiveInboxOverflow(ctx context.Context, arg db.ArchiveInboxOverflowParams) (int64, error)
NormalizeInboxReturns(ctx context.Context, arg db.NormalizeInboxReturnsParams) (int64, error)
+ InboxReturnsSettled(ctx context.Context, arg db.InboxReturnsSettledParams) (bool, error)
+ BackfillInboxSnoozeReturns(ctx context.Context, arg db.BackfillInboxSnoozeReturnsParams) (int64, error)
ListHiddenProjectIDsForUser(ctx context.Context, arg db.ListHiddenProjectIDsForUserParams) ([]pgtype.UUID, error)
}
@@ -138,6 +148,7 @@ func recipientOfNewItem(e events.Event) (Recipient, bool) {
// Run trims the marked inboxes every trimInterval until ctx ends.
func (t *Trimmer) Run(ctx context.Context) {
+ go t.runBackfill(ctx)
ticker := time.NewTicker(trimInterval)
defer ticker.Stop()
for {
@@ -152,6 +163,41 @@ func (t *Trimmer) Run(ctx context.Context) {
}
}
+func (t *Trimmer) runBackfill(ctx context.Context) {
+ start := time.Now()
+ for _, at := range backfillReruns {
+ select {
+ case <-ctx.Done():
+ return
+ case <-time.After(time.Until(start.Add(at))):
+ }
+ runCtx, cancel := context.WithTimeout(ctx, backfillBudget)
+ n, err := t.Backfill(runCtx, pgtype.UUID{})
+ cancel()
+ if err != nil {
+ slog.Warn("inbox snooze return backfill failed", "count", n, "error", err)
+ } else if n > 0 {
+ slog.Info("inbox snooze return backfill ranked snoozed issues", "count", n)
+ }
+ }
+}
+
+// Backfill gives every snoozed issue written without a return rank its rank,
+// in batches that skip rows another write holds. workspaceID narrows it (for
+// tests); the zero value covers every workspace.
+func (t *Trimmer) Backfill(ctx context.Context, workspaceID pgtype.UUID) (int64, error) {
+ var total int64
+ for {
+ n, err := t.queries.BackfillInboxSnoozeReturns(ctx, db.BackfillInboxSnoozeReturnsParams{
+ WorkspaceID: workspaceID, BatchSize: trimBatchSize,
+ })
+ total += n
+ if err != nil || n < trimBatchSize {
+ return total, err
+ }
+ }
+}
+
// Flush trims every inbox marked so far. An inbox that could not be finished
// (an error, the round's deadline, or more rows than one round archives) is
// marked again for the next round.
@@ -207,10 +253,12 @@ func (t *Trimmer) trim(ctx context.Context, r Recipient) (archived int64, done b
return 0, err == nil, err
}
// Settle which row ranks each issue by its return before ranking decides
- // what to archive (see NormalizeInboxReturns).
- if _, err := t.queries.NormalizeInboxReturns(ctx, db.NormalizeInboxReturnsParams{
- WorkspaceID: r.WorkspaceID, RecipientType: r.RecipientType, RecipientID: r.RecipientID,
- }); err != nil {
+ // what to archive (see NormalizeInboxReturns). Until every rank is
+ // settled, rows another write holds included, archive nothing: an
+ // unsettled duplicate rank would keep a row that is not the issue's and
+ // push a real one out. The inbox stays queued for the next round.
+ settled, err := t.normalize(ctx, r)
+ if err != nil || !settled {
return 0, false, err
}
for range trimMaxBatches {
@@ -233,6 +281,27 @@ func (t *Trimmer) trim(ctx context.Context, r Recipient) (archived int64, done b
return archived, !over, nil
}
+// normalize runs NormalizeInboxReturns until it returns a partial batch, at
+// most trimMaxBatches times, then reports whether anything is left: a
+// partial batch can also mean rows it skipped because another write held them.
+func (t *Trimmer) normalize(ctx context.Context, r Recipient) (settled bool, err error) {
+ for range trimMaxBatches {
+ n, err := t.queries.NormalizeInboxReturns(ctx, db.NormalizeInboxReturnsParams{
+ WorkspaceID: r.WorkspaceID, RecipientType: r.RecipientType, RecipientID: r.RecipientID,
+ BatchSize: trimBatchSize,
+ })
+ if err != nil {
+ return false, err
+ }
+ if n < trimBatchSize {
+ break
+ }
+ }
+ return t.queries.InboxReturnsSettled(ctx, db.InboxReturnsSettledParams{
+ WorkspaceID: r.WorkspaceID, RecipientType: r.RecipientType, RecipientID: r.RecipientID,
+ })
+}
+
// hiddenProjects returns the private projects a member recipient cannot see,
// so the limit counts the rows their own inbox list shows (ListInboxItems
// filters the same projects). Nil when there are none, or for an agent.
diff --git a/server/internal/inbox/trim_test.go b/server/internal/inbox/trim_test.go
index 6c26fba259..748d950319 100644
--- a/server/internal/inbox/trim_test.go
+++ b/server/internal/inbox/trim_test.go
@@ -18,6 +18,16 @@ type fakeTrimQueries struct {
locked int
archiveRun int
normalized int
+ unsettled int // rows NormalizeInboxReturns still has to fix
+ held int // unsettled rows another write holds, which it skips
+}
+
+func (f *fakeTrimQueries) InboxReturnsSettled(context.Context, db.InboxReturnsSettledParams) (bool, error) {
+ return f.unsettled == 0 && f.held == 0, nil
+}
+
+func (f *fakeTrimQueries) BackfillInboxSnoozeReturns(context.Context, db.BackfillInboxSnoozeReturnsParams) (int64, error) {
+ return 0, nil
}
func (f *fakeTrimQueries) InboxOverflows(_ context.Context, arg db.InboxOverflowsParams) (bool, error) {
@@ -28,9 +38,11 @@ func (f *fakeTrimQueries) ListHiddenProjectIDsForUser(context.Context, db.ListHi
return nil, nil
}
-func (f *fakeTrimQueries) NormalizeInboxReturns(context.Context, db.NormalizeInboxReturnsParams) (int64, error) {
+func (f *fakeTrimQueries) NormalizeInboxReturns(_ context.Context, arg db.NormalizeInboxReturnsParams) (int64, error) {
f.normalized++
- return 0, nil
+ n := min(f.unsettled, int(arg.BatchSize))
+ f.unsettled -= n
+ return int64(n), nil
}
func (f *fakeTrimQueries) ArchiveInboxOverflow(_ context.Context, arg db.ArchiveInboxOverflowParams) (int64, error) {
@@ -185,3 +197,45 @@ func TestNilTrimmerMarkIsNoop(t *testing.T) {
var tr *Trimmer
tr.Mark(trimRecipient)
}
+
+// Return ranks left unsettled after a round's normalize budget keep the inbox
+// queued, so the next round finishes them.
+func TestTrimmerRequeuesInboxWithUnsettledReturns(t *testing.T) {
+ q := &fakeTrimQueries{rows: ActiveLimit + 1, unsettled: trimMaxBatches*trimBatchSize + 1}
+ tr := NewTrimmer(q, nil)
+
+ tr.Mark(trimRecipient)
+ tr.Flush(context.Background())
+ if _, ok := tr.pending[trimRecipient]; !ok || q.normalized != trimMaxBatches {
+ t.Fatalf("pending=%v normalize calls=%d; want queued after %d calls", tr.pending, q.normalized, trimMaxBatches)
+ }
+
+ // Ranks only matter while the inbox is over the limit.
+ q.rows = ActiveLimit + 1
+ tr.Flush(context.Background())
+ if len(tr.pending) != 0 || q.unsettled != 0 {
+ t.Fatalf("pending=%v unsettled=%d after the next round", tr.pending, q.unsettled)
+ }
+}
+
+// Unsettled ranks normalize skipped because another write held them block
+// this round's archive: a duplicate rank would keep the wrong row.
+func TestTrimmerArchivesNothingWhileRanksAreHeld(t *testing.T) {
+ q := &fakeTrimQueries{rows: ActiveLimit + 2, held: 1}
+ tr := NewTrimmer(q, nil)
+
+ tr.Mark(trimRecipient)
+ tr.Flush(context.Background())
+ if q.archiveRun != 0 || q.rows != ActiveLimit+2 {
+ t.Fatalf("archive runs=%d rows=%d; want nothing archived while a rank is held", q.archiveRun, q.rows)
+ }
+ if _, ok := tr.pending[trimRecipient]; !ok {
+ t.Fatal("inbox with a held rank was not queued for the next round")
+ }
+
+ q.held = 0
+ tr.Flush(context.Background())
+ if q.rows != ActiveLimit || len(tr.pending) != 0 {
+ t.Fatalf("rows=%d pending=%v once the lock cleared", q.rows, tr.pending)
+ }
+}
diff --git a/server/pkg/db/generated/inbox.sql.go b/server/pkg/db/generated/inbox.sql.go
index 6a60daebc6..ad7ec48a52 100644
--- a/server/pkg/db/generated/inbox.sql.go
+++ b/server/pkg/db/generated/inbox.sql.go
@@ -199,7 +199,7 @@ func (q *Queries) ArchiveInboxItem(ctx context.Context, id pgtype.UUID) (InboxIt
}
const archiveInboxOverflow = `-- name: ArchiveInboxOverflow :execrows
-WITH boundary AS (
+WITH boundary AS MATERIALIZED (
SELECT GREATEST(b.created_at, b.returned_at) AS shown_at, b.id
FROM inbox_item b
LEFT JOIN issue b_iss ON b_iss.id = b.issue_id
@@ -223,6 +223,18 @@ WITH boundary AS (
AND ($4::uuid[] IS NULL OR o_iss.project_id IS NULL
OR NOT (o_iss.project_id = ANY($4::uuid[])))
AND (GREATEST(o.created_at, o.returned_at), o.id) < (boundary.shown_at, boundary.id)
+ -- An issue back from a snooze whose newest row does not carry the
+ -- return yet (written by an older server, or not normalized) ranks too
+ -- low here; never archive that row on its stale rank.
+ AND NOT (o.issue_id IS NOT NULL AND o.snoozed_until IS NOT NULL
+ AND (o.returned_at IS NULL OR o.returned_at < o.snoozed_until)
+ AND NOT EXISTS (
+ SELECT 1 FROM inbox_item newer
+ WHERE newer.workspace_id = o.workspace_id AND newer.recipient_type = o.recipient_type
+ AND newer.recipient_id = o.recipient_id AND newer.issue_id = o.issue_id
+ AND newer.archived = false
+ AND (newer.created_at, newer.id) > (o.created_at, o.id)
+ ))
ORDER BY GREATEST(o.created_at, o.returned_at), o.id
LIMIT $6::int
FOR UPDATE OF o SKIP LOCKED
@@ -249,6 +261,7 @@ type ArchiveInboxOverflowParams struct {
// behind the user's back, and hidden rows never push out visible ones. SKIP LOCKED keeps a trim from waiting on, or
// deadlocking with, the user's own inbox writes; InboxOverflows tells the
// caller whether skipped rows remain.
+// MATERIALIZED: the boundary is read once per statement, not once per row.
// ANY(ARRAY(...)) keeps the update on primary-key lookups; a join against the
// CTE lets the planner pick a scan of the whole table.
func (q *Queries) ArchiveInboxOverflow(ctx context.Context, arg ArchiveInboxOverflowParams) (int64, error) {
@@ -266,6 +279,46 @@ func (q *Queries) ArchiveInboxOverflow(ctx context.Context, arg ArchiveInboxOver
return result.RowsAffected(), nil
}
+const backfillInboxSnoozeReturns = `-- name: BackfillInboxSnoozeReturns :execrows
+WITH candidates AS (
+ SELECT s.id
+ FROM inbox_item s
+ WHERE ($1::uuid IS NULL OR s.workspace_id = $1::uuid)
+ AND s.archived = false AND s.issue_id IS NOT NULL
+ AND s.snoozed_until IS NOT NULL AND s.returned_at IS NULL
+ AND NOT EXISTS (
+ SELECT 1 FROM inbox_item newer
+ WHERE newer.workspace_id = s.workspace_id AND newer.recipient_type = s.recipient_type
+ AND newer.recipient_id = s.recipient_id AND newer.issue_id = s.issue_id
+ AND newer.archived = false
+ AND (newer.created_at, newer.id) > (s.created_at, s.id)
+ )
+ LIMIT $2::int
+ FOR UPDATE OF s SKIP LOCKED
+)
+UPDATE inbox_item AS item SET returned_at = item.snoozed_until
+WHERE item.id = ANY (ARRAY(SELECT candidates.id FROM candidates))
+`
+
+type BackfillInboxSnoozeReturnsParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ BatchSize int32 `json:"batch_size"`
+}
+
+// Gives up to batch_size snoozed issues their return rank where a writer that
+// predates returned_at left it out: the issue's newest active row ranks by
+// when the snooze ends. Snoozes set before the column existed, and by an
+// older server during the rollout. Skips rows another write holds and
+// touches only rows still without a rank, so it can run again at any time.
+// workspace_id narrows it for tests; production passes NULL.
+func (q *Queries) BackfillInboxSnoozeReturns(ctx context.Context, arg BackfillInboxSnoozeReturnsParams) (int64, error) {
+ result, err := q.db.Exec(ctx, backfillInboxSnoozeReturns, arg.WorkspaceID, arg.BatchSize)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
const countUnreadInbox = `-- name: CountUnreadInbox :one
SELECT count(*) FROM inbox_item i
WHERE i.workspace_id = $1
@@ -372,10 +425,10 @@ INSERT INTO inbox_item (
workspace_id, recipient_type, recipient_id,
type, severity, issue_id, title, body,
actor_type, actor_id, details, id,
- snoozed_until, snoozed_at
+ snoozed_until, snoozed_at, returned_at
)
SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, COALESCE($12::uuid, gen_random_uuid()),
- snoozed.snoozed_until, snoozed.snoozed_at
+ snoozed.snoozed_until, snoozed.snoozed_at, snoozed.snoozed_until
FROM (SELECT 1) AS one
LEFT JOIN LATERAL (
SELECT s.snoozed_until, s.snoozed_at
@@ -424,7 +477,9 @@ type CreateInboxItemParams struct {
// MUL-9333: a row written on an issue the recipient has snoozed joins the
// snooze, so it stays out of the inbox with the rest of the issue.
// inbox.Deliver ends the snooze instead when the row is one that
-// wakes it.
+// wakes it. A joining row is the issue's newest, so it carries the issue's
+// return rank (returned_at, the snooze end); inbox.Deliver clears it from the
+// row that held it (HandInboxReturnToRow).
// MUL-8472: a member outside a private project gets no notification about its
// issues, whatever their workspace role. Only project members do.
func (q *Queries) CreateInboxItem(ctx context.Context, arg CreateInboxItemParams) (InboxItem, error) {
@@ -535,6 +590,37 @@ func (q *Queries) GetInboxItemInWorkspace(ctx context.Context, arg GetInboxItemI
return i, err
}
+const handInboxReturnToRow = `-- name: HandInboxReturnToRow :exec
+UPDATE inbox_item AS item SET returned_at = NULL
+FROM inbox_item AS kept
+WHERE kept.id = $5
+ AND item.workspace_id = $1 AND item.recipient_type = $2 AND item.recipient_id = $3 AND item.issue_id = $4
+ AND item.archived = false AND item.returned_at IS NOT NULL
+ AND (item.created_at, item.id) < (kept.created_at, kept.id)
+`
+
+type HandInboxReturnToRowParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ RecipientType string `json:"recipient_type"`
+ RecipientID pgtype.UUID `json:"recipient_id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ KeepID pgtype.UUID `json:"keep_id"`
+}
+
+// Clears the issue's return rank from the active rows older than keep_id, the
+// row that now carries it (see CreateInboxItem). Only older rows: two joining
+// rows handing over concurrently, in either order, leave the rank on the newer.
+func (q *Queries) HandInboxReturnToRow(ctx context.Context, arg HandInboxReturnToRowParams) error {
+ _, err := q.db.Exec(ctx, handInboxReturnToRow,
+ arg.WorkspaceID,
+ arg.RecipientType,
+ arg.RecipientID,
+ arg.IssueID,
+ arg.KeepID,
+ )
+ return err
+}
+
const inboxOverflows = `-- name: InboxOverflows :one
SELECT count(*) > 0 FROM (
SELECT 1 FROM inbox_item i
@@ -575,6 +661,49 @@ func (q *Queries) InboxOverflows(ctx context.Context, arg InboxOverflowsParams)
return column_1, err
}
+const inboxReturnsSettled = `-- name: InboxReturnsSettled :one
+WITH marked AS MATERIALIZED (
+ SELECT g.issue_id, max(g.returned_at) AS returned_at
+ FROM inbox_item g
+ WHERE g.workspace_id = $1 AND g.recipient_type = $2 AND g.recipient_id = $3
+ AND g.archived = false AND g.issue_id IS NOT NULL
+ AND (g.returned_at IS NOT NULL OR g.snoozed_until IS NOT NULL)
+ GROUP BY g.issue_id
+), wanted AS MATERIALIZED (
+ SELECT DISTINCT ON (r.issue_id) r.issue_id, r.id,
+ GREATEST(marked.returned_at, r.snoozed_until) AS returned_at
+ FROM inbox_item r
+ JOIN marked ON marked.issue_id = r.issue_id
+ WHERE r.workspace_id = $1 AND r.recipient_type = $2 AND r.recipient_id = $3
+ AND r.archived = false
+ ORDER BY r.issue_id, r.created_at DESC, r.id DESC
+)
+SELECT count(*) = 0 FROM (
+ SELECT 1 FROM inbox_item item
+ JOIN wanted ON wanted.issue_id = item.issue_id
+ WHERE item.workspace_id = $1 AND item.recipient_type = $2 AND item.recipient_id = $3
+ AND item.archived = false
+ AND item.returned_at IS DISTINCT FROM (CASE WHEN item.id = wanted.id THEN wanted.returned_at END)
+ LIMIT 1
+) unsettled
+`
+
+type InboxReturnsSettledParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ RecipientType string `json:"recipient_type"`
+ RecipientID pgtype.UUID `json:"recipient_id"`
+}
+
+// Whether NormalizeInboxReturns has nothing left to fix for the recipient,
+// rows another write holds included. The inbox limit archives only then, so
+// an unsettled duplicate rank never widens the set of rows it keeps.
+func (q *Queries) InboxReturnsSettled(ctx context.Context, arg InboxReturnsSettledParams) (bool, error) {
+ row := q.db.QueryRow(ctx, inboxReturnsSettled, arg.WorkspaceID, arg.RecipientType, arg.RecipientID)
+ var column_1 bool
+ err := row.Scan(&column_1)
+ return column_1, err
+}
+
const listArchivedInboxItems = `-- name: ListArchivedInboxItems :many
WITH eligible_archived AS MATERIALIZED (
SELECT i.id,
@@ -1116,50 +1245,62 @@ func (q *Queries) MarkInboxUnread(ctx context.Context, id pgtype.UUID) (InboxIte
}
const normalizeInboxReturns = `-- name: NormalizeInboxReturns :execrows
-WITH ranked_groups AS (
- SELECT g.issue_id,
- max(g.returned_at) AS returned_at
+WITH marked AS MATERIALIZED (
+ SELECT g.issue_id, max(g.returned_at) AS returned_at
FROM inbox_item g
WHERE g.workspace_id = $1 AND g.recipient_type = $2
AND g.recipient_id = $3
AND g.archived = false AND g.issue_id IS NOT NULL
AND (g.returned_at IS NOT NULL OR g.snoozed_until IS NOT NULL)
GROUP BY g.issue_id
-), representative AS (
+), wanted AS MATERIALIZED (
SELECT DISTINCT ON (r.issue_id) r.issue_id, r.id,
- GREATEST(ranked_groups.returned_at, r.snoozed_until) AS returned_at
+ GREATEST(marked.returned_at, r.snoozed_until) AS returned_at
FROM inbox_item r
- JOIN ranked_groups ON ranked_groups.issue_id = r.issue_id
+ JOIN marked ON marked.issue_id = r.issue_id
WHERE r.workspace_id = $1 AND r.recipient_type = $2
AND r.recipient_id = $3
AND r.archived = false
ORDER BY r.issue_id, r.created_at DESC, r.id DESC
+), stale AS (
+ SELECT item.id, CASE WHEN item.id = wanted.id THEN wanted.returned_at END AS returned_at
+ FROM inbox_item item
+ JOIN wanted ON wanted.issue_id = item.issue_id
+ WHERE item.workspace_id = $1 AND item.recipient_type = $2
+ AND item.recipient_id = $3
+ AND item.archived = false
+ AND item.returned_at IS DISTINCT FROM (CASE WHEN item.id = wanted.id THEN wanted.returned_at END)
+ ORDER BY item.issue_id, item.id
+ LIMIT $4::int
+ FOR UPDATE OF item SKIP LOCKED
)
-UPDATE inbox_item AS item
-SET returned_at = CASE WHEN item.id = representative.id THEN representative.returned_at END
-FROM representative
-WHERE item.workspace_id = $1 AND item.recipient_type = $2
- AND item.recipient_id = $3
- AND item.archived = false
- AND item.issue_id = representative.issue_id
- AND item.returned_at IS DISTINCT FROM (CASE WHEN item.id = representative.id THEN representative.returned_at END)
+UPDATE inbox_item AS fixed
+SET returned_at = (SELECT stale.returned_at FROM stale WHERE stale.id = fixed.id)
+WHERE fixed.id = ANY (ARRAY(SELECT stale.id FROM stale))
`
type NormalizeInboxReturnsParams struct {
WorkspaceID pgtype.UUID `json:"workspace_id"`
RecipientType string `json:"recipient_type"`
RecipientID pgtype.UUID `json:"recipient_id"`
+ BatchSize int32 `json:"batch_size"`
}
// Leaves at most one row per issue ranked by its return (returned_at): the
// issue's newest active row, carrying the latest return any of its rows had,
-// or its snooze time. Rows that joined a snooze after it started (a comment
-// that arrived meanwhile) thereby take over the issue's rank from the row that
-// was newest when it was snoozed, and snoozes written without returned_at (by
-// an older server, before the column existed) get one. The inbox limit runs
-// this before it archives anything, so a ranking gap never costs a row.
+// or its snooze time. Writes keep this true; this repairs what they could not,
+// such as rows an older server wrote during a rollout. Fixes up to batch_size
+// rows, skipping rows another write holds, so it never waits on a lock; the
+// caller runs it again while it returns a full batch.
+// MATERIALIZED: each step runs once; inlined, a planner without statistics
+// re-ran them for every row.
func (q *Queries) NormalizeInboxReturns(ctx context.Context, arg NormalizeInboxReturnsParams) (int64, error) {
- result, err := q.db.Exec(ctx, normalizeInboxReturns, arg.WorkspaceID, arg.RecipientType, arg.RecipientID)
+ result, err := q.db.Exec(ctx, normalizeInboxReturns,
+ arg.WorkspaceID,
+ arg.RecipientType,
+ arg.RecipientID,
+ arg.BatchSize,
+ )
if err != nil {
return 0, err
}
diff --git a/server/pkg/db/queries/inbox.sql b/server/pkg/db/queries/inbox.sql
index f1b4e7535c..f9c50ab98a 100644
--- a/server/pkg/db/queries/inbox.sql
+++ b/server/pkg/db/queries/inbox.sql
@@ -127,15 +127,17 @@ WHERE id = $1 AND workspace_id = $2;
-- MUL-9333: a row written on an issue the recipient has snoozed joins the
-- snooze, so it stays out of the inbox with the rest of the issue.
-- inbox.Deliver ends the snooze instead when the row is one that
--- wakes it.
+-- wakes it. A joining row is the issue's newest, so it carries the issue's
+-- return rank (returned_at, the snooze end); inbox.Deliver clears it from the
+-- row that held it (HandInboxReturnToRow).
INSERT INTO inbox_item (
workspace_id, recipient_type, recipient_id,
type, severity, issue_id, title, body,
actor_type, actor_id, details, id,
- snoozed_until, snoozed_at
+ snoozed_until, snoozed_at, returned_at
)
SELECT $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, COALESCE(sqlc.narg('id')::uuid, gen_random_uuid()),
- snoozed.snoozed_until, snoozed.snoozed_at
+ snoozed.snoozed_until, snoozed.snoozed_at, snoozed.snoozed_until
FROM (SELECT 1) AS one
LEFT JOIN LATERAL (
SELECT s.snoozed_until, s.snoozed_at
@@ -505,7 +507,8 @@ SELECT count(*) > 0 FROM (
-- behind the user's back, and hidden rows never push out visible ones. SKIP LOCKED keeps a trim from waiting on, or
-- deadlocking with, the user's own inbox writes; InboxOverflows tells the
-- caller whether skipped rows remain.
-WITH boundary AS (
+-- MATERIALIZED: the boundary is read once per statement, not once per row.
+WITH boundary AS MATERIALIZED (
SELECT GREATEST(b.created_at, b.returned_at) AS shown_at, b.id
FROM inbox_item b
LEFT JOIN issue b_iss ON b_iss.id = b.issue_id
@@ -529,6 +532,18 @@ WITH boundary AS (
AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR o_iss.project_id IS NULL
OR NOT (o_iss.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
AND (GREATEST(o.created_at, o.returned_at), o.id) < (boundary.shown_at, boundary.id)
+ -- An issue back from a snooze whose newest row does not carry the
+ -- return yet (written by an older server, or not normalized) ranks too
+ -- low here; never archive that row on its stale rank.
+ AND NOT (o.issue_id IS NOT NULL AND o.snoozed_until IS NOT NULL
+ AND (o.returned_at IS NULL OR o.returned_at < o.snoozed_until)
+ AND NOT EXISTS (
+ SELECT 1 FROM inbox_item newer
+ WHERE newer.workspace_id = o.workspace_id AND newer.recipient_type = o.recipient_type
+ AND newer.recipient_id = o.recipient_id AND newer.issue_id = o.issue_id
+ AND newer.archived = false
+ AND (newer.created_at, newer.id) > (o.created_at, o.id)
+ ))
ORDER BY GREATEST(o.created_at, o.returned_at), o.id
LIMIT sqlc.arg('batch_size')::int
FOR UPDATE OF o SKIP LOCKED
@@ -541,35 +556,107 @@ WHERE item.id = ANY (ARRAY(SELECT overflow.id FROM overflow));
-- name: NormalizeInboxReturns :execrows
-- Leaves at most one row per issue ranked by its return (returned_at): the
-- issue's newest active row, carrying the latest return any of its rows had,
--- or its snooze time. Rows that joined a snooze after it started (a comment
--- that arrived meanwhile) thereby take over the issue's rank from the row that
--- was newest when it was snoozed, and snoozes written without returned_at (by
--- an older server, before the column existed) get one. The inbox limit runs
--- this before it archives anything, so a ranking gap never costs a row.
-WITH ranked_groups AS (
- SELECT g.issue_id,
- max(g.returned_at) AS returned_at
+-- or its snooze time. Writes keep this true; this repairs what they could not,
+-- such as rows an older server wrote during a rollout. Fixes up to batch_size
+-- rows, skipping rows another write holds, so it never waits on a lock; the
+-- caller runs it again while it returns a full batch.
+-- MATERIALIZED: each step runs once; inlined, a planner without statistics
+-- re-ran them for every row.
+WITH marked AS MATERIALIZED (
+ SELECT g.issue_id, max(g.returned_at) AS returned_at
FROM inbox_item g
WHERE g.workspace_id = sqlc.arg('workspace_id') AND g.recipient_type = sqlc.arg('recipient_type')
AND g.recipient_id = sqlc.arg('recipient_id')
AND g.archived = false AND g.issue_id IS NOT NULL
AND (g.returned_at IS NOT NULL OR g.snoozed_until IS NOT NULL)
GROUP BY g.issue_id
-), representative AS (
+), wanted AS MATERIALIZED (
SELECT DISTINCT ON (r.issue_id) r.issue_id, r.id,
- GREATEST(ranked_groups.returned_at, r.snoozed_until) AS returned_at
+ GREATEST(marked.returned_at, r.snoozed_until) AS returned_at
FROM inbox_item r
- JOIN ranked_groups ON ranked_groups.issue_id = r.issue_id
+ JOIN marked ON marked.issue_id = r.issue_id
WHERE r.workspace_id = sqlc.arg('workspace_id') AND r.recipient_type = sqlc.arg('recipient_type')
AND r.recipient_id = sqlc.arg('recipient_id')
AND r.archived = false
ORDER BY r.issue_id, r.created_at DESC, r.id DESC
+), stale AS (
+ SELECT item.id, CASE WHEN item.id = wanted.id THEN wanted.returned_at END AS returned_at
+ FROM inbox_item item
+ JOIN wanted ON wanted.issue_id = item.issue_id
+ WHERE item.workspace_id = sqlc.arg('workspace_id') AND item.recipient_type = sqlc.arg('recipient_type')
+ AND item.recipient_id = sqlc.arg('recipient_id')
+ AND item.archived = false
+ AND item.returned_at IS DISTINCT FROM (CASE WHEN item.id = wanted.id THEN wanted.returned_at END)
+ ORDER BY item.issue_id, item.id
+ LIMIT sqlc.arg('batch_size')::int
+ FOR UPDATE OF item SKIP LOCKED
)
-UPDATE inbox_item AS item
-SET returned_at = CASE WHEN item.id = representative.id THEN representative.returned_at END
-FROM representative
-WHERE item.workspace_id = sqlc.arg('workspace_id') AND item.recipient_type = sqlc.arg('recipient_type')
- AND item.recipient_id = sqlc.arg('recipient_id')
- AND item.archived = false
- AND item.issue_id = representative.issue_id
- AND item.returned_at IS DISTINCT FROM (CASE WHEN item.id = representative.id THEN representative.returned_at END);
+UPDATE inbox_item AS fixed
+SET returned_at = (SELECT stale.returned_at FROM stale WHERE stale.id = fixed.id)
+WHERE fixed.id = ANY (ARRAY(SELECT stale.id FROM stale));
+
+-- name: HandInboxReturnToRow :exec
+-- Clears the issue's return rank from the active rows older than keep_id, the
+-- row that now carries it (see CreateInboxItem). Only older rows: two joining
+-- rows handing over concurrently, in either order, leave the rank on the newer.
+UPDATE inbox_item AS item SET returned_at = NULL
+FROM inbox_item AS kept
+WHERE kept.id = sqlc.arg('keep_id')
+ AND item.workspace_id = $1 AND item.recipient_type = $2 AND item.recipient_id = $3 AND item.issue_id = $4
+ AND item.archived = false AND item.returned_at IS NOT NULL
+ AND (item.created_at, item.id) < (kept.created_at, kept.id);
+
+-- name: InboxReturnsSettled :one
+-- Whether NormalizeInboxReturns has nothing left to fix for the recipient,
+-- rows another write holds included. The inbox limit archives only then, so
+-- an unsettled duplicate rank never widens the set of rows it keeps.
+WITH marked AS MATERIALIZED (
+ SELECT g.issue_id, max(g.returned_at) AS returned_at
+ FROM inbox_item g
+ WHERE g.workspace_id = $1 AND g.recipient_type = $2 AND g.recipient_id = $3
+ AND g.archived = false AND g.issue_id IS NOT NULL
+ AND (g.returned_at IS NOT NULL OR g.snoozed_until IS NOT NULL)
+ GROUP BY g.issue_id
+), wanted AS MATERIALIZED (
+ SELECT DISTINCT ON (r.issue_id) r.issue_id, r.id,
+ GREATEST(marked.returned_at, r.snoozed_until) AS returned_at
+ FROM inbox_item r
+ JOIN marked ON marked.issue_id = r.issue_id
+ WHERE r.workspace_id = $1 AND r.recipient_type = $2 AND r.recipient_id = $3
+ AND r.archived = false
+ ORDER BY r.issue_id, r.created_at DESC, r.id DESC
+)
+SELECT count(*) = 0 FROM (
+ SELECT 1 FROM inbox_item item
+ JOIN wanted ON wanted.issue_id = item.issue_id
+ WHERE item.workspace_id = $1 AND item.recipient_type = $2 AND item.recipient_id = $3
+ AND item.archived = false
+ AND item.returned_at IS DISTINCT FROM (CASE WHEN item.id = wanted.id THEN wanted.returned_at END)
+ LIMIT 1
+) unsettled;
+
+-- name: BackfillInboxSnoozeReturns :execrows
+-- Gives up to batch_size snoozed issues their return rank where a writer that
+-- predates returned_at left it out: the issue's newest active row ranks by
+-- when the snooze ends. Snoozes set before the column existed, and by an
+-- older server during the rollout. Skips rows another write holds and
+-- touches only rows still without a rank, so it can run again at any time.
+-- workspace_id narrows it for tests; production passes NULL.
+WITH candidates AS (
+ SELECT s.id
+ FROM inbox_item s
+ WHERE (sqlc.narg('workspace_id')::uuid IS NULL OR s.workspace_id = sqlc.narg('workspace_id')::uuid)
+ AND s.archived = false AND s.issue_id IS NOT NULL
+ AND s.snoozed_until IS NOT NULL AND s.returned_at IS NULL
+ AND NOT EXISTS (
+ SELECT 1 FROM inbox_item newer
+ WHERE newer.workspace_id = s.workspace_id AND newer.recipient_type = s.recipient_type
+ AND newer.recipient_id = s.recipient_id AND newer.issue_id = s.issue_id
+ AND newer.archived = false
+ AND (newer.created_at, newer.id) > (s.created_at, s.id)
+ )
+ LIMIT sqlc.arg('batch_size')::int
+ FOR UPDATE OF s SKIP LOCKED
+)
+UPDATE inbox_item AS item SET returned_at = item.snoozed_until
+WHERE item.id = ANY (ARRAY(SELECT candidates.id FROM candidates));