From e67009db3f7381989f5bef6c09f04a93d322ec8d Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Tue, 1 Dec 2026 08:28:04 +0000 Subject: [PATCH] fix(voice): let board incoming-call requests wait for membership locks (#23353) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Voice connections (Speko) let a board user approve incoming phone calls and see call history in the board UI > - The incoming-call panel polls `GET /companies/:companyId/voice-phone/:endpointId/incoming` every two seconds > - The inbound voice service checks the caller's company membership with a `FOR SHARE NOWAIT` lock on every request, including these board requests > - When another transaction holds that membership row, the poll fails with Postgres error `55P03` and the error handler returns a 500 and reports it to Sentry > - This pull request makes the board routes wait for the row lock, like the other board voice routes do, and keeps `NOWAIT` for provider callbacks > - The benefit is that ordinary lock contention no longer causes 500 responses or Sentry noise for board users ## Linked Issues or Issue Description No public issue exists. This is the problem description. **What happened?** On staging, board requests to the voice incoming-call routes failed with `Failed query: select "id" from "company_memberships" ... for share nowait`, caused by `PostgresError: could not obtain lock on row in relation "company_memberships"` (`55P03`). The culprit frame is `authorizeCaller` in `voice-session-store.ts`. Sentry recorded 32 events in one day, all on staging. **Expected behavior** A board request waits for a short row lock that another transaction holds, and then returns its normal result. A concurrent membership change must not cause a 500. **Steps to reproduce** 1. Open a transaction that locks the caller's `company_memberships` row (`FOR NO KEY UPDATE`). 2. While the lock is held, call the inbound voice `list` or `decide` service method for that caller. 3. The call fails immediately with `55P03`. **Relevant logs or output** `Error: Failed query: select "id" from "company_memberships" where (... "membership_role" is distinct from 'viewer') for share nowait` caused by `PostgresError: could not obtain lock on row in relation "company_memberships"`. ## What Changed - `server/src/services/voice/voice-inbound-service.ts`: add a second session store, `boardStore`, without `nonblockingAuthority`. The board routes (`configuration`/`saveConfiguration` through `manager`, `list`, `history`, and `decide`) use it. The provider callback and tool paths (`lifecycle`, `pendingTool`, `authorizeGuest`) keep the `NOWAIT` store. - `server/src/__tests__/voice-session-store.integration.test.ts`: add a regression test. It holds the caller's membership row lock, calls `list` and `decide`, checks that both wait on the lock, releases the lock, and checks that both succeed. ## Verification - Red: with the service change stashed, the new test failed. Both requests rejected with `55P03` (`for share nowait`), which is the same error as in Sentry. - Green: `cd server && npx vitest run src/__tests__/voice-session-store.integration.test.ts` passes all 135 tests, the new test included. - `cd server && pnpm typecheck` passes. ## Risks - Low risk. Board voice requests can now wait for a row lock instead of failing at once. This matches `voice-session-service`, which already uses ordinary share locks for board routes. Each board transaction takes the membership lock as its first statement, so this change adds no new lock-order cycle. - Provider callbacks keep their fail-fast behavior. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), with tool use and code execution in an agent harness. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../voice-session-store.integration.test.ts | 34 ++++++++++++++++++- .../services/voice/voice-inbound-service.ts | 26 ++++++++------ 2 files changed, 48 insertions(+), 12 deletions(-) diff --git a/server/src/__tests__/voice-session-store.integration.test.ts b/server/src/__tests__/voice-session-store.integration.test.ts index 2f75d13e446..527eb64a4fa 100644 --- a/server/src/__tests__/voice-session-store.integration.test.ts +++ b/server/src/__tests__/voice-session-store.integration.test.ts @@ -22,7 +22,7 @@ import { documentService } from "../services/documents.js"; import { applyConnectorSkills, prepareConnectorSkillDelivery, resolveConnectorAssignments } from "../services/connector-runtime.js"; import { VOICE_RESULT_NOTIFICATION } from "@paperclipai/shared"; import { createHash, createHmac, randomUUID } from "node:crypto"; -import { eq } from "drizzle-orm"; +import { and, eq, sql } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { applyPendingMigrations, chatActions, instanceUserRoles, principalPermissionGrants, environments, chatVoiceInboundCalls, chatVoicePhoneLines, chatVoiceReports, heartbeatRuns, toolCatalogEntries, toolProfileBindings, chatVoiceCallbacks, agentWakeupRequests, issueThreadInteractions, issueQuestionResponseDeliveries, issueComments, agents, chatConversations, chatDeliveries, chatEndpoints, chatPublications, chatVoiceReplies, chatVoiceSessions, chatVoiceToolCalls, companies, companyMemberships, companySecrets, connectionGrants, connectionGrantMembers, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, issues, toolApplications, toolConnections, toolConnectionInstalls } from "@paperclipai/db"; import { configureSpekoSessionTools } from "../services/voice/speko-tool-setup.js"; @@ -1845,6 +1845,38 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu expect(history).toHaveLength(1); expect(history[0]).toMatchObject({id: call.id, state: "ended"}); expect(JSON.stringify(history)).not.toContain("approvalCode"); expect(JSON.stringify(history)).not.toContain("toolToken"); }); + it("waits for a concurrent membership lock instead of failing board incoming-call requests", async () => { + // The board polls the incoming-call list every two seconds. + // A NOWAIT share lock failed that poll with 55P03 whenever another + // transaction held the caller's membership row. + const f = await inboundFixture(); + let release!: () => void, locked!: () => void; + const released = new Promise(resolve => { release = resolve; }); + const held = new Promise(resolve => { locked = resolve; }); + const holder = db.transaction(async tx => { + await tx.select({ id: companyMemberships.id }).from(companyMemberships).where(and(eq(companyMemberships.companyId, f.companyId), + eq(companyMemberships.principalId, f.callerId))).for("no key update"); + locked(); await released; + }); + await held; + const requests = Promise.allSettled([ + f.service.inbound.list(f.companyId, f.endpointId, f.input.caller), + f.service.inbound.decide(f.companyId, f.endpointId, f.call.id, f.input.caller, { approve: false, approvalCode: f.call.approvalCode }), + ]); + let settledUnderLock: unknown; + void requests.then(outcomes => { settledUnderLock = outcomes; }); + try { + await vi.waitFor(async () => { + expect(settledUnderLock).toBeUndefined(); + const [waiting] = await db.execute(sql`select count(*)::int as count from pg_stat_activity + where datname = current_database() and wait_event_type = 'Lock'`) as unknown as Array<{ count: number }>; + expect(waiting.count).toBe(2); + }, { timeout: 5000 }); + } finally { release(); await holder; } + const [list, decision] = await requests; + expect(list).toMatchObject({ status: "fulfilled" }); + expect(decision).toMatchObject({ status: "fulfilled", value: { id: f.call.id, state: "denied" } }); + }); it("uses task-comment follow-ups for guest clarifications and rejects protected question waits", async () => { const f = await inboundFixture(true); await f.tool("submit_request", {text: "Draft a public inquiry"}); diff --git a/server/src/services/voice/voice-inbound-service.ts b/server/src/services/voice/voice-inbound-service.ts index b270e420caf..4c958fdb84f 100644 --- a/server/src/services/voice/voice-inbound-service.ts +++ b/server/src/services/voice/voice-inbound-service.ts @@ -34,7 +34,11 @@ export function voiceInboundService(db: Db, options: { voicePrompt: string; lowTrustVoicePrompt: string; }) { - const store = voiceSessionStore(db, {...options, nonblockingAuthority: true}), provider = options.provider ?? createSpekoProvider; + // Provider callbacks answer a live call, so their authority checks fail fast + // instead of queueing behind a concurrent change. Board requests (including + // the two-second incoming-call poll) wait like other board routes; NOWAIT + // there turned ordinary membership-row contention into a 500. + const store = voiceSessionStore(db, {...options, nonblockingAuthority: true}), boardStore = voiceSessionStore(db, options), provider = options.provider ?? createSpekoProvider; const issueSvc = issueService(db), environments = environmentService(db); async function sandboxChoices(companyId: string) { const choices = await environments.list({driver: "sandbox", status: "active"}); @@ -51,7 +55,7 @@ export function voiceInboundService(db: Db, options: { async function enabled() { if (!(await instanceSettingsService(db).getExperimental()).enableChatConnectors) throw forbidden("Voice connections are disabled"); } async function manager(companyId: string, caller: VoiceCaller, transaction?: VoiceTransaction) { const check = async (tx: VoiceTransaction) => { - await store.authorizeCaller(tx, companyId, caller); + await boardStore.authorizeCaller(tx, companyId, caller); if (caller.authority === "local_board" || caller.authority === "instance_admin" || (await authorizationService(tx).decidePrincipalGrant({companyId, principalType: "user", principalId: caller.id, permissionKey: "tools:manage_connections", action: "tools:manage_connections"})).allowed) return; throw forbidden("Missing permission: tools:manage_connections"); }; @@ -71,7 +75,7 @@ export function voiceInboundService(db: Db, options: { await assertEnvironmentSelectionForCompany(environments, companyId, input.lowTrustEnvironmentId, {allowedDrivers: ["sandbox"]}); if (!(await sandboxChoices(companyId)).some(e => e.id === input.lowTrustEnvironmentId)) throw forbidden("Choose a sandbox available to this company"); } - const context = await db.transaction(tx => store.endpointContext(tx, companyId, endpointId)); + const context = await db.transaction(tx => boardStore.endpointContext(tx, companyId, endpointId)); const credentials = await options.credentials(row, context.fingerprint), client = provider(credentials.apiKey); let numbers = await client.listPhoneNumbers(), number = numbers.find(n => n.id === input.numberId && n.organizationId === row.providerAccountId); if (!number || number.agentId && number.agentId !== credentials.agentId || number.routeToBrokerId || number.suspendedAt || number.direction === "outbound") throw conflict("Choose an available incoming number in this Speko workspace"); @@ -84,7 +88,7 @@ export function voiceInboundService(db: Db, options: { if (!number) throw conflict("Speko could not confirm this phone number"); await db.transaction(async tx => { await manager(companyId, caller, tx); - const current = await store.endpointContext(tx, companyId, endpointId); + const current = await boardStore.endpointContext(tx, companyId, endpointId); if (current.fingerprint !== context.fingerprint || current.generation !== context.generation) throw conflict("Voice configuration changed. Refresh before saving."); await tx.insert(chatVoicePhoneLines).values({companyId, endpointId, providerNumberId: number!.id, phoneNumber: number!.e164, enabled: input.enabled, guestIntake: input.guestIntake ?? false, lowTrustEnvironmentId: input.lowTrustEnvironmentId ?? null}).onConflictDoUpdate({target: chatVoicePhoneLines.endpointId, set: {providerNumberId: number!.id, phoneNumber: number!.e164, enabled: input.enabled, guestIntake: input.guestIntake ?? false, ...(input.lowTrustEnvironmentId !== undefined ? {lowTrustEnvironmentId: input.lowTrustEnvironmentId} : {}), updatedAt: new Date()}}); await tx.insert(activityLog).values({companyId, actorType: "user", actorId: caller.id, action: "voice.phone_line.configured", entityType: "chat_endpoint", entityId: endpointId, details: {enabled: input.enabled, guestIntake: input.guestIntake ?? false}}); @@ -212,16 +216,16 @@ export function voiceInboundService(db: Db, options: { } async function list(companyId: string, endpointId: string, caller: VoiceCaller) { await enabled(); - await db.transaction(async tx => { await store.authorizeCaller(tx, companyId, caller); const context = await store.endpointContext(tx, companyId, endpointId); await store.authorizeConnection(tx, context, caller); }); + await db.transaction(async tx => { await boardStore.authorizeCaller(tx, companyId, caller); const context = await boardStore.endpointContext(tx, companyId, endpointId); await boardStore.authorizeConnection(tx, context, caller); }); const rows = await db.select().from(chatVoiceInboundCalls).where(and(eq(chatVoiceInboundCalls.companyId, companyId), eq(chatVoiceInboundCalls.endpointId, endpointId), inArray(chatVoiceInboundCalls.state, ["guest_intake", "awaiting_approval", "approving"]))).orderBy(desc(chatVoiceInboundCalls.createdAt)).limit(20); return rows.filter(row => !row.approvedByUserId || row.approvedByUserId === caller.id).map(projection); } async function history(companyId: string, endpointId: string, caller: VoiceCaller) { await enabled(); return db.transaction(async tx => { - await store.authorizeCaller(tx, companyId, caller); - const context = await store.endpointContext(tx, companyId, endpointId); - await store.authorizeConnection(tx, context, caller); + await boardStore.authorizeCaller(tx, companyId, caller); + const context = await boardStore.endpointContext(tx, companyId, endpointId); + await boardStore.authorizeConnection(tx, context, caller); const rows = await tx.select({id: chatVoiceInboundCalls.id, state: chatVoiceInboundCalls.state, createdAt: chatVoiceInboundCalls.createdAt, updatedAt: chatVoiceInboundCalls.updatedAt}).from(chatVoiceInboundCalls).where(and(eq(chatVoiceInboundCalls.companyId, companyId), eq(chatVoiceInboundCalls.endpointId, endpointId), isNull(chatVoiceInboundCalls.sessionId), inArray(chatVoiceInboundCalls.state, ["denied", "expired", "ended"]))).orderBy(desc(chatVoiceInboundCalls.createdAt)).limit(20); return rows.map(row => ({...row, state: row.state as "denied" | "expired" | "ended", createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString()})); }); @@ -229,8 +233,8 @@ export function voiceInboundService(db: Db, options: { async function decide(companyId: string, endpointId: string, callId: string, caller: VoiceCaller, input: {approve: boolean; approvalCode: string; issueId?: string}) { await enabled(); let admission = await db.transaction(async tx => { - await store.authorizeCaller(tx, companyId, caller); - const context = await store.endpointContext(tx, companyId, endpointId); await store.authorizeConnection(tx, context, caller); + await boardStore.authorizeCaller(tx, companyId, caller); + const context = await boardStore.endpointContext(tx, companyId, endpointId); await boardStore.authorizeConnection(tx, context, caller); const [row] = await tx.select().from(chatVoiceInboundCalls).where(and(eq(chatVoiceInboundCalls.id, callId), eq(chatVoiceInboundCalls.companyId, companyId), eq(chatVoiceInboundCalls.endpointId, endpointId))).for("update"); if (!row) throw notFound("Incoming call not found"); if (row.approvalCode !== input.approvalCode) throw forbidden("Confirm the approval code spoken on this live call"); @@ -239,7 +243,7 @@ export function voiceInboundService(db: Db, options: { if (row.state === "approved") { if (row.requestedIssueId !== (input.issueId ?? row.intakeIssueId ?? null)) throw conflict("This call is already bound to another task"); return row; } if (!["guest_intake", "awaiting_approval", "approving"].includes(row.state)) throw conflict("This incoming call is no longer waiting for approval"); if (row.state === "approving" && (!input.approve || row.requestedIssueId !== (input.issueId ?? row.intakeIssueId ?? null))) throw conflict("This call is already being approved"); - if (input.issueId) await store.authorizeTask(tx, companyId, input.issueId, caller); + if (input.issueId) await boardStore.authorizeTask(tx, companyId, input.issueId, caller); await notifyVoiceInbound(tx, { kind: "admission", id: row.id }); const [changed] = await tx.update(chatVoiceInboundCalls).set({state: input.approve ? "approving" : row.state === "guest_intake" ? "ended" : "denied", approvedByUserId: caller.id, callerAuthority: caller.authority, requestedIssueId: input.issueId ?? row.intakeIssueId ?? null, updatedAt: new Date()}).where(eq(chatVoiceInboundCalls.id, row.id)).returning(); await tx.insert(activityLog).values({companyId, actorType: "user", actorId: caller.id, action: input.approve ? "voice.inbound.approval_started" : row.state === "guest_intake" ? "voice.low_trust_call.ended" : "voice.inbound.denied", entityType: "voice_inbound_call", entityId: row.id});