test(ai-connections): start the receiver lock-wait deadline after child startup (#23014)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The managed AI connections service refreshes single-use quota
credentials and must handle a receiver process that dies after a token
exchange
> - A server test spawns a real child process to prove this case, but it
fails every time in the server General tests shard 7/8
> - The failure blocks unrelated PRs, for example Dependabot PR #22604
> - The child starts through tsx. Loading `services/ai-connections.ts`
takes about 20–30 seconds on a 4-CPU runner. The test gave the child
only 25 seconds from spawn to reach the advisory lock, so the deadline
ended before the child ran its first line
> - This pull request starts the 25-second lock-wait budget only after
the child reports that its imports are done, and it makes the test setup
safe for a retry
> - The benefit is that the shard passes again and the test still proves
the same behavior

## Linked Issues or Issue Description

Refs #22604

**What happened?**
The test "requires sign-in after the receiver process dies with an
exchanged but unsaved token" in
`server/src/__tests__/ai-connections.test.ts` fails with `expected false
to be true` at `expect(blocked).toBe(true)`. On the vitest retry, it
then fails with `duplicate key value violates unique constraint
"company_memberships_company_principal_unique_idx"`.

**Steps to reproduce**
Run `pnpm vitest run server/src/__tests__/ai-connections.test.ts -t
"receiver process dies"` on a 4-CPU machine. The test fails after 25
seconds. Tracing showed that the child process never ran its first
statement before the deadline. A direct run of the child helper took 32
seconds cold and 21 seconds warm, all in module loading.

**Expected behavior**
The test waits for the child to start, then gives the child 25 seconds
to block on the advisory lock after one provider exchange. A retry does
not collide with rows from the first attempt.

## What Changed

- `helpers/quota-credential-process.ts`: The child writes `ready` to
stdout after its imports finish. It writes no credential data.
- `ai-connections.test.ts`: The test pipes the child stdout and waits up
to 150 seconds for `ready` (or for the child to exit). Then the existing
25-second lock-wait loop starts.
- `ai-connections.test.ts`: The test owner is now unique per attempt
(`quota-receiver-process-loss-<uuid>`), so a retry does not hit the
membership unique index.
- The test timeout increases from 40 seconds to 200 seconds to cover the
startup wait.

## Verification

- Before the fix: `pnpm vitest run
server/src/__tests__/ai-connections.test.ts -t "receiver process dies"`
failed at line 933 (`expected false to be true`), the same as CI.
- After the fix: the same command passes.
- `pnpm vitest run server/src/__tests__/ai-connections.test.ts`: 167 of
167 tests pass.
- CI: the server General tests shard 7/8 must pass on this PR.

## Risks

Low risk. Only test code changes. The assertions about the exchange
count, the saved credential, the recovery journal, and re-authorization
do not change. The test can take longer on a slow runner because startup
now has its own wait.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use (shell,
file edits) in Claude Code.

## 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: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-11-26 04:06:08 +00:00
1 parent bde164de54
commit 5a7150be7e
2 files changed
+9 -3

No files matched your search

+8 -3
View File
@@ -891,7 +891,7 @@ describe("managed AI connections", () => {
});
it("requires sign-in after the receiver process dies with an exchanged but unsaved token", async () => {
const owner = "quota-receiver-process-loss";
const owner = `quota-receiver-process-loss-${randomUUID()}`;
await db.insert(companyMemberships).values({ companyId, principalId: owner, principalType: "user", status: "active", membershipRole: "member" });
const original = JSON.stringify({ tokens: { access_token: "expired-process", refresh_token: "single-use-process" } });
await service.save(companyId, owner, { provider: "openai", method: "subscription", ownership: "personal", name: owner, loginSessionId: "fixture", agentIds: [], allAgents: true }, original);
@@ -918,10 +918,15 @@ describe("managed AI connections", () => {
const child = spawn(process.execPath, ["--import", createRequire(import.meta.url).resolve("tsx"), new URL("./helpers/quota-credential-process.ts", import.meta.url).pathname], {
env: { ...process.env, CREDENTIAL_TEST_DATABASE_URL: database.connectionString,
CREDENTIAL_TEST_PROVIDER_URL: `http://127.0.0.1:${address.port}`, CREDENTIAL_TEST_COMPANY_ID: companyId, CREDENTIAL_TEST_OWNER: owner },
stdio: "ignore",
stdio: ["ignore", "pipe", "ignore"],
});
const exited = once(child, "exit");
let ready = false, output = "";
child.stdout!.setEncoding("utf8").on("data", (chunk: string) => { output += chunk; ready ||= output.includes("ready\n"); });
try {
const startup = Date.now() + 150_000;
while (!ready && Date.now() < startup && child.exitCode === null) await new Promise(resolve => setTimeout(resolve, 25));
expect(ready).toBe(true);
let blocked = false;
const deadline = Date.now() + 25_000;
while (!blocked && Date.now() < deadline && child.exitCode === null) {
@@ -952,7 +957,7 @@ describe("managed AI connections", () => {
await receiver.save(companyId, owner, { connectionId: row.connection.id, provider: "openai", method: "subscription", ownership: "personal", name: owner, loginSessionId: "fixture", agentIds: [], allAgents: true }, signedIn);
const [current] = await receiver.quotaAccounts(companyId, owner);
expect(await receiver.runtimeCredential(current)).toBe(signedIn);
}, 40_000);
}, 200_000);
it("does not exchange a token when a required database transaction fails", async () => {
const owner = "quota-db-prerequisite";
@@ -10,6 +10,7 @@ globalThis.fetch = (url, init) => {
if (String(url) !== "https://auth.openai.com/oauth/token") throw new Error("Unexpected fixture network request");
return request(provider, init);
};
process.stdout.write("ready\n");
try {
const service = aiConnectionService(db);
const [row] = await service.quotaAccounts(process.env.CREDENTIAL_TEST_COMPANY_ID!, process.env.CREDENTIAL_TEST_OWNER!);