diff --git a/server/src/__tests__/chat-channels/github-review-publications.integration.test.ts b/server/src/__tests__/chat-channels/github-review-publications.integration.test.ts index 76a9569b66b..32b41be8a4c 100644 --- a/server/src/__tests__/chat-channels/github-review-publications.integration.test.ts +++ b/server/src/__tests__/chat-channels/github-review-publications.integration.test.ts @@ -271,8 +271,8 @@ describeEmbeddedPostgres("chat channels: github review publications", () => { it("reconciles a GitHub working comment when execution stops without a publication", async () => { const f = await toolReplyFixture("github:paperclipai/paperclip:418"); - await db.update(heartbeatRuns).set({ status: "failed", errorCode: "execution_finalization_deadline_exceeded" }) - .where(eq(heartbeatRuns.id, f.run.id)); + await db.update(heartbeatRuns).set({ status: "failed", errorCode: "execution_finalization_deadline_exceeded", + updatedAt: new Date(Date.now() - 31 * 60_000) }).where(eq(heartbeatRuns.id, f.run.id)); await db.update(issues).set({ status: "blocked" }).where(eq(issues.id, f.conversation.issueId!)); await githubResponseCommentService(db, f.providerFetch).processPending(); expect(f.responseComments.size).toBe(1); diff --git a/server/src/__tests__/chat-channels/github-review-response-maintenance.integration.test.ts b/server/src/__tests__/chat-channels/github-review-response-maintenance.integration.test.ts index 8d20974043c..d24faf28ef1 100644 --- a/server/src/__tests__/chat-channels/github-review-response-maintenance.integration.test.ts +++ b/server/src/__tests__/chat-channels/github-review-response-maintenance.integration.test.ts @@ -19,6 +19,7 @@ vi.mock("@chat-adapter/telegram", async (importOriginal) => { return candidate ? import(/* @vite-ignore */ candidate) : importOriginal(); }); import { githubResponseCommentService } from "../../services/chat-github-response-comments.js"; +import { createDeliveryWorkCoordinator } from "../../services/delivery-work-coordinator.js"; import { githubChatReviewService } from "../../services/chat-github-reviews.js"; import { type TestDb, describeEmbeddedPostgres, makeThread, makeMessage } from "./providers.js"; import { createChatChannelHarness } from "./harness.js"; @@ -129,6 +130,104 @@ describeEmbeddedPostgres("chat channels: github review response maintenance", () await responses.processPending(); expect(f.responseWrites).toHaveLength(writes); }); + it.each([["recent", 0, "See the [latest response]"], ["too old", 31 * 60_000, "stopped before completing"]] as const)( + "waits for the automatic continuation of a failed GitHub request run: %s", async (_label, failedAgoMs, settled) => { + const f = await toolReplyFixture("github:paperclipai/paperclip:418:rc:4100"); + const [firstId] = [...f.responseComments.keys()]; + await db.update(heartbeatRuns).set({ status: "failed", runtimeMode: "native", + errorCode: "native_continuation_requires_reconciliation", updatedAt: new Date(Date.now() - failedAgoMs) }) + .where(eq(heartbeatRuns.id, f.run.id)); + const responses = githubResponseCommentService(db, f.providerFetch); + const stopped = { companyId: f.companyId, endpointId: f.endpoint.id, issueId: f.conversation.issueId!, runId: f.run.id, + body: "This turn stopped before completing. See the Paperclip task for details." }; + if (failedAgoMs === 0) { + await expect(responses.failRun(stopped)).rejects.toMatchObject({ status: 409 }); + await responses.processPending(); + expect(f.responseComments.get(firstId)?.body).toContain("Working on this"); + await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.assignedAgentId, status: "succeeded", + runtimeMode: "native", nativePhase: "committed", retryOfRunId: f.run.id, + contextSnapshot: { issueId: f.conversation.issueId }, resultJson: { presentationDecision: { + schema: "paperclip.run_presentation_decision.v1", chosenSource: "none", commentAction: "none" } } }); + const [main] = await db.insert(chatConversations).values({ companyId: f.companyId, endpointId: f.endpoint.id, + issueId: f.conversation.issueId, externalConversationId: "github:paperclipai/paperclip", + externalLabel: "paperclipai/paperclip", externalThreadId: "github:paperclipai/paperclip:418" }).returning(); + await db.insert(chatActions).values({ companyId: f.companyId, endpointId: f.endpoint.id, conversationId: main.id, + kind: "github_review_publication", providerActionId: `github_publication:${randomUUID()}`, status: "processed", + payload: { operation: "assessment", session: { companyId: f.companyId, issueId: f.conversation.issueId, + runId: randomUUID(), agentId: f.assignedAgentId } }, + result: { summaryUrl: "https://github.com/paperclipai/paperclip/pull/418#issuecomment-5" } }); + await responses.processPending(); + } else { + await responses.failRun(stopped); + } + expect(f.responseComments.get(firstId)?.body).toContain(settled); + }); + it("keeps waiting while the automatic continuations of a failed GitHub request run also fail", async () => { + const f = await toolReplyFixture("github:paperclipai/paperclip:418:rc:4100"); + const [firstId] = [...f.responseComments.keys()]; + const failed = (ago: number) => ({ status: "failed", runtimeMode: "native" as const, + errorCode: "native_continuation_requires_reconciliation", updatedAt: new Date(Date.now() - ago) }); + await db.update(heartbeatRuns).set(failed(50 * 60_000)).where(eq(heartbeatRuns.id, f.run.id)); + const [first] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.assignedAgentId, + ...failed(40 * 60_000), retryOfRunId: f.run.id, contextSnapshot: { issueId: f.conversation.issueId } }).returning(); + const [second] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.assignedAgentId, + ...failed(60_000), contextSnapshot: { issueId: f.conversation.issueId, previousRunId: first.id } }).returning(); + const responses = githubResponseCommentService(db, f.providerFetch); + await responses.processPending(); + expect(f.responseComments.get(firstId)?.body).toContain("Working on this"); + await db.update(heartbeatRuns).set({ updatedAt: new Date(Date.now() - 31 * 60_000) }).where(eq(heartbeatRuns.id, second.id)); + await responses.processPending(); + expect(f.responseComments.get(firstId)?.body).toContain("stopped before completing"); + }); + it("links a request awaiting a continuation to a later response without waiting for the deadline", async () => { + const f = await toolReplyFixture("github:paperclipai/paperclip:418:rc:4100"); + const [firstId] = [...f.responseComments.keys()]; + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true }); + const errors: unknown[] = []; + const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: error => errors.push(error) }); + try { + await db.update(heartbeatRuns).set({ status: "failed", runtimeMode: "native", + errorCode: "native_continuation_requires_reconciliation", updatedAt: new Date(Date.now() - 60_000) }) + .where(eq(heartbeatRuns.id, f.run.id)); + const [main] = await db.insert(chatConversations).values({ companyId: f.companyId, endpointId: f.endpoint.id, + issueId: f.conversation.issueId, externalConversationId: "github:paperclipai/paperclip", + externalLabel: "paperclipai/paperclip", externalThreadId: "github:paperclipai/paperclip:418" }).returning(); + await db.insert(chatActions).values({ companyId: f.companyId, endpointId: f.endpoint.id, conversationId: main.id, + kind: "github_review_publication", providerActionId: `github_publication:${randomUUID()}`, status: "processed", + payload: { operation: "assessment", session: { companyId: f.companyId, issueId: f.conversation.issueId, + runId: randomUUID(), agentId: f.assignedAgentId } }, + result: { summaryUrl: "https://github.com/paperclipai/paperclip/pull/418#issuecomment-5" } }); + await githubResponseCommentService(db, f.providerFetch).registerTerminalResponseWork(coordinator, () => true).ready; + await vi.waitFor(() => expect(f.responseComments.get(firstId)?.body).toContain("See the [latest response]"), + { timeout: 10_000 }); + expect(errors).toEqual([]); + } finally { + await coordinator.stop(); + vi.useRealTimers(); + } + }); + it("settles a request still waiting for a continuation once the wait expires, through the registered worker", async () => { + const f = await toolReplyFixture("github:paperclipai/paperclip:418:rc:4100"); + const [firstId] = [...f.responseComments.keys()]; + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true }); + const errors: unknown[] = []; + const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: error => errors.push(error) }); + try { + await db.update(heartbeatRuns).set({ status: "failed", runtimeMode: "native", + errorCode: "native_continuation_requires_reconciliation", updatedAt: new Date(Date.now() - 29 * 60_000) }) + .where(eq(heartbeatRuns.id, f.run.id)); + await githubResponseCommentService(db, f.providerFetch).registerTerminalResponseWork(coordinator, () => true).ready; + await vi.advanceTimersByTimeAsync(5_000); + expect(f.responseComments.get(firstId)?.body).toContain("Working on this"); + await vi.advanceTimersByTimeAsync(2 * 60_000); + await vi.waitFor(() => expect(f.responseComments.get(firstId)?.body).toContain("stopped before completing"), + { timeout: 10_000 }); + expect(errors).toEqual([]); + } finally { + await coordinator.stop(); + vi.useRealTimers(); + } + }); it.each(["in_progress", "blocked"] as const)("links the latest response when a request's run ends without its own reply: %s", async issueStatus => { const f = await toolReplyFixture("github:paperclipai/paperclip:418:rc:4100"); diff --git a/server/src/services/chat-channels/github/response-execution.ts b/server/src/services/chat-channels/github/response-execution.ts index c1033f3b38f..2d73f6fa9d9 100644 --- a/server/src/services/chat-channels/github/response-execution.ts +++ b/server/src/services/chat-channels/github/response-execution.ts @@ -34,6 +34,16 @@ export function settlesFromRequestRun(state: GitHubResponseRunState, issueStatus issueStatus !== "blocked" && !!state.finishedRequestRun; } +export const GITHUB_CONTINUATION_WAIT_MS = 30 * 60_000; + +export function awaitsAutomaticContinuation( + latestRun: { continuesAutomatically: boolean; updatedAt: Date }, + continuesRequest: boolean, + now = Date.now(), +) { + return continuesRequest && latestRun.continuesAutomatically && now - latestRun.updatedAt.getTime() < GITHUB_CONTINUATION_WAIT_MS; +} + /** The notice that points a request at the latest response its agent published * on the same pull request or issue after the request arrived, if any. */ export async function latestResponseNotice(db: Db, @@ -47,7 +57,7 @@ export async function latestResponseNotice(db: Db, export async function githubResponseExecution(db: Db, input: GitHubResponseExecutionInput, read?: GitHubResponseRunRead) { const state = read ?? await readGitHubResponseRun(db, input); if ("forbidden" in state) throw state.forbidden; - const { latestRun, ownsLatestRequest, finishedRequestRun } = state; + const { latestRun, ownsLatestRequest, finishedRequestRun, latestContinuesRequestRun } = state; const requestRunning = ownsLatestRequest && latestRun?.status === "running"; const terminal = latestRun && finished(latestRun.status); // Once the task is idle, a request whose own run finished earlier settles @@ -70,19 +80,22 @@ export async function githubResponseExecution(db: Db, input: GitHubResponseExecu const taskFinished = ["done", "cancelled"].includes(input.issueStatus); // Precedence: a later published response is more useful to the reader than // any notice about this request's own run, including a refused reply. + const awaitingContinuation = !!run && !!latestRun && !taskFinished && + awaitsAutomaticContinuation(latestRun, run.id === latestRun.id || (run.id === requestRun?.id && latestContinuesRequestRun)); const outcome: keyof typeof STATUS_TEXT | "link" | "waiting" | null = presentationPending ? null : !run ? paused ? "paused" : null : reply === "confirmed" ? "handled" : paused ? "paused" : latestResponse ? "link" - : run.passiveResponseWait && !isMainPullThread(input.threadId) && !taskFinished ? "waiting" + : awaitingContinuation || (run.passiveResponseWait && !isMainPullThread(input.threadId) && !taskFinished) ? "waiting" : run.responsePublicationFailed ? "publish_failed" : run.status === "succeeded" ? "ended" : "stopped"; const body = outcome === null || outcome === "waiting" ? undefined : outcome === "link" ? latestResponse! : STATUS_TEXT[outcome]; return { - body, outcome, paused, reply, running: requestRunning, presentationPending, passiveResponseWait, + body, outcome, paused, reply, running: requestRunning, presentationPending, passiveResponseWait, awaitingContinuation, + continuationDeadline: outcome === "waiting" && awaitingContinuation && latestRun ? latestRun.updatedAt.getTime() + GITHUB_CONTINUATION_WAIT_MS : undefined, versionAt: run ? new Date(Math.max(run.updatedAt.getTime(), input.deliveryCreatedAt.getTime())) : paused ? input.deliveryCreatedAt : undefined, version: JSON.stringify([latestRun?.id ?? null, latestRun?.status ?? null, diff --git a/server/src/services/chat-channels/github/response-run-state.ts b/server/src/services/chat-channels/github/response-run-state.ts index 0f023d3f3a6..bec3426994c 100644 --- a/server/src/services/chat-channels/github/response-run-state.ts +++ b/server/src/services/chat-channels/github/response-run-state.ts @@ -2,6 +2,8 @@ import { and, eq, inArray, sql, type SQL } from "drizzle-orm"; import { chatMessageLinks, heartbeatRuns, runIdentityContexts, type Db } from "@paperclipai/db"; import type { HttpError } from "../../../errors.js"; import { chatRunSourceMessageId, chatRunSourceMessageIds } from "../run-origin.js"; +import { continuesAutomaticallySql } from "../../continuation-cause.js"; +import { canonicalExecutionUuid } from "../../execution-identity.js"; /** Run statuses after which a run publishes nothing more for its request. */ export const FINISHED_RUN_STATUSES = ["succeeded", "failed", "interrupted", "timed_out", "cancelled"] as const; @@ -19,6 +21,7 @@ export const responseRunColumns = { issueId: heartbeatRuns.issueId, status: heartbeatRuns.status, updatedAt: heartbeatRuns.updatedAt, + continuesAutomatically: sql`coalesce(${continuesAutomaticallySql("heartbeat_runs")}, false)`, // Terminal execution can precede native presentation commit. Until its // durable decision exists, missing output is undecided rather than failure. nativePresentationPending: sql`coalesce( @@ -65,7 +68,8 @@ type RunRow = Omit>[number], "ordinal">; type ResponseRun = Omit; export type GitHubResponseRunState = { latestRun: ResponseRun | undefined; ownsLatestRequest: boolean; /** The latest finished run that woke for this request, which can differ from the latest run. */ - finishedRequestRun: ResponseRun | null }; + finishedRequestRun: ResponseRun | null; + latestContinuesRequestRun: boolean }; /** The state of one request of a batch, or the 403 that its single read throws. */ export type GitHubResponseRunRead = GitHubResponseRunState | { forbidden: HttpError }; @@ -140,14 +144,43 @@ async function readRunRows(db: Db, inputs: Array): GitHubResponseRunState { - if (!row) return { latestRun: undefined, ownsLatestRequest: false, finishedRequestRun: null }; + finished: Map, continuations: Set): GitHubResponseRunState { + if (!row) return NO_RUN; const { wokeForRequest: requestRunIsLatest, requestRunId, ...latestRun } = row; const ownsLatestRequest = requestRunIsLatest || (!!input.sourceMessageId && originMessageId === input.sourceMessageId); return { latestRun, ownsLatestRequest, - finishedRequestRun: !requestRunId ? null : requestRunId === latestRun.id ? latestRun : finished.get(requestRunId) ?? null }; + finishedRequestRun: !requestRunId ? null : requestRunId === latestRun.id ? latestRun : finished.get(requestRunId) ?? null, + latestContinuesRequestRun: !!requestRunId && continuations.has(`${latestRun.id}:${requestRunId}`) }; +} + +const continuedRunId = (run: SQL) => sql`coalesce(${canonicalExecutionUuid(sql`${run}.context_snapshot->>'previousRunId'`)}, + ${run}.retry_of_run_id, ${canonicalExecutionUuid(sql`${run}.context_snapshot->>'retryOfRunId'`)})`; + +async function readContinuations(db: Db, rows: RunRow[]) { + const pairs = [...new Map(rows.filter(row => row.continuesAutomatically && row.requestRunId && row.requestRunId !== row.id) + .map(row => [`${row.id}:${row.requestRunId}`, row])).values()]; + const found = new Set(); + if (!pairs.length) return found; + const result = await db.execute<{ latest_id: string; request_id: string }>(sql`with recursive + pairs(company_id, latest_id, request_id) as (select * from unnest( + ${sql.param(pairs.map(row => row.companyId))}::uuid[], ${sql.param(pairs.map(row => row.id))}::uuid[], + ${sql.param(pairs.map(row => row.requestRunId))}::uuid[])), + chain(company_id, latest_id, request_id, run_id, depth) as ( + select p.company_id, p.latest_id, p.request_id, ${continuedRunId(sql`r`)}, 1 + from pairs p join ${heartbeatRuns} r on r.id = p.latest_id and r.company_id = p.company_id + union all + select c.company_id, c.latest_id, c.request_id, ${continuedRunId(sql`r`)}, c.depth + 1 + from chain c join ${heartbeatRuns} r on r.id = c.run_id and r.company_id = c.company_id + where c.run_id <> c.request_id and c.depth < 20) + select distinct latest_id, request_id from chain where run_id = request_id`); + for (const row of result) + found.add(`${row.latest_id}:${row.request_id}`); + return found; } /** The response columns of the earlier finished runs of the rows, in one statement. */ @@ -162,14 +195,15 @@ async function readFinishedRuns(db: Db, rows: RunRow[]) { /** Shared request ownership and presentation state for delivery and recovery. */ export async function readGitHubResponseRun(db: Db, input: GitHubResponseRunInput): Promise { const { issueId } = input; - if (!issueId) return { latestRun: undefined, ownsLatestRequest: false, finishedRequestRun: null }; + if (!issueId) return NO_RUN; const of = { ...input, issueId }; const [row] = await db.select({ ...responseRunColumns, wokeForRequest: wokeForRequest(of), requestRunId: finishedRequestRunId(of) }).from(heartbeatRuns) .where(and(eq(heartbeatRuns.companyId, input.companyId), sql`${heartbeatRuns.id} = ${latestRunId(of)}`)); const originMessageId = row?.activeIdentityContextId ? await chatRunSourceMessageId(db, row, { allowLegacyWakeComment: true, provider: "github" }) : null; - return ownership(input, row, originMessageId, await readFinishedRuns(db, row ? [row] : [])); + const rows = row ? [row] : []; + return ownership(input, row, originMessageId, await readFinishedRuns(db, rows), await readContinuations(db, rows)); } /** `readGitHubResponseRun` for a page of requests: one latest-run read for the @@ -185,11 +219,12 @@ export async function readGitHubResponseRuns(db: Db, inputs: GitHubResponseRunIn const runs = [...new Map([...found.values()].filter(row => row.activeIdentityContextId).map(row => [row.id, row])).values()]; const checked = await chatRunSourceMessageIds(db, runs, { allowLegacyWakeComment: true, provider: "github" }); const finished = await readFinishedRuns(db, [...found.values()]); + const continuations = await readContinuations(db, [...found.values()]); const origins = new Map(runs.map((run, index) => [run.id, checked[index]!])); return inputs.map((input, index) => { const row = found.get(index); const origin = row ? origins.get(row.id) : undefined; if (origin && "forbidden" in origin) return { forbidden: origin.forbidden }; - return ownership(input, row, origin?.messageId ?? null, finished); + return ownership(input, row, origin?.messageId ?? null, finished, continuations); }); } diff --git a/server/src/services/chat-channels/github/terminal-response-work.ts b/server/src/services/chat-channels/github/terminal-response-work.ts index 5195a749c35..8602d248356 100644 --- a/server/src/services/chat-channels/github/terminal-response-work.ts +++ b/server/src/services/chat-channels/github/terminal-response-work.ts @@ -98,6 +98,10 @@ export function registerGitHubTerminalResponseWork( async function entry(row: Row, read: GitHubResponseRunRead): Promise { try { const execution = await githubResponseExecution(db, { ...row, agentId: row.agentId!, deliveryId: row.deliveryId! }, read); + if (execution.continuationDeadline !== undefined) { + const entry = pending(row); + return { ...entry, dueAt: Math.max(entry.dueAt, execution.continuationDeadline) }; + } if (execution.body === undefined || execution.reply === "unsettled" || (execution.paused && row.result?.pausedVersion === execution.version)) return { parkable: !execution.presentationPending && execution.reply === "none" }; diff --git a/server/src/services/chat-github-response-comments.ts b/server/src/services/chat-github-response-comments.ts index f4c3300e0f7..1492238d73b 100644 --- a/server/src/services/chat-github-response-comments.ts +++ b/server/src/services/chat-github-response-comments.ts @@ -6,7 +6,7 @@ import { type Db, } from "@paperclipai/db"; import { registerGitHubTerminalResponseWork } from "./chat-channels/github/terminal-response-work.js"; -import { githubResponseExecution, githubResponseRunColumns as responseRunColumns, latestResponseNotice } from "./chat-channels/github/response-execution.js"; +import { awaitsAutomaticContinuation, githubResponseExecution, githubResponseRunColumns as responseRunColumns, latestResponseNotice } from "./chat-channels/github/response-execution.js"; import { FINISHED_RUN_STATUSES, finishedRunStatusSql, runBoundToIssue, runWokeForComment } from "./chat-channels/github/response-run-state.js"; import { notifyChatResponseAvailability } from "./chat-response-availability.js"; import { registerGitHubAcknowledgementWork } from "./chat-channels/github/acknowledgement-work.js"; @@ -424,6 +424,7 @@ export function githubResponseCommentService(db: Db, fetchImpl = fetch) { if (latest?.id !== run.id) throw forbidden("A newer GitHub run owns the response"); if ((await responseForRequest())?.result?.final === true) throw forbidden("GitHub request already has a final response"); if (current.nativePresentationPending) throw conflict("GitHub native response presentation is still being resolved"); + if (awaitsAutomaticContinuation(current, true)) throw conflict("GitHub run continues automatically"); if (isMainPullResponse(source) && current.passiveResponseWait) throw forbidden("GitHub run intentionally yielded without a new response"); if (await githubRunReplyState(db, input) !== "none") throw conflict("GitHub reply is still being resolved"); };