From acbe86379396df0717cc0d2bd098170e8667a95a Mon Sep 17 00:00:00 2001 From: Dotta Date: Sat, 7 Nov 2026 14:03:03 -0600 Subject: [PATCH] Retry publication preparation failures before provider invocation --- .../__tests__/chat-run-milestone-work.test.ts | 28 ++++++++++++++++++- .../chat-channels/publications/failures.ts | 3 +- .../chat-channels/publications/worker.ts | 10 ++++++- .../services/chat-publication-errors.test.ts | 13 +++++++++ .../src/services/chat-publication-errors.ts | 4 +++ 5 files changed, 55 insertions(+), 3 deletions(-) diff --git a/server/src/__tests__/chat-run-milestone-work.test.ts b/server/src/__tests__/chat-run-milestone-work.test.ts index 40d3ce01195..555435fe2a1 100644 --- a/server/src/__tests__/chat-run-milestone-work.test.ts +++ b/server/src/__tests__/chat-run-milestone-work.test.ts @@ -46,7 +46,7 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu beforeAll(async () => { if (!external) temporary = await startEmbeddedPostgresTestDatabase("chat-milestones-"); - db = createDb(external ?? temporary!.connectionString, { maxConnections: 6, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 }); + db = createDb(external ?? temporary!.connectionString, { maxConnections: 4, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 }); fixtures = createChatMilestoneFixtures(db); }, 60_000); const fixture = (companyId?: string) => fixtures.create(companyId); @@ -765,6 +765,32 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu expect((await publications()).map(row => row.idempotencyKey)).toContain(`run:${targetId}:queued:${f.endpointId}`); await quiet(); }); + it.each([ + ["not_started", false, "retry"], + ["possible", false, "delivery_unknown"], + ["not_started", true, "delivery_unknown"], + ] as const)("settles local preparation context %s with accepted=%s as %s", async (providerInvocation, providerAccepted, state) => { + const [claimed] = await db.insert(chatPublications).values({ + companyId: f.companyId, endpointId: f.endpointId, conversationId: f.conversationId, + issueId: f.issueId, idempotencyKey: `preparation:${randomUUID()}`, + payload: { text: "Original publication" }, state: "streaming", attempts: 1, + }).returning(); + const failures = createChatPublicationFailures(db, { + FailedChatRetryPublicationReadError: class extends Error {}, + MAX_ERROR_TEXT: 1000, getTaskBaseUrl: () => null, + invalidateRuntime: async () => false, runtimeCallbackEndpoint: async () => null, + }); + const before = Date.now(); + await expect(failures.finalizePublicationFailure({ ...claimed, attempts: 0 }, + new Error("form_publication_enrollment_pending"), providerAccepted, null, undefined, providerInvocation)).resolves.toBe(true); + const [settled] = await db.select().from(chatPublications).where(eq(chatPublications.id, claimed.id)); + expect(settled).toMatchObject({ state, attempts: 1, providerMessageId: null, payload: claimed.payload }); + if (state === "retry") { + expect(settled.nextAttemptAt?.getTime()).toBeGreaterThanOrEqual(before + 2000); + expect(settled.nextAttemptAt?.getTime()).toBeLessThanOrEqual(Date.now() + 2000); + expect(settled.redactedError).toBe("form_publication_enrollment_pending"); + } else expect(settled.nextAttemptAt).toBeNull(); + }); it.each([ ["retry", null], ["failed", null], ["delivery_unknown", "cancel"], ["delivery_unknown", "mark_delivered"], ] as const)("rechecks resolved prompt ownership after delivery %s (%s)", async (state, resolution) => { diff --git a/server/src/services/chat-channels/publications/failures.ts b/server/src/services/chat-channels/publications/failures.ts index c7e22f1c680..9fd3e12a751 100644 --- a/server/src/services/chat-channels/publications/failures.ts +++ b/server/src/services/chat-channels/publications/failures.ts @@ -58,6 +58,7 @@ export function createChatPublicationFailures(db: Db, options: PublicationFailur providerAccepted = false, runtimeContext?: LifecycleRuntimeFence | null, credentialLease?: CredentialMutationLeaseGuard, + providerInvocation: "possible" | "not_started" = "possible", ): Promise { const attempts = publication.attempts + 1; const disposition = providerAccepted @@ -88,7 +89,7 @@ export function createChatPublicationFailures(db: Db, options: PublicationFailur ), reason: error.message, } - : classifyChatPublicationError(error, attempts); + : classifyChatPublicationError(error, attempts, providerInvocation); const failure = redactSensitiveText(disposition.reason).slice( 0, MAX_ERROR_TEXT, diff --git a/server/src/services/chat-channels/publications/worker.ts b/server/src/services/chat-channels/publications/worker.ts index 236cdc326ea..5cbf5ac6f5b 100644 --- a/server/src/services/chat-channels/publications/worker.ts +++ b/server/src/services/chat-channels/publications/worker.ts @@ -425,6 +425,7 @@ export function createChatPublicationWorker(db: Db, options: PublicationWorkerOp const settlePublicationFailure = async ( error: unknown, credentialLease?: CredentialMutationLeaseGuard, + providerInvocation: "possible" | "not_started" = "possible", ) => { try { await finalizePublicationFailure( @@ -433,6 +434,7 @@ export function createChatPublicationWorker(db: Db, options: PublicationWorkerOp providerAccepted, publicationRuntimeContext, credentialLease ?? publicationLease, + providerInvocation, ); } catch (finalizationError) { // If the provider accepted the message, a failed receipt write @@ -783,7 +785,13 @@ export function createChatPublicationWorker(db: Db, options: PublicationWorkerOp runtimeContext: currentPublicationRuntimeContext, }) : null; - const stageSlackForm = await options.prepareSlackFormPublication?.(authorizationClaim.endpoint, publication); + let stageSlackForm: Awaited>> | undefined; + try { + stageSlackForm = await options.prepareSlackFormPublication?.(authorizationClaim.endpoint, publication); + } catch (error) { + await settlePublicationFailure(error, credentialLease, "not_started"); + return; + } const sent = await postSafePublication({ endpoint: authorizationClaim.endpoint, conversation: authorizationClaim.conversation, diff --git a/server/src/services/chat-publication-errors.test.ts b/server/src/services/chat-publication-errors.test.ts index a2337931264..56abb236e21 100644 --- a/server/src/services/chat-publication-errors.test.ts +++ b/server/src/services/chat-publication-errors.test.ts @@ -475,4 +475,17 @@ describe("chat publication error classification", () => { }); }, ); + it("retries an unknown preparation failure only with a local before-invocation fact", () => { + const error = new Error("form_publication_enrollment_pending"); + expect(classifyChatPublicationError(error, 1, "not_started")).toEqual({ + kind: "retry", retryAfterMs: 2000, reason: error.message, + }); + expect(classifyChatPublicationError(error, 1)).toEqual({ kind: "delivery_unknown", reason: error.message }); + expect(classifyChatPublicationError(error, 1, "possible")).toEqual({ kind: "delivery_unknown", reason: error.message }); + }); + it("preserves definite provider dispositions with before-invocation context", () => { + expect(classifyChatPublicationError(Object.assign(new Error("rejected"), { status: 400 }), 1, "not_started")).toMatchObject({ kind: "failed" }); + expect(classifyChatPublicationError(Object.assign(new Error("slow down"), { status: 429 }), 1, "not_started")).toMatchObject({ kind: "retry", providerRateLimit: true }); + }); + }); diff --git a/server/src/services/chat-publication-errors.ts b/server/src/services/chat-publication-errors.ts index 24847917fa0..04f4c1c23d8 100644 --- a/server/src/services/chat-publication-errors.ts +++ b/server/src/services/chat-publication-errors.ts @@ -145,6 +145,7 @@ function structuredProviderErrors(error: unknown): StructuredProviderError[] { export function classifyChatPublicationError( error: unknown, attempt: number, + providerInvocation: "possible" | "not_started" = "possible", ): ChatPublicationErrorDisposition { const values = structuredProviderErrors(error); const firstNumber = (select: (value: StructuredProviderError) => unknown) => @@ -399,5 +400,8 @@ export function classifyChatPublicationError( // Adapter NetworkError and ordinary fetch/transport errors are ambiguous: // the request may have reached the provider even when no response reached // Paperclip. An operator must inspect the native conversation before replay. + if (providerInvocation === "not_started") { + return { kind: "retry", retryAfterMs: Math.min(60_000, 2 ** Math.max(0, attempt) * 1_000), reason }; + } return { kind: "delivery_unknown", reason }; }