diff --git a/server/src/services/chat-channels/github/acknowledgement-work.ts b/server/src/services/chat-channels/github/acknowledgement-work.ts index 60e0db1cb7a..fca3560053b 100644 --- a/server/src/services/chat-channels/github/acknowledgement-work.ts +++ b/server/src/services/chat-channels/github/acknowledgement-work.ts @@ -1,4 +1,4 @@ -import { readGitHubResponseRun } from "./response-run-state.js"; +import { readGitHubResponseRuns, type GitHubResponseRunRead } from "./response-run-state.js"; import { githubRunReplyState } from "../../chat-run-publications.js"; import { and, asc, eq, gt, isNotNull, or, sql } from "drizzle-orm"; import { chatActions, chatConversations, chatEndpointLeases, chatEndpointResources, @@ -57,16 +57,34 @@ export function registerGitHubAcknowledgementWork( actionId ? eq(chatActions.id, actionId) : undefined, )).orderBy(asc(chatActions.id)).limit(100); } - async function entry(row: Awaited>[number]): Promise { - const { latestRun, ownsLatestRequest } = await readGitHubResponseRun(db, { - companyId: row.companyId, endpointId: row.endpointId, agentId: row.agentId, - issueId: row.issueId, deliveryId: row.deliveryId!, sourceMessageId: row.sourceMessageId, - }); - // Execution success alone does not decide whether a final response exists. - // Presentation/publication commits invalidate this parked request. - if (row.issueId && ownsLatestRequest && latestRun?.nativePresentationPending && - await githubRunReplyState(db, { companyId: row.companyId, endpointId: row.endpointId, - issueId: row.issueId, runId: latestRun.id }) === "none") return null; + type Row = Awaited>[number]; + async function entry(row: Row, read: GitHubResponseRunRead): Promise { + // A request whose requester provenance changed stays due, so the + // acknowledgement owner revokes it. It must not stop the rest of the page. + if (!("forbidden" in read)) { + const { latestRun, ownsLatestRequest } = read; + // Execution success alone does not decide whether a final response exists. + // Presentation/publication commits invalidate this parked request. + if (row.issueId && ownsLatestRequest && latestRun?.nativePresentationPending && + await githubRunReplyState(db, { companyId: row.companyId, endpointId: row.endpointId, + issueId: row.issueId, runId: latestRun.id }) === "none") return null; + } + return schedule(row); + } + /** The entries of a page, by position, from one batched run-state read. */ + async function entries(rows: Row[]) { + const reads = await readGitHubResponseRuns(db, rows.map(row => ({ companyId: row.companyId, endpointId: row.endpointId, + agentId: row.agentId, issueId: row.issueId, deliveryId: row.deliveryId!, sourceMessageId: row.sourceMessageId }))); + const values: Array = []; + for (const [index, row] of rows.entries()) values.push(await entry(row, reads[index]!)); + return values; + } + async function current(actionId: string) { + const [row] = await page(undefined, undefined, actionId); + return row ? (await entries([row]))[0] ?? null : null; + } + /** When the request is due, from its own row. */ + function schedule(row: Row): Entry | null { let dueAt = row.status === "failed" ? Date.parse(String(row.result?.retryAt)) : 0; if (!Number.isFinite(dueAt)) throw new Error("GitHub acknowledgement has an invalid retry deadline"); const fast = row.fast; @@ -89,23 +107,24 @@ export function registerGitHubAcknowledgementWork( (!scope.endpointId || value.endpointId === scope.endpointId) && (!scope.repositoryId || value.repositoryId === scope.repositoryId) && (!scope.number || value.number === scope.number)), load: async (scope?: Scope, signal?: AbortSignal) => { - const entries: Entry[] = []; + const loaded: Entry[] = []; let cursor: string | undefined; while (canRun() && !signal?.aborted) { const rows = await page(scope, cursor); - for (const row of rows) { const value = await entry(row); if (value) entries.push(value); } - if (rows.length < 100) return entries; + for (const value of await entries(rows)) if (value) loaded.push(value); + if (rows.length < 100) return loaded; cursor = rows[rows.length - 1].id; } throw signal?.reason ?? new Error("GitHub acknowledgement recovery stopped"); }, check: async (value: Entry, signal?: AbortSignal) => { - const [row] = await page(undefined, undefined, value.id); - const current = row ? await entry(row) : null; - if (!current || current.dueAt > Date.now() || !canRun() || signal?.aborted) return current; - await acknowledge(current.deliveryId, () => canRun() && !signal?.aborted); + const due = await current(value.id); + if (!due || due.dueAt > Date.now() || !canRun() || signal?.aborted) return due; + await acknowledge(due.deliveryId, () => canRun() && !signal?.aborted); + // A request that is still owed keeps its saved deadline. The next check + // reads its run state again before it acknowledges. const [remaining] = await page(undefined, undefined, value.id); - return remaining ? await entry(remaining) : null; + return remaining ? schedule(remaining) : null; }, }, canRun); } diff --git a/server/src/services/chat-channels/github/response-execution.ts b/server/src/services/chat-channels/github/response-execution.ts index cb9ca365a2e..2812d3311d2 100644 --- a/server/src/services/chat-channels/github/response-execution.ts +++ b/server/src/services/chat-channels/github/response-execution.ts @@ -1,6 +1,6 @@ import type { Db } from "@paperclipai/db"; import { githubRunReplyState } from "../../chat-run-publications.js"; -import { readGitHubResponseRun } from "./response-run-state.js"; +import { readGitHubResponseRun, type GitHubResponseRunRead } from "./response-run-state.js"; export { responseRunColumns as githubResponseRunColumns } from "./response-run-state.js"; export type GitHubResponseExecutionInput = { @@ -14,8 +14,11 @@ export type GitHubResponseExecutionInput = { deliveryCreatedAt: Date; }; -export async function githubResponseExecution(db: Db, input: GitHubResponseExecutionInput) { - const { latestRun, ownsLatestRequest } = await readGitHubResponseRun(db, input); +/** `read` is this request's state from a batched page read, if the caller has it. */ +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 } = state; const requestRunning = ownsLatestRequest && latestRun?.status === "running"; const terminal = latestRun && ["succeeded", "failed", "interrupted", "timed_out", "cancelled"].includes(latestRun.status); const run = terminal && (ownsLatestRequest || input.issueStatus === "blocked") ? latestRun : null; diff --git a/server/src/services/chat-channels/github/response-run-state.test.ts b/server/src/services/chat-channels/github/response-run-state.test.ts index c59865a1466..ea409c26661 100644 --- a/server/src/services/chat-channels/github/response-run-state.test.ts +++ b/server/src/services/chat-channels/github/response-run-state.test.ts @@ -4,7 +4,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { chatMessageLinks, createDb, heartbeatRuns, type Db } from "@paperclipai/db"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js"; import { chatRunSourceMessageId } from "../run-origin.js"; -import { readGitHubResponseRun, responseRunColumns } from "./response-run-state.js"; +import { readGitHubResponseRun, readGitHubResponseRuns, responseRunColumns } from "./response-run-state.js"; const support = await getEmbeddedPostgresTestSupport(); const suite = support.supported ? describe : describe.skip; @@ -195,6 +195,18 @@ suite("GitHub response run state", () => { .toEqual(new Set(["native", "legacy"])); }, 120_000); + it("reads a page of requests in one latest-run statement with the state each single read returns", async () => { + const all = inputs(); + const single = []; + for (const input of all) single.push(await readGitHubResponseRun(db, input)); + const statements: string[] = [], prior = db.$client.options.debug; + db.$client.options.debug = (_connection, query) => { statements.push(query); }; + let batch; + try { batch = await readGitHubResponseRuns(db, all); } finally { db.$client.options.debug = prior; } + expect(batch).toEqual(single); + expect(statements.filter(query => /from "heartbeat_runs"|join "heartbeat_runs"/.test(query))).toHaveLength(1); + }, 120_000); + it("reads a few runs of the issue, not the agent's whole run history", async () => { const tenant = tenants[0]!; const request = tenant.requests[0]!; 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 8060536ddf4..0e169a4edc7 100644 --- a/server/src/services/chat-channels/github/response-run-state.ts +++ b/server/src/services/chat-channels/github/response-run-state.ts @@ -1,6 +1,7 @@ -import { and, eq, sql } from "drizzle-orm"; +import { and, eq, sql, type SQL } from "drizzle-orm"; import { chatMessageLinks, heartbeatRuns, type Db } from "@paperclipai/db"; -import { chatRunSourceMessageId } from "../run-origin.js"; +import type { HttpError } from "../../../errors.js"; +import { chatRunSourceMessageId, chatRunSourceMessageIds } from "../run-origin.js"; export const responseRunColumns = { id: heartbeatRuns.id, @@ -47,35 +48,97 @@ export const responseRunColumns = { 'wakeCommentIds', ${heartbeatRuns.contextSnapshot}->'wakeCommentIds' )`, }; -/** Shared request ownership and presentation state for delivery and recovery. */ -export async function readGitHubResponseRun(db: Db, input: { + +export type GitHubResponseRunInput = { companyId: string; endpointId: string; agentId: string; issueId: string | null; deliveryId: string; sourceMessageId: string | null; -}) { - const { issueId } = input; - if (!issueId) return { latestRun: undefined, ownsLatestRequest: false }; - const latestRunId = sql`(select latest.id from ( - (select r.id, r.created_at from ${heartbeatRuns} r - where r.company_id = ${input.companyId} and r.native_issue_id = ${issueId} and r.agent_id = ${input.agentId} - order by r.created_at desc, r.id desc limit 1) - union all - (select r.id, r.created_at from ${heartbeatRuns} r - where r.company_id = ${input.companyId} and r.native_issue_id is null - and r.context_snapshot->>'issueId' = ${issueId} and r.agent_id = ${input.agentId} - order by r.created_at desc, r.id desc limit 1) - ) latest order by latest.created_at desc, latest.id desc limit 1)`; - const wokeForRequest = sql`exists (select 1 from ${chatMessageLinks} l - where l.company_id = ${input.companyId} and l.endpoint_id = ${input.endpointId} - and l.delivery_id = ${input.deliveryId} and l.direction = 'inbound' - and (l.comment_id::text = ${heartbeatRuns.contextSnapshot}->>'wakeCommentId' - or coalesce(${heartbeatRuns.contextSnapshot}->'wakeCommentIds', '[]'::jsonb) ? l.comment_id::text))`; - const [row] = await db.select({ ...responseRunColumns, wokeForRequest }).from(heartbeatRuns) - .where(and(eq(heartbeatRuns.companyId, input.companyId), sql`${heartbeatRuns.id} = ${latestRunId}`)); +}; +type RunRow = Omit>[number], "ordinal">; +export type GitHubResponseRunState = { latestRun: Omit | undefined; ownsLatestRequest: boolean }; +/** The state of one request of a batch, or the 403 that its single read throws. */ +export type GitHubResponseRunRead = GitHubResponseRunState | { forbidden: HttpError }; + +/** A value of the run reads: a literal of one request in a single read, or a + * column of the request row in a batch read. */ +type Value = string | SQL; +type Of = Record<"companyId" | "endpointId" | "agentId" | "issueId" | "deliveryId", Value>; + +/** The assigned agent's latest run bound to the issue, where a run's issue is + * coalesce(native_issue_id, context_snapshot->>'issueId'). The two precedence + * branches are disjoint and each uses an issue index. */ +const latestRunId = (of: Of) => sql`(select latest.id from ( + (select r.id, r.created_at from ${heartbeatRuns} r + where r.company_id = ${of.companyId}::uuid and r.native_issue_id = ${of.issueId}::uuid and r.agent_id = ${of.agentId}::uuid + order by r.created_at desc, r.id desc limit 1) + union all + (select r.id, r.created_at from ${heartbeatRuns} r + where r.company_id = ${of.companyId}::uuid and r.native_issue_id is null + and r.context_snapshot->>'issueId' = ${of.issueId}::text and r.agent_id = ${of.agentId}::uuid + order by r.created_at desc, r.id desc limit 1) + ) latest order by latest.created_at desc, latest.id desc limit 1)`; +/** Whether the run woke for one of the request's inbound comments. */ +const wokeForRequest = (of: Of) => sql`exists (select 1 from ${chatMessageLinks} l + where l.company_id = ${of.companyId}::uuid and l.endpoint_id = ${of.endpointId}::uuid + and l.delivery_id = ${of.deliveryId}::uuid and l.direction = 'inbound' + and (l.comment_id::text = ${heartbeatRuns.contextSnapshot}->>'wakeCommentId' + or coalesce(${heartbeatRuns.contextSnapshot}->'wakeCommentIds', '[]'::jsonb) ? l.comment_id::text))`; + +const request = sql.identifier("github_response_request"); +const column = (name: string) => sql`${request}.${sql.identifier(name)}`; +const columns: Array<[keyof Of, string]> = [["companyId", "company_id"], ["endpointId", "endpoint_id"], + ["agentId", "agent_id"], ["issueId", "issue_id"], ["deliveryId", "delivery_id"]]; + +/** The latest run of each request, in one statement. For each request row the + * lateral subquery is the single read with the request columns in place of + * the literals. */ +async function readRunRows(db: Db, inputs: Array) { + const of = Object.fromEntries(columns.map(([key, name]) => [key, column(name)])) as Of; + return db.select({ ordinal: sql`${column("ordinal")}`.mapWith(Number), ...responseRunColumns, + wokeForRequest: wokeForRequest(of) }) + .from(sql`unnest(${sql.join(columns.map(([key]) => sql`${sql.param(inputs.map(input => input[key]))}::uuid[]`), sql`, `)}) + with ordinality as ${request}(${sql.join([...columns.map(([, name]) => sql.identifier(name)), sql.identifier("ordinal")], sql`, `)}) + cross join lateral (select ${latestRunId(of)} as id) latest_request_run`) + .innerJoin(heartbeatRuns, and(sql`${heartbeatRuns.id} = latest_request_run.id`, + sql`${heartbeatRuns.companyId} = ${column("company_id")}`)); +} + +function ownership(input: GitHubResponseRunInput, row: RunRow | undefined, originMessageId: string | null): GitHubResponseRunState { if (!row) return { latestRun: undefined, ownsLatestRequest: false }; const { wokeForRequest: requestRunIsLatest, ...latestRun } = row; - const originMessageId = latestRun.activeIdentityContextId ? await chatRunSourceMessageId(db, latestRun, - { allowLegacyWakeComment: true, provider: "github" }) : null; const ownsLatestRequest = requestRunIsLatest || (!!input.sourceMessageId && originMessageId === input.sourceMessageId); return { latestRun, ownsLatestRequest }; } + +/** 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 }; + const of = { ...input, issueId }; + const [row] = await db.select({ ...responseRunColumns, wokeForRequest: wokeForRequest(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); +} + +/** `readGitHubResponseRun` for a page of requests: one latest-run read for the + * whole page, then one batched provenance check of its distinct runs, which + * reuses the single check's reads. Each request gets, by position, the state a + * separate call returns or the 403 that call throws. */ +export async function readGitHubResponseRuns(db: Db, inputs: GitHubResponseRunInput[]): Promise { + const bound = inputs.flatMap((input, index) => input.issueId ? [{ index, input: { ...input, issueId: input.issueId } }] : []); + const found = new Map(); + if (bound.length) { + for (const { ordinal, ...row } of await readRunRows(db, bound.map(entry => entry.input))) found.set(bound[ordinal - 1]!.index, row); + } + 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 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); + }); +} diff --git a/server/src/services/chat-channels/github/response-sweep-scope.test.ts b/server/src/services/chat-channels/github/response-sweep-scope.test.ts index f162a1689ec..cdbd263c5fe 100644 --- a/server/src/services/chat-channels/github/response-sweep-scope.test.ts +++ b/server/src/services/chat-channels/github/response-sweep-scope.test.ts @@ -68,7 +68,12 @@ suite("GitHub response sweep scopes", () => { builder.from = ((...args: Parameters) => { const selection = from(...args), execute = selection.execute.bind(selection); selection.execute = (async () => { - if (selection.toSQL().sql.includes(`'wakeCommentIds', '[]'::jsonb) ?`)) reads += 1; + // Count requests whose run state is read. A batched read names its + // requests in arrays, so count the requests rather than statements. + const query = selection.toSQL(); + if (query.sql.includes(`'wakeCommentIds', '[]'::jsonb) ?`)) { + reads += Array.isArray(query.params[0]) ? query.params[0].length : 1; + } return execute(); }) as typeof selection.execute; return selection; diff --git a/server/src/services/chat-channels/github/terminal-response-work.test.ts b/server/src/services/chat-channels/github/terminal-response-work.test.ts index cd28076b6f2..d4b6362dcef 100644 --- a/server/src/services/chat-channels/github/terminal-response-work.test.ts +++ b/server/src/services/chat-channels/github/terminal-response-work.test.ts @@ -7,6 +7,7 @@ import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } fro import { createDeliveryWorkCoordinator } from "../../delivery-work-coordinator.js"; import { DELIVERY_QUEUES, notifyDeliveryWork } from "../../delivery-work-notifications.js"; import { idleWorkSnapshot } from "../../task-admission.js"; +import { registerGitHubAcknowledgementWork } from "./acknowledgement-work.js"; import { registerGitHubTerminalResponseWork } from "./terminal-response-work.js"; const support = await getEmbeddedPostgresTestSupport(); @@ -40,7 +41,9 @@ describe.skipIf(!support.supported)("GitHub terminal response sweep backlog", () afterAll(async () => { await db?.$client.end({ timeout: 1 }); await temporary?.cleanup(); }); type Request = { issueId: string; deliveryId: string; actionId: string; commentId: string }; - async function seed() { + /** `waiting`: processed, non-final responses as on staging. `received`: every + * request still owes its first acknowledgement. */ + async function seed(shape: "waiting" | "received" = "waiting") { const client = db.$client; const companyId = randomUUID(), agentId = randomUUID(); await db.insert(companies).values({ id: companyId, name: "GitHub backlog", issuePrefix: `G${companyId.slice(0, 7)}` }); @@ -75,13 +78,14 @@ describe.skipIf(!support.supported)("GitHub terminal response sweep backlog", () const latest = request === STALE_PER_ISSUE; const [action] = await db.insert(chatActions).values({ companyId, endpointId: endpoint, conversationId: conversation, deliveryId: delivery, kind: "github_response_comment", providerActionId: `github_response:${delivery}`, - payload: { agentId }, status: "processed", - result: { id: String(1_000 + index), url: `https://github.com/paperclipai/paperclip/pull/${issueNumber}#c${index}`, + payload: { agentId }, status: shape === "received" ? "received" : "processed", + result: shape === "received" ? null : { id: String(1_000 + index), + url: `https://github.com/paperclipai/paperclip/pull/${issueNumber}#c${index}`, final: latest, versionAt: new Date(base).toISOString(), ...(latest ? {} : { code: code(index) }) }, updatedAt: new Date(base + index * 60_000) }).returning(); requests.push({ issueId: issue, deliveryId: delivery, actionId: action!.id, commentId: comment }); } - stale.push(...requests.slice(0, STALE_PER_ISSUE)); + stale.push(...(shape === "received" ? requests : requests.slice(0, STALE_PER_ISSUE))); // The latest run answered the newest request, through its identity context. const runId = randomUUID(), contextId = randomUUID(); await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, nativeIssueId: issue, issueId: issue, @@ -95,13 +99,14 @@ describe.skipIf(!support.supported)("GitHub terminal response sweep backlog", () return { companyId, agentId, endpointId: endpoint as string, stale, runs }; } - async function start() { + async function start(register: typeof registerGitHubTerminalResponseWork = registerGitHubTerminalResponseWork) { coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, canReconcile: () => true, onError: error => errors.push(error) }); - const worker = registerGitHubTerminalResponseWork(db, coordinator, async deliveryId => { + const worker = register(db, coordinator, async deliveryId => { acknowledged.push(deliveryId); // Stand in for the real acknowledgement, which records a final response. - await db.update(chatActions).set({ result: sql`${chatActions.result} || '{"final": true}'::jsonb`, updatedAt: new Date() }) + await db.update(chatActions).set({ status: "processed", updatedAt: new Date(), + result: sql`coalesce(${chatActions.result}, '{}'::jsonb) || '{"final": true}'::jsonb` }) .where(and(eq(chatActions.deliveryId, deliveryId), eq(chatActions.kind, "github_response_comment"))); }, () => true); await worker.ready; @@ -150,6 +155,31 @@ describe.skipIf(!support.supported)("GitHub terminal response sweep backlog", () expect(await finals(f.stale.map(request => request.actionId))).toBe(0); }, 300_000); + it("reads a page of waiting responses in a constant number of statements", async () => { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true }); + await seed(); + const first = await observe(async () => { await start(); await advance(5_000); }); + console.info(`terminal response sweep, first pass: ${first.statements} statements ` + + `(${first.provenance} run identity reads) for ${STALE} rows in 2 pages`); + expect(acknowledged).toEqual([]); + // Per page: the page, its latest runs, the batched context and link reads, and the wait keys. + expect(first.provenance).toBeLessThanOrEqual(2); + expect(first.statements).toBeLessThanOrEqual(2 * 5); + }, 300_000); + + it("acknowledges every owed request of a page when one run's requester provenance changed", async () => { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true }); + const f = await seed("received"); + // One task's latest run lost its accepted identity context, so reading its + // requester provenance is forbidden. Only that task's requests are affected. + await db.update(runIdentityContexts).set({ status: "revoked" }).where(eq(runIdentityContexts.runId, f.runs[3]!.runId)); + const first = await observe(async () => { await start(registerGitHubAcknowledgementWork); await advance(30_000); }); + console.info(`acknowledgement sweep: ${first.statements} statements (${first.provenance} run identity reads) ` + + `for ${f.stale.length} owed requests`); + expect(new Set(acknowledged)).toEqual(new Set(f.stale.map(request => request.deliveryId))); + expect(acknowledged).toHaveLength(f.stale.length); + }, 300_000); + it("still settles a waiting response once a run that owns it ends", async () => { vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true }); const f = await seed(); 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 49c8447c25a..fdbb18d8ef5 100644 --- a/server/src/services/chat-channels/github/terminal-response-work.ts +++ b/server/src/services/chat-channels/github/terminal-response-work.ts @@ -5,6 +5,7 @@ import type { createDeliveryWorkCoordinator } from "../../delivery-work-coordina import { DELIVERY_QUEUES } from "../../delivery-work-notifications.js"; import { registerScopedDeadlineWork } from "../../scoped-deadline-work.js"; import { githubResponseExecution } from "./response-execution.js"; +import { readGitHubResponseRuns, type GitHubResponseRunRead } from "./response-run-state.js"; import { githubResponseReconstructionIntervalMs, type GitHubResponseSweepScope as Scope } from "./response-sweep-scope.js"; import { HttpError } from "../../../errors.js"; type Entry = { id: string; companyId: string; endpointId: string; deliveryId: string; @@ -87,12 +88,9 @@ export function registerGitHubTerminalResponseWork( * recorded. A wait on the owning run's reply or presentation is never * recorded: a publication that commits it changes no wait-key input, and a * restart can lose the hint that its lease release sends. */ - async function entry(row: Row): Promise { - const pending: Entry = { id: row.id, companyId: row.companyId, endpointId: row.endpointId, deliveryId: row.deliveryId!, - issueId: row.issueId, conversationId: row.conversationId, repositoryId: row.repositoryId, - number: row.number ? Number(row.number) : null, dueAt: row.leaseExpiresAt ? Date.parse(row.leaseExpiresAt) : 0 }; + async function entry(row: Row, read: GitHubResponseRunRead): Promise { try { - const execution = await githubResponseExecution(db, { ...row, agentId: row.agentId!, deliveryId: row.deliveryId! }); + const execution = await githubResponseExecution(db, { ...row, agentId: row.agentId!, deliveryId: row.deliveryId! }, read); if (execution.body === undefined || execution.reply === "unsettled" || (execution.paused && row.result?.pausedVersion === execution.version)) return { parkable: !execution.presentationPending && execution.reply === "none" }; @@ -101,7 +99,24 @@ export function registerGitHubTerminalResponseWork( // Keep this request eligible for the acknowledgement owner's authority // check and cancellation; it must not poison discovery for other requests. } - return pending; + return pending(row); + } + /** The request's entry, before its run state is read. */ + function pending(row: Row): Entry { + return { id: row.id, companyId: row.companyId, endpointId: row.endpointId, deliveryId: row.deliveryId!, + issueId: row.issueId, conversationId: row.conversationId, repositoryId: row.repositoryId, + number: row.number ? Number(row.number) : null, dueAt: row.leaseExpiresAt ? Date.parse(row.leaseExpiresAt) : 0 }; + } + /** The entries of a page, by position, from one batched run-state read. */ + async function entries(rows: Row[], signal?: AbortSignal) { + const reads = await readGitHubResponseRuns(db, rows.map(row => ({ companyId: row.companyId, endpointId: row.endpointId, + agentId: row.agentId!, issueId: row.issueId, deliveryId: row.deliveryId!, sourceMessageId: row.sourceMessageId }))); + const values: Array>> = []; + for (const [index, row] of rows.entries()) { + if (!canRun() || signal?.aborted) throw signal?.reason ?? new Error("GitHub terminal-response recovery stopped"); + values.push(await entry(row, reads[index]!)); + } + return values; } /** Record the wait of requests that cannot progress yet. A request whose row * changed after the read gets no key and is read again. The write leaves @@ -119,8 +134,8 @@ export function registerGitHubTerminalResponseWork( async function current(actionId: string) { const [row] = await page(undefined, undefined, actionId); if (!row) return null; - const value = await entry(row); - if (!("parkable" in value)) return value; + const [value] = await entries([row]); + if (!("parkable" in value!)) return value!; if (value.parkable) await park([row]); return null; } @@ -135,18 +150,17 @@ export function registerGitHubTerminalResponseWork( (!scope.endpointId || value.endpointId === scope.endpointId) && (!scope.repositoryId || value.repositoryId === scope.repositoryId) && (!scope.number || value.number === scope.number)), load: async (scope?: Scope, signal?: AbortSignal) => { - const entries: Entry[] = []; + const loaded: Entry[] = []; let cursor: string | undefined; while (canRun() && !signal?.aborted) { const rows = await page(scope, cursor); + const values = await entries(rows, signal); const waiting: Row[] = []; - for (const row of rows) { - if (!canRun() || signal?.aborted) throw signal?.reason ?? new Error("GitHub terminal-response recovery stopped"); - const value = await entry(row); - if (!("parkable" in value)) entries.push(value); else if (value.parkable) waiting.push(row); + for (const [index, value] of values.entries()) { + if (!("parkable" in value)) loaded.push(value); else if (value.parkable) waiting.push(rows[index]!); } await park(waiting); - if (rows.length < 100) return entries; + if (rows.length < 100) return loaded; cursor = rows[rows.length - 1].id; } throw signal?.reason ?? new Error("GitHub terminal-response recovery stopped"); @@ -155,7 +169,10 @@ export function registerGitHubTerminalResponseWork( const due = await current(value.id); if (!due || due.dueAt > Date.now() || !canRun() || signal?.aborted) return due; await acknowledge(due.deliveryId, () => canRun() && !signal?.aborted); - return current(value.id); + // Keep a request that still waits for the next check, which reads its + // run state again before it acknowledges. One check reads it once. + const [remaining] = await page(undefined, undefined, value.id); + return remaining ? pending(remaining) : null; }, }, canRun); }