Files
PaperClipAI/server/src/services/hot-restart.test.ts
T
DottaandPaperclip b163c6c473 fix(server): preserve hot restart intent across path upgrade (#10593)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The server can preserve eligible agent runs during a controlled hot
restart.
> - A path change moved restart state from the Paperclip home root to
the instance root.
> - A staged update can therefore make the old server and the new server
read different intent files.
> - The old server then drains live runs, while the new server can start
without a shutdown snapshot.
> - This pull request adds a correlated compatibility handoff and
records the live preflight set.
> - It also verifies the target process instance on Linux, macOS, and
Windows.
> - The benefit is complete and safe run classification across the path
upgrade.

## Linked Issues or Issue Description

No public GitHub issue covers this defect.

**What happened?**

A staged hot restart can run an older server that reads
`hot-restart-intent.json` from the Paperclip home root and a new server
that writes the file under the instance root. The old server misses the
request and uses graceful drain. The new server later finds its marker
without a shutdown snapshot. Before this change, that state could
produce an empty loss list even when live runs existed before restart.

**Expected behavior**

The old server must receive the PID-targeted restart request at its
legacy path. The new server must correlate the legacy shutdown snapshot
with its instance-scoped request. Every run that was live during
preflight must appear as adopted, finalized while down, or lost. A
reused PID must not let a stale marker claim a different process
instance.

**Steps to reproduce**

1. Start a server version from before the instance-root marker change.
2. Keep one or more local-agent heartbeat runs active.
3. Stage a current build and request a hot restart from that build.
4. Observe that the old server reads only the home-root path while the
staged build writes only the instance-root path.
5. Observe graceful drain and a new-server intent that has no shutdown
snapshot.

**Paperclip version or commit**

The path transition entered `master` in #10045. The hot-restart adoption
flow came from #9647. This fix targets current `master` and
compatibility with the immediately preceding home-root behavior.

**Deployment mode**

Self-hosted server built from source with controlled service hot
restarts.

Related work: #9628 is the original broader hot-restart feature PR.
#10556 addresses embedded PostgreSQL lifecycle behavior and does not
address marker-path compatibility.

## What Changed

- Write an authoritative instance-scoped intent and a correlated legacy
home-root handoff marker.
- Merge a legacy shutdown snapshot only when immutable request identity
fields match.
- Prevent a non-default instance from consuming an uncorrelated
legacy-only marker.
- Record preflight running heartbeat IDs and reconcile snapshot
omissions from current database state.
- Serialize marker claims, snapshot writes, stale recovery, and matching
cleanup with recoverable per-path filesystem leases.
- Read process start identity on Linux, macOS, and Windows to
distinguish a reused PID from the original server.
- Require identity for new restart requests and fail closed when a
supported platform cannot provide it.
- Classify older markers by comparing the replacement server boot time
or operating-system process start time with the request time.
- Close the preflight database client explicitly and use a root-safe SQL
query.
- Add focused unit, platform-branch, database-backed, and CI regression
coverage.
- Document the compatibility handoff, process identity probes, and
instance-scoped report path.

## Verification

- `pnpm exec vitest run server/src/services/hot-restart.test.ts
server/src/__tests__/heartbeat-process-recovery.test.ts -t
"hot-restart|old-server legacy|preflight live|preflight run|spawn
identity before hot restart"` — 24 tests passed and 90 tests were
skipped across 2 files.
- `pnpm exec vitest run server/src/services/hot-restart.test.ts` — 17
tests passed.
- `pnpm exec vitest run
server/src/__tests__/issue-watchdogs-routes.test.ts -t "restarts a
stalled claimed run"` — 1 test passed and 10 tests were skipped.
- `pnpm exec vitest run
server/src/__tests__/agent-action-audit-routes.test.ts -t "allows an
agent with issue:delegate"` — 1 test passed and 7 tests were skipped.
- `pnpm --filter @paperclipai/server typecheck` — passed.
- `git diff --check` — passed.
- GitHub Actions — 26 of 26 checks passed at
`55a79cb029be8b1dc89926d9d89ccd2181266d5c`.
- Greptile — 5/5 at the same head with no unresolved current-head review
threads.

## Risks

- The legacy handoff path is shared across instances. Exclusive claims
and per-path leases prevent overwrite and match-before-delete races.
- Process identity uses platform commands as a fallback when the health
endpoint has no identity. Linux reads `/proc`, macOS and BSD use `ps`,
and Windows uses PowerShell.
- A supported-platform identity probe failure aborts the restart. This
fails closed instead of replacing an unknown live process.
- Older intent files do not contain process identity. The server
compares the replacement boot or process start time with the request
time when those values are available.
- A preflight database read can fail before the marker is written. The
command fails closed instead of claiming a restart whose live-run set is
unknown.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- OpenAI Codex with GPT-5. The exact deployment model ID and
context-window size were not exposed by this runtime. Reasoning,
repository editing, shell execution, test execution, GitHub CLI, and
Paperclip API capabilities were enabled.

## 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 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>
2026-07-31 21:55:59 -07:00

477 lines
16 KiB
TypeScript

import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
findMissingHotRestartSnapshotRunIds,
isObservedHotRestartTargetAlive,
readHotRestartIntent,
readProcessStartedAt,
removeHotRestartIntent,
resolveHotRestartIntentPath,
resolveLegacyHotRestartIntentPath,
writeHotRestartIntent,
} from "./hot-restart.js";
const originalInstanceId = process.env.PAPERCLIP_INSTANCE_ID;
afterEach(() => {
if (originalInstanceId === undefined) delete process.env.PAPERCLIP_INSTANCE_ID;
else process.env.PAPERCLIP_INSTANCE_ID = originalInstanceId;
});
async function withTempHome<T>(fn: (homeDir: string) => Promise<T>) {
const homeDir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-hot-restart-paths-"));
try {
return await fn(homeDir);
} finally {
await fs.rm(homeDir, { recursive: true, force: true });
}
}
describe("hot-restart path compatibility", () => {
it("reads Linux process start time from proc metadata", async () => {
await expect(
readProcessStartedAt(123, {
platform: "linux",
stat: async (target) => {
expect(target).toBe("/proc/123");
return {
ctimeMs: Date.parse("2026-08-01T01:00:00.123Z"),
};
},
}),
).resolves.toBe("2026-08-01T01:00:00.123Z");
});
it("reads macOS process start time through ps", async () => {
await expect(
readProcessStartedAt(456, {
platform: "darwin",
runCommand: async (command, args) => {
expect([command, ...args]).toEqual([
"ps",
"-o",
"lstart=",
"-p",
"456",
]);
return "Fri Aug 1 01:02:03 2026\n";
},
}),
).resolves.toBe(new Date("Fri Aug 1 01:02:03 2026").toISOString());
});
it("reads Windows process start time through PowerShell", async () => {
await expect(
readProcessStartedAt(789, {
platform: "win32",
runCommand: async (command, args) => {
expect(command).toBe("powershell.exe");
expect(args.at(-1)).toContain("Get-Process -Id 789");
return "2026-08-01T01:02:03.456Z\r\n";
},
}),
).resolves.toBe("2026-08-01T01:02:03.456Z");
});
it("falls back from Windows PowerShell to pwsh", async () => {
const commands: string[] = [];
await expect(
readProcessStartedAt(790, {
platform: "win32",
runCommand: async (command) => {
commands.push(command);
if (command === "powershell.exe") throw new Error("not installed");
return "2026-08-01T01:02:04.000Z\n";
},
}),
).resolves.toBe("2026-08-01T01:02:04.000Z");
expect(commands).toEqual(["powershell.exe", "pwsh.exe"]);
});
it("surfaces supported-platform process identity probe failures", async () => {
await expect(readProcessStartedAt(791, {
platform: "darwin",
runCommand: async () => {
throw new Error("ps unavailable");
},
})).rejects.toThrow("ps unavailable");
});
it("distinguishes recycled PIDs and rejects unknown live claim classification", () => {
const intent = {
version: 1 as const,
requestedAt: "2026-08-01T01:05:00.000Z",
previousServerPid: 123,
previousServerIdentity: "server-boot-a",
previousServerStartedAt: "2026-08-01T01:00:00.000Z",
previousServerVersion: "old-version",
drainRequired: false,
requestedByRunId: null,
preflightActiveRunIds: [],
};
expect(isObservedHotRestartTargetAlive(intent, {
alive: true,
startedAt: "2026-08-01T01:00:00.000Z",
replacement: {
previousServerPid: 123,
previousServerIdentity: "server-boot-a",
},
})).toBe(true);
expect(isObservedHotRestartTargetAlive(intent, {
alive: true,
startedAt: null,
replacement: {
previousServerPid: 123,
previousServerIdentity: "server-boot-b",
},
})).toBe(false);
const legacyIntent = {
...intent,
previousServerIdentity: null,
previousServerStartedAt: null,
};
expect(isObservedHotRestartTargetAlive(legacyIntent, {
alive: true,
startedAt: "2026-08-01T01:06:00.000Z",
})).toBe(false);
expect(() => isObservedHotRestartTargetAlive(legacyIntent, {
alive: true,
startedAt: null,
})).toThrow("Cannot establish process identity");
expect(isObservedHotRestartTargetAlive(legacyIntent, {
alive: true,
startedAt: null,
replacement: {
previousServerPid: 123,
previousServerIdentity: "2026-08-01T01:04:00.000Z",
},
})).toBe(true);
expect(isObservedHotRestartTargetAlive(legacyIntent, {
alive: true,
startedAt: null,
replacement: {
previousServerPid: 123,
previousServerIdentity: "2026-08-01T01:06:00.000Z",
},
})).toBe(false);
expect(isObservedHotRestartTargetAlive(legacyIntent, {
alive: true,
startedAt: null,
replacement: {
previousServerPid: 123,
previousServerIdentity: null,
previousServerStartedAt: "2026-08-01T01:04:00.000Z",
},
})).toBe(true);
expect(isObservedHotRestartTargetAlive(legacyIntent, {
alive: true,
startedAt: null,
replacement: {
previousServerPid: 123,
previousServerIdentity: null,
previousServerStartedAt: "2026-08-01T01:06:00.000Z",
},
})).toBe(false);
});
it("refuses to create an unidentifiable process claim", async () => {
await withTempHome(async (homeDir) => {
await expect(writeHotRestartIntent({
homeDir,
previousServerPid: 2_147_483_647,
previousServerStartedAt: null,
})).rejects.toThrow("process start time are unavailable");
await expect(fs.stat(resolveHotRestartIntentPath(homeDir))).rejects.toMatchObject({
code: "ENOENT",
});
await expect(fs.stat(resolveLegacyHotRestartIntentPath(homeDir))).rejects.toMatchObject({
code: "ENOENT",
});
});
});
it("reclaims a live recycled PID when server boot identities differ", async () => {
await withTempHome(async (homeDir) => {
process.env.PAPERCLIP_INSTANCE_ID = "blue";
await writeHotRestartIntent({
homeDir,
previousServerPid: process.pid,
previousServerIdentity: "server-boot-a",
requestedByRunId: "blue-deploy",
});
process.env.PAPERCLIP_INSTANCE_ID = "green";
await expect(writeHotRestartIntent({
homeDir,
previousServerPid: process.pid,
previousServerIdentity: "server-boot-b",
requestedByRunId: "green-deploy",
})).resolves.toMatchObject({
previousServerIdentity: "server-boot-b",
requestedByRunId: "green-deploy",
});
});
});
it("writes both paths but does not merge a legacy snapshot from another request", async () => {
process.env.PAPERCLIP_INSTANCE_ID = "blue";
await withTempHome(async (homeDir) => {
await writeHotRestartIntent({
homeDir,
previousServerPid: 101,
previousServerStartedAt: "2026-08-01T01:00:00.000Z",
requestedAt: new Date("2026-08-01T02:00:00.000Z"),
requestedByRunId: "blue-deploy",
preflightActiveRunIds: ["blue-run"],
});
await expect(fs.stat(resolveHotRestartIntentPath(homeDir))).resolves.toBeDefined();
await expect(fs.stat(resolveLegacyHotRestartIntentPath(homeDir))).resolves.toBeDefined();
const unrelatedLegacyIntent = {
version: 1,
requestedAt: "2026-08-01T02:00:01.000Z",
previousServerPid: 202,
previousServerVersion: "other-instance",
drainRequired: false,
requestedByRunId: "other-deploy",
shutdownSnapshot: {
capturedAt: "2026-08-01T02:00:02.000Z",
signal: "SIGTERM",
activeRuns: [],
},
};
await fs.writeFile(
resolveLegacyHotRestartIntentPath(homeDir),
`${JSON.stringify(unrelatedLegacyIntent, null, 2)}\n`,
"utf8",
);
await expect(readHotRestartIntent(homeDir)).resolves.toMatchObject({
previousServerPid: 101,
requestedByRunId: "blue-deploy",
preflightActiveRunIds: ["blue-run"],
});
expect((await readHotRestartIntent(homeDir))?.shutdownSnapshot).toBeUndefined();
});
});
it("does not let a non-default instance consume an uncorrelated legacy-only marker", async () => {
process.env.PAPERCLIP_INSTANCE_ID = "green";
await withTempHome(async (homeDir) => {
await fs.writeFile(
resolveLegacyHotRestartIntentPath(homeDir),
`${JSON.stringify({
version: 1,
requestedAt: "2026-08-01T03:00:00.000Z",
previousServerPid: 303,
previousServerVersion: "legacy",
drainRequired: false,
requestedByRunId: null,
})}\n`,
"utf8",
);
await expect(readHotRestartIntent(homeDir)).resolves.toBeNull();
});
});
it("ignores a malformed legacy marker when the instance marker is valid", async () => {
process.env.PAPERCLIP_INSTANCE_ID = "blue";
await withTempHome(async (homeDir) => {
await writeHotRestartIntent({
homeDir,
previousServerPid: 304,
previousServerStartedAt: "2026-08-01T03:00:00.000Z",
requestedAt: new Date("2026-08-01T03:30:00.000Z"),
preflightActiveRunIds: ["blue-run"],
});
await fs.writeFile(resolveLegacyHotRestartIntentPath(homeDir), "not-json", "utf8");
await expect(readHotRestartIntent(homeDir)).resolves.toMatchObject({
previousServerPid: 304,
preflightActiveRunIds: ["blue-run"],
});
});
});
it("does not overwrite another instance's active legacy handoff", async () => {
await withTempHome(async (homeDir) => {
process.env.PAPERCLIP_INSTANCE_ID = "blue";
await writeHotRestartIntent({
homeDir,
previousServerPid: process.pid,
requestedAt: new Date("2026-08-01T03:40:00.000Z"),
requestedByRunId: "blue-deploy",
});
process.env.PAPERCLIP_INSTANCE_ID = "green";
await expect(writeHotRestartIntent({
homeDir,
previousServerPid: 502,
previousServerStartedAt: "2026-08-01T03:00:00.000Z",
requestedAt: new Date("2026-08-01T03:40:01.000Z"),
requestedByRunId: "green-deploy",
})).rejects.toMatchObject({ code: "EEXIST" });
const legacyIntent = JSON.parse(
await fs.readFile(resolveLegacyHotRestartIntentPath(homeDir), "utf8"),
) as Record<string, unknown>;
expect(legacyIntent).toMatchObject({
previousServerPid: process.pid,
requestedByRunId: "blue-deploy",
});
await expect(fs.stat(resolveHotRestartIntentPath(homeDir))).rejects.toMatchObject({
code: "ENOENT",
});
});
});
it("reclaims an abandoned legacy handoff after its target process exits", async () => {
await withTempHome(async (homeDir) => {
process.env.PAPERCLIP_INSTANCE_ID = "blue";
await writeHotRestartIntent({
homeDir,
previousServerPid: 2_147_483_647,
previousServerStartedAt: "2026-08-01T03:00:00.000Z",
requestedAt: new Date("2026-08-01T03:50:00.000Z"),
requestedByRunId: "abandoned-deploy",
});
process.env.PAPERCLIP_INSTANCE_ID = "green";
await expect(writeHotRestartIntent({
homeDir,
previousServerPid: process.pid,
requestedAt: new Date("2026-08-01T03:51:00.000Z"),
requestedByRunId: "green-deploy",
})).resolves.toMatchObject({ requestedByRunId: "green-deploy" });
await expect(readHotRestartIntent(homeDir)).resolves.toMatchObject({
previousServerPid: process.pid,
requestedByRunId: "green-deploy",
});
});
});
it("reclaims an abandoned handoff when its PID belongs to a newer process", async () => {
await withTempHome(async (homeDir) => {
process.env.PAPERCLIP_INSTANCE_ID = "blue";
await writeHotRestartIntent({
homeDir,
previousServerPid: process.pid,
requestedAt: new Date("2020-01-01T00:00:00.000Z"),
requestedByRunId: "expired-deploy",
});
const legacyPath = resolveLegacyHotRestartIntentPath(homeDir);
const legacyIntent = JSON.parse(
await fs.readFile(legacyPath, "utf8"),
) as Record<string, unknown>;
delete legacyIntent.previousServerStartedAt;
await fs.writeFile(
legacyPath,
`${JSON.stringify(legacyIntent, null, 2)}\n`,
"utf8",
);
process.env.PAPERCLIP_INSTANCE_ID = "green";
await expect(writeHotRestartIntent({
homeDir,
previousServerPid: process.pid,
requestedByRunId: "green-deploy",
})).resolves.toMatchObject({ requestedByRunId: "green-deploy" });
await expect(readHotRestartIntent(homeDir)).resolves.toMatchObject({
requestedByRunId: "green-deploy",
});
});
});
it("keeps an old handoff while its original target process is alive", async () => {
await withTempHome(async (homeDir) => {
process.env.PAPERCLIP_INSTANCE_ID = "blue";
await writeHotRestartIntent({
homeDir,
previousServerPid: process.pid,
requestedAt: new Date(),
requestedByRunId: "blue-deploy",
});
vi.useFakeTimers({ now: Date.now() + 10 * 60_000 });
try {
process.env.PAPERCLIP_INSTANCE_ID = "green";
await expect(writeHotRestartIntent({
homeDir,
previousServerPid: process.pid,
requestedByRunId: "green-deploy",
})).rejects.toMatchObject({ code: "EEXIST" });
} finally {
vi.useRealTimers();
}
});
});
it("does not let matching cleanup delete replacement intent markers", async () => {
await withTempHome(async (homeDir) => {
process.env.PAPERCLIP_INSTANCE_ID = "blue";
const abandonedIntent = await writeHotRestartIntent({
homeDir,
previousServerPid: 2_147_483_647,
previousServerStartedAt: "2026-08-01T03:00:00.000Z",
requestedAt: new Date("2026-08-01T03:55:00.000Z"),
requestedByRunId: "abandoned-deploy",
});
await Promise.all([
removeHotRestartIntent(homeDir, abandonedIntent),
writeHotRestartIntent({
homeDir,
previousServerPid: process.pid,
requestedAt: new Date("2026-08-01T03:56:00.000Z"),
requestedByRunId: "replacement-deploy",
}),
]);
const legacyIntent = JSON.parse(
await fs.readFile(resolveLegacyHotRestartIntentPath(homeDir), "utf8"),
) as Record<string, unknown>;
expect(legacyIntent).toMatchObject({ requestedByRunId: "replacement-deploy" });
await expect(readHotRestartIntent(homeDir)).resolves.toMatchObject({
requestedByRunId: "replacement-deploy",
});
});
});
it("treats every preflight run omitted from the shutdown snapshot as missing", () => {
expect(findMissingHotRestartSnapshotRunIds({
version: 1,
requestedAt: "2026-08-01T04:00:00.000Z",
previousServerPid: 404,
previousServerVersion: "old-version",
drainRequired: false,
requestedByRunId: null,
preflightActiveRunIds: ["captured-run", "missing-run"],
shutdownSnapshot: {
capturedAt: "2026-08-01T04:00:01.000Z",
signal: "SIGTERM",
activeRuns: [{
runId: "captured-run",
companyId: "company",
agentId: "agent",
adapterType: "codex_local",
status: "running",
processPid: 405,
processGroupId: null,
issueId: "issue",
}],
},
})).toEqual(["missing-run"]);
});
});