diff --git a/server/src/__tests__/chat-channels.integration.test.ts b/server/src/__tests__/chat-channels.integration.test.ts index fe10f773b46..a9aad9d63fa 100644 --- a/server/src/__tests__/chat-channels.integration.test.ts +++ b/server/src/__tests__/chat-channels.integration.test.ts @@ -2749,10 +2749,13 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { const [settled] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, receipt.id)); const successors = (await readHeartbeatRunsByCompanyId(f.companyId)).filter(row => row.wakeupRequestId === receipt.id); const admitted = ["callback", "restart", "race"].includes(safetyScenario); + const sourceGone = { deleted_comment: "authority_source_comment", changed_generation: "authority_conversation_binding", + changed_source: "authority_source_shape" }[safetyScenario as "deleted_comment" | "changed_generation" | "changed_source"]; expect(successors).toHaveLength(admitted ? 1 : 0); expect(settled).toMatchObject({ id: receipt.id, idempotencyKey: receipt.idempotencyKey, requestedByActorId: receipt.requestedByActorId, requestedAt: receipt.requestedAt, - status: admitted ? "queued" : "deferred_issue_execution" }); + status: admitted ? "queued" : sourceGone ? "skipped" : "deferred_issue_execution", + ...(sourceGone ? { error: sourceGone, runId: null } : {}) }); if (admitted) { expect(extractWakeCommentIds(successors[0].contextSnapshot)).toEqual([comment.id]); expect(successors[0].contextSnapshot?.chatConversationId).toBe(f.conversation.id); diff --git a/server/src/__tests__/deferred-chat-wake-sweep.test.ts b/server/src/__tests__/deferred-chat-wake-sweep.test.ts new file mode 100644 index 00000000000..801863d4790 --- /dev/null +++ b/server/src/__tests__/deferred-chat-wake-sweep.test.ts @@ -0,0 +1,420 @@ +import { randomUUID } from "node:crypto"; +import { setImmediate as immediate } from "node:timers/promises"; +import { setTimeout as realTimeout } from "node:timers"; +import { and, eq, sql } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { agents, agentWakeupRequests, authUsers, chatActions, chatConversations, chatDeliveries, chatEndpoints, + chatExternalPrincipals, companies, companyMemberships, createDb, heartbeatRuns, issueComments, issues, + chatMessageLinks, chatPublications, toolApplications, toolConnections, type Db } from "@paperclipai/db"; +import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; +import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js"; +import { notifyDeferredExecutionEligibility, notifyDeferredExecutionWork, notifyDeferredWakesForIssue } from "../services/deferred-execution-notifications.js"; +import { heartbeatService } from "../services/heartbeat.js"; +import { createDurableChatWakeupRequest, resumeDeferredChatWake } from "../services/durable-chat-wakeup.js"; +import { createInboundWakeups } from "../services/chat-channels/inbound/wakeups.js"; +import { chatWakeAuthorityDenied } from "../services/chat-channels/inbound/wakeup-authorization-error.js"; +import { createInboundWakeNotices } from "../services/chat-channels/inbound/wakeup-notices.js"; +import { inboundWakePublicationKey } from "../services/chat-inbound-wakeup-publications.js"; +import { projectSafeChatPublication } from "../services/chat-publication-projection.js"; +import { DELIVERY_QUEUES, subscribeDeliveryWork } from "../services/delivery-work-notifications.js"; +import { logger } from "../middleware/logger.js"; + +vi.setConfig({ testTimeout: 120_000 }); +const RESUME_FAILED = "saved chat source could not resume after recovery"; +const HOUR_MS = 60 * 60_000; + +describe("deferred chat wake sweep", () => { + let temporary: Awaited> | undefined; + let db: ReturnType; + let heartbeat: ReturnType; + let coordinator: ReturnType; + let unregisterOwner: (() => void) | undefined; + const statements: string[] = []; + const errors: unknown[] = []; + const passes = new Set>(); + + beforeAll(async () => { + const external = resolveExternalTestDatabaseUrl("PAPERCLIP_DEFERRED_CHAT_WAKE_TEST_DATABASE_URL"); + if (!external) temporary = await startEmbeddedPostgresTestDatabase("deferred-chat-wake-"); + db = createDb(external ?? temporary!.connectionString, { maxConnections: 6, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 }); + db.$client.options.onnotice = () => {}; + db.$client.options.debug = (_connection, query) => { statements.push(query); }; + }); + beforeEach(async () => { + await db.execute(sql`truncate companies cascade`); + errors.length = 0; + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true }); + heartbeat = heartbeatService(db); + coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, canReconcile: () => true, + onError: error => { errors.push(error); } }); + const register = coordinator.register.bind(coordinator); + coordinator.register = (queue, task) => register(queue, { ...task, run: signal => { + const pass = Promise.resolve(task.run(signal)); passes.add(pass); + void pass.then(() => passes.delete(pass), () => passes.delete(pass)); return pass; + } }); + unregisterOwner = createInboundWakeups(db, { + authorizeInboundWakeup: async () => { throw new Error("unused"); }, + authorizeInboundWorkStart: (tx, action) => authorize(tx as unknown as Db, action) as never, + attachmentOmissionDetail: () => null, isExternalActionAuthorizationChange: () => false, redactError: String, + fetchImpl: async () => { throw new Error("unused"); }, heartbeat, + }).unregisterDeferredWakeOwner; + }); + afterEach(async () => { + unregisterOwner?.(); onAuthorize = undefined; + await coordinator.stop(); await heartbeat.drainActiveRunExecutions(); + vi.useRealTimers(); vi.restoreAllMocks(); + }); + afterAll(async () => { await db?.$client.end({ timeout: 1 }); await temporary?.cleanup(); }); + + let onAuthorize: ((action: typeof chatActions.$inferSelect) => Promise) | undefined; + async function authorize(tx: Db, action: typeof chatActions.$inferSelect) { + await onAuthorize?.(action); + const [issue] = await tx.select().from(issues).where(and(eq(issues.companyId, action.companyId), + eq(issues.id, String(action.payload.issueId)))).for("update"); + if (!issue || issue.assigneeAgentId !== action.payload.agentId || ["backlog", "done", "cancelled"].includes(issue.status)) + throw chatWakeAuthorityDenied("task_assignment"); + const [comment] = await tx.select().from(issueComments).where(eq(issueComments.id, String(action.payload.commentId))); + if (!comment || comment.deletedAt) throw chatWakeAuthorityDenied("source_comment"); + const [endpoint] = await tx.select().from(chatEndpoints).where(eq(chatEndpoints.id, action.endpointId)); + if (endpoint.status === "paused") throw chatWakeAuthorityDenied("runtime_fence"); + const [conversation] = await tx.select().from(chatConversations).where(eq(chatConversations.id, action.conversationId!)); + const [delivery] = await tx.select().from(chatDeliveries).where(eq(chatDeliveries.id, action.deliveryId!)); + return { issue, endpoint, conversation, delivery }; + } + + async function company() { + const companyId = randomUUID(), userId = `chat-user-${companyId.slice(0, 8)}`; + await db.insert(authUsers).values({ id: userId, name: "Chat sender", email: `${userId}@example.test`, + createdAt: new Date(), updatedAt: new Date() }); + await db.insert(companies).values({ id: companyId, name: "Deferred chat", issuePrefix: `DC${companyId.slice(0, 6)}`, + defaultResponsibleUserId: userId, requireBoardApprovalForNewAgents: false }); + await db.insert(companyMemberships).values({ companyId, principalId: userId, principalType: "user", status: "active", membershipRole: "owner" }); + const [agent] = await db.insert(agents).values({ companyId, name: "Chat agent", adapterType: "process", status: "idle", + adapterConfig: { command: process.execPath, args: ["-e", "console.log('chat-proof')"], cwd: process.cwd() }, + runtimeConfig: { heartbeat: { enabled: true, intervalSec: 0, wakeOnDemand: true } } }).returning(); + const [application] = await db.insert(toolApplications).values({ companyId, name: "Chat", type: "mcp_http" }).returning(); + const [connection] = await db.insert(toolConnections).values({ companyId, applicationId: application.id, + uid: randomUUID(), name: "Chat", transport: "rest_api" }).returning(); + const [endpoint] = await db.insert(chatEndpoints).values({ companyId, connectionId: connection.id, provider: "slack", + publicId: randomUUID(), assignedAgentId: agent.id, status: "active" }).returning(); + const [principal] = await db.insert(chatExternalPrincipals).values({ companyId, provider: "slack", + providerAccountId: "TWORKSPACE", externalId: `U${companyId.slice(0, 6)}`, kind: "user", isBot: false }).returning(); + return { companyId, userId, agent, endpoint, principal }; + } + + async function wake(c: Awaited>, input: { status: string; ageMs: number; runStatus?: string; + on?: { issue: typeof issues.$inferSelect; conversation: typeof chatConversations.$inferSelect } }) { + const createdAt = new Date(Date.now() - input.ageMs); + const issue = input.on?.issue ?? (await db.insert(issues).values({ companyId: c.companyId, title: "Chat task", status: input.status, + assigneeAgentId: c.agent.id }).returning())[0]; + const conversation = input.on?.conversation ?? (await db.insert(chatConversations).values({ companyId: c.companyId, + endpointId: c.endpoint.id, issueId: issue.id, externalConversationId: "CCHANNEL", + externalThreadId: `slack:CCHANNEL:${randomUUID()}`, externalLabel: "Thread", state: "active", isDirectMessage: false }).returning())[0]; + const [comment] = await db.insert(issueComments).values({ companyId: c.companyId, issueId: issue.id, + authorUserId: c.userId, body: "A follow-up sent while the task was running" }).returning(); + const providerEventId = randomUUID(); + const [delivery] = await db.insert(chatDeliveries).values({ companyId: c.companyId, endpointId: c.endpoint.id, + conversationId: conversation.id, principalId: c.principal.id, providerEventId, deduplicationKey: randomUUID(), + eventKind: "message", state: "processed", attempts: 1, normalizedEvent: { providerEventId, kind: "message" } }).returning(); + const actionId = randomUUID(); + const payload = { version: 1, issueId: issue.id, agentId: c.agent.id, commentId: comment.id, sessionGeneration: 1, + requestedByActorType: "user", requestedByActorId: c.userId }; + await db.insert(chatActions).values({ id: actionId, companyId: c.companyId, endpointId: c.endpoint.id, deliveryId: delivery.id, + conversationId: conversation.id, principalId: c.principal.id, kind: "inbound_wakeup", + providerActionId: `inbound_wakeup:${delivery.id}`, status: "processed", payload, createdAt }); + const request = createDurableChatWakeupRequest({ id: actionId, companyId: c.companyId, agentId: c.agent.id, issueId: issue.id, + commentId: comment.id, requestedByActorType: "user", requestedByActorId: c.userId, requestedAt: createdAt, + authorize: async () => {} }); + await db.insert(agentWakeupRequests).values({ id: actionId, companyId: c.companyId, agentId: c.agent.id, + source: "assignment", triggerDetail: "system", reason: "issue_commented", status: "deferred_issue_execution", + requestedByActorType: "user", requestedByActorId: c.userId, idempotencyKey: request.idempotencyKey, + requestedAt: createdAt, createdAt, updatedAt: createdAt, + payload: { issueId: issue.id, mutation: "comment", _paperclipWakeContext: { issueId: issue.id, wakeReason: "issue_commented", + wakeCommentId: comment.id, wakeCommentIds: [comment.id], commentId: comment.id } } }); + const [run] = await db.insert(heartbeatRuns).values({ companyId: c.companyId, agentId: c.agent.id, + status: input.runStatus ?? "succeeded", startedAt: createdAt, + finishedAt: input.runStatus === "running" ? null : new Date(createdAt.getTime() + 1000), + contextSnapshot: { issueId: issue.id } }).returning(); + return { issue, requestId: actionId, run, conversation, payloadCommentId: comment.id }; + } + + async function settle() { + for (let index = 0; index < 20; index++) { + await vi.advanceTimersByTimeAsync(1000); + await Promise.allSettled([...passes]); await immediate(); + } + } + function resumeFailures(spy: { mock: { calls: unknown[][] } }): unknown[][] { + return spy.mock.calls.filter(call => call[1] === RESUME_FAILED); + } + async function idle(minutes: number) { + const before = statements.length; + const updatesBefore = statements.filter(query => /^\s*update\s+"agent_wakeup_requests"/i.test(query)).length; + for (let minute = 0; minute < minutes; minute++) { + await vi.advanceTimersByTimeAsync(60_000); + await Promise.allSettled([...passes]); await immediate(); + } + return { statements: statements.length - before, + wakeUpdates: statements.filter(query => /^\s*update\s+"agent_wakeup_requests"/i.test(query)).length - updatesBefore }; + } + async function receipt(requestId: string) { + return (await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, requestId)))[0]; + } + function waitForReal(assertion: () => Promise, timeout = 10_000) { + const started = performance.now(); + return new Promise((resolve, reject) => { + const attempt = async () => { + try { await assertion(); resolve(); } + catch (error) { if (performance.now() - started > timeout) reject(error); else realTimeout(attempt, 50); } + }; + void attempt(); + }); + } + + it("settles stale wakes of finished tasks once and then stays idle for 30 minutes", async () => { + const c = await company(); + const wakes = []; + for (let index = 0; index < 12; index++) { + wakes.push(await wake(c, { status: index % 3 === 0 ? "cancelled" : "done", ageMs: 7 * 24 * 60 * 60_000 })); + } + const warn = vi.spyOn(logger, "warn"); + await heartbeat.registerDeferredReceiptWork(coordinator, () => true).ready; + await settle(); + const settledLogs = resumeFailures(warn).length; + const quiet = await idle(30); + const logs = resumeFailures(warn).length - settledLogs; + console.info(`[deferred-chat-wake] 12 stale wakes, 30 idle minutes: statements=${quiet.statements} ` + + `wakeUpdates=${quiet.wakeUpdates} resumeFailureLogs=${logs} firstPassLogs=${settledLogs}`); + for (const { requestId } of wakes) { + expect(await receipt(requestId)).toMatchObject({ status: "skipped", error: "task_closed", runId: null }); + } + expect(await db.select().from(heartbeatRuns).where(sql`${heartbeatRuns.wakeupRequestId} is not null`)).toHaveLength(0); + expect((await db.select().from(issues).where(eq(issues.companyId, c.companyId))).map(row => row.status).sort()) + .toEqual(wakes.map((_, index) => index % 3 === 0 ? "cancelled" : "done").sort()); + expect(resumeFailures(warn).every(call => (call[0] as { reason?: string }).reason === "task_closed")).toBe(true); + expect(quiet).toEqual({ statements: 0, wakeUpdates: 0 }); + expect(logs).toBe(0); + expect(errors).toEqual([]); + }); + + it("settles a saved chat wake whose task no longer exists", async () => { + const c = await company(); + const orphan = await wake(c, { status: "todo", ageMs: 60_000 }); + const before = await receipt(orphan.requestId); + await db.update(agentWakeupRequests).set({ payload: { ...before.payload, issueId: randomUUID() } }) + .where(eq(agentWakeupRequests.id, orphan.requestId)); + await heartbeat.registerDeferredReceiptWork(coordinator, () => true).ready; + await settle(); + expect(await receipt(orphan.requestId)).toMatchObject({ status: "skipped", error: "task_missing", runId: null }); + expect(await idle(30)).toEqual({ statements: 0, wakeUpdates: 0 }); + expect(errors).toEqual([]); + }); + + async function visibleQueuedNotice(c: Awaited>, saved: Awaited>) { + const [action] = await db.select().from(chatActions).where(eq(chatActions.id, saved.requestId)); + const providerMessageId = randomUUID(); + const [publication] = await db.insert(chatPublications).values({ companyId: c.companyId, endpointId: c.endpoint.id, + conversationId: saved.conversation.id, issueId: saved.issue.id, commentId: saved.payloadCommentId, + idempotencyKey: inboundWakePublicationKey(saved.requestId, "queued", c.endpoint.id, saved.conversation.id), + payload: projectSafeChatPublication({ classification: "external", source: "safe_milestone", + text: "Your follow-up is queued.", progressState: "queued" }), + state: "published", providerMessageId }).returning(); + await db.insert(chatMessageLinks).values({ companyId: c.companyId, endpointId: c.endpoint.id, + conversationId: saved.conversation.id, publicationId: publication.id, providerMessageId, direction: "outbound" }); + return action; + } + function noticeWorker() { + return createInboundWakeNotices(db, { + authorizeInboundWakeup: (async (tx: Db, action: typeof chatActions.$inferSelect) => { + const [issue] = await tx.select().from(issues).where(eq(issues.id, String(action.payload.issueId))); + const [endpoint] = await tx.select().from(chatEndpoints).where(eq(chatEndpoints.id, action.endpointId)); + const [conversation] = await tx.select().from(chatConversations).where(eq(chatConversations.id, action.conversationId!)); + const [delivery] = await tx.select().from(chatDeliveries).where(eq(chatDeliveries.id, action.deliveryId!)); + return { issue, endpoint, conversation, delivery, resource: null }; + }) as never, + enqueueFailedChatRetryPublications: async () => 0, + authorizeRetainedChatSourcePublication: async () => false, + isExternalActionAuthorizationChange: () => false, + isShuttingDown: () => false, + }); + } + async function notStartedNotices(companyId: string) { + return (await db.select().from(chatPublications).where(eq(chatPublications.companyId, companyId))) + .filter(row => row.idempotencyKey.includes(":not_started:")); + } + + it("closes old saved messages silently and tells a recent watcher once, across passes and restarts", async () => { + const c = await company(); + const old = await wake(c, { status: "done", ageMs: 72 * HOUR_MS }); + const recent = await wake(c, { status: "done", ageMs: 3 * HOUR_MS }); + await visibleQueuedNotice(c, old); + await visibleQueuedNotice(c, recent); + const noticeSignals: string[] = []; + const unsubscribe = subscribeDeliveryWork(db, DELIVERY_QUEUES.chatInboundWakeNotices, () => { noticeSignals.push("signal"); }); + try { + await heartbeat.registerDeferredReceiptWork(coordinator, () => true).ready; + await settle(); + } finally { unsubscribe(); } + expect(await receipt(old.requestId)).toMatchObject({ status: "skipped", error: "task_closed", runId: null, + payload: { silentSettlement: true } }); + expect(await receipt(recent.requestId)).toMatchObject({ status: "skipped", error: "task_closed", runId: null }); + expect((await receipt(recent.requestId)).payload?.silentSettlement).toBeUndefined(); + expect(noticeSignals).toHaveLength(1); + const deliveries = await db.select().from(chatDeliveries).where(eq(chatDeliveries.companyId, c.companyId)); + const deliveryOf = async (requestId: string) => { + const [action] = await db.select().from(chatActions).where(eq(chatActions.id, requestId)); + return deliveries.find(row => row.id === action.deliveryId)!; + }; + expect((await deliveryOf(old.requestId)).redactedError).toBeNull(); + expect((await deliveryOf(recent.requestId)).redactedError).toContain("Input saved."); + const first = await noticeWorker().reconcileInboundWakeNotices({ scope: { companyId: c.companyId } }); + expect(first.inserted).toBe(1); + expect((await notStartedNotices(c.companyId)).map(row => row.commentId)).toEqual([recent.payloadCommentId]); + expect((await noticeWorker().reconcileInboundWakeNotices({ scope: { companyId: c.companyId } })).inserted).toBe(0); + expect(await noticeWorker().loadInboundWakeNoticeScopes()).toEqual([]); + expect((await notStartedNotices(c.companyId)).map(row => row.commentId)).toEqual([recent.payloadCommentId]); + }); + + it("reopens a finished task for a recent saved chat message, as a message on a finished task does", async () => { + const c = await company(); + const recent = await wake(c, { status: "done", ageMs: 5 * 60_000 }); + await heartbeat.registerDeferredReceiptWork(coordinator, () => true).ready; + await waitForReal(async () => { + const runs = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.wakeupRequestId, recent.requestId)); + expect(runs).toHaveLength(1); + }); + expect((await db.select().from(issues).where(eq(issues.id, recent.issue.id)))[0].status).not.toBe("done"); + expect((await receipt(recent.requestId)).status).not.toBe("skipped"); + }); + + it("starts one follow-up run for two recent saved messages on the same finished task", async () => { + const c = await company(); + const first = await wake(c, { status: "done", ageMs: 10 * 60_000 }); + const second = await wake(c, { status: "done", ageMs: 5 * 60_000, on: first }); + await heartbeat.registerDeferredReceiptWork(coordinator, () => true).ready; + await waitForReal(async () => { + const runs = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, c.companyId), + sql`${heartbeatRuns.wakeupRequestId} is not null`)); + expect(runs).toHaveLength(1); + const receipts = await Promise.all([receipt(first.requestId), receipt(second.requestId)]); + expect(receipts.map(row => row.runId)).toEqual([runs[0].id, runs[0].id]); + expect(receipts[0]).toMatchObject({ status: "coalesced", payload: { coalescedIntoWakeupRequestId: second.requestId } }); + expect(runs[0].contextSnapshot?.wakeCommentIds).toEqual([ + first.payloadCommentId, second.payloadCommentId]); + }); + await settle(); + expect(await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, c.companyId), + sql`${heartbeatRuns.wakeupRequestId} is not null`))).toHaveLength(1); + }); + + it("answers a recent saved message alone when a newer message of the same task lost its source", async () => { + const c = await company(); + const valid = await wake(c, { status: "done", ageMs: 10 * 60_000 }); + const removed = await wake(c, { status: "done", ageMs: 5 * 60_000, on: valid }); + await db.update(issueComments).set({ deletedAt: new Date() }).where(eq(issueComments.id, removed.payloadCommentId)); + await heartbeat.registerDeferredReceiptWork(coordinator, () => true).ready; + await waitForReal(async () => { + const runs = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, c.companyId), + sql`${heartbeatRuns.wakeupRequestId} is not null`)); + expect(runs).toHaveLength(1); + expect(runs[0].wakeupRequestId).toBe(valid.requestId); + expect(runs[0].contextSnapshot?.wakeCommentIds ?? []).not.toContain(removed.payloadCommentId); + const left = await receipt(removed.requestId); + expect(left.runId).toBeNull(); + expect(["skipped", "deferred_issue_execution"]).toContain(left.status); + if (left.status === "skipped") expect(left.error).toBe("authority_source_comment"); + }); + }); + + it("refuses a batch that another run took a message from before admission, then answers the rest alone", async () => { + const c = await company(); + const older = await wake(c, { status: "done", ageMs: 10 * 60_000 }); + const newer = await wake(c, { status: "done", ageMs: 5 * 60_000, on: older }); + const [other] = await db.insert(heartbeatRuns).values({ companyId: c.companyId, agentId: c.agent.id, status: "succeeded", + startedAt: new Date(Date.now() - 2000), finishedAt: new Date(Date.now() - 1000), + contextSnapshot: { issueId: randomUUID(), wakeCommentIds: [older.payloadCommentId] } }).returning(); + let newerChecks = 0; + onAuthorize = async action => { + if (action.id !== newer.requestId || ++newerChecks !== 2) return; + await db.update(agentWakeupRequests).set({ status: "completed", runId: other.id }).where(eq(agentWakeupRequests.id, older.requestId)); + }; + const scope = { companyId: c.companyId, agentId: c.agent.id, issueId: older.issue.id, recoverySweep: true }; + await expect(resumeDeferredChatWake(db, { ...scope, requestId: older.requestId })) + .rejects.toThrow("chat_inbound_wakeup_batch_changed"); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.wakeupRequestId, newer.requestId))).toHaveLength(0); + expect(await receipt(newer.requestId)).toMatchObject({ status: "deferred_issue_execution", runId: null }); + await resumeDeferredChatWake(db, { ...scope, requestId: newer.requestId }); + const [alone] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.wakeupRequestId, newer.requestId)); + expect(alone.contextSnapshot?.wakeCommentIds ?? [newer.payloadCommentId]).toEqual([newer.payloadCommentId]); + expect(await receipt(older.requestId)).toMatchObject({ status: "completed", runId: other.id }); + }); + + it("keeps a refused follow-up in the saved pause wait without retrying, then starts it when the pause lifts", async () => { + const c = await company(); + await db.update(agents).set({ status: "paused" }).where(eq(agents.id, c.agent.id)); + const refused = await wake(c, { status: "done", ageMs: 5 * 60_000 }); + await heartbeat.registerDeferredReceiptWork(coordinator, () => true).ready; + await settle(); + const waiting = await receipt(refused.requestId); + expect(waiting).toMatchObject({ status: "deferred_issue_execution", runId: null, + payload: { executionWait: { reason: "agent.not_invokable" } } }); + expect(waiting.payload?.chatResume).toBeUndefined(); + expect(await db.select().from(heartbeatRuns).where(sql`${heartbeatRuns.wakeupRequestId} is not null`)).toHaveLength(0); + await idle(1); + expect(await idle(30)).toEqual({ statements: 0, wakeUpdates: 0 }); + expect(await db.select().from(heartbeatRuns).where(sql`${heartbeatRuns.wakeupRequestId} is not null`)).toHaveLength(0); + await db.transaction(async tx => { + await tx.update(agents).set({ status: "idle" }).where(eq(agents.id, c.agent.id)); + await notifyDeferredExecutionEligibility(tx, { companyId: c.companyId }); + }); + await waitForReal(async () => { + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.wakeupRequestId, refused.requestId))).toHaveLength(1); + }, 10_000); + }); + + it("spaces bounded attempts on a stored time and still resumes promptly on a real event", async () => { + const c = await company(); + await db.update(chatEndpoints).set({ status: "paused" }).where(eq(chatEndpoints.id, c.endpoint.id)); + const paused = await wake(c, { status: "todo", ageMs: 60_000 }); + const warn = vi.spyOn(logger, "warn"); + await heartbeat.registerDeferredReceiptWork(coordinator, () => true).ready; + await settle(); + const first = await receipt(paused.requestId); + expect(first).toMatchObject({ status: "deferred_issue_execution", error: "authority_runtime_fence" }); + const nextAttemptAt = Date.parse(String((first.payload?.chatResume as Record).nextAttemptAt)); + expect(nextAttemptAt).toBeGreaterThan(Date.now()); + const window = await idle(30); + const attempts = resumeFailures(warn); + console.info(`[deferred-chat-wake] paused endpoint, 30 idle minutes: attempts=${attempts.length} statements=${window.statements}`); + expect(attempts.length).toBeGreaterThanOrEqual(2); + expect(attempts.length).toBeLessThanOrEqual(4); + expect(attempts.every(call => (call[0] as { reason?: string }).reason === "authority_runtime_fence")).toBe(true); + const later = await receipt(paused.requestId); + expect(later.status).toBe("deferred_issue_execution"); + await db.transaction(async tx => { + await tx.update(chatEndpoints).set({ status: "active" }).where(eq(chatEndpoints.id, c.endpoint.id)); + await notifyDeferredExecutionWork(tx, { companyId: c.companyId, requestId: paused.requestId }); + }); + await waitForReal(async () => { + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.wakeupRequestId, paused.requestId))).toHaveLength(1); + }, 5_000); + }); + + it("waits for the run it was deferred behind and resumes as soon as that run finishes", async () => { + const c = await company(); + const waiting = await wake(c, { status: "in_progress", ageMs: 30_000, runStatus: "running" }); + await heartbeat.registerDeferredReceiptWork(coordinator, () => true).ready; + await settle(); + const window = await idle(10); + expect(window).toEqual({ statements: 0, wakeUpdates: 0 }); + expect(await receipt(waiting.requestId)).toMatchObject({ status: "deferred_issue_execution", error: null }); + await db.transaction(async tx => { + await tx.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, waiting.run.id)); + await notifyDeferredWakesForIssue(tx, { companyId: c.companyId, issueId: waiting.issue.id }); + }); + await waitForReal(async () => { + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.wakeupRequestId, waiting.requestId))).toHaveLength(1); + }, 5_000); + }); +}); diff --git a/server/src/services/chat-channels/inbound/wakeup-notices.ts b/server/src/services/chat-channels/inbound/wakeup-notices.ts index de9f0b57d71..a77c9540e4c 100644 --- a/server/src/services/chat-channels/inbound/wakeup-notices.ts +++ b/server/src/services/chat-channels/inbound/wakeup-notices.ts @@ -10,6 +10,7 @@ import { isExternalChatWaitAuthorizationContention } from "../../native-runtime/ import { projectSafeChatPublication } from "../../chat-publication-projection.js"; import { inboundWakePublicationKey, inboundWakePublicationText, parseInboundWakePublicationKey, resolveInboundWakeReceipt } from "../../chat-inbound-wakeup-publications.js"; import { inboundWakeScope, type createInboundWakeAuthority } from "./wakeup-authorization.js"; +import { SILENT_CHAT_WAKE_SETTLEMENT_KEY } from "../../durable-chat-wakeup.js"; import type { createChatFailedRunRetry } from "../failed-run-retry.js"; type NoticeOptions = { authorizeInboundWakeup: ReturnType["authorizeInboundWakeup"]; @@ -182,6 +183,8 @@ export function createInboundWakeNotices(db: Db, options: NoticeOptions) { scope?.issueId ? eq(payloadIssueId, scope.issueId) : undefined, inArray(chatActions.status, ["processed", "failed"]), eq(owner.companyId, chatActions.companyId), + sql`${owner.payload}->>${SILENT_CHAT_WAKE_SETTLEMENT_KEY} is distinct from 'true'`, + sql`${agentWakeupRequests.payload}->>${SILENT_CHAT_WAKE_SETTLEMENT_KEY} is distinct from 'true'`, or( and( isNull(owner.runId), diff --git a/server/src/services/chat-channels/inbound/wakeups.ts b/server/src/services/chat-channels/inbound/wakeups.ts index feea97ba8f0..7b107b8debf 100644 --- a/server/src/services/chat-channels/inbound/wakeups.ts +++ b/server/src/services/chat-channels/inbound/wakeups.ts @@ -5,11 +5,12 @@ import type { EndpointRow, DbOrTransaction } from "../runtime-types.js"; import { notifyChatRunMilestones } from "../../chat-run-milestone-notifications.js"; import { notifyChatDeliveryWork } from "../../chat-work-notifications.js"; import { enqueueFastResponse } from "../../fast-responses.js"; -import { and, eq, sql } from "drizzle-orm"; +import { and, asc, eq, gte, inArray, isNull, sql } from "drizzle-orm"; import { retryChatControlAdmission } from "../../chat-control-admission-retry.js"; import type { Db } from "@paperclipai/db"; -import { createDurableChatWakeupRequest, assertDurableChatWakeupReceipt, registerDeferredChatWakeOwner } from "../../durable-chat-wakeup.js"; -import { agentWakeupRequests, chatActions, chatConversations, chatDeliveries, chatEndpoints } from "@paperclipai/db"; +import { createDurableChatWakeupRequest, assertDurableChatWakeupReceipt, registerDeferredChatWakeOwner, CLOSED_TASK_CHAT_WAKE_REOPEN_WINDOW_MS, type DeferredChatWakeDecline } from "../../durable-chat-wakeup.js"; +import { agentWakeupRequests, chatActions, chatConversations, chatDeliveries, chatEndpoints, heartbeatRuns, issues } from "@paperclipai/db"; +import { issueService } from "../../issues.js"; import { forbidden } from "../../../errors.js"; import { logger } from "../../../middleware/logger.js"; import { queueIssueAssignmentWakeup } from "../../issue-assignment-wakeup.js"; @@ -438,44 +439,117 @@ export function createInboundWakeups(db: Db, options: WakeupOptions) { return denied; } } - const unregisterDeferredWakeOwner = registerDeferredChatWakeOwner(db, async (scope) => { - const action = await db.select().from(chatActions).where(and( + async function reopenClosedChatTask(tx: Db, action: typeof chatActions.$inferSelect) { + const [issue] = await tx.select().from(issues).where(and(eq(issues.companyId, action.companyId), + eq(issues.id, String(action.payload.issueId)))).for("update"); + if (!issue || issue.assigneeAgentId !== action.payload.agentId || !["done", "cancelled"].includes(issue.status)) return; + const [endpoint] = await tx.select({ sponsorUserId: chatEndpoints.sponsorUserId }).from(chatEndpoints) + .where(and(eq(chatEndpoints.companyId, action.companyId), eq(chatEndpoints.id, action.endpointId))); + await issueService(tx).update(issue.id, { status: "todo", + actorUserId: action.payload.requestedByActorType === "user" ? String(action.payload.requestedByActorId) : endpoint?.sponsorUserId ?? null, + }, tx); + } + async function recentClosedTaskChatWakes(scope: { companyId: string; agentId: string; issueId: string }, + action: typeof chatActions.$inferSelect) { + const rows = await db.select({ receipt: agentWakeupRequests, action: chatActions }).from(agentWakeupRequests) + .innerJoin(chatActions, and(eq(chatActions.companyId, agentWakeupRequests.companyId), eq(chatActions.id, agentWakeupRequests.id))) + .where(and(eq(agentWakeupRequests.companyId, scope.companyId), eq(agentWakeupRequests.agentId, scope.agentId), + eq(agentWakeupRequests.status, "deferred_issue_execution"), isNull(agentWakeupRequests.runId), + sql`${agentWakeupRequests.idempotencyKey} like 'chat-inbound:%'`, + sql`${agentWakeupRequests.payload}->>'issueId' = ${scope.issueId}`, + gte(agentWakeupRequests.createdAt, new Date(Date.now() - CLOSED_TASK_CHAT_WAKE_REOPEN_WINDOW_MS)), + eq(chatActions.kind, "inbound_wakeup"), eq(chatActions.status, "processed"), + action.conversationId ? eq(chatActions.conversationId, action.conversationId) : isNull(chatActions.conversationId), + sql`${chatActions.payload}->>'issueId' = ${scope.issueId}`, sql`${chatActions.payload}->>'agentId' = ${scope.agentId}`)) + .orderBy(asc(agentWakeupRequests.createdAt), asc(agentWakeupRequests.id)); + return rows; + } + const unregisterDeferredWakeOwner = registerDeferredChatWakeOwner(db, async (scope): Promise => { + const saved = await db.select().from(chatActions).where(and( eq(chatActions.id, scope.requestId), eq(chatActions.companyId, scope.companyId), - eq(chatActions.kind, "inbound_wakeup"), eq(chatActions.status, "processed"), )).then(rows => rows[0] ?? null); - if (!action || action.payload.agentId !== scope.agentId || action.payload.issueId !== scope.issueId) return; + if (!saved || saved.kind !== "inbound_wakeup") return; + const source = saved; const [receipt] = await db.select().from(agentWakeupRequests).where(and( - eq(agentWakeupRequests.id, action.id), eq(agentWakeupRequests.companyId, scope.companyId), + eq(agentWakeupRequests.id, scope.requestId), eq(agentWakeupRequests.companyId, scope.companyId), eq(agentWakeupRequests.agentId, scope.agentId), eq(agentWakeupRequests.status, "deferred_issue_execution"), )); if (!receipt || receipt.runId) return; - const authorize = async (tx: Db) => { - const [source] = await tx.select().from(chatActions).where(and( - eq(chatActions.id, action.id), eq(chatActions.companyId, scope.companyId), + const sweep = scope.recoverySweep === true; + if (["preparing", "issued", "processing"].includes(source.status)) return sweep ? { retry: "source_pending" } : undefined; + if (source.status !== "processed" || source.payload.agentId !== scope.agentId || + source.payload.issueId !== scope.issueId) return sweep ? { settle: "source_missing" } : undefined; + let closed = false; + if (sweep) { + const [task] = await db.select({ status: issues.status, assigneeAgentId: issues.assigneeAgentId }).from(issues) + .where(and(eq(issues.companyId, scope.companyId), eq(issues.id, scope.issueId))); + if (!task) return { settle: "task_missing" }; + if (task.assigneeAgentId !== scope.agentId) return { settle: "task_reassigned" }; + if (task.status === "backlog") return { retry: "task_backlog" }; + closed = task.status === "done" || task.status === "cancelled"; + if (closed && receipt.createdAt.getTime() < Date.now() - CLOSED_TASK_CHAT_WAKE_REOPEN_WINDOW_MS) return { settle: "task_closed" }; + } + const candidates = closed + ? (await recentClosedTaskChatWakes(scope, source)).filter(row => row.receipt.id !== receipt.id) : []; + const authorizeAction = async (tx: Db, saved: typeof chatActions.$inferSelect) => { + const [current] = await tx.select().from(chatActions).where(and( + eq(chatActions.id, saved.id), eq(chatActions.companyId, scope.companyId), eq(chatActions.kind, "inbound_wakeup"), eq(chatActions.status, "processed"), )); - if (!source || inboundWakeScope(source) !== inboundWakeScope(action)) + if (!current || inboundWakeScope(current) !== inboundWakeScope(saved)) throw forbidden("The saved chat source changed", { code: "chat_action_authorization_changed" }); - const current = await authorizeInboundWorkStart(tx, source); - if (current.delivery.state !== "processed") throw new Error("chat_inbound_wakeup_acceptance_not_committed"); - return current; + const authorized = await authorizeInboundWorkStart(tx, current); + if (authorized.delivery.state !== "processed") throw new Error("chat_inbound_wakeup_acceptance_not_committed"); + return authorized; }; + const accepted: typeof candidates = []; // The same authority used at ingress checks the live endpoint, principal, // immutable action source, conversation generation and original comment. - const context = await db.transaction(tx => authorize(tx as unknown as Db)); + const context = await db.transaction(async tx => { + if (closed) await reopenClosedChatTask(tx as unknown as Db, source); + const authorized = await authorizeAction(tx as unknown as Db, source); + for (const candidate of candidates) { + if (await tx.transaction(inner => authorizeAction(inner as unknown as Db, candidate.action)).then(() => true, () => false)) + accepted.push(candidate); + } + return authorized; + }); + const batch = [{ receipt, action: source }, ...accepted].sort((left, right) => + left.receipt.createdAt.getTime() - right.receipt.createdAt.getTime() || left.receipt.id.localeCompare(right.receipt.id)); + const { receipt: primaryReceipt, action } = batch.at(-1)!; + const riders = batch.slice(0, -1); const request = createDurableChatWakeupRequest({ id: action.id, companyId: scope.companyId, agentId: scope.agentId, issueId: scope.issueId, commentId: String(action.payload.commentId), requestedByActorType: action.payload.requestedByActorType as "user" | "system", requestedByActorId: String(action.payload.requestedByActorId), requestedAt: action.createdAt, - resumeDeferred: true, authorize: async tx => { await authorize(tx); }, + resumeDeferred: true, + authorize: async tx => { + await authorizeAction(tx, action); + if (!riders.length) return; + const current = await tx.select({ status: agentWakeupRequests.status, runId: agentWakeupRequests.runId }) + .from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, scope.companyId), + inArray(agentWakeupRequests.id, riders.map(rider => rider.receipt.id)))).for("update"); + if (current.length !== riders.length || current.some(row => row.status !== "deferred_issue_execution" || row.runId)) + throw new Error("chat_inbound_wakeup_batch_changed"); + }, + ...(riders.length ? { onAdmitted: async (tx: Db, admitted: { runId: string | null }) => { + if (!admitted.runId) return; + const now = new Date(); + await tx.update(agentWakeupRequests).set({ status: "coalesced", runId: admitted.runId, finishedAt: now, updatedAt: now, + payload: sql`coalesce(${agentWakeupRequests.payload}, '{}'::jsonb) || ${JSON.stringify({ coalescedIntoWakeupRequestId: action.id })}::jsonb`, + }).where(and(eq(agentWakeupRequests.companyId, scope.companyId), + inArray(agentWakeupRequests.id, riders.map(rider => rider.receipt.id)), + eq(agentWakeupRequests.status, "deferred_issue_execution"), isNull(agentWakeupRequests.runId))); + } } : {}), }); - assertDurableChatWakeupReceipt(request, receipt); + assertDurableChatWakeupReceipt(request, primaryReceipt); await queueIssueAssignmentWakeup({ heartbeat: options.heartbeat, issue: context.issue, reason: EXTERNAL_CHAT_MESSAGE_WAKE_REASON, mutation: EXTERNAL_CHAT_MESSAGE_WAKE_MUTATION, contextSource: `chat:${context.endpoint.provider}`, taskKey: context.issue.identifier, requestedByActorType: request.requestedByActorType, requestedByActorId: request.requestedByActorId, wakeCommentId: request.commentId, chatConversationId: context.conversation.id, + ...(riders.length ? { wakeCommentIds: batch.map(entry => String(entry.action.payload.commentId)) } : {}), attachmentOmissionReasons: action.payload.attachmentOmissionReasons as Record | undefined, durableChatRequest: request, rethrowOnError: true }); }); diff --git a/server/src/services/chat-inbound-wakeup-publications.ts b/server/src/services/chat-inbound-wakeup-publications.ts index d037459beb5..44cf53d2f1a 100644 --- a/server/src/services/chat-inbound-wakeup-publications.ts +++ b/server/src/services/chat-inbound-wakeup-publications.ts @@ -2,6 +2,7 @@ import type { agentWakeupRequests, chatActions } from "@paperclipai/db"; import { assertDurableChatWakeupReceipt, createDurableChatWakeupRequest, + SILENT_CHAT_WAKE_SETTLEMENT_KEY, } from "./durable-chat-wakeup.js"; import { QUEUED_MESSAGES_DELIVERED_REASON } from "../modules/wake-queue/index.js"; @@ -130,6 +131,8 @@ export function resolveInboundWakeReceipt( // "not started" would be wrong; it keeps the same silence as a promotion. if (declined && owner.status === "cancelled" && owner.error === QUEUED_MESSAGES_DELIVERED_REASON) return null; + if (declined && [owner, receipt].some(row => row.payload?.[SILENT_CHAT_WAKE_SETTLEMENT_KEY] === true)) + return null; if (declined) return owner.runId || receipt.runId ? null diff --git a/server/src/services/deferred-execution-notifications.ts b/server/src/services/deferred-execution-notifications.ts index de9f1d1235e..2fc7c522f80 100644 --- a/server/src/services/deferred-execution-notifications.ts +++ b/server/src/services/deferred-execution-notifications.ts @@ -7,6 +7,7 @@ export type DeferredReceiptRecoveryOptions = { companyId?: string; requestId?: string; onError?: (error: unknown) => void; + onDeferredDeadline?: (at: number) => void; }; const ASSIGNMENT_WAKE_REASON = "issue_assigned"; diff --git a/server/src/services/durable-chat-wakeup.ts b/server/src/services/durable-chat-wakeup.ts index acfb4b4ca63..15e909d74a9 100644 --- a/server/src/services/durable-chat-wakeup.ts +++ b/server/src/services/durable-chat-wakeup.ts @@ -1,8 +1,10 @@ import { slackDeliveryMeetsMentionRequirement } from "./chat-channels/slack/wake-authority.js"; import { createHash } from "node:crypto"; import { agentWakeupRequests, chatActions, chatConversations, chatDeliveries, chatEndpoints, type Db } from "@paperclipai/db"; -import { and, eq, exists, inArray, or, sql, type SQLWrapper } from "drizzle-orm"; +import { and, eq, exists, inArray, isNull, or, sql, type SQLWrapper } from "drizzle-orm"; import { HttpError } from "../errors.js"; +import { safeChatWakeAuthorityReason } from "./chat-channels/inbound/wakeup-authorization-error.js"; +import { notifyChatInboundWakeNotices } from "./chat-inbound-wake-notice-notifications.js"; export interface CommittedChatResponseAuthorizationInput { companyId: string; @@ -233,6 +235,82 @@ export interface DeferredChatWakeScope { agentId: string; issueId: string; requestId: string; + recoverySweep?: boolean; +} + +export type DeferredChatWakeDecline = { settle: string } | { retry: string }; + +export const CLOSED_TASK_CHAT_WAKE_REOPEN_WINDOW_MS = 60 * 60_000; +export const SILENT_CHAT_WAKE_SETTLEMENT_AFTER_MS = 24 * 60 * 60_000; +export const DEFERRED_CHAT_WAKE_RETRY_KEY = "chatResume"; +export const SILENT_CHAT_WAKE_SETTLEMENT_KEY = "silentSettlement"; +export const DEFERRED_CHAT_WAKE_RETRY_DELAYS_MS = [60_000, 10 * 60_000, 60 * 60_000, 6 * 60 * 60_000, 24 * 60 * 60_000]; +const SETTLED_AUTHORITY_REASONS = new Set(["source_shape", "delivery_binding", "conversation_binding", + "destination_binding", "source_comment"]); +const DECLINED_CHAT_INPUT_NOTICE = + "Input saved. Its work request was skipped, cancelled, or failed; no automatic replay was performed."; + +export function deferredChatWakeNextAttemptAt(payload: Record | null | undefined): number | null { + const retry = payload?.[DEFERRED_CHAT_WAKE_RETRY_KEY]; + if (!retry || typeof retry !== "object" || Array.isArray(retry)) return null; + const at = Date.parse(String((retry as Record).nextAttemptAt)); + return Number.isFinite(at) ? at : null; +} + +export function deferredChatWakeDeclineForError(error: unknown): DeferredChatWakeDecline { + const authority = safeChatWakeAuthorityReason(error); + if (authority) return SETTLED_AUTHORITY_REASONS.has(authority) + ? { settle: `authority_${authority}` } : { retry: `authority_${authority}` }; + if (error instanceof HttpError) { + const details = error.details && typeof error.details === "object" ? error.details as Record : {}; + return { retry: typeof details.code === "string" ? details.code : `http_${error.status}` }; + } + return { retry: error instanceof Error && /^chat_[a-z_]+$/.test(error.message) ? error.message : "resume_failed" }; +} + +export async function recordDeferredChatWakeDecline(db: Db, + scope: { companyId: string; issueId: string; requestId: string }, decline: DeferredChatWakeDecline) { + return db.transaction(async tx => { + const [receipt] = await tx.select({ payload: agentWakeupRequests.payload, createdAt: agentWakeupRequests.createdAt }) + .from(agentWakeupRequests).where(and( + eq(agentWakeupRequests.companyId, scope.companyId), eq(agentWakeupRequests.id, scope.requestId), + eq(agentWakeupRequests.status, "deferred_issue_execution"), isNull(agentWakeupRequests.runId))).for("update"); + if (!receipt) return null; + const previous = receipt.payload?.[DEFERRED_CHAT_WAKE_RETRY_KEY]; + const attempts = (previous && typeof previous === "object" && !Array.isArray(previous) + ? Number((previous as Record).attempts) || 0 : 0) + 1; + const now = new Date(); + if ("retry" in decline && attempts <= DEFERRED_CHAT_WAKE_RETRY_DELAYS_MS.length) { + const nextAttemptAt = now.getTime() + DEFERRED_CHAT_WAKE_RETRY_DELAYS_MS[attempts - 1]!; + await tx.update(agentWakeupRequests).set({ error: decline.retry, updatedAt: now, + payload: sql`coalesce(${agentWakeupRequests.payload}, '{}'::jsonb) || ${JSON.stringify({ [DEFERRED_CHAT_WAKE_RETRY_KEY]: { + attempts, reason: decline.retry, nextAttemptAt: new Date(nextAttemptAt).toISOString() } })}::jsonb`, + }).where(eq(agentWakeupRequests.id, scope.requestId)); + return { outcome: "retry" as const, reason: decline.retry, attempts, nextAttemptAt }; + } + const reason = "settle" in decline ? decline.settle : `retry_exhausted:${decline.retry}`; + const silent = receipt.createdAt.getTime() < now.getTime() - SILENT_CHAT_WAKE_SETTLEMENT_AFTER_MS; + await tx.update(agentWakeupRequests).set({ status: "skipped", error: reason, finishedAt: now, updatedAt: now, + payload: silent + ? sql`(${agentWakeupRequests.payload} - ${DEFERRED_CHAT_WAKE_RETRY_KEY}::text) || ${JSON.stringify({ [SILENT_CHAT_WAKE_SETTLEMENT_KEY]: true })}::jsonb` + : sql`${agentWakeupRequests.payload} - ${DEFERRED_CHAT_WAKE_RETRY_KEY}::text`, + }).where(eq(agentWakeupRequests.id, scope.requestId)); + if (silent) return { outcome: "settled" as const, reason, attempts, silent }; + await notifyChatInboundWakeNotices(tx, { companyId: scope.companyId, issueId: scope.issueId }); + await tx.update(chatDeliveries).set({ redactedError: DECLINED_CHAT_INPUT_NOTICE, updatedAt: now }).where(and( + eq(chatDeliveries.companyId, scope.companyId), eq(chatDeliveries.state, "processed"), + sql`${chatDeliveries.id} = (select ${chatActions.deliveryId} from ${chatActions} + where ${chatActions.companyId} = ${scope.companyId} and ${chatActions.id} = ${scope.requestId} + and ${chatActions.kind} = 'inbound_wakeup')`)); + return { outcome: "settled" as const, reason, attempts, silent }; + }); +} + +export async function clearDeferredChatWakeRetry(db: Db, scope: { companyId: string; requestId: string }) { + await db.update(agentWakeupRequests).set({ error: null, + payload: sql`${agentWakeupRequests.payload} - ${DEFERRED_CHAT_WAKE_RETRY_KEY}::text`, + }).where(and(eq(agentWakeupRequests.companyId, scope.companyId), eq(agentWakeupRequests.id, scope.requestId), + sql`${agentWakeupRequests.payload} ? ${DEFERRED_CHAT_WAKE_RETRY_KEY}::text`)); } /** Identify saved input by its canonical receipt, never by a caller's source @@ -250,15 +328,18 @@ export function deferredChatInputPredicate(db: Db) { sql`${chatActions.payload}->>'issueId' = ${agentWakeupRequests.payload}->>'issueId'`, sql`${chatActions.payload}->>'agentId' = ${agentWakeupRequests.agentId}::text`))); } -const deferredChatWakeOwners = new WeakMap Promise>(); +type DeferredChatWakeOwner = (input: DeferredChatWakeScope) => Promise; +const deferredChatWakeOwners = new WeakMap(); /** The live inbound owner reauthorizes the original source. Cleanup owns no chat authority. */ -export function registerDeferredChatWakeOwner(db: Db, owner: (input: DeferredChatWakeScope) => Promise) { +export function registerDeferredChatWakeOwner(db: Db, owner: DeferredChatWakeOwner) { deferredChatWakeOwners.set(db, owner); return () => { if (deferredChatWakeOwners.get(db) === owner) deferredChatWakeOwners.delete(db); }; } -export async function resumeDeferredChatWake(db: Db, input: DeferredChatWakeScope) { - await deferredChatWakeOwners.get(db)?.(input); +export async function resumeDeferredChatWake(db: Db, input: DeferredChatWakeScope): Promise { + const owner = deferredChatWakeOwners.get(db); + if (!owner) return undefined; + return (await owner(input)) ?? undefined; } /** Internal authority: this object cannot be supplied through a JSON API. */ diff --git a/server/src/services/heartbeat/deferred-receipt-work.ts b/server/src/services/heartbeat/deferred-receipt-work.ts index 3892352a1fc..e8507e0346a 100644 --- a/server/src/services/heartbeat/deferred-receipt-work.ts +++ b/server/src/services/heartbeat/deferred-receipt-work.ts @@ -6,8 +6,9 @@ import { DELIVERY_QUEUES } from "../delivery-work-notifications.js"; import { assignmentWakePayloadSql, type DeferredExecutionScope, type DeferredReceiptRecoveryOptions } from "../deferred-execution-notifications.js"; import { registerScopedDeadlineWork } from "../scoped-deadline-work.js"; import { dependencyResolvedWakePayloadSql } from "../issue-dependency-wakeups.js"; +import { DEFERRED_CHAT_WAKE_RETRY_KEY, deferredChatWakeNextAttemptAt } from "../durable-chat-wakeup.js"; -type Entry = { id: string; companyId: string; dueAt: number; immediate: boolean; operatorRetry?: boolean }; +type Entry = { id: string; companyId: string; dueAt: number; immediate: boolean; operatorRetry?: boolean; forced?: boolean }; type NativeIntentOptions = DeferredExecutionScope & { onDeferredDeadline(at: number): void; onError(error: unknown): void; @@ -63,6 +64,7 @@ export function registerDeferredReceiptWork( status: agentWakeupRequests.status, updatedAt: agentWakeupRequests.updatedAt, claimedAt: agentWakeupRequests.claimedAt, error: agentWakeupRequests.error, operatorRetry: sql`${operatorRetry}`, + chatRetryAt: sql`${agentWakeupRequests.payload} #>> ${`{${DEFERRED_CHAT_WAKE_RETRY_KEY},nextAttemptAt}`}`, delayed: sql`${agentWakeupRequests.payload}->'queuedCommentInterrupt' is not null or ${agentWakeupRequests.payload}->'executionWait' is not null`, interruptedLegacy: sql`exists (select 1 from heartbeat_runs r @@ -104,13 +106,16 @@ export function registerDeferredReceiptWork( if (complete) cursors.delete(key); else cursors.set(key, rows.at(-1)!.id); const now = Date.now(); return { rows: [...prioritized, ...rows].map(row => { + const forced = kind === "deferred" && scope?.requestId === row.id; + const chatRetryAt = kind === "deferred" && !forced && row.chatRetryAt ? Date.parse(row.chatRetryAt) : NaN; const deadline = kind === "native" && row.status === "claimed" && row.claimedAt ? row.claimedAt.getTime() + 60_000 : kind === "native" && row.error ? row.updatedAt.getTime() + 30_000 - : kind === "deferred" && row.delayed && !row.interruptedLegacy ? row.updatedAt.getTime() + 30_000 + : kind === "deferred" && row.delayed && !row.interruptedLegacy ? Math.max(row.updatedAt.getTime() + 30_000, chatRetryAt || 0) + : Number.isFinite(chatRetryAt) ? chatRetryAt : null; const immediate = deadline === null || deadline <= now; return { id: row.id, companyId: row.companyId, dueAt: immediate ? now : deadline, immediate, - operatorRetry: kind === "deferred" && row.operatorRetry }; + operatorRetry: kind === "deferred" && row.operatorRetry, forced }; }), complete }; }, check: async entry => { @@ -125,12 +130,15 @@ export function registerDeferredReceiptWork( }).from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, entry.companyId), eq(agentWakeupRequests.id, entry.id))); if (!current) return null; - const due = kind === "native" && current.status === "claimed" && current.claimedAt + const chatRetryAt = kind === "deferred" && !entry.forced && current.status === "deferred_issue_execution" + ? deferredChatWakeNextAttemptAt(current.payload) : null; + const delayedDue = kind === "native" && current.status === "claimed" && current.claimedAt ? current.claimedAt.getTime() + 60_000 : kind === "native" && current.status === "queued" && current.error ? current.updatedAt.getTime() + 30_000 : kind === "deferred" && current.status === "deferred_issue_execution" && !current.interruptedLegacy && (current.payload?.queuedCommentInterrupt || current.payload?.executionWait) ? current.updatedAt.getTime() + 30_000 : null; + const due = chatRetryAt === null ? delayedDue : Math.max(delayedDue ?? 0, chatRetryAt); if (due !== null && due > Date.now()) return { ...entry, dueAt: due, immediate: false }; } const errors: unknown[] = []; @@ -143,11 +151,12 @@ export function registerDeferredReceiptWork( else if (kind === "task_chat") await owner.settleTaskChat(scope); else { const failed = (error: unknown) => { if (!(error instanceof PersistedExecutionWaitRefusal)) errors.push(error); }; - try { await owner.resume({ ...scope, onError: failed }); } + try { await owner.resume({ ...scope, onError: failed, + onDeferredDeadline: at => { next = next === null ? at : Math.min(next, at); } }); } catch (error) { failed(error); } } if (errors.length) throw new AggregateError(errors, `Deferred receipt ${entry.id} could not settle`); - return next === null ? null : { ...entry, dueAt: next, immediate: false }; + return next === null ? null : { ...entry, dueAt: next, immediate: false, forced: false }; }, }, canRun); } diff --git a/server/src/services/heartbeat/queue.ts b/server/src/services/heartbeat/queue.ts index 92aa415c07d..221a9284839 100644 --- a/server/src/services/heartbeat/queue.ts +++ b/server/src/services/heartbeat/queue.ts @@ -83,6 +83,10 @@ import { executionFailureRetryCount } from "../execution-recovery-attempt.js"; import { slackMentionAllowsRunStart, resumeDeferredChatWake, + recordDeferredChatWakeDecline, + clearDeferredChatWakeRetry, + deferredChatWakeDeclineForError, + DEFERRED_CHAT_WAKE_RETRY_KEY, assertDurableChatWakeupReceipt, assertDurableChatWakeupRequest, withDurableChatAdmission, @@ -2197,6 +2201,27 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende // A server restart or a message/cleanup race can leave a deferred wake // after its owner has released the issue lock. Revisit it through the same // release admission, so recovery holds and operator Stops still apply. + const orphanedChatWakes = await db.select({ id: agentWakeupRequests.id, companyId: agentWakeupRequests.companyId, + payload: agentWakeupRequests.payload }).from(agentWakeupRequests) + .where(and(scope.companyId ? eq(agentWakeupRequests.companyId, scope.companyId) : undefined, + scope.requestId ? eq(agentWakeupRequests.id, scope.requestId) : undefined, + eq(agentWakeupRequests.status, "deferred_issue_execution"), isNull(agentWakeupRequests.runId), + sql`${agentWakeupRequests.idempotencyKey} like 'chat-inbound:%'`, + sql`EXISTS (SELECT 1 FROM chat_actions chat_wake_source WHERE chat_wake_source.company_id = ${agentWakeupRequests.companyId} + AND chat_wake_source.id = ${agentWakeupRequests.id} AND chat_wake_source.kind = 'inbound_wakeup')`, + sql`NOT EXISTS (SELECT 1 FROM issues chat_wake_issue WHERE chat_wake_issue.company_id = ${agentWakeupRequests.companyId} + AND chat_wake_issue.id::text = ${agentWakeupRequests.payload}->>'issueId')`)) + .limit(50); + for (const wake of orphanedChatWakes) { + await recordDeferredChatWakeDecline(db, { companyId: wake.companyId, issueId: String(wake.payload?.issueId), + requestId: wake.id }, { settle: "task_missing" }).then(recorded => { + if (recorded) logger.warn({ requestId: wake.id, reason: recorded.reason, outcome: recorded.outcome, attempts: recorded.attempts }, + "saved chat source could not resume after recovery"); + }).catch(err => { + scope.onError?.(err); + logger.warn({ err, requestId: wake.id }, "saved chat source could not record its resume outcome"); + }); + } const strandedQueues = await db.select({ wake: agentWakeupRequests }) .from(agentWakeupRequests) .innerJoin(issues, and(eq(issues.companyId, agentWakeupRequests.companyId), @@ -2214,6 +2239,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende ), sql`${agentWakeupRequests.payload}->>'mutation' = 'interaction'`, dependencyResolvedWakePayloadSql, assignmentWakePayloadSql), sql`${agentWakeupRequests.payload}->'queuedCommentInterrupt' is null`, + scope.requestId ? undefined : sql`coalesce((${agentWakeupRequests.payload} #>> ${`{${DEFERRED_CHAT_WAKE_RETRY_KEY},nextAttemptAt}`})::timestamptz <= now(), true)`, sql`NOT EXISTS (SELECT 1 FROM heartbeat_runs live_issue_run WHERE live_issue_run.company_id = ${issues.companyId} AND (live_issue_run.context_snapshot->>'issueId' = ${issues.id}::text @@ -2240,17 +2266,29 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${String(wake.payload?.issueId)}`, or(isNull(heartbeatRuns.nativeIssueId), sql`${heartbeatRuns.nativeIssueId}::text = ${String(wake.payload?.issueId)}`), )).orderBy(desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id)).limit(1); - await db.update(agentWakeupRequests).set({ updatedAt: new Date() }).where(and( + if (!wake.idempotencyKey?.startsWith("chat-inbound:")) await db.update(agentWakeupRequests).set({ updatedAt: new Date() }).where(and( eq(agentWakeupRequests.id, wake.id), eq(agentWakeupRequests.status, "deferred_issue_execution"), )); if (!latest || !latest.finishedAt || !isHeartbeatRunTerminalStatus(latest.status)) continue; if (latest.runtimeMode !== "legacy" && latest.runtimeMode !== "native") continue; if (wake.idempotencyKey?.startsWith("chat-inbound:")) { - await resumeDeferredChatWake(db, { companyId: wake.companyId, agentId: wake.agentId, - issueId: String(wake.payload?.issueId), requestId: wake.id }).catch(err => { - scope.onError?.(err); - logger.warn({ requestId: wake.id }, "saved chat source could not resume after recovery"); - }); + const chatScope = { companyId: wake.companyId, issueId: String(wake.payload?.issueId), requestId: wake.id }; + await resumeDeferredChatWake(db, { ...chatScope, agentId: wake.agentId, recoverySweep: true }) + .then(decline => decline ?? null, err => err instanceof PersistedExecutionWaitRefusal ? null : deferredChatWakeDeclineForError(err)) + .then(async decline => { + if (!decline) { + if (wake.payload?.[DEFERRED_CHAT_WAKE_RETRY_KEY]) await clearDeferredChatWakeRetry(db, chatScope); + return; + } + const recorded = await recordDeferredChatWakeDecline(db, chatScope, decline); + if (!recorded) return; + logger.warn({ requestId: wake.id, reason: recorded.reason, outcome: recorded.outcome, attempts: recorded.attempts, + silent: "silent" in recorded ? recorded.silent : undefined }, "saved chat source could not resume after recovery"); + if (recorded.outcome === "retry") scope.onDeferredDeadline?.(recorded.nextAttemptAt); + }).catch(err => { + scope.onError?.(err); + logger.warn({ err, requestId: wake.id }, "saved chat source could not record its resume outcome"); + }); continue; } const releaseSource = `${latest.companyId}:${String(wake.payload?.issueId)}:${latest.id}:${latest.sourceVersion}`; diff --git a/server/src/services/issue-assignment-wakeup.ts b/server/src/services/issue-assignment-wakeup.ts index 3081d377d4a..f8f8e3375eb 100644 --- a/server/src/services/issue-assignment-wakeup.ts +++ b/server/src/services/issue-assignment-wakeup.ts @@ -36,6 +36,7 @@ export function queueIssueAssignmentWakeup(input: { /** Latest issue comment that caused this wakeup. Included in both payload * and context so the heartbeat can build the exact turn that was requested. */ wakeCommentId?: string | null; + wakeCommentIds?: string[]; /** Closed, server-derived omission counts for provider attachments on the * exact wake comment. These are prompt diagnostics, never authorization. */ attachmentOmissionReasons?: Record | null; @@ -69,6 +70,7 @@ export function queueIssueAssignmentWakeup(input: { source: input.contextSource, ...(input.taskKey ? { taskKey: input.taskKey } : {}), ...(input.wakeCommentId ? { wakeCommentId: input.wakeCommentId } : {}), + ...(input.wakeCommentIds?.length ? { wakeCommentIds: input.wakeCommentIds } : {}), ...(input.chatConversationId ? { chatConversationId: input.chatConversationId } : {}), ...(input.wakeCommentId && input.attachmentOmissionReasons ? {