From 2bd476fb7cac2baadfd857adb61c2a5f1ef13608 Mon Sep 17 00:00:00 2001 From: Michael Zhou Date: Fri, 4 Dec 2026 03:13:47 +0800 Subject: [PATCH] Deduplicate Slack mirror replies and reuse its client The Slack mirror recorded a ticket's thread identity, but not which replies it had already posted. A retried reply job could therefore post the same message again. Add a per-message delivery ledger with an atomic claim lease, mark delivery after Slack accepts the post, and skip retries for messages already delivered. The claim is taken and judged against the database clock, so lease expiry does not depend on worker clock skew. A handler can now ask for a minimum delay before its next attempt, and the worker honours it when it is longer than the exponential backoff; that is how a job waits out a lease held by another execution. A permanent Slack rejection releases the claim so the message is not stranded; an ambiguous failure keeps it, because Slack may already have accepted the post. Slack requests get a timeout and the WebClient is cached per token, so a stalled request cannot outlive the job without bound and successive jobs reuse one client. Truncation now counts grapheme clusters rather than UTF-16 code units, so an emoji is never cut in half. The ledger is a new additive table related to Message, so rolling workers can continue using the existing schema. The delivery marker and the Slack post cannot be committed atomically; a process crash in between can still duplicate a post after the lease expires. Refs #152 Co-Authored-By: Claude Code --- .../migration.sql | 17 ++ packages/outpost/db/prisma/schema.prisma | 14 ++ .../outpost/queue/src/__tests__/queue.test.ts | 28 +++ .../handlers/__tests__/slack-mirror.test.ts | 225 +++++++++++++++++- .../queue/src/handlers/slack-mirror.ts | 177 +++++++++++++- packages/outpost/queue/src/types.ts | 5 + packages/outpost/queue/src/worker.ts | 11 +- 7 files changed, 453 insertions(+), 24 deletions(-) create mode 100644 packages/outpost/db/prisma/migrations/20261203201507_add_slack_mirror_reply_delivery_state/migration.sql diff --git a/packages/outpost/db/prisma/migrations/20261203201507_add_slack_mirror_reply_delivery_state/migration.sql b/packages/outpost/db/prisma/migrations/20261203201507_add_slack_mirror_reply_delivery_state/migration.sql new file mode 100644 index 00000000..6d69fcc6 --- /dev/null +++ b/packages/outpost/db/prisma/migrations/20261203201507_add_slack_mirror_reply_delivery_state/migration.sql @@ -0,0 +1,17 @@ +-- Per-message Slack delivery ledger. A unique messageId makes one row the +-- single durable identity of that reply; nullable claim fields let a worker +-- lease the row before posting and recover after a process exits. +CREATE TABLE "SlackMirrorDelivery" ( + "id" TEXT NOT NULL, + "messageId" TEXT NOT NULL, + "deliveredAt" TIMESTAMP(3), + "claimToken" TEXT, + "claimUntil" TIMESTAMP(3), + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "SlackMirrorDelivery_pkey" PRIMARY KEY ("id") +); + +CREATE UNIQUE INDEX "SlackMirrorDelivery_messageId_key" ON "SlackMirrorDelivery"("messageId"); + +ALTER TABLE "SlackMirrorDelivery" ADD CONSTRAINT "SlackMirrorDelivery_messageId_fkey" FOREIGN KEY ("messageId") REFERENCES "Message"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/packages/outpost/db/prisma/schema.prisma b/packages/outpost/db/prisma/schema.prisma index e9fe99d1..445688ef 100644 --- a/packages/outpost/db/prisma/schema.prisma +++ b/packages/outpost/db/prisma/schema.prisma @@ -133,6 +133,7 @@ model Message { // still PENDING, so folding them into the enum would lose the outcome. deliveryConfirmed Boolean @default(false) escalationRequiredReason String? + slackMirrorDelivery SlackMirrorDelivery? attachments Json? createdAt DateTime @default(now()) @@ -149,6 +150,19 @@ model Message { @@index([responseState, createdAt]) } +// Per-message idempotency for posts to the external Slack mirror. This is a +// separate table because mirror delivery is independent of the source message's +// response lifecycle and must not overload responseError or attachments. +model SlackMirrorDelivery { + id String @id @default(cuid()) + messageId String @unique + message Message @relation(fields: [messageId], references: [id], onDelete: Cascade) + deliveredAt DateTime? + claimToken String? + claimUntil DateTime? + createdAt DateTime @default(now()) +} + enum MessageType { USER BOT diff --git a/packages/outpost/queue/src/__tests__/queue.test.ts b/packages/outpost/queue/src/__tests__/queue.test.ts index 153bde72..ca33e3bd 100644 --- a/packages/outpost/queue/src/__tests__/queue.test.ts +++ b/packages/outpost/queue/src/__tests__/queue.test.ts @@ -551,6 +551,34 @@ describe('Worker', () => { ); }); + it('respects a handler minimum retry delay longer than exponential backoff', async () => { + const jobRow = makeJobRow({ attempts: 0, maxAttempts: 5 }); + mockPrisma.$queryRaw.mockResolvedValueOnce([jobRow]); + mockPrisma.$queryRaw.mockResolvedValue([]); + mockPrismaJob.updateMany.mockResolvedValue({ count: 1 }); + const scheduledAt = new Date(Date.now() + 10_000); + + worker.on(JobType.AI_RESPONSE, async () => ({ + success: false, + error: 'external delivery lease is still active', + retryable: true, + retryAfterMs: 10_000, + })); + + worker.start(); + await vi.advanceTimersByTimeAsync(0); + + expect(mockPrismaJob.updateMany).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.objectContaining({ + status: 'PENDING', + attempts: 1, + runAt: scheduledAt, + }), + }), + ); + }); + it('retries failed jobs with backoff when attempts remain', async () => { const jobRow = makeJobRow({ attempts: 1, maxAttempts: 5 }); // attempt will be 2 mockPrisma.$queryRaw.mockResolvedValueOnce([jobRow]); diff --git a/packages/outpost/queue/src/handlers/__tests__/slack-mirror.test.ts b/packages/outpost/queue/src/handlers/__tests__/slack-mirror.test.ts index 681fa588..40bcf2af 100644 --- a/packages/outpost/queue/src/handlers/__tests__/slack-mirror.test.ts +++ b/packages/outpost/queue/src/handlers/__tests__/slack-mirror.test.ts @@ -5,11 +5,36 @@ const mockMessageFindUnique = vi.fn(); const mockLinkFindUnique = vi.fn(); const mockLinkCreate = vi.fn(); const mockLinkUpdate = vi.fn(); +const mockDeliveryCreate = vi.fn(); +const mockDeliveryFindUnique = vi.fn(); +const mockDeliveryUpdateMany = vi.fn(); +const mockQueryRaw = vi.fn(); +const { mockSlackPostMessage, mockWebClientConstructor } = vi.hoisted(() => ({ + mockSlackPostMessage: vi.fn(), + mockWebClientConstructor: vi.fn(), +})); +const deliveryRows = new Map>(); + +vi.mock('@slack/web-api', () => ({ + WebClient: class { + chat = { postMessage: mockSlackPostMessage }; + + constructor(...args: unknown[]) { + mockWebClientConstructor(...args); + } + }, +})); vi.mock('@copilotkit/outpost/db', () => ({ prisma: { + $queryRaw: (...a: unknown[]) => mockQueryRaw(...a), ticket: { findUnique: (...a: unknown[]) => mockTicketFindUnique(...a) }, message: { findUnique: (...a: unknown[]) => mockMessageFindUnique(...a) }, + slackMirrorDelivery: { + create: (...a: unknown[]) => mockDeliveryCreate(...a), + findUnique: (...a: unknown[]) => mockDeliveryFindUnique(...a), + updateMany: (...a: unknown[]) => mockDeliveryUpdateMany(...a), + }, ticketExternalLink: { findUnique: (...a: unknown[]) => mockLinkFindUnique(...a), create: (...a: unknown[]) => mockLinkCreate(...a), @@ -77,10 +102,52 @@ describe('isSlackMirrorEnabled', () => { describe('handleSlackMirror', () => { beforeEach(() => { vi.clearAllMocks(); + mockQueryRaw.mockResolvedValue([{ now: new Date() }]); mockTicketFindUnique.mockResolvedValue(TICKET); mockLinkFindUnique.mockResolvedValue(null); mockLinkCreate.mockResolvedValue({}); mockLinkUpdate.mockResolvedValue({}); + deliveryRows.clear(); + mockDeliveryCreate.mockImplementation( + async ({ data }: { data: Record }) => { + const messageId = String(data.messageId); + if (deliveryRows.has(messageId)) { + throw Object.assign(new Error('Unique constraint'), { code: 'P2002' }); + } + const row = { ...data, deliveredAt: null }; + deliveryRows.set(messageId, row); + return row; + }, + ); + mockDeliveryFindUnique.mockImplementation( + async ({ where }: { where: { messageId: string } }) => + deliveryRows.get(where.messageId) ?? null, + ); + mockDeliveryUpdateMany.mockImplementation( + async ({ + where, + data, + }: { + where: Record; + data: Record; + }) => { + const row = deliveryRows.get(String(where.messageId)); + if (!row || row.deliveredAt !== null) return { count: 0 }; + if (typeof where.claimToken === 'string' && row.claimToken !== where.claimToken) { + return { count: 0 }; + } + if (Array.isArray(where.OR)) { + const expired = + row.claimUntil == null || + (row.claimUntil instanceof Date && + row.claimUntil <= + (where.OR[1] as { claimUntil: { lte: Date } }).claimUntil.lte); + if (!expired) return { count: 0 }; + } + Object.assign(row, data); + return { count: 1 }; + }, + ); }); it('posts nothing and touches no DB when the mirror is off', async () => { @@ -370,7 +437,7 @@ describe('handleSlackMirror', () => { }); }); - it('a duplicate reply job opens no thread and writes no link', async () => { + it('a duplicate reply job does not post the same message twice', async () => { mockLinkFindUnique.mockResolvedValue({ externalId: 'C0MIRROR:111.222' }); mockMessageFindUnique.mockResolvedValue({ id: 'msg-9', @@ -380,22 +447,154 @@ describe('handleSlackMirror', () => { }); const { poster, postMessage } = makePoster(); + const first = await handleSlackMirror( + { ticketId: 'tkt-1', kind: 'reply', messageId: 'msg-9' }, + context, + { config: liveConfig, poster }, + ); + const duplicate = await handleSlackMirror( + { ticketId: 'tkt-1', kind: 'reply', messageId: 'msg-9' }, + context, + { config: liveConfig, poster }, + ); + + expect(first.success).toBe(true); + expect(duplicate).toEqual({ success: true, data: { skipped: 'reply-already-mirrored' } }); + expect(postMessage).toHaveBeenCalledTimes(1); + expect(postMessage.mock.calls[0][0].thread_ts).toBe('111.222'); + expect(mockLinkCreate).not.toHaveBeenCalled(); + expect(mockLinkUpdate).not.toHaveBeenCalled(); + }); + + it('reuses one WebClient for successive jobs with the same token', async () => { + mockLinkFindUnique.mockResolvedValue({ externalId: 'C0MIRROR:111.222' }); + mockMessageFindUnique.mockImplementation(async ({ where }: { where: { id: string } }) => ({ + id: where.id, + author: 'octocat (12345)', + content: 'Still broken', + isAiGenerated: false, + })); + mockSlackPostMessage.mockResolvedValue({ ts: '222.333' }); + const config = { ...liveConfig, token: 'xoxb-client-cache-test' }; + for (let i = 0; i < 2; i++) { - const result = await handleSlackMirror( - { ticketId: 'tkt-1', kind: 'reply', messageId: 'msg-9' }, + await handleSlackMirror( + { ticketId: 'tkt-1', kind: 'reply', messageId: `msg-client-cache-${i}` }, context, - { config: liveConfig, poster }, + { config }, ); - expect(result.success).toBe(true); } - // Two reply posts, but never a root post and never a link write. - expect(postMessage).toHaveBeenCalledTimes(2); - for (const [args] of postMessage.mock.calls) { - expect(args.thread_ts).toBe('111.222'); - } - expect(mockLinkCreate).not.toHaveBeenCalled(); - expect(mockLinkUpdate).not.toHaveBeenCalled(); + expect(mockWebClientConstructor).toHaveBeenCalledTimes(1); + expect(mockWebClientConstructor).toHaveBeenCalledWith( + 'xoxb-client-cache-test', + expect.objectContaining({ + timeout: 30_000, + retryConfig: expect.any(Object), + }), + ); + expect(mockSlackPostMessage).toHaveBeenCalledTimes(2); + }); + + it('truncates an over-limit reply without splitting an emoji', async () => { + mockLinkFindUnique.mockResolvedValue({ externalId: 'C0MIRROR:111.222' }); + mockMessageFindUnique.mockResolvedValue({ + id: 'msg-emoji', + author: 'octocat (12345)', + content: `${'a'.repeat(2798)}πŸ‡ΊπŸ‡Έzz`, + isAiGenerated: false, + }); + const { poster, postMessage } = makePoster(); + + await handleSlackMirror( + { ticketId: 'tkt-1', kind: 'reply', messageId: 'msg-emoji' }, + context, + { config: liveConfig, poster }, + ); + + const text = postMessage.mock.calls[0][0].text; + expect(text).toContain('πŸ‡ΊπŸ‡Έ'); + expect(text.endsWith('…')).toBe(true); + }); + + it('does not post a reply while another unexpired claim owns it', async () => { + const messageId = 'msg-busy'; + deliveryRows.set(messageId, { + messageId, + claimToken: 'other-worker', + claimUntil: new Date(Date.now() + 60_000), + deliveredAt: null, + }); + mockLinkFindUnique.mockResolvedValue({ externalId: 'C0MIRROR:111.222' }); + mockMessageFindUnique.mockResolvedValue({ + id: messageId, + author: 'octocat (12345)', + content: 'Still broken', + isAiGenerated: false, + }); + const { poster, postMessage } = makePoster(); + + const result = await handleSlackMirror( + { ticketId: 'tkt-1', kind: 'reply', messageId }, + context, + { config: liveConfig, poster }, + ); + + expect(result).toMatchObject({ success: false, retryable: true }); + expect(postMessage).not.toHaveBeenCalled(); + }); + + it('keeps the reply claim and waits out its lease after a transient post failure', async () => { + mockLinkFindUnique.mockResolvedValue({ externalId: 'C0MIRROR:111.222' }); + mockMessageFindUnique.mockResolvedValue({ + id: 'msg-transient', + author: 'octocat (12345)', + content: 'Still broken', + isAiGenerated: false, + }); + const postMessage = vi.fn().mockRejectedValue(new Error('socket hangup')); + + const result = await handleSlackMirror( + { ticketId: 'tkt-1', kind: 'reply', messageId: 'msg-transient' }, + context, + { config: liveConfig, poster: { postMessage } }, + ); + + expect(result.success).toBe(false); + expect(result.retryable).toBe(true); + expect(result.retryAfterMs).toBeGreaterThan(0); + expect(postMessage).toHaveBeenCalledTimes(1); + const row = deliveryRows.get('msg-transient'); + expect(row?.claimToken).toEqual(expect.any(String)); + expect(row?.claimUntil).toBeInstanceOf(Date); + }); + + it('releases the reply claim when Slack permanently rejects the post', async () => { + mockLinkFindUnique.mockResolvedValue({ externalId: 'C0MIRROR:111.222' }); + mockMessageFindUnique.mockResolvedValue({ + id: 'msg-perm', + author: 'octocat (12345)', + content: 'Still broken', + isAiGenerated: false, + }); + const postMessage = vi.fn().mockRejectedValue( + Object.assign(new Error('An API error occurred'), { + data: { error: 'not_in_channel' }, + }), + ); + + const result = await handleSlackMirror( + { ticketId: 'tkt-1', kind: 'reply', messageId: 'msg-perm' }, + context, + { config: liveConfig, poster: { postMessage } }, + ); + + expect(result.success).toBe(false); + expect(result.retryable).toBe(false); + expect(result.error).toContain('not_in_channel'); + const row = deliveryRows.get('msg-perm'); + expect(row?.claimToken).toBeNull(); + expect(row?.claimUntil).toBeNull(); }); it('fails the job when the ticket is gone', async () => { @@ -543,6 +742,7 @@ describe('isMirrorableSource', () => { describe('handleSlackMirror β€” permanent vs retryable', () => { beforeEach(() => { vi.clearAllMocks(); + mockQueryRaw.mockResolvedValue([{ now: new Date() }]); mockTicketFindUnique.mockResolvedValue(TICKET); mockLinkFindUnique.mockResolvedValue(null); mockLinkCreate.mockResolvedValue({}); @@ -610,6 +810,7 @@ describe('handleSlackMirror β€” permanent vs retryable', () => { describe('handleSlackMirror β€” untrusted text', () => { beforeEach(() => { vi.clearAllMocks(); + mockQueryRaw.mockResolvedValue([{ now: new Date() }]); mockTicketFindUnique.mockResolvedValue({ ...TICKET, title: 'Crash