Skip to content

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

fix(server): retry read-only delivery lookups after a pooled disconnect (#16859)

Devin Foley18e9ca7277f0
diff --git a/server/src/__tests__/execution-workspaces-service.test.ts b/server/src/__tests__/execution-workspaces-service.test.ts
index f070bde146..f59437ed14 100644
--- a/server/src/__tests__/execution-workspaces-service.test.ts
+++ b/server/src/__tests__/execution-workspaces-service.test.ts
@@ -762,6 +762,101 @@ describeEmbeddedPostgres("executionWorkspaceService.getCloseReadiness", () => {
expect(archived?.cleanupEligibleAt).toBeInstanceOf(Date);
}, 20_000);
+ describe("delivery reads after a pooled disconnect", () => {
+ const issueTreeFields = "id,status,completedAt,cancelledAt,updatedAt";
+ const pullRequestProductFields = "id,url,externalId,title,summary,metadata";
+
+ function disconnected() {
+ return new Error("Failed query", {
+ cause: Object.assign(new Error("write CONNECTION_CLOSED"), { code: "CONNECTION_CLOSED" }),
+ });
+ }
+
+ // Fails the first `failuresPerRead` awaits of each delivery read, like a
+ // stale pooled socket, and counts every attempt by projection. Each
+ // attempt builds a fresh query, so recovery must rebuild the read.
+ function flakyDeliveryDb(failuresPerRead: number) {
+ const attempts = new Map<string, number>();
+ const errors: Error[] = [];
+ function failingQuery<T extends object>(query: T, key: string): T {
+ return new Proxy(query, {
+ get(target, prop, receiver) {
+ const value = Reflect.get(target, prop, target);
+ if (typeof value !== "function") return value;
+ if (prop === "then") {
+ return (resolve: (rows: unknown) => unknown, reject: (error: unknown) => unknown) => {
+ const attempt = attempts.get(key) ?? 0;
+ attempts.set(key, attempt + 1);
+ if (attempt >= failuresPerRead) return value.call(target, resolve, reject);
+ const error = disconnected();
+ errors.push(error);
+ return Promise.reject(error).then(resolve, reject);
+ };
+ }
+ return (...args: unknown[]) => {
+ const result = value.apply(target, args);
+ return result === target ? receiver : result;
+ };
+ },
+ });
+ }
+ const flaky = new Proxy(db, {
+ get(target, prop, receiver) {
+ if (prop !== "select") return Reflect.get(target, prop, receiver);
+ return (fields?: Record<string, unknown>) => {
+ const builder = target.select(fields as never);
+ const key = fields ? Object.keys(fields).join(",") : "";
+ if (key !== issueTreeFields && key !== pullRequestProductFields) return builder;
+ return new Proxy(builder, {
+ get(inner, builderProp) {
+ const value = Reflect.get(inner, builderProp, inner);
+ if (builderProp !== "from" || typeof value !== "function") return value;
+ return (...args: unknown[]) => failingQuery(value.apply(inner, args) as object, key);
+ },
+ });
+ };
+ },
+ });
+ return { db: flaky, attempts, errors };
+ }
+
+ function serviceFor(flakyDb: typeof db) {
+ return executionWorkspaceService(flakyDb, {
+ resolvePullRequestDetails: vi.fn(async (companyId, reference) =>
+ pullRequestDetailsByKey.get(`${companyId}:${reference.number}`)
+ ?? { state: "unknown", headRef: null, headSha: null }
+ ),
+ workspaceReaperCooldownDays: 0,
+ });
+ }
+
+ it("rebuilds the issue tree and pull request reads in close readiness", async () => {
+ const seeded = await seedTerminalWorkspace({ mergedPr: true });
+ const expected = await svc.getCloseReadiness(seeded.executionWorkspaceId);
+ const flaky = flakyDeliveryDb(1);
+
+ const readiness = await serviceFor(flaky.db).getCloseReadiness(seeded.executionWorkspaceId);
+
+ expect(readiness).toEqual(expected);
+ expect(readiness?.deliveryState).toBe("merged_via_pr");
+ expect(flaky.errors).toHaveLength(2);
+ expect(flaky.attempts.get(issueTreeFields)).toBe(2);
+ expect(flaky.attempts.get(pullRequestProductFields)).toBe(2);
+ }, 20_000);
+
+ it("propagates a persistent disconnect after three issue tree attempts", async () => {
+ const seeded = await seedTerminalWorkspace({ mergedPr: true });
+ const flaky = flakyDeliveryDb(3);
+
+ const failure = await serviceFor(flaky.db).getCloseReadiness(seeded.executionWorkspaceId)
+ .then(() => null, (error: unknown) => error);
+ expect(flaky.errors).toHaveLength(3);
+ expect(failure).toBe(flaky.errors[2]);
+ expect(flaky.attempts.get(issueTreeFields)).toBe(3);
+ expect(flaky.attempts.get(pullRequestProductFields)).toBeUndefined();
+ }, 20_000);
+ });
+
async function seedAncestryTerminalWorkspace(overrides: { updatedAt?: Date } = {}) {
// Build a worktree whose HEAD equals the base ref, so HEAD is an ancestor
// of the base. This workspace landed by ancestry and carries no tracked
diff --git a/server/src/services/execution-workspaces.ts b/server/src/services/execution-workspaces.ts
index 75616fa2bc..a4b56ce9e0 100644
--- a/server/src/services/execution-workspaces.ts
+++ b/server/src/services/execution-workspaces.ts
@@ -11,6 +11,7 @@ import { instanceSettingsService } from "./instance-settings.js";
import { taskWorkspaceSelectableCondition } from "./task-workspace-selection.js";
import { executionWorkspaceRepositoryService, lockExecutionWorkspaceRootProvenance, preserveExecutionWorkspaceRootProvenance, assertExecutionWorkspaceRootWriteAccess, assertExecutionWorkspaceRootReadAccess, assertIsolatedWorkspaceSourceReadAccess, retainIsolatedWorkspaceSourceAccess, canonicalRepositoryRoot, type IsolatedWorkspaceSourceAccess, type TaskWorkspaceCreationTrustContext } from "./execution-workspace-repositories.js";
import { forbidden } from "../errors.js";
+import { retryIdempotentDatabaseOperation } from "../database-retry.js";
import { taskWorkspaceSelectionSchema, type TaskWorkspaceSelection, type TaskWorkspaceIntent } from "@paperclipai/shared";
import { authorizationService, executionWorkspaceReadSqlCondition, projectReadSqlCondition, issueReadSqlCondition, type AuthorizationActor } from "./authorization.js";
import type { SQL } from "drizzle-orm";
@@ -1672,8 +1673,10 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
let terminalSweepInProgress = false;
async function listWorkspaceIssueTree(workspace: Pick<ExecutionWorkspaceRow, "companyId" | "sourceIssueId">) {
- if (!workspace.sourceIssueId) return [];
- return db
+ const sourceIssueId = workspace.sourceIssueId;
+ if (!sourceIssueId) return [];
+ // A read-only lookup: rebuild it after a transient pooled disconnect.
+ return retryIdempotentDatabaseOperation(() => db
.select({
id: issues.id,
status: issues.status,
@@ -1690,7 +1693,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
SELECT ${issues.id}
FROM ${issues}
WHERE ${issues.companyId} = ${workspace.companyId}
- AND ${issues.id} = ${workspace.sourceIssueId}
+ AND ${issues.id} = ${sourceIssueId}
UNION ALL
SELECT child.id
FROM ${issues} child
@@ -1700,15 +1703,17 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
SELECT id FROM issue_tree
)
`,
- ));
+ )));
}
async function listDeliveryPullRequestProducts(
workspace: Pick<ExecutionWorkspaceRow, "companyId" | "sourceIssueId">,
) {
- if (!workspace.sourceIssueId) return [];
+ const sourceIssueId = workspace.sourceIssueId;
+ if (!sourceIssueId) return [];
- return db
+ // A read-only lookup: rebuild it after a transient pooled disconnect.
+ return retryIdempotentDatabaseOperation(() => db
.select({
id: issueWorkProducts.id,
url: issueWorkProducts.url,
@@ -1721,10 +1726,10 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic
.where(and(
eq(issueWorkProducts.companyId, workspace.companyId),
eq(issueWorkProducts.type, "pull_request"),
- eq(issueWorkProducts.issueId, workspace.sourceIssueId),
+ eq(issueWorkProducts.issueId, sourceIssueId),
))
.orderBy(desc(issueWorkProducts.updatedAt))
- .limit(100);
+ .limit(100));
}
async function assessDelivery(