Skip to content

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

Go

MUL-9644 feat(inbox): keep each inbox to its newest 2,000 notifications (#10969)

Multica Eve1fecba3a303b
diff --git a/apps/docs/content/docs/inbox.fr.mdx b/apps/docs/content/docs/inbox.fr.mdx
index 9aed285ba8..73479f98c3 100644
--- a/apps/docs/content/docs/inbox.fr.mdx
+++ b/apps/docs/content/docs/inbox.fr.mdx
@@ -135,6 +135,7 @@ Lire une notification ne la retire pas. Une ligne quitte la boîte de réception
- quand vous reportez sa tâche. C'est temporaire : la tâche revient à l'heure choisie, ou plus tôt si quelque chose a besoin de vous. Voir « Reporter une tâche » ci-dessus ;
- quand vous passez vous-même sa tâche à n'importe quel statut des catégories `done` ou `closed`, tant que **Archiver les tâches que vous terminez** est activé (c'est le cas par défaut). Seules vos propres notifications sur cette tâche sont archivées, lues ou non. Quand quelqu'un d'autre ou un agent termine une tâche, ses notifications restent dans votre boîte de réception, pour que vous voyiez la nouvelle ;
- quand c'est une notification **Exécution en échec** et que sa tâche passe à un statut qui la rend à une personne : `in_review`, un statut personnalisé de la catégorie `started`, ou n'importe quel statut des catégories `done` ou `closed`. Les notifications Exécution en échec de tout le monde sur cette tâche sont alors archivées, quelle que soit la personne qui a changé le statut, et indépendamment du réglage ci-dessus. `blocked` fait exception : il rend aussi la tâche, mais le travail reste bloqué, donc les échecs précédents méritent encore d'être lus.
+- quand votre boîte de réception dans l'espace de travail dépasse 2 000 notifications. Elle garde les 2 000 plus récentes et archive peu après les plus anciennes, lues ou non. Une notification revenue d'un report ou restaurée depuis l'archive compte à partir de son retour. Les notifications d'une tâche reportée ne comptent pas et restent en place.
Les fenêtres ouvertes retirent aussitôt une ligne archivée, sauf celle que vous avez ouverte. Quand sa notification quitte la boîte de réception autrement (vous passez la tâche à `done` depuis son statut, une autre fenêtre l'archive, ou une modification la sort des filtres de la section), la ligne reste en surbrillance à sa place et l'en-tête de la tâche indique ce qui s'est passé. **Annuler** fait revenir la notification, et **Suivante** (ou `E`) ouvre la ligne suivante. La ligne disparaît dès que vous passez à autre chose.
diff --git a/apps/docs/content/docs/inbox.ja.mdx b/apps/docs/content/docs/inbox.ja.mdx
index 5e089a19ca..05be00d534 100644
--- a/apps/docs/content/docs/inbox.ja.mdx
+++ b/apps/docs/content/docs/inbox.ja.mdx
@@ -135,6 +135,7 @@ multica inbox snooze <id>... --until tomorrow # RFC 3339、30m、3h、1d、1w
- タスクをスヌーズしたとき。これは一時的で、指定した時間になるか、対応が必要な通知が届くと戻ります。上の「タスクをスヌーズする」を参照してください。
- **自分が完了したタスクをアーカイブ** がオン(既定でオン)の状態で、あなた自身がタスクを `done` または `closed` カテゴリのいずれかのステータスにしたとき。アーカイブされるのは、そのタスクに届いたあなた自身の通知だけで、既読かどうかは問いません。ほかの人やエージェントがタスクを完了した場合、その通知はあなたのインボックスに残るので、変化を見逃しません。
- 「実行失敗」の通知で、タスクが人に引き継がれるステータスになったとき。対象は `in_review`、`started` カテゴリのカスタムステータス、`done`・`closed` カテゴリのすべてのステータスです。誰がステータスを変えたかにかかわらず、そのタスクの全員分の「実行失敗」の通知がアーカイブされ、上の設定には左右されません。`blocked` は例外です。人に引き継がれはしますが作業は止まったままなので、それまでの失敗の記録はまだ確認する必要があります。
+- そのワークスペースのインボックスが 2,000 件を超えたとき。新しい 2,000 件を残し、それより古い通知は既読かどうかにかかわらず、少し後に自動でアーカイブされます。スヌーズから戻った通知やアーカイブから戻した通知は、戻った時点の新しさで数えます。スヌーズ中のタスクの通知は数えず、そのまま残ります。
アーカイブされた行は、開いているウィンドウからもすぐに消えます。ただし、いま開いている行は別です。その通知がほかの理由でインボックスから外れたとき(ステータスからタスクを `done` にした、別のウィンドウでアーカイブされた、編集でセクションのフィルターに合わなくなった)、行は元の位置でハイライトされたまま残り、タスクのヘッダーに何が起きたかが表示されます。**元に戻す** で通知が戻り、**次へ**(または `E`)で次の行が開きます。行が消えるのは、ほかへ移ったときです。
diff --git a/apps/docs/content/docs/inbox.ko.mdx b/apps/docs/content/docs/inbox.ko.mdx
index 39942c5063..08e0920ae8 100644
--- a/apps/docs/content/docs/inbox.ko.mdx
+++ b/apps/docs/content/docs/inbox.ko.mdx
@@ -135,6 +135,7 @@ multica inbox snooze <id>... --until tomorrow # RFC 3339, 30m, 3h, 1d, 1w; uns
- 태스크를 미룰 때. 이 경우는 일시적이며, 지정한 시간이 되거나 내가 처리해야 할 알림이 오면 다시 돌아옵니다. 위의 '태스크 미루기'를 참고하세요.
- **내가 완료한 태스크 보관**이 켜져 있는 상태(기본값)에서 내가 직접 태스크를 `done` 또는 `closed` 카테고리의 어떤 상태로 바꿀 때. 그 태스크에 온 내 알림만 읽음 여부와 관계없이 보관됩니다. 다른 사람이나 에이전트가 태스크를 완료하면 그 알림은 내 인박스에 남으므로 변화를 놓치지 않습니다.
- "실행 실패함" 알림이고, 태스크가 사람에게 넘어가는 상태가 될 때. 해당 상태는 `in_review`, `started` 카테고리의 사용자 지정 상태, `done`·`closed` 카테고리의 모든 상태입니다. 누가 상태를 바꿨는지와 관계없이 그 태스크의 모든 사람의 "실행 실패함" 알림이 보관되며, 위 설정의 영향을 받지 않습니다. `blocked`는 예외입니다. 사람에게 넘어가기는 하지만 작업이 여전히 막혀 있으므로 지난 실패 기록을 계속 확인해야 합니다.
+- 그 워크스페이스의 인박스가 알림 2,000개를 넘을 때. 최신 2,000개를 남기고, 그보다 오래된 알림은 읽음 여부와 관계없이 잠시 후 자동으로 보관됩니다. 미루기에서 돌아온 알림과 보관함에서 복원한 알림은 돌아온 시점을 기준으로 셉니다. 미룬 태스크의 알림은 개수에 포함되지 않으며 그대로 남습니다.
보관된 행은 열려 있는 창에서도 바로 사라집니다. 단, 지금 열어 둔 행은 예외입니다. 그 알림이 다른 이유로 인박스에서 빠지면(상태에서 태스크를 `done`으로 바꿨거나, 다른 창에서 보관했거나, 편집으로 섹션 필터에 더 이상 맞지 않게 된 경우) 행은 제자리에서 강조된 채 남고, 태스크 헤더에 무슨 일이 있었는지 표시됩니다. **실행 취소**로 알림을 되돌리고, **다음**(또는 `E`)으로 다음 행을 엽니다. 행은 다른 곳으로 이동할 때 사라집니다.
diff --git a/apps/docs/content/docs/inbox.mdx b/apps/docs/content/docs/inbox.mdx
index c4da76b650..698d48a3fa 100644
--- a/apps/docs/content/docs/inbox.mdx
+++ b/apps/docs/content/docs/inbox.mdx
@@ -135,6 +135,7 @@ Reading a notification doesn't remove it. A row leaves the inbox only when:
- you snooze its issue. This one is temporary: the issue comes back at the time you picked, or earlier when something needs you. See [Snooze an issue](#snooze-an-issue);
- you move its issue to any status in the `done` or `closed` category yourself, while **Archive issues you complete** is on (it is by default). Only your own notifications on that issue are archived, read or not. When someone else or an agent completes an issue, its notifications stay in your inbox, so you still see the news;
- it's a **Run failed** notification and its issue moves to a status that hands it back to a person: `in_review`, a custom status in the `started` category, or any status in the `done` or `closed` category. This archives everyone's Run failed notifications on the issue, whoever moved it, and doesn't depend on the setting above. `blocked` is the exception: it hands the issue over too, but the work is still stuck, so the earlier failures are still worth reading.
+- your inbox in the workspace goes past 2,000 notifications. It keeps the newest 2,000 and shortly afterwards archives the older ones, read or not. A notification that comes back from a snooze or that you restore from the archive counts from when it came back. Notifications on a snoozed issue don't count and are left alone.
Open windows drop an archived row right away, except the one you have open. When its notification leaves the inbox some other way (you set the issue to `done` from its status, another window archived it, or an edit took it out of the section's filters), the row stays lit where it was and the issue header says what happened. **Undo** brings the notification back, and **Next** (or `E`) opens the next row. The row leaves once you move on.
diff --git a/apps/docs/content/docs/inbox.zh-Hant.mdx b/apps/docs/content/docs/inbox.zh-Hant.mdx
index c9a7ea2072..09795a4012 100644
--- a/apps/docs/content/docs/inbox.zh-Hant.mdx
+++ b/apps/docs/content/docs/inbox.zh-Hant.mdx
@@ -135,6 +135,7 @@ multica inbox snooze <id>... --until tomorrow # RFC 3339、30m、3h、1d、1w
- 你延後了它的任務。這是暫時的:到你選的時間,或有需要你處理的通知時,它會回來。見上方的「延後任務」;
- 你親自把它的任務改為 `done` 或 `closed` 分類下的任一狀態,且**自動歸檔我完成的任務**處於開啟狀態(預設開啟)。只歸檔你自己在該任務上的通知,無論是否已讀。別人或 AI 代理完成的任務,通知會留在你的收件箱裡,你仍能看到這個變化;
- 它是"執行失敗"通知,且任務進入交回給人的狀態:`in_review`、`started` 分類下的自定義狀態,或 `done`、`closed` 分類下的任一狀態。這會歸檔所有人在該任務上的"執行失敗"通知,不論是誰改的狀態,也不受上面的開關影響。`blocked` 例外:它同樣交回給人,但工作還卡著,之前的失敗記錄還要看。
+- 你在該工作區的收件箱超過 2,000 條通知。收件箱保留最新的 2,000 條,隨後自動歸檔更早的通知,無論是否已讀。從延後中回來或從歸檔中還原的通知,按回來的時間算作新通知。已延後任務上的通知不計入,也不會被歸檔。
開著的視窗會立即移除已歸檔的列,但你正開著的那一列除外。它的通知因為其他原因離開收件箱時(你在狀態裡把任務改為 `done`、別的視窗歸檔了它,或修改後不再符合分區的篩選),這一列會在原位保持高亮,任務頁首會說明發生了什麼:**復原**讓通知回來,**下一條**(或按 `E`)開啟下一列。你離開之後,這一列才會移出。
diff --git a/apps/docs/content/docs/inbox.zh.mdx b/apps/docs/content/docs/inbox.zh.mdx
index 5d4d2084e7..3158cc2dd1 100644
--- a/apps/docs/content/docs/inbox.zh.mdx
+++ b/apps/docs/content/docs/inbox.zh.mdx
@@ -135,6 +135,7 @@ multica inbox snooze <id>... --until tomorrow # RFC 3339、30m、3h、1d、1w
- 你延后了它的任务。这是暂时的:到你选的时间,或有需要你处理的通知时,它会回来。见上方的「延后任务」;
- 你亲自把它的任务改为 `done` 或 `closed` 分类下的任一状态,且**自动归档我完成的任务**处于开启状态(默认开启)。只归档你自己在该任务上的通知,无论是否已读。别人或智能体完成的任务,通知会留在你的收件箱里,你仍能看到这个变化;
- 它是"运行失败"通知,且任务进入交回给人的状态:`in_review`、`started` 分类下的自定义状态,或 `done`、`closed` 分类下的任一状态。这会归档所有人在该任务上的"运行失败"通知,不论是谁改的状态,也不受上面的开关影响。`blocked` 例外:它同样交回给人,但工作还卡着,之前的失败记录还要看。
+- 你在该工作区的收件箱超过 2,000 条通知。收件箱保留最新的 2,000 条,随后自动归档更早的通知,无论是否已读。从延后中回来或从归档中还原的通知,按回来的时间算作新通知。已延后任务上的通知不计入,也不会被归档。
打开着的窗口会立即移除已归档的行,但你正打开的那一行除外。它的通知因为其他原因离开收件箱时(你在状态里把任务改为 `done`、别的窗口归档了它,或修改后不再符合分区的筛选),这一行会在原位保持高亮,任务页头会说明发生了什么:**撤销**让通知回来,**下一条**(或按 `E`)打开下一行。你离开之后,这一行才会移出。
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index 45115a248a..defa69583e 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -152,6 +152,7 @@ var concurrentIndexCleanups = map[string]string{
"692_doc_folder_workspace_idx": "doc_folder_workspace_idx",
"693_doc_workspace_idx": "doc_workspace_idx",
"694_doc_version_workspace_idx": "doc_version_workspace_idx",
+ "696_inbox_item_active_shown_idx": "idx_inbox_active_shown",
"671_weixin_account_state_unique_index": "weixin_account_state_pkey",
"669_weixin_login_session_unique_index": "weixin_login_session_pkey",
"666_weixin_login_expiry_idx": "weixin_login_expiry_idx",
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index 20f41760b3..4e28a7ba97 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -22,6 +22,7 @@ import (
"github.com/multica-ai/multica/server/internal/dbstartup"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/handler"
+ "github.com/multica-ai/multica/server/internal/inbox"
"github.com/multica-ai/multica/server/internal/integrations/wecom"
"github.com/multica-ai/multica/server/internal/logger"
"github.com/multica-ai/multica/server/internal/maintenance"
@@ -617,6 +618,8 @@ func main() {
registerNotificationListeners(bus, queries)
registerChatReplyNotifications(bus, broadcaster, &membershipChecker{queries: queries})
registerIssueUnreadListeners(bus, queries)
+ inboxTrimmer := inbox.NewTrimmer(queries, bus)
+ inboxTrimmer.Subscribe(bus)
metricsConfig := obsmetrics.ConfigFromEnv()
var metricsServer *http.Server
@@ -702,6 +705,7 @@ func main() {
// member_delegation_day exists only for self-host telemetry; DO_NOT_TRACK
// stops writing it as well as sending the snapshot.
h.TaskService.RecordMemberActivity = telemetryConfig.Enabled
+ h.InboxTrimmer = inboxTrimmer
var replicaQueries *db.Queries
if replicaPool != nil {
replicaQueries = db.New(replicaPool)
@@ -769,6 +773,7 @@ func main() {
// Source-context cleanup is object-store work, so it gets its own goroutine
// instead of a slot in the runtime sweep tick.
go runSourceContextSweeper(sweepCtx, taskSvc)
+ go inboxTrimmer.Run(sweepCtx)
go runEnvironmentLogSweeper(sweepCtx, queries)
if h.ConnectedApps != nil {
go h.ConnectedApps.RunSweeper(sweepCtx)
diff --git a/server/cmd/server/notification_listeners_test.go b/server/cmd/server/notification_listeners_test.go
index 67758b9431..8b5b98bf3a 100644
--- a/server/cmd/server/notification_listeners_test.go
+++ b/server/cmd/server/notification_listeners_test.go
@@ -8,6 +8,7 @@ import (
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/handler"
+ "github.com/multica-ai/multica/server/internal/inbox"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
@@ -58,6 +59,7 @@ func inboxItemsForRecipient(t *testing.T, queries *db.Queries, recipientID strin
WorkspaceID: util.MustParseUUID(testWorkspaceID),
RecipientType: "member",
RecipientID: util.MustParseUUID(recipientID),
+ RowLimit: inbox.ActiveLimit,
})
if err != nil {
t.Fatalf("ListInboxItems: %v", err)
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index f4639c81fb..04884681f9 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -26,6 +26,7 @@ import (
"github.com/multica-ai/multica/server/internal/dbreader"
"github.com/multica-ai/multica/server/internal/entitlement"
"github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/inbox"
"github.com/multica-ai/multica/server/internal/inboxread"
"github.com/multica-ai/multica/server/internal/integrations/channel/engine"
composio "github.com/multica-ai/multica/server/internal/integrations/composio"
@@ -221,6 +222,7 @@ type RuntimeRecoveryNotifier interface {
type Handler struct {
InboxReads *inboxread.Guard
+ InboxTrimmer *inbox.Trimmer // nil leaves inboxes untrimmed
Queries *db.Queries
ReadSelector *dbreader.Selector
DB dbExecutor
diff --git a/server/internal/handler/inbox.go b/server/internal/handler/inbox.go
index e86000802b..193794b6a3 100644
--- a/server/internal/handler/inbox.go
+++ b/server/internal/handler/inbox.go
@@ -11,6 +11,7 @@ import (
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/inbox"
"github.com/multica-ai/multica/server/internal/logger"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
@@ -246,12 +247,18 @@ func (h *Handler) ListInbox(w http.ResponseWriter, r *http.Request) {
RecipientType: "member",
RecipientID: parseUUID(userID),
HiddenProjectIds: hidden.Param(),
+ RowLimit: inbox.ActiveLimit,
})
})
if err != nil {
writeInboxReadError(w, err, "failed to list inbox")
return
}
+ // A full page may mean an inbox the trimmer has not reached yet, such as
+ // one that outgrew the limit before it existed and gets no new rows.
+ if len(items) >= inbox.ActiveLimit {
+ h.InboxTrimmer.Mark(inbox.Recipient{WorkspaceID: wsUUID, RecipientType: "member", RecipientID: parseUUID(userID)})
+ }
issuePrefix := h.getIssuePrefix(r.Context(), wsUUID)
resp := make([]InboxItemResponse, len(items))
diff --git a/server/internal/handler/inbox_limit_test.go b/server/internal/handler/inbox_limit_test.go
new file mode 100644
index 0000000000..551dc2f5c2
--- /dev/null
+++ b/server/internal/handler/inbox_limit_test.go
@@ -0,0 +1,376 @@
+package handler
+
+import (
+ "context"
+ "net/http"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/inbox"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// seedInboxRows writes count active rows for recipient, step apart (zero for
+// identical times), the newest at base and titled row-0000.
+func seedInboxRows(t *testing.T, workspaceID, recipientID string, count int, base time.Time, step time.Duration) {
+ t.Helper()
+ dbfx.Exec(t, `
+ INSERT INTO inbox_item (workspace_id, recipient_type, recipient_id, type, severity, title, created_at)
+ SELECT $1, 'member', $2, 'system', 'info', 'row-' || lpad(i::text, 4, '0'),
+ $3::timestamptz - i * $5::interval
+ FROM generate_series(0, $4::int - 1) AS i
+ `, workspaceID, recipientID, base, count, step.String())
+}
+
+func limitInboxWorkspace(t *testing.T, name string) string {
+ t.Helper()
+ workspaceID := dbfx.Workspace(t, name, "inbox-limit-"+uuid.NewString())
+ dbfx.Member(t, workspaceID, testUserID, "owner")
+ dbfx.Cleanup(t, `DELETE FROM inbox_item WHERE workspace_id = $1`, workspaceID)
+ return workspaceID
+}
+
+func insertOldInboxRow(t *testing.T, workspaceID, title string, cols testutil.Cols) string {
+ t.Helper()
+ row := testutil.Cols{
+ "workspace_id": workspaceID,
+ "recipient_type": "member",
+ "recipient_id": testUserID,
+ "type": "system",
+ "severity": "info",
+ "title": title,
+ "created_at": time.Now().Add(-48 * time.Hour),
+ }
+ for k, v := range cols {
+ row[k] = v
+ }
+ return dbfx.Insert(t, "inbox_item", row)
+}
+
+// wokeCols is a row whose snooze ran out a minute ago, as SnoozeInboxGroup
+// leaves an issue's newest row.
+func wokeCols() testutil.Cols {
+ wake := time.Now().Add(-time.Minute)
+ return testutil.Cols{"snoozed_until": wake, "snoozed_at": wake.Add(-24 * time.Hour), "returned_at": wake}
+}
+
+func trimInbox(t *testing.T, workspaceID string) []events.Event {
+ t.Helper()
+ bus := events.New()
+ var announced []events.Event
+ bus.Subscribe(protocol.EventInboxBatchArchived, func(e events.Event) { announced = append(announced, e) })
+ trimmer := inbox.NewTrimmer(testHandler.Queries, bus)
+ trimmer.Mark(inbox.Recipient{WorkspaceID: parseUUID(workspaceID), RecipientType: "member", RecipientID: parseUUID(testUserID)})
+ trimmer.Flush(context.Background())
+ return announced
+}
+
+func isArchived(t *testing.T, id string) bool {
+ t.Helper()
+ var archived bool
+ dbfx.QueryRow(t, `SELECT archived FROM inbox_item WHERE id = $1`, id).Scan(&archived)
+ return archived
+}
+
+// The list returns the newest ActiveLimit rows, ranking a row that came back
+// from a snooze or from the archive by when it came back.
+func TestListInboxReturnsNewestRowsUpToTheLimit(t *testing.T) {
+ workspaceID := limitInboxWorkspace(t, "Inbox limit list")
+ seedInboxRows(t, workspaceID, testUserID, inbox.ActiveLimit+3, time.Now().UTC().Add(-time.Hour), time.Millisecond)
+ insertOldInboxRow(t, workspaceID, "woke", wokeCols())
+ insertOldInboxRow(t, workspaceID, "restored", testutil.Cols{"returned_at": time.Now()})
+
+ var items []InboxItemResponse
+ testutil.Call(t, inboxWorkspaceHandler(testHandler.ListInbox),
+ inboxRequest(http.MethodGet, "/api/inbox", workspaceID)).
+ Want(http.StatusOK).
+ JSON(&items)
+
+ if len(items) != inbox.ActiveLimit {
+ t.Fatalf("inbox items = %d, want %d", len(items), inbox.ActiveLimit)
+ }
+ if items[0].Title != "restored" || items[1].Title != "woke" || items[2].Title != "row-0000" ||
+ items[len(items)-1].Title != "row-1997" {
+ t.Fatalf("list = %q, %q, %q .. %q; want the rows that came back on top, then the newest",
+ items[0].Title, items[1].Title, items[2].Title, items[len(items)-1].Title)
+ }
+}
+
+// The trimmer archives the shown rows beyond the newest ActiveLimit, row by
+// row, and leaves snoozed rows, rows that came back, and other inboxes alone.
+func TestInboxTrimmerArchivesRowsBeyondTheLimit(t *testing.T) {
+ workspaceID := limitInboxWorkspace(t, "Inbox limit trim")
+ otherID := dbfx.User(t, "Other inbox owner", "inbox-limit-"+uuid.NewString()+"@example.com")
+ dbfx.Member(t, workspaceID, otherID, "member")
+
+ base := time.Now().UTC().Add(-time.Hour)
+ extra := 150
+ seedInboxRows(t, workspaceID, testUserID, inbox.ActiveLimit+extra, base, time.Millisecond)
+ seedInboxRows(t, workspaceID, otherID, inbox.ActiveLimit+extra, base, time.Millisecond)
+ issueID := dbfx.Issue(t, "Snoozed issue", testutil.Cols{"workspace_id": workspaceID})
+ snoozedID := insertOldInboxRow(t, workspaceID, "snoozed", testutil.Cols{
+ "issue_id": issueID,
+ "snoozed_until": time.Now().Add(time.Hour),
+ "snoozed_at": time.Now(),
+ })
+ wokeID := insertOldInboxRow(t, workspaceID, "woke", wokeCols())
+ restoredID := insertOldInboxRow(t, workspaceID, "restored", testutil.Cols{"returned_at": time.Now()})
+
+ announced := trimInbox(t, workspaceID)
+
+ var active, archived int
+ var oldestKept string
+ dbfx.QueryRow(t, `
+ SELECT count(*) FILTER (WHERE NOT archived), count(*) FILTER (WHERE archived),
+ (SELECT title FROM inbox_item WHERE workspace_id = $1 AND recipient_id = $2
+ AND NOT archived AND title LIKE 'row-%' ORDER BY created_at LIMIT 1)
+ FROM inbox_item
+ WHERE workspace_id = $1 AND recipient_id = $2 AND title LIKE 'row-%'
+ `, workspaceID, testUserID).Scan(&active, &archived, &oldestKept)
+ // The woken and restored rows rank on top, so two more seeded rows go.
+ if active != inbox.ActiveLimit-2 || archived != extra+2 || oldestKept != "row-1997" {
+ t.Fatalf("seeded rows active=%d archived=%d oldest kept=%q", active, archived, oldestKept)
+ }
+ if isArchived(t, snoozedID) || isArchived(t, wokeID) || isArchived(t, restoredID) {
+ t.Fatal("archived a snoozed row or a row that came back")
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM inbox_item WHERE workspace_id = $1 AND recipient_id = $2 AND NOT archived`,
+ workspaceID, otherID); n != inbox.ActiveLimit+extra {
+ t.Fatalf("unmarked inbox active rows = %d, want untouched %d", n, inbox.ActiveLimit+extra)
+ }
+ if len(announced) != 1 {
+ t.Fatalf("batch-archived events = %d, want 1", len(announced))
+ }
+ if payload := announced[0].Payload.(map[string]any); payload["recipient_id"] != testUserID || payload["count"] != int64(extra+2) {
+ t.Fatalf("event payload = %v", payload)
+ }
+}
+
+// Rows written in the same instant are cut by id, the list's tie-break, so
+// exactly ActiveLimit stay and they are the ones the list shows.
+func TestInboxTrimmerCutsIdenticalTimesByID(t *testing.T) {
+ workspaceID := limitInboxWorkspace(t, "Inbox limit ties")
+ seedInboxRows(t, workspaceID, testUserID, inbox.ActiveLimit+201, time.Now().UTC().Add(-time.Hour), 0)
+
+ trimInbox(t, workspaceID)
+
+ var items []InboxItemResponse
+ testutil.Call(t, inboxWorkspaceHandler(testHandler.ListInbox),
+ inboxRequest(http.MethodGet, "/api/inbox", workspaceID)).
+ Want(http.StatusOK).
+ JSON(&items)
+ active := dbfx.Count(t, `SELECT count(*) FROM inbox_item WHERE workspace_id = $1 AND NOT archived`, workspaceID)
+ if active != inbox.ActiveLimit || len(items) != inbox.ActiveLimit {
+ t.Fatalf("active=%d listed=%d, want %d of each", active, len(items), inbox.ActiveLimit)
+ }
+ listedArchived := dbfx.Count(t, `SELECT count(*) FROM inbox_item WHERE id = ANY($1::uuid[]) AND archived`, inboxItemIDs(items))
+ if listedArchived != 0 {
+ t.Fatalf("%d listed rows were archived; the trim must keep exactly what the list shows", listedArchived)
+ }
+}
+
+func inboxItemIDs(items []InboxItemResponse) []string {
+ ids := make([]string, len(items))
+ for i, item := range items {
+ ids[i] = item.ID
+ }
+ return ids
+}
+
+// Restoring a notification older than the newest ActiveLimit brings it back
+// into the list instead of leaving it in neither list.
+func TestUnarchiveRanksOldNotificationAsBack(t *testing.T) {
+ workspaceID := limitInboxWorkspace(t, "Inbox limit restore")
+ seedInboxRows(t, workspaceID, testUserID, inbox.ActiveLimit, time.Now().UTC().Add(-time.Hour), time.Millisecond)
+ oldID := insertOldInboxRow(t, workspaceID, "restored", testutil.Cols{"archived": true})
+
+ testutil.Call(t, inboxWorkspaceHandler(testHandler.UnarchiveInboxItem),
+ testutil.WithURLParams(inboxRequest(http.MethodPost, "/api/inbox/"+oldID+"/unarchive", workspaceID), "id", oldID)).
+ Want(http.StatusOK)
+ trimInbox(t, workspaceID)
+
+ var items []InboxItemResponse
+ testutil.Call(t, inboxWorkspaceHandler(testHandler.ListInbox),
+ inboxRequest(http.MethodGet, "/api/inbox", workspaceID)).
+ Want(http.StatusOK).
+ JSON(&items)
+ if isArchived(t, oldID) || len(items) == 0 || items[0].ID != oldID {
+ t.Fatalf("restored row archived=%v, list head=%v; want it back on top", isArchived(t, oldID), items[0].Title)
+ }
+}
+
+// Restoring a busy issue brings back the restored row on top, but its older
+// rows keep their rank, so they do not push the rest of the inbox out.
+func TestUnarchiveBusyIssueKeepsOtherRowsInTheInbox(t *testing.T) {
+ workspaceID := limitInboxWorkspace(t, "Inbox limit busy restore")
+ base := time.Now().UTC().Add(-time.Hour)
+ seedInboxRows(t, workspaceID, testUserID, inbox.ActiveLimit, base, time.Millisecond)
+ issueID := dbfx.Issue(t, "Busy archived issue", testutil.Cols{"workspace_id": workspaceID})
+ dbfx.Exec(t, `
+ INSERT INTO inbox_item (workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, archived, created_at)
+ SELECT $1, 'member', $2, 'new_comment', 'info', $3, 'busy', true, $4::timestamptz - i * interval '1 millisecond'
+ FROM generate_series(0, $5::int) AS i
+ `, workspaceID, testUserID, issueID, base.Add(-24*time.Hour), inbox.ActiveLimit)
+ var newestID string
+ dbfx.QueryRow(t, `SELECT id FROM inbox_item WHERE issue_id = $1 ORDER BY created_at DESC LIMIT 1`, issueID).Scan(&newestID)
+
+ testutil.Call(t, inboxWorkspaceHandler(testHandler.UnarchiveInboxItem),
+ testutil.WithURLParams(inboxRequest(http.MethodPost, "/api/inbox/"+newestID+"/unarchive", workspaceID), "id", newestID)).
+ Want(http.StatusOK)
+ trimInbox(t, workspaceID)
+
+ plain := dbfx.Count(t, `SELECT count(*) FROM inbox_item WHERE workspace_id = $1 AND issue_id IS NULL AND NOT archived`, workspaceID)
+ if plain != inbox.ActiveLimit-1 || isArchived(t, newestID) {
+ t.Fatalf("other rows kept=%d, restored row archived=%v; want %d kept beside the restored issue",
+ plain, isArchived(t, newestID), inbox.ActiveLimit-1)
+ }
+}
+
+// Snoozing ranks only the issue's newest row by the wake time; ending the
+// snooze early ranks it by now.
+func TestSnoozeRanksOnlyTheNewestRowByItsReturn(t *testing.T) {
+ workspaceID := limitInboxWorkspace(t, "Inbox limit snooze rank")
+ issueID := dbfx.Issue(t, "Snoozed busy issue", testutil.Cols{"workspace_id": workspaceID})
+ olderID := insertOldInboxRow(t, workspaceID, "older", testutil.Cols{"issue_id": issueID})
+ newestID := insertOldInboxRow(t, workspaceID, "newest", testutil.Cols{"issue_id": issueID, "created_at": time.Now().Add(-time.Hour)})
+
+ until := time.Now().Add(time.Hour).UTC().Truncate(time.Microsecond)
+ if _, err := testHandler.Queries.SnoozeInboxGroup(context.Background(), db.SnoozeInboxGroupParams{
+ ID: parseUUID(newestID), SnoozedUntil: pgtype.Timestamptz{Time: until, Valid: true},
+ }); err != nil {
+ t.Fatal(err)
+ }
+ returnedAt := func(id string) *time.Time {
+ var at *time.Time
+ dbfx.QueryRow(t, `SELECT returned_at FROM inbox_item WHERE id = $1`, id).Scan(&at)
+ return at
+ }
+ if at := returnedAt(newestID); at == nil || !at.Equal(until) || returnedAt(olderID) != nil {
+ t.Fatalf("after snooze newest returned_at=%v older=%v; want only the newest at %v", at, returnedAt(olderID), until)
+ }
+
+ if _, err := testHandler.Queries.UnsnoozeInboxGroup(context.Background(), db.UnsnoozeInboxGroupParams{
+ WorkspaceID: parseUUID(workspaceID), RecipientType: "member", RecipientID: parseUUID(testUserID), IssueID: parseUUID(issueID),
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if at := returnedAt(newestID); at == nil || time.Since(*at) > time.Minute || at.After(until) || returnedAt(olderID) != nil {
+ t.Fatalf("after unsnooze newest returned_at=%v older=%v; want only the newest, at about now", at, returnedAt(olderID))
+ }
+}
+
+// Rows in a private project the member cannot see are not shown, so they
+// neither count toward the limit nor push out rows the member can see.
+func TestInboxTrimmerIgnoresRowsTheMemberCannotSee(t *testing.T) {
+ workspaceID := limitInboxWorkspace(t, "Inbox limit hidden")
+ projectID := dbfx.Project(t, "Private project", testutil.Cols{"workspace_id": workspaceID, "visibility": "private"})
+ hiddenIssueID := dbfx.Issue(t, "Hidden issue", testutil.Cols{"workspace_id": workspaceID, "project_id": projectID})
+ dbfx.Exec(t, `
+ INSERT INTO inbox_item (workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, created_at)
+ SELECT $1, 'member', $2, 'new_comment', 'info', $3, 'hidden', now() - i * interval '1 millisecond'
+ FROM generate_series(0, $4::int - 1) AS i
+ `, workspaceID, testUserID, hiddenIssueID, inbox.ActiveLimit)
+ visibleID := insertOldInboxRow(t, workspaceID, "visible", nil)
+
+ trimInbox(t, workspaceID)
+
+ if isArchived(t, visibleID) {
+ t.Fatal("a visible row was archived to make room for rows the member cannot see")
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM inbox_item WHERE issue_id = $1 AND NOT archived`, hiddenIssueID); n != inbox.ActiveLimit {
+ t.Fatalf("hidden rows active = %d, want untouched %d", n, inbox.ActiveLimit)
+ }
+}
+
+func returnedAtOf(t *testing.T, id string) *time.Time {
+ t.Helper()
+ var at *time.Time
+ dbfx.QueryRow(t, `SELECT returned_at FROM inbox_item WHERE id = $1`, id).Scan(&at)
+ return at
+}
+
+// A snooze written before returned_at existed (or by an older server during a
+// rollout) carries only snoozed_until. The trim gives its issue's newest row
+// the wake rank before it archives anything, so the woken issue stays.
+func TestInboxTrimmerKeepsSnoozeWrittenWithoutReturn(t *testing.T) {
+ workspaceID := limitInboxWorkspace(t, "Inbox limit legacy snooze")
+ seedInboxRows(t, workspaceID, testUserID, inbox.ActiveLimit, time.Now().UTC().Add(-time.Hour), time.Millisecond)
+ issueID := dbfx.Issue(t, "Legacy snoozed issue", 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)
+
+ trimInbox(t, workspaceID)
+
+ if isArchived(t, newestID) {
+ t.Fatal("the woken issue's newest row was archived")
+ }
+ if at := returnedAtOf(t, newestID); at == nil || !at.Equal(wake) {
+ t.Fatalf("newest returned_at = %v, want the wake time %v", at, wake)
+ }
+ if !isArchived(t, olderID) {
+ t.Fatal("the woken issue's older row should rank by its own time and go")
+ }
+}
+
+// A comment that joined a running snooze is the issue's newest row when the
+// snooze ends, so it, not the row that was newest when snoozing, keeps the
+// issue's rank.
+func TestInboxTrimmerHandsReturnToRowThatJoinedSnooze(t *testing.T) {
+ workspaceID := limitInboxWorkspace(t, "Inbox limit joined snooze")
+ seedInboxRows(t, workspaceID, testUserID, inbox.ActiveLimit, time.Now().UTC().Add(-time.Hour), time.Millisecond)
+ issueID := dbfx.Issue(t, "Snoozed issue with news", testutil.Cols{"workspace_id": workspaceID})
+ wake := time.Now().Add(-time.Minute).UTC().Truncate(time.Microsecond)
+ snoozedAt := wake.Add(-24 * time.Hour)
+ beforeID := insertOldInboxRow(t, workspaceID, "before-snooze", testutil.Cols{
+ "issue_id": issueID, "snoozed_until": wake, "snoozed_at": snoozedAt, "returned_at": wake,
+ })
+ joinedID := insertOldInboxRow(t, workspaceID, "joined-snooze", testutil.Cols{
+ "issue_id": issueID, "snoozed_until": wake, "snoozed_at": snoozedAt, "created_at": time.Now().Add(-2 * time.Hour),
+ })
+
+ trimInbox(t, workspaceID)
+
+ if isArchived(t, joinedID) {
+ t.Fatal("the comment that arrived during the snooze was archived")
+ }
+ if at := returnedAtOf(t, joinedID); at == nil || !at.Equal(wake) {
+ t.Fatalf("joined row returned_at = %v, want the wake time %v", at, wake)
+ }
+ if returnedAtOf(t, beforeID) != nil || !isArchived(t, beforeID) {
+ t.Fatal("the row newest at snooze time kept the issue's rank")
+ }
+}
+
+// Bulk archives drop the return rank, so a later restore earns it anew on the
+// restored row only.
+func TestBulkArchiveClearsReturn(t *testing.T) {
+ workspaceID := limitInboxWorkspace(t, "Inbox limit bulk archive")
+ allID := insertOldInboxRow(t, workspaceID, "archive-all", testutil.Cols{"returned_at": time.Now(), "read": true})
+ ctx := context.Background()
+ if _, err := testHandler.Queries.ArchiveAllReadInbox(ctx, db.ArchiveAllReadInboxParams{
+ WorkspaceID: parseUUID(workspaceID), RecipientID: parseUUID(testUserID),
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if !isArchived(t, allID) || returnedAtOf(t, allID) != nil {
+ t.Fatalf("archive all read: archived=%v returned_at=%v", isArchived(t, allID), returnedAtOf(t, allID))
+ }
+
+ dbfx.Exec(t, `UPDATE inbox_item SET archived = false, returned_at = now() WHERE id = $1`, allID)
+ if _, err := testHandler.Queries.ArchiveAllInbox(ctx, db.ArchiveAllInboxParams{
+ WorkspaceID: parseUUID(workspaceID), RecipientID: parseUUID(testUserID),
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if !isArchived(t, allID) || returnedAtOf(t, allID) != nil {
+ t.Fatalf("archive all: archived=%v returned_at=%v", isArchived(t, allID), returnedAtOf(t, allID))
+ }
+}
diff --git a/server/internal/inbox/trim.go b/server/internal/inbox/trim.go
new file mode 100644
index 0000000000..9ada8f82c9
--- /dev/null
+++ b/server/internal/inbox/trim.go
@@ -0,0 +1,268 @@
+package inbox
+
+import (
+ "context"
+ "log/slog"
+ "sync"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// ActiveLimit is how many rows a recipient's inbox keeps in one workspace,
+// newest first by when each arrived or came back (returned_at). Snoozed rows
+// and rows in projects the recipient cannot see do not count. Older rows are
+// archived, so every inbox read stays bounded however many notifications a
+// recipient collects.
+const ActiveLimit = 2000
+
+const (
+ // trimBatchSize bounds the rows one archive statement locks and writes.
+ trimBatchSize = 500
+ // trimMaxBatches bounds the work one recipient gets per round. A
+ // recipient with more left over is trimmed further in the next round.
+ trimMaxBatches = 20
+
+ // trimInterval also coalesces a burst of notifications for one recipient
+ // into one trim, and one inbox:batch-archived, per round.
+ trimInterval = 30 * time.Second
+ trimRoundBudget = 25 * time.Second
+)
+
+// 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)
+ ListHiddenProjectIDsForUser(ctx context.Context, arg db.ListHiddenProjectIDsForUserParams) ([]pgtype.UUID, error)
+}
+
+// Recipient identifies one inbox: a recipient in a workspace.
+type Recipient struct {
+ WorkspaceID pgtype.UUID
+ RecipientType string
+ RecipientID pgtype.UUID
+}
+
+// Trimmer keeps inboxes within ActiveLimit. Inboxes that may have outgrown it
+// are marked (see Subscribe, plus a list read that hit the limit) and trimmed
+// in the background, so no notification write or inbox read waits on
+// the archive.
+type Trimmer struct {
+ queries TrimQueries
+ pub Publisher
+
+ mu sync.Mutex
+ pending map[Recipient]struct{}
+}
+
+// NewTrimmer returns a Trimmer that archives through queries and announces
+// what it archived on pub.
+func NewTrimmer(queries TrimQueries, pub Publisher) *Trimmer {
+ return &Trimmer{queries: queries, pub: pub, pending: map[Recipient]struct{}{}}
+}
+
+// Mark queues r for the next round. Safe on a nil Trimmer.
+func (t *Trimmer) Mark(r Recipient) {
+ if t == nil {
+ return
+ }
+ t.mu.Lock()
+ t.pending[r] = struct{}{}
+ t.mu.Unlock()
+}
+
+// Subscribe marks the inboxes that may have grown: a new row, a row restored
+// from the archive, or an issue taken out of a snooze early. A row written
+// into a snooze is announced as inbox:snoozed and does not count yet.
+func (t *Trimmer) Subscribe(bus *events.Bus) {
+ bus.Subscribe(protocol.EventInboxNew, func(e events.Event) {
+ if r, ok := recipientOfNewItem(e); ok {
+ t.Mark(r)
+ }
+ })
+ for _, eventType := range []string{protocol.EventInboxUnarchived, protocol.EventInboxUnsnoozed} {
+ bus.Subscribe(eventType, func(e events.Event) {
+ if r, ok := memberRecipient(e); ok {
+ t.Mark(r)
+ }
+ })
+ }
+}
+
+// memberRecipient reads the member a personal inbox event names at the top
+// of its payload.
+func memberRecipient(e events.Event) (Recipient, bool) {
+ payload, ok := e.Payload.(map[string]any)
+ if !ok {
+ return Recipient{}, false
+ }
+ recipientID, _ := payload["recipient_id"].(string)
+ ws, err := util.ParseUUID(e.WorkspaceID)
+ if err != nil {
+ return Recipient{}, false
+ }
+ rid, err := util.ParseUUID(recipientID)
+ if err != nil {
+ return Recipient{}, false
+ }
+ return Recipient{WorkspaceID: ws, RecipientType: "member", RecipientID: rid}, true
+}
+
+func recipientOfNewItem(e events.Event) (Recipient, bool) {
+ payload, ok := e.Payload.(map[string]any)
+ if !ok {
+ return Recipient{}, false
+ }
+ item, ok := payload["item"].(map[string]any)
+ if !ok {
+ return Recipient{}, false
+ }
+ workspaceID, _ := item["workspace_id"].(string)
+ recipientType, _ := item["recipient_type"].(string)
+ recipientID, _ := item["recipient_id"].(string)
+ ws, err := util.ParseUUID(workspaceID)
+ if err != nil || recipientType == "" {
+ return Recipient{}, false
+ }
+ rid, err := util.ParseUUID(recipientID)
+ if err != nil {
+ return Recipient{}, false
+ }
+ return Recipient{WorkspaceID: ws, RecipientType: recipientType, RecipientID: rid}, true
+}
+
+// Run trims the marked inboxes every trimInterval until ctx ends.
+func (t *Trimmer) Run(ctx context.Context) {
+ ticker := time.NewTicker(trimInterval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ roundCtx, cancel := context.WithTimeout(ctx, trimRoundBudget)
+ t.Flush(roundCtx)
+ cancel()
+ }
+ }
+}
+
+// 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.
+func (t *Trimmer) Flush(ctx context.Context) {
+ t.mu.Lock()
+ batch := t.pending
+ t.pending = make(map[Recipient]struct{}, len(batch))
+ t.mu.Unlock()
+
+ for r := range batch {
+ if ctx.Err() != nil {
+ t.Mark(r)
+ continue
+ }
+ archived, done, err := t.trim(ctx, r)
+ if err != nil {
+ slog.Warn("inbox trim failed",
+ "workspace_id", util.UUIDToString(r.WorkspaceID),
+ "recipient_type", r.RecipientType,
+ "recipient_id", util.UUIDToString(r.RecipientID),
+ "error", err)
+ }
+ if !done {
+ t.Mark(r)
+ }
+ if archived > 0 {
+ slog.Info("inbox trim archived rows beyond the inbox limit",
+ "workspace_id", util.UUIDToString(r.WorkspaceID),
+ "recipient_type", r.RecipientType,
+ "recipient_id", util.UUIDToString(r.RecipientID),
+ "count", archived)
+ t.announce(r, archived)
+ }
+ }
+}
+
+// trim archives r's shown rows beyond its newest ActiveLimit. done is false
+// while rows beyond the limit remain: rows another write held locked, or more
+// than one round archives.
+func (t *Trimmer) trim(ctx context.Context, r Recipient) (archived int64, done bool, err error) {
+ hidden, err := t.hiddenProjects(ctx, r)
+ if err != nil {
+ return 0, false, err
+ }
+ overflows := func() (bool, error) {
+ return t.queries.InboxOverflows(ctx, db.InboxOverflowsParams{
+ WorkspaceID: r.WorkspaceID, RecipientType: r.RecipientType, RecipientID: r.RecipientID,
+ HiddenProjectIds: hidden, Keep: ActiveLimit,
+ })
+ }
+ over, err := overflows()
+ if err != nil || !over {
+ 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 {
+ return 0, false, err
+ }
+ for range trimMaxBatches {
+ n, err := t.queries.ArchiveInboxOverflow(ctx, db.ArchiveInboxOverflowParams{
+ WorkspaceID: r.WorkspaceID, RecipientType: r.RecipientType, RecipientID: r.RecipientID,
+ HiddenProjectIds: hidden, Keep: ActiveLimit, BatchSize: trimBatchSize,
+ })
+ archived += n
+ if err != nil {
+ return archived, false, err
+ }
+ if n < trimBatchSize {
+ break
+ }
+ }
+ over, err = overflows()
+ if err != nil {
+ return archived, false, err
+ }
+ return archived, !over, nil
+}
+
+// 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.
+func (t *Trimmer) hiddenProjects(ctx context.Context, r Recipient) ([]pgtype.UUID, error) {
+ if r.RecipientType != "member" {
+ return nil, nil
+ }
+ ids, err := t.queries.ListHiddenProjectIDsForUser(ctx, db.ListHiddenProjectIDsForUserParams{
+ WorkspaceID: r.WorkspaceID, UserID: r.RecipientID,
+ })
+ if err != nil || len(ids) == 0 {
+ return nil, err
+ }
+ return ids, nil
+}
+
+// announce tells a member's clients to drop the archived rows, as the bulk
+// archive actions do. Only members have a personal feed.
+func (t *Trimmer) announce(r Recipient, count int64) {
+ if r.RecipientType != "member" {
+ return
+ }
+ publish(t.pub, events.Event{
+ Type: protocol.EventInboxBatchArchived,
+ WorkspaceID: util.UUIDToString(r.WorkspaceID),
+ ActorType: "system",
+ Payload: map[string]any{
+ "recipient_id": util.UUIDToString(r.RecipientID),
+ "count": count,
+ "reason": "inbox_limit",
+ },
+ })
+}
diff --git a/server/internal/inbox/trim_test.go b/server/internal/inbox/trim_test.go
new file mode 100644
index 0000000000..6c26fba259
--- /dev/null
+++ b/server/internal/inbox/trim_test.go
@@ -0,0 +1,187 @@
+package inbox
+
+import (
+ "context"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// fakeTrimQueries models an inbox of `rows` shown rows of which `locked` of
+// the overflow are held by another write and skipped.
+type fakeTrimQueries struct {
+ rows int
+ locked int
+ archiveRun int
+ normalized int
+}
+
+func (f *fakeTrimQueries) InboxOverflows(_ context.Context, arg db.InboxOverflowsParams) (bool, error) {
+ return f.rows > int(arg.Keep), nil
+}
+
+func (f *fakeTrimQueries) ListHiddenProjectIDsForUser(context.Context, db.ListHiddenProjectIDsForUserParams) ([]pgtype.UUID, error) {
+ return nil, nil
+}
+
+func (f *fakeTrimQueries) NormalizeInboxReturns(context.Context, db.NormalizeInboxReturnsParams) (int64, error) {
+ f.normalized++
+ return 0, nil
+}
+
+func (f *fakeTrimQueries) ArchiveInboxOverflow(_ context.Context, arg db.ArchiveInboxOverflowParams) (int64, error) {
+ f.archiveRun++
+ n := min(max(f.rows-int(arg.Keep)-f.locked, 0), int(arg.BatchSize))
+ f.rows -= n
+ return int64(n), nil
+}
+
+var trimRecipient = Recipient{
+ WorkspaceID: util.MustParseUUID("33333333-3333-3333-3333-333333333333"),
+ RecipientType: "member",
+ RecipientID: util.MustParseUUID("11111111-1111-1111-1111-111111111111"),
+}
+
+func batchArchivedEvents(bus *events.Bus) *[]events.Event {
+ var got []events.Event
+ bus.Subscribe(protocol.EventInboxBatchArchived, func(e events.Event) { got = append(got, e) })
+ return &got
+}
+
+func TestTrimmerLeavesInboxAtTheLimit(t *testing.T) {
+ q := &fakeTrimQueries{rows: ActiveLimit}
+ bus := events.New()
+ got := batchArchivedEvents(bus)
+ tr := NewTrimmer(q, bus)
+
+ tr.Mark(trimRecipient)
+ tr.Flush(context.Background())
+
+ if q.rows != ActiveLimit || q.archiveRun != 0 || q.normalized != 0 || len(*got) != 0 {
+ t.Fatalf("rows=%d archive runs=%d normalized=%d events=%d; want the inbox untouched", q.rows, q.archiveRun, q.normalized, len(*got))
+ }
+ if len(tr.pending) != 0 {
+ t.Fatalf("pending = %v, want the inbox settled", tr.pending)
+ }
+}
+
+// One row past the limit is trimmed: the list shows only ActiveLimit rows, so
+// an extra row would otherwise sit out of sight in neither list.
+func TestTrimmerArchivesOneRowPastTheLimitAndAnnounces(t *testing.T) {
+ q := &fakeTrimQueries{rows: ActiveLimit + 1}
+ bus := events.New()
+ got := batchArchivedEvents(bus)
+ tr := NewTrimmer(q, bus)
+
+ tr.Mark(trimRecipient)
+ tr.Flush(context.Background())
+
+ if q.rows != ActiveLimit || len(tr.pending) != 0 || q.normalized != 1 {
+ t.Fatalf("rows=%d pending=%v normalized=%d; want returns settled once, trimmed to %d and settled", q.rows, tr.pending, q.normalized, ActiveLimit)
+ }
+ if len(*got) != 1 {
+ t.Fatalf("batch-archived events = %d, want 1", len(*got))
+ }
+ payload := (*got)[0].Payload.(map[string]any)
+ if payload["recipient_id"] != util.UUIDToString(trimRecipient.RecipientID) ||
+ payload["count"] != int64(1) || payload["reason"] != "inbox_limit" ||
+ (*got)[0].WorkspaceID != util.UUIDToString(trimRecipient.WorkspaceID) {
+ t.Fatalf("event = %+v", (*got)[0])
+ }
+}
+
+// Rows skipped because another write held them keep the inbox queued.
+func TestTrimmerRequeuesInboxWithSkippedRows(t *testing.T) {
+ q := &fakeTrimQueries{rows: ActiveLimit + 10, locked: 3}
+ tr := NewTrimmer(q, nil)
+
+ tr.Mark(trimRecipient)
+ tr.Flush(context.Background())
+ if q.rows != ActiveLimit+3 {
+ t.Fatalf("rows = %d, want the unlocked overflow archived", q.rows)
+ }
+ if _, ok := tr.pending[trimRecipient]; !ok {
+ t.Fatal("inbox with skipped rows was not queued for the next round")
+ }
+
+ q.locked = 0
+ tr.Flush(context.Background())
+ if q.rows != ActiveLimit || len(tr.pending) != 0 {
+ t.Fatalf("rows=%d pending=%v after the lock cleared", q.rows, tr.pending)
+ }
+}
+
+// One round archives at most trimMaxBatches batches per inbox; the rest waits
+// for the next round instead of holding the round up.
+func TestTrimmerCarriesLargeBacklogToNextRound(t *testing.T) {
+ q := &fakeTrimQueries{rows: ActiveLimit + trimMaxBatches*trimBatchSize + 10}
+ tr := NewTrimmer(q, nil)
+
+ tr.Mark(trimRecipient)
+ tr.Flush(context.Background())
+ if q.rows != ActiveLimit+10 || q.archiveRun != trimMaxBatches {
+ t.Fatalf("after one round rows=%d runs=%d", q.rows, q.archiveRun)
+ }
+ if _, ok := tr.pending[trimRecipient]; !ok {
+ t.Fatal("unfinished inbox was not marked for the next round")
+ }
+}
+
+func TestTrimmerDoesNotAnnounceForAgents(t *testing.T) {
+ q := &fakeTrimQueries{rows: ActiveLimit + 5}
+ bus := events.New()
+ got := batchArchivedEvents(bus)
+ tr := NewTrimmer(q, bus)
+
+ agent := trimRecipient
+ agent.RecipientType = "agent"
+ tr.Mark(agent)
+ tr.Flush(context.Background())
+
+ if q.rows != ActiveLimit || len(*got) != 0 {
+ t.Fatalf("rows=%d events=%d; want trimmed silently", q.rows, len(*got))
+ }
+}
+
+func TestTrimmerMarksInboxesThatMayHaveGrown(t *testing.T) {
+ bus := events.New()
+ tr := NewTrimmer(&fakeTrimQueries{}, bus)
+ tr.Subscribe(bus)
+
+ item := db.InboxItem{
+ ID: util.MustParseUUID("44444444-4444-4444-4444-444444444444"),
+ WorkspaceID: trimRecipient.WorkspaceID,
+ RecipientType: trimRecipient.RecipientType,
+ RecipientID: trimRecipient.RecipientID,
+ Type: "new_comment",
+ }
+ bus.Publish(newEvent(item, nil))
+ bus.Publish(events.Event{Type: protocol.EventInboxNew, Payload: map[string]any{"item": "malformed"}})
+ if len(tr.pending) != 1 {
+ t.Fatalf("pending = %v, want only the new item's recipient", tr.pending)
+ }
+ if _, ok := tr.pending[trimRecipient]; !ok {
+ t.Fatalf("pending = %v, want %v", tr.pending, trimRecipient)
+ }
+
+ for _, eventType := range []string{protocol.EventInboxUnarchived, protocol.EventInboxUnsnoozed} {
+ tr.pending = map[Recipient]struct{}{}
+ bus.Publish(events.Event{
+ Type: eventType,
+ WorkspaceID: util.UUIDToString(trimRecipient.WorkspaceID),
+ Payload: map[string]any{"recipient_id": util.UUIDToString(trimRecipient.RecipientID)},
+ })
+ if _, ok := tr.pending[trimRecipient]; !ok || len(tr.pending) != 1 {
+ t.Fatalf("%s: pending = %v, want %v", eventType, tr.pending, trimRecipient)
+ }
+ }
+}
+
+func TestNilTrimmerMarkIsNoop(t *testing.T) {
+ var tr *Trimmer
+ tr.Mark(trimRecipient)
+}
diff --git a/server/migrations/695_inbox_item_returned_at.down.sql b/server/migrations/695_inbox_item_returned_at.down.sql
new file mode 100644
index 0000000000..52a052663f
--- /dev/null
+++ b/server/migrations/695_inbox_item_returned_at.down.sql
@@ -0,0 +1 @@
+ALTER TABLE inbox_item DROP COLUMN IF EXISTS returned_at;
diff --git a/server/migrations/695_inbox_item_returned_at.up.sql b/server/migrations/695_inbox_item_returned_at.up.sql
new file mode 100644
index 0000000000..91c35ec87f
--- /dev/null
+++ b/server/migrations/695_inbox_item_returned_at.up.sql
@@ -0,0 +1,8 @@
+-- When an issue's newest inbox row comes back to the inbox later than it was
+-- created: the end of a snooze, or now when it is restored from the archive
+-- or taken out of a snooze early. The inbox limit (inbox.ActiveLimit) ranks
+-- rows by GREATEST(created_at, returned_at). Only the issue's newest row
+-- carries it, so bringing back a busy issue does not outrank everything else.
+-- NULL means the row ranks by created_at. Nullable with no default: a
+-- catalog-only change.
+ALTER TABLE inbox_item ADD COLUMN IF NOT EXISTS returned_at TIMESTAMPTZ;
diff --git a/server/migrations/696_inbox_item_active_shown_idx.down.sql b/server/migrations/696_inbox_item_active_shown_idx.down.sql
new file mode 100644
index 0000000000..b9766131bd
--- /dev/null
+++ b/server/migrations/696_inbox_item_active_shown_idx.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_inbox_active_shown;
diff --git a/server/migrations/696_inbox_item_active_shown_idx.up.sql b/server/migrations/696_inbox_item_active_shown_idx.up.sql
new file mode 100644
index 0000000000..8191c7b491
--- /dev/null
+++ b/server/migrations/696_inbox_item_active_shown_idx.up.sql
@@ -0,0 +1,8 @@
+-- Orders a recipient's active inbox the way the list shows it: by when each
+-- row arrived or came back (see returned_at in migration 695), newest
+-- first. Serves ListInboxItems and the inbox limit's trim queries, which must
+-- use this exact expression. Keep this as the migration's only statement:
+-- PostgreSQL rejects CREATE INDEX CONCURRENTLY inside a transaction.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_inbox_active_shown
+ ON inbox_item (workspace_id, recipient_type, recipient_id, (GREATEST(created_at, returned_at)) DESC, id DESC)
+ WHERE archived = false;
diff --git a/server/pkg/db/generated/inbox.sql.go b/server/pkg/db/generated/inbox.sql.go
index e1eda87dac..6a60daebc6 100644
--- a/server/pkg/db/generated/inbox.sql.go
+++ b/server/pkg/db/generated/inbox.sql.go
@@ -12,7 +12,7 @@ import (
)
const archiveAllInbox = `-- name: ArchiveAllInbox :execrows
-UPDATE inbox_item SET archived = true
+UPDATE inbox_item SET archived = true, returned_at = NULL
WHERE workspace_id = $1 AND recipient_type = 'member' AND recipient_id = $2 AND archived = false
AND (snoozed_until IS NULL OR snoozed_until <= now())
`
@@ -22,6 +22,8 @@ type ArchiveAllInboxParams struct {
RecipientID pgtype.UUID `json:"recipient_id"`
}
+// Every archive clears returned_at: a row restored later earns its rank anew
+// (UnarchiveInboxItem), so old return times never outrank the inbox again.
func (q *Queries) ArchiveAllInbox(ctx context.Context, arg ArchiveAllInboxParams) (int64, error) {
result, err := q.db.Exec(ctx, archiveAllInbox, arg.WorkspaceID, arg.RecipientID)
if err != nil {
@@ -47,7 +49,7 @@ WITH newest_groups AS (
FROM newest_groups
WHERE read = true
)
-UPDATE inbox_item i SET archived = true
+UPDATE inbox_item i SET archived = true, returned_at = NULL
FROM read_groups selected
WHERE i.workspace_id = $1
AND i.recipient_type = 'member'
@@ -75,7 +77,7 @@ func (q *Queries) ArchiveAllReadInbox(ctx context.Context, arg ArchiveAllReadInb
}
const archiveCompletedInbox = `-- name: ArchiveCompletedInbox :execrows
-UPDATE inbox_item i SET archived = true, snoozed_until = NULL, snoozed_at = NULL
+UPDATE inbox_item i SET archived = true, snoozed_until = NULL, snoozed_at = NULL, returned_at = NULL
WHERE i.workspace_id = $1 AND i.recipient_type = 'member' AND i.recipient_id = $2 AND i.archived = false
AND i.issue_id IN (
SELECT id FROM issue
@@ -100,7 +102,7 @@ func (q *Queries) ArchiveCompletedInbox(ctx context.Context, arg ArchiveComplete
}
const archiveInboxByIssue = `-- name: ArchiveInboxByIssue :execrows
-UPDATE inbox_item SET archived = true, snoozed_until = NULL, snoozed_at = NULL
+UPDATE inbox_item SET archived = true, snoozed_until = NULL, snoozed_at = NULL, returned_at = NULL
WHERE workspace_id = $1 AND recipient_type = $2 AND recipient_id = $3 AND issue_id = $4 AND archived = false
`
@@ -125,7 +127,7 @@ func (q *Queries) ArchiveInboxByIssue(ctx context.Context, arg ArchiveInboxByIss
}
const archiveInboxByIssueAndType = `-- name: ArchiveInboxByIssueAndType :many
-UPDATE inbox_item SET archived = true, snoozed_until = NULL, snoozed_at = NULL
+UPDATE inbox_item SET archived = true, snoozed_until = NULL, snoozed_at = NULL, returned_at = NULL
WHERE workspace_id = $1 AND issue_id = $2 AND type = $3 AND archived = false
RETURNING recipient_type, recipient_id
`
@@ -162,9 +164,9 @@ func (q *Queries) ArchiveInboxByIssueAndType(ctx context.Context, arg ArchiveInb
}
const archiveInboxItem = `-- name: ArchiveInboxItem :one
-UPDATE inbox_item SET archived = true, snoozed_until = NULL, snoozed_at = NULL
+UPDATE inbox_item SET archived = true, snoozed_until = NULL, snoozed_at = NULL, returned_at = NULL
WHERE id = $1
-RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section, snoozed_until, snoozed_at
+RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section, snoozed_until, snoozed_at, returned_at
`
// Archiving ends a snooze (MUL-9333), on every archive path below: a row
@@ -191,10 +193,79 @@ func (q *Queries) ArchiveInboxItem(ctx context.Context, id pgtype.UUID) (InboxIt
&i.Section,
&i.SnoozedUntil,
&i.SnoozedAt,
+ &i.ReturnedAt,
)
return i, err
}
+const archiveInboxOverflow = `-- name: ArchiveInboxOverflow :execrows
+WITH boundary AS (
+ 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
+ WHERE b.workspace_id = $1 AND b.recipient_type = $2
+ AND b.recipient_id = $3
+ AND b.archived = false
+ AND (b.snoozed_until IS NULL OR b.snoozed_until <= now())
+ AND ($4::uuid[] IS NULL OR b_iss.project_id IS NULL
+ OR NOT (b_iss.project_id = ANY($4::uuid[])))
+ ORDER BY GREATEST(b.created_at, b.returned_at) DESC, b.id DESC
+ OFFSET $5::int - 1
+ LIMIT 1
+), overflow AS (
+ SELECT o.id FROM inbox_item o
+ CROSS JOIN boundary
+ LEFT JOIN issue o_iss ON o_iss.id = o.issue_id
+ WHERE o.workspace_id = $1 AND o.recipient_type = $2
+ AND o.recipient_id = $3
+ AND o.archived = false
+ AND (o.snoozed_until IS NULL OR o.snoozed_until <= now())
+ 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)
+ ORDER BY GREATEST(o.created_at, o.returned_at), o.id
+ LIMIT $6::int
+ FOR UPDATE OF o SKIP LOCKED
+)
+UPDATE inbox_item AS item SET archived = true, snoozed_until = NULL, snoozed_at = NULL, returned_at = NULL
+WHERE item.id = ANY (ARRAY(SELECT overflow.id FROM overflow))
+`
+
+type ArchiveInboxOverflowParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ RecipientType string `json:"recipient_type"`
+ RecipientID pgtype.UUID `json:"recipient_id"`
+ HiddenProjectIds []pgtype.UUID `json:"hidden_project_ids"`
+ Keep int32 `json:"keep"`
+ BatchSize int32 `json:"batch_size"`
+}
+
+// Archives up to batch_size of the recipient's shown rows ranked below the
+// newest `keep`, oldest first, in ListInboxItems' order. The boundary is read
+// in the same statement, so every batch sees the inbox as it is now. Rows are
+// archived one by one: unlike the issue-level archive actions, newer rows on
+// the same issue stay. Snoozed rows, and rows in projects the recipient can
+// no longer see, neither count nor get archived: a snooze is never ended
+// 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.
+// 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) {
+ result, err := q.db.Exec(ctx, archiveInboxOverflow,
+ arg.WorkspaceID,
+ arg.RecipientType,
+ arg.RecipientID,
+ arg.HiddenProjectIds,
+ arg.Keep,
+ 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
@@ -329,7 +400,7 @@ AND NOT ($2::text = 'member' AND EXISTS (
WHERE pm.project_id = private_project.id AND pm.user_id = $3
)
))
-RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section, snoozed_until, snoozed_at
+RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section, snoozed_until, snoozed_at, returned_at
`
type CreateInboxItemParams struct {
@@ -391,13 +462,14 @@ func (q *Queries) CreateInboxItem(ctx context.Context, arg CreateInboxItemParams
&i.Section,
&i.SnoozedUntil,
&i.SnoozedAt,
+ &i.ReturnedAt,
)
return i, err
}
const deleteInboxGroup = `-- name: DeleteInboxGroup :execrows
WITH target AS (
- SELECT selected.id, selected.workspace_id, selected.recipient_type, selected.recipient_id, selected.type, selected.severity, selected.issue_id, selected.title, selected.body, selected.read, selected.archived, selected.created_at, selected.actor_type, selected.actor_id, selected.details, selected.section, selected.snoozed_until, selected.snoozed_at FROM inbox_item selected
+ SELECT selected.id, selected.workspace_id, selected.recipient_type, selected.recipient_id, selected.type, selected.severity, selected.issue_id, selected.title, selected.body, selected.read, selected.archived, selected.created_at, selected.actor_type, selected.actor_id, selected.details, selected.section, selected.snoozed_until, selected.snoozed_at, selected.returned_at FROM inbox_item selected
WHERE selected.id = $1 AND selected.workspace_id = $2
AND selected.recipient_type = 'member' AND selected.recipient_id = $3
)
@@ -427,7 +499,7 @@ func (q *Queries) DeleteInboxGroup(ctx context.Context, arg DeleteInboxGroupPara
}
const getInboxItemInWorkspace = `-- name: GetInboxItemInWorkspace :one
-SELECT id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section, snoozed_until, snoozed_at FROM inbox_item
+SELECT id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section, snoozed_until, snoozed_at, returned_at FROM inbox_item
WHERE id = $1 AND workspace_id = $2
`
@@ -458,10 +530,51 @@ func (q *Queries) GetInboxItemInWorkspace(ctx context.Context, arg GetInboxItemI
&i.Section,
&i.SnoozedUntil,
&i.SnoozedAt,
+ &i.ReturnedAt,
)
return i, err
}
+const inboxOverflows = `-- name: InboxOverflows :one
+SELECT count(*) > 0 FROM (
+ SELECT 1 FROM inbox_item i
+ LEFT JOIN issue iss ON iss.id = i.issue_id
+ WHERE i.workspace_id = $1 AND i.recipient_type = $2 AND i.recipient_id = $3
+ AND i.archived = false
+ AND (i.snoozed_until IS NULL OR i.snoozed_until <= now())
+ AND ($4::uuid[] IS NULL OR iss.project_id IS NULL
+ OR NOT (iss.project_id = ANY($4::uuid[])))
+ ORDER BY GREATEST(i.created_at, i.returned_at) DESC, i.id DESC
+ OFFSET $5::int
+ LIMIT 1
+) beyond
+`
+
+type InboxOverflowsParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ RecipientType string `json:"recipient_type"`
+ RecipientID pgtype.UUID `json:"recipient_id"`
+ HiddenProjectIds []pgtype.UUID `json:"hidden_project_ids"`
+ Keep int32 `json:"keep"`
+}
+
+// Whether the recipient's inbox shows more than `keep` rows, by the rules
+// ListInboxItems shows them: active, not snoozed, outside the projects the
+// recipient cannot see (hidden_project_ids), ranked by when they arrived or
+// came back.
+func (q *Queries) InboxOverflows(ctx context.Context, arg InboxOverflowsParams) (bool, error) {
+ row := q.db.QueryRow(ctx, inboxOverflows,
+ arg.WorkspaceID,
+ arg.RecipientType,
+ arg.RecipientID,
+ arg.HiddenProjectIds,
+ arg.Keep,
+ )
+ 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,
@@ -513,7 +626,7 @@ WITH eligible_archived AS MATERIALIZED (
UNION
SELECT id FROM comment_anchors
)
-SELECT i.id, i.workspace_id, i.recipient_type, i.recipient_id, i.type, i.severity, i.issue_id, i.title, i.body, i.read, i.archived, i.created_at, i.actor_type, i.actor_id, i.details, i.section, i.snoozed_until, i.snoozed_at,
+SELECT i.id, i.workspace_id, i.recipient_type, i.recipient_id, i.type, i.severity, i.issue_id, i.title, i.body, i.read, i.archived, i.created_at, i.actor_type, i.actor_id, i.details, i.section, i.snoozed_until, i.snoozed_at, i.returned_at,
iss.number AS issue_number,
iss.status AS issue_status,
iss.priority AS issue_priority,
@@ -556,6 +669,7 @@ type ListArchivedInboxItemsRow struct {
Section pgtype.Text `json:"section"`
SnoozedUntil pgtype.Timestamptz `json:"snoozed_until"`
SnoozedAt pgtype.Timestamptz `json:"snoozed_at"`
+ ReturnedAt pgtype.Timestamptz `json:"returned_at"`
IssueNumber pgtype.Int4 `json:"issue_number"`
IssueStatus pgtype.Text `json:"issue_status"`
IssuePriority pgtype.Text `json:"issue_priority"`
@@ -620,6 +734,7 @@ func (q *Queries) ListArchivedInboxItems(ctx context.Context, arg ListArchivedIn
&i.Section,
&i.SnoozedUntil,
&i.SnoozedAt,
+ &i.ReturnedAt,
&i.IssueNumber,
&i.IssueStatus,
&i.IssuePriority,
@@ -640,7 +755,7 @@ func (q *Queries) ListArchivedInboxItems(ctx context.Context, arg ListArchivedIn
}
const listInboxItems = `-- name: ListInboxItems :many
-SELECT i.id, i.workspace_id, i.recipient_type, i.recipient_id, i.type, i.severity, i.issue_id, i.title, i.body, i.read, i.archived, i.created_at, i.actor_type, i.actor_id, i.details, i.section, i.snoozed_until, i.snoozed_at,
+SELECT i.id, i.workspace_id, i.recipient_type, i.recipient_id, i.type, i.severity, i.issue_id, i.title, i.body, i.read, i.archived, i.created_at, i.actor_type, i.actor_id, i.details, i.section, i.snoozed_until, i.snoozed_at, i.returned_at,
iss.number AS issue_number,
iss.status AS issue_status,
iss.priority AS issue_priority,
@@ -659,7 +774,8 @@ WHERE i.workspace_id = $1 AND i.recipient_type = $2 AND i.recipient_id = $3 AND
-- how the client tells an issue that came back on its own.
AND (i.snoozed_until IS NULL OR i.snoozed_until <= now())
AND ($4::uuid[] IS NULL OR iss.project_id IS NULL OR NOT (iss.project_id = ANY($4::uuid[])))
-ORDER BY i.created_at DESC
+ORDER BY GREATEST(i.created_at, i.returned_at) DESC, i.id DESC
+LIMIT $5
`
type ListInboxItemsParams struct {
@@ -667,6 +783,7 @@ type ListInboxItemsParams struct {
RecipientType string `json:"recipient_type"`
RecipientID pgtype.UUID `json:"recipient_id"`
HiddenProjectIds []pgtype.UUID `json:"hidden_project_ids"`
+ RowLimit int32 `json:"row_limit"`
}
type ListInboxItemsRow struct {
@@ -688,6 +805,7 @@ type ListInboxItemsRow struct {
Section pgtype.Text `json:"section"`
SnoozedUntil pgtype.Timestamptz `json:"snoozed_until"`
SnoozedAt pgtype.Timestamptz `json:"snoozed_at"`
+ ReturnedAt pgtype.Timestamptz `json:"returned_at"`
IssueNumber pgtype.Int4 `json:"issue_number"`
IssueStatus pgtype.Text `json:"issue_status"`
IssuePriority pgtype.Text `json:"issue_priority"`
@@ -701,12 +819,17 @@ type ListInboxItemsRow struct {
// The issue projections feed the inbox filters. Keep this column list
// identical to ListArchivedInboxItems: the handler converts one row type into
// the other.
+// Newest first by when the row arrived or came back (returned_at), the order
+// idx_inbox_active_shown keeps. The
+// inbox keeps only its newest rows (inbox.ActiveLimit); inbox.Trimmer archives
+// the rest, and the limit bounds the response until it has.
func (q *Queries) ListInboxItems(ctx context.Context, arg ListInboxItemsParams) ([]ListInboxItemsRow, error) {
rows, err := q.db.Query(ctx, listInboxItems,
arg.WorkspaceID,
arg.RecipientType,
arg.RecipientID,
arg.HiddenProjectIds,
+ arg.RowLimit,
)
if err != nil {
return nil, err
@@ -734,6 +857,7 @@ func (q *Queries) ListInboxItems(ctx context.Context, arg ListInboxItemsParams)
&i.Section,
&i.SnoozedUntil,
&i.SnoozedAt,
+ &i.ReturnedAt,
&i.IssueNumber,
&i.IssueStatus,
&i.IssuePriority,
@@ -875,7 +999,7 @@ WITH target AS (
)
UPDATE inbox_item AS item SET read = true
WHERE item.id = $1
-RETURNING item.id, item.workspace_id, item.recipient_type, item.recipient_id, item.type, item.severity, item.issue_id, item.title, item.body, item.read, item.archived, item.created_at, item.actor_type, item.actor_id, item.details, item.section, item.snoozed_until, item.snoozed_at, (SELECT count(*) FROM siblings)::bigint AS siblings_read
+RETURNING item.id, item.workspace_id, item.recipient_type, item.recipient_id, item.type, item.severity, item.issue_id, item.title, item.body, item.read, item.archived, item.created_at, item.actor_type, item.actor_id, item.details, item.section, item.snoozed_until, item.snoozed_at, item.returned_at, (SELECT count(*) FROM siblings)::bigint AS siblings_read
`
type MarkInboxReadRow struct {
@@ -914,6 +1038,7 @@ func (q *Queries) MarkInboxRead(ctx context.Context, id pgtype.UUID) (MarkInboxR
&i.InboxItem.Section,
&i.InboxItem.SnoozedUntil,
&i.InboxItem.SnoozedAt,
+ &i.InboxItem.ReturnedAt,
&i.SiblingsRead,
)
return i, err
@@ -954,7 +1079,7 @@ func (q *Queries) MarkInboxReadByIssue(ctx context.Context, arg MarkInboxReadByI
const markInboxUnread = `-- name: MarkInboxUnread :one
UPDATE inbox_item SET read = false
WHERE id = $1
-RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section, snoozed_until, snoozed_at
+RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section, snoozed_until, snoozed_at, returned_at
`
// Item-level, unlike MarkInboxRead: the inbox renders one row per issue
@@ -985,10 +1110,62 @@ func (q *Queries) MarkInboxUnread(ctx context.Context, id pgtype.UUID) (InboxIte
&i.Section,
&i.SnoozedUntil,
&i.SnoozedAt,
+ &i.ReturnedAt,
)
return i, err
}
+const normalizeInboxReturns = `-- name: NormalizeInboxReturns :execrows
+WITH ranked_groups AS (
+ 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 (
+ SELECT DISTINCT ON (r.issue_id) r.issue_id, r.id,
+ GREATEST(ranked_groups.returned_at, r.snoozed_until) AS returned_at
+ FROM inbox_item r
+ JOIN ranked_groups ON ranked_groups.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
+)
+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)
+`
+
+type NormalizeInboxReturnsParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ RecipientType string `json:"recipient_type"`
+ RecipientID pgtype.UUID `json:"recipient_id"`
+}
+
+// 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.
+func (q *Queries) NormalizeInboxReturns(ctx context.Context, arg NormalizeInboxReturnsParams) (int64, error) {
+ result, err := q.db.Exec(ctx, normalizeInboxReturns, arg.WorkspaceID, arg.RecipientType, arg.RecipientID)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
const snoozeInboxGroup = `-- name: SnoozeInboxGroup :many
WITH target AS (
SELECT t.workspace_id, t.recipient_type, t.recipient_id, t.issue_id
@@ -1008,14 +1185,17 @@ WITH target AS (
UPDATE inbox_item item
SET snoozed_until = $1::timestamptz,
snoozed_at = CASE WHEN item.snoozed_until > now() AND item.snoozed_at IS NOT NULL THEN item.snoozed_at ELSE now() END,
- read = CASE WHEN item.id = (SELECT id FROM newest) THEN false ELSE item.read END
+ read = CASE WHEN item.id = (SELECT id FROM newest) THEN false ELSE item.read END,
+ -- The issue comes back on top when the snooze ends: the newest row ranks
+ -- by that time for the inbox limit, the others by when they arrived.
+ returned_at = CASE WHEN item.id = (SELECT id FROM newest) THEN $1::timestamptz END
FROM target
WHERE item.workspace_id = target.workspace_id
AND item.recipient_type = target.recipient_type
AND item.recipient_id = target.recipient_id
AND item.issue_id = target.issue_id
AND item.archived = false
-RETURNING item.id, item.workspace_id, item.recipient_type, item.recipient_id, item.type, item.severity, item.issue_id, item.title, item.body, item.read, item.archived, item.created_at, item.actor_type, item.actor_id, item.details, item.section, item.snoozed_until, item.snoozed_at
+RETURNING item.id, item.workspace_id, item.recipient_type, item.recipient_id, item.type, item.severity, item.issue_id, item.title, item.body, item.read, item.archived, item.created_at, item.actor_type, item.actor_id, item.details, item.section, item.snoozed_until, item.snoozed_at, item.returned_at
`
type SnoozeInboxGroupParams struct {
@@ -1056,6 +1236,7 @@ func (q *Queries) SnoozeInboxGroup(ctx context.Context, arg SnoozeInboxGroupPara
&i.Section,
&i.SnoozedUntil,
&i.SnoozedAt,
+ &i.ReturnedAt,
); err != nil {
return nil, err
}
@@ -1096,14 +1277,18 @@ func (q *Queries) UnarchiveInboxByIssue(ctx context.Context, arg UnarchiveInboxB
}
const unarchiveInboxItem = `-- name: UnarchiveInboxItem :one
-UPDATE inbox_item SET archived = false
+UPDATE inbox_item SET archived = false, returned_at = now()
WHERE id = $1
-RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section, snoozed_until, snoozed_at
+RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section, snoozed_until, snoozed_at, returned_at
`
// Deliberately does not touch `read`: unarchiving restores an item to the main
// inbox in the exact read/unread state it was archived in, so restoring an
// unread item legitimately raises the unread badge again (MUL-3736).
+// returned_at ranks the row as just back for the inbox limit, so a restored
+// old notification is not trimmed straight back into the archive. Only the
+// restored row: its issue's older rows, restored by UnarchiveInboxByIssue,
+// keep their rank so a busy issue does not outrank the whole inbox.
func (q *Queries) UnarchiveInboxItem(ctx context.Context, id pgtype.UUID) (InboxItem, error) {
row := q.db.QueryRow(ctx, unarchiveInboxItem, id)
var i InboxItem
@@ -1126,15 +1311,24 @@ func (q *Queries) UnarchiveInboxItem(ctx context.Context, id pgtype.UUID) (Inbox
&i.Section,
&i.SnoozedUntil,
&i.SnoozedAt,
+ &i.ReturnedAt,
)
return i, err
}
const unsnoozeInboxGroup = `-- name: UnsnoozeInboxGroup :many
-UPDATE inbox_item SET snoozed_until = NULL, snoozed_at = NULL
-WHERE workspace_id = $1 AND recipient_type = $2 AND recipient_id = $3 AND issue_id = $4
- AND archived = false AND snoozed_until IS NOT NULL
-RETURNING id, workspace_id, recipient_type, recipient_id, type, severity, issue_id, title, body, read, archived, created_at, actor_type, actor_id, details, section, snoozed_until, snoozed_at
+WITH newest AS (
+ SELECT n.id FROM inbox_item n
+ WHERE n.workspace_id = $1 AND n.recipient_type = $2 AND n.recipient_id = $3 AND n.issue_id = $4
+ AND n.archived = false
+ ORDER BY n.created_at DESC, n.id DESC
+ LIMIT 1
+)
+UPDATE inbox_item AS item SET snoozed_until = NULL, snoozed_at = NULL,
+ returned_at = CASE WHEN item.id = (SELECT id FROM newest) THEN LEAST(item.snoozed_until, now()) END
+WHERE 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.snoozed_until IS NOT NULL
+RETURNING item.id, item.workspace_id, item.recipient_type, item.recipient_id, item.type, item.severity, item.issue_id, item.title, item.body, item.read, item.archived, item.created_at, item.actor_type, item.actor_id, item.details, item.section, item.snoozed_until, item.snoozed_at, item.returned_at
`
type UnsnoozeInboxGroupParams struct {
@@ -1145,7 +1339,9 @@ type UnsnoozeInboxGroupParams struct {
}
// Ends a snooze on one issue: back in the inbox now. Also clears the time a
-// snooze that already ran out left on the rows.
+// snooze that already ran out left on the rows. The issue's newest row ranks
+// as back now for the inbox limit, or when the snooze ran out if it already
+// had; the others rank by when they arrived.
func (q *Queries) UnsnoozeInboxGroup(ctx context.Context, arg UnsnoozeInboxGroupParams) ([]InboxItem, error) {
rows, err := q.db.Query(ctx, unsnoozeInboxGroup,
arg.WorkspaceID,
@@ -1179,6 +1375,7 @@ func (q *Queries) UnsnoozeInboxGroup(ctx context.Context, arg UnsnoozeInboxGroup
&i.Section,
&i.SnoozedUntil,
&i.SnoozedAt,
+ &i.ReturnedAt,
); err != nil {
return nil, err
}
diff --git a/server/pkg/db/generated/inbox_archive.sql.go b/server/pkg/db/generated/inbox_archive.sql.go
index 228cbaabbb..d8e3e1509e 100644
--- a/server/pkg/db/generated/inbox_archive.sql.go
+++ b/server/pkg/db/generated/inbox_archive.sql.go
@@ -291,7 +291,7 @@ WITH base AS MATERIALIZED (
ORDER BY created_at DESC, id DESC
LIMIT $20::int
)
-SELECT i.id, i.workspace_id, i.recipient_type, i.recipient_id, i.type, i.severity, i.issue_id, i.title, i.body, i.read, i.archived, i.created_at, i.actor_type, i.actor_id, i.details, i.section, i.snoozed_until, i.snoozed_at, selected.issue_status, selected.issue_priority,
+SELECT i.id, i.workspace_id, i.recipient_type, i.recipient_id, i.type, i.severity, i.issue_id, i.title, i.body, i.read, i.archived, i.created_at, i.actor_type, i.actor_id, i.details, i.section, i.snoozed_until, i.snoozed_at, i.returned_at, selected.issue_status, selected.issue_priority,
iss.number AS issue_number,
iss.project_id AS issue_project_id,
iss.assignee_type AS issue_assignee_type,
@@ -414,6 +414,7 @@ func (q *Queries) ListArchivedInboxPage(ctx context.Context, arg ListArchivedInb
&i.InboxItem.Section,
&i.InboxItem.SnoozedUntil,
&i.InboxItem.SnoozedAt,
+ &i.InboxItem.ReturnedAt,
&i.IssueStatus,
&i.IssuePriority,
&i.IssueNumber,
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 40ac357a14..be2bb3d104 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -1036,6 +1036,7 @@ type InboxItem struct {
Section pgtype.Text `json:"section"`
SnoozedUntil pgtype.Timestamptz `json:"snoozed_until"`
SnoozedAt pgtype.Timestamptz `json:"snoozed_at"`
+ ReturnedAt pgtype.Timestamptz `json:"returned_at"`
}
type InstanceTelemetryState struct {
diff --git a/server/pkg/db/queries/inbox.sql b/server/pkg/db/queries/inbox.sql
index 5abdecbabc..f1b4e7535c 100644
--- a/server/pkg/db/queries/inbox.sql
+++ b/server/pkg/db/queries/inbox.sql
@@ -21,7 +21,12 @@ WHERE i.workspace_id = $1 AND i.recipient_type = $2 AND i.recipient_id = $3 AND
-- how the client tells an issue that came back on its own.
AND (i.snoozed_until IS NULL OR i.snoozed_until <= now())
AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR iss.project_id IS NULL OR NOT (iss.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
-ORDER BY i.created_at DESC;
+-- Newest first by when the row arrived or came back (returned_at), the order
+-- idx_inbox_active_shown keeps. The
+-- inbox keeps only its newest rows (inbox.ActiveLimit); inbox.Trimmer archives
+-- the rest, and the limit bounds the response until it has.
+ORDER BY GREATEST(i.created_at, i.returned_at) DESC, i.id DESC
+LIMIT sqlc.arg('row_limit');
-- name: ListArchivedInboxItems :many
-- Archived counterpart of ListInboxItems, backing the inbox's "Archived"
@@ -202,7 +207,7 @@ RETURNING *;
-- name: ArchiveInboxItem :one
-- Archiving ends a snooze (MUL-9333), on every archive path below: a row
-- restored later must not come back still hidden.
-UPDATE inbox_item SET archived = true, snoozed_until = NULL, snoozed_at = NULL
+UPDATE inbox_item SET archived = true, snoozed_until = NULL, snoozed_at = NULL, returned_at = NULL
WHERE id = $1
RETURNING *;
@@ -223,14 +228,18 @@ WHERE item.workspace_id = target.workspace_id
AND (item.id = target.id OR item.issue_id = target.issue_id);
-- name: ArchiveInboxByIssue :execrows
-UPDATE inbox_item SET archived = true, snoozed_until = NULL, snoozed_at = NULL
+UPDATE inbox_item SET archived = true, snoozed_until = NULL, snoozed_at = NULL, returned_at = NULL
WHERE workspace_id = $1 AND recipient_type = $2 AND recipient_id = $3 AND issue_id = $4 AND archived = false;
-- name: UnarchiveInboxItem :one
-- Deliberately does not touch `read`: unarchiving restores an item to the main
-- inbox in the exact read/unread state it was archived in, so restoring an
-- unread item legitimately raises the unread badge again (MUL-3736).
-UPDATE inbox_item SET archived = false
+-- returned_at ranks the row as just back for the inbox limit, so a restored
+-- old notification is not trimmed straight back into the archive. Only the
+-- restored row: its issue's older rows, restored by UnarchiveInboxByIssue,
+-- keep their rank so a busy issue does not outrank the whole inbox.
+UPDATE inbox_item SET archived = false, returned_at = now()
WHERE id = $1
RETURNING *;
@@ -242,7 +251,7 @@ UPDATE inbox_item SET archived = false
WHERE workspace_id = $1 AND recipient_type = $2 AND recipient_id = $3 AND issue_id = $4 AND archived = true;
-- name: ArchiveInboxByIssueAndType :many
-UPDATE inbox_item SET archived = true, snoozed_until = NULL, snoozed_at = NULL
+UPDATE inbox_item SET archived = true, snoozed_until = NULL, snoozed_at = NULL, returned_at = NULL
WHERE workspace_id = $1 AND issue_id = $2 AND type = $3 AND archived = false
RETURNING recipient_type, recipient_id;
@@ -326,7 +335,9 @@ WHERE workspace_id = $1 AND recipient_type = 'member' AND recipient_id = $2
AND (snoozed_until IS NULL OR snoozed_until <= now());
-- name: ArchiveAllInbox :execrows
-UPDATE inbox_item SET archived = true
+-- Every archive clears returned_at: a row restored later earns its rank anew
+-- (UnarchiveInboxItem), so old return times never outrank the inbox again.
+UPDATE inbox_item SET archived = true, returned_at = NULL
WHERE workspace_id = $1 AND recipient_type = 'member' AND recipient_id = $2 AND archived = false
AND (snoozed_until IS NULL OR snoozed_until <= now());
@@ -352,7 +363,7 @@ WITH newest_groups AS (
FROM newest_groups
WHERE read = true
)
-UPDATE inbox_item i SET archived = true
+UPDATE inbox_item i SET archived = true, returned_at = NULL
FROM read_groups selected
WHERE i.workspace_id = $1
AND i.recipient_type = 'member'
@@ -362,7 +373,7 @@ WHERE i.workspace_id = $1
-- name: ArchiveCompletedInbox :execrows
-- Snoozed issues included: a done issue leaves the inbox either way.
-UPDATE inbox_item i SET archived = true, snoozed_until = NULL, snoozed_at = NULL
+UPDATE inbox_item i SET archived = true, snoozed_until = NULL, snoozed_at = NULL, returned_at = NULL
WHERE i.workspace_id = $1 AND i.recipient_type = 'member' AND i.recipient_id = $2 AND i.archived = false
AND i.issue_id IN (
SELECT id FROM issue
@@ -394,7 +405,10 @@ WITH target AS (
UPDATE inbox_item item
SET snoozed_until = sqlc.arg('snoozed_until')::timestamptz,
snoozed_at = CASE WHEN item.snoozed_until > now() AND item.snoozed_at IS NOT NULL THEN item.snoozed_at ELSE now() END,
- read = CASE WHEN item.id = (SELECT id FROM newest) THEN false ELSE item.read END
+ read = CASE WHEN item.id = (SELECT id FROM newest) THEN false ELSE item.read END,
+ -- The issue comes back on top when the snooze ends: the newest row ranks
+ -- by that time for the inbox limit, the others by when they arrived.
+ returned_at = CASE WHEN item.id = (SELECT id FROM newest) THEN sqlc.arg('snoozed_until')::timestamptz END
FROM target
WHERE item.workspace_id = target.workspace_id
AND item.recipient_type = target.recipient_type
@@ -405,11 +419,21 @@ RETURNING item.*;
-- name: UnsnoozeInboxGroup :many
-- Ends a snooze on one issue: back in the inbox now. Also clears the time a
--- snooze that already ran out left on the rows.
-UPDATE inbox_item SET snoozed_until = NULL, snoozed_at = NULL
-WHERE workspace_id = $1 AND recipient_type = $2 AND recipient_id = $3 AND issue_id = $4
- AND archived = false AND snoozed_until IS NOT NULL
-RETURNING *;
+-- snooze that already ran out left on the rows. The issue's newest row ranks
+-- as back now for the inbox limit, or when the snooze ran out if it already
+-- had; the others rank by when they arrived.
+WITH newest AS (
+ SELECT n.id FROM inbox_item n
+ WHERE n.workspace_id = $1 AND n.recipient_type = $2 AND n.recipient_id = $3 AND n.issue_id = $4
+ AND n.archived = false
+ ORDER BY n.created_at DESC, n.id DESC
+ LIMIT 1
+)
+UPDATE inbox_item AS item SET snoozed_until = NULL, snoozed_at = NULL,
+ returned_at = CASE WHEN item.id = (SELECT id FROM newest) THEN LEAST(item.snoozed_until, now()) END
+WHERE 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.snoozed_until IS NOT NULL
+RETURNING item.*;
-- name: ListSnoozedInbox :many
-- The recipient's snoozed issues, soonest back first (MUL-9333). `updates` is
@@ -452,3 +476,100 @@ JOIN LATERAL (
LIMIT 1
) newest ON true
ORDER BY g.snoozed_until ASC, g.issue_id;
+
+-- name: InboxOverflows :one
+-- Whether the recipient's inbox shows more than `keep` rows, by the rules
+-- ListInboxItems shows them: active, not snoozed, outside the projects the
+-- recipient cannot see (hidden_project_ids), ranked by when they arrived or
+-- came back.
+SELECT count(*) > 0 FROM (
+ SELECT 1 FROM inbox_item i
+ LEFT JOIN issue iss ON iss.id = i.issue_id
+ WHERE i.workspace_id = $1 AND i.recipient_type = $2 AND i.recipient_id = $3
+ AND i.archived = false
+ AND (i.snoozed_until IS NULL OR i.snoozed_until <= now())
+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR iss.project_id IS NULL
+ OR NOT (iss.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
+ ORDER BY GREATEST(i.created_at, i.returned_at) DESC, i.id DESC
+ OFFSET sqlc.arg('keep')::int
+ LIMIT 1
+) beyond;
+
+-- name: ArchiveInboxOverflow :execrows
+-- Archives up to batch_size of the recipient's shown rows ranked below the
+-- newest `keep`, oldest first, in ListInboxItems' order. The boundary is read
+-- in the same statement, so every batch sees the inbox as it is now. Rows are
+-- archived one by one: unlike the issue-level archive actions, newer rows on
+-- the same issue stay. Snoozed rows, and rows in projects the recipient can
+-- no longer see, neither count nor get archived: a snooze is never ended
+-- 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 (
+ 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
+ WHERE b.workspace_id = sqlc.arg('workspace_id') AND b.recipient_type = sqlc.arg('recipient_type')
+ AND b.recipient_id = sqlc.arg('recipient_id')
+ AND b.archived = false
+ AND (b.snoozed_until IS NULL OR b.snoozed_until <= now())
+ AND (sqlc.narg('hidden_project_ids')::uuid[] IS NULL OR b_iss.project_id IS NULL
+ OR NOT (b_iss.project_id = ANY(sqlc.narg('hidden_project_ids')::uuid[])))
+ ORDER BY GREATEST(b.created_at, b.returned_at) DESC, b.id DESC
+ OFFSET sqlc.arg('keep')::int - 1
+ LIMIT 1
+), overflow AS (
+ SELECT o.id FROM inbox_item o
+ CROSS JOIN boundary
+ LEFT JOIN issue o_iss ON o_iss.id = o.issue_id
+ WHERE o.workspace_id = sqlc.arg('workspace_id') AND o.recipient_type = sqlc.arg('recipient_type')
+ AND o.recipient_id = sqlc.arg('recipient_id')
+ AND o.archived = false
+ AND (o.snoozed_until IS NULL OR o.snoozed_until <= now())
+ 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)
+ ORDER BY GREATEST(o.created_at, o.returned_at), o.id
+ LIMIT sqlc.arg('batch_size')::int
+ FOR UPDATE OF o SKIP LOCKED
+)
+-- ANY(ARRAY(...)) keeps the update on primary-key lookups; a join against the
+-- CTE lets the planner pick a scan of the whole table.
+UPDATE inbox_item AS item SET archived = true, snoozed_until = NULL, snoozed_at = NULL, returned_at = NULL
+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
+ 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 (
+ SELECT DISTINCT ON (r.issue_id) r.issue_id, r.id,
+ GREATEST(ranked_groups.returned_at, r.snoozed_until) AS returned_at
+ FROM inbox_item r
+ JOIN ranked_groups ON ranked_groups.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
+)
+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);