From bde164de54b038dfeacfe738334eb1c73fa05716 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:42:21 -0600 Subject: [PATCH] test(server): fix the issue-prefix collision and the shared-role idle timeout that fail Cloud readiness (#23013) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 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 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 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 --- .../agent-hire-idempotency-routes.test.ts | 3 +- .../antigravity-swarm-request-path.test.ts | 5 +-- server/src/__tests__/cases-routes.test.ts | 5 +-- .../src/__tests__/decision-training.test.ts | 3 +- .../environment-custom-images-service.test.ts | 7 ++-- .../__tests__/helpers/issue-prefix.test.ts | 14 ++++++++ server/src/__tests__/helpers/issue-prefix.ts | 5 +++ .../issue-blocker-diagnostics-routes.test.ts | 3 +- .../issue-subtree-diagnostics-routes.test.ts | 3 +- .../issue-wake-diagnostics-routes.test.ts | 3 +- .../low-trust-red-team-routes.test.ts | 5 +-- .../test-database-session-settings.test.ts | 33 +++++++++++++++++++ .../__tests__/work-timeline-service.test.ts | 5 +-- .../src/__tests__/workload-identity.test.ts | 3 +- .../src/services/antigravity-swarm.db.test.ts | 3 +- .../budget-resume-continuation.test.ts | 3 +- ...lated-remote-workspace-source-lock.test.ts | 5 ++- .../first-turn-queued-input.test.ts | 3 +- .../generate-image-tool.test.ts | 3 +- .../model-rejected-retry.test.ts | 4 +-- .../native-provider-turn-wait.test.ts | 3 +- .../native-runner-checkpoint-save.test.ts | 3 +- .../native-workspace-finalizer.test.ts | 8 ++--- .../queued-comment-history-read.test.ts | 3 +- .../run-evidence-migration-appended.test.ts | 3 +- ...package-storage-migration-postgres.test.ts | 3 +- 26 files changed, 106 insertions(+), 35 deletions(-) create mode 100644 server/src/__tests__/helpers/issue-prefix.test.ts create mode 100644 server/src/__tests__/helpers/issue-prefix.ts create mode 100644 server/src/__tests__/test-database-session-settings.test.ts diff --git a/server/src/__tests__/agent-hire-idempotency-routes.test.ts b/server/src/__tests__/agent-hire-idempotency-routes.test.ts index 282cae1da5d..e1b649c7378 100644 --- a/server/src/__tests__/agent-hire-idempotency-routes.test.ts +++ b/server/src/__tests__/agent-hire-idempotency-routes.test.ts @@ -17,6 +17,7 @@ import { import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; import { errorHandler } from "../middleware/index.js"; import { agentRoutes } from "../routes/agents.js"; +import { uniqueIssuePrefix } from "./helpers/issue-prefix.js"; const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; @@ -43,7 +44,7 @@ async function seedHiringFixture(db: Db) { .insert(companies) .values({ name: `Idempotency Co ${nonce}`, - issuePrefix: `ID${nonce.slice(0, 4).toUpperCase()}`, + issuePrefix: uniqueIssuePrefix("ID"), defaultResponsibleUserId: "board-user", // Direct hires (no board approval) mirror the reported QA org where the // duplicate "Sam 2" agent was actually created. diff --git a/server/src/__tests__/antigravity-swarm-request-path.test.ts b/server/src/__tests__/antigravity-swarm-request-path.test.ts index 540c109f622..1578bc9d66b 100644 --- a/server/src/__tests__/antigravity-swarm-request-path.test.ts +++ b/server/src/__tests__/antigravity-swarm-request-path.test.ts @@ -8,6 +8,7 @@ import { instanceSettingsService } from "../services/instance-settings.js"; import { buildNativeExecutionInput } from "../services/native-runtime/native-execution-input.js"; import { nativeRuntimeContextFixture } from "../services/native-runtime/runtime-context.test-fixture.js"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { uniqueIssuePrefix } from "./helpers/issue-prefix.js"; const support = await getEmbeddedPostgresTestSupport(); const USER = "swarm-user"; @@ -31,7 +32,7 @@ describe.skipIf(!support.supported)("the /swarm request path to the CLI", () => afterAll(async () => { await db?.$client.end(); await database?.cleanup(); }); it("sends byte for byte the recorded comment (the request the composer sent), never a merged wake's agent comment or the description", async () => { - const [company] = await db.insert(companies).values({ name: "Swarm", issuePrefix: `P${randomUUID().slice(0, 4)}` }).returning(); + const [company] = await db.insert(companies).values({ name: "Swarm", issuePrefix: uniqueIssuePrefix("P") }).returning(); const [agent] = await db.insert(agents).values({ companyId: company!.id, name: "Gemma", adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "antigravity", model: "gemini-3.8-flash-low" } }).returning(); const [issue] = await db.insert(issues).values({ companyId: company!.id, title: "Write two files", description: DESCRIPTION, @@ -82,7 +83,7 @@ describe.skipIf(!support.supported)("the /swarm request path to the CLI", () => }); it("marks only the user's recorded request as a swarm, never from the comment's own text or metadata", async () => { - const [company] = await db.insert(companies).values({ name: "Swarm marker", issuePrefix: `M${randomUUID().slice(0, 4)}` }).returning(); + const [company] = await db.insert(companies).values({ name: "Swarm marker", issuePrefix: uniqueIssuePrefix("M") }).returning(); const [agent] = await db.insert(agents).values({ companyId: company!.id, name: "Gemma", adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "antigravity", model: "gemini-3.8-flash-low" } }).returning(); const [issue] = await db.insert(issues).values({ companyId: company!.id, title: "Swarm", status: "todo", assigneeAgentId: agent!.id }).returning(); diff --git a/server/src/__tests__/cases-routes.test.ts b/server/src/__tests__/cases-routes.test.ts index d9b5088cc17..ebfe78f4f78 100644 --- a/server/src/__tests__/cases-routes.test.ts +++ b/server/src/__tests__/cases-routes.test.ts @@ -46,6 +46,7 @@ import { assertCaseTrustedForExecution, canActorReadCase, canActorReceiveCase, r import { instanceSettingsService } from "../services/instance-settings.js"; import { subscribeCompanyLiveEvents } from "../services/live-events.js"; import type { StorageService } from "../storage/types.js"; +import { uniqueIssuePrefix } from "./helpers/issue-prefix.js"; const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; @@ -166,7 +167,7 @@ describeEmbeddedPostgres("cases routes", () => { async function seedCompany(prefix = "CASE") { const [company] = await db.insert(companies).values({ name: `${prefix} Co`, - issuePrefix: `${prefix}${randomUUID().replace(/-/g, "").slice(0, 4)}`, + issuePrefix: uniqueIssuePrefix(prefix), }).returning(); return company!; } @@ -360,7 +361,7 @@ describeEmbeddedPostgres("cases routes", () => { const byIdentifier = await http.get(`/api/cases/${created.body.identifier}`).expect(200); expect(byIdentifier.body.id).toBe(created.body.id); - expect(byIdentifier.body.identifier).toMatch(/^REF[A-Z0-9]{4}-C1$/); + expect(byIdentifier.body.identifier).toMatch(/^REF[A-Z0-9]{12}-C1$/); }); it("auto-links run writes to their issue with a work link and event", async () => { diff --git a/server/src/__tests__/decision-training.test.ts b/server/src/__tests__/decision-training.test.ts index b274b50ce46..fe0f880629f 100644 --- a/server/src/__tests__/decision-training.test.ts +++ b/server/src/__tests__/decision-training.test.ts @@ -29,6 +29,7 @@ import { errorHandler } from "../middleware/index.js"; import { decisionTrainingRoutes } from "../routes/decision-training.js"; import { attentionService } from "../services/attention.js"; import { captureDecisionSnapshot, decisionTrainingService, withoutGoogleWorkspaceContent } from "../services/decision-training.js"; +import { uniqueIssuePrefix } from "./helpers/issue-prefix.js"; const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; @@ -76,7 +77,7 @@ describeEmbeddedPostgres("decision training", () => { const atCutoffId = randomUUID(); const afterId = randomUUID(); - await db.insert(companies).values({ id: companyId, name: "Decision Co", issuePrefix: `D${companyId.slice(0, 4)}` }); + await db.insert(companies).values({ id: companyId, name: "Decision Co", issuePrefix: uniqueIssuePrefix("D") }); await db.insert(projects).values({ id: projectId, companyId, name: "Decisions" }); await db.insert(issues).values({ id: issueId, diff --git a/server/src/__tests__/environment-custom-images-service.test.ts b/server/src/__tests__/environment-custom-images-service.test.ts index 23448af57ae..198e18e1f67 100644 --- a/server/src/__tests__/environment-custom-images-service.test.ts +++ b/server/src/__tests__/environment-custom-images-service.test.ts @@ -35,6 +35,7 @@ import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase, } from "./helpers/embedded-postgres.js"; +import { uniqueIssuePrefix } from "./helpers/issue-prefix.js"; const externalTestDatabase = resolveExternalTestDatabaseUrl("PAPERCLIP_CUSTOM_IMAGE_TEST_DATABASE_URL"); const embeddedPostgresSupport = externalTestDatabase ? { supported: true, reason: undefined } : await getEmbeddedPostgresTestSupport(); @@ -189,7 +190,7 @@ describeEmbeddedPostgres("environmentCustomImageService", () => { const companyId = randomUUID(); const environmentId = randomUUID(); await db.insert(companies).values( - { id: companyId, name: "Acme", issuePrefix: `A${companyId.slice(0, 4)}` }, + { id: companyId, name: "Acme", issuePrefix: uniqueIssuePrefix("A") }, ); await db.insert(environments).values({ id: environmentId, @@ -1101,7 +1102,7 @@ describeEmbeddedPostgres("environmentCustomImageService reconciliation", () => { const companyId = randomUUID(); const environmentId = randomUUID(); await db.insert(companies).values( - { id: companyId, name: "Acme", issuePrefix: `A${companyId.slice(0, 4)}` }, + { id: companyId, name: "Acme", issuePrefix: uniqueIssuePrefix("A") }, ); await db.insert(environments).values({ id: environmentId, @@ -1422,7 +1423,7 @@ describeEmbeddedPostgres("environmentCustomImageService relink", () => { const companyId = randomUUID(); const environmentId = randomUUID(); await db.insert(companies).values( - { id: companyId, name: "Acme", issuePrefix: `A${companyId.slice(0, 4)}` }, + { id: companyId, name: "Acme", issuePrefix: uniqueIssuePrefix("A") }, ); await db.insert(environments).values({ id: environmentId, diff --git a/server/src/__tests__/helpers/issue-prefix.test.ts b/server/src/__tests__/helpers/issue-prefix.test.ts new file mode 100644 index 00000000000..2c4f5e851fc --- /dev/null +++ b/server/src/__tests__/helpers/issue-prefix.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from "vitest"; +import { uniqueIssuePrefix } from "./issue-prefix.js"; + +describe("uniqueIssuePrefix", () => { + it("does not repeat across more companies than four hex characters can name", () => { + const count = 70_000; + const prefixes = new Set(Array.from({ length: count }, () => uniqueIssuePrefix("S"))); + expect(prefixes.size).toBe(count); + }); + + it("keeps the tag and an uppercase hex suffix", () => { + expect(uniqueIssuePrefix("CS")).toMatch(/^CS[0-9A-F]{12}$/); + }); +}); diff --git a/server/src/__tests__/helpers/issue-prefix.ts b/server/src/__tests__/helpers/issue-prefix.ts new file mode 100644 index 00000000000..96024854120 --- /dev/null +++ b/server/src/__tests__/helpers/issue-prefix.ts @@ -0,0 +1,5 @@ +import { randomBytes } from "node:crypto"; + +export function uniqueIssuePrefix(tag: string) { + return `${tag}${randomBytes(6).toString("hex").toUpperCase()}`; +} diff --git a/server/src/__tests__/issue-blocker-diagnostics-routes.test.ts b/server/src/__tests__/issue-blocker-diagnostics-routes.test.ts index e488f0266eb..871854e6d3a 100644 --- a/server/src/__tests__/issue-blocker-diagnostics-routes.test.ts +++ b/server/src/__tests__/issue-blocker-diagnostics-routes.test.ts @@ -19,6 +19,7 @@ import { } from "./helpers/embedded-postgres.js"; import { errorHandler } from "../middleware/index.js"; import { issueRoutes } from "../routes/issues.js"; +import { uniqueIssuePrefix } from "./helpers/issue-prefix.js"; const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; @@ -74,7 +75,7 @@ async function seedCompany(db: Db, label = "Diagnostics") { const nonce = randomUUID().slice(0, 8); const [company] = await db.insert(companies).values({ name: `${label} ${nonce}`, - issuePrefix: `DG${nonce.slice(0, 4).toUpperCase()}`, + issuePrefix: uniqueIssuePrefix("DG"), defaultResponsibleUserId: "board-user", }).returning(); return company!; diff --git a/server/src/__tests__/issue-subtree-diagnostics-routes.test.ts b/server/src/__tests__/issue-subtree-diagnostics-routes.test.ts index 626662a1f46..ba4dd9f1eec 100644 --- a/server/src/__tests__/issue-subtree-diagnostics-routes.test.ts +++ b/server/src/__tests__/issue-subtree-diagnostics-routes.test.ts @@ -22,6 +22,7 @@ import { } from "./helpers/embedded-postgres.js"; import { errorHandler } from "../middleware/index.js"; import { issueRoutes } from "../routes/issues.js"; +import { uniqueIssuePrefix } from "./helpers/issue-prefix.js"; const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; @@ -77,7 +78,7 @@ async function seedCompany(db: Db, label = "Subtree Diagnostics") { const nonce = randomUUID().slice(0, 8); const [company] = await db.insert(companies).values({ name: `${label} ${nonce}`, - issuePrefix: `SD${nonce.slice(0, 4).toUpperCase()}`, + issuePrefix: uniqueIssuePrefix("SD"), defaultResponsibleUserId: "board-user", }).returning(); return company!; diff --git a/server/src/__tests__/issue-wake-diagnostics-routes.test.ts b/server/src/__tests__/issue-wake-diagnostics-routes.test.ts index d45f722851c..44f1e6e1423 100644 --- a/server/src/__tests__/issue-wake-diagnostics-routes.test.ts +++ b/server/src/__tests__/issue-wake-diagnostics-routes.test.ts @@ -21,6 +21,7 @@ import { } from "./helpers/embedded-postgres.js"; import { errorHandler } from "../middleware/index.js"; import { issueRoutes } from "../routes/issues.js"; +import { uniqueIssuePrefix } from "./helpers/issue-prefix.js"; const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; @@ -76,7 +77,7 @@ async function seedCompany(db: Db, label = "Wake Diagnostics") { const nonce = randomUUID().slice(0, 8); const [company] = await db.insert(companies).values({ name: `${label} ${nonce}`, - issuePrefix: `WD${nonce.slice(0, 4).toUpperCase()}`, + issuePrefix: uniqueIssuePrefix("WD"), defaultResponsibleUserId: "board-user", }).returning(); return company!; diff --git a/server/src/__tests__/low-trust-red-team-routes.test.ts b/server/src/__tests__/low-trust-red-team-routes.test.ts index 1df8eabb106..c365295dc3e 100644 --- a/server/src/__tests__/low-trust-red-team-routes.test.ts +++ b/server/src/__tests__/low-trust-red-team-routes.test.ts @@ -57,6 +57,7 @@ import { issueRoutes } from "../routes/issues.js"; import { issueService } from "../services/issues.js"; import { heartbeatService } from "../services/heartbeat.js"; import { LOW_TRUST_QUARANTINED_BODY } from "../services/source-trust.js"; +import { uniqueIssuePrefix } from "./helpers/issue-prefix.js"; const externalTestDatabaseUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_LOW_TRUST_TEST_DATABASE_URL"); const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); @@ -444,7 +445,7 @@ async function seedLowTrustFixture(db: Db) { .insert(companies) .values({ name: `Low trust ${nonce}`, - issuePrefix: `LT${nonce.slice(0, 4).toUpperCase()}`, + issuePrefix: uniqueIssuePrefix("LT"), defaultResponsibleUserId: "board-user", }) .returning(); @@ -2269,7 +2270,7 @@ describeEmbeddedPostgres( .insert(companies) .values({ name: "Foreign low-trust source", - issuePrefix: `FGN${randomUUID().slice(0, 4).toUpperCase()}`, + issuePrefix: uniqueIssuePrefix("FGN"), defaultResponsibleUserId: "board-user", }) .returning(); diff --git a/server/src/__tests__/test-database-session-settings.test.ts b/server/src/__tests__/test-database-session-settings.test.ts new file mode 100644 index 00000000000..fcddd1f8d05 --- /dev/null +++ b/server/src/__tests__/test-database-session-settings.test.ts @@ -0,0 +1,33 @@ +import { promises as fs } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it } from "vitest"; + +const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../.."); +const roots = ["server/src", "packages"]; +const roleSetting = /alter\s+(?:role|user)\s[^`'"]*\bset\b/i; + +async function testFiles(directory: string): Promise { + const entries = await fs.readdir(directory, { withFileTypes: true }).catch(() => []); + const files = await Promise.all(entries.map(async entry => { + const target = path.join(directory, entry.name); + if (entry.isDirectory()) return entry.name === "node_modules" || entry.name === "dist" ? [] : testFiles(target); + return /\.test\.(?:ts|tsx|mts|mjs|js)$/.test(entry.name) ? [target] : []; + })); + return files.flat(); +} + +describe("test database session settings", () => { + it("scope session settings to the suite's own database, never to the shared role", async () => { + const offenders: string[] = []; + for (const root of roots) { + for (const file of await testFiles(path.join(repoRoot, root))) { + const lines = (await fs.readFile(file, "utf8")).split("\n"); + lines.forEach((line, index) => { + if (roleSetting.test(line)) offenders.push(`${path.relative(repoRoot, file)}:${index + 1}`); + }); + } + } + expect(offenders).toEqual([]); + }); +}); diff --git a/server/src/__tests__/work-timeline-service.test.ts b/server/src/__tests__/work-timeline-service.test.ts index f112873f6d8..674a831fd89 100644 --- a/server/src/__tests__/work-timeline-service.test.ts +++ b/server/src/__tests__/work-timeline-service.test.ts @@ -31,6 +31,7 @@ import { companyRoutes } from "../routes/companies.js"; import { buildOpenApiSpec } from "../routes/openapi.js"; import { registerTimelineReceiptBoundaryCases } from "./helpers/work-timeline-receipt-cases.js"; import { normalizeTimelineWindow, workTimelineService } from "../services/work-timeline.js"; +import { uniqueIssuePrefix } from "./helpers/issue-prefix.js"; const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; @@ -100,7 +101,7 @@ describeEmbeddedPostgres("work timeline aggregation", () => { await db.insert(companies).values({ id: companyId, name: "Timeline Co", - issuePrefix: `T${randomUUID().replace(/-/g, "").slice(0, 4).toUpperCase()}`, + issuePrefix: uniqueIssuePrefix("T"), requireBoardApprovalForNewAgents: false, }); await db.insert(authUsers).values({ @@ -367,7 +368,7 @@ describeEmbeddedPostgres("work timeline aggregation", () => { await db.insert(companies).values({ id: otherCompanyId, name: "Other Timeline Co", - issuePrefix: `O${randomUUID().replace(/-/g, "").slice(0, 4).toUpperCase()}`, + issuePrefix: uniqueIssuePrefix("O"), requireBoardApprovalForNewAgents: false, }); await db.insert(agents).values({ diff --git a/server/src/__tests__/workload-identity.test.ts b/server/src/__tests__/workload-identity.test.ts index 70db716529c..3c1ca45acdf 100644 --- a/server/src/__tests__/workload-identity.test.ts +++ b/server/src/__tests__/workload-identity.test.ts @@ -34,6 +34,7 @@ import { workloadIdentityIssuerOrigin, workloadIdentityService, } from "../services/workload-identity.js"; +import { uniqueIssuePrefix } from "./helpers/issue-prefix.js"; const ORIGIN = "https://acme.paperclip.app"; const actor = { actorType: "user" as const, actorId: "board-user" }; @@ -68,7 +69,7 @@ describe("company workload identity issuer", () => { async function company() { const id = randomUUID(); await db.insert(companies).values({ - id, name: `Identity ${id.slice(0, 6)}`, issuePrefix: `W${id.slice(0, 4).toUpperCase()}`, + id, name: `Identity ${id.slice(0, 6)}`, issuePrefix: uniqueIssuePrefix("W"), defaultResponsibleUserId: "workload-identity-owner", }); return id; diff --git a/server/src/services/antigravity-swarm.db.test.ts b/server/src/services/antigravity-swarm.db.test.ts index a8e10761130..3d47ce71fca 100644 --- a/server/src/services/antigravity-swarm.db.test.ts +++ b/server/src/services/antigravity-swarm.db.test.ts @@ -10,6 +10,7 @@ import { deliveredQueuedCommentIds } from "./queued-comment-delivery.js"; import { queuedCommentIdsFromWakePayload } from "../lib/queued-comment-context.js"; import { mergeCoalescedContextSnapshot } from "./heartbeat/run-preparation.js"; import { saveUndeliveredUserComments } from "./work-intent-outbox.js"; +import { uniqueIssuePrefix } from "../__tests__/helpers/issue-prefix.js"; const support = await getEmbeddedPostgresTestSupport(); const USER = "swarm-user"; @@ -25,7 +26,7 @@ describe.skipIf(!support.supported)("trusted /swarm run selection (database)", ( afterAll(async () => { await db?.$client.end(); await database?.cleanup(); }); async function seed(options: { author?: "user" | "agent"; record?: "match" | "none" | "other-actor" | "other-comment" } = {}) { - const [company] = await db.insert(companies).values({ name: "Swarm", issuePrefix: `S${randomUUID().slice(0, 4)}` }).returning(); + const [company] = await db.insert(companies).values({ name: "Swarm", issuePrefix: uniqueIssuePrefix("S") }).returning(); const [agent] = await db.insert(agents).values({ companyId: company!.id, name: "Gemma", adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "antigravity", model: "gemini-3.8-flash-low" } }).returning(); const [issue] = await db.insert(issues).values({ companyId: company!.id, title: "Swarm", status: "todo", assigneeAgentId: agent!.id }).returning(); diff --git a/server/src/services/budget-resume-continuation.test.ts b/server/src/services/budget-resume-continuation.test.ts index 94d758a8185..3ce917606d0 100644 --- a/server/src/services/budget-resume-continuation.test.ts +++ b/server/src/services/budget-resume-continuation.test.ts @@ -13,6 +13,7 @@ import { import { EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase, } from "../__tests__/helpers/embedded-postgres.js"; +import { uniqueIssuePrefix } from "../__tests__/helpers/issue-prefix.js"; const mockLogActivity = vi.hoisted(() => vi.fn()); vi.mock("./activity-log.js", async (importOriginal) => ({ @@ -41,7 +42,7 @@ describe.skipIf(!support.supported)("resuming after a budget hard stop", () => { async function seedScope(label: string, scopeType: "company" | "agent" = "company") { const [company] = await db.insert(companies).values({ name: `Budget ${label}`, - issuePrefix: `B${randomUUID().slice(0, 4).toUpperCase()}` }).returning(); + issuePrefix: uniqueIssuePrefix("B") }).returning(); const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Worker" }).returning(); const scopeId = scopeType === "agent" ? agent.id : company.id; const [policy] = await db.insert(budgetPolicies).values({ companyId: company.id, scopeType, diff --git a/server/src/services/isolated-remote-workspace-source-lock.test.ts b/server/src/services/isolated-remote-workspace-source-lock.test.ts index 8f893b39492..c710a6b0fa8 100644 --- a/server/src/services/isolated-remote-workspace-source-lock.test.ts +++ b/server/src/services/isolated-remote-workspace-source-lock.test.ts @@ -18,9 +18,8 @@ describePostgres("workspace source ownership during preparation", () => { beforeAll(async () => { database = await startEmbeddedPostgresTestDatabase("workspace-source-lock-"); db = createDb(database.connectionString, { maxConnections: 1 }); - const rows = await db.execute(sql`select current_user as name`); - const role = String(rows[0].name); - await db.execute(sql`alter role ${sql.identifier(role)} set idle_in_transaction_session_timeout = '1s'`); + 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 () => { diff --git a/server/src/services/native-runtime/first-turn-queued-input.test.ts b/server/src/services/native-runtime/first-turn-queued-input.test.ts index 70f654e23d4..af1696d0415 100644 --- a/server/src/services/native-runtime/first-turn-queued-input.test.ts +++ b/server/src/services/native-runtime/first-turn-queued-input.test.ts @@ -13,6 +13,7 @@ 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"; @@ -27,7 +28,7 @@ describe.skipIf(!support.supported)("first-turn queued input", () => { afterAll(async () => { await db?.$client.end(); await database?.cleanup(); }); async function seed() { - const [company] = await db.insert(companies).values({ name: "First turn", issuePrefix: `F${randomUUID().slice(0, 4)}` }).returning(); + 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); diff --git a/server/src/services/native-runtime/generate-image-tool.test.ts b/server/src/services/native-runtime/generate-image-tool.test.ts index e3120bd4466..c9ccb2c1c46 100644 --- a/server/src/services/native-runtime/generate-image-tool.test.ts +++ b/server/src/services/native-runtime/generate-image-tool.test.ts @@ -11,6 +11,7 @@ import { accountRunCost } from "../run-cost-accounting.js"; import { budgetServiceInTransaction } from "../budgets.js"; import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js"; import { imageGenerationBindingForRun, priceGeneratedImage, requestOpenAiImage } from "./generate-image-tool.js"; +import { uniqueIssuePrefix } from "../../__tests__/helpers/issue-prefix.js"; // One transparent 1x1 PNG. The handler only needs real PNG bytes to save. const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==", "base64"); @@ -42,7 +43,7 @@ describe("generate_image for OpenAI API-key Codex agents (N-12)", () => { /** An onboarding-style company: one Codex agent running on an OpenAI API key. */ async function fixture() { const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID(); - await db.insert(companies).values({ id: companyId, name: "Pixel Bakery", issuePrefix: `PX${companyId.slice(0, 4).toUpperCase()}` }); + await db.insert(companies).values({ id: companyId, name: "Pixel Bakery", issuePrefix: uniqueIssuePrefix("PX") }); await db.insert(companyMemberships).values({ companyId, principalId: "alice", principalType: "user", status: "active", membershipRole: "owner" }); await db.insert(agents).values({ id: agentId, companyId, name: "Head baker", adapterType: "paperclip_runner", adapterConfig: { provider: "codex" }, status: "active" }); diff --git a/server/src/services/native-runtime/model-rejected-retry.test.ts b/server/src/services/native-runtime/model-rejected-retry.test.ts index 74ee1713da2..6b7bb32b89d 100644 --- a/server/src/services/native-runtime/model-rejected-retry.test.ts +++ b/server/src/services/native-runtime/model-rejected-retry.test.ts @@ -1,9 +1,9 @@ -import { randomUUID } from "node:crypto"; import { eq } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { agents, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, heartbeatRuns, issues } from "@paperclipai/db"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; import { rejectedModelRetryRefusal } from "./model-rejected-retry.js"; +import { uniqueIssuePrefix } from "../../__tests__/helpers/issue-prefix.js"; const support = await getEmbeddedPostgresTestSupport(); const REJECTED = "openrouter/paperclip-eval/unavailable"; @@ -19,7 +19,7 @@ describe.skipIf(!support.supported)("retrying a run whose model the provider rej afterAll(async () => { await db?.$client.end(); await database?.cleanup(); }); async function seed(input: { agentModel: string; overrideModel?: string; errorCode?: string }) { - const [company] = await db.insert(companies).values({ name: "Model retry", issuePrefix: `M${randomUUID().slice(0, 4)}` }).returning(); + const [company] = await db.insert(companies).values({ name: "Model retry", issuePrefix: uniqueIssuePrefix("M") }).returning(); const [agent] = await db.insert(agents).values({ companyId: company!.id, name: "Morgan", adapterType: "paperclip_runner", adapterConfig: { provider: "opencode", model: input.agentModel } }).returning(); const [issue] = await db.insert(issues).values({ companyId: company!.id, title: "Website task", status: "blocked", assigneeAgentId: agent!.id, diff --git a/server/src/services/native-runtime/native-provider-turn-wait.test.ts b/server/src/services/native-runtime/native-provider-turn-wait.test.ts index 6738589567e..dae1bb08f18 100644 --- a/server/src/services/native-runtime/native-provider-turn-wait.test.ts +++ b/server/src/services/native-runtime/native-provider-turn-wait.test.ts @@ -12,6 +12,7 @@ import { awaitPersonCommentDuringNativeRun, nativeProviderTurnWaitOptions, nativeProviderTurnWaitStartedAt, personCommentedDuringNativeRun, registerPersonCommentWaitWork, } from "./native-provider-turn-wait.js"; +import { uniqueIssuePrefix } from "../../__tests__/helpers/issue-prefix.js"; const support = await getEmbeddedPostgresTestSupport(); const USER = "provider-turn-user"; @@ -57,7 +58,7 @@ describe.skipIf(!support.supported)("native provider-turn wait control-plane hoo } async function seed(startedAt = new Date()) { - const [company] = await db.insert(companies).values({ name: "Provider turn", issuePrefix: `P${randomUUID().slice(0, 4)}` }).returning(); + const [company] = await db.insert(companies).values({ name: "Provider turn", issuePrefix: uniqueIssuePrefix("P") }).returning(); const [agent] = await db.insert(agents).values({ companyId: company!.id, name: "Claude", adapterType: "paperclip_runner" }).returning(); const issueId = randomUUID(); const [run] = await db.insert(heartbeatRuns).values({ companyId: company!.id, agentId: agent!.id, status: "running", runtimeMode: "native", diff --git a/server/src/services/native-runtime/native-runner-checkpoint-save.test.ts b/server/src/services/native-runtime/native-runner-checkpoint-save.test.ts index 7e564f8ae98..c533cff4696 100644 --- a/server/src/services/native-runtime/native-runner-checkpoint-save.test.ts +++ b/server/src/services/native-runtime/native-runner-checkpoint-save.test.ts @@ -6,6 +6,7 @@ import { agents, checkpointDb, closeCheckpointDb, companies, createDb, heartbeat 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(); @@ -27,7 +28,7 @@ const support = await getEmbeddedPostgresTestSupport(); }); const fixture = async (leaseExpiresAt: Date) => { - const [company] = await db.insert(companies).values({ name: "Checkpoint save", issuePrefix: `CS${randomUUID().slice(0, 4)}` }).returning(); + 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(); diff --git a/server/src/services/native-runtime/native-workspace-finalizer.test.ts b/server/src/services/native-runtime/native-workspace-finalizer.test.ts index ae98d0f80a3..c279cd82e85 100644 --- a/server/src/services/native-runtime/native-workspace-finalizer.test.ts +++ b/server/src/services/native-runtime/native-workspace-finalizer.test.ts @@ -1048,9 +1048,9 @@ describe("native workspace finalization recovery", () => { }); it("preserves a live copyback owner across the configured idle transaction timeout", async () => { const seeded = await seedRun({ executionWorkspaceId: randomUUID(), title: "Idle copyback lock" }); - const rows = await db.execute(sql`select current_user as name`); - const role = String(rows[0].name); - await db.execute(sql`alter role ${sql.identifier(role)} set idle_in_transaction_session_timeout = '1s'`); + const rows = await db.execute(sql`select current_database() as name`); + const database = sql.identifier(String(rows[0].name)); + await db.execute(sql`alter database ${database} set idle_in_transaction_session_timeout = '1s'`); await closeDedicatedDbConnections(db, 1); try { const result = await withNativeWorkspaceFinalizationOwnership({ db, companyId, runId: seeded.runId }, async ownership => { @@ -1060,7 +1060,7 @@ describe("native workspace finalization recovery", () => { }); expect(result).toEqual({ acquired: true, value: "copied" }); } finally { - await db.execute(sql`alter role ${sql.identifier(role)} reset idle_in_transaction_session_timeout`); + await db.execute(sql`alter database ${database} reset idle_in_transaction_session_timeout`); } }); diff --git a/server/src/services/queued-comment-history-read.test.ts b/server/src/services/queued-comment-history-read.test.ts index f1358db944c..8bebe725dce 100644 --- a/server/src/services/queued-comment-history-read.test.ts +++ b/server/src/services/queued-comment-history-read.test.ts @@ -6,6 +6,7 @@ import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } fro import { undeliveredLegacyUserCommentIds } from "./explicit-native-continuation.js"; import { PaperclipRunnerToolAuthority } from "./native-runtime/paperclip-runner-tool-authority.js"; import { taskHistoryReadsForRun } from "./queued-comment-delivery.js"; +import { uniqueIssuePrefix } from "../__tests__/helpers/issue-prefix.js"; const support = await getEmbeddedPostgresTestSupport(); const USER = "history-read-user"; @@ -20,7 +21,7 @@ describe.skipIf(!support.supported)("task history reads", () => { afterAll(async () => { await db?.$client.end(); await database?.cleanup(); }); async function seed() { - const [company] = await db.insert(companies).values({ name: "History read", issuePrefix: `H${randomUUID().slice(0, 4)}` }).returning(); + const [company] = await db.insert(companies).values({ name: "History read", issuePrefix: uniqueIssuePrefix("H") }).returning(); const [agent] = await db.insert(agents).values({ companyId: company!.id, name: "Codie", adapterType: "paperclip_runner" }).returning(); const issueId = randomUUID(); const [run] = await db.insert(heartbeatRuns).values({ companyId: company!.id, agentId: agent!.id, status: "running", diff --git a/server/src/services/run-evidence-migration-appended.test.ts b/server/src/services/run-evidence-migration-appended.test.ts index ebb0cf73284..d49748bd149 100644 --- a/server/src/services/run-evidence-migration-appended.test.ts +++ b/server/src/services/run-evidence-migration-appended.test.ts @@ -9,6 +9,7 @@ import type { StorageProvider } from "../storage/types.js"; import { EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase, } from "../__tests__/helpers/embedded-postgres.js"; +import { uniqueIssuePrefix } from "../__tests__/helpers/issue-prefix.js"; const objects = vi.hoisted(() => new Map()); const mirrors = vi.hoisted(() => new Map()); @@ -79,7 +80,7 @@ describe.skipIf(!support.supported)("run log migration after a retry appended to }); async function seed(prefix: string, file: string, recordedSha256 = etag(Buffer.from(prefix)), runtimeMode = "legacy") { - const [company] = await db.insert(companies).values({ name: "Logs", issuePrefix: `L${Math.random().toString(36).slice(2, 6).toUpperCase()}` }).returning(); + const [company] = await db.insert(companies).values({ name: "Logs", issuePrefix: uniqueIssuePrefix("L") }).returning(); const [agent] = await db.insert(agents).values({ companyId: company!.id, name: "Worker" }).returning(); const [run] = await db.insert(heartbeatRuns).values({ companyId: company!.id, agentId: agent!.id, status: "failed", runtimeMode }).returning(); const logRef = `${company!.id}/${agent!.id}/${run!.id}.ndjson`; diff --git a/server/src/services/skill-package-storage-migration-postgres.test.ts b/server/src/services/skill-package-storage-migration-postgres.test.ts index 11f1c8c7f9e..a5f8d1f9963 100644 --- a/server/src/services/skill-package-storage-migration-postgres.test.ts +++ b/server/src/services/skill-package-storage-migration-postgres.test.ts @@ -8,6 +8,7 @@ import { migrateLocalSkillPackageObjects } from "./skill-package-storage-migrati import { EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase, } from "../__tests__/helpers/embedded-postgres.js"; +import { uniqueIssuePrefix } from "../__tests__/helpers/issue-prefix.js"; vi.mock("./skill-package-store.js", () => ({ skillPackageStore: () => ({ verifyDurable: async () => true }) })); @@ -56,7 +57,7 @@ describe.skipIf(!support.supported)("online skill object copy against PostgreSQL }); async function snapshot(upload: Record | null = null) { - const [company] = await db.insert(companies).values({ name: "Skills", issuePrefix: `S${randomUUID().slice(0, 4).toUpperCase()}` }).returning(); + const [company] = await db.insert(companies).values({ name: "Skills", issuePrefix: uniqueIssuePrefix("S") }).returning(); const receipt = localReceipt(); const [row] = await db.insert(snapshots).values({ companyId: company!.id, contentHash: randomUUID(), storage: receipt as never, upload: upload as never }).returning();