mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 15:52:36 +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>
124 lines
5.9 KiB
TypeScript
124 lines
5.9 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import { setTimeout as delay } from "node:timers/promises";
|
|
import { sql } from "drizzle-orm";
|
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
import { createDb } from "@paperclipai/db";
|
|
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js";
|
|
import { IsolatedRepositorySourceBusy, withIsolatedRepositorySourceLock } from "./isolated-remote-workspace-source.js";
|
|
import { withIndependentWorkspaceSourceLocks } from "./workspace-source-lock.js";
|
|
|
|
const support = await getEmbeddedPostgresTestSupport();
|
|
const describePostgres = support.supported ? describe : describe.skip;
|
|
if (!support.supported) console.warn(`Workspace source lock tests require Postgres: ${support.reason}`);
|
|
|
|
describePostgres("workspace source ownership during preparation", () => {
|
|
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
|
let db: ReturnType<typeof createDb>;
|
|
|
|
beforeAll(async () => {
|
|
database = await startEmbeddedPostgresTestDatabase("workspace-source-lock-");
|
|
db = createDb(database.connectionString, { maxConnections: 1 });
|
|
const rows = await db.execute(sql`select current_database() as name`);
|
|
await db.execute(sql`alter database ${sql.identifier(String(rows[0].name))} set idle_in_transaction_session_timeout = '1s'`);
|
|
});
|
|
|
|
afterAll(async () => {
|
|
try {
|
|
await db?.$client.end({ timeout: 1 });
|
|
} finally {
|
|
await database?.cleanup();
|
|
}
|
|
});
|
|
|
|
it("keeps preparation exclusive beyond the idle timeout while the ordinary pool stays usable", async () => {
|
|
const companyId = randomUUID(), issueId = randomUUID();
|
|
let entered!: () => void, release!: () => void;
|
|
const started = new Promise<void>(resolve => { entered = resolve; });
|
|
const pending = new Promise<void>(resolve => { release = resolve; });
|
|
const preparation = withIsolatedRepositorySourceLock(db, companyId, issueId, async () => {
|
|
await db.execute(sql`select 1`);
|
|
entered();
|
|
await pending;
|
|
return withIsolatedRepositorySourceLock(db, companyId, issueId, async () => "prepared");
|
|
}).then(value => ({ value }), error => ({ error }));
|
|
|
|
try {
|
|
await started;
|
|
await delay(1400);
|
|
await expect(db.execute(sql`select 1 as usable`)).resolves.toMatchObject([{ usable: 1 }]);
|
|
await expect(withIsolatedRepositorySourceLock(db, companyId, issueId, async () => "overlap", true))
|
|
.rejects.toBeInstanceOf(IsolatedRepositorySourceBusy);
|
|
await expect(withIsolatedRepositorySourceLock(db, randomUUID(), issueId, async () => "independent", true))
|
|
.resolves.toBe("independent");
|
|
} finally {
|
|
release();
|
|
await preparation;
|
|
}
|
|
expect(await preparation).toEqual({ value: "prepared" });
|
|
await expect(withIsolatedRepositorySourceLock(db, companyId, issueId, async () => "next", true))
|
|
.resolves.toBe("next");
|
|
});
|
|
|
|
it("releases a failed preparation and preserves the original failure", async () => {
|
|
const companyId = randomUUID(), issueId = randomUUID();
|
|
const failure = new Error("source preparation failed");
|
|
await expect(withIsolatedRepositorySourceLock(db, companyId, issueId, async () => {
|
|
await delay(1400);
|
|
throw failure;
|
|
})).rejects.toBe(failure);
|
|
await expect(withIsolatedRepositorySourceLock(db, companyId, issueId, async () => "recovered", true))
|
|
.resolves.toBe("recovered");
|
|
});
|
|
|
|
// RC-53: a recovery timer armed inside one source scope later dispatched a
|
|
// reattached run. Its preparation joined the committed scope and failed with
|
|
// `Failed query: select pg_try_advisory_xact_lock(...)` on a closed connection.
|
|
it("gives work detached from a finished scope its own source lock", async () => {
|
|
const companyId = randomUUID(), outerIssueId = randomUUID(), laterIssueId = randomUUID();
|
|
let fire!: () => void, entered!: () => void, release!: () => void;
|
|
const fired = new Promise<void>(resolve => { fire = resolve; });
|
|
const started = new Promise<void>(resolve => { entered = resolve; });
|
|
const pending = new Promise<void>(resolve => { release = resolve; });
|
|
let detached!: Promise<unknown>;
|
|
await withIsolatedRepositorySourceLock(db, companyId, outerIssueId, async () => {
|
|
detached = fired.then(() => withIsolatedRepositorySourceLock(db, companyId, laterIssueId, async () => {
|
|
entered();
|
|
await pending;
|
|
return "prepared";
|
|
})).then(value => ({ value }), error => ({ error: String(error) }));
|
|
});
|
|
fire();
|
|
expect(await Promise.race([started.then(() => "entered"), detached])).toBe("entered");
|
|
try {
|
|
await expect(withIsolatedRepositorySourceLock(db, companyId, laterIssueId, async () => "overlap", true))
|
|
.rejects.toBeInstanceOf(IsolatedRepositorySourceBusy);
|
|
} finally {
|
|
release();
|
|
}
|
|
expect(await detached).toEqual({ value: "prepared" });
|
|
});
|
|
|
|
it("keeps an independent preparation's lock after the scope that started it commits", async () => {
|
|
const companyId = randomUUID(), outerIssueId = randomUUID(), runIssueId = randomUUID();
|
|
let entered!: () => void, release!: () => void;
|
|
const started = new Promise<void>(resolve => { entered = resolve; });
|
|
const pending = new Promise<void>(resolve => { release = resolve; });
|
|
let preparation!: Promise<unknown>;
|
|
await withIsolatedRepositorySourceLock(db, companyId, outerIssueId, async () => {
|
|
preparation = withIndependentWorkspaceSourceLocks(db, { companyId, issueIds: [runIssueId] }, async () => {
|
|
entered();
|
|
await pending;
|
|
return "prepared";
|
|
}).then(value => ({ value }), error => ({ error: String(error) }));
|
|
await started;
|
|
});
|
|
try {
|
|
await expect(withIsolatedRepositorySourceLock(db, companyId, runIssueId, async () => "overlap", true))
|
|
.rejects.toBeInstanceOf(IsolatedRepositorySourceBusy);
|
|
} finally {
|
|
release();
|
|
}
|
|
expect(await preparation).toEqual({ value: "prepared" });
|
|
});
|
|
});
|