Skip to content

The open-source app everyone uses to manage agents at work

Retry transient failures in dashboard reads (#14873)

Devin Foley4a999089ef60
diff --git a/doc/DATABASE.md b/doc/DATABASE.md
index 0f7fd97f60..b6258c21ac 100644
--- a/doc/DATABASE.md
+++ b/doc/DATABASE.md
@@ -177,6 +177,13 @@ idempotent actor synchronization operations, not arbitrary transactions. A
persistent outage still fails the request after the bounded retries; each
connection attempt remains subject to the configured database connect timeout.
+The dashboard's company lookup, task counts, pending approval count, and
+monthly spend each retry these connection errors at most twice. Each callback
+is read-only and rebuilds its query for each attempt. A failed read
+does not replay completed reads or the budget workflow. Missing companies,
+authentication errors, and other database errors propagate without retry.
+This does not enable general SQL replay.
+
## Execution identity row locks
Identity initialization, credential acquisition, and steering reconciliation lock
diff --git a/server/src/__tests__/dashboard-disconnect-retry.test.ts b/server/src/__tests__/dashboard-disconnect-retry.test.ts
new file mode 100644
index 0000000000..16ad286261
--- /dev/null
+++ b/server/src/__tests__/dashboard-disconnect-retry.test.ts
@@ -0,0 +1,165 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { getTableName, type SQL } from "drizzle-orm";
+import { PgDialect } from "drizzle-orm/pg-core";
+import type { Db } from "@paperclipai/db";
+import { dashboardService } from "../services/dashboard.js";
+
+const { overview } = vi.hoisted(() => ({ overview: vi.fn() }));
+vi.mock("../services/budgets.js", () => ({
+ budgetService: () => ({ overview }),
+}));
+
+const companyId = "00000000-0000-4000-8000-000000000001";
+const dialect = new PgDialect();
+
+function disconnected(code = "CONNECTION_CLOSED") {
+ const cause = Object.assign(new Error(`write ${code}`), { code });
+ return new Error("Failed query", { cause });
+}
+
+function fixture(failures: Error[] = [], options: {
+ laterError?: Error;
+ missingCompany?: boolean;
+ readFailures?: Record<string, Error[]>;
+} = {}) {
+ const reads: string[] = [];
+ const companyParameters: unknown[][] = [];
+ const parameters = new Map<string, unknown[][]>();
+ let companyAttempts = 0;
+ const select = vi.fn(() => ({
+ from(table: Parameters<typeof getTableName>[0]) {
+ const name = getTableName(table);
+ let condition: SQL | undefined;
+ const query = {
+ where(value: SQL) { condition = value; return query; },
+ groupBy() { return query; },
+ then(resolve: (value: unknown[]) => unknown, reject: (error: unknown) => unknown) {
+ return Promise.resolve().then(() => {
+ reads.push(name);
+ const attempts = parameters.get(name) ?? [];
+ const failure = options.readFailures?.[name]?.[attempts.length];
+ attempts.push(dialect.sqlToQuery(condition!).params);
+ parameters.set(name, attempts);
+ if (failure) throw failure;
+ if (name === "companies") {
+ companyParameters.push(dialect.sqlToQuery(condition!).params);
+ const failure = failures[companyAttempts++];
+ if (failure) throw failure;
+ return options.missingCompany ? [] : [{ id: companyId, budgetMonthlyCents: 10_000 }];
+ }
+ if (options.laterError) throw options.laterError;
+ if (name === "agents") return [{ status: "idle", count: 2 }];
+ if (name === "issues") return [{ status: "in_progress", count: 1 }];
+ if (name === "approvals") return [{ count: 3 }];
+ if (name === "cost_events") return [{ monthSpend: 125 }];
+ throw new Error(`Unexpected dashboard read: ${name}`);
+ }).then(resolve, reject);
+ },
+ };
+ return query;
+ },
+ }));
+ const execute = vi.fn().mockResolvedValue([]);
+ const db = { select, execute } as unknown as Db;
+ return { service: dashboardService(db), reads, companyParameters, parameters, select, execute };
+}
+
+beforeEach(() => {
+ overview.mockReset().mockResolvedValue({
+ activeIncidents: [], pendingApprovalCount: 0, pausedAgentCount: 0, pausedProjectCount: 0,
+ });
+});
+
+describe("dashboard read connection recovery", () => {
+ it.each(["CONNECT_TIMEOUT", "CONNECTION_CLOSED", "CONNECTION_ENDED", "CONNECTION_DESTROYED"])(
+ "rebuilds the scoped company read after a nested %s cause", async (code) => {
+ const test = fixture([disconnected(code)]);
+ await expect(test.service.summary(companyId)).resolves.toMatchObject({
+ companyId,
+ agents: { active: 2 },
+ tasks: { inProgress: 1 },
+ costs: { monthSpendCents: 125, monthBudgetCents: 10_000 },
+ pendingApprovals: 3,
+ });
+ expect(test.companyParameters).toEqual([[companyId], [companyId]]);
+ expect(test.reads).toEqual(["companies", "companies", "agents", "issues", "approvals", "cost_events"]);
+ expect(test.execute).toHaveBeenCalledTimes(1);
+ expect(overview).toHaveBeenCalledExactlyOnceWith(companyId);
+ },
+ );
+
+ it("can replace two stale pooled connections within the existing retry budget", async () => {
+ const test = fixture([disconnected(), disconnected()]);
+ await expect(test.service.summary(companyId)).resolves.toMatchObject({ companyId });
+ expect(test.companyParameters).toEqual([[companyId], [companyId], [companyId]]);
+ expect(overview).toHaveBeenCalledTimes(1);
+ });
+
+ it("propagates the final failure after three attempts without starting later work", async () => {
+ const failures = [disconnected(), disconnected(), disconnected()];
+ const test = fixture(failures);
+ await expect(test.service.summary(companyId)).rejects.toBe(failures[2]);
+ expect(test.reads).toEqual(["companies", "companies", "companies"]);
+ expect(test.execute).not.toHaveBeenCalled();
+ expect(overview).not.toHaveBeenCalled();
+ });
+
+ it.each([new Error("write CONNECTION_CLOSED"), disconnected("28P01"), disconnected("23505")])(
+ "does not retry message-only, authentication, or constraint errors", async (error) => {
+ const test = fixture([error]);
+ await expect(test.service.summary(companyId)).rejects.toBe(error);
+ expect(test.reads).toEqual(["companies"]);
+ expect(test.execute).not.toHaveBeenCalled();
+ expect(overview).not.toHaveBeenCalled();
+ },
+ );
+
+ it("retains the missing-company error without retrying", async () => {
+ const test = fixture([], { missingCompany: true });
+ await expect(test.service.summary(companyId)).rejects.toMatchObject({ status: 404 });
+ expect(test.reads).toEqual(["companies"]);
+ expect(overview).not.toHaveBeenCalled();
+ });
+
+ it("does not replay later summary reads when they lose a connection", async () => {
+ const error = disconnected();
+ const test = fixture([], { laterError: error });
+ await expect(test.service.summary(companyId)).rejects.toBe(error);
+ expect(test.reads).toEqual(["companies", "agents"]);
+ expect(overview).not.toHaveBeenCalled();
+ });
+
+ it("does not replay the budget workflow when it loses a connection", async () => {
+ const error = disconnected();
+ overview.mockRejectedValue(error);
+ const test = fixture();
+ await expect(test.service.summary(companyId)).rejects.toBe(error);
+ expect(test.companyParameters).toEqual([[companyId]]);
+ expect(overview).toHaveBeenCalledTimes(1);
+ });
+
+ const tables = ["companies", "agents", "issues", "approvals", "cost_events"];
+ it.each(["issues", "approvals", "cost_events"])("retries only the failed %s read", async (table) => {
+ const test = fixture([], { readFailures: { [table]: [disconnected()] } });
+ await expect(test.service.summary(companyId)).resolves.toMatchObject({ companyId });
+ const prefix = tables.slice(0, tables.indexOf(table) + 1);
+ const suffix = tables.slice(tables.indexOf(table) + 1);
+ expect(test.reads).toEqual([...prefix, table, ...suffix]);
+ const attempts = test.parameters.get(table)!;
+ expect(attempts).toHaveLength(2);
+ expect(attempts[0]).toContain(companyId);
+ expect(attempts[1]).toEqual(attempts[0]);
+ expect(test.execute).toHaveBeenCalledTimes(1);
+ expect(overview).toHaveBeenCalledExactlyOnceWith(companyId);
+ });
+
+ it.each(["issues", "approvals", "cost_events"])("stops after the %s read exhausts its budget", async (table) => {
+ const failures = [disconnected(), disconnected(), disconnected()];
+ const test = fixture([], { readFailures: { [table]: failures } });
+ await expect(test.service.summary(companyId)).rejects.toBe(failures[2]);
+ const prefix = tables.slice(0, tables.indexOf(table));
+ expect(test.reads).toEqual([...prefix, table, table, table]);
+ expect(test.execute).not.toHaveBeenCalled();
+ expect(overview).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/src/database-retry.ts b/server/src/database-retry.ts
new file mode 100644
index 0000000000..d56429f714
--- /dev/null
+++ b/server/src/database-retry.ts
@@ -0,0 +1,36 @@
+/** postgres.js transient connection codes, including wrapped Drizzle errors. */
+const transientDbConnectionCodes = new Set([
+ "CONNECT_TIMEOUT",
+ "CONNECTION_CLOSED",
+ "CONNECTION_ENDED",
+ "CONNECTION_DESTROYED",
+]);
+
+export function isTransientDbConnectionError(error: unknown): boolean {
+ for (let current: unknown = error; current instanceof Error; current = current.cause) {
+ const code = (current as { code?: unknown }).code;
+ if (typeof code === "string" && transientDbConnectionCodes.has(code)) return true;
+ }
+ return false;
+}
+
+/**
+ * Retry only an explicitly idempotent operation, such as a known read-only
+ * lookup or receipt-protected synchronization. Neither a SQL prefix nor a
+ * connection error message proves replay safety: a disconnected write may
+ * already have committed. Callers own this proof for the entire callback.
+ *
+ * Two replays allow for a pool-wide recycle where the first replay draws
+ * another stale socket. The pauses give the driver time to replace them.
+ * Persistent failures still propagate after three total attempts.
+ */
+export async function retryIdempotentDatabaseOperation<T>(run: () => Promise<T>): Promise<T> {
+ for (let attempt = 0; ; attempt += 1) {
+ try {
+ return await run();
+ } catch (error) {
+ if (attempt >= 2 || !isTransientDbConnectionError(error)) throw error;
+ await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1)));
+ }
+ }
+}
diff --git a/server/src/middleware/auth.ts b/server/src/middleware/auth.ts
index 76a534daff..8bc814f44f 100644
--- a/server/src/middleware/auth.ts
+++ b/server/src/middleware/auth.ts
@@ -27,6 +27,12 @@ import type { BetterAuthSessionResult } from "../auth/better-auth.js";
import { logger } from "./logger.js";
import { captureRunIdentity } from "../services/run-identity.js";
import { boardAuthService } from "../services/board-auth.js";
+import { retryIdempotentDatabaseOperation } from "../database-retry.js";
+
+export {
+ isTransientDbConnectionError,
+ retryIdempotentDatabaseOperation as retryOnTransientDbConnectionError,
+} from "../database-retry.js";
const CLOUD_TENANT_WRITE_DEBOUNCE_MS = 5_000;
const CLOUD_TENANT_WRITE_DEBOUNCE_MAX = 1_000;
@@ -545,53 +551,6 @@ export function cloudActorHeaderSourceFromHeaders(
};
}
-/**
- * postgres.js codes for connection establishment timing out or for a
- * connection the server side closed out from under an in-flight query —
- * a pooled Postgres endpoint recycling or suspending
- * (observed 2026-09-03 with a managed pooler closing the socket mid-INSERT).
- * The driver reconnects transparently on the next query; only the statement
- * that was on the wire is lost.
- */
-const transientDbConnectionCodes = new Set([
- "CONNECT_TIMEOUT",
- "CONNECTION_CLOSED",
- "CONNECTION_ENDED",
- "CONNECTION_DESTROYED",
-]);
-
-/**
- * True when the error chain (drizzle wraps the driver error as `cause`)
- * carries a postgres.js transient connection code. Exported for tests.
- */
-export function isTransientDbConnectionError(error: unknown): boolean {
- for (let current: unknown = error; current instanceof Error; current = current.cause) {
- const code = (current as { code?: unknown }).code;
- if (typeof code === "string" && transientDbConnectionCodes.has(code)) return true;
- }
- return false;
-}
-
-/**
- * Runs `run` and retries it up to twice when it fails on a transient
- * connection error. Two replays, not one: when a pooled endpoint
- * suspends or recycles, EVERY pooled socket is dead at once, so the first
- * replay can draw another stale socket from the pool and fail identically
- * (observed 2026-09-12: retried actor resolution still surfacing
- * CONNECTION_CLOSED). The short pause gives the driver time to notice and
- * re-dial. Callers must pass an idempotent operation. Exported for tests.
- */
-export async function retryOnTransientDbConnectionError<T>(run: () => Promise<T>): Promise<T> {
- for (let attempt = 0; ; attempt += 1) {
- try {
- return await run();
- } catch (error) {
- if (attempt >= 2 || !isTransientDbConnectionError(error)) throw error;
- await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1)));
- }
- }
-}
-
/**
* Trusted-header actor resolution with bounded transient-connection retries.
* The tenant sync inside is idempotent end to end — every write is an
@@ -603,7 +562,7 @@ export async function resolveCloudTenantActor(
db: Db,
req: CloudActorHeaderSource,
): Promise<Express.Request["actor"] | null> {
- return retryOnTransientDbConnectionError(() => resolveCloudTenantActorOnce(db, req));
+ return retryIdempotentDatabaseOperation(() => resolveCloudTenantActorOnce(db, req));
}
async function resolveCloudTenantActorOnce(
diff --git a/server/src/services/dashboard.ts b/server/src/services/dashboard.ts
index b9bd598ea3..f4d7f7e4ed 100644
--- a/server/src/services/dashboard.ts
+++ b/server/src/services/dashboard.ts
@@ -4,6 +4,7 @@ import { agents, approvals, companies, costEvents, heartbeatRuns, issues } from
import { notFound } from "../errors.js";
import { budgetService } from "./budgets.js";
import { executionIssueCondition } from "./issue-visibility.js";
+import { retryIdempotentDatabaseOperation } from "../database-retry.js";
const DASHBOARD_RUN_ACTIVITY_DAYS = 14;
@@ -27,11 +28,13 @@ export function dashboardService(db: Db) {
const budgets = budgetService(db);
return {
summary: async (companyId: string) => {
- const company = await db
+ // This lookup only reads the company row. Rebuild it after a transient
+ // disconnect; do not replay the later summary or budget workflows.
+ const company = await retryIdempotentDatabaseOperation(() => db
.select()
.from(companies)
.where(eq(companies.id, companyId))
- .then((rows) => rows[0] ?? null);
+ .then((rows) => rows[0] ?? null));
if (!company) throw notFound("Company not found");
@@ -41,17 +44,17 @@ export function dashboardService(db: Db) {
.where(eq(agents.companyId, companyId))
.groupBy(agents.status);
- const taskRows = await db
+ const taskRows = await retryIdempotentDatabaseOperation(() => db
.select({ status: issues.status, count: sql<number>`count(*)` })
.from(issues)
.where(and(eq(issues.companyId, companyId), executionIssueCondition()))
- .groupBy(issues.status);
+ .groupBy(issues.status));
- const pendingApprovals = await db
+ const pendingApprovals = await retryIdempotentDatabaseOperation(() => db
.select({ count: sql<number>`count(*)` })
.from(approvals)
.where(and(eq(approvals.companyId, companyId), eq(approvals.status, "pending")))
- .then((rows) => Number(rows[0]?.count ?? 0));
+ .then((rows) => Number(rows[0]?.count ?? 0)));
const agentCounts: Record<string, number> = {
active: 0,
@@ -84,7 +87,7 @@ export function dashboardService(db: Db) {
const monthStart = getUtcMonthStart(now);
const runActivityDays = getRecentUtcDateKeys(now, DASHBOARD_RUN_ACTIVITY_DAYS);
const runActivityStart = new Date(`${runActivityDays[0]}T00:00:00.000Z`);
- const [{ monthSpend }] = await db
+ const [{ monthSpend }] = await retryIdempotentDatabaseOperation(() => db
.select({
monthSpend: sql<number>`coalesce(sum(${costEvents.costCents}), 0)::double precision`,
})
@@ -94,7 +97,7 @@ export function dashboardService(db: Db) {
eq(costEvents.companyId, companyId),
gte(costEvents.occurredAt, monthStart),
),
- );
+ ));
const monthSpendCents = Number(monthSpend);
// Per-day run breakdown. A run is "recovered" when its retry chain later