mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 20:09:33 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Profiling live 8-core PR runs (`45592683902`, `45578886514`, `45591289735`, `45587659461`) showed that every single top Vitest critical-path straggler across all 4 Vitest lanes was caused by **single-file tail pinning**—one massive file running solo while 4–6 CPU cores sat idle—rather than insufficient shard counts: > - `Verify Paperclip Runner (vitest package 1/6)` (`245s` job): `runnerd-codex-transport.test.ts` = `190.9s` solo > - `Verify Paperclip Runner (vitest package 2/6)` (`236s` job): `runnerd-codex-transport-deadlines.test.ts` = `181.3s` solo > - `Verify Paperclip Runner (vitest package 3/6)` (`185s` job): `runnerd-codex-transport-settlement.test.ts` = `123.6s` solo > - `General tests (chat 1/2)` (`229s` job): `github-review-workflow.integration.test.ts` = `179.2s` solo > - `General tests (server 1/20)` (`209s` job): `connection-management.integration.test.ts` = `160.1s` solo > - `Verify serialized server suites (1/9)` (`190s` job): `issue-queued-comments-routes.test.ts` = `132.8s` solo > - Instead of bloating shard counts, this pull request splits those 6 single-file tails into 20 focused sibling suites (`<925 LOC` per new file) with shared non-test harness helpers so existing 8-core workers execute them in parallel, keeps all 6 original anchor filenames intact so every existing `maps/` and contract reference remains valid, and refreshes all 4 Vitest LPT duration manifests from live 8-core measurements. > - Every single original test case is preserved (`694/694` live pass across the 20 split suites, zero deleted assertions) while shaving `60–105s` off every Vitest lane's critical-path tail. ## Linked Issues or Issue Description Refs #22804 **What existing behavior does this improve?** Parallel wall-clock execution time of the slowest shards across `Verify Paperclip Runner (vitest package)`, `General tests (chat)`, `General tests (server)`, and `Verify serialized server suites`. **Subsystem affected** packages/paperclip-runner/, server/, and scripts/ — Vitest integration test layout, sequencer priorities, and LPT shard duration manifests **Current behavior** Six oversized test files (`123s–191s` solo each) pin the tail of the slowest shard in every Vitest lane while peer workers on the 8-core runner sit idle. **Proposed behavior** Split those 6 single-file stragglers into 20 parallelizable sibling suites (retaining all 6 original anchor filenames and extracting shared non-test harnesses) and refresh `packages/paperclip-runner/scripts/vitest-lane-durations.json`, `scripts/chat-shard-durations.json`, `scripts/general-server-shard-durations.json`, and `scripts/serialized-shard-durations.json` plus `packages/paperclip-runner/scripts/vitest-sequencer.mjs`. ## What Changed - **Split all 6 single-file stragglers (31 files changed: 11 modified, 20 new; every new file `<925 LOC`, 100% of test cases preserved):** 1. `packages/paperclip-runner/test/runnerd-codex-transport-deadlines.test.ts` (`181.3s` CI) → 3 files (`anchor` + `-lease-expiry` + `-cold-admission`, 9/9 tests) 2. `packages/paperclip-runner/test/runnerd-codex-transport-settlement.test.ts` (`123.6s` CI) → 2 files (`anchor` + `-settlement-revocation`, 19/19 tests) + 3 non-test support harnesses (`runnerd-settlement-assertions.ts`, `runnerd-settlement-harness.ts`, `runnerd-settlement-fixture.ts`) 3. `packages/paperclip-runner/test/runnerd-codex-transport.test.ts` (`190.9s` CI) → 4 files (`anchor` + `-backlog-proxy` + `-held-calls` + `-provider-turns`, 337/337 tests) 4. `server/src/__tests__/chat-channels/github-review-workflow.integration.test.ts` (`179.2s` CI) → 4 files (`anchor` + `-finding-threads` + `-response-maintenance` + `-publications`, 89/89 tests) + `github-review-harness.ts` 5. `server/src/__tests__/connection-management.integration.test.ts` (`160.1s` CI) → 4 files (`anchor` + `-providers` + `-delegated-policy` + `-gateways`, 92/92 tests) + `helpers/connection-management-harness.ts` 6. `server/src/__tests__/issue-queued-comments-routes.test.ts` (`132.8s` CI) → 3 `*routes*` files (`anchor` + `-steering-routes` + `-dispatch-routes`, 148/148 tests, all matching `routeTestPattern` in the `serialized` lane) + `helpers/issue-queued-comments-harness.ts` - **Updated sequencer & LPT duration manifests:** - Updated `packages/paperclip-runner/scripts/vitest-sequencer.mjs` and refreshed `packages/paperclip-runner/scripts/vitest-lane-durations.json`, `scripts/chat-shard-durations.json`, `scripts/general-server-shard-durations.json`, and `scripts/serialized-shard-durations.json` from live 8-core PR run `45592683902` with exact `coverage` reconciliation. ## Verification - Live execution of all 20 split suites: **20/20 files, 694/694 tests PASS** (`deadlines` 9/9 in `81.1s` parallel, `settlement` 19/19 in `105.4s` parallel, `transport` 337/337 in `109.2s` parallel, `github-review` 89/89 under shared PG, `connection-management` 92/92 under shared PG, `issue-queued-comments` 148/148 under shared PG) - `node scripts/check-test-budget.mjs --base origin/master` — **PASS** (105 nightly suites, 11 test files checked, 0 violations) - `node scripts/check-maps.mjs` — **PASS** (35 areas, 192 capability IDs aligned) - `pnpm --filter @paperclipai/paperclip-runner exec tsc --noEmit` — **PASS** (0 errors) - `pnpm --filter @paperclipai/paperclip-runner exec vitest run scripts/vitest-sequencer.test.mjs` — **5/5 PASS** - `node --test` across `native-completion-source-contract`, `run-vitest-stable-shard`, `run-vitest-stable-pr-mode`, `runner-vitest-package-lanes`, `test-selection-pr-timings`, `test-selection-timings`, `e2e-shard`, `check-test-budget`, and `ci-plan` — **121/121 PASS** ## Risks - Low risk: all 6 original anchor filenames remain intact, zero `.github/**` or `CODEOWNERS` files are touched, zero cross-test-file imports were introduced (shared setup lives in non-test harness modules), and full CI will execute all 20 split suites live before merge. ## Model Used - Gemini 4 Neon (High) via Antigravity agent swarm (`vitest-runner`, `verifier`, `ci-pipeline`). ## 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
433 lines
14 KiB
TypeScript
433 lines
14 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import { and, eq } from "drizzle-orm";
|
|
import { expect } from "vitest";
|
|
import {
|
|
chatActions,
|
|
chatEndpoints,
|
|
chatExternalPrincipals,
|
|
chatGitHubReviews,
|
|
chatIdentityLinks,
|
|
heartbeatRuns,
|
|
} from "@paperclipai/db";
|
|
import { githubChatManagementService } from "../../services/chat-github-management.js";
|
|
import { githubChatReviewService } from "../../services/chat-github-reviews.js";
|
|
import { githubReviewCheckService } from "../../services/chat-github-checks.js";
|
|
import { githubAutomaticReviewEvent } from "../../services/chat-github-events.js";
|
|
import { makeMessage, makeThread } from "./providers.js";
|
|
import type { ChatChannelHarness } from "./harness.js";
|
|
import type { GitHubHarness } from "./github-harness.js";
|
|
|
|
export function createGitHubReviewHarness(h: ChatChannelHarness, gh: GitHubHarness) {
|
|
const {
|
|
seedCompany,
|
|
readChatConversationsByEndpointId,
|
|
readChatEndpointsById,
|
|
readChatGitHubReviewsByEndpointId,
|
|
chatWakeContext,
|
|
deliverMessage,
|
|
} = h;
|
|
const { signedGitHubWebhookRequest, configuredGitHubEndpoint } = gh;
|
|
|
|
async function reviewBotFixture() {
|
|
const db = h.db;
|
|
const fixture = await seedCompany();
|
|
const context = await configuredGitHubEndpoint(fixture, {}, true);
|
|
const endpoint = await context.service.get(context.endpoint.id);
|
|
const [principal] = await db
|
|
.insert(chatExternalPrincipals)
|
|
.values({
|
|
companyId: fixture.companyId,
|
|
provider: "github",
|
|
providerAccountId: endpoint.providerAccountId!,
|
|
externalId: "42",
|
|
kind: "user",
|
|
displayName: "Octocat",
|
|
handle: "octocat",
|
|
isBot: false,
|
|
})
|
|
.returning();
|
|
await db.insert(chatIdentityLinks).values({
|
|
companyId: fixture.companyId,
|
|
endpointId: endpoint.id,
|
|
principalId: principal.id,
|
|
paperclipUserId: "owner-user",
|
|
status: "linked",
|
|
confirmedAt: new Date(),
|
|
});
|
|
const management = githubChatManagementService(db, context.providerFetch);
|
|
const initial = await management.configuration(endpoint.id, "owner-user");
|
|
await management.saveConfiguration(
|
|
endpoint.id,
|
|
{
|
|
expectedRevision: initial.revision,
|
|
configuration: { ...initial.configuration, toolsEnabled: true },
|
|
},
|
|
"owner-user",
|
|
);
|
|
await context.service.update(
|
|
endpoint.id,
|
|
{ allowGroupChats: true },
|
|
"owner-user",
|
|
);
|
|
return { ...fixture, ...context, endpoint, principal, management };
|
|
}
|
|
|
|
async function subscribedGitHubFixture(threadId = "github:paperclipai/paperclip:issue:419") {
|
|
const f = await reviewBotFixture();
|
|
const thread = makeThread({ channelId: "paperclipai/paperclip", id: threadId }).thread;
|
|
await deliverMessage({
|
|
callbacks: f.callbacks,
|
|
endpointId: f.endpoint.id,
|
|
provider: "github",
|
|
thread,
|
|
trigger: "mention",
|
|
message: makeMessage({
|
|
id: "41901",
|
|
text: `@${f.endpoint.botUsername} start this thread`,
|
|
userId: "42",
|
|
userName: "octocat",
|
|
mentioned: true,
|
|
}),
|
|
});
|
|
const [conversation] = await readChatConversationsByEndpointId(f.endpoint.id);
|
|
return { ...f, thread, conversation };
|
|
}
|
|
|
|
async function addPeerGitHubBot(f: Awaited<ReturnType<typeof reviewBotFixture>>) {
|
|
const db = h.db;
|
|
const peer = await f.service.create(
|
|
f.companyId,
|
|
{ provider: "github", assignedAgentId: f.assignedAgentId, name: "Gonzo" },
|
|
"owner-user",
|
|
);
|
|
await db
|
|
.update(chatEndpoints)
|
|
.set({ botUsername: "gonzo[bot]", status: "active" })
|
|
.where(eq(chatEndpoints.id, peer.id));
|
|
return peer;
|
|
}
|
|
|
|
async function toolReplyFixture(
|
|
threadId = "github:paperclipai/paperclip:issue:418",
|
|
reportOnly = false,
|
|
findingCategories?: string[],
|
|
) {
|
|
const db = h.db;
|
|
const f = await reviewBotFixture();
|
|
if (reportOnly || findingCategories) {
|
|
const config = await f.management.configuration(f.endpoint.id, "owner-user");
|
|
await f.management.saveConfiguration(
|
|
f.endpoint.id,
|
|
{
|
|
expectedRevision: config.revision,
|
|
configuration: {
|
|
...config.configuration,
|
|
defaults: {
|
|
...config.configuration.defaults,
|
|
...(reportOnly ? { ratingThreshold: null } : {}),
|
|
...(findingCategories ? { findingCategories } : {}),
|
|
},
|
|
},
|
|
},
|
|
"owner-user",
|
|
);
|
|
}
|
|
const thread = makeThread({ channelId: "paperclipai/paperclip", id: threadId }).thread;
|
|
await deliverMessage({
|
|
callbacks: f.callbacks,
|
|
endpointId: f.endpoint.id,
|
|
provider: "github",
|
|
thread,
|
|
trigger: "mention",
|
|
message: makeMessage({
|
|
id: "41801",
|
|
text: "Are you there?",
|
|
userId: "42",
|
|
userName: "octocat",
|
|
mentioned: true,
|
|
}),
|
|
});
|
|
const [conversation] = await readChatConversationsByEndpointId(f.endpoint.id);
|
|
const [run] = await db
|
|
.insert(heartbeatRuns)
|
|
.values({
|
|
companyId: f.companyId,
|
|
agentId: f.assignedAgentId,
|
|
status: "running",
|
|
runtimeMode: "native",
|
|
contextSnapshot: await chatWakeContext({
|
|
endpointId: f.endpoint.id,
|
|
issueId: conversation.issueId,
|
|
provider: "github",
|
|
providerMessageId: "41801",
|
|
}),
|
|
})
|
|
.returning();
|
|
const session = {
|
|
companyId: f.companyId,
|
|
agentId: f.assignedAgentId,
|
|
issueId: conversation.issueId,
|
|
runId: run.id,
|
|
};
|
|
return { ...f, conversation, run, session };
|
|
}
|
|
|
|
async function publicationRetryFixture(findingCategories?: string[]) {
|
|
const db = h.db;
|
|
const f = await toolReplyFixture("github:paperclipai/paperclip:418", true, findingCategories);
|
|
const head = "b".repeat(40);
|
|
const inline: Array<{ id: number; body: string; html_url: string; user: { login: string } }> = [];
|
|
const checks: Array<{ id: number; external_id: string; app: { id: number }; html_url: string }> = [];
|
|
const writes: Array<{ path: string; method: string }> = [];
|
|
const provider = async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
const url = String(input);
|
|
if (url.endsWith("/pulls/418")) {
|
|
return Response.json({
|
|
number: 418,
|
|
state: "open",
|
|
draft: false,
|
|
head: { sha: head },
|
|
base: { sha: "a".repeat(40), ref: "master" },
|
|
user: { id: 42, login: "octocat", type: "User" },
|
|
labels: [],
|
|
});
|
|
}
|
|
if (url.includes("/files?")) {
|
|
return Response.json([
|
|
{ filename: "src/math.ts", status: "modified", patch: "@@ -1 +1 @@\n-old\n+new" },
|
|
]);
|
|
}
|
|
if (url.includes("/pulls/418/comments?")) return Response.json(inline);
|
|
if (url.includes("/check-runs?")) return Response.json({ check_runs: checks });
|
|
if (init?.method === "POST" && url.endsWith("/pulls/418/comments")) {
|
|
writes.push({ path: url, method: init.method });
|
|
const item = {
|
|
id: 420 + inline.length,
|
|
body: JSON.parse(String(init.body)).body,
|
|
html_url: "https://github.com/acme/repo/pull/418#discussion_r420",
|
|
user: { login: f.endpoint.botUsername! },
|
|
};
|
|
inline.push(item);
|
|
return Response.json(item);
|
|
}
|
|
if (url.includes("/check-runs") && init?.method) {
|
|
writes.push({ path: url, method: init.method });
|
|
const body = JSON.parse(String(init.body));
|
|
const check = checks[0] ?? {
|
|
id: 419,
|
|
external_id: body.external_id,
|
|
app: { id: Number(f.endpoint.botExternalId) },
|
|
html_url: "https://github.com/checks/419",
|
|
};
|
|
if (!checks.length) checks.push(check);
|
|
return Response.json(check);
|
|
}
|
|
return undefined;
|
|
};
|
|
f.setSupplementalProviderFetch(provider);
|
|
const service = githubChatReviewService(db, f.providerFetch);
|
|
await service.execute(f.session, "begin_review", { reviewedCommit: head });
|
|
const assessment = {
|
|
reviewedCommit: head,
|
|
score: 3,
|
|
complete: true,
|
|
summary: "Advisory review",
|
|
rationale: "Reviewed the file",
|
|
coverage: { reviewedPaths: ["src/math.ts"], omittedPaths: [], limitations: [] },
|
|
findings: [],
|
|
};
|
|
const action = async () =>
|
|
(
|
|
await db
|
|
.select()
|
|
.from(chatActions)
|
|
.where(
|
|
and(
|
|
eq(chatActions.endpointId, f.endpoint.id),
|
|
eq(chatActions.kind, "github_review_publication"),
|
|
),
|
|
)
|
|
)[0];
|
|
return { ...f, service, head, assessment, provider, action, inline, checks, writes };
|
|
}
|
|
|
|
async function reviewCheckWorkerFixture(status: "running" | "failed" = "failed") {
|
|
const db = h.db;
|
|
const f = await toolReplyFixture("github:paperclipai/paperclip:418");
|
|
const config = await f.management.configuration(f.endpoint.id, "owner-user");
|
|
const event = githubAutomaticReviewEvent(
|
|
{
|
|
action: "opened",
|
|
repository: { id: 97531, full_name: "paperclipai/paperclip" },
|
|
sender: { id: 42, login: "octocat" },
|
|
pull_request: {
|
|
number: 418,
|
|
title: "Review",
|
|
body: "",
|
|
draft: false,
|
|
base: { sha: "a".repeat(40), ref: "master" },
|
|
head: { sha: "b".repeat(40) },
|
|
user: { id: 42, login: "octocat" },
|
|
labels: [],
|
|
},
|
|
},
|
|
randomUUID(),
|
|
)!;
|
|
const [review] = await db
|
|
.insert(chatGitHubReviews)
|
|
.values({
|
|
companyId: f.companyId,
|
|
endpointId: f.endpoint.id,
|
|
issueId: f.conversation.issueId!,
|
|
runId: f.run.id,
|
|
repositoryId: "97531",
|
|
repository: event.repository,
|
|
pullNumber: 418,
|
|
headSha: event.headSha,
|
|
deliveryId: event.deliveryId,
|
|
configurationRevision: config.revision,
|
|
policySnapshot: config.configuration.defaults,
|
|
event,
|
|
})
|
|
.returning();
|
|
await db.update(heartbeatRuns).set({ status }).where(eq(heartbeatRuns.id, f.run.id));
|
|
const writes: Record<string, unknown>[] = [];
|
|
const requests: string[] = [];
|
|
let remoteHead = event.headSha;
|
|
let unavailable = false;
|
|
f.setSupplementalProviderFetch(async (input, init) => {
|
|
const url = String(input);
|
|
if (url.endsWith("/pulls/418")) {
|
|
requests.push(url);
|
|
return Response.json({ head: { sha: remoteHead } });
|
|
}
|
|
if (url.includes("/check-runs?")) {
|
|
requests.push(url);
|
|
return Response.json({ check_runs: [] });
|
|
}
|
|
if (url.endsWith("/check-runs") && init?.method === "POST") {
|
|
requests.push(url);
|
|
if (unavailable) return Response.json({ message: "injected check outage" }, { status: 503 });
|
|
writes.push(JSON.parse(String(init.body)));
|
|
return Response.json({ id: 418, html_url: "https://github.com/checks/418" });
|
|
}
|
|
return undefined;
|
|
});
|
|
const checks = githubReviewCheckService(db, f.providerFetch);
|
|
const [endpoint] = await readChatEndpointsById(f.endpoint.id);
|
|
const action = async () =>
|
|
(
|
|
await db
|
|
.select()
|
|
.from(chatActions)
|
|
.where(
|
|
and(
|
|
eq(chatActions.endpointId, endpoint.id),
|
|
eq(chatActions.kind, "github_review_check"),
|
|
),
|
|
)
|
|
)[0];
|
|
return {
|
|
...f,
|
|
event,
|
|
review,
|
|
endpoint,
|
|
checks,
|
|
writes,
|
|
requests,
|
|
action,
|
|
enqueue: () => checks.enqueue(endpoint, event, true, "authorized"),
|
|
setRemoteHead: (value: string) => {
|
|
remoteHead = value;
|
|
},
|
|
setUnavailable: (value: boolean) => {
|
|
unavailable = value;
|
|
},
|
|
};
|
|
}
|
|
|
|
async function reviewProjectionFixture(cancelFirst = true) {
|
|
const db = h.db;
|
|
const f = await reviewBotFixture();
|
|
const deliveryId = randomUUID();
|
|
const payload = {
|
|
action: "synchronize",
|
|
installation: { id: 2468 },
|
|
repository: {
|
|
id: 97531,
|
|
full_name: "paperclipai/paperclip",
|
|
name: "paperclip",
|
|
owner: { id: 1357, login: "paperclipai" },
|
|
},
|
|
sender: { id: 42, login: "octocat" },
|
|
pull_request: {
|
|
number: 82,
|
|
title: "Rapid pushes",
|
|
body: "",
|
|
draft: false,
|
|
base: { sha: "a".repeat(40), ref: "master" },
|
|
head: { sha: "b".repeat(40) },
|
|
user: { id: 42, login: "octocat", type: "User" },
|
|
labels: [],
|
|
},
|
|
};
|
|
f.setSupplementalProviderFetch(async (input) =>
|
|
String(input).endsWith("/pulls/82")
|
|
? Response.json({ ...payload.pull_request, head: { sha: "c".repeat(40) } })
|
|
: undefined,
|
|
);
|
|
const checks = githubReviewCheckService(db, f.providerFetch);
|
|
const [endpoint] = await readChatEndpointsById(f.endpoint.id);
|
|
const event = githubAutomaticReviewEvent(payload, deliveryId)!;
|
|
await checks.enqueue(endpoint, event, true, "authorized");
|
|
const action = async () =>
|
|
(
|
|
await db
|
|
.select()
|
|
.from(chatActions)
|
|
.where(
|
|
and(
|
|
eq(chatActions.endpointId, endpoint.id),
|
|
eq(chatActions.kind, "github_review_check"),
|
|
),
|
|
)
|
|
)[0];
|
|
if (cancelFirst) await checks.processPending();
|
|
const admit = async () => {
|
|
expect(
|
|
(
|
|
await f.service.handleWebhook(
|
|
endpoint.publicId,
|
|
"github",
|
|
signedGitHubWebhookRequest({
|
|
event: "pull_request",
|
|
delivery: deliveryId,
|
|
payload,
|
|
webhookSecret: f.webhookSecret,
|
|
}),
|
|
)
|
|
).status,
|
|
).toBeLessThan(300);
|
|
await expect
|
|
.poll(async () => (await readChatGitHubReviewsByEndpointId(endpoint.id)).length, {
|
|
timeout: 10_000,
|
|
})
|
|
.toBe(1);
|
|
return (await readChatGitHubReviewsByEndpointId(endpoint.id))[0];
|
|
};
|
|
const read = async (id: string) =>
|
|
(await db.select().from(chatGitHubReviews).where(eq(chatGitHubReviews.id, id)))[0];
|
|
return { ...f, endpoint, event, action, checks, admit, read };
|
|
}
|
|
|
|
return {
|
|
reviewBotFixture,
|
|
subscribedGitHubFixture,
|
|
addPeerGitHubBot,
|
|
toolReplyFixture,
|
|
publicationRetryFixture,
|
|
reviewCheckWorkerFixture,
|
|
reviewProjectionFixture,
|
|
};
|
|
}
|