perf(github): fix inherited review wait join and batch lookup plan (#23817)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - When an agent publishes a GitHub pull request review, the Paperclip
task waits in review for the next GitHub reply. Later runs on that task
inherit this wait.
> - Issue lists and inbox attention call
`readInheritedGitHubReviewWaits` to check all waiting runs of a company
in one batch (`readInheritedReviewsForKeys`).
> - In `readInheritedReviewsForKeys`, the join between
`chat_message_links` and `chat_conversations` matched only
`conversation_id` and omitted `endpoint_id`, while filtering
`comment_id`, `issue_id`, and `agent_id` through three separate `=
ANY(...)` arrays and joining every historical `chat_github_reviews` row
before `DISTINCT ON`.
> - On PostgreSQL with many endpoints and message links, the missing
leading `endpoint_id` column caused PostgreSQL to skip-scan
`chat_message_links_provider_message_uq (endpoint_id, conversation_id,
provider_message_id)` across all endpoints for every matched
conversation, reading hundreds of buffers per conversation. Separate `=
ANY(...)` arrays also allowed cross-key cartesian matching in SQL, and
joining all historical reviews forced extra `heartbeat_runs` lookups and
`assessment` JSONB detoasting before `DISTINCT ON` discarded older rows.
> - This pull request binds `chat_message_links.endpoint_id =
chat_conversations.endpoint_id` in both the single-key and batch
queries, replaces the three `= ANY(...)` arrays with deduplicated
`(comment_id, issue_id, agent_id)` tuples via `unnest(...)`, and selects
only the latest `chat_github_reviews` row per `(endpoint_id, issue_id)`
in a lateral subquery before joining `heartbeat_runs` and projecting
`assessment->'reviewedCommit'`.
> - The benefit is 25x-35x lower query execution time and 34x-50x fewer
shared buffer hits on realistic multi-endpoint batches, with exact
result equivalence and zero schema changes.

## Linked Issues or Issue Description

Refs #20673
Refs #20851

**What happened?**

`readInheritedReviewsForKeys` in
`server/src/services/chat-channels/github/review-wait.ts` ran slow
multi-second queries on hosted multi-tenant PostgreSQL instances when
listing in-review issues. `EXPLAIN (ANALYZE, BUFFERS)` showed PostgreSQL
skip-scanning `chat_message_links_provider_message_uq` on
`conversation_id = chat_conversations.id` without the leading
`endpoint_id` column, producing over 200 buffer hits per conversation.
The query also used three independent `= ANY(...)` array predicates
(allowing cross-key combinations in SQL) and joined all historical
`chat_github_reviews` rows to `heartbeat_runs` before `DISTINCT ON`
discarded older reviews.

**Expected behavior**

`readInheritedReviewsForKeys` should look up exact `(comment_id,
issue_id, agent_id)` keys using leading-prefix index scans
(`chat_message_links_company_comment_idx` or `(endpoint_id,
conversation_id)` on `chat_message_links_provider_message_uq`), avoid
cross-key matches in SQL, and join `heartbeat_runs` and project
`assessment->'reviewedCommit'` only for the latest review per key.

**Steps to reproduce**

1. Seed a PostgreSQL database with multiple chat endpoints (across
GitHub and other channels), tens of thousands of `chat_message_links`,
and 100-250 waiting GitHub PR tasks with 5-20 historical
`chat_github_reviews` rows each.
2. Run `VACUUM ANALYZE`.
3. Call `readInheritedGitHubReviewWaits` for 100 or 250 waiting runs and
run `EXPLAIN (ANALYZE, BUFFERS)` on the `chat_github_reviews` query.
4. Observe PostgreSQL skip-scanning
`chat_message_links_provider_message_uq` across all endpoints (over
100,000 shared buffer hits for 100 keys) and probing `heartbeat_runs`
once for every historical review.

**Paperclip version or commit**

`83f10b968d` (`master`)

**Deployment mode**

Self-hosted server

**Database mode**

External Postgres

## What Changed

- `server/src/services/chat-channels/github/review-wait.ts`:
- Added `eq(chatConversations.endpointId, chatMessageLinks.endpointId)`
to both `prepareInheritedReviewQuery` and `readInheritedReviewsForKeys`.
- Replaced the three independent `= ANY(...)` array predicates in
`readInheritedReviewsForKeys` with deduplicated `(comment_id, issue_id,
agent_id)` tuples via `unnest(...)`, matching
`chat_message_links.comment_id` with strict equality so
`chat_message_links_company_comment_idx` (`WHERE comment_id IS NOT
NULL`) is directly eligible and cross-key cartesian matches cannot occur
in SQL.
- Added `latestGitHubReviewSubquery` (`CROSS JOIN LATERAL ... ORDER BY
created_at DESC, id DESC LIMIT 1`) in `readInheritedReviewsForKeys` so
`heartbeat_runs` joins and `assessment->'reviewedCommit'` extraction run
only on the newest review per `(endpoint_id, issue_id)`, while retaining
outer `DISTINCT ON` ordering and shared `inheritedReviewFields`
projection with `prepareInheritedReviewQuery`.
- `server/src/__tests__/github-review-wait.test.ts`:
- Verified batch parity on malformed, null, and valid JSON `assessment`
values.
- Added regression coverage proving cross-key `(comment_id, issue_id,
agent_id)` combinations return zero rows from SQL and mismatched
`chat_message_links.endpoint_id` values return `null` in both single and
batch reads.
- Added an `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)` regression test
over multi-endpoint data confirming `chat_message_links` never
skip-scans without `endpoint_id`, `heartbeat_runs` joins only one row
per key across multiple historical reviews, and raw wire rows stay under
1,000 bytes.

## Verification

- Audited `packages/db/src/schema/chat_channels.ts` and all production
write sites of `chat_message_links` (`chat-channels.ts`,
`email-channels.ts`, `chat-teams-file-publication.ts`,
`interactions/callbacks.ts`, `publications/transport.ts`,
`publications/worker.ts`) and `chat_conversations` updates: every insert
writes matching `endpointId` for the conversation and no production path
mutates `endpointId` on either table.
- Ran checks on commit `e76ca43f1714b31fd47fd9149661090dd3a98483`:
  - `pnpm check:module-boundaries` — passed.
- `node scripts/check-test-budget.mjs --base origin/master` — passed
(`113 nightly suites validated, 1 test file(s) checked`).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/github-review-wait.test.ts
src/__tests__/github-review-check-state.test.ts
src/__tests__/issue-list-review-wait-authorization.integration.test.ts
src/services/native-runtime/external-review-wait.test.ts` — 4 test
files, 26/26 tests passed.
- `pnpm --filter @paperclipai/server typecheck` — passed across all 7
typecheck layers.
- Captured apples-to-apples before (`origin/master`) vs. after
(`8a7b1939db4d3ee66c6fdfebcac38032c2a2895b`) `EXPLAIN (ANALYZE,
BUFFERS)` on embedded PostgreSQL 18.1 with `VACUUM ANALYZE` (253
`chat_endpoints` including 3 GitHub + 20 Slack in the target company and
230 in other companies, 2,980 `chat_conversations`, 89,400
`chat_message_links`, 4,200 `chat_github_reviews` with ~8 KB TOASTed
`assessment` JSONB, 4,680 `heartbeat_runs`, 7 warm samples per query,
exact result equivalence asserted with `assert.deepEqual`):

| Batch | Before (`origin/master`) | After (this PR) | Improvement |
| --- | --- | --- | --- |
| 100 keys (5 reviews/PR) | 21.85 ms median (21.75-22.03 ms), 109,761
shared buffer hits (`chat_message_links_provider_message_uq` skip-scan:
29,237 searches, 105,656 hits; `heartbeat_runs`: 500 loops, 1,500 hits)
| 0.68 ms median (0.63-0.75 ms), 2,208 shared buffer hits
(`chat_message_links_company_comment_idx`: 100 searches, 400 hits;
`heartbeat_runs`: 100 loops, 300 hits) | 32.1x faster, 49.7x fewer
buffers |
| 100 keys (20 reviews/PR) | 28.49 ms median (28.02-28.78 ms), 124,939
shared buffer hits (`chat_message_links_provider_message_uq` skip-scan:
30,229 searches, 108,902 hits; `heartbeat_runs`: 2,000 loops, 6,000
hits) | 1.11 ms median (1.09-1.36 ms), 3,619 shared buffer hits
(`chat_message_links_company_comment_idx`: 100 searches, 400 hits;
`heartbeat_runs`: 100 loops, 300 hits) | 25.7x faster, 34.5x fewer
buffers |
| 250 keys (5 reviews/PR) | 58.24 ms median (57.77-58.62 ms), 278,373
shared buffer hits (`chat_message_links_provider_message_uq` skip-scan:
73,820 searches, 268,080 hits; `heartbeat_runs`: 1,250 loops, 3,750
hits) | 1.68 ms median (1.59-1.76 ms), 5,525 shared buffer hits
(`chat_message_links_company_comment_idx`: 250 searches, 1,000 hits;
`heartbeat_runs`: 250 loops, 750 hits) | 34.7x faster, 50.4x fewer
buffers |

## Risks

- Low risk. No database schema or migration changes.
- Adding `chat_conversations.endpoint_id =
chat_message_links.endpoint_id` relies on the invariant that every
`chat_message_links` row belongs to the same endpoint as its
`chat_conversations` row. All production write paths enforce this
invariant, and rejecting a mismatched cross-endpoint link is stricter
and safer than matching it.
- The `CROSS JOIN LATERAL (... ORDER BY created_at DESC, id DESC LIMIT
1)` subquery is mathematically equivalent to the previous `DISTINCT ON`
because `heartbeat_runs` is a primary-key `LEFT JOIN` that neither
filters nor multiplies rows, and the outer query still applies `DISTINCT
ON (comment_id, issue_id, agent_id) ORDER BY ..., created_at DESC, id
DESC` across any multiple conversations or endpoints.

## Model Used

- Gemini 4 Neon (Google DeepMind, XHigh reasoning, with tool use and
code execution)

## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
This commit is contained in:
Dotta authored and GitHub committed 2026-12-04 20:04:50 -06:00
1 parent 69144bcf22
commit 74e67231bd
2 files changed
+253 -30

No files matched your search

+192 -5
View File
@@ -1,8 +1,9 @@
import { randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
import { and, eq } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { agents, chatActions, chatConversations, chatEndpointResources, chatEndpoints, chatGitHubReviews,
companies, createDb, heartbeatRuns, runIdentityContexts, toolConnections, type Db } from "@paperclipai/db";
chatMessageLinks, companies, createDb, heartbeatRuns, issueComments, runIdentityContexts, toolApplications,
toolConnections, type Db } from "@paperclipai/db";
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { captureReviewWaitQueries, seedGitHubReviewWait, setGitHubReviewAssessment,
type CapturedReviewWaitQuery } from "./helpers/github-review-wait.js";
@@ -38,8 +39,13 @@ async function withStatements<T>(db: Db, read: () => Promise<T>) {
const client = db.$client as unknown as { unsafe: (query: string, ...rest: unknown[]) => unknown };
const unsafe = client.unsafe;
const sql: string[] = [];
client.unsafe = (query: string, ...rest: unknown[]) => { sql.push(query); return unsafe.call(client, query, ...rest); };
try { return { result: await read(), sql }; } finally { client.unsafe = unsafe; }
const calls: CapturedReviewWaitQuery[] = [];
client.unsafe = (query: string, ...rest: unknown[]) => {
sql.push(query);
calls.push({ sql: query, params: Array.isArray(rest[0]) ? rest[0] : [] });
return unsafe.call(client, query, ...rest);
};
try { return { result: await read(), sql, calls }; } finally { client.unsafe = unsafe; }
}
describe("inherited GitHub review wait projection", () => {
@@ -81,11 +87,14 @@ describe("inherited GitHub review wait projection", () => {
await setGitHubReviewAssessment(db, f.reviewId, assessment);
const expected = (assessment as { reviewedCommit?: unknown } | null)?.reviewedCommit === f.headSha;
expect((await readInheritedGitHubReviewWait(db, f.run))?.kind).toBe(expected ? "published" : "revoked");
expect((await readInheritedGitHubReviewWaits(db, [f.run]))[0]?.kind).toBe(expected ? "published" : "revoked");
}
await db.$client.unsafe("UPDATE chat_github_reviews SET head_sha = '1', assessment = '{\"reviewedCommit\":1}' WHERE id = $1", [f.reviewId]);
expect(await readInheritedGitHubReviewWait(db, f.run)).toEqual({ kind: "revoked" });
expect(await readInheritedGitHubReviewWaits(db, [f.run])).toEqual([{ kind: "revoked" }]);
await db.$client.unsafe("UPDATE chat_github_reviews SET assessment = NULL WHERE id = $1", [f.reviewId]);
expect(await readInheritedGitHubReviewWait(db, f.run)).toEqual({ kind: "revoked" });
expect(await readInheritedGitHubReviewWaits(db, [f.run])).toEqual([{ kind: "revoked" }]);
});
it.each(reviewWaitChanges)(
@@ -131,7 +140,7 @@ describe("inherited GitHub review wait projection", () => {
expect(result).toEqual(single);
// One review read and one publication read for each company with a source
// comment, not one of each for every run.
expect(sql.filter(text => /join "chat_github_reviews"/i.test(text))).toHaveLength(2);
expect(sql.filter(text => /from "chat_github_reviews"/i.test(text))).toHaveLength(2);
expect(sql.filter(text => /from "chat_actions"/i.test(text))).toHaveLength(2);
expect(await readInheritedGitHubReviewWaits(db, [])).toEqual([]);
});
@@ -193,4 +202,182 @@ describe("inherited GitHub review wait projection", () => {
expect(await readInheritedGitHubReviewWait(db, { ...f.run, nativeIssueId: null })).toBeNull();
expect(await readInheritedGitHubReviewWait(db, { ...f.run, activeIdentityContextId: null })).toBeNull();
});
it("matches only exact (comment, issue, agent) tuples and binds links to the conversation endpoint", async () => {
const first = await seedGitHubReviewWait(db);
const secondAgentId = randomUUID(), secondAppId = randomUUID(), secondConnId = randomUUID();
const secondEndpointId = randomUUID(), secondResourceId = randomUUID(), secondConversationId = randomUUID();
const secondCommentId = randomUUID(), secondReviewRunId = randomUUID(), secondReviewId = randomUUID();
await db.insert(agents).values({ id: secondAgentId, companyId: first.companyId, name: "Second", adapterType: "process" });
await db.insert(toolApplications).values({ id: secondAppId, companyId: first.companyId, name: "GitHub B", type: "chat" });
await db.insert(toolConnections).values({ id: secondConnId, companyId: first.companyId, applicationId: secondAppId,
name: "GitHub B", uid: secondConnId, transport: "chat_sdk", connectionPurpose: "channel", enabled: true, status: "active" });
await db.insert(chatEndpoints).values({ id: secondEndpointId, companyId: first.companyId, connectionId: secondConnId,
provider: "github", publicId: secondEndpointId, assignedAgentId: secondAgentId });
await db.insert(chatEndpointResources).values({ id: secondResourceId, companyId: first.companyId, endpointId: secondEndpointId,
type: "repository", providerResourceId: "synthetic/repository", label: "synthetic/repository",
metadata: { providerRepositoryId: "42" } });
await db.insert(chatConversations).values({ id: secondConversationId, companyId: first.companyId,
endpointId: secondEndpointId, resourceId: secondResourceId, issueId: first.issueId,
externalConversationId: "synthetic/repository", externalThreadId: "github:synthetic/repository:7", externalLabel: "Review" });
await db.insert(issueComments).values({ id: secondCommentId, companyId: first.companyId, issueId: first.issueId,
authorUserId: "operator", body: "Second review" });
await db.insert(chatMessageLinks).values({ companyId: first.companyId, endpointId: secondEndpointId,
conversationId: secondConversationId, commentId: secondCommentId, providerMessageId: secondCommentId, direction: "inbound" });
await db.insert(heartbeatRuns).values({ id: secondReviewRunId, companyId: first.companyId, agentId: secondAgentId,
nativeIssueId: first.issueId, status: "succeeded" });
const [firstReview] = await db.select().from(chatGitHubReviews).where(eq(chatGitHubReviews.id, first.reviewId));
await db.insert(chatGitHubReviews).values({ ...firstReview!, id: secondReviewId, endpointId: secondEndpointId,
runId: secondReviewRunId, deliveryId: secondReviewId });
const crossRunAId = randomUUID(), crossCtxAId = randomUUID(), crossRunBId = randomUUID(), crossCtxBId = randomUUID();
await db.insert(heartbeatRuns).values([
{ id: crossRunAId, companyId: first.companyId, agentId: secondAgentId, nativeIssueId: first.issueId,
responsibleUserId: "operator", activeIdentityContextId: crossCtxAId },
{ id: crossRunBId, companyId: first.companyId, agentId: first.agentId, nativeIssueId: first.issueId,
responsibleUserId: "operator", activeIdentityContextId: crossCtxBId },
]);
await db.insert(runIdentityContexts).values([
{ id: crossCtxAId, companyId: first.companyId, runId: crossRunAId, revision: 1,
responsibleUserId: "operator", messageId: first.commentId, cause: "test", correlationId: "test", status: "accepted" },
{ id: crossCtxBId, companyId: first.companyId, runId: crossRunBId, revision: 1,
responsibleUserId: "operator", messageId: secondCommentId, cause: "test", correlationId: "test", status: "accepted" },
]);
const [crossRunA] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, crossRunAId));
const [crossRunB] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, crossRunBId));
expect(await readInheritedGitHubReviewWait(db, crossRunA!)).toBeNull();
expect(await readInheritedGitHubReviewWait(db, crossRunB!)).toBeNull();
const crossBatch = await withStatements(db, () => readInheritedGitHubReviewWaits(db, [crossRunA!, crossRunB!]));
expect(crossBatch.result).toEqual([null, null]);
const reviewCall = crossBatch.calls.find(call => /from "chat_github_reviews"/i.test(call.sql))!;
expect(reviewCall).toBeTruthy();
const rawCrossRows = await db.$client.unsafe(reviewCall.sql, reviewCall.params as never[]);
expect(rawCrossRows).toHaveLength(0);
await db.update(chatMessageLinks).set({ endpointId: secondEndpointId })
.where(and(eq(chatMessageLinks.companyId, first.companyId), eq(chatMessageLinks.commentId, first.commentId)));
expect(await readInheritedGitHubReviewWait(db, first.run)).toBeNull();
expect(await readInheritedGitHubReviewWaits(db, [first.run])).toEqual([null]);
});
it("avoids skip-scanning chat_message_links and joins heartbeat_runs only for the latest review per key", async () => {
const first = await seedGitHubReviewWait(db);
const fixtures = [first];
while (fixtures.length < 24) {
fixtures.push(await seedGitHubReviewWait(db, { companyId: first.companyId, agentId: first.agentId }));
}
const largeAssessment = { reviewedCommit: first.headSha, summary: "Large summary ".repeat(400), findings: [] };
for (const f of fixtures) {
await setGitHubReviewAssessment(db, f.reviewId, largeAssessment);
const [review] = await db.select().from(chatGitHubReviews).where(eq(chatGitHubReviews.id, f.reviewId));
const olderRuns = Array.from({ length: 3 }, () => randomUUID());
await db.insert(heartbeatRuns).values(olderRuns.map(id => ({
id, companyId: f.companyId, agentId: f.agentId, nativeIssueId: f.issueId, status: "succeeded",
})));
await db.insert(chatGitHubReviews).values(olderRuns.map((runId, idx) => ({
...review!, id: randomUUID(), deliveryId: randomUUID(), runId,
createdAt: new Date(review!.createdAt.getTime() - (idx + 1) * 60_000),
})));
await db.insert(chatMessageLinks).values(Array.from({ length: 20 }, (_, idx) => ({
companyId: f.companyId, endpointId: f.endpointId, conversationId: f.conversationId,
commentId: null, providerMessageId: `out-${f.conversationId}-${idx}`, direction: "outbound" as const,
})));
}
await db.$client.unsafe(
`with eps as (
select g, gen_random_uuid() as company_id, gen_random_uuid() as endpoint_id,
gen_random_uuid() as app_id, gen_random_uuid() as conn_id, gen_random_uuid() as agent_id,
gen_random_uuid() as conv_id, gen_random_uuid() as issue_id
from generate_series(1, 40) g
),
ins_co as (
insert into companies (id, name, issue_prefix)
select company_id, 'Noise ' || g, company_id::text from eps
),
ins_ag as (
insert into agents (id, company_id, name, adapter_type)
select agent_id, company_id, 'Noise', 'process' from eps
),
ins_app as (
insert into tool_applications (id, company_id, name, type)
select app_id, company_id, 'Slack', 'chat' from eps
),
ins_conn as (
insert into tool_connections (id, company_id, application_id, name, uid, transport, connection_purpose, enabled, status)
select conn_id, company_id, app_id, 'Slack', conn_id::text, 'chat_sdk', 'channel', true, 'active' from eps
),
ins_ep as (
insert into chat_endpoints (id, company_id, connection_id, provider, public_id, assigned_agent_id, status)
select endpoint_id, company_id, conn_id, 'slack', endpoint_id::text, agent_id, 'active' from eps
),
ins_issue as (
insert into issues (id, company_id, title, assignee_agent_id)
select issue_id, company_id, 'Noise', agent_id from eps
),
ins_conv as (
insert into chat_conversations (id, company_id, endpoint_id, issue_id, external_conversation_id, external_thread_id, external_label)
select conv_id, company_id, endpoint_id, issue_id, 'ch', 't-' || g, 'Noise' from eps
)
insert into chat_message_links (company_id, endpoint_id, conversation_id, comment_id, provider_message_id, direction)
select eps.company_id, eps.endpoint_id, eps.conv_id, null, 'noise-' || m, 'outbound'
from eps cross join generate_series(1, 150) m`,
);
await db.$client.unsafe(
"analyze chat_endpoints, chat_endpoint_resources, chat_conversations, chat_message_links, chat_github_reviews, heartbeat_runs, tool_connections",
);
const runs = fixtures.map(f => f.run);
const { result, calls } = await withStatements(db, () => readInheritedGitHubReviewWaits(db, runs));
expect(result.map(wait => wait?.kind)).toEqual(runs.map(() => "published"));
const reviewCall = calls.find(call => /from "chat_github_reviews"/i.test(call.sql))!;
expect(reviewCall).toBeTruthy();
const rawRows = await db.$client.unsafe(reviewCall.sql, reviewCall.params as never[]).raw();
expect(rawRows).toHaveLength(runs.length);
for (const row of rawRows) {
expect(row.reduce((bytes, value) => bytes + (value?.byteLength ?? 0), 0)).toBeLessThan(1_000);
}
const [plan] = await db.$client.begin(async sql => {
await sql.unsafe("set local enable_seqscan = off");
const [row] = await sql.unsafe(
`explain (analyze, buffers, format json) ${reviewCall.sql}`,
reviewCall.params as never[],
);
return row!["QUERY PLAN"] as Array<{ Plan: Record<string, unknown> }>;
});
const linkIndexScans: Array<{ indexName: string; indexCond: string }> = [];
const heartbeatScans: Array<{ actualLoops: number }> = [];
const collectBitmapIndexes = (node: Record<string, unknown>) => {
if (node["Node Type"] === "Bitmap Index Scan") {
linkIndexScans.push({ indexName: String(node["Index Name"] ?? ""), indexCond: String(node["Index Cond"] ?? "") });
}
for (const child of (node.Plans as Array<Record<string, unknown>> | undefined) ?? []) collectBitmapIndexes(child);
};
const walk = (node: Record<string, unknown>) => {
const children = (node.Plans as Array<Record<string, unknown>> | undefined) ?? [];
if (node["Relation Name"] === "chat_message_links") {
if (node["Node Type"] === "Bitmap Heap Scan") collectBitmapIndexes(node);
else linkIndexScans.push({ indexName: String(node["Index Name"] ?? ""), indexCond: String(node["Index Cond"] ?? "") });
}
if (node["Relation Name"] === "heartbeat_runs") {
heartbeatScans.push({ actualLoops: Number(node["Actual Loops"] ?? 0) });
}
for (const child of children) walk(child);
};
walk(plan!.Plan);
expect(linkIndexScans.length).toBeGreaterThan(0);
for (const { indexName, indexCond } of linkIndexScans) {
expect(
indexName === "chat_message_links_company_comment_idx" ||
(indexName === "chat_message_links_provider_message_uq" &&
indexCond.includes("endpoint_id") && indexCond.includes("conversation_id")),
).toBe(true);
}
expect(heartbeatScans.length).toBeGreaterThan(0);
for (const scan of heartbeatScans) {
expect(scan.actualLoops).toBeLessThanOrEqual(runs.length);
}
});
});
@@ -35,23 +35,43 @@ type WaitRun = Pick<typeof heartbeatRuns.$inferSelect,
/** The columns of one inherited review. The single read and the batch read
* select the same columns. */
const inheritedReviewFields = {
function inheritedReviewFields<T extends typeof chatGitHubReviews | ReturnType<typeof latestGitHubReviewSubquery>>(reviews: T) {
return {
id: reviews.id, endpointId: reviews.endpointId,
state: reviews.state, repository: reviews.repository,
repositoryId: reviews.repositoryId, headSha: reviews.headSha,
reviewedCommit: sql<unknown>`${reviews.assessment}->'reviewedCommit'`, reviewRunId: reviews.runId,
connectionEnabled: toolConnections.enabled, connectionStatus: toolConnections.status,
reviewAgentId: heartbeatRuns.agentId, reviewCompanyId: heartbeatRuns.companyId,
resourceRepository: chatEndpointResources.providerResourceId,
resourceRepositoryId: sql<string | null>`${chatEndpointResources.metadata}->>'providerRepositoryId'`,
pullNumber: reviews.pullNumber, thread: chatConversations.externalThreadId,
};
}
const latestReviewColumns = {
id: chatGitHubReviews.id, endpointId: chatGitHubReviews.endpointId,
state: chatGitHubReviews.state, repository: chatGitHubReviews.repository,
repositoryId: chatGitHubReviews.repositoryId, headSha: chatGitHubReviews.headSha,
reviewedCommit: sql<unknown>`${chatGitHubReviews.assessment}->'reviewedCommit'`, reviewRunId: chatGitHubReviews.runId,
connectionEnabled: toolConnections.enabled, connectionStatus: toolConnections.status,
reviewAgentId: heartbeatRuns.agentId, reviewCompanyId: heartbeatRuns.companyId,
resourceRepository: chatEndpointResources.providerResourceId,
resourceRepositoryId: sql<string | null>`${chatEndpointResources.metadata}->>'providerRepositoryId'`,
pullNumber: chatGitHubReviews.pullNumber, thread: chatConversations.externalThreadId,
assessment: chatGitHubReviews.assessment, runId: chatGitHubReviews.runId,
pullNumber: chatGitHubReviews.pullNumber, createdAt: chatGitHubReviews.createdAt,
};
function latestGitHubReviewSubquery(db: Db, companyId: string) {
return db.select(latestReviewColumns).from(chatGitHubReviews)
.where(and(eq(chatGitHubReviews.companyId, companyId),
eq(chatGitHubReviews.endpointId, chatEndpoints.id),
eq(chatGitHubReviews.issueId, chatConversations.issueId)))
.orderBy(desc(chatGitHubReviews.createdAt), desc(chatGitHubReviews.id)).limit(1)
.as("latest_github_review");
}
const inheritedReviewQueries = new WeakMap<Db, ReturnType<typeof prepareInheritedReviewQuery>>();
function prepareInheritedReviewQuery(db: Db) {
return db.select(inheritedReviewFields).from(chatMessageLinks)
return db.select(inheritedReviewFields(chatGitHubReviews)).from(chatMessageLinks)
.innerJoin(chatConversations, and(eq(chatConversations.id, chatMessageLinks.conversationId),
eq(chatConversations.endpointId, chatMessageLinks.endpointId),
eq(chatConversations.companyId, sql.placeholder("companyId")), eq(chatConversations.issueId, sql.placeholder("issueId"))))
.innerJoin(chatEndpoints, and(eq(chatEndpoints.id, chatConversations.endpointId),
eq(chatEndpoints.companyId, sql.placeholder("companyId")), eq(chatEndpoints.provider, "github"),
@@ -86,35 +106,51 @@ function inheritedReviewKey(key: InheritedReviewKey) {
return `${key.commentId}:${key.issueId}:${key.agentId}`;
}
/** The latest review for each (source comment, task, agent) key of one
* company. For each key this is the row of the single prepared read: the same
* joins and filters, and DISTINCT ON keeps the first row in the same order. */
const requestedReviewKey = sql.identifier("inherited_review_key");
const requestedKeyCommentId = sql`${requestedReviewKey}."comment_id"`;
const requestedKeyIssueId = sql`${requestedReviewKey}."issue_id"`;
const requestedKeyAgentId = sql`${requestedReviewKey}."agent_id"`;
async function readInheritedReviewsForKeys(db: Db, companyId: string, keys: InheritedReviewKey[]) {
const unique = (values: string[]) => [...new Set(values)];
const commentIds: string[] = [];
const issueIds: string[] = [];
const agentIds: string[] = [];
const seenKeys = new Set<string>();
for (const key of keys) {
const id = inheritedReviewKey(key);
if (seenKeys.has(id)) continue;
seenKeys.add(id);
commentIds.push(key.commentId);
issueIds.push(key.issueId);
agentIds.push(key.agentId);
}
const byKey = new Map<string, InheritedReviewRow>();
if (!commentIds.length) return byKey;
const latestReview = latestGitHubReviewSubquery(db, companyId);
const rows = await db.selectDistinctOn([chatMessageLinks.commentId, chatConversations.issueId, chatEndpoints.assignedAgentId], {
...inheritedReviewFields,
...inheritedReviewFields(latestReview),
keyCommentId: chatMessageLinks.commentId, keyIssueId: chatConversations.issueId, keyAgentId: chatEndpoints.assignedAgentId,
}).from(chatMessageLinks)
.innerJoin(sql`unnest(${sql.param(commentIds)}::uuid[], ${sql.param(issueIds)}::uuid[], ${sql.param(agentIds)}::uuid[]) as ${requestedReviewKey}("comment_id", "issue_id", "agent_id")`,
eq(chatMessageLinks.commentId, requestedKeyCommentId))
.innerJoin(chatConversations, and(eq(chatConversations.id, chatMessageLinks.conversationId),
eq(chatConversations.companyId, companyId),
sql`${chatConversations.issueId} = any(${sql.param(unique(keys.map(key => key.issueId)))}::uuid[])`))
eq(chatConversations.endpointId, chatMessageLinks.endpointId),
eq(chatConversations.companyId, companyId), eq(chatConversations.issueId, requestedKeyIssueId)))
.innerJoin(chatEndpoints, and(eq(chatEndpoints.id, chatConversations.endpointId),
eq(chatEndpoints.companyId, companyId), eq(chatEndpoints.provider, "github"),
sql`${chatEndpoints.assignedAgentId} = any(${sql.param(unique(keys.map(key => key.agentId)))}::uuid[])`))
eq(chatEndpoints.assignedAgentId, requestedKeyAgentId)))
.leftJoin(toolConnections, and(eq(toolConnections.id, chatEndpoints.connectionId),
eq(toolConnections.companyId, companyId)))
.innerJoin(chatEndpointResources, and(eq(chatEndpointResources.id, chatConversations.resourceId),
eq(chatEndpointResources.companyId, companyId), eq(chatEndpointResources.endpointId, chatEndpoints.id)))
.innerJoin(chatGitHubReviews, and(eq(chatGitHubReviews.endpointId, chatEndpoints.id),
eq(chatGitHubReviews.companyId, companyId), eq(chatGitHubReviews.issueId, chatConversations.issueId)))
.leftJoin(heartbeatRuns, eq(heartbeatRuns.id, chatGitHubReviews.runId))
.where(and(eq(chatMessageLinks.companyId, companyId),
sql`${chatMessageLinks.commentId} = any(${sql.param(unique(keys.map(key => key.commentId)))}::uuid[])`,
eq(chatMessageLinks.direction, "inbound")))
.crossJoinLateral(latestReview)
.leftJoin(heartbeatRuns, eq(heartbeatRuns.id, latestReview.runId))
.where(and(eq(chatMessageLinks.companyId, companyId), eq(chatMessageLinks.direction, "inbound")))
.orderBy(chatMessageLinks.commentId, chatConversations.issueId, chatEndpoints.assignedAgentId,
desc(chatGitHubReviews.createdAt), desc(chatGitHubReviews.id));
// The array filters can also match a mix of two keys. Only exact keys are read.
const byKey = new Map<string, InheritedReviewRow>();
desc(latestReview.createdAt), desc(latestReview.id));
for (const { keyCommentId, keyIssueId, keyAgentId, ...review } of rows) {
if (keyCommentId && keyIssueId && keyAgentId) {
byKey.set(inheritedReviewKey({ commentId: keyCommentId, issueId: keyIssueId, agentId: keyAgentId }), review);