perf(chat): read the run state of a GitHub response sweep page in one batch (#21711)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The GitHub chat channel has two sweeps for request response
comments: the acknowledgement sweep (`acknowledgement-work.ts`) and the
terminal-response sweep (`terminal-response-work.ts`). Each reads pages
of up to 100 requests.
> - For each loaded request, both sweeps call `readGitHubResponseRun`
one row at a time. That is one latest-run statement, plus the run
identity context read and the message link read of
`chatRunSourceMessageId`. A page of 100 requests costs about 300
statements.
> - On paperclip.staging, those two provenance reads ran at about 13/s
each. #21705 stops the idle backlog from being reloaded. This PR makes
the reads that remain cost a constant number of statements per page.
> - The per-row read also had a failure mode. A 403 from one run's
provenance check aborted the acknowledgement sweep's whole page, so no
request of that company was acknowledged until the 403 went away.
> - This pull request adds a batched `readGitHubResponseRuns` and uses
it once per page in both sweeps.
> - The benefit is a constant number of statements per page, and a
provenance failure that affects only its own request.

## Linked Issues or Issue Description

Refs #21705 (the same sweeps; that PR stops reloading requests that
cannot progress).

No issue exists. This describes the problem with the fields of
`.github/ISSUE_TEMPLATE/bug_report.yml`.

**What happened?**

On paperclip.staging (2026-11-15, about 01:45–02:25Z),
`provenanceReads.context` (`select … from run_identity_contexts where id
= $1 and run_id = $2 and company_id = $3 and status = $4 limit $5`) ran
at 13.37/s, and `provenanceReads.link` (`select
chat_conversations.issue_id, chat_endpoints.provider from
chat_message_links join … where chat_message_links.company_id = $3 and
comment_id = $4 …`) ran at 13.20/s. Both GitHub response sweeps reach
them through `readGitHubResponseRun` → `chatRunSourceMessageId(db, run,
{ provider: "github" })`, once for each loaded row. `load()` costs one
page read plus three statements per row. `check()` read the run state
twice for each due request (before and after the acknowledgement).

In the acknowledgement sweep, a 403 from `chatRunSourceMessageId` (for
example, a run whose identity context is no longer accepted) threw out
of `entry()` and aborted the whole page. The terminal sweep already kept
such a row due, so the acknowledgement owner could revoke it.

**Expected behavior**

A page of requests costs a constant number of statements. A failure for
one run affects only the requests of that run.

**Steps to reproduce**

1. Create 120 GitHub response requests on 30 tasks. Give each task an
ended run with an accepted identity context.
2. Register the terminal-response sweep. On master, the first pass costs
one page read plus three statements per row.
3. Mark the requests `received`, revoke one run's identity context, and
register the acknowledgement sweep. On master, the load fails with a
403, and none of the 150 requests is acknowledged.

**Paperclip version or commit**

master at ea8c734cb9 (includes #21705).

## What Changed

- `server/src/services/chat-channels/github/response-run-state.ts`:
- The latest-run subquery and the "woke for this request" check are
built once, from literals (single read) or from the columns of a request
row (batch read). The single read keeps the same query shape.
- New `readGitHubResponseRuns(db, inputs)`. It reads the latest run of
every request of a page in one statement: `unnest(…) with ordinality`
and a lateral latest-run subquery, then a join to `heartbeat_runs` by id
and company. It then calls the existing `chatRunSourceMessageIds(db,
runs, { allowLegacyWakeComment: true, provider: "github" })` once for
the page's distinct runs. That helper reuses `provenanceReads`, so the
scope, status filters and joins are the same as the single check.
Results map back by position. A run whose provenance check is forbidden
gives `{ forbidden }` for its requests only.
- `server/src/services/chat-channels/github/response-execution.ts`:
`githubResponseExecution` takes an optional pre-read state. It throws a
`{ forbidden }` state as the same 403 that the single read throws.
- `server/src/services/chat-channels/github/terminal-response-work.ts`:
`load()` reads each page's run state with one `readGitHubResponseRuns`
call. `check()` reads the run state once: after the acknowledgement it
reads the row only, and keeps a request that is still owed for the next
check, which reads its run state again first.
- `server/src/services/chat-channels/github/acknowledgement-work.ts`:
the same batching. A forbidden provenance check keeps that request due,
so the acknowledgement owner revokes it (`authorization_changed`), and
the rest of the page continues. After an acknowledgement, a still-owed
request keeps the deadline from its own row (retry time, fast-response
expiry or lease).
- Tests:
- `terminal-response-work.test.ts`: `reads a page of waiting responses
in a constant number of statements` and `acknowledges every owed request
of a page when one run's requester provenance changed`.
- `response-run-state.test.ts`: `reads a page of requests in one
latest-run statement with the state each single read returns` compares
the batch with the single read for every seeded binding and wake link.
- `response-sweep-scope.test.ts`: `rebuilds parked requests once per
interval for company-wide hints` counted run-state *statements* as a
proxy for requests reloaded. With batching, one statement reads a whole
page, so the count dropped from 6 to 2 and the test failed in CI. The
behavior it guards must stay: a company-wide rebuild reloads every
eligible request once per interval, and repeated hints inside the
interval reload none. The test now counts the requests that each
run-state read names (the length of a batched read's request arrays, or
1 for a single read). The expectations stay 6 / `[6, 0, 0, 0, 0]` / 6,
so the test still proves the same rebuild behavior.

No GitHub comment behavior changes.

## Verification

- `pnpm vitest run
src/services/chat-channels/github/terminal-response-work.test.ts`
(server), staging-shaped fixtures (120 waiting requests on 30 tasks;
codes null / `acknowledgement_unconfirmed` /
`acknowledgement_superseded`):
- before (#21705 only): the first pass costs 364 statements, with 120
run identity reads. With one revoked context, the acknowledgement sweep
acknowledges 0 of 150 owed requests. The 2 new tests fail (red).
- after: the first pass costs 10 statements, with 2 run identity reads
(per page: page, latest runs, context, link, wait keys). All 150 owed
requests are acknowledged, including the 5 whose provenance is
forbidden. 8 of 8 tests pass (green). All 7 files under
`chat-channels/github/`: 60 passed. `idle-completed-history.test.ts`: 75
passed.
- On master before #21705, the first pass was 362 statements, and every
company rebuild repeated it.
- `pnpm vitest run
src/services/chat-channels/github/response-run-state.test.ts`: 3 passed.
- `pnpm vitest run src/__tests__/chat-channels.integration.test.ts -t
"terminal|acknowledg|GitHub response|response comment|GitHub review"`:
192 passed.
- `pnpm typecheck` (server): passed.
- `pnpm verify` on #21705 selected 2,738 of 3,565 files (close to the
full suite). I relied on the focused runs and required CI, per
AGENTS.md.

## Risks

- The batched latest-run statement must return the same run as the
single read. The equivalence test covers native and legacy bindings,
ties, other agents and other companies.
- `check()` no longer reads the run state again right after an
acknowledgement. A request that is still owed keeps the deadline from
its own row and is read in full at its next check. The acknowledgement
still revalidates everything before it writes.
- A database error still rejects the whole page, as before. Only the 403
provenance decision is isolated per request.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edits, local PostgreSQL tests) and
extended reasoning.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [ ] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-14 21:15:08 -06:00
1 parent 8cc26221af
commit f4f4902707
7 files changed
+221 -72

No files matched your search

@@ -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<ReturnType<typeof page>>[number]): Promise<Entry | null> {
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<ReturnType<typeof page>>[number];
async function entry(row: Row, read: GitHubResponseRunRead): Promise<Entry | null> {
// 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<Entry | null> = [];
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);
}
@@ -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;
@@ -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]!;
@@ -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<boolean>`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<Awaited<ReturnType<typeof readRunRows>>[number], "ordinal">;
export type GitHubResponseRunState = { latestRun: Omit<RunRow, "wokeForRequest"> | 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<boolean>`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<GitHubResponseRunInput & { issueId: string }>) {
const of = Object.fromEntries(columns.map(([key, name]) => [key, column(name)])) as Of;
return db.select({ ordinal: sql<number>`${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<GitHubResponseRunState> {
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<GitHubResponseRunRead[]> {
const bound = inputs.flatMap((input, index) => input.issueId ? [{ index, input: { ...input, issueId: input.issueId } }] : []);
const found = new Map<number, RunRow>();
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);
});
}
@@ -68,7 +68,12 @@ suite("GitHub response sweep scopes", () => {
builder.from = ((...args: Parameters<typeof from>) => {
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;
@@ -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();
@@ -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<Entry | { parkable: boolean }> {
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<Entry | { parkable: boolean }> {
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<Awaited<ReturnType<typeof entry>>> = [];
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);
}