Files
PaperClipAI/server/src/services/native-runtime/native-runner-checkpoint-save.test.ts
T
DottaandClaude Opus 5.5 bde164de54 test(server): fix the issue-prefix collision and the shared-role idle timeout that fail Cloud readiness (#23013)
## 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>
2026-11-25 21:42:21 -06:00

173 lines
10 KiB
TypeScript

import { randomBytes, randomUUID } from "node:crypto";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { eq, sql } from "drizzle-orm";
import { agents, checkpointDb, closeCheckpointDb, companies, createDb, heartbeatRuns, issues, nativeRunFinalizations, nativeRunnerCheckpoints,
subscribeDatabaseWork } from "@paperclipai/db";
import { DELIVERY_QUEUES } from "../delivery-work-notifications.js";
import { nativeRunnerCheckpointWriter } from "./native-runner-checkpoint.js";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
import { uniqueIssuePrefix } from "../../__tests__/helpers/issue-prefix.js";
const support = await getEmbeddedPostgresTestSupport();
(support.supported ? describe : describe.skip)("native runner checkpoint save", () => {
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
let otherDb: ReturnType<typeof createDb>;
beforeAll(async () => {
process.env.PAPERCLIP_SECRETS_MASTER_KEY ??= randomBytes(32).toString("base64");
temporary = await startEmbeddedPostgresTestDatabase("paperclip-checkpoint-save-");
db = createDb(temporary.connectionString);
otherDb = createDb(temporary.connectionString);
}, 60_000);
afterAll(async () => {
if (db) await closeCheckpointDb(db, 1);
await otherDb?.$client.end({ timeout: 1 });
await db?.$client.end({ timeout: 1 });
await temporary?.cleanup();
});
const fixture = async (leaseExpiresAt: Date) => {
const [company] = await db.insert(companies).values({ name: "Checkpoint save", issuePrefix: uniqueIssuePrefix("CS") }).returning();
const [agent] = await db.insert(agents).values({ companyId: company!.id, name: "Checkpoint agent", adapterType: "process" }).returning();
const [issue] = await db.insert(issues).values({ companyId: company!.id, title: "Checkpoint task" }).returning();
const runId = randomUUID(), leaseOwner = randomUUID(), bootId = randomUUID();
await db.insert(heartbeatRuns).values({ id: runId, companyId: company!.id, agentId: agent!.id, status: "running",
runtimeMode: "native", nativeIssueId: issue!.id, issueId: issue!.id });
await db.insert(nativeRunFinalizations).values({ runId, companyId: company!.id, issueId: issue!.id, phase: "observed", attempt: 0,
controllerBootId: bootId, controllerPid: process.pid, controllerProcessStartedAt: new Date(), controllerGeneration: 1,
leaseOwner, leaseExpiresAt });
const write = nativeRunnerCheckpointWriter(db, { companyId: company!.id, issueId: issue!.id, runId, authorityRunId: runId,
bootId, generation: 1, leaseOwner });
const checkpoint = (changed: Map<string, string>, reset: boolean) => ({
runId, records: new Map(changed), changedRecords: changed, removedRecords: [], reset, workCommandIds: [], predecessor: null,
runnerVersion: "test", runnerDigest: `sha256:${"a".repeat(64)}`,
recoveryEvidence: { runnerInstanceId: "test", normalizedSessionId: "test", authenticatedConnectionCount: 1, highestRecordedSourceSeq: 0 },
restoreSessionDirectory() {},
}) as unknown as Parameters<typeof write>[0];
return { runId, companyId: company!.id, issueId: issue!.id, write, checkpoint };
};
const sentStatements = async (action: () => Promise<unknown>) => {
const statements: string[] = [];
const options = checkpointDb(db).$client.options as { debug?: unknown };
options.debug = (_connection: number, text: string) => { statements.push(text.trim().replace(/\s+/g, " ")); };
try { await action(); return statements; } finally { options.debug = undefined; }
};
const parts = async (runId: string) => (await db.select({ part: nativeRunnerCheckpoints.part })
.from(nativeRunnerCheckpoints).where(eq(nativeRunnerCheckpoints.runId, runId))).map(row => row.part).sort();
const recoveryWakes = () => {
const events: string[] = [];
const unsubscribe = subscribeDatabaseWork(db, DELIVERY_QUEUES.nativeProcessSessions, event => { events.push(event); });
return { events, unsubscribe };
};
it("saves a routine checkpoint in one statement that checks the owner, and registers no recovery wake", async () => {
const f = await fixture(new Date(Date.now() + 3_600_000));
await f.write(f.checkpoint(new Map([["header", "{}"], ["cursor", "{\"ackedSourceSeq\":0}"]]), true));
const wakes = recoveryWakes();
let statements: string[];
try {
statements = await sentStatements(() => f.write(f.checkpoint(new Map([["event:1", "{}"], ["cursor", "{\"ackedSourceSeq\":1}"]]), false)));
} finally { wakes.unsubscribe(); }
expect(statements).toHaveLength(1);
expect(statements[0]).toMatch(/^with locked_owner as .* for update .* lease_expires_at > clock_timestamp\(\) .* insert into "native_runner_checkpoints"/);
expect(wakes.events).toEqual([]);
expect(await parts(f.runId)).toEqual(["cursor", "event:1", "header"]);
});
it("saves a reset with the owner lock, the write and the commit, and registers its recovery wake before the write", async () => {
const f = await fixture(new Date(Date.now() + 3_600_000));
await f.write(f.checkpoint(new Map([["header", "{}"], ["cursor", "{\"ackedSourceSeq\":0}"]]), true));
const wakes = recoveryWakes();
let statements: string[];
try {
statements = await sentStatements(() => f.write(f.checkpoint(new Map([["header", "{}"], ["cursor", "{\"ackedSourceSeq\":2}"]]), true)));
} finally { wakes.unsubscribe(); }
expect(statements[0]).toMatch(/^begin/i);
expect(statements[1]).toMatch(/pg_current_xact_id\(\)/);
expect(statements.at(-1)).toMatch(/^commit/i);
expect(wakes.events).toEqual(["intent", "settled"]);
expect(await parts(f.runId)).toEqual(["cursor", "header"]);
});
it.each(["takeover", "takeover with a reset"])("falls back to the full owner check when a routine save races a lease %s", async (race) => {
const f = await fixture(new Date(Date.now() + 3_600_000));
await f.write(f.checkpoint(new Map([["header", "{}"], ["cursor", "{\"ackedSourceSeq\":0}"]]), true));
let release!: () => void, locked!: () => void;
const released = new Promise<void>(resolve => { release = resolve; });
const lockedOwner = new Promise<void>(resolve => { locked = resolve; });
const holder = otherDb.transaction(async tx => {
await tx.execute(sql`select run_id from native_run_finalizations where run_id = ${f.runId} for update`);
await tx.update(nativeRunFinalizations).set({ leaseOwner: randomUUID(), controllerGeneration: 2 })
.where(eq(nativeRunFinalizations.runId, f.runId));
if (race === "takeover with a reset") {
await tx.delete(nativeRunnerCheckpoints).where(eq(nativeRunnerCheckpoints.runId, f.runId));
await tx.insert(nativeRunnerCheckpoints).values({ companyId: f.companyId, issueId: f.issueId, runId: f.runId,
part: "header", material: { successor: true } });
}
locked();
await released;
});
void holder.catch(() => undefined);
await lockedOwner;
const saved = f.write(f.checkpoint(new Map([["event:1", "{}"], ["cursor", "{\"ackedSourceSeq\":1}"]]), false))
.then(() => "saved", (error: Error) => error.message);
try {
await vi.waitFor(async () => {
const [waiting] = await otherDb.execute<{ count: number }>(sql`select count(*)::int as count from pg_stat_activity
where datname = current_database() and wait_event_type = 'Lock' and query like '%with locked_owner as%'`);
expect(waiting?.count).toBe(1);
}, { timeout: 10_000, interval: 20 });
} finally {
release();
await holder;
}
expect(await saved).toBe("native_runner_checkpoint_owner_lost");
expect(await parts(f.runId)).toEqual(race === "takeover" ? ["cursor", "header"] : ["header"]);
});
it("judges the lease after the owner lock, so a lease that expires while a routine save waits writes nothing", async () => {
const f = await fixture(new Date(Date.now() + 3_600_000));
await f.write(f.checkpoint(new Map([["header", "{}"], ["cursor", "{\"ackedSourceSeq\":0}"]]), true));
await db.update(nativeRunFinalizations).set({ leaseExpiresAt: sql`clock_timestamp() + interval '1 second'` })
.where(eq(nativeRunFinalizations.runId, f.runId));
let release!: () => void, locked!: () => void;
const released = new Promise<void>(resolve => { release = resolve; });
const lockedOwner = new Promise<void>(resolve => { locked = resolve; });
const holder = otherDb.transaction(async tx => {
await tx.execute(sql`select run_id from native_run_finalizations where run_id = ${f.runId} for update`);
locked();
await released;
});
void holder.catch(() => undefined);
await lockedOwner;
const saved = f.write(f.checkpoint(new Map([["event:1", "{}"], ["cursor", "{\"ackedSourceSeq\":1}"]]), false))
.then(() => "saved", (error: Error) => error.message);
try {
await vi.waitFor(async () => {
const [waiting] = await otherDb.execute<{ count: number }>(sql`select count(*)::int as count from pg_stat_activity
where datname = current_database() and wait_event_type = 'Lock' and query like '%with locked_owner as%'`);
expect(waiting?.count).toBe(1);
}, { timeout: 10_000, interval: 20 });
await otherDb.execute(sql`select pg_sleep(1.2)`);
} finally {
release();
await holder;
}
expect(await saved).toBe("native_runner_checkpoint_owner_lost");
expect(await parts(f.runId)).toEqual(["cursor", "header"]);
});
it("refuses a save after the owner's lease expired and writes nothing", async () => {
const f = await fixture(new Date(Date.now() + 3_600_000));
await f.write(f.checkpoint(new Map([["header", "{}"]]), true));
await db.update(nativeRunFinalizations).set({ leaseExpiresAt: new Date(Date.now() - 1_000) })
.where(eq(nativeRunFinalizations.runId, f.runId));
await expect(f.write(f.checkpoint(new Map([["event:1", "{}"]]), false))).rejects.toThrow("native_runner_checkpoint_owner_lost");
expect((await db.select({ part: nativeRunnerCheckpoints.part }).from(nativeRunnerCheckpoints)
.where(eq(nativeRunnerCheckpoints.runId, f.runId))).map(row => row.part)).toEqual(["header"]);
});
});