mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
Retry publication preparation failures before provider invocation
This commit is contained in:
1 parent
d293deecd6
commit
acbe863793
5 files changed
+55
-3
No files matched your search
@@ -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) => {
|
||||
|
||||
@@ -58,6 +58,7 @@ export function createChatPublicationFailures(db: Db, options: PublicationFailur
|
||||
providerAccepted = false,
|
||||
runtimeContext?: LifecycleRuntimeFence | null,
|
||||
credentialLease?: CredentialMutationLeaseGuard,
|
||||
providerInvocation: "possible" | "not_started" = "possible",
|
||||
): Promise<boolean> {
|
||||
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,
|
||||
|
||||
@@ -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<ReturnType<NonNullable<PublicationWorkerOptions["prepareSlackFormPublication"]>>> | 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,
|
||||
|
||||
@@ -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 });
|
||||
});
|
||||
|
||||
});
|
||||
@@ -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 };
|
||||
}
|
||||
Reference in new issue
Block a user