test: remove recovery and Tailscale readiness races (#23678)

## Thinking Path

> - Paperclip requires checks for an exact Core source commit before it
publishes images.
> - Cloud readiness runs the server integration tests without retries.
> - Server shard 18/20 failed in recovery cleanup and Tailscale
enrollment.
> - The recovery test returned before its status wake reached the
heartbeat drain.
> - The Tailscale fixture exposed state before it was safe to read or
observe.
> - This pull request makes those fixtures wait for their actual
completion boundaries.

## Linked Issues or Issue Description

Refs #23227. Related earlier cleanup fix: #23673.

**What happened?**

[Docker run
47225196060](https://github.com/paperclipai/paperclip/actions/runs/47225196060)
stopped after [Cloud readiness server shard
18/20](https://github.com/paperclipai/paperclip/actions/runs/47225196237/job/144677926140)
failed. Staging image preparation then waited for a verified Core image.
The previous Runner reattachment cleanup fix passed its protocol lane in
that run.

The recovery test deleted agents after a late wake inserted a child row.
The Tailscale test failed its first connection. On the [next master
run](https://github.com/paperclipai/paperclip/actions/runs/47227863572/job/144687185775),
the Tailscale blocked-save test timed out while waiting for a callback
that startup might never reach.

**Expected behavior**

Fixture teardown must join the status wake. The fake Tailscale CLI must
publish complete state and receive each simulated consent event
reliably. Tests must await enrollment completion and fail promptly when
connection setup fails.

**Steps to reproduce**

Run the two changed test files or server shard 18/20 with retries
disabled. The unmodified local files reproduced a consent callback
failure. The CI links above record the foreign-key and blocked-save
failures. The foreign-key failure did not reproduce in the initial local
run.

**Paperclip version or commit**

Failures on `07150650c926d8947ae591f61e4ed854ca284149` and
`ba521863f6090e40a37ed3cb6b1ecaf358a11424`. The fix starts from the
latter and is rebased onto `86042310917c15eb04be121baf58a6929e52a7d2`,
which adds release notes only.

**Deployment mode**

Source checkout in GitHub Actions. Local checks use macOS arm64, Node
25.6.1, hermetic Tailscale executables, and disposable embedded
PostgreSQL.

Searched open PRs and issues for the failing files, `ENOTEMPTY`, Runner
cleanup, and Tailscale tests. No duplicate fix was found. Issue #23227
describes the startup-dependent expiry window and is also addressed
here.

## What Changed

- Wait for the accepted recovery status change to persist its wake
before the existing heartbeat drain deletes fixture tables. The wake has
an asynchronous route prologue that can outlive the HTTP response.
- Register a signal handler in the owned fake CLI before exposing the
login URL. Publish fixture state atomically, then signal that exact
child to simulate consent. This removes the dependency on filesystem
notification delivery.
- Await the network manager's completion promise instead of a short
callback polling window.
- Start the expiry test with a valid window, advance the application
clock after startup, and submit late consent. Keep real subprocess
timers and restore the clock spy in `finally`.
- Race blocked-save admission against early connection settlement so
startup failures are reported instead of hanging the test.
- Only two test files change. Runtime behavior, release gates, and
deployment policy do not change.

## Verification

- Baseline: the unmodified two-file run failed the consent callback
assertion; 129 tests passed. The recovery cleanup passed locally, with
its CI failure retained above.
- An intermediate expiry check failed its one-second callback wait. A
later parallel shard run still lost a filesystem notification. The final
fixture uses an explicit consent signal and awaits manager completion.
- That eight-worker shard run also timed out in unchanged
workspace-trust and runtime-control fixtures while a monolithic
typecheck ran concurrently. Those two unchanged files passed in a serial
control with the changed fixtures: 186 tests passed across four files.
The final shard is run separately with four workers and retries
disabled.
- `pnpm exec tsc --noEmit -p tsconfig.json` from `server/`: passed.
- After the release-notes-only rebase, the Tailscale file passed again:
9 tests, retries disabled. The two fixture file contents are identical
to the final shard run.
- `PAPERCLIP_VITEST_RETRY=0 PAPERCLIP_VITEST_MAX_WORKERS=4 pnpm
test:run:general -- --group general-server-without-chat-or-native-runner
--shard-index 17 --shard-count 20`: passed on the final fixture
contents. 85 files passed, 3 skipped; 1945 tests passed, 18 skipped.
Duration: 160 seconds.
- `node scripts/check-test-budget.mjs --files
server/src/__tests__/issue-recovery-actions.test.ts
server/src/services/connectors/tailscale/device-login-network.test.ts`:
passed.
- `git diff --check` and local secret/PII review: passed.
- [Greptile
review](https://github.com/paperclipai/paperclip/pull/23678#issuecomment-7396242983):
5/5 on head `13bf3586bcf3201ce137f674812e8faf778ee77d`, with a
successful current-head check and no actionable findings or review
threads. The [full PR CI
workflow](https://github.com/paperclipai/paperclip/actions/runs/47231990509)
passed on attempt 1. All 71 reported checks are clean on this head;
GitHub reports `CLEAN` / `MERGEABLE` and there are no unresolved review
threads.

## Risks

Low risk. The change is limited to fixtures. A missing status wake or
failed enrollment still fails the tests. The expiry case now checks
actual late-consent rejection without making success depend on process
startup time. No schema, API, or runtime changes are required. The tests
and PR explain the behavior; no documentation update is needed. A new
verified master image is still required before staging can resume.

## Model Used

OpenAI `gpt-6.1-sol` through the Codex harness in T3 Code, with xhigh
reasoning effort, shell and file tools. The harness does not expose the
context window size.

## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Devin FoleyandPaperclip authored and GitHub committed 2026-12-03 16:22:38 -08:00
1 parent c2a8821809
commit c5f5d3163d
2 files changed
+31 -10

No files matched your search

@@ -2222,6 +2222,12 @@ describeEmbeddedPostgres("issue recovery actions", () => {
await db.delete(issueRecoveryActions).where(eq(issueRecoveryActions.id, f.hold.id));
await seedLiveOwnerRun(f);
await request(f.agent).patch(`/api/issues/${f.sourceIssueId}`).send({ status: "todo" }).expect(200);
await vi.waitFor(async () => {
const wakes = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, f.companyId));
expect(wakes).toEqual(expect.arrayContaining([expect.objectContaining({
agentId: f.coderId, payload: expect.objectContaining({ issueId: f.sourceIssueId }),
})]));
}, { timeout: 5_000 });
});
async function seedReconciledDelivery() {
@@ -9,6 +9,8 @@ async function publishState(statePath: string, state: unknown) {
const nextPath = `${statePath}.next`;
await fs.writeFile(nextPath, JSON.stringify(state));
await fs.rename(nextPath, statePath);
const pid = Number(await fs.readFile(path.join(path.dirname(statePath), "up-pid"), "utf8"));
process.kill(pid, "SIGUSR2");
}
describe("Tailscale interactive device enrollment", () => {
@@ -36,10 +38,15 @@ if (args[1] === 'up') {
if (args.some(arg => arg.startsWith('--auth-key'))) process.exit(5);
if (state.BackendState === 'Running') process.exit(0);
state = { MachineKey: state.MachineKey || path.basename(dir), BackendState: 'NeedsLogin', AuthURL: 'https://login.tailscale.com/a/fixture' };
fs.writeFileSync(statePath, JSON.stringify(state));
fs.watch(dir, () => {
const check = () => {
if (JSON.parse(fs.readFileSync(statePath, 'utf8')).BackendState === 'Running') process.exit(0);
});
};
process.on('SIGUSR2', check);
fs.writeFileSync(path.join(dir, 'up-pid'), String(process.pid));
fs.writeFileSync(statePath + '.next', JSON.stringify(state));
fs.renameSync(statePath + '.next', statePath);
check();
setInterval(() => {}, 1000);
} else if (args[1] === 'status') console.log(JSON.stringify(state));
`, { mode: 0o700 });
manager = createTailscaleNetworkManager({ daemon: path.join(dir, "daemon"), cli: path.join(dir, "cli") });
@@ -59,7 +66,8 @@ if (args[1] === 'up') {
expect(credential).not.toBe(emptyState);
expect(authorized).not.toHaveBeenCalled();
await publishState(statePath, { ...state, BackendState: "Running", AuthURL: "" });
await vi.waitFor(() => expect(authorized).toHaveBeenCalledOnce());
expect(await manager.loginStatus(input.identity)).toEqual({ status: "connected" });
expect(authorized).toHaveBeenCalledOnce();
await manager.close();
const restored = await manager.connect({ identity: input.identity, credential, persist: input.persist });
expect(JSON.parse(await fs.readFile(path.join(path.dirname(restored), "state"), "utf8")).MachineKey).toBe(state.MachineKey);
@@ -83,12 +91,19 @@ if (args[1] === 'up') {
it("stops an expired sign-in without accepting late consent", async () => {
const authorized = vi.fn();
const failure = vi.fn().mockResolvedValue(undefined);
const expiresAt = Date.now() + 60_000;
const socket = await manager.connect({ identity: "expires", credential: emptyState, persist: vi.fn(),
login: { expiresAt: Date.now() + 1200, onAuthorized: authorized, onFailure: failure } });
await vi.waitFor(() => expect(failure).toHaveBeenCalledOnce(), { timeout: 4000 });
await vi.waitFor(async () => expect(await manager.loginStatus("expires")).toBeNull());
expect(authorized).not.toHaveBeenCalled();
await expect(fs.stat(path.dirname(socket))).rejects.toMatchObject({ code: "ENOENT" });
login: { expiresAt, onAuthorized: authorized, onFailure: failure } });
const now = Date.now.bind(Date);
const clock = vi.spyOn(Date, "now").mockImplementation(() => now() + 60_000);
try {
await publishState(path.join(path.dirname(socket), "state"), { BackendState: "Running" });
await manager.loginStatus("expires").catch(() => undefined);
expect(failure).toHaveBeenCalledOnce();
await vi.waitFor(async () => expect(await manager.loginStatus("expires")).toBeNull(), { timeout: 5_000 });
expect(authorized).not.toHaveBeenCalled();
await expect(fs.stat(path.dirname(socket))).rejects.toMatchObject({ code: "ENOENT" });
} finally { clock.mockRestore(); }
});
it("lets secret deletion cancel a blocked credential save", async () => {
@@ -100,7 +115,7 @@ if (args[1] === 'up') {
login: { expiresAt: Date.now() + 60_000, onAuthorized: vi.fn(), onFailure: vi.fn() } });
const settled = connecting.catch(() => undefined);
try {
await entered;
await Promise.race([entered, connecting.then(() => { throw new Error("Credential save did not block"); })]);
await manager.disconnect("deleted-secret", { discardState: true });
await expect(connecting).rejects.toThrow("Tailscale");
expect(await manager.loginStatus("deleted-secret")).toBeNull();