diff --git a/server/src/__tests__/approval-retention-work.test.ts b/server/src/__tests__/approval-retention-work.test.ts index 01de4141ebd..b004e9cd956 100644 --- a/server/src/__tests__/approval-retention-work.test.ts +++ b/server/src/__tests__/approval-retention-work.test.ts @@ -1,7 +1,7 @@ import { randomUUID } from "node:crypto"; import { eq, sql } from "drizzle-orm"; import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; -import { activityLog, agents, approvals, chatConversations, chatEndpoints, companies, createDb, decisionArchiveNotificationOutbox, decisionRetention, issueApprovals, issues, toolApplications, toolConnections, type Db } from "@paperclipai/db"; +import { activityLog, agents, approvals, chatConversations, chatEndpoints, companies, createDb, subscribeDatabaseWork, decisionArchiveNotificationOutbox, decisionRetention, issueApprovals, issues, toolApplications, toolConnections, type Db } from "@paperclipai/db"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; import { approvalRecords } from "../services/approvals.js"; @@ -12,6 +12,7 @@ import { issueApprovalService } from "../services/issue-approvals.js"; import { companyService } from "../services/companies.js"; import { issueService } from "../services/issues.js"; import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js"; +import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js"; import { idleWorkSnapshot } from "../services/task-admission.js"; const externalUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_APPROVAL_RETENTION_TEST_DATABASE_URL"); @@ -101,6 +102,48 @@ const delay = DEFAULT_DECISION_ARCHIVE_DAYS * 86_400_000; expect((await db.select().from(approvals).where(eq(approvals.id, row.id)))[0].status).toBe("pending"); }); + it.each(["approved", "rejected"] as const)("wakes parked tool reviews only on formal %s resolution", async outcome => { + const queues = [DELIVERY_QUEUES.toolReviewExpiry, DELIVERY_QUEUES.toolReviewRecovery, + DELIVERY_QUEUES.toolReviewInterruption, DELIVERY_QUEUES.toolReviewProjection]; + const events = queues.map(() => [] as string[]); + const subscriptions = queues.map((queue, index) => subscribeDatabaseWork(db, queue, event => { events[index].push(event); })); + try { + const row = await create(), target = await issue(); + for (let pass = 0; pass < 3; pass++) { + await issueApprovalService(db).link(target.id, row.id); + await issueApprovalService(db).unlink(target.id, row.id); + } + await approvalRecords(db).requestRevision(row.id, "board-user"); + await approvalRecords(db).resubmit(row.id); + expect(events).toEqual(queues.map(() => [])); + await approvalRecords(db).resolveApproval(row.id, outcome, "board-user", null); + expect(events).toEqual(queues.map(() => ["intent", "settled"])); + } finally { for (const unsubscribe of subscriptions) unsubscribe(); } + }); + + it("bounds aggregate retention reads to one reconciliation per thirty seconds of sequential tenant writes", async () => { + const [otherCompany] = await db.insert(companies).values({ name: "Other tenant", issuePrefix: `B${companyId.slice(0, 6)}` }).returning(); + const other = await approvalRecords(db).create(otherCompany.id, { type: "request_board_approval", payload: {} }); + const service = await start(); await settle(); + const sweep = vi.spyOn(service, "sweep"), reads = vi.spyOn(db, "select"); + await create(); + await vi.waitFor(() => expect(sweep).toHaveBeenCalledTimes(1)); + await sweep.mock.results[0].value; + await vi.waitFor(() => expect(idleWorkSnapshot().active).toBe(0)); + const afterFirst = reads.mock.calls.length; + expect(afterFirst).toBe(2); + for (let pass = 0; pass < 3; pass++) { + await create(); + await vi.advanceTimersByTimeAsync(100); + } + await vi.advanceTimersByTimeAsync(29_000); + expect(reads).toHaveBeenCalledTimes(afterFirst); + await vi.advanceTimersByTimeAsync(2000); + await vi.waitFor(() => expect(reads).toHaveBeenCalledTimes(afterFirst + 2)); + reads.mockRestore(); + expect((await db.select().from(approvals).where(eq(approvals.id, other.id)))[0].status).toBe("pending"); + }); + it("recovers old unseen approvals on startup and leaves completed history quiet", async () => { const due = await create(old()), completed = await create(old()); await approvalRecords(db).resolveApproval(completed.id, "approved", "board-user", null); diff --git a/server/src/lib/approval-records.ts b/server/src/lib/approval-records.ts index 8427d142902..7bd14df166a 100644 --- a/server/src/lib/approval-records.ts +++ b/server/src/lib/approval-records.ts @@ -1,3 +1,4 @@ +import { notifyToolReviewChange } from "../services/tool-review-work-notifications.js"; import { writeApprovalChange } from "../services/retention-work-notifications.js"; import { and, eq, inArray } from "drizzle-orm"; import { approvals, type Db } from "@paperclipai/db"; @@ -38,8 +39,9 @@ export function approvalResolutionRecords(db: Db) { } const now = new Date(); - const updated = await writeApprovalChange(database, existing.companyId, tx => tx - .update(approvals) + const updated = await writeApprovalChange(database, async tx => { + await notifyToolReviewChange(tx, existing.companyId); + return tx.update(approvals) .set({ status: targetStatus, decidedByUserId, @@ -49,7 +51,8 @@ export function approvalResolutionRecords(db: Db) { }) .where(and(eq(approvals.id, id), inArray(approvals.status, resolvableStatuses))) .returning() - .then((rows) => rows[0] ?? null)); + .then((rows) => rows[0] ?? null); + }); if (updated) { return { approval: updated, applied: true }; diff --git a/server/src/services/approval-retention.ts b/server/src/services/approval-retention.ts index db3c4daac24..855c81e413d 100644 --- a/server/src/services/approval-retention.ts +++ b/server/src/services/approval-retention.ts @@ -62,6 +62,6 @@ export function registerApprovalRetentionWork( canRun: () => boolean, ) { return registerDeadlineWork(coordinator, DELIVERY_QUEUES.approvalRetention, { - run: signal => service.sweep(new Date(), signal), next: service.next, canRun, retryMs: 30_000, + run: signal => service.sweep(new Date(), signal), next: service.next, canRun, retryMs: 30_000, notificationCoalesceMs: 30_000, }); } diff --git a/server/src/services/approvals.ts b/server/src/services/approvals.ts index 88d3fe7a546..d25efb8d01d 100644 --- a/server/src/services/approvals.ts +++ b/server/src/services/approvals.ts @@ -54,7 +54,7 @@ export function approvalRecords(db: Db) { }, create: (companyId: string, data: Omit) => - writeApprovalChange(db, companyId, tx => tx + writeApprovalChange(db, tx => tx .insert(approvals) .values({ ...data, companyId }) .returning() @@ -67,7 +67,7 @@ export function approvalRecords(db: Db) { const now = new Date(); const [existing] = await db.select({ companyId: approvals.companyId }).from(approvals).where(eq(approvals.id, id)); if (!existing) return null; - const updated = await writeApprovalChange(db, existing.companyId, tx => tx + const updated = await writeApprovalChange(db, tx => tx .update(approvals) .set({ status: "cancelled", @@ -88,7 +88,7 @@ export function approvalRecords(db: Db) { } const now = new Date(); - return writeApprovalChange(db, existing.companyId, tx => tx + return writeApprovalChange(db, tx => tx .update(approvals) .set({ status: "revision_requested", @@ -109,7 +109,7 @@ export function approvalRecords(db: Db) { } const now = new Date(); - return writeApprovalChange(db, existing.companyId, tx => tx + return writeApprovalChange(db, tx => tx .update(approvals) .set({ status: "pending", diff --git a/server/src/services/issue-approvals.ts b/server/src/services/issue-approvals.ts index 83267b2872b..b00133898b0 100644 --- a/server/src/services/issue-approvals.ts +++ b/server/src/services/issue-approvals.ts @@ -108,7 +108,7 @@ export function issueApprovalService(db: Db) { link: async (issueId: string, approvalId: string, actor?: LinkActor) => { const { issue } = await assertIssueAndApprovalSameCompany(issueId, approvalId); - await writeApprovalChange(db, issue.companyId, tx => tx + await writeApprovalChange(db, tx => tx .insert(issueApprovals) .values({ companyId: issue.companyId, @@ -128,7 +128,7 @@ export function issueApprovalService(db: Db) { unlink: async (issueId: string, approvalId: string) => { const { issue } = await assertIssueAndApprovalSameCompany(issueId, approvalId); - await writeApprovalChange(db, issue.companyId, tx => tx + await writeApprovalChange(db, tx => tx .delete(issueApprovals) .where(and(eq(issueApprovals.issueId, issueId), eq(issueApprovals.approvalId, approvalId)))); }, @@ -158,7 +158,7 @@ export function issueApprovalService(db: Db) { } } - await writeApprovalChange(db, approval.companyId, tx => tx + await writeApprovalChange(db, tx => tx .insert(issueApprovals) .values( uniqueIssueIds.map((issueId) => ({ diff --git a/server/src/services/retention-work-notifications.ts b/server/src/services/retention-work-notifications.ts index 87f725e802d..3464c624e89 100644 --- a/server/src/services/retention-work-notifications.ts +++ b/server/src/services/retention-work-notifications.ts @@ -1,4 +1,3 @@ -import { notifyToolReviewChange } from "./tool-review-work-notifications.js"; import type { Db } from "@paperclipai/db"; import type { AttentionSourceKind } from "@paperclipai/shared"; import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; @@ -7,12 +6,9 @@ export async function notifyRetentionWork(transaction: object, kind: AttentionSo if (kind === "approval") await notifyDeliveryWork(transaction, DELIVERY_QUEUES.approvalRetention); } -export function writeApprovalChange(db: Db, companyId: string, write: (transaction: Db) => Promise): Promise { +export function writeApprovalChange(db: Db, write: (transaction: Db) => Promise): Promise { return db.transaction(async tx => { await notifyRetentionWork(tx, "approval"); - // Formal decisions also release parked tool reviews. Share the existing - // approval write transaction rather than nesting another facade wrapper. - await notifyToolReviewChange(tx, companyId); return write(tx as unknown as Db); }); } diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index 318eb9cbe28..ae81998e947 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -2650,7 +2650,7 @@ export function createToolGatewayService( let formalApprovalId: string | null = null; if (toolRequiresFormalApproval(input.tool)) { - const [approval] = await writeApprovalChange(db, input.session.companyId, tx => tx + const [approval] = await writeApprovalChange(db, tx => tx .insert(approvals) .values({ companyId: input.session.companyId, @@ -2676,7 +2676,7 @@ export function createToolGatewayService( .returning()); formalApprovalId = approval.id; const approvalIssueId = input.session.issueId; - await writeApprovalChange(db, input.session.companyId, tx => tx + await writeApprovalChange(db, tx => tx .insert(issueApprovals) .values({ companyId: input.session.companyId,