From b1bb59e286e2a9829c1abdaa182b9ab21ea5a3c1 Mon Sep 17 00:00:00 2001 From: Dotta Date: Mon, 26 Oct 2026 18:11:01 -0500 Subject: [PATCH 1/2] fix(server): scope pending tool review expiry to company changes Require company hints at existing review-write boundaries, refresh saved company deadlines, and drain bounded due batches without scanning unrelated companies. Co-Authored-By: Paperclip --- doc/idle-tool-review-expiry.md | 18 ++- .../server-startup-feedback-export.test.ts | 2 + .../__tests__/tool-gateway-service.test.ts | 107 +++++++++++++++++- server/src/services/company-deletion.ts | 2 + .../src/services/issue-thread-interactions.ts | 2 +- .../tool-access/activity/review-queue.ts | 2 +- server/src/services/tool-action-review.ts | 2 +- server/src/services/tool-gateway.ts | 18 +-- .../src/services/tool-review-expiry-work.ts | 23 ++-- server/src/services/tool-review-expiry.ts | 74 +++++++----- .../tool-review-work-notifications.ts | 8 +- 11 files changed, 196 insertions(+), 62 deletions(-) diff --git a/doc/idle-tool-review-expiry.md b/doc/idle-tool-review-expiry.md index f189baf70f8..25cf4df743d 100644 --- a/doc/idle-tool-review-expiry.md +++ b/doc/idle-tool-review-expiry.md @@ -9,7 +9,7 @@ or change the one-hour review policy. The tool gateway owns request signing and authorization. `toolReviewExpiryService` owns pending-expiry selection and settlement. `registerToolReviewExpiryWork` -supplies those operations to the existing shared deadline worker. Startup wires +supplies company-scoped operations to the existing shared scoped deadline worker. Startup wires that contract without interpreting tool or provider behavior. The supported writers are: @@ -27,9 +27,15 @@ The supported writers are: - Administrative interaction resolution signals in the caller-owned transaction before resolving linked requests. Review-queue invalidation signals before invalidating unreadable or unsigned requests. +- Company deletion signals its company before removing saved review obligations. - The expiry worker signals before its own settlement. A compare-and-set against pending status and the observed update time protects concurrent resolution. +Every notification requires the company ID. Normal commits reload only that +company's saved minimum expiry; due cleanup selects only that company. Startup +reconstructs all saved company deadlines once. A company with only unsigned +null-expiry requests has no deadline. + Only the SQL mutation is wrapped. Signing, provider requests, telemetry, and interaction publication are not moved inside an enclosing recovery transaction. The database signal layer handles nested savepoints, outer commit/rollback, and @@ -59,7 +65,10 @@ worker active. The concurrent index migration uses the existing top-level executor and is safe to apply again after interruption. The shared coordinator coalesces changes and preserves a write arriving during -reconciliation. It retries failed or unfinished reconciliation after 30 seconds. +reconciliation. Each due pass expires at most 100 rows for one company; companies +rotate between passes until the backlog drains. Failed scopes retry independently +with exponential backoff from 30 seconds to five minutes. Other companies retain +their own deadlines. New writes do not erase a failed sweep's backoff. Once reconciliation completes with no deadline, it has no recurring SQL. Drain retains first writes without passive database scans; resume processes overdue reviews. Startup reconstructs persisted deadlines. Shutdown stops subscription @@ -70,7 +79,10 @@ With heartbeat scheduling disabled, startup-only expiry remains as before. ## Verification scope -Real PostgreSQL tests exercise normal gateway signing and human decisions, +Real PostgreSQL tests record SQL to prove signing, human decisions, and due expiry +remain company-scoped. They also verify five-second and earlier replacement +deadlines, company deletion, and bounded multi-pass draining. Existing cases cover +normal gateway signing and human decisions, configured idle and terminal history, outer commit/rollback, startup/restart, drain/resume, concurrent producer/read, unsigned rows, multi-page expiry, and injected invocation-write failure with atomic rollback and retry. Existing diff --git a/server/src/__tests__/server-startup-feedback-export.test.ts b/server/src/__tests__/server-startup-feedback-export.test.ts index fc66f95154c..7206ebfbdcf 100644 --- a/server/src/__tests__/server-startup-feedback-export.test.ts +++ b/server/src/__tests__/server-startup-feedback-export.test.ts @@ -69,6 +69,8 @@ const { sweepActionReviews: vi.fn(async () => ({ scanned: 0 })), sweepExpiredActionReviews: vi.fn(async () => ({ scanned: 0 })), nextActionReviewExpiryAt: vi.fn(async () => null), + actionReviewExpiryDeadlines: vi.fn(async () => []), + sweepExpiredActionReviewsForCompany: vi.fn(async () => ({ scanned: 0 })), cleanupExpiredSessions: vi.fn(async () => ({ deletedCount: 0 })), nextCredentialExpiryAt: vi.fn(async () => null), }, diff --git a/server/src/__tests__/tool-gateway-service.test.ts b/server/src/__tests__/tool-gateway-service.test.ts index 7d6023926ef..1dee432b5d1 100644 --- a/server/src/__tests__/tool-gateway-service.test.ts +++ b/server/src/__tests__/tool-gateway-service.test.ts @@ -1,3 +1,4 @@ +import { deleteCompany } from "../services/company-deletion.js"; import { subscribeDeliveryWork } from "../services/delivery-work-notifications.js"; import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js"; import { randomUUID } from "node:crypto"; @@ -293,12 +294,15 @@ describeEmbeddedPostgres("tool gateway service", () => { expect(selects).not.toHaveBeenCalled(); expect(executes).not.toHaveBeenCalled(); selects.mockRestore(); executes.mockRestore(); } - async function request(service = gateway, source = db) { - const session = await service.createSession(runSessionInput(fixture.company, fixture.agent, fixture.run)); + async function request(service = gateway, source = db, context = fixture) { + const before = new Set((await source.select({ id: toolActionRequests.id }).from(toolActionRequests) + .where(eq(toolActionRequests.companyId, context.company.id))).map(row => row.id)); + const session = await service.createSession(runSessionInput(context.company, context.agent, context.run)); const noteId = randomUUID(); await expect(service.executeTool({ sessionToken: session.token, tool: "mcp-remote-fixture:update_note", parameters: { noteId, body: "Awaiting a human" } })).rejects.toMatchObject({ reasonCode: "approval_required" }); - const rows = await source.select().from(toolActionRequests).where(eq(toolActionRequests.companyId, fixture.company.id)); + const rows = (await source.select().from(toolActionRequests).where(eq(toolActionRequests.companyId, context.company.id))) + .filter(row => !before.has(row.id)); expect(rows).toHaveLength(1); return rows[0]; } @@ -309,6 +313,92 @@ describeEmbeddedPostgres("tool gateway service", () => { expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toEqual([]); } + async function requestWithExpiry(expiresAt: Date, context = fixture) { + return db.transaction(async tx => { + const source = tx as unknown as typeof db; + const pending = await request(createTestToolGatewayService(source), source, context); + const [saved] = await tx.update(toolActionRequests).set({ expiresAt }) + .where(eq(toolActionRequests.id, pending.id)).returning(); + return saved; + }); + } + + it("keeps signing and human resolution reads scoped to their company", async () => { + const other = await createRunFixture(db); + await db.insert(toolPolicies).values(reviewNotePolicyRow(other.company)); + const foreign = await request(gateway, db, other); + await start(); await settle(1); + const reads: Array<{ query: string; params: unknown[] }> = []; + const debug = db.$client.options.debug; + db.$client.options.debug = (_id, query, params) => { + if (/^select/i.test(query) && query.includes('"tool_action_requests"') && + (query.includes('min(') || query.includes('"expires_at" <='))) reads.push({ query, params: [...params] }); + }; + try { + for (let index = 0; index < 3; index++) { + const pending = await request(); await settle(1000); + await commitToolActionReview(db, { companyId: fixture.company.id, actionRequestId: pending.id, + decision: "rejected", actor: { userId: "reviewer" } }); + await settle(1000); + } + } finally { db.$client.options.debug = debug; } + expect(reads.length).toBeGreaterThan(0); + for (const read of reads) { + expect(read.query).toContain('"tool_action_requests"."company_id" ='); + expect(read.params).toContain(fixture.company.id); + expect(read.params).not.toContain(other.company.id); + } + expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, foreign.id)))[0].status).toBe("pending"); + expect(coordinator!.nextWakeAt()).toBe(foreign.expiresAt!.getTime()); + }); + + it("preserves a five-second deadline and an earlier committed replacement", async () => { + await start(); await quiet(); + const later = await requestWithExpiry(new Date(Date.now() + 120_000)); await settle(1); + expect(coordinator!.nextWakeAt()).toBe(later.expiresAt!.getTime()); + const earlier = await requestWithExpiry(new Date(Date.now() + 5000)); await settle(1); + expect(coordinator!.nextWakeAt()).toBe(earlier.expiresAt!.getTime()); + await settle(6000); await expectExpired(earlier.id, earlier.invocationId); + expect(coordinator!.nextWakeAt()).toBe(later.expiresAt!.getTime()); + await settle(120_000); await expectExpired(later.id, later.invocationId); await quiet(); + }); + + it("limits due expiry reads to the company whose deadline arrived", async () => { + const other = await createRunFixture(db); + await db.insert(toolPolicies).values(reviewNotePolicyRow(other.company)); + const foreign = await request(gateway, db, other); + const due = await requestWithExpiry(new Date(Date.now() + 5000)); + await start(); await settle(1); + const reads: Array<{ query: string; params: unknown[] }> = []; + const debug = db.$client.options.debug; + db.$client.options.debug = (_id, query, params) => { + if (/^select/i.test(query) && query.includes('"tool_action_requests"') && + (query.includes('min(') || query.includes('"expires_at" <='))) reads.push({ query, params: [...params] }); + }; + try { await settle(6000); } finally { db.$client.options.debug = debug; } + expect(reads.some(read => read.query.includes('"expires_at" <='))).toBe(true); + for (const read of reads) { + expect(read.query).toContain('"tool_action_requests"."company_id" ='); + expect(read.params).toContain(fixture.company.id); + expect(read.params).not.toContain(other.company.id); + } + await expectExpired(due.id, due.invocationId); + expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, foreign.id)))[0].status).toBe("pending"); + expect(coordinator!.nextWakeAt()).toBe(foreign.expiresAt!.getTime()); + }); + + it("removes cached review deadlines after company deletion commits", async () => { + await request(); await start(); await settle(1); + expect(coordinator!.nextWakeAt()).not.toBeNull(); + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }) + .where(eq(heartbeatRuns.id, fixture.run.id)); + await db.update(agents).set({ status: "terminated", lifecycleState: "terminated" }) + .where(eq(agents.id, fixture.agent.id)); + expect(await deleteCompany(db, fixture.company.id)).toMatchObject({ id: fixture.company.id }); + await quiet(); + expect(await gateway.actionReviewExpiryDeadlines()).toEqual([]); + }); + it("is quiet when configured idle, wakes on signing, expires the review and card, then stays quiet with history", async () => { await start(); await quiet(); const pending = await request(); @@ -379,8 +469,8 @@ describeEmbeddedPostgres("tool gateway service", () => { let release!: () => void, reading!: () => void; const gate = new Promise(resolve => { release = resolve; }); const ready = new Promise(resolve => { reading = resolve; }); - const actual = gateway.nextActionReviewExpiryAt.bind(gateway); - vi.spyOn(gateway, "nextActionReviewExpiryAt").mockImplementationOnce(async () => { + const actual = gateway.actionReviewExpiryDeadlines.bind(gateway); + vi.spyOn(gateway, "actionReviewExpiryDeadlines").mockImplementationOnce(async () => { const deadline = await actual(); reading(); await gate; return deadline; }); const starting = start(); await ready; @@ -405,7 +495,11 @@ describeEmbeddedPostgres("tool gateway service", () => { await db.insert(toolActionRequests).values(Array.from({ length: 101 }, () => ({ ...pending, id: randomUUID(), interactionId: null, expiresAt: past, }))); + const passes = vi.spyOn(gateway, "sweepExpiredActionReviewsForCompany"); await start(); await quiet(); + const results = await Promise.all(passes.mock.results.map(result => result.value)); + expect(results.length).toBeGreaterThan(1); + expect(results.every(result => result.scanned <= 100)).toBe(true); const rows = await db.select().from(toolActionRequests); expect(rows).toHaveLength(102); expect(rows.every(row => row.status === "expired")).toBe(true); @@ -422,7 +516,8 @@ describeEmbeddedPostgres("tool gateway service", () => { expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)))[0].status).toBe("pending"); expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, pending.invocationId)))[0].status).toBe("awaiting_approval"); await db.execute(sql`drop trigger sleep_review_fail on tool_invocations`); - expect(errors.every(error => (error as { cause?: Error }).cause?.message === "expiry settlement fixture failure")).toBe(true); + expect(errors.every(error => error instanceof AggregateError && error.errors.every( + failure => (failure as { cause?: Error }).cause?.message === "expiry settlement fixture failure"))).toBe(true); errors.length = 0; await settle(); await expectExpired(pending.id, pending.invocationId); await quiet(); }); diff --git a/server/src/services/company-deletion.ts b/server/src/services/company-deletion.ts index 7e4a41a95d7..ab549ecbfb8 100644 --- a/server/src/services/company-deletion.ts +++ b/server/src/services/company-deletion.ts @@ -1,3 +1,4 @@ +import { notifyToolReviewChange } from "./tool-review-work-notifications.js"; import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; import { agentObservabilityService } from "./agent-observability.js"; import { withAccountHomeSecretMutationLock } from "@paperclipai/adapter-codex-local/server"; @@ -62,6 +63,7 @@ export async function deleteCompany(db: Db, id: string) { if (!existing) return null; await notifyDeliveryWork(tx, DELIVERY_QUEUES.skillSourceSync); await notifyDeliveryWork(tx, DELIVERY_QUEUES.secretProposalExpiry, id); + await notifyToolReviewChange(tx, id); await agentObservabilityService(tx as unknown as Db).removeForCompanyDeletion(id); // Finance can reference costs and both can reference runs. Incidents // reference policies and approvals; delete these dependents first. diff --git a/server/src/services/issue-thread-interactions.ts b/server/src/services/issue-thread-interactions.ts index cf459b5e775..2843b2e48aa 100644 --- a/server/src/services/issue-thread-interactions.ts +++ b/server/src/services/issue-thread-interactions.ts @@ -1084,7 +1084,7 @@ async function resolveLinkedToolActionRequests( }, ) { if (interaction.kind !== "request_confirmation") return; - await notifyToolReviewChange(db); + await notifyToolReviewChange(db, interaction.companyId); await db .update(toolActionRequests) .set({ diff --git a/server/src/services/tool-access/activity/review-queue.ts b/server/src/services/tool-access/activity/review-queue.ts index 8f5955f261b..37df9bb6c94 100644 --- a/server/src/services/tool-access/activity/review-queue.ts +++ b/server/src/services/tool-access/activity/review-queue.ts @@ -87,7 +87,7 @@ listActionRequests: async ( if (!readable) invalidRequestIds.push(request.id); } if (invalidRequestIds.length > 0) { - await writeToolReviewChange(db, tx => tx + await writeToolReviewChange(db, companyId, tx => tx .update(toolActionRequests) .set({ status: "cancelled", diff --git a/server/src/services/tool-action-review.ts b/server/src/services/tool-action-review.ts index 38b69a24205..014065dbddd 100644 --- a/server/src/services/tool-action-review.ts +++ b/server/src/services/tool-action-review.ts @@ -141,7 +141,7 @@ export async function commitToolActionReview( throw conflict("This review has already been resolved"); } const now = new Date(); - await notifyToolReviewChange(tx); + await notifyToolReviewChange(tx, current.companyId); const [updated] = await tx .update(toolActionRequests) .set({ diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index f43f2e950d6..53a7e0a4b4f 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -2509,7 +2509,7 @@ export function createToolGatewayService( signingSecret: options.toolActionSigningSecret, }); } catch (error) { - await writeToolReviewChange(db, tx => tx + await writeToolReviewChange(db, actionRequest.companyId, tx => tx .update(toolActionRequests) .set({ status: "cancelled", @@ -2668,7 +2668,7 @@ export function createToolGatewayService( // an expired row. When the guard matches no row, the row is already resolved. // Do not emit an approval card for a dead row; throw a retriable conflict so // the retry finds the live request or creates a fresh, signable one. - const signedRows = await writeToolReviewChange(db, tx => tx + const signedRows = await writeToolReviewChange(db, actionRequest.companyId, tx => tx .update(toolActionRequests) .set({ interactionId: interaction.id, @@ -8498,7 +8498,7 @@ export function createToolGatewayService( pendingRequest.expiresAt.getTime() <= Date.now(); if (pendingUnsigned || pendingExpired) { const now = new Date(); - await writeToolReviewChange(db, tx => tx + await writeToolReviewChange(db, pendingRequest.companyId, tx => tx .update(toolActionRequests) .set({ status: "expired", resolvedAt: now, updatedAt: now }) .where( @@ -9533,7 +9533,7 @@ export function createToolGatewayService( signingSecret: options.toolActionSigningSecret, }); } catch (error) { - await writeToolReviewChange(db, tx => tx + await writeToolReviewChange(db, pendingActionRequest.companyId, tx => tx .update(toolActionRequests) .set({ status: "cancelled", @@ -9574,7 +9574,7 @@ export function createToolGatewayService( tool, argumentsSummary: argumentValidation.summary, }); - await writeToolReviewChange(db, tx => tx + await writeToolReviewChange(db, pendingActionRequest.companyId, tx => tx .update(toolActionRequests) .set({ canonicalArgumentsHash, @@ -9729,6 +9729,8 @@ export function createToolGatewayService( sweepExpiredActionReviews: reviewExpiry.sweep, nextActionReviewExpiryAt: reviewExpiry.next, + actionReviewExpiryDeadlines: reviewExpiry.deadlines, + sweepExpiredActionReviewsForCompany: reviewExpiry.sweepForCompany, async sweepActionReviews(input: { includeExpiry?: boolean } = {}) { // A process may stop between persisting a provider outcome and updating the @@ -9943,7 +9945,7 @@ export function createToolGatewayService( } if (!signedPayload) { if (actionRequest.status === "pending") { - await writeToolReviewChange(db, tx => tx + await writeToolReviewChange(db, actionRequest.companyId, tx => tx .update(toolActionRequests) .set({ status: "cancelled", @@ -10512,7 +10514,7 @@ export function createToolGatewayService( actionRequest.expiresAt.getTime() <= Date.now() ) { const expiredAt = new Date(); - const [expired] = await writeToolReviewChange(db, tx => tx + const [expired] = await writeToolReviewChange(db, actionRequest.companyId, tx => tx .update(toolActionRequests) .set({ status: "expired", @@ -10560,7 +10562,7 @@ export function createToolGatewayService( interaction?.kind === "request_confirmation" && interaction.status === "accepted" ) { - const [approved] = await writeToolReviewChange(db, tx => tx + const [approved] = await writeToolReviewChange(db, actionRequest.companyId, tx => tx .update(toolActionRequests) .set({ status: "approved", diff --git a/server/src/services/tool-review-expiry-work.ts b/server/src/services/tool-review-expiry-work.ts index 03019a5655e..8b7a8caad13 100644 --- a/server/src/services/tool-review-expiry-work.ts +++ b/server/src/services/tool-review-expiry-work.ts @@ -1,16 +1,25 @@ import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js"; import { DELIVERY_QUEUES } from "./delivery-work-notifications.js"; -import { registerDeadlineWork } from "./deadline-work.js"; +import { registerScopedDeadlineWork } from "./scoped-deadline-work.js"; import type { createToolGatewayService } from "./tool-gateway.js"; export function registerToolReviewExpiryWork( coordinator: ReturnType, - gateway: Pick, "sweepExpiredActionReviews" | "nextActionReviewExpiryAt">, + gateway: Pick, "sweepExpiredActionReviewsForCompany" | "actionReviewExpiryDeadlines">, canRun: () => boolean, ) { - return registerDeadlineWork(coordinator, DELIVERY_QUEUES.toolReviewExpiry, { - retryMs: 30_000, canRun, - run: () => gateway.sweepExpiredActionReviews(), - next: () => gateway.nextActionReviewExpiryAt(), - }); + return registerScopedDeadlineWork(coordinator, { + queue: DELIVERY_QUEUES.toolReviewExpiry, + batchSize: 1, + minimumPassIntervalMs: 0, + decodeScope: hint => hint === "*" ? undefined : hint, + matches: (entry, companyId?: string) => companyId === undefined || entry.companyId === companyId, + load: async (companyId?: string) => (await gateway.actionReviewExpiryDeadlines(companyId)) + .map(row => ({ ...row, id: row.companyId })), + check: async entry => { + await gateway.sweepExpiredActionReviewsForCompany(entry.companyId); + const [next] = await gateway.actionReviewExpiryDeadlines(entry.companyId); + return next ? { ...next, id: next.companyId } : null; + }, + }, canRun); } diff --git a/server/src/services/tool-review-expiry.ts b/server/src/services/tool-review-expiry.ts index 3280821fd7f..69e9b557349 100644 --- a/server/src/services/tool-review-expiry.ts +++ b/server/src/services/tool-review-expiry.ts @@ -1,4 +1,4 @@ -import { and, asc, eq, gt, lte, sql } from "drizzle-orm"; +import { and, asc, eq, gt, isNotNull, lte, sql } from "drizzle-orm"; import { toolActionRequests, toolInvocations, type Db } from "@paperclipai/db"; import { writeToolReviewChange } from "./tool-review-work-notifications.js"; @@ -15,36 +15,48 @@ export function toolReviewExpiryService(db: Db, onExpired: (input: { .from(toolActionRequests).where(eq(toolActionRequests.status, "pending")); return row?.at == null ? null : new Date(row.at).getTime(); }, - async sweep(now = new Date()) { - let cursor: string | undefined; - let scanned = 0; - for (;;) { - const rows = await db.select().from(toolActionRequests).where(and( - eq(toolActionRequests.status, "pending"), lte(toolActionRequests.expiresAt, now), - cursor ? gt(toolActionRequests.id, cursor) : undefined, - )).orderBy(asc(toolActionRequests.id)).limit(100); - for (const row of rows) { - const errorCode = "action_expired"; - const errorMessage = "The approval request expired before a decision."; - const changed = await writeToolReviewChange(db, async tx => { - const [updated] = await tx.update(toolActionRequests) - .set({ status: "expired", resolvedAt: now, updatedAt: now }).where(and( - eq(toolActionRequests.id, row.id), eq(toolActionRequests.status, "pending"), - eq(toolActionRequests.updatedAt, row.updatedAt), - )).returning({ id: toolActionRequests.id }); - if (!updated) return false; - await tx.update(toolInvocations).set({ status: "failed", errorCode, errorMessage, - completedAt: now, updatedAt: now }).where(eq(toolInvocations.id, row.invocationId)); - return true; - }); - if (changed) await onExpired({ actionRequestId: row.id, invocationId: row.invocationId, - status: "expired", errorCode, errorMessage }); - } - scanned += rows.length; - if (rows.length < 100) break; - cursor = rows[rows.length - 1].id; - } - return { scanned }; + sweep, + sweepForCompany: (companyId: string) => sweep(new Date(), companyId, 1), + async deadlines(companyId?: string) { + const rows = await db.select({ companyId: toolActionRequests.companyId, + at: sql`min(${toolActionRequests.expiresAt})` }) + .from(toolActionRequests).where(and(eq(toolActionRequests.status, "pending"), + isNotNull(toolActionRequests.expiresAt), + companyId === undefined ? undefined : eq(toolActionRequests.companyId, companyId))) + .groupBy(toolActionRequests.companyId); + return rows.map(row => ({ companyId: row.companyId, dueAt: new Date(row.at).getTime() })); }, }; + async function sweep(now = new Date(), companyId?: string, maxPages = Infinity) { + let cursor: string | undefined; + let scanned = 0; + for (let page = 0; page < maxPages; page++) { + const rows = await db.select().from(toolActionRequests).where(and( + eq(toolActionRequests.status, "pending"), lte(toolActionRequests.expiresAt, now), + cursor ? gt(toolActionRequests.id, cursor) : undefined, + companyId === undefined ? undefined : eq(toolActionRequests.companyId, companyId), + )).orderBy(asc(toolActionRequests.id)).limit(100); + for (const row of rows) { + const errorCode = "action_expired"; + const errorMessage = "The approval request expired before a decision."; + const changed = await writeToolReviewChange(db, row.companyId, async tx => { + const [updated] = await tx.update(toolActionRequests) + .set({ status: "expired", resolvedAt: now, updatedAt: now }).where(and( + eq(toolActionRequests.id, row.id), eq(toolActionRequests.status, "pending"), + eq(toolActionRequests.updatedAt, row.updatedAt), + )).returning({ id: toolActionRequests.id }); + if (!updated) return false; + await tx.update(toolInvocations).set({ status: "failed", errorCode, errorMessage, + completedAt: now, updatedAt: now }).where(eq(toolInvocations.id, row.invocationId)); + return true; + }); + if (changed) await onExpired({ actionRequestId: row.id, invocationId: row.invocationId, + status: "expired", errorCode, errorMessage }); + } + scanned += rows.length; + if (rows.length < 100) break; + cursor = rows[rows.length - 1].id; + } + return { scanned }; + } } diff --git a/server/src/services/tool-review-work-notifications.ts b/server/src/services/tool-review-work-notifications.ts index 6c13b75c7c6..19c8e433d75 100644 --- a/server/src/services/tool-review-work-notifications.ts +++ b/server/src/services/tool-review-work-notifications.ts @@ -1,13 +1,13 @@ import type { Db } from "@paperclipai/db"; import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; -export function notifyToolReviewChange(transaction: object) { - return notifyDeliveryWork(transaction, DELIVERY_QUEUES.toolReviewExpiry); +export function notifyToolReviewChange(transaction: object, companyId: string) { + return notifyDeliveryWork(transaction, DELIVERY_QUEUES.toolReviewExpiry, companyId); } -export function writeToolReviewChange(db: Db, write: (transaction: Db) => Promise): Promise { +export function writeToolReviewChange(db: Db, companyId: string, write: (transaction: Db) => Promise): Promise { return db.transaction(async transaction => { - await notifyToolReviewChange(transaction); + await notifyToolReviewChange(transaction, companyId); return write(transaction as unknown as Db); }); } From b04548e345e0564aa7502786961b45dff8b4597b Mon Sep 17 00:00:00 2001 From: Dotta Date: Mon, 26 Oct 2026 18:20:18 -0500 Subject: [PATCH 2/2] fix(server): scope approved review recovery to affected companies Keep startup reconstruction and paginated recovery in the existing owner. Preserve per-company retry deadlines across notifications and let healthy companies progress independently. Co-Authored-By: Paperclip --- doc/idle-approved-tool-recovery.md | 29 ++++++- .../server-startup-feedback-export.test.ts | 1 + .../__tests__/tool-gateway-service.test.ts | 76 +++++++++++++++++++ server/src/services/tool-gateway.ts | 8 +- .../src/services/tool-review-recovery-work.ts | 33 +++++--- server/src/services/tool-review-recovery.ts | 14 +++- 6 files changed, 142 insertions(+), 19 deletions(-) diff --git a/doc/idle-approved-tool-recovery.md b/doc/idle-approved-tool-recovery.md index 9d8f28d7ae8..571cb3f1d12 100644 --- a/doc/idle-approved-tool-recovery.md +++ b/doc/idle-approved-tool-recovery.md @@ -13,9 +13,18 @@ approval can owe execution even when no agent run exists. Recovery uses the save origin and current authorization/target checks; the scheduler sees only whether another attempt is needed. -Recovery pages approved requests in ID order using a partial index. It does not +Startup discovers companies with saved approved requests. Committed review +signals carry the affected company ID; subsequent discovery and recovery reads +filter by that company. The shared scoped worker coalesces changes and dispatches +one company per pass with a one-second minimum spacing. A company writing reviews +does not scan or lock another company's approved backlog. + +Recovery pages that company's approved requests in ID order using a partial index. It does not let a full batch of unavailable approvals starve later work. A failed read or -unresolved executable approval retains a 30-second retry. Once a pass leaves no +unresolved executable approval retains a 30-second retry. New writes preserve +that company's retry deadline, while other companies can run independently. +A company pass still drains all its pages; this change does not cap provider +calls within that pass or alter the provider's existing execution timeout. Once a pass leaves no such obligation, there is no recurring approved-recovery query. An empty system, configured idle tools, completed history, and deliberately inert approvals are quiet after reconciliation. @@ -29,7 +38,7 @@ queue invalidation, and the gateway's approval claims and managed-argument invalidation. The notification is awaited before SQL in the existing transaction; caller-owned outer transactions retain commit/rollback ownership. -A pending-only change can cause one empty approved-recovery pass. It does not +A pending-only change can cause one empty company-scoped discovery read. It does not create a periodic scan. No per-route recovery bookkeeping or database listener is added. Signals use the existing database owner's single-active-writer model. Independent SQL writers or another process need a separate notification contract. @@ -57,7 +66,8 @@ replay an uncertain provider call. The shared deadline worker coalesces notifications, preserves changes during a pass, and retains skipped work across idle drain/resume. Startup reconstructs -saved approvals. Shutdown stops its coordinator registration. With heartbeat +saved approvals. Company deletion invalidates cached recovery and retries through +the same transactional notification boundary. Shutdown stops its coordinator registration. With heartbeat scheduling disabled, startup keeps the existing one-off recovery behavior. Pending expiry is owned by the preceding slice. Interrupted execution and @@ -94,3 +104,14 @@ request to be executed and verifies exactly one provider call before asking for a new approval. Its full 469-test suite passes. The initial local command skipped its database cases; the suite now honors its supplied disposable database through the standard test-database guard independently of embedded Postgres support. + +Company-scoping regression: a real signed/reviewed action in company A previously +caused an unfiltered approved-request SELECT over company B's inert legacy action. +The captured-SQL test fails before this repair and passes with scoped reads. Added +lifecycle cases check retry preservation across committed writes, independent +company progress, and disarming after the real company-deletion producer. These +checks supplement the earlier execution, transaction, and paging evidence above. + +After company scoping, the complete gateway-service and startup selection passes +149 tests against a disposable PostgreSQL database, and server typecheck passes. +Stack integration, workspace checks, and fresh remote CI remain separate gates. diff --git a/server/src/__tests__/server-startup-feedback-export.test.ts b/server/src/__tests__/server-startup-feedback-export.test.ts index eaa51268645..5b10f2d5cde 100644 --- a/server/src/__tests__/server-startup-feedback-export.test.ts +++ b/server/src/__tests__/server-startup-feedback-export.test.ts @@ -67,6 +67,7 @@ const { }, toolGateway: { recoverApprovedActionReviews: vi.fn(async () => ({ scanned: 0, retry: false })), + approvedActionReviewCompanies: vi.fn(async () => []), sweepActionReviews: vi.fn(async () => ({ scanned: 0 })), sweepExpiredActionReviews: vi.fn(async () => ({ scanned: 0 })), nextActionReviewExpiryAt: vi.fn(async () => null), diff --git a/server/src/__tests__/tool-gateway-service.test.ts b/server/src/__tests__/tool-gateway-service.test.ts index ca9ef3ed91c..1040ab9271a 100644 --- a/server/src/__tests__/tool-gateway-service.test.ts +++ b/server/src/__tests__/tool-gateway-service.test.ts @@ -338,6 +338,43 @@ describeEmbeddedPostgres("tool gateway service", () => { expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toHaveLength(1); }); + it("does not scan another company's approved backlog after review writes", async () => { + const other = await createRunFixture(db); + await db.insert(toolPolicies).values(reviewNotePolicyRow(other.company)); + const foreign = await request(gateway, db, other); + await db.update(toolActionRequests).set({ signedArguments: signToolArguments({ + invocationId: foreign.invocationId, toolName: "mcp-remote-fixture:update_note", + canonicalArguments: canonicalToolArguments({ noteId: "legacy", body: "inert" }), + signingSecret: testToolActionSigningSecret, + }) }).where(eq(toolActionRequests.id, foreign.id)); + await commitToolActionReview(db, { companyId: other.company.id, actionRequestId: foreign.id, + decision: "approved", actor: { userId: "board" } }); + await startRecovery(); await quiet(); + const reads: Array<{ query: string; params: unknown[] }> = []; + const debug = db.$client.options.debug; + db.$client.options.debug = (_id, query, params) => { + if (/^select/i.test(query) && query.includes('"tool_action_requests"') && + query.includes('"tool_action_requests"."status" =') && params.includes("approved")) + reads.push({ query, params: [...params] }); + }; + try { + for (let index = 0; index < 3; index++) { + const pending = await request(); await settle(1500); + await approve(pending); await settle(1500); await executed(pending); + } + } finally { db.$client.options.debug = debug; } + expect(reads.length).toBeGreaterThan(0); + for (const read of reads) { + expect(read.query).toContain('"tool_action_requests"."company_id" ='); + expect(read.params).toContain(fixture.company.id); + expect(read.params).not.toContain(other.company.id); + } + expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, foreign.id)))[0].status).toBe("approved"); + expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, foreign.invocationId)))[0].status).toBe("awaiting_approval"); + expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toHaveLength(3); + await quiet(); + }); + it.each(["foreground", "recovery"] as const)("preserves the admitted rate slot for an agent action through %s approval", async mode => { await db.insert(toolPolicies).values({ companyId: fixture.company.id, name: "One reviewed note", policyType: "rate_limit", priority: 1, selectors: { toolName: "mcp-remote-fixture:update_note" }, @@ -368,6 +405,45 @@ describeEmbeddedPostgres("tool gateway service", () => { recover.mockRestore(); await settle(); await executed(pending); await quiet(); }); + it("preserves a failed company's retry across writes while another company executes", async () => { + const pending = await request(); await approve(pending); + const original = gateway.approveActionRequest.bind(gateway); + const dispatch = vi.spyOn(gateway, "approveActionRequest").mockImplementation(async input => { + if (input.companyId === fixture.company.id) throw new Error("Company dependency unavailable"); + return original(input); + }); + await startRecovery(); + expect(dispatch).toHaveBeenCalledTimes(1); + const retryAt = coordinator!.nextWakeAt(); + expect(retryAt).not.toBeNull(); + const later = await request(); await approve(later); + const other = await createRunFixture(db); + await db.insert(toolPolicies).values(reviewNotePolicyRow(other.company)); + const foreign = await request(gateway, db, other); + await commitToolActionReview(db, { companyId: other.company.id, actionRequestId: foreign.id, + decision: "approved", actor: { userId: "board" } }); + await settle(5000); await executed(foreign); + expect(dispatch.mock.calls.filter(([input]) => input.companyId === fixture.company.id)).toHaveLength(1); + expect(coordinator!.nextWakeAt()).toBe(retryAt); + dispatch.mockRestore(); + await settle(); await executed(pending); await executed(later); await quiet(); + expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toHaveLength(3); + }); + + it("disarms a failed company's recovery after company deletion commits", async () => { + const pending = await request(); await approve(pending); + const dispatch = vi.spyOn(gateway, "approveActionRequest").mockRejectedValue(new Error("Company dependency unavailable")); + await startRecovery(); expect(coordinator!.nextWakeAt()).not.toBeNull(); + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }) + .where(eq(heartbeatRuns.id, fixture.run.id)); + await db.update(agents).set({ status: "terminated", lifecycleState: "terminated" }) + .where(eq(agents.id, fixture.agent.id)); + await deleteCompany(db, fixture.company.id); + await settle(1500); + expect(coordinator!.nextWakeAt()).toBeNull(); + expect(dispatch).toHaveBeenCalledTimes(1); await quiet(); + }); + it.each([null, "unreadable-old-signature"])("settles an approved invalid signature (%s) without recurring recovery", async signedArguments => { const pending = await request(); await approve(pending); await db.update(toolActionRequests).set({ signedArguments }).where(eq(toolActionRequests.id, pending.id)); diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index cae9c4f3a24..da785592c31 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -1,5 +1,5 @@ import { claimToolTestApproval, persistToolTestOutcome, startToolTestInvocation, type ToolTestApprovalClaim } from "./tool-test-approval.js"; -import { prepareApprovedToolReview, recoverApprovedToolReviews } from "./tool-review-recovery.js"; +import { approvedToolReviewCompanies, prepareApprovedToolReview, recoverApprovedToolReviews } from "./tool-review-recovery.js"; import { toolReviewExpiryService } from "./tool-review-expiry.js"; import { writeToolReviewChange } from "./tool-review-work-notifications.js"; import { restConnectorFor } from "./connectors/rest-registry.js"; @@ -9656,7 +9656,9 @@ export function createToolGatewayService( actionReviewExpiryDeadlines: reviewExpiry.deadlines, sweepExpiredActionReviewsForCompany: reviewExpiry.sweepForCompany, - async recoverApprovedActionReviews() { + approvedActionReviewCompanies: (companyId?: string) => approvedToolReviewCompanies(db, companyId), + + async recoverApprovedActionReviews(companyId?: string) { return recoverApprovedToolReviews(db, async row => { try { const prepared = await prepareApprovedToolReview(db, { actionRequestId: row.request.id, @@ -9677,7 +9679,7 @@ export function createToolGatewayService( logger.warn({ err, actionRequestId: row.request.id }, "Could not recover approved tool action"); return true; } - }); + }, companyId); }, async sweepActionReviews(input: { includeExpiry?: boolean; includeApproved?: boolean } = {}) { diff --git a/server/src/services/tool-review-recovery-work.ts b/server/src/services/tool-review-recovery-work.ts index 1322b5f50a0..5611f5cf155 100644 --- a/server/src/services/tool-review-recovery-work.ts +++ b/server/src/services/tool-review-recovery-work.ts @@ -1,20 +1,33 @@ import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js"; import { DELIVERY_QUEUES } from "./delivery-work-notifications.js"; -import { registerDeadlineWork } from "./deadline-work.js"; +import { registerScopedDeadlineWork } from "./scoped-deadline-work.js"; import type { createToolGatewayService } from "./tool-gateway.js"; export function registerToolReviewRecoveryWork( coordinator: ReturnType, - gateway: Pick, "recoverApprovedActionReviews">, + gateway: Pick, "recoverApprovedActionReviews" | "approvedActionReviewCompanies">, canRun: () => boolean, ) { - let next: number | null = null; - return registerDeadlineWork(coordinator, DELIVERY_QUEUES.toolReviewRecovery, { - retryMs: 30_000, canRun, - run: async () => { - const result = await gateway.recoverApprovedActionReviews(); - next = result.retry ? Date.now() + 30_000 : null; + // Dispatch failures are reported by the domain owner, not thrown. Preserve + // their retry deadline when another write reloads the same company's work. + const retries = new Map(); + return registerScopedDeadlineWork(coordinator, { + queue: DELIVERY_QUEUES.toolReviewRecovery, + batchSize: 1, + decodeScope: hint => hint === "*" ? undefined : hint, + matches: (entry, companyId?: string) => companyId === undefined || entry.companyId === companyId, + load: async (companyId?: string) => { + const rows = await gateway.approvedActionReviewCompanies(companyId); + const retained = new Set(rows.map(row => row.companyId)); + for (const id of retries.keys()) if ((companyId === undefined || id === companyId) && !retained.has(id)) retries.delete(id); + return rows.map(row => ({ ...row, id: row.companyId, dueAt: retries.get(row.companyId) ?? Date.now() })); }, - next: async () => next, - }); + check: async entry => { + const result = await gateway.recoverApprovedActionReviews(entry.companyId); + if (!result.retry) { retries.delete(entry.companyId); return null; } + const dueAt = Date.now() + 30_000; + retries.set(entry.companyId, dueAt); + return { ...entry, dueAt }; + }, + }, canRun); } diff --git a/server/src/services/tool-review-recovery.ts b/server/src/services/tool-review-recovery.ts index 46ff9f0cada..69aa98c76f0 100644 --- a/server/src/services/tool-review-recovery.ts +++ b/server/src/services/tool-review-recovery.ts @@ -89,16 +89,26 @@ export async function prepareApprovedToolReview(db: Db, input: { }); } +export function approvedToolReviewCompanies(db: Db, companyId?: string) { + return db.select({ companyId: toolActionRequests.companyId }).from(toolActionRequests) + .innerJoin(toolInvocations, eq(toolInvocations.id, toolActionRequests.invocationId)) + .where(and(eq(toolActionRequests.status, "approved"), + companyId ? eq(toolActionRequests.companyId, companyId) : undefined)) + .groupBy(toolActionRequests.companyId); +} + export async function recoverApprovedToolReviews(db: Db, recover: (input: { request: typeof toolActionRequests.$inferSelect; invocation: typeof toolInvocations.$inferSelect; -}) => Promise) { +}) => Promise, companyId?: string) { let cursor: string | undefined; let scanned = 0, retry = false; for (;;) { const rows = await db.select({ request: toolActionRequests, invocation: toolInvocations }) .from(toolActionRequests).innerJoin(toolInvocations, eq(toolInvocations.id, toolActionRequests.invocationId)) - .where(and(eq(toolActionRequests.status, "approved"), cursor ? gt(toolActionRequests.id, cursor) : undefined)) + .where(and(eq(toolActionRequests.status, "approved"), + companyId ? eq(toolActionRequests.companyId, companyId) : undefined, + cursor ? gt(toolActionRequests.id, cursor) : undefined)) .orderBy(asc(toolActionRequests.id)).limit(100); for (const row of rows) retry = await recover(row) || retry; scanned += rows.length;