fix(voice): let board incoming-call requests wait for membership locks (#23353)

## 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 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-12-01 08:28:04 +00:00
1 parent 5abce3b492
commit e67009db3f
2 files changed
+48 -12

No files matched your search

@@ -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<void>(resolve => { release = resolve; });
const held = new Promise<void>(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"});