Files
PaperClipAI/server/src/services/chat-channels/github/response-run-state.test.ts
T
DottaandClaude Opus 5.5 f4f4902707 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>
2026-11-14 21:15:08 -06:00

237 lines
15 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { and, desc, eq, or, sql } from "drizzle-orm";
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, readGitHubResponseRuns, responseRunColumns } from "./response-run-state.js";
const support = await getEmbeddedPostgresTestSupport();
const suite = support.supported ? describe : describe.skip;
type Input = Parameters<typeof readGitHubResponseRun>[1];
async function previousReadGitHubResponseRun(db: Db, input: Input) {
const [requestRun] = await db.select({ runId: heartbeatRuns.id }).from(heartbeatRuns).innerJoin(chatMessageLinks, and(
eq(chatMessageLinks.companyId, input.companyId), eq(chatMessageLinks.endpointId, input.endpointId),
eq(chatMessageLinks.deliveryId, input.deliveryId), eq(chatMessageLinks.direction, "inbound"),
or(sql`${chatMessageLinks.commentId}::text = ${heartbeatRuns.contextSnapshot}->>'wakeCommentId'`,
sql`coalesce(${heartbeatRuns.contextSnapshot}->'wakeCommentIds', '[]'::jsonb) ? ${chatMessageLinks.commentId}::text`),
)).where(and(eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.agentId, input.agentId),
sql`coalesce(${heartbeatRuns.nativeIssueId}::text, ${heartbeatRuns.contextSnapshot}->>'issueId') = ${input.issueId}`))
.orderBy(desc(heartbeatRuns.createdAt)).limit(1);
const [latestRun] = await db.select(responseRunColumns).from(heartbeatRuns).where(and(
eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.agentId, input.agentId),
sql`coalesce(${heartbeatRuns.nativeIssueId}::text, ${heartbeatRuns.contextSnapshot}->>'issueId') = ${input.issueId}`,
)).orderBy(desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id)).limit(1);
const originMessageId = latestRun?.activeIdentityContextId ? await chatRunSourceMessageId(db, latestRun,
{ allowLegacyWakeComment: true, provider: "github" }) : null;
const ownsLatestRequest = !!latestRun && (requestRun?.runId === latestRun.id ||
(!!input.sourceMessageId && originMessageId === input.sourceMessageId));
return { latestRun, ownsLatestRequest };
}
function random(seed: number) {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) >>> 0;
let value = Math.imul(state ^ (state >>> 15), 1 | state);
value = (value + Math.imul(value ^ (value >>> 7), 61 | value)) ^ value;
return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
};
}
type PlanNode = { "Relation Name"?: string; "Actual Loops"?: number; "Actual Rows"?: number;
"Rows Removed by Filter"?: number; "Rows Removed by Index Recheck"?: number; Plans?: PlanNode[] };
function heartbeatRunRowsRead(node: PlanNode): number {
const own = node["Relation Name"] === "heartbeat_runs" ? (node["Actual Loops"] ?? 0)
* ((node["Actual Rows"] ?? 0) + (node["Rows Removed by Filter"] ?? 0) + (node["Rows Removed by Index Recheck"] ?? 0)) : 0;
return own + (node.Plans ?? []).reduce((total, child) => total + heartbeatRunRowsRead(child), 0);
}
type Tenant = { companyId: string; endpointId: string; agentIds: [string, string];
requests: Array<{ issueId: string; deliveryId: string; inboundCommentId: string | null; outboundCommentId: string }> };
suite("GitHub response run state", () => {
let db!: Db;
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
const tenants: Tenant[] = [];
const history = 1_500;
async function seedTenant(index: number): Promise<Tenant> {
const client = db.$client;
const [{ company }] = await client.unsafe(`insert into companies (name, issue_prefix) values ($1, $2) returning id as company`,
[`Response ${index}`, `RS${index}`]);
const agentRows = await client.unsafe(`insert into agents (company_id, name) values ($1, 'GitHub agent'), ($1, 'Other agent')
returning id`, [company]);
const agentIds = agentRows.map(row => row.id as string) as [string, string];
const [{ application }] = await client.unsafe(`insert into tool_applications (company_id, application_key, name, type)
values ($1, 'github', 'GitHub', 'chat') returning id as application`, [company]);
const [{ connection }] = await client.unsafe(`insert into tool_connections (company_id, application_id, name, uid, transport, connection_purpose)
values ($1, $2, 'GitHub', $3, 'chat_sdk', 'channel') returning id as connection`, [company, application, `github-${index}`]);
const [{ endpoint }] = await client.unsafe(`insert into chat_endpoints (company_id, connection_id, provider, public_id, assigned_agent_id, status)
values ($1, $2, 'github', $3, $4, 'active') returning id as endpoint`, [company, connection, `response-${index}`, agentIds[0]]);
const requests: Tenant["requests"] = [];
for (let issueNumber = 1; issueNumber <= 60; issueNumber++) {
const [{ issue }] = await client.unsafe(`insert into issues (company_id, title, status) values ($1, $2, 'in_progress') returning id as issue`,
[company, `Issue ${issueNumber}`]);
const [{ conversation }] = await client.unsafe(`insert into chat_conversations (company_id, endpoint_id, issue_id,
external_conversation_id, external_label, external_thread_id)
values ($1, $2, $3, $4, $4, $4) returning id as conversation`, [company, endpoint, issue, `github:paperclipai/paperclip:${issueNumber}`]);
for (let request = 0; request < 1 + (issueNumber % 2); request++) {
const [{ delivery }] = await client.unsafe(`insert into chat_deliveries (company_id, endpoint_id, provider_event_id,
deduplication_key, event_kind, normalized_event, conversation_id, state)
values ($1, $2, $3, $3, 'message', '{}', $4, 'processed') returning id as delivery`,
[company, endpoint, `event-${issueNumber}-${request}`, conversation]);
const commentRows = await client.unsafe(`insert into issue_comments (company_id, issue_id, body)
values ($1, $2, 'Inbound'), ($1, $2, 'Outbound') returning id`, [company, issue]);
const inboundCommentId = issueNumber % 13 === 0 ? null : commentRows[0]!.id as string;
const outboundCommentId = commentRows[1]!.id as string;
await client.unsafe(`insert into chat_message_links (company_id, endpoint_id, conversation_id, delivery_id, comment_id,
provider_message_id, direction)
values ($1, $2, $3, $4, $5, $6, 'inbound'), ($1, $2, $3, $4, $7, $8, 'outbound')`,
[company, endpoint, conversation, delivery, inboundCommentId, `in-${issueNumber}-${request}`,
outboundCommentId, `out-${issueNumber}-${request}`]);
requests.push({ issueId: issue, deliveryId: delivery, inboundCommentId, outboundCommentId });
}
}
return { companyId: company, endpointId: endpoint, agentIds, requests };
}
async function seedRuns(seed: number) {
const next = random(seed);
const pick = <T,>(values: readonly T[]): T => values[Math.floor(next() * values.length)]!;
const base = Date.UTC(2026, 10, 1);
const rows: Array<typeof heartbeatRuns.$inferInsert> = [];
let timeline = 0;
for (const tenant of tenants) {
const other = tenants.find(candidate => candidate !== tenant)!;
const issueIds = [...new Set(tenant.requests.map(request => request.issueId))];
for (const issueId of issueIds) {
timeline += 1;
const requests = tenant.requests.filter(request => request.issueId === issueId);
const slots = Array.from({ length: 1 + Math.floor(next() * 6) }, (_, slot) => slot);
let linkedAt = new Set<number>();
for (const slot of slots) {
const tie = slot > 0 && next() < 0.3;
const minute = tie ? slot - 1 : slot;
const request = pick(requests);
let wake = pick(["none", "comment", "comments", "scalar", "sibling", "outbound", "foreign"] as const);
const links = wake === "comment" || wake === "comments" || wake === "scalar" || wake === "sibling";
if (links && linkedAt.has(minute)) wake = "none";
else if (links) linkedAt = new Set([...linkedAt, minute]);
const sibling = requests.find(candidate => candidate !== request) ?? request;
const foreignComment = pick(other.requests).inboundCommentId;
const wakeContext = wake === "comment" ? { wakeCommentId: request.inboundCommentId }
: wake === "comments" ? { wakeCommentIds: [randomUUID(), request.inboundCommentId] }
: wake === "scalar" ? { wakeCommentIds: request.inboundCommentId }
: wake === "outbound" ? { wakeCommentId: request.outboundCommentId }
: wake === "foreign" ? { wakeCommentId: foreignComment }
: wake === "sibling" ? { wakeCommentIds: [sibling.inboundCommentId] } : {};
const binding = pick(["native", "native", "legacy", "legacy", "nativeElsewhere", "otherCompany", "otherAgent"] as const);
const nativeIssueId = binding === "native" ? issueId : binding === "nativeElsewhere" ? pick(issueIds) : null;
rows.push({
id: randomUUID(),
companyId: binding === "otherCompany" ? other.companyId : tenant.companyId,
agentId: binding === "otherCompany" ? other.agentIds[0] : binding === "otherAgent" ? tenant.agentIds[1] : pick([tenant.agentIds[0], tenant.agentIds[0], tenant.agentIds[1]]),
scopeKind: nativeIssueId ? "issue" : "company",
issueId: nativeIssueId,
nativeIssueId,
status: pick(["queued", "running", "succeeded", "failed", "cancelled", "timed_out"]),
createdAt: new Date(base + timeline * 3_600_000 + minute * 60_000),
contextSnapshot: { issueId, ...wakeContext },
});
}
}
}
await db.insert(heartbeatRuns).values(rows);
}
beforeAll(async () => {
temporary = await startEmbeddedPostgresTestDatabase("paperclip-github-response-run-state-");
db = createDb(temporary.connectionString);
tenants.push(await seedTenant(0), await seedTenant(1));
await seedRuns(20261114);
await db.$client.unsafe(`insert into heartbeat_runs (company_id, agent_id, status, context_snapshot, created_at)
select $1::uuid, $2::uuid, 'succeeded', jsonb_build_object('issueId', gen_random_uuid()::text,
'prompt', (select string_agg(md5(random()::text || g::text || n::text), '') from generate_series(1, 64) g)),
timestamptz '2026-10-01' + (n || ' minutes')::interval from generate_series(1, ${history}) n`,
[tenants[0]!.companyId, tenants[0]!.agentIds[0]]);
await db.execute(sql`analyze`);
}, 120_000);
afterAll(async () => { await db?.$client.end(); await temporary?.cleanup(); });
function inputs(): Input[] {
const all: Input[] = [];
for (const tenant of tenants) {
const other = tenants.find(candidate => candidate !== tenant)!;
for (const request of tenant.requests) {
for (const agentId of [...tenant.agentIds, other.agentIds[0]]) {
all.push({ companyId: tenant.companyId, endpointId: tenant.endpointId, agentId, issueId: request.issueId,
deliveryId: request.deliveryId, sourceMessageId: request.inboundCommentId });
}
all.push({ companyId: tenant.companyId, endpointId: other.endpointId, agentId: tenant.agentIds[0], issueId: request.issueId,
deliveryId: request.deliveryId, sourceMessageId: null });
all.push({ companyId: tenant.companyId, endpointId: tenant.endpointId, agentId: tenant.agentIds[0], issueId: null,
deliveryId: request.deliveryId, sourceMessageId: null });
}
}
return all;
}
it("returns the latest run and request ownership the previous queries returned, for every run binding and wake link", async () => {
const before = [], after = [];
for (const input of inputs()) {
before.push(await previousReadGitHubResponseRun(db, input));
after.push(await readGitHubResponseRun(db, input));
}
expect(after).toEqual(before);
expect(before.filter(result => result.ownsLatestRequest).length).toBeGreaterThan(20);
expect(before.filter(result => result.latestRun && !result.ownsLatestRequest).length).toBeGreaterThan(20);
expect(before.filter(result => !result.latestRun).length).toBeGreaterThan(20);
expect(new Set(before.flatMap(result => result.latestRun ? [result.latestRun.nativeIssueId ? "native" : "legacy"] : [])))
.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]!;
const captured: Array<{ sql: string; params: unknown[] }> = [];
const capture = new Proxy(db, { get(target, key) {
if (key !== "select") return Reflect.get(target, key);
return (...fields: Parameters<typeof db.select>) => {
const builder = target.select(...fields), from = builder.from.bind(builder);
builder.from = ((...args: Parameters<typeof from>) => {
const selection = from(...args), execute = selection.execute.bind(selection);
selection.execute = (async () => { captured.push(selection.toSQL()); return execute(); }) as typeof selection.execute;
return selection;
}) as typeof builder.from;
return builder;
};
} });
await readGitHubResponseRun(capture as Db, { companyId: tenant.companyId, endpointId: tenant.endpointId,
agentId: tenant.agentIds[0], issueId: request.issueId, deliveryId: request.deliveryId, sourceMessageId: null });
expect(captured.length).toBeGreaterThan(0);
let rowsRead = 0;
for (const query of captured) {
const [row] = await db.$client.unsafe(`explain (analyze, format json) ${query.sql}`, query.params as never[]);
rowsRead += heartbeatRunRowsRead((row!["QUERY PLAN"] as Array<{ Plan: PlanNode }>)[0]!.Plan);
}
expect(rowsRead).toBeLessThan(history / 10);
}, 60_000);
});