mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 11:47:42 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Every master commit must pass Cloud readiness before Docker publishes it and staging deploys it > - Two server tests failed there on and off, so master stopped reaching staging > - Both failures came from test setup that leaked across suites, not from product behavior > - CI runs each shard against one shared PostgreSQL server, and each suite gets its own database on it > - This pull request removes both leaks at their cause and adds a guard for each > - The benefit is that Cloud readiness no longer fails on these two tests, and Docker publishing and staging deploys continue ## Linked Issues or Issue Description **What happened?** Cloud readiness failed on master in two server test shards. 1. `antigravity-swarm.db.test.ts` failed with `duplicate key value violates unique constraint "companies_issue_prefix_idx"`. 2. `git-workspace-expiration.test.ts` > "rolls back when new history appears after capture without changing files" returned `skipReason: "inspection_failed"` instead of `restore_point_contents_changed`. This failed on four attempts of one master commit. **Root cause** 1. The swarm suite and 20 other suites made company issue prefixes from four random hex characters (65,536 values). The swarm suite seeds about 65 companies in one database, so one run of that file had about a 3% chance of a collision. 2. `isolated-remote-workspace-source-lock.test.ts` and `native-workspace-finalizer.test.ts` ran `ALTER ROLE <current_user> SET idle_in_transaction_session_timeout = '1s'`. In CI all suites in a shard share one PostgreSQL server and one role. So every new session in every other suite also got a 1-second idle-in-transaction limit. The expiration test holds a transaction open while it runs Git commands. PostgreSQL closed that session, and the expiration recorded `CONNECTION_CLOSED` as `inspection_failed`. The lock suite never reset the setting. **Steps to reproduce** 1. Run the lock suite and then the expiration test on one shared test server (the same layout CI uses). 2. Before this change, 40 of 40 runs of the expiration test fail with `CONNECTION_CLOSED`. **Expected behavior** A suite's session settings apply only to its own database. Seeded companies never share an issue prefix. ## What Changed - Added `uniqueIssuePrefix(tag)`, a shared test helper that adds 48 random bits (12 uppercase hex characters) to a tag. - Changed all 24 company seeds that used four or fewer random characters (21 files) to use the helper. Updated one identifier assertion in `cases-routes.test.ts` for the longer prefix. - Changed the two suites from `ALTER ROLE ... SET` to `ALTER DATABASE <current_database()> SET`, so the 1-second limit applies only to their own disposable database. The finalizer suite still resets it after its test. - Added two guard tests: one proves the helper does not repeat across 70,000 prefixes, and one fails if any test file changes a setting for a whole role. ## Verification - Deterministic red for the Git expiration failure: one shared test server, lock suite first, then the expiration test 40 times. Before: 40 of 40 failed with `CONNECTION_CLOSED`. After: 40 of 40 passed, and 40 of 40 passed again with 12 CPU-burning processes running. - The same failure appeared in PR CI before the fix: with the full suite on one shared server, 17 runs of the looped expiration test failed with `CONNECTION_CLOSED`. - Deterministic red for the prefix generator: the old four-character generator gives 42,898 distinct prefixes from 70,000 calls. The new helper gives 70,000. - `antigravity-swarm.db.test.ts`: 30 of 30 runs passed with 12 CPU-burning processes running. - All 21 suites that changed seeds pass locally. The two changed lock suites pass (72 tests). ## Risks - Low risk. Only test files change. The product code is unchanged. - Longer test prefixes make test issue identifiers longer. One assertion that checked a four-character prefix is updated. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, GitHub CLI) 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 - [x] 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>
234 lines
15 KiB
TypeScript
234 lines
15 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import { eq, sql } from "drizzle-orm";
|
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
import {
|
|
agents, agentWakeupRequests, assets, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, heartbeatRuns, issueAttachments,
|
|
issueComments, issues,
|
|
} from "@paperclipai/db";
|
|
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
|
|
import { appendHeartbeatRunEvent } from "../heartbeat-run-events.js";
|
|
import { undeliveredLegacyUserCommentIds } from "../explicit-native-continuation.js";
|
|
import { deliveredQueuedCommentIds } from "../queued-comment-delivery.js";
|
|
import {
|
|
claimFirstTurnQueuedInput, deferredWakeJoinsFirstTurn, firstTurnClaimedCommentIds, firstTurnQueuedCommentIds, firstTurnTakesAllQueuedComments,
|
|
firstTurnWakeColumns, firstTurnWakeContextFields, firstTurnWakePayloadFields, runAcceptsFirstTurnQueuedInput,
|
|
} from "./first-turn-queued-input.js";
|
|
import { uniqueIssuePrefix } from "../../__tests__/helpers/issue-prefix.js";
|
|
|
|
const support = await getEmbeddedPostgresTestSupport();
|
|
const USER = "first-turn-user";
|
|
|
|
describe.skipIf(!support.supported)("first-turn queued input", () => {
|
|
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
|
let db: ReturnType<typeof createDb>;
|
|
beforeAll(async () => {
|
|
database = await startEmbeddedPostgresTestDatabase("paperclip-first-turn-queued-input-");
|
|
db = createDb(database.connectionString);
|
|
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
|
|
afterAll(async () => { await db?.$client.end(); await database?.cleanup(); });
|
|
|
|
async function seed() {
|
|
const [company] = await db.insert(companies).values({ name: "First turn", issuePrefix: uniqueIssuePrefix("F") }).returning();
|
|
const [agent] = await db.insert(agents).values({ companyId: company!.id, name: "Codie", adapterType: "paperclip_runner" }).returning();
|
|
const issueId = randomUUID();
|
|
const runId = await startRun(company!.id, agent!.id, issueId);
|
|
await db.insert(issues).values({ id: issueId, companyId: company!.id, title: "Fix the reports", status: "in_progress",
|
|
assigneeAgentId: agent!.id, executionRunId: runId });
|
|
return { companyId: company!.id, agentId: agent!.id, issueId, runId };
|
|
}
|
|
|
|
async function startRun(companyId: string, agentId: string, issueId: string) {
|
|
const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "running", runtimeMode: "native",
|
|
runtimeModeResolvedAt: new Date(), nativeIssueId: issueId, responsibleUserId: USER, startedAt: new Date(),
|
|
contextSnapshot: { issueId } }).returning();
|
|
return run!.id;
|
|
}
|
|
|
|
/** A user's comment saved behind the active run, in the shape the previous release writes. */
|
|
async function queueMessage(f: Awaited<ReturnType<typeof seed>>, body: string) {
|
|
const [comment] = await db.insert(issueComments).values({ companyId: f.companyId, issueId: f.issueId,
|
|
authorType: "user", authorUserId: USER, body }).returning();
|
|
const [existing] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.status, "deferred_issue_execution"))
|
|
.then(rows => rows.filter(row => row.companyId === f.companyId));
|
|
const ids = [...((existing?.payload?._paperclipWakeContext as { wakeCommentIds?: string[] } | undefined)?.wakeCommentIds ?? []), comment!.id];
|
|
const payload = { issueId: f.issueId, commentId: comment!.id, _paperclipWakeContext: { issueId: f.issueId, taskId: f.issueId,
|
|
wakeReason: "issue_commented", source: "issue.comment", wakeCommentId: comment!.id, wakeCommentIds: ids } };
|
|
if (existing) await db.update(agentWakeupRequests).set({ payload }).where(eq(agentWakeupRequests.id, existing.id));
|
|
else await db.insert(agentWakeupRequests).values({ companyId: f.companyId, agentId: f.agentId, source: "automation",
|
|
triggerDetail: "system", reason: "issue_execution_deferred", status: "deferred_issue_execution",
|
|
requestedByActorType: "user", requestedByActorId: USER, payload });
|
|
return comment!.id;
|
|
}
|
|
|
|
const binding = (f: { companyId: string; issueId: string; agentId: string }, runId: string) =>
|
|
({ companyId: f.companyId, issueId: f.issueId, agentId: f.agentId, runId });
|
|
const accept = (f: { companyId: string; agentId: string }, runId: string) => appendHeartbeatRunEvent(db, {
|
|
companyId: f.companyId, runId, agentId: f.agentId, eventType: "turn.accepted", stream: "system", level: "info", message: "turn accepted" });
|
|
const readRun = async (id: string) => (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, id)))[0]!;
|
|
|
|
it("takes no queued message into a swarm run, whose only instruction is the recorded request", async () => {
|
|
const f = await seed();
|
|
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, antigravitySwarmCommentId: randomUUID() } }).where(eq(heartbeatRuns.id, f.runId));
|
|
await queueMessage(f, "an ordinary message written while the swarm prepares");
|
|
expect(await claimFirstTurnQueuedInput(db, binding(f, f.runId))).toBeNull();
|
|
// Nor does Interrupt treat it as a first turn that will take the message.
|
|
expect(await runAcceptsFirstTurnQueuedInput(db, await readRun(f.runId))).toBe(false);
|
|
});
|
|
|
|
// The board's queue view reads a lean projection of the wake. It must decide as
|
|
// the first-turn claim does, or a waiting /swarm looks sent and loses its controls.
|
|
it("keeps a queued /swarm waiting in the board's lean view, as the first-turn claim does", async () => {
|
|
const f = await seed();
|
|
const ordinary = await queueMessage(f, "an ordinary message");
|
|
const lean = async () => (await db.select({ ...firstTurnWakeColumns, status: agentWakeupRequests.status,
|
|
payload: sql<Record<string, unknown>>`jsonb_build_object(${firstTurnWakePayloadFields(agentWakeupRequests.payload)},
|
|
'_paperclipWakeContext', jsonb_build_object(${firstTurnWakeContextFields(agentWakeupRequests.payload)},
|
|
'wakeCommentIds', ${agentWakeupRequests.payload}->'_paperclipWakeContext'->'wakeCommentIds'))` })
|
|
.from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, f.companyId)))[0]!;
|
|
const view = async () => firstTurnQueuedCommentIds(db, { companyId: f.companyId, issueId: f.issueId, runId: f.runId, wake: await lean() });
|
|
expect(await view()).toEqual([ordinary]);
|
|
const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, f.companyId));
|
|
await db.update(agentWakeupRequests).set({ payload: { ...wake!.payload,
|
|
_paperclipWakeContext: { ...(wake!.payload!._paperclipWakeContext as object), antigravitySwarmCommentId: ordinary } } }).where(eq(agentWakeupRequests.id, wake!.id));
|
|
expect(await view()).toEqual([]);
|
|
expect(await claimFirstTurnQueuedInput(db, binding(f, f.runId))).toBeNull();
|
|
});
|
|
|
|
it("gives a message that arrived during preparation to the first turn, without a stop", async () => {
|
|
const f = await seed();
|
|
const message = await queueMessage(f, "oh i mean each of the ones that appeared within the last 24 hours");
|
|
expect(await runAcceptsFirstTurnQueuedInput(db, await readRun(f.runId))).toBe(true);
|
|
const startedAt = performance.now();
|
|
const firstTurn = await claimFirstTurnQueuedInput(db, binding(f, f.runId));
|
|
const sealMs = performance.now() - startedAt;
|
|
console.info(`first-turn queued input seal took ${sealMs.toFixed(1)}ms before turn.start`);
|
|
expect(firstTurn).toContain("oh i mean each of the ones that appeared within the last 24 hours");
|
|
expect(firstTurn).toContain(`comment ${message}`);
|
|
const run = await readRun(f.runId);
|
|
expect(run.status).toBe("running");
|
|
expect([...firstTurnClaimedCommentIds(run)]).toEqual([message]);
|
|
// Sealed: a later message waits for the turn boundary and Interrupt applies.
|
|
expect(await runAcceptsFirstTurnQueuedInput(db, run)).toBe(false);
|
|
const later = await queueMessage(f, "one more thing");
|
|
expect(await claimFirstTurnQueuedInput(db, binding(f, f.runId))).not.toContain("one more thing");
|
|
expect(firstTurnClaimedCommentIds(await readRun(f.runId)).has(later)).toBe(false);
|
|
expect(sealMs).toBeLessThan(1_000);
|
|
});
|
|
|
|
it("delivers two messages from preparation in their queued order", async () => {
|
|
const f = await seed();
|
|
await queueMessage(f, "FIRST follow-up");
|
|
await queueMessage(f, "SECOND follow-up");
|
|
const firstTurn = await claimFirstTurnQueuedInput(db, binding(f, f.runId));
|
|
expect(firstTurn).toMatch(/Message 1 of 2[^\n]*\nFIRST follow-up[\s\S]*Message 2 of 2[^\n]*\nSECOND follow-up/);
|
|
});
|
|
|
|
it("keeps the message queued when the run fails before turn.start, then delivers it exactly once", async () => {
|
|
const f = await seed();
|
|
const message = await queueMessage(f, "please include the staging run");
|
|
expect(await claimFirstTurnQueuedInput(db, binding(f, f.runId))).toContain("please include the staging run");
|
|
// A restart before the provider accepted the turn repeats the same input.
|
|
expect(await claimFirstTurnQueuedInput(db, binding(f, f.runId))).toContain("please include the staging run");
|
|
await db.update(heartbeatRuns).set({ status: "failed", finishedAt: new Date() }).where(eq(heartbeatRuns.id, f.runId));
|
|
// Not consumed: release promotion and Send both still deliver it.
|
|
const ids = { companyId: f.companyId, issueId: f.issueId, agentId: f.agentId, commentIds: [message] };
|
|
expect([...await deliveredQueuedCommentIds(db, ids)]).toEqual([]);
|
|
expect(await undeliveredLegacyUserCommentIds(db, f.companyId, f.issueId, f.agentId, [message])).toEqual([message]);
|
|
const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, f.companyId));
|
|
expect(wake!.status).toBe("deferred_issue_execution");
|
|
|
|
// The next run takes it into its own first turn; the provider accepts.
|
|
const nextRunId = await startRun(f.companyId, f.agentId, f.issueId);
|
|
await db.update(issues).set({ executionRunId: nextRunId }).where(eq(issues.id, f.issueId));
|
|
expect(await claimFirstTurnQueuedInput(db, binding(f, nextRunId))).toContain("please include the staging run");
|
|
await accept(f, nextRunId);
|
|
expect([...await deliveredQueuedCommentIds(db, ids)]).toEqual([message]);
|
|
expect(await undeliveredLegacyUserCommentIds(db, f.companyId, f.issueId, f.agentId, [message])).toEqual([]);
|
|
|
|
// Exactly once: a later run, and a retry that copied the context, take nothing.
|
|
await db.update(heartbeatRuns).set({ status: "failed", finishedAt: new Date() }).where(eq(heartbeatRuns.id, nextRunId));
|
|
const thirdRunId = await startRun(f.companyId, f.agentId, f.issueId);
|
|
await db.update(heartbeatRuns).set({ contextSnapshot: (await readRun(nextRunId)).contextSnapshot })
|
|
.where(eq(heartbeatRuns.id, thirdRunId));
|
|
await db.update(issues).set({ executionRunId: thirdRunId }).where(eq(issues.id, f.issueId));
|
|
expect(await claimFirstTurnQueuedInput(db, binding(f, thirdRunId))).toBeNull();
|
|
});
|
|
|
|
it("counts a message as delivered once the provider accepted the turn, even if the run later fails", async () => {
|
|
const f = await seed();
|
|
const message = await queueMessage(f, "ship it");
|
|
await claimFirstTurnQueuedInput(db, binding(f, f.runId));
|
|
await accept(f, f.runId);
|
|
await db.update(heartbeatRuns).set({ status: "failed", finishedAt: new Date() }).where(eq(heartbeatRuns.id, f.runId));
|
|
expect([...await deliveredQueuedCommentIds(db, { companyId: f.companyId, issueId: f.issueId, agentId: f.agentId,
|
|
commentIds: [message] })]).toEqual([message]);
|
|
});
|
|
|
|
it("treats a run saved by the previous release as started once its provider accepted a turn", async () => {
|
|
const f = await seed();
|
|
await queueMessage(f, "mid-turn message");
|
|
await accept(f, f.runId);
|
|
expect(await runAcceptsFirstTurnQueuedInput(db, await readRun(f.runId))).toBe(false);
|
|
});
|
|
|
|
it("leaves another user's message and a run without a responsible user to their own delivery", async () => {
|
|
const f = await seed();
|
|
await queueMessage(f, "mine");
|
|
await db.update(agentWakeupRequests).set({ requestedByActorId: "someone-else" }).where(eq(agentWakeupRequests.companyId, f.companyId));
|
|
expect(await claimFirstTurnQueuedInput(db, binding(f, f.runId))).toBeNull();
|
|
});
|
|
it("seals on a one-connection pool without waiting for a second connection", async () => {
|
|
const f = await seed();
|
|
await queueMessage(f, "secret-free follow-up");
|
|
const single = createDb(database.connectionString, { maxConnections: 1 });
|
|
try {
|
|
const sealed = await Promise.race([
|
|
claimFirstTurnQueuedInput(single, binding(f, f.runId)),
|
|
new Promise<"stuck">((resolve) => setTimeout(() => resolve("stuck"), 5_000)),
|
|
]);
|
|
expect(sealed).toContain("secret-free follow-up");
|
|
} finally {
|
|
await single.$client.end({ timeout: 1 });
|
|
}
|
|
});
|
|
|
|
it("leaves a message with files on its own delivery path so the files reach the agent", async () => {
|
|
const f = await seed();
|
|
await queueMessage(f, "text only");
|
|
const withFile = await queueMessage(f, "see the attached screenshot");
|
|
const [asset] = await db.insert(assets).values({ companyId: f.companyId, provider: "local_disk",
|
|
objectKey: `${f.companyId}/screenshot`, originalFilename: "screenshot.png", contentType: "image/png",
|
|
byteSize: 1, sha256: "0".repeat(64) }).returning();
|
|
await db.insert(issueAttachments).values({ companyId: f.companyId, issueId: f.issueId, assetId: asset!.id,
|
|
issueCommentId: withFile });
|
|
const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, f.companyId));
|
|
const queuedIds = (wake!.payload?._paperclipWakeContext as { wakeCommentIds: string[] }).wakeCommentIds;
|
|
// Interrupt keeps its meaning for this queue: the first turn cannot take all of it.
|
|
expect(await firstTurnTakesAllQueuedComments(db, { companyId: f.companyId, issueId: f.issueId, responsibleUserId: USER,
|
|
commentIds: queuedIds })).toBe(false);
|
|
const firstTurn = await claimFirstTurnQueuedInput(db, binding(f, f.runId));
|
|
expect(firstTurn).toContain("text only");
|
|
expect(firstTurn).not.toContain("see the attached screenshot");
|
|
const run = await readRun(f.runId);
|
|
expect(firstTurnClaimedCommentIds(run).has(withFile)).toBe(false);
|
|
await accept(f, f.runId);
|
|
// Still owed after the turn: release promotion delivers it with its file.
|
|
expect([...await deliveredQueuedCommentIds(db, { companyId: f.companyId, issueId: f.issueId, agentId: f.agentId,
|
|
commentIds: [withFile] })]).toEqual([]);
|
|
});
|
|
});
|
|
|
|
describe("a /swarm request never joins another run's first turn", () => {
|
|
const user = "user-1";
|
|
const commentId = "6f1c1b0e-5a52-4b0a-9a51-0d6c9c3b2f11";
|
|
const wake = (context: Record<string, unknown>) => ({
|
|
agentId: "agent-1", status: "deferred_issue_execution", requestedByActorType: "user", requestedByActorId: user, reason: "issue_commented",
|
|
payload: { issueId: "issue-1", commentId, mutation: "comment", _paperclipWakeContext: { wakeReason: "issue_commented", commentId, wakeCommentId: commentId, wakeCommentIds: [commentId], ...context } },
|
|
});
|
|
it("keeps the swarm request for its own run selection", () => {
|
|
const run = { agentId: "agent-1", responsibleUserId: user };
|
|
expect(deferredWakeJoinsFirstTurn(wake({}), run)).toBe(true);
|
|
expect(deferredWakeJoinsFirstTurn(wake({ antigravitySwarmCommentId: commentId }), run)).toBe(false);
|
|
});
|
|
});
|