diff --git a/server/src/__tests__/github-review-wait.test.ts b/server/src/__tests__/github-review-wait.test.ts index 5db20770e8b..54f9db58008 100644 --- a/server/src/__tests__/github-review-wait.test.ts +++ b/server/src/__tests__/github-review-wait.test.ts @@ -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(db: Db, read: () => Promise) { 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 }>; + }); + const linkIndexScans: Array<{ indexName: string; indexCond: string }> = []; + const heartbeatScans: Array<{ actualLoops: number }> = []; + const collectBitmapIndexes = (node: Record) => { + 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> | undefined) ?? []) collectBitmapIndexes(child); + }; + const walk = (node: Record) => { + const children = (node.Plans as Array> | 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); + } + }); }); diff --git a/server/src/services/chat-channels/github/review-wait.ts b/server/src/services/chat-channels/github/review-wait.ts index 5758d35554c..415eb668ad5 100644 --- a/server/src/services/chat-channels/github/review-wait.ts +++ b/server/src/services/chat-channels/github/review-wait.ts @@ -35,23 +35,43 @@ type WaitRun = Pick>(reviews: T) { + return { + id: reviews.id, endpointId: reviews.endpointId, + state: reviews.state, repository: reviews.repository, + repositoryId: reviews.repositoryId, headSha: reviews.headSha, + reviewedCommit: sql`${reviews.assessment}->'reviewedCommit'`, reviewRunId: reviews.runId, + connectionEnabled: toolConnections.enabled, connectionStatus: toolConnections.status, + reviewAgentId: heartbeatRuns.agentId, reviewCompanyId: heartbeatRuns.companyId, + resourceRepository: chatEndpointResources.providerResourceId, + resourceRepositoryId: sql`${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`${chatGitHubReviews.assessment}->'reviewedCommit'`, reviewRunId: chatGitHubReviews.runId, - connectionEnabled: toolConnections.enabled, connectionStatus: toolConnections.status, - reviewAgentId: heartbeatRuns.agentId, reviewCompanyId: heartbeatRuns.companyId, - resourceRepository: chatEndpointResources.providerResourceId, - resourceRepositoryId: sql`${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>(); 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(); + 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(); + 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(); + 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);