Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-9456: bound inbox read load and coalesce summary refreshes (PR1) (#10798)
Multica Eve7e9c07703138
diff --git a/.env.example b/.env.exampleindex 03565c2cf8..b07e27e006 100644--- a/.env.example+++ b/.env.example@@ -13,6 +13,10 @@ DATABASE_URL=postgres://multica:multica@localhost:5432/multica?sslmode=disable# node. Set 1-64 to lower it for memory-constrained databases, or 0 to keep the# database/session default. Values above 64 or invalid values fall back to 64.# DATABASE_SEARCH_WORK_MEM_MB=64+# Optional per-process inbox read budgets (see docs/inbox-read-protection.md).+# INBOX_READ_CONCURRENCY=2+# INBOX_READ_STATEMENT_TIMEOUT_MS=3000+# INBOX_READ_TIMEOUT_MS=5000# Optional PostgreSQL read replica. The API keeps all existing reads on primary# until a business explicitly opts into eventual-consistency routing in code.# Every new replica connection is required to be read-only and is recycleddiff --git a/apps/mobile/data/query-client.test.ts b/apps/mobile/data/query-client.test.tsnew file mode 100644index 0000000000..6b12a5fe1e--- /dev/null+++ b/apps/mobile/data/query-client.test.ts@@ -0,0 +1,45 @@+// @vitest-environment node+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { queryClient } from "./query-client";+import { inboxKeys, inboxListOptions, inboxUnreadSummaryOptions } from "./queries/inbox";++const api = vi.hoisted(() => ({ listInbox: vi.fn(), getInboxUnreadSummary: vi.fn() }));+vi.mock("@/data/api", () => ({ api }));+vi.mock("react-native", () => ({ AppState: { addEventListener: () => ({ remove: vi.fn() }) } }));+vi.mock("@react-native-community/netinfo", () => ({ default: { addEventListener: () => vi.fn() } }));++beforeEach(() => vi.resetAllMocks());+afterEach(() => queryClient.clear());++it("does not retry an overloaded inbox list and still forwards cancellation", async () => {+ const busy = Object.assign(new Error("busy"), { status: 503 });+ api.listInbox.mockRejectedValue(busy);+ await expect(queryClient.fetchQuery(inboxListOptions("ws-1"))).rejects.toBe(busy);+ expect(api.listInbox).toHaveBeenCalledTimes(1);+ expect(api.listInbox.mock.calls[0]![0].signal).toBeInstanceOf(AbortSignal);+});++it("retains cached unread counts on 503 and refreshes on the next request", async () => {+ const before = [{ workspace_id: "ws-1", count: 3 }];+ const after = [{ workspace_id: "ws-1", count: 4 }];+ const busy = Object.assign(new Error("busy"), { status: 503 });+ api.getInboxUnreadSummary.mockRejectedValueOnce(busy).mockResolvedValue(after);+ queryClient.setQueryData(inboxKeys.unreadSummary(), before);+ const options = { ...inboxUnreadSummaryOptions("ws-1"), staleTime: 0 };+ await expect(queryClient.fetchQuery(options)).rejects.toBe(busy);+ expect(api.getInboxUnreadSummary).toHaveBeenCalledTimes(1);+ expect(queryClient.getQueryData(inboxKeys.unreadSummary())).toEqual(before);+ await expect(queryClient.fetchQuery(options)).resolves.toEqual(after);+});++it("keeps one retry for other inbox failures", async () => {+ api.listInbox.mockRejectedValueOnce(Object.assign(new Error("failed"), { status: 500 })).mockResolvedValue([]);+ await expect(queryClient.fetchQuery({ ...inboxListOptions("ws-1"), retryDelay: 0 })).resolves.toEqual([]);+ expect(api.listInbox).toHaveBeenCalledTimes(2);+});++it("keeps the retry policy for other query families", async () => {+ const queryFn = vi.fn().mockRejectedValueOnce(Object.assign(new Error("busy"), { status: 503 })).mockResolvedValue("ok");+ await expect(queryClient.fetchQuery({ queryKey: ["other"], queryFn, retryDelay: 0 })).resolves.toBe("ok");+ expect(queryFn).toHaveBeenCalledTimes(2);+});diff --git a/apps/mobile/data/query-client.ts b/apps/mobile/data/query-client.tsindex 5a471b3feb..b46ac9784c 100644--- a/apps/mobile/data/query-client.ts+++ b/apps/mobile/data/query-client.ts@@ -32,6 +32,13 @@ export const queryClient = new QueryClient({},});+// Match web/desktop: keep the previous inbox result on overload and let the+// next event or refresh fetch again, without changing other queries' retries.+queryClient.setQueryDefaults(["inbox"], {+ retry: (failureCount, error) =>+ (error as { status?: number } | null)?.status !== 503 && failureCount < 1,+});+// ── focusManager ← AppState ──────────────────────────────────────────// Foregrounding the app counts as "focus" → triggers refetchOnWindowFocus// for any stale queries the user is currently looking at.diff --git a/docs/inbox-read-protection.md b/docs/inbox-read-protection.mdnew file mode 100644index 0000000000..c16f9f71d9--- /dev/null+++ b/docs/inbox-read-protection.md@@ -0,0 +1,96 @@+# Inbox read protection++Inbox list, unread count, account summary, snoozed list, legacy archive,+archive pages and archive facets share one execution budget per API process.+Admission happens before acquiring a primary database connection. Mutations and+daemon endpoints retain their existing behavior. No SQL or schema changes are+required, and old clients receive the same successful response shapes.++Defaults are two executions, twenty queued reads and 200 ms maximum admission+wait. Pool acquisition plus transaction setup has a separate 200 ms deadline.+Every expensive query runs in a read-only transaction with a transaction-local+3 s PostgreSQL statement timeout. Read work has a 5 s deadline; rollback has a+fresh context bounded to 250 ms and runs before releasing execution capacity.+Once SQL begins, HTTP cancellation does not release its permit early: the SQL+finishes or PostgreSQL stops it before the detached Go query deadline. Transport+failures retain capacity through the possible remaining server query budget.++Summary requests are coalesced per authenticated account and generation. There+is no result cache. Requests arriving before a generation starts share its+result. Later arrivals share the next generation, which starts after the+current one finishes and has its own execution budget. A successful generation+returns immediately to its callers. A later refresh neither discards that+result nor accepts its old SQL snapshot as fresh data. There is at most one+running generation and one pending generation per account, both subject to the+shared admission budget. HTTP callers retain their own 5 s request deadline;+canceling one caller does not cancel its generation's work.+Summary callers, including canceled callers retained until completion, are+bounded to execution concurrency plus twenty per process.++Capacity exhaustion, connection acquisition deadlines and database statement+timeouts return `503` with `Retry-After: 1`. Other database errors remain `500`.+Web, desktop and mobile forward cancellation and skip automatic inbox retries+on 503. They retain cached data on a failed refresh; a subsequent inbox event+or explicit refresh can fetch again. Existing archive queries already disable+retries. Older clients may still retry, but+server execution and waiting remain bounded.++## Configuration and monitoring++All settings are optional. Invalid values log a warning and use the default.++| Environment variable | Default | Accepted values |+| --- | --- | --- |+| `INBOX_READ_CONCURRENCY` | 2 | 1–20 per process |+| `INBOX_READ_STATEMENT_TIMEOUT_MS` | 3000 | 1–60000 ms |+| `INBOX_READ_TIMEOUT_MS` | 5000 | 1000–120000 ms |++The request budget must exceed the SQL budget by at least one second. An+inconsistent configuration is increased to SQL timeout plus two seconds with a+warning. Queries do not begin when the remaining deadline cannot accommodate+the SQL timeout, network headroom and rollback. Changing settings requires a+process restart. Increasing either concurrency or SQL time raises database load.++The existing metrics listener exports `multica_inbox_read_active`,+`multica_inbox_read_queued`, `multica_inbox_read_rejected_total`,+`multica_inbox_read_duration_seconds`, `multica_inbox_read_query_duration_seconds`+and `multica_inbox_read_timeouts_total`.+Duration measures admitted transaction work including pool acquisition and+cleanup. Labels contain operation and rejection reason, never account IDs.+Correlate with primary CPU, connection acquisition latency, inbox failures and+daemon latency/5xx. A per-process budget limits work; it does not by itself+guarantee a database CPU ceiling or a daemon SLO.++## Rollout validation and rollback++Deploy server and clients independently. At three replicas the default admits+six concurrent inbox transactions; include surge replicas when sizing a rolling+deployment. Verify large-account latency and rejection rates before increasing+limits. Keep 503 responses visible in availability metrics.++Local regression coverage exercises database `pg_sleep` termination, pooled+setting restoration, bounded execution/queueing, canceled waiters, account+isolation, shared execution, all seven HTTP routes, and frontend cache/cancellation+behavior. Local checks do not substitute for the planned staging acceptance:+three API pods, normal daemon traffic, tenfold inbox refresh traffic and injected+2 s SQL delays. Confirm admission limits, primary CPU and daemon SLOs there.++`TestInboxReadThreeInstancesBoundSlowSQL` provides a repeatable local stress+check on the checkout's isolated test database: three independent 25-connection+pools and guards, a burst of 30 inbox reads per instance (10x a three-read+refresh), 2 s SQL delays and 150 concurrent control reads. It checks execution+limits, overload rejection and capacity for unrelated database reads. Run with+the checkout's test `DATABASE_URL` configured:++```sh+cd server+go test -race ./internal/handler -run TestInboxReadThreeInstancesBoundSlowSQL -count=1 -v+```++This checks database admission locally; it does not exercise daemon HTTP+endpoints, measure staging CPU or validate a three-pod rollout.++Redis and read replicas are not dependencies of this guard. SQL optimization+and indexes remain a separate PR. Application rollback requires no database+rollback, but removing this guard also removes overload protection. Prefer+adjusting the optional settings after measurement while keeping protection on.diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 1bd5623833..c7dce0c8c2 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -3196,8 +3196,8 @@ export class ApiClient {}// Inbox- async listInbox(): Promise<InboxItem[]> {- const raw = await this.fetch<unknown>("/api/inbox");+ async listInbox(signal?: AbortSignal): Promise<InboxItem[]> {+ const raw = await this.fetch<unknown>("/api/inbox", { signal });return parseWithFallback(raw, InboxItemListSchema, EMPTY_INBOX_ITEMS, {endpoint: "GET /api/inbox",});@@ -3255,8 +3255,8 @@ export class ApiClient {}// The viewer's snoozed issues, soonest back first (MUL-9333).- async listSnoozedInbox(): Promise<SnoozedInboxIssue[]> {- const raw = await this.fetch<unknown>("/api/inbox/snoozed");+ async listSnoozedInbox(signal?: AbortSignal): Promise<SnoozedInboxIssue[]> {+ const raw = await this.fetch<unknown>("/api/inbox/snoozed", { signal });return parseWithFallback(raw, SnoozedInboxListSchema, EMPTY_SNOOZED_INBOX, {endpoint: "GET /api/inbox/snoozed",});@@ -3278,8 +3278,8 @@ export class ApiClient {// to that has unread inbox items. Backs the workspace-switcher dot for// OTHER workspaces. Schema-guarded so a contract drift hides the dot rather// than crashing the sidebar.- async getInboxUnreadSummary(): Promise<InboxWorkspaceUnread[]> {- const raw = await this.fetch<unknown>("/api/inbox/unread-summary");+ async getInboxUnreadSummary(signal?: AbortSignal): Promise<InboxWorkspaceUnread[]> {+ const raw = await this.fetch<unknown>("/api/inbox/unread-summary", { signal });return parseWithFallback(raw, InboxUnreadSummarySchema, EMPTY_INBOX_UNREAD_SUMMARY, {endpoint: "GET /api/inbox/unread-summary",});diff --git a/packages/core/inbox/overload.test.ts b/packages/core/inbox/overload.test.tsnew file mode 100644index 0000000000..6b9f75ad3a--- /dev/null+++ b/packages/core/inbox/overload.test.ts@@ -0,0 +1,79 @@+// @vitest-environment node+import { afterEach, expect, it, vi } from "vitest";+import { QueryClient } from "@tanstack/react-query";+import { ApiClient, ApiError, setApiInstance } from "../api";+import { createQueryClient } from "../query-client";+import { inboxKeys, inboxUnreadSummaryOptions } from "./queries";++afterEach(() => vi.unstubAllGlobals());++it.each(["listInbox", "listSnoozedInbox", "getInboxUnreadSummary"] as const)(+ "%s forwards cancellation to HTTP",+ async (method) => {+ const fetch = vi.fn().mockResolvedValue(Response.json([]));+ vi.stubGlobal("fetch", fetch);+ const controller = new AbortController();+ await new ApiClient("https://api.example.test")[method](controller.signal);+ expect(fetch.mock.calls[0]![1].signal).toBe(controller.signal);+ },+);++it("keeps cached counts on 503 without retrying, then refreshes on the next request", async () => {+ const summary = [{ workspace_id: "ws-1", count: 3 }];+ const fetch = vi.fn()+ .mockResolvedValueOnce(Response.json({ error: "busy" }, { status: 503, headers: { "Retry-After": "1" } }))+ .mockResolvedValueOnce(Response.json([{ workspace_id: "ws-1", count: 4 }]));+ vi.stubGlobal("fetch", fetch);+ setApiInstance(new ApiClient("https://api.example.test"));+ const qc = createQueryClient();+ qc.setQueryData(inboxKeys.unreadSummary(), summary);+ const options = { ...inboxUnreadSummaryOptions(), staleTime: 0 };+ try {+ await expect(qc.fetchQuery(options)).rejects.toBeInstanceOf(ApiError);+ expect(fetch).toHaveBeenCalledTimes(1);+ expect(qc.getQueryData(inboxKeys.unreadSummary())).toEqual(summary);+ await expect(qc.fetchQuery(options)).resolves.toEqual([{ workspace_id: "ws-1", count: 4 }]);+ expect(fetch).toHaveBeenCalledTimes(2);+ } finally { qc.clear(); }+});++it("Query cancellation aborts the superseded summary HTTP request", async () => {+ let signal: AbortSignal | undefined;+ const fetch = vi.fn((_url: string, init: RequestInit) => new Promise<Response>((_resolve, reject) => {+ signal = init.signal as AbortSignal;+ signal.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")));+ }));+ vi.stubGlobal("fetch", fetch);+ setApiInstance(new ApiClient("https://api.example.test"));+ const qc = createQueryClient();+ const result = qc.fetchQuery(inboxUnreadSummaryOptions()).catch(() => undefined);+ try {+ await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(1));+ await qc.cancelQueries({ queryKey: inboxKeys.unreadSummary() });+ await result;+ expect(signal?.aborted).toBe(true);+ } finally { qc.clear(); }+});++it("does not depend on an API error class to recognize overload", async () => {+ const busy = Object.assign(new Error("busy"), { status: 503 });+ const getInboxUnreadSummary = vi.fn().mockRejectedValue(busy);+ setApiInstance({ getInboxUnreadSummary } as unknown as ApiClient);+ const qc = createQueryClient();+ try {+ await expect(qc.fetchQuery(inboxUnreadSummaryOptions())).rejects.toBe(busy);+ expect(getInboxUnreadSummary).toHaveBeenCalledTimes(1);+ } finally { qc.clear(); }+});++it("respects the retry settings of a custom QueryClient", async () => {+ const failed = new Error("unavailable");+ const getInboxUnreadSummary = vi.fn().mockRejectedValueOnce(failed).mockResolvedValue([]);+ setApiInstance({ getInboxUnreadSummary } as unknown as ApiClient);+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ try {+ await expect(qc.fetchQuery(inboxUnreadSummaryOptions())).rejects.toBe(failed);+ expect(getInboxUnreadSummary).toHaveBeenCalledTimes(1);+ await expect(qc.fetchQuery(inboxUnreadSummaryOptions())).resolves.toEqual([]);+ } finally { qc.clear(); }+});diff --git a/packages/core/inbox/queries.ts b/packages/core/inbox/queries.tsindex 8465a251ec..36ded9b764 100644--- a/packages/core/inbox/queries.ts+++ b/packages/core/inbox/queries.ts@@ -24,7 +24,7 @@ export const inboxKeys = {export function inboxListOptions(wsId: string) {return queryOptions({queryKey: inboxKeys.list(wsId),- queryFn: () => api.listInbox(),+ queryFn: ({ signal }) => api.listInbox(signal),});}@@ -35,7 +35,7 @@ export function inboxListOptions(wsId: string) {export function snoozedInboxOptions(wsId: string) {return queryOptions({queryKey: inboxKeys.snoozed(wsId),- queryFn: () => api.listSnoozedInbox(),+ queryFn: ({ signal }) => api.listSnoozedInbox(signal),});}@@ -133,7 +133,7 @@ export function patchArchivedInboxCaches(qc: QueryClient, wsId: string, patch: (export function inboxUnreadSummaryOptions() {return queryOptions({queryKey: inboxKeys.unreadSummary(),- queryFn: () => api.getInboxUnreadSummary(),+ queryFn: ({ signal }) => api.getInboxUnreadSummary(signal),enabled: () => focusManager.isFocused(),refetchOnWindowFocus: true,});diff --git a/packages/core/query-client.ts b/packages/core/query-client.tsindex 7a8ada9172..7c515fd3f2 100644--- a/packages/core/query-client.ts+++ b/packages/core/query-client.ts@@ -4,7 +4,7 @@ import { workspaceKeys } from "./workspace/queries";import type { Workspace } from "./types";export function createQueryClient(): QueryClient {- return new QueryClient({+ const client = new QueryClient({defaultOptions: {queries: {staleTime: Infinity,@@ -18,6 +18,14 @@ export function createQueryClient(): QueryClient {},},});+ // Keep the policy on the app client so custom clients and explicit query+ // overrides retain their retry settings. Status checks also work across+ // mocked API modules and different client error classes.+ client.setQueryDefaults(["inbox"], {+ retry: (failureCount, error) =>+ (error as { status?: number } | null)?.status !== 503 && failureCount < 1,+ });+ return client;}/**diff --git a/server/cmd/server/main.go b/server/cmd/server/main.goindex 73053b60bf..20f41760b3 100644--- a/server/cmd/server/main.go+++ b/server/cmd/server/main.go@@ -620,6 +620,7 @@ func main() {metricsConfig := obsmetrics.ConfigFromEnv()var metricsServer *http.Server+ var inboxReadMetrics *obsmetrics.InboxReadMetricsvar httpMetrics *obsmetrics.HTTPMetricsvar businessMetrics *obsmetrics.BusinessMetricsvar channelMediaMetrics *obsmetrics.ChannelMediaReconcilerMetrics@@ -635,6 +636,7 @@ func main() {Version: version,Commit: commit,})+ inboxReadMetrics = metricsRegistry.InboxReadhttpMetrics = metricsRegistry.HTTPbusinessMetrics = metricsRegistry.BusinesschannelMediaMetrics = metricsRegistry.ChannelMedia@@ -682,6 +684,7 @@ func main() {}r, h := NewRouterWithOptions(pool, hub, bus, analyticsClient, storeRedis, RouterOptions{+ InboxReadMetrics: inboxReadMetrics,HTTPMetrics: httpMetrics,BusinessMetrics: businessMetrics,ChannelLeaseMetrics: channelLeaseMetrics,diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 1cd4fd0b3f..ee16de438f 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -223,6 +223,7 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus, analytics}type RouterOptions struct {+ InboxReadMetrics *obsmetrics.InboxReadMetricsHTTPMetrics *obsmetrics.HTTPMetricsBusinessMetrics *obsmetrics.BusinessMetricsChannelLeaseMetrics *obsmetrics.ChannelLeaseMetrics@@ -463,6 +464,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.BusinvitationRateLimits.Recipient.Limit = envNonNegativeInt("RATE_LIMIT_INVITATION_RECIPIENT_24H", invitationRateLimits.Recipient.Limit)h.InvitationRateLimiters = handler.NewMemoryInvitationRateLimiters(invitationRateLimits)h.Metrics = opts.BusinessMetrics+ h.InboxReads.Metrics = opts.InboxReadMetricsh.FeatureFlags = opts.FeatureFlagsh.ThemeStore = themeStoreFromEnv()h.TaskService.FeatureFlags = opts.FeatureFlagsdiff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex 98a1bf7297..c0903921a0 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/inboxread""github.com/multica-ai/multica/server/internal/integrations/channel/engine"composio "github.com/multica-ai/multica/server/internal/integrations/composio""github.com/multica-ai/multica/server/internal/integrations/dingtalk"@@ -219,6 +220,7 @@ type RuntimeRecoveryNotifier interface {}type Handler struct {+ InboxReads *inboxread.GuardQueries *db.QueriesReadSelector *dbreader.SelectorDB dbExecutor@@ -524,6 +526,7 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *eventReadSelector: dbreader.NewPrimaryOnly(queries),DB: executor,TxStarter: txStarter,+ InboxReads: inboxread.New(inboxread.ConfigFromEnv()),Hub: hub,DaemonHub: daemonHub,DaemonProfileRefresh: daemonProfileRefresh,diff --git a/server/internal/handler/inbox.go b/server/internal/handler/inbox.goindex 9fed9434ee..634fbcdc5b 100644--- a/server/internal/handler/inbox.go+++ b/server/internal/handler/inbox.go@@ -198,6 +198,8 @@ func (h *Handler) enrichInboxResponse(ctx context.Context, resp InboxItemRespons}func (h *Handler) ListInbox(w http.ResponseWriter, r *http.Request) {+ r, cancel := h.inboxReadRequest(r)+ defer cancel()userID, ok := requireUserID(w, r)if !ok {return@@ -215,18 +217,20 @@ func (h *Handler) ListInbox(w http.ResponseWriter, r *http.Request) {// Notifications about private-project issues are not written for// outsiders (CreateInboxItem); this read filter also drops older rows once// the reader loses access.- hidden, ok := h.requestHiddenProjects(w, r, workspaceID)+ hidden, ok := h.requestInboxHiddenProjects(w, r, workspaceID)if !ok {return}- items, err := h.Queries.ListInboxItems(r.Context(), db.ListInboxItemsParams{- WorkspaceID: wsUUID,- RecipientType: "member",- RecipientID: parseUUID(userID),- HiddenProjectIds: hidden.Param(),+ items, err := runInboxRead(r.Context(), h, "list", func(ctx context.Context, q *db.Queries) ([]db.ListInboxItemsRow, error) {+ return q.ListInboxItems(ctx, db.ListInboxItemsParams{+ WorkspaceID: wsUUID,+ RecipientType: "member",+ RecipientID: parseUUID(userID),+ HiddenProjectIds: hidden.Param(),+ })})if err != nil {- writeError(w, http.StatusInternalServerError, "failed to list inbox")+ writeInboxReadError(w, err, "failed to list inbox")return}@@ -256,7 +260,7 @@ func (h *Handler) requireInboxOwnerAccess(w http.ResponseWriter, r *http.Requestreturn deny()}slog.Warn("resolve inbox access failed", append(logger.RequestAttrs(r), "error", err)...)- writeError(w, http.StatusInternalServerError, "failed to resolve inbox access")+ writeInboxReadError(w, err, "failed to resolve inbox access")return false}// A cloud-node PAT has no authenticated task binding or human trigger.@@ -298,6 +302,8 @@ func (h *Handler) requireInboxOwnerAccess(w http.ResponseWriter, r *http.Request// groups and returns only each group's newest row plus its optional comment// anchor — see the query comment for both the bound and the grouping contract.func (h *Handler) ListArchivedInbox(w http.ResponseWriter, r *http.Request) {+ r, cancel := h.inboxReadRequest(r)+ defer cancel()userID, ok := requireUserID(w, r)if !ok {return@@ -312,18 +318,20 @@ func (h *Handler) ListArchivedInbox(w http.ResponseWriter, r *http.Request) {return}- hidden, ok := h.requestHiddenProjects(w, r, workspaceID)+ hidden, ok := h.requestInboxHiddenProjects(w, r, workspaceID)if !ok {return}- items, err := h.Queries.ListArchivedInboxItems(r.Context(), db.ListArchivedInboxItemsParams{- WorkspaceID: wsUUID,- RecipientType: "member",- RecipientID: parseUUID(userID),- HiddenProjectIds: hidden.Param(),+ items, err := runInboxRead(r.Context(), h, "archived", func(ctx context.Context, q *db.Queries) ([]db.ListArchivedInboxItemsRow, error) {+ return q.ListArchivedInboxItems(ctx, db.ListArchivedInboxItemsParams{+ WorkspaceID: wsUUID,+ RecipientType: "member",+ RecipientID: parseUUID(userID),+ HiddenProjectIds: hidden.Param(),+ })})if err != nil {- writeError(w, http.StatusInternalServerError, "failed to list archived inbox")+ writeInboxReadError(w, err, "failed to list archived inbox")return}@@ -493,6 +501,8 @@ func (h *Handler) UnarchiveInboxItem(w http.ResponseWriter, r *http.Request) {}func (h *Handler) CountUnreadInbox(w http.ResponseWriter, r *http.Request) {+ r, cancel := h.inboxReadRequest(r)+ defer cancel()userID, ok := requireUserID(w, r)if !ok {return@@ -503,18 +513,20 @@ func (h *Handler) CountUnreadInbox(w http.ResponseWriter, r *http.Request) {return}- hidden, ok := h.requestHiddenProjects(w, r, workspaceID)+ hidden, ok := h.requestInboxHiddenProjects(w, r, workspaceID)if !ok {return}- count, err := h.Queries.CountUnreadInbox(r.Context(), db.CountUnreadInboxParams{- WorkspaceID: wsUUID,- RecipientType: "member",- RecipientID: parseUUID(userID),- HiddenProjectIds: hidden.Param(),+ count, err := runInboxRead(r.Context(), h, "unread_count", func(ctx context.Context, q *db.Queries) (int64, error) {+ return q.CountUnreadInbox(ctx, db.CountUnreadInboxParams{+ WorkspaceID: wsUUID,+ RecipientType: "member",+ RecipientID: parseUUID(userID),+ HiddenProjectIds: hidden.Param(),+ })})if err != nil {- writeError(w, http.StatusInternalServerError, "failed to count unread inbox")+ writeInboxReadError(w, err, "failed to count unread inbox")return}@@ -535,17 +547,24 @@ type InboxWorkspaceUnreadResponse struct {// account-level by nature: it ignores the active workspace and keys only on// the authenticated user.func (h *Handler) UnreadInboxSummary(w http.ResponseWriter, r *http.Request) {+ r, cancel := h.inboxReadRequest(r)+ defer cancel()userID, ok := requireUserID(w, r)if !ok {return}- rows, err := h.Queries.CountUnreadInboxByWorkspace(r.Context(), parseUUID(userID))+ value, err := h.inboxReadGuard().Summary(r.Context(), userID, func(ctx context.Context) (any, error) {+ return runInboxRead(ctx, h, "summary", func(ctx context.Context, q *db.Queries) ([]db.CountUnreadInboxByWorkspaceRow, error) {+ return q.CountUnreadInboxByWorkspace(ctx, parseUUID(userID))+ })+ })if err != nil {- writeError(w, http.StatusInternalServerError, "failed to summarize unread inbox")+ writeInboxReadError(w, err, "failed to summarize unread inbox")return}+ rows := value.([]db.CountUnreadInboxByWorkspaceRow)resp := make([]InboxWorkspaceUnreadResponse, len(rows))for i, row := range rows {resp[i] = InboxWorkspaceUnreadResponse{diff --git a/server/internal/handler/inbox_access_test.go b/server/internal/handler/inbox_access_test.goindex 0f63fd5338..af5f0372db 100644--- a/server/internal/handler/inbox_access_test.go+++ b/server/internal/handler/inbox_access_test.go@@ -100,15 +100,19 @@ func TestListInboxAccessLookupErrors(t *testing.T) {}{{"missing", pgx.ErrNoRows, http.StatusForbidden},{"wrapped missing", fmt.Errorf("%s: %w", privateDetails, pgx.ErrNoRows), http.StatusForbidden},- {"deadline", fmt.Errorf("%s: %w", privateDetails, context.DeadlineExceeded), http.StatusInternalServerError},- {"statement timeout", &pgconn.PgError{Code: "57014", Message: privateDetails}, http.StatusInternalServerError},+ {"deadline", fmt.Errorf("%s: %w", privateDetails, context.DeadlineExceeded), http.StatusServiceUnavailable},+ {"statement timeout", &pgconn.PgError{Code: "57014", Message: privateDetails}, http.StatusServiceUnavailable},{"connection failure", errors.New(privateDetails), http.StatusInternalServerError},} {t.Run(e.name+"/"+query+"/"+tc.name, func(t *testing.T) {faults := &inboxAccessFailureDB{DBTX: testPool, query: query, err: tc.err}h := *testHandlerh.Queries = db.New(faults)- body := testutil.Call(t, e.serve(&h, nil), e.request(token, testWorkspaceID)).Want(tc.status).Map()+ response := testutil.Call(t, e.serve(&h, nil), e.request(token, testWorkspaceID)).Want(tc.status)+ if tc.status == http.StatusServiceUnavailable && response.Header().Get("Retry-After") != "1" {+ t.Fatal("temporary access-lookup failure must supply Retry-After")+ }+ body := response.Map()if faults.failures != 1 || faults.inboxReads != 0 {t.Fatalf("lookup failures=%d inbox reads=%d; want one failure and no Inbox read", faults.failures, faults.inboxReads)}diff --git a/server/internal/handler/inbox_archive.go b/server/internal/handler/inbox_archive.goindex 79be7d3c24..da7052c72e 100644--- a/server/internal/handler/inbox_archive.go+++ b/server/internal/handler/inbox_archive.go@@ -1,6 +1,7 @@package handlerimport (+ "context""crypto/sha256""encoding/base64""encoding/json"@@ -140,6 +141,8 @@ func archivedInboxScope(p db.ArchivedInboxFacetsParams, groupID pgtype.UUID) str}func (h *Handler) ListArchivedInboxPage(w http.ResponseWriter, r *http.Request) {+ r, cancel := h.inboxReadRequest(r)+ defer cancel()filters, ok := h.parseArchivedInboxFilters(w, r)if !ok {return@@ -193,14 +196,16 @@ func (h *Handler) ListArchivedInboxPage(w http.ResponseWriter, r *http.Request)// Filtered inside the query, before grouping and paging, so a hidden// notification neither shows up nor shortens a page. Not part of the// cursor scope: access can change between pages.- hidden, ok := h.requestHiddenProjects(w, r, uuidToString(filters.WorkspaceID))+ hidden, ok := h.requestInboxHiddenProjects(w, r, uuidToString(filters.WorkspaceID))if !ok {return}p.HiddenProjectIds = hidden.Param()- rows, err := h.Queries.ListArchivedInboxPage(r.Context(), p)+ rows, err := runInboxRead(r.Context(), h, "archived_page", func(ctx context.Context, q *db.Queries) ([]db.ListArchivedInboxPageRow, error) {+ return q.ListArchivedInboxPage(ctx, p)+ })if err != nil {- writeError(w, http.StatusInternalServerError, "failed to load archived inbox page")+ writeInboxReadError(w, err, "failed to load archived inbox page")return}resp := archivedInboxPageResponse{Items: make([]InboxItemResponse, 0, limit), HasMore: len(rows) > limit}@@ -237,18 +242,22 @@ func (h *Handler) ListArchivedInboxPage(w http.ResponseWriter, r *http.Request)}func (h *Handler) GetArchivedInboxFacets(w http.ResponseWriter, r *http.Request) {+ r, cancel := h.inboxReadRequest(r)+ defer cancel()p, ok := h.parseArchivedInboxFilters(w, r)if !ok {return}- hidden, ok := h.requestHiddenProjects(w, r, uuidToString(p.WorkspaceID))+ hidden, ok := h.requestInboxHiddenProjects(w, r, uuidToString(p.WorkspaceID))if !ok {return}p.HiddenProjectIds = hidden.Param()- rows, err := h.Queries.ArchivedInboxFacets(r.Context(), p)+ rows, err := runInboxRead(r.Context(), h, "archived_facets", func(ctx context.Context, q *db.Queries) ([]db.ArchivedInboxFacetsRow, error) {+ return q.ArchivedInboxFacets(ctx, p)+ })if err != nil {- writeError(w, http.StatusInternalServerError, "failed to load archived inbox filters")+ writeInboxReadError(w, err, "failed to load archived inbox filters")return}resp := archivedInboxFacetsResponse{diff --git a/server/internal/handler/inbox_read.go b/server/internal/handler/inbox_read.gonew file mode 100644index 0000000000..059fd30419--- /dev/null+++ b/server/internal/handler/inbox_read.go@@ -0,0 +1,65 @@+package handler++import (+ "context"+ "errors"+ "log/slog"+ "net/http"++ "github.com/jackc/pgx/v5"+ "github.com/multica-ai/multica/server/internal/inboxread"+ "github.com/multica-ai/multica/server/internal/logger"+ "github.com/multica-ai/multica/server/internal/projectaccess"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// Struct-literal handlers used by tests still share a bounded guard.+var defaultInboxReadGuard = inboxread.New(inboxread.ConfigFromEnv())++func (h *Handler) inboxReadGuard() *inboxread.Guard {+ if h.InboxReads != nil {+ return h.InboxReads+ }+ return defaultInboxReadGuard+}++func runInboxRead[T any](ctx context.Context, h *Handler, operation string, query func(context.Context, *db.Queries) (T, error)) (result T, err error) {+ err = h.inboxReadGuard().Run(ctx, operation, h.TxStarter, func(ctx context.Context, tx pgx.Tx) error {+ var queryErr error+ result, queryErr = query(ctx, h.Queries.WithTx(tx))+ return queryErr+ })+ return result, err+}++func writeInboxReadError(w http.ResponseWriter, err error, message string) {+ if inboxread.IsUnavailable(err) {+ w.Header().Set("Retry-After", "1")+ writeError(w, http.StatusServiceUnavailable, "inbox is temporarily busy; retry shortly")+ return+ }+ if errors.Is(err, context.Canceled) {+ w.WriteHeader(499)+ return+ }+ writeError(w, http.StatusInternalServerError, message)+}++func (h *Handler) inboxReadRequest(r *http.Request) (*http.Request, context.CancelFunc) {+ ctx, cancel := h.inboxReadGuard().Context(r.Context())+ return r.WithContext(ctx), cancel+}++// Permission failures still fail closed. A request-budget timeout during the+// lookup follows the same temporary-unavailability contract as the inbox SQL.+func (h *Handler) requestInboxHiddenProjects(w http.ResponseWriter, r *http.Request, workspaceID string) (projectaccess.Hidden, bool) {+ hidden, err := h.hiddenProjects(r, workspaceID)+ if err != nil {+ if !writeQueryCancellation(w, r, err) {+ slog.Warn("resolve inbox project access failed", append(logger.RequestAttrs(r), "error", err)...)+ writeInboxReadError(w, err, "failed to resolve project access")+ }+ return projectaccess.Hidden{}, false+ }+ return hidden, true+}diff --git a/server/internal/handler/inbox_read_test.go b/server/internal/handler/inbox_read_test.gonew file mode 100644index 0000000000..952559f584--- /dev/null+++ b/server/internal/handler/inbox_read_test.go@@ -0,0 +1,241 @@+package handler++import (+ "context"+ "errors"+ "net/http"+ "net/http/httptest"+ "sync"+ "sync/atomic"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn"+ "github.com/jackc/pgx/v5/pgxpool"+ "github.com/multica-ai/multica/server/internal/inboxread"+ "github.com/multica-ai/multica/server/internal/testutil"+)++func TestInboxReadPostgresTimeoutAndLocalSettings(t *testing.T) {+ conn, err := testPool.Acquire(context.Background())+ if err != nil {+ t.Fatal(err)+ }+ defer conn.Release()+ var before string+ if err := conn.QueryRow(context.Background(), "SHOW statement_timeout").Scan(&before); err != nil {+ t.Fatal(err)+ }+ g := inboxread.New(inboxread.Config{Concurrency: 1, StatementTimeout: 50 * time.Millisecond})+ start := time.Now()+ err = g.Run(context.Background(), "summary", conn, func(ctx context.Context, tx pgx.Tx) error {+ var timeout, readOnly string+ if err := tx.QueryRow(ctx, "SELECT current_setting('statement_timeout'), current_setting('transaction_read_only')").Scan(&timeout, &readOnly); err != nil {+ return err+ }+ if timeout != "50ms" || readOnly != "on" {+ t.Errorf("transaction settings = %s, %s", timeout, readOnly)+ }+ _, err := tx.Exec(ctx, "SELECT pg_sleep(2)")+ return err+ })+ var pgErr *pgconn.PgError+ if !errors.As(err, &pgErr) || pgErr.Code != "57014" {+ t.Fatalf("database did not terminate slow SQL: %v", err)+ }+ if time.Since(start) > time.Second {+ t.Fatal("statement timeout took too long")+ }+ var after string+ if err := conn.QueryRow(context.Background(), "SHOW statement_timeout").Scan(&after); err != nil {+ t.Fatalf("connection not reusable after rollback: %v", err)+ }+ if after != before {+ t.Fatalf("transaction setting leaked: before %s after %s", before, after)+ }+ if err := g.Run(context.Background(), "list", conn, func(ctx context.Context, tx pgx.Tx) error { _, err := tx.Exec(ctx, "SELECT 1"); return err }); err != nil {+ t.Fatalf("permit/transaction leaked: %v", err)+ }+}++func TestInboxReadCallerCancellationKeepsDatabaseBudget(t *testing.T) {+ g := inboxread.New(inboxread.Config{Concurrency: 1, StatementTimeout: 50 * time.Millisecond})+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ err := g.Run(ctx, "list", testPool, func(ctx context.Context, tx pgx.Tx) error {+ cancel()+ if ctx.Err() != nil {+ t.Fatalf("caller canceled active SQL context: %v", ctx.Err())+ }+ _, err := tx.Exec(ctx, "SELECT pg_sleep(2)")+ return err+ })+ var pgErr *pgconn.PgError+ if !errors.As(err, &pgErr) || pgErr.Code != "57014" {+ t.Fatalf("permit returned before database timeout: %v", err)+ }+}++func TestAllInboxReadHandlersShareCapacity(t *testing.T) {+ h := *testHandler+ h.InboxReads = inboxread.New(inboxread.Config{Concurrency: 1})+ started, finish, result := make(chan struct{}), make(chan struct{}), make(chan error, 1)+ go func() {+ result <- h.InboxReads.Run(context.Background(), "summary", testPool, func(context.Context, pgx.Tx) error { close(started); <-finish; return nil })+ }()+ <-started+ defer func() {+ close(finish)+ if err := <-result; err != nil {+ t.Error(err)+ }+ }()+ for _, endpoint := range []struct {+ path string+ handler http.HandlerFunc+ }{+ {"/api/inbox", h.ListInbox},+ {"/api/inbox/unread-count", h.CountUnreadInbox},+ {"/api/inbox/unread-summary", h.UnreadInboxSummary},+ {"/api/inbox/snoozed", h.ListSnoozedInbox},+ {"/api/inbox/archived", h.ListArchivedInbox},+ {"/api/inbox/archived/page", h.ListArchivedInboxPage},+ {"/api/inbox/archived/facets", h.GetArchivedInboxFacets},+ } {+ t.Run(endpoint.path, func(t *testing.T) {+ rec := testutil.Call(t, inboxWorkspaceHandler(endpoint.handler), inboxRequest(http.MethodGet, endpoint.path, testWorkspaceID)).Want(http.StatusServiceUnavailable)+ if rec.Header().Get("Retry-After") != "1" {+ t.Fatal("missing Retry-After")+ }+ })+ }+}++func TestInboxReadErrorContract(t *testing.T) {+ for _, tc := range []struct {+ err error+ status int+ }{+ {inboxread.ErrBusy, 503},+ {context.DeadlineExceeded, 503},+ {&pgconn.PgError{Code: "57014"}, 503},+ {&pgconn.PgError{Code: "42P01"}, 500},+ {context.Canceled, 499},+ } {+ rec := httptest.NewRecorder()+ writeInboxReadError(rec, tc.err, "failed to read inbox")+ if rec.Code != tc.status {+ t.Fatalf("%v => %d, want %d", tc.err, rec.Code, tc.status)+ }+ if tc.status == 503 && rec.Header().Get("Retry-After") != "1" {+ t.Fatal("missing Retry-After")+ }+ if tc.status == 499 && rec.Body.Len() != 0 {+ t.Fatal("wrote a body after cancellation")+ }+ }+}++// This local database stress test verifies connection isolation with three+// independent API budgets. It does not measure staging CPU or daemon API SLOs.+func TestInboxReadThreeInstancesBoundSlowSQL(t *testing.T) {+ const instances, requestsPerInstance = 3, 30 // 10x a list/summary/snoozed refresh.+ var pools [instances]*pgxpool.Pool+ var guards [instances]*inboxread.Guard+ var active, peak [instances]atomic.Int32+ var accepted, refused atomic.Int32+ started := make(chan struct{}, instances*2)+ results := make(chan error, instances*requestsPerInstance)+ for instance := range instances {+ cfg := testPool.Config().Copy()+ cfg.MaxConns, cfg.MinConns = 25, 0+ pool, err := pgxpool.NewWithConfig(context.Background(), cfg)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(pool.Close)+ if err := pool.Ping(context.Background()); err != nil {+ t.Fatal(err)+ }+ pools[instance] = pool+ guards[instance] = inboxread.New(inboxread.Config{Concurrency: 2})+ }+ for instance := range instances {+ for range requestsPerInstance {+ go func() {+ err := guards[instance].Run(context.Background(), "list", pools[instance], func(ctx context.Context, tx pgx.Tx) error {+ n := active[instance].Add(1)+ defer active[instance].Add(-1)+ for previous := peak[instance].Load(); n > previous; previous = peak[instance].Load() {+ if peak[instance].CompareAndSwap(previous, n) {+ break+ }+ }+ select {+ case started <- struct{}{}:+ default:+ }+ _, err := tx.Exec(ctx, "SELECT pg_sleep(2)")+ return err+ })+ if err == nil {+ accepted.Add(1)+ } else if inboxread.IsUnavailable(err) {+ refused.Add(1)+ err = nil+ }+ results <- err+ }()+ }+ }+ for range instances * 2 {+ select {+ case <-started:+ case <-time.After(time.Second):+ t.Fatal("slow reads did not start")+ }+ }+ var controls sync.WaitGroup+ controlResults := make(chan error, instances)+ var maxControlLatency [instances]time.Duration+ for instance := range instances {+ controls.Go(func() {+ for range 50 {+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)+ start := time.Now()+ var value int+ err := pools[instance].QueryRow(ctx, "SELECT 1").Scan(&value)+ cancel()+ maxControlLatency[instance] = max(maxControlLatency[instance], time.Since(start))+ if err != nil {+ controlResults <- err+ return+ }+ time.Sleep(20 * time.Millisecond)+ }+ controlResults <- nil+ })+ }+ controls.Wait()+ for range instances {+ if err := <-controlResults; err != nil {+ t.Errorf("unrelated database read failed: %v", err)+ }+ }+ for range instances * requestsPerInstance {+ if err := <-results; err != nil {+ t.Error(err)+ }+ }+ for instance := range instances {+ if n := peak[instance].Load(); n > 2 {+ t.Errorf("instance %d ran %d inbox queries", instance, n)+ }+ t.Logf("instance=%d peak_inbox_queries=%d max_control_latency=%s", instance, peak[instance].Load(), maxControlLatency[instance])+ }+ if refused.Load() == 0 {+ t.Error("burst did not exercise overload rejection")+ }+ t.Logf("inbox_requests=%d accepted=%d unavailable=%d control_reads=%d", instances*requestsPerInstance, accepted.Load(), refused.Load(), instances*50)+}diff --git a/server/internal/handler/inbox_snooze.go b/server/internal/handler/inbox_snooze.goindex 0a13905b52..971e40b836 100644--- a/server/internal/handler/inbox_snooze.go+++ b/server/internal/handler/inbox_snooze.go@@ -1,6 +1,7 @@package handlerimport (+ "context""encoding/json""net/http""time"@@ -26,6 +27,8 @@ type SnoozedInboxResponse struct {// for the Snoozed view (MUL-9333). An issue whose time has passed is back in// the main list and no longer here.func (h *Handler) ListSnoozedInbox(w http.ResponseWriter, r *http.Request) {+ r, cancel := h.inboxReadRequest(r)+ defer cancel()userID, ok := requireUserID(w, r)if !ok {return@@ -35,17 +38,19 @@ func (h *Handler) ListSnoozedInbox(w http.ResponseWriter, r *http.Request) {if !ok {return}- hidden, ok := h.requestHiddenProjects(w, r, workspaceID)+ hidden, ok := h.requestInboxHiddenProjects(w, r, workspaceID)if !ok {return}- rows, err := h.Queries.ListSnoozedInbox(r.Context(), db.ListSnoozedInboxParams{- WorkspaceID: wsUUID,- RecipientID: parseUUID(userID),- HiddenProjectIds: hidden.Param(),+ rows, err := runInboxRead(r.Context(), h, "snoozed", func(ctx context.Context, q *db.Queries) ([]db.ListSnoozedInboxRow, error) {+ return q.ListSnoozedInbox(ctx, db.ListSnoozedInboxParams{+ WorkspaceID: wsUUID,+ RecipientID: parseUUID(userID),+ HiddenProjectIds: hidden.Param(),+ })})if err != nil {- writeError(w, http.StatusInternalServerError, "failed to list snoozed inbox")+ writeInboxReadError(w, err, "failed to list snoozed inbox")return}resp := make([]SnoozedInboxResponse, len(rows))diff --git a/server/internal/inboxread/guard.go b/server/internal/inboxread/guard.gonew file mode 100644index 0000000000..ca54e31e8a--- /dev/null+++ b/server/internal/inboxread/guard.go@@ -0,0 +1,296 @@+// Package inboxread bounds expensive inbox reads before they acquire a database+// connection. Budgets are per process; replicas must be sized together.+package inboxread++import (+ "context"+ "errors"+ "fmt"+ "log/slog"+ "os"+ "strconv"+ "strings"+ "sync"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn"+ "github.com/multica-ai/multica/server/internal/metrics"+)++var ErrBusy = errors.New("inbox read capacity unavailable")++const (+ queueLimit = 20+ queueWait = 200 * time.Millisecond+ setupTimeout = 200 * time.Millisecond+ cleanupTimeout = 250 * time.Millisecond+)++type Config struct {+ Concurrency int+ StatementTimeout time.Duration+ RequestTimeout time.Duration+}++func ConfigFromEnv() Config {+ cfg := Config{+ Concurrency: envInt("INBOX_READ_CONCURRENCY", 2, 1, 20),+ StatementTimeout: time.Duration(envInt("INBOX_READ_STATEMENT_TIMEOUT_MS", 3000, 1, 60000)) * time.Millisecond,+ RequestTimeout: time.Duration(envInt("INBOX_READ_TIMEOUT_MS", 5000, 1000, 120000)) * time.Millisecond,+ }+ if cfg.RequestTimeout < cfg.StatementTimeout+time.Second {+ slog.Warn("inbox read deadline needs headroom above statement timeout; increasing deadline")+ cfg.RequestTimeout = cfg.StatementTimeout + 2*time.Second+ }+ return cfg+}++func envInt(name string, fallback, min, max int) int {+ raw := strings.TrimSpace(os.Getenv(name))+ if raw == "" {+ return fallback+ }+ n, err := strconv.Atoi(raw)+ if err != nil || n < min || n > max {+ slog.Warn("invalid inbox read setting; using default", "name", name, "default", fallback)+ return fallback+ }+ return n+}++type Guard struct {+ active chan struct{}+ queued chan struct{}+ summaryWaiters chan struct{}+ summaryMu sync.Mutex+ summaryCalls map[string]*summaryQueue+ statementTimeout time.Duration+ requestTimeout time.Duration+ Metrics *metrics.InboxReadMetrics+}++type summaryQueue struct {+ current *summaryGeneration+ next *summaryGeneration+}++type summaryGeneration struct {+ ctx context.Context+ query func(context.Context) (any, error)+ started bool // protected by summaryMu+ done chan struct{}+ value any+ err error+}++func New(cfg Config) *Guard {+ if cfg.Concurrency <= 0 {+ cfg.Concurrency = 2+ }+ if cfg.StatementTimeout <= 0 {+ cfg.StatementTimeout = 3 * time.Second+ }+ if cfg.RequestTimeout <= 0 {+ cfg.RequestTimeout = 5 * time.Second+ }+ return &Guard{+ active: make(chan struct{}, cfg.Concurrency),+ queued: make(chan struct{}, queueLimit),+ summaryWaiters: make(chan struct{}, cfg.Concurrency+queueLimit),+ summaryCalls: make(map[string]*summaryQueue),+ statementTimeout: cfg.StatementTimeout,+ requestTimeout: cfg.RequestTimeout,+ }+}++func (g *Guard) acquire(ctx context.Context, operation string) (func(), error) {+ if err := ctx.Err(); err != nil {+ return nil, err+ }+ select {+ case g.active <- struct{}{}:+ return g.release, nil+ default:+ }+ select {+ case g.queued <- struct{}{}:+ default:+ g.Metrics.Reject(operation, "queue_full")+ return nil, ErrBusy+ }+ g.Metrics.Queue(1)+ defer func() { <-g.queued; g.Metrics.Queue(-1) }()+ timer := time.NewTimer(queueWait)+ defer timer.Stop()+ select {+ case g.active <- struct{}{}:+ return g.release, nil+ case <-ctx.Done():+ return nil, ctx.Err()+ case <-timer.C:+ g.Metrics.Reject(operation, "queue_timeout")+ return nil, ErrBusy+ }+}++func (g *Guard) release() { <-g.active }++// Context starts the complete handler budget, including permission lookups.+func (g *Guard) Context(ctx context.Context) (context.Context, context.CancelFunc) {+ return context.WithTimeout(ctx, g.requestTimeout)+}++type TxStarter interface {+ Begin(context.Context) (pgx.Tx, error)+}++// Run keeps the permit through SQL completion and rollback. Once SQL starts,+// a disconnected HTTP caller must not release capacity while Postgres still+// runs its statement. The database timeout fires before the detached Go budget.+// Queueing and pool acquisition remain cancellable and acquire no unbounded work.+func (g *Guard) Run(ctx context.Context, operation string, starter TxStarter, query func(context.Context, pgx.Tx) error) (err error) {+ ctx, cancel := context.WithTimeout(ctx, g.requestTimeout)+ defer cancel()+ release, err := g.acquire(ctx, operation)+ if err != nil {+ return err+ }+ defer release()+ if err := ctx.Err(); err != nil {+ return err+ }+ start := time.Now()+ g.Metrics.Active(1)+ defer func() { g.Metrics.Active(-1); g.Metrics.Observe(operation, time.Since(start), err) }()++ setupCtx, setupCancel := context.WithTimeout(ctx, setupTimeout)+ defer setupCancel()+ tx, err := starter.Begin(setupCtx)+ if err != nil {+ return fmt.Errorf("begin inbox read: %w", err)+ }+ var uncertainUntil time.Time+ defer func() {+ cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), cleanupTimeout)+ defer cleanupCancel()+ _ = tx.Rollback(cleanupCtx)+ // A transport failure can hide a still-running backend. Keep its+ // permit until the server-side timeout could have stopped the SQL,+ // even when rollback cannot communicate with that connection.+ if wait := time.Until(uncertainUntil); wait > 0 {+ timer := time.NewTimer(wait)+ defer timer.Stop()+ <-timer.C+ }+ }()+ if _, err = tx.Exec(setupCtx, fmt.Sprintf("SET LOCAL statement_timeout = %d", g.statementTimeout.Milliseconds())); err != nil {+ return err+ }+ if _, err = tx.Exec(setupCtx, "SET LOCAL transaction_read_only = on"); err != nil {+ return err+ }+ if err := ctx.Err(); err != nil {+ return err+ }+ // Include cleanup in the remaining request budget before detaching SQL.+ if deadline, ok := ctx.Deadline(); ok && time.Until(deadline) < g.statementTimeout+500*time.Millisecond+cleanupTimeout {+ return context.DeadlineExceeded+ }+ // Include server timeout and network headroom, independently of the caller.+ // This is one sqlc query, fully scanned before commit, not a transaction+ // containing an arbitrary number of separately timed statements.+ queryCtx, queryCancel := context.WithTimeout(context.WithoutCancel(ctx), g.statementTimeout+500*time.Millisecond)+ defer queryCancel()+ queryDeadline := time.Now().Add(g.statementTimeout + 500*time.Millisecond)+ queryStart := time.Now()+ err = query(queryCtx, tx)+ g.Metrics.ObserveQuery(operation, time.Since(queryStart))+ if err != nil {+ var pgErr *pgconn.PgError+ if !errors.As(err, &pgErr) && !errors.Is(err, pgx.ErrNoRows) {+ uncertainUntil = queryDeadline+ }+ return err+ }+ return tx.Commit(queryCtx)+}++// Summary coalesces requests into generations per authenticated account. A+// caller arriving after execution starts waits for the next generation, whose+// independent budget begins after the current generation finishes. Successful+// earlier callers never wait for a later refresh. Canceled callers retain their+// admission slot until their generation completes, bounding retained work.+func (g *Guard) Summary(ctx context.Context, userID string, query func(context.Context) (any, error)) (any, error) {+ if err := ctx.Err(); err != nil {+ return nil, err+ }+ select {+ case g.summaryWaiters <- struct{}{}:+ default:+ g.Metrics.Reject("summary", "waiters_full")+ return nil, ErrBusy+ }+ g.summaryMu.Lock()+ queue := g.summaryCalls[userID]+ var generation *summaryGeneration+ if queue == nil {+ generation = newSummaryGeneration(ctx, query)+ queue = &summaryQueue{current: generation}+ g.summaryCalls[userID] = queue+ go g.runSummary(userID, queue)+ } else if !queue.current.started {+ generation = queue.current+ } else {+ if queue.next == nil {+ queue.next = newSummaryGeneration(ctx, query)+ }+ generation = queue.next+ }+ g.summaryMu.Unlock()+ select {+ case <-generation.done:+ <-g.summaryWaiters+ return generation.value, generation.err+ case <-ctx.Done():+ go func() { <-generation.done; <-g.summaryWaiters }()+ return nil, ctx.Err()+ }+}++func newSummaryGeneration(ctx context.Context, query func(context.Context) (any, error)) *summaryGeneration {+ return &summaryGeneration{ctx: context.WithoutCancel(ctx), query: query, done: make(chan struct{})}+}++func (g *Guard) runSummary(userID string, queue *summaryQueue) {+ for {+ g.summaryMu.Lock()+ generation := queue.current+ generation.started = true+ g.summaryMu.Unlock()++ sharedCtx, cancel := context.WithTimeout(generation.ctx, g.requestTimeout)+ value, err := generation.query(sharedCtx)+ if err == nil {+ err = sharedCtx.Err()+ }+ cancel()++ g.summaryMu.Lock()+ generation.value, generation.err = value, err+ close(generation.done)+ if queue.next == nil {+ delete(g.summaryCalls, userID)+ g.summaryMu.Unlock()+ return+ }+ queue.current, queue.next = queue.next, nil+ g.summaryMu.Unlock()+ }+}++func IsUnavailable(err error) bool {+ var pgErr *pgconn.PgError+ return errors.Is(err, ErrBusy) || errors.Is(err, context.DeadlineExceeded) ||+ (errors.As(err, &pgErr) && pgErr.Code == "57014")+}diff --git a/server/internal/inboxread/guard_test.go b/server/internal/inboxread/guard_test.gonew file mode 100644index 0000000000..e4978cabd6--- /dev/null+++ b/server/internal/inboxread/guard_test.go@@ -0,0 +1,318 @@+package inboxread++import (+ "context"+ "errors"+ "io"+ "sync"+ "sync/atomic"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn"+)++type testTx struct{ pgx.Tx }++func (testTx) Exec(context.Context, string, ...any) (pgconn.CommandTag, error) {+ return pgconn.CommandTag{}, nil+}+func (testTx) Commit(context.Context) error { return nil }+func (testTx) Rollback(context.Context) error { return nil }++type testStarter struct{ calls atomic.Int32 }++func (s *testStarter) Begin(context.Context) (pgx.Tx, error) { s.calls.Add(1); return testTx{}, nil }++type blockedStarter struct{}++func (blockedStarter) Begin(ctx context.Context) (pgx.Tx, error) { <-ctx.Done(); return nil, ctx.Err() }++func eventually(t *testing.T, condition func() bool) {+ t.Helper()+ deadline := time.Now().Add(time.Second)+ for !condition() {+ if time.Now().After(deadline) {+ t.Fatal("condition did not become true")+ }+ time.Sleep(time.Millisecond)+ }+}++func TestBoundedExecutionAndQueue(t *testing.T) {+ g := New(Config{Concurrency: 2})+ starter := &testStarter{}+ gate := make(chan struct{})+ defer close(gate)+ var executing atomic.Int32+ query := func(context.Context, pgx.Tx) error { executing.Add(1); <-gate; return nil }+ results := make(chan error, 22)+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ for range 2 {+ go func() { results <- g.Run(ctx, "list", starter, query) }()+ }+ eventually(t, func() bool { return executing.Load() == 2 })+ for range 20 {+ go func() { results <- g.Run(ctx, "snoozed", starter, query) }()+ }+ eventually(t, func() bool { return len(g.queued) == 20 })+ if err := g.Run(ctx, "summary", starter, query); !errors.Is(err, ErrBusy) {+ t.Fatalf("overflow = %v", err)+ }+ if n := starter.calls.Load(); n != 2 {+ t.Fatalf("queued/rejected calls acquired connections: %d", n)+ }+ cancel()+ for range 20 {+ if err := <-results; !errors.Is(err, context.Canceled) {+ t.Fatalf("queued cancel = %v", err)+ }+ }+ // Already executing SQL owns its permits until the database work finishes.+ if len(g.active) != 2 {+ t.Fatal("cancellation released active database capacity")+ }+ gate <- struct{}{}+ gate <- struct{}{}+ for range 2 {+ if err := <-results; err != nil {+ t.Fatal(err)+ }+ }+ if len(g.active) != 0 || len(g.queued) != 0 {+ t.Fatal("capacity leaked")+ }+}++func TestQueueWaitAndPoolAcquireAreBounded(t *testing.T) {+ g := New(Config{Concurrency: 1})+ starter := &testStarter{}+ release, err := g.acquire(context.Background(), "list")+ if err != nil {+ t.Fatal(err)+ }+ start := time.Now()+ err = g.Run(context.Background(), "list", starter, func(context.Context, pgx.Tx) error { t.Fatal("entered SQL"); return nil })+ release()+ if !errors.Is(err, ErrBusy) || time.Since(start) > time.Second || starter.calls.Load() != 0 {+ t.Fatalf("queue wait = %v", err)+ }+ start = time.Now()+ err = g.Run(context.Background(), "list", blockedStarter{}, nil)+ if !errors.Is(err, context.DeadlineExceeded) || time.Since(start) > time.Second || len(g.active) != 0 {+ t.Fatalf("pool acquire = %v", err)+ }+}++func TestSummaryCancellationIsolationAndNoCache(t *testing.T) {+ g := New(Config{Concurrency: 2})+ ctx, cancel := context.WithCancel(context.Background())+ gate := make(chan struct{})+ started := make(chan struct{})+ var calls atomic.Int32+ query := func(ctx context.Context) (any, error) {+ if calls.Add(1) == 1 {+ close(started)+ }+ <-gate+ return "shared", ctx.Err()+ }+ first := make(chan error, 1)+ go func() { _, err := g.Summary(ctx, "user-a", query); first <- err }()+ <-started+ cancel()+ if err := <-first; !errors.Is(err, context.Canceled) {+ t.Fatalf("first = %v", err)+ }+ second := make(chan error, 1)+ go func() {+ value, err := g.Summary(context.Background(), "user-a", query)+ if value != "shared" && err == nil {+ err = errors.New("wrong shared value")+ }+ second <- err+ }()+ eventually(t, func() bool { return len(g.summaryWaiters) == 2 })+ // A different account never shares this account's data.+ value, err := g.Summary(context.Background(), "user-b", func(context.Context) (any, error) { return "other", nil })+ if err != nil || value != "other" {+ t.Fatalf("different user = %v, %v", value, err)+ }+ close(gate)+ if err := <-second; err != nil {+ t.Fatal(err)+ }+ if calls.Load() != 2 {+ t.Fatalf("expected one fresh read for the late caller, got: %d", calls.Load())+ }+ eventually(t, func() bool { return len(g.summaryWaiters) == 0 })+ value, err = g.Summary(context.Background(), "user-a", func(context.Context) (any, error) { return "fresh", nil })+ if err != nil || value != "fresh" {+ t.Fatalf("summary cached stale result: %v %v", value, err)+ }+}++func TestSummaryWaitersRemainBoundedAfterCancellation(t *testing.T) {+ g := New(Config{Concurrency: 1})+ gate := make(chan struct{})+ var executions atomic.Int32+ query := func(context.Context) (any, error) { executions.Add(1); <-gate; return nil, nil }+ for index := range cap(g.summaryWaiters) {+ ctx, cancel := context.WithCancel(context.Background())+ returned := make(chan error, 1)+ go func() { _, err := g.Summary(ctx, "same-user", query); returned <- err }()+ eventually(t, func() bool { return len(g.summaryWaiters) == index+1 })+ cancel()+ if err := <-returned; !errors.Is(err, context.Canceled) {+ t.Fatalf("canceled waiter = %v", err)+ }+ }+ if _, err := g.Summary(context.Background(), "same-user", query); !errors.Is(err, ErrBusy) {+ t.Fatalf("waiter overflow = %v", err)+ }+ close(gate)+ eventually(t, func() bool { return len(g.summaryWaiters) == 0 })+ if executions.Load() > 2 {+ t.Fatalf("queued callers were not coalesced: %d executions", executions.Load())+ }+}++func TestConfigDefaultsAndInvalidValues(t *testing.T) {+ for _, name := range []string{"INBOX_READ_CONCURRENCY", "INBOX_READ_STATEMENT_TIMEOUT_MS", "INBOX_READ_TIMEOUT_MS"} {+ t.Setenv(name, "")+ }+ if cfg := ConfigFromEnv(); cfg.Concurrency != 2 || cfg.StatementTimeout != 3*time.Second || cfg.RequestTimeout != 5*time.Second {+ t.Fatalf("defaults = %+v", cfg)+ }+ t.Setenv("INBOX_READ_CONCURRENCY", "0")+ t.Setenv("INBOX_READ_STATEMENT_TIMEOUT_MS", "garbage")+ if cfg := ConfigFromEnv(); cfg.Concurrency != 2 || cfg.StatementTimeout != 3*time.Second {+ t.Fatalf("invalid config = %+v", cfg)+ }+ t.Setenv("INBOX_READ_STATEMENT_TIMEOUT_MS", "6000")+ if cfg := ConfigFromEnv(); cfg.RequestTimeout < cfg.StatementTimeout+time.Second {+ t.Fatalf("missing deadline headroom = %+v", cfg)+ }+}++func TestTransportFailureRetainsPermitUntilServerBudgetExpires(t *testing.T) {+ g := New(Config{Concurrency: 1, StatementTimeout: 20 * time.Millisecond})+ start := time.Now()+ err := g.Run(context.Background(), "list", &testStarter{}, func(context.Context, pgx.Tx) error { return io.ErrUnexpectedEOF })+ if !errors.Is(err, io.ErrUnexpectedEOF) {+ t.Fatal(err)+ }+ if elapsed := time.Since(start); elapsed < 500*time.Millisecond || elapsed > 2*time.Second {+ t.Fatalf("uncertain SQL permit duration = %s", elapsed)+ }+ if len(g.active) != 0 {+ t.Fatal("permit leaked after server budget expired")+ }+}++func TestSummaryLateRefreshDoesNotReusePreMutationSnapshot(t *testing.T) {+ g := New(Config{Concurrency: 2})+ var current, calls atomic.Int32+ started, finish := make(chan struct{}), make(chan struct{})+ query := func(context.Context) (any, error) {+ snapshot := current.Load()+ if calls.Add(1) == 1 {+ close(started)+ <-finish+ }+ return snapshot, nil+ }+ first, second := make(chan any, 1), make(chan any, 1)+ read := func(results chan<- any) {+ value, err := g.Summary(context.Background(), "user", query)+ if err != nil {+ results <- err+ } else {+ results <- value+ }+ }+ go read(first)+ <-started+ current.Store(1) // A committed mutation and its subsequent refresh event.+ go read(second)+ eventually(t, func() bool {+ g.summaryMu.Lock()+ defer g.summaryMu.Unlock()+ return g.summaryCalls["user"].next != nil+ })+ close(finish)+ if value := <-first; value != int32(0) {+ t.Fatalf("original generation lost its successful result: %v", value)+ }+ if value := <-second; value != int32(1) {+ t.Fatalf("refresh accepted stale snapshot: %v", value)+ }+ if calls.Load() != 2 {+ t.Fatalf("expected one follow-up read, got %d", calls.Load())+ }+ g.summaryMu.Lock()+ defer g.summaryMu.Unlock()+ if len(g.summaryCalls) != 0 {+ t.Fatal("completed summary version leaked")+ }+}++func TestSummarySlowReadReturnsEachGenerationWithItsOwnBudget(t *testing.T) {+ g := New(Config{Concurrency: 2})+ starter := &testStarter{}+ var runs atomic.Int32+ var executing atomic.Int32+ started := make(chan struct{})+ secondGate := make(chan struct{})+ var releaseOnce sync.Once+ releaseSecond := func() { releaseOnce.Do(func() { close(secondGate) }) }+ defer releaseSecond()+ type result struct {+ value any+ err error+ }+ query := func(ctx context.Context) (any, error) {+ var value int32+ err := g.Run(ctx, "summary", starter, func(context.Context, pgx.Tx) error {+ if n := executing.Add(1); n != 1 {+ t.Errorf("same account ran %d queries concurrently", n)+ }+ defer executing.Add(-1)+ value = runs.Add(1)+ if value == 1 {+ close(started)+ } else {+ <-secondGate // The first caller must return before this read finishes.+ }+ time.Sleep(1500 * time.Millisecond)+ return nil+ })+ return value, err+ }+ first, second := make(chan result, 1), make(chan result, 1)+ go func() { value, err := g.Summary(context.Background(), "user", query); first <- result{value, err} }()+ <-started+ time.Sleep(300 * time.Millisecond)+ go func() { value, err := g.Summary(context.Background(), "user", query); second <- result{value, err} }()+ for _, waiter := range []struct {+ result <-chan result+ want int32+ }{{first, 1}, {second, 2}} {+ select {+ case got := <-waiter.result:+ if got.err != nil || got.value != waiter.want {+ t.Fatalf("generation result = %+v, want %d", got, waiter.want)+ }+ if waiter.want == 1 {+ releaseSecond()+ }+ case <-time.After(5 * time.Second):+ t.Fatal("generation did not finish")+ }+ }+ if runs.Load() != 2 {+ t.Fatalf("SQL executions = %d, want 2", runs.Load())+ }+}diff --git a/server/internal/metrics/inbox_read.go b/server/internal/metrics/inbox_read.gonew file mode 100644index 0000000000..aab781ad57--- /dev/null+++ b/server/internal/metrics/inbox_read.go@@ -0,0 +1,70 @@+package metrics++import (+ "context"+ "errors"+ "time"++ "github.com/jackc/pgx/v5/pgconn"+ "github.com/prometheus/client_golang/prometheus"+)++// Labels contain fixed operation/reason names only, never user/workspace IDs.+type InboxReadMetrics struct {+ active prometheus.Gauge+ queued prometheus.Gauge+ rejected *prometheus.CounterVec+ duration *prometheus.HistogramVec+ queryDuration *prometheus.HistogramVec+ timeouts *prometheus.CounterVec+}++func NewInboxReadMetrics() *InboxReadMetrics {+ return &InboxReadMetrics{+ active: prometheus.NewGauge(prometheus.GaugeOpts{Name: "multica_inbox_read_active", Help: "Inbox read transactions holding execution capacity."}),+ queued: prometheus.NewGauge(prometheus.GaugeOpts{Name: "multica_inbox_read_queued", Help: "Inbox reads waiting for execution capacity."}),+ rejected: prometheus.NewCounterVec(prometheus.CounterOpts{Name: "multica_inbox_read_rejected_total", Help: "Inbox reads rejected before acquiring a connection."}, []string{"operation", "reason"}),+ duration: prometheus.NewHistogramVec(prometheus.HistogramOpts{Name: "multica_inbox_read_duration_seconds", Help: "Inbox transaction duration including acquisition and cleanup, excluding admission wait.", Buckets: []float64{.01, .025, .05, .1, .25, .5, 1, 2, 3, 5}}, []string{"operation"}),+ queryDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{Name: "multica_inbox_read_query_duration_seconds", Help: "Inbox SQL execution and row scanning duration.", Buckets: []float64{.01, .025, .05, .1, .25, .5, 1, 2, 3, 5}}, []string{"operation"}),+ timeouts: prometheus.NewCounterVec(prometheus.CounterOpts{Name: "multica_inbox_read_timeouts_total", Help: "Inbox database or connection acquisition timeouts."}, []string{"operation"}),+ }+}++func (m *InboxReadMetrics) Collectors() []prometheus.Collector {+ return []prometheus.Collector{m.active, m.queued, m.rejected, m.duration, m.queryDuration, m.timeouts}+}++func (m *InboxReadMetrics) ObserveQuery(operation string, elapsed time.Duration) {+ if m != nil {+ m.queryDuration.WithLabelValues(operation).Observe(elapsed.Seconds())+ }+}+func (m *InboxReadMetrics) Active(n float64) {+ if m != nil {+ m.active.Add(n)+ }+}+func (m *InboxReadMetrics) Queue(n float64) {+ if m != nil {+ m.queued.Add(n)+ }+}+func (m *InboxReadMetrics) Reject(operation, reason string) {+ if m != nil {+ m.rejected.WithLabelValues(operation, reason).Inc()+ }+}+func (m *InboxReadMetrics) Observe(operation string, elapsed time.Duration, err error) {+ if m == nil {+ return+ }+ m.duration.WithLabelValues(operation).Observe(elapsed.Seconds())+ if isInboxTimeout(err) {+ m.timeouts.WithLabelValues(operation).Inc()+ }+}++func isInboxTimeout(err error) bool {+ var pgErr *pgconn.PgError+ return errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &pgErr) && pgErr.Code == "57014")+}diff --git a/server/internal/metrics/inbox_read_test.go b/server/internal/metrics/inbox_read_test.gonew file mode 100644index 0000000000..165d791db1--- /dev/null+++ b/server/internal/metrics/inbox_read_test.go@@ -0,0 +1,51 @@+package metrics++import (+ "context"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgconn"+ "github.com/prometheus/client_golang/prometheus/testutil"+)++func TestInboxReadMetrics(t *testing.T) {+ r := NewRegistry(RegistryOptions{})+ m := r.InboxRead+ m.Active(1)+ m.Queue(2)+ m.Reject("list", "queue_full")+ m.Observe("list", time.Second, context.DeadlineExceeded)+ m.Observe("summary", time.Second, &pgconn.PgError{Code: "57014"})+ m.ObserveQuery("summary", 50*time.Millisecond)+ if testutil.ToFloat64(m.active) != 1 || testutil.ToFloat64(m.queued) != 2 {+ t.Fatal("missing admission gauges")+ }+ if testutil.ToFloat64(m.rejected.WithLabelValues("list", "queue_full")) != 1 {+ t.Fatal("missing rejection")+ }+ for _, operation := range []string{"list", "summary"} {+ if testutil.ToFloat64(m.timeouts.WithLabelValues(operation)) != 1 {+ t.Fatal("missing timeout")+ }+ }+ families, err := r.Gatherer.Gather()+ if err != nil {+ t.Fatal(err)+ }+ foundQuery := false+ for _, family := range families {+ if family.GetName() == "multica_inbox_read_query_duration_seconds" {+ foundQuery = family.Metric[0].Histogram.GetSampleCount() == 1+ }+ }+ if !foundQuery {+ t.Fatal("missing registered SQL duration histogram")+ }+ var disabled *InboxReadMetrics+ disabled.Active(1)+ disabled.Queue(1)+ disabled.Reject("list", "queue_full")+ disabled.Observe("list", time.Second, nil)+ disabled.ObserveQuery("list", time.Second)+}diff --git a/server/internal/metrics/registry.go b/server/internal/metrics/registry.goindex 7604cd489c..c34eb0b717 100644--- a/server/internal/metrics/registry.go+++ b/server/internal/metrics/registry.go@@ -21,6 +21,7 @@ type RegistryOptions struct {}type Registry struct {+ InboxRead *InboxReadMetricsGatherer prometheus.GathererHTTP *HTTPMetricsBusiness *BusinessMetrics@@ -42,6 +43,9 @@ func NewRegistry(opts RegistryOptions) *Registry {buildInfo.WithLabelValues(defaultLabel(opts.Version, "dev"), defaultLabel(opts.Commit, "unknown")).Set(1)reg.MustRegister(buildInfo)+ inboxRead := NewInboxReadMetrics()+ reg.MustRegister(inboxRead.Collectors()...)+httpMetrics := NewHTTPMetrics()reg.MustRegister(httpMetrics.Collectors()...)@@ -70,6 +74,7 @@ func NewRegistry(opts RegistryOptions) *Registry {}return &Registry{+ InboxRead: inboxRead,Gatherer: reg,HTTP: httpMetrics,Business: businessMetrics,