Files
PaperClipAI/server/src/services/controller-process-identity.ts
T
DottaandClaude Opus 5.5 fa86162790 refactor(recovery): one process boot id and a cached controller identity (#19851)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Restart recovery decides when a record owned by a dead server
process may be released
> - One server process minted three different boot UUIDs, one per module
(`controller-process-identity.ts:13`, `native-restart-recovery.ts:284`,
`legacy-controller-lease.ts:8`)
> - The controller identity also ran `ps -o lstart` on macOS at every
native claim, preparation check and lease renewal, which is on the path
before `turn.start`
> - The durable ownership plan (Phase 1, step 1) needs one process
identity before it can add one owner stamp and one prover
> - This pull request makes the three modules stamp one boot id and
reads the process start time from the OS once
> - The benefit is one meaning of "owned by this process" across tables,
and no `ps` spawn on the turn path

## Linked Issues or Issue Description

Refs #19831 (plan:
`doc/plans/2026-11-07-durable-ownership-and-reconciliation.md`, Phase
1). Refs #19846 (Phase 0 inventory, finding 1, and the TTFT baseline row
"Controller identity").

**Problem**
One process has three boot ids, so the same fact ("this record is owned
by this process") has three encodings. The uncached controller identity
spawns `ps` on macOS on every claim and renewal.

**Expected behavior**
One boot id per process. The OS start-time read runs once per process.

**Impact**
Phase 1 needs one identity to build `OwnerStamp` and `proveOwnerGone`
on. The turn path loses one subprocess spawn per claim and renewal.

## What Changed

- `controller-process-identity.ts` owns the single process boot id. It
adds `currentProcessStartedAtMs()`, which caches a successful OS
start-time read for the life of the process and retries a failed read.
It also exports `currentProcessSpaceHash()` for the coming prover.
- `native-restart-recovery.ts`: `currentNativeControllerIdentity()` and
`isCurrentNativeControllerProcess()` use the shared boot id and the
cached start time. Its own `randomUUID()` boot id is removed. The
fallback to the server-info start time is kept.
- `legacy-controller-lease.ts`: `legacyControllerBootId` is now the
shared boot id.
- Tests in `native-controller-identity.test.ts`: one boot id across
native claims, legacy leases and creation intents; one OS read across
many claims and renewals; a failed read is retried, not cached.

## Verification

- `npx vitest run
src/services/native-runtime/native-controller-identity.test.ts
src/services/legacy-controller-lease.test.ts
src/__tests__/heartbeat-pending-cleanup-sweep.test.ts
src/__tests__/sandbox-creation-operations.test.ts
src/services/heartbeat/upgrade-readiness-post-result.test.ts
src/services/heartbeat/recovery.test.ts` (in `server/`): 6 files pass.
- `npx tsc --noEmit -p server`: no errors.
- I checked every reader of the three ids. Each one compares a stored
column only with the id of the module that writes that column
(`heartbeat_runs.controller_boot_id` with the legacy id,
`native_run_finalizations.controller_boot_id` with the native id,
metadata `bootId` with the creation id). No reader compares the ids of
two modules, so making them equal changes no decision inside one
process.

## Risks

- Low risk. No schema change and no persisted shape change.
- Previous-release story (`rules/upgrade-safe-run-state.mdc`): rows
saved by an older release carry that release's random per-module ids.
They never equal the new process's id, exactly as a row from any earlier
boot never did. They carry forward with no migration.
- The start-time cache is correct because a process's own start time
never changes. A failed read is not cached, so a transient `ps` failure
does not pin the fallback value.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with
tool use and code execution.

## 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-07 10:49:12 -06:00

145 lines
6.3 KiB
TypeScript

import { createHash, randomUUID } from "node:crypto";
import { readFileSync, readlinkSync } from "node:fs";
import { hostname, uptime } from "node:os";
import { readProcessStartedAt } from "./hot-restart.js";
/**
* Identity of the server process that started a provider side effect, saved
* with its durable record. After a restart, recovery uses it to prove that the
* starter has exited, so the side effect cannot still be in flight there.
*/
export type ControllerProcess = { bootId: string; pid: number; hostHash: string; processStartedAt: string | null };
/**
* The one boot id of this server process. Native coordinator claims
* (`native_run_finalizations.controller_boot_id`), legacy controller leases
* (`heartbeat_runs.controller_boot_id`), sandbox creation intents and teardown
* claims all stamp this value, so "owned by this process" means the same thing
* in every table. Records written by an older release carry that release's
* random per-module ids; those never equal this value, exactly as a record
* from any earlier boot never did.
*/
const bootId = randomUUID();
const UNKNOWN_PROCESS_SPACE = "unknown";
/**
* Names the space in which PIDs are comparable: one kernel boot and, on Linux,
* one PID namespace. Containers that share a hostname but not a PID namespace
* get different values. When the space cannot be read, no record is judged.
* A redeploy onto another host or namespace also never matches; such records
* keep their original deadlines.
*/
function processSpaceHash(): string {
try {
const parts = [hostname()];
if (process.platform === "linux") {
parts.push(readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim(), readlinkSync("/proc/self/ns/pid"));
} else {
// No PID namespaces here. The boot time keeps a rebooted host distinct;
// rounding can only make a record unmatched, which fails closed.
parts.push(String(Math.round((Date.now() - uptime() * 1000) / 600_000)));
}
if (parts.some(part => !part)) return UNKNOWN_PROCESS_SPACE;
return createHash("sha256").update(parts.join("\0")).digest("hex").slice(0, 32);
} catch {
return UNKNOWN_PROCESS_SPACE;
}
}
const hostHash = processSpaceHash();
async function observedProcessStartedAt(pid: number): Promise<number | null> {
try {
const startedAt = Date.parse(await readProcessStartedAt(pid) ?? "");
return Number.isFinite(startedAt) ? startedAt : null;
} catch {
return null;
}
}
// This process's own start time never changes, so it is read from the OS once.
// On macOS the read runs `ps -o lstart`; uncached, it ran on every native
// claim, preparation check and lease renewal. A failed read is not cached, so
// a transient failure is retried by the next caller.
let ownStartedAt: Promise<number | null> | undefined;
/** OS-observed start time of this server process (epoch ms), read at most once
* successfully per process. Null when the OS cannot report it. */
export function currentProcessStartedAtMs(): Promise<number | null> {
if (!ownStartedAt) {
const read = observedProcessStartedAt(process.pid);
ownStartedAt = read;
void read.then(value => {
if (value === null && ownStartedAt === read) ownStartedAt = undefined;
});
}
return ownStartedAt;
}
/** Test seam: forget the cached start time so a test can stub the OS read. */
export function resetCurrentProcessStartedAtForTests(): void {
ownStartedAt = undefined;
}
export function currentControllerBootId(): string {
return bootId;
}
export async function currentControllerProcess(): Promise<ControllerProcess> {
const startedAt = await currentProcessStartedAtMs();
return { bootId, pid: process.pid, hostHash,
processStartedAt: startedAt === null ? null : new Date(startedAt).toISOString() };
}
export function readControllerProcess(value: unknown): ControllerProcess | null {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const record = value as Record<string, unknown>;
if (typeof record.bootId !== "string" || typeof record.hostHash !== "string" ||
typeof record.pid !== "number" || !Number.isInteger(record.pid) || record.pid <= 0) return null;
return { bootId: record.bootId, pid: record.pid, hostHash: record.hostHash,
processStartedAt: typeof record.processStartedAt === "string" ? record.processStartedAt : null };
}
/**
* True when some process owns the PID in this PID space. EPERM means the
* process exists but belongs to another user, so it counts as alive.
*/
export function processExists(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch (error) {
return (error as NodeJS.ErrnoException | undefined)?.code === "EPERM";
}
}
/** Process start times closer than this may be the same process. */
export const PROCESS_START_PRECISION_MS = 1_000;
/**
* True only when two start times for one PID prove different processes.
* `ps -o lstart` on macOS and BSD has whole-second precision, while a recorded
* start can come from a millisecond clock, so a sub-second gap is ambiguous
* and fails closed (same process). A missing or unparsable time proves nothing.
*/
export function processStartsDefinitelyDiffer(
recorded: Date | string | null | undefined,
observed: Date | string | null | undefined,
): boolean {
const left = recorded instanceof Date ? recorded.getTime() : Date.parse(recorded ?? "");
const right = observed instanceof Date ? observed.getTime() : Date.parse(observed ?? "");
return Number.isFinite(left) && Number.isFinite(right) && Math.abs(left - right) >= PROCESS_START_PRECISION_MS;
}
/** True only with proof, in this process's own PID space, that the recorded
* server process has exited. Another space, an unreadable space, this server,
* or an ambiguous live PID returns false. */
export async function controllerProcessExited(controller: ControllerProcess): Promise<boolean> {
if (controller.bootId === bootId || hostHash === UNKNOWN_PROCESS_SPACE || controller.hostHash !== hostHash) return false;
if (!processExists(controller.pid)) return true;
// The PID now belongs to a live process, possibly this restarted server.
// Only a definitely different start time proves the recorded process is gone.
const observed = await observedProcessStartedAt(controller.pid);
return observed !== null && processStartsDefinitelyDiffer(controller.processStartedAt, new Date(observed));
}