Files
PaperClipAI/server/src/services/controller-process-identity.ts
T
Dotta a3e7e63330 Guard Native recovery with process-space proof and explicit containment (#19813)
## Thinking Path

> - Paperclip manages agents and their work.
> - Recovery must preserve execution ownership and accepted results.
> - A saved PID proves nothing outside its recorded process namespace.
> - Uncertain unfinished work must stay held until its original owners
stop.
> - Operators need a source-bound containment action and a separate
ordinary Retry.
> - Accepted results must use the existing finalizer without another
provider turn.
> - This PR keeps those paths safe, recoverable, and quiet between real
obligations.

## Linked Issues or Issue Description

Refs: #19713

Refs: #19591

Recovery could use a local PID to release or replace a controller from
another process namespace. Connected-chat Retry also rejected successful
containment on a task in `todo`. The new containment action used a
broader permission than the existing owner-stop action. A later review
found that result-less guards also rejected the existing accepted-result
confirmation action.

## What Changed

- Record and verify the controller's kernel/PID namespace. Keep unknown
and foreign unfinished ownership held. Preserve independent durable stop
evidence and the existing remote lease fences.
- Use the shared accepted-result ownership reconciler. Bind settlement
to the observed lease token, generation, boot, PID, namespace and
process birth. Retain finalizer, cleanup, current-controller, live-owner
and remote exclusions.
- Share the remote-owner reader across recovery consumers. Scope runner
leases to the same company, task and run. Do not make local PID probes
for remote accepted-result ownership.
- Gate original-host containment on `runtime:confirm_owner_stop`. Bind
it to the current task, source, assignee, original expiry, lease and
Stop state. Audit separate controller/provider containment and reviewed
action outcomes.
- Keep containment separate from ordinary Retry. Use one canonical
committed receipt and the normal admission, budget, workspace and
lineage checks. Preserve the recorded external-action outcomes.
- Keep the controller-only confirmation actionable for both result-less
work and accepted results. Result-less work gets its next source-bound
attention in the same transaction. Accepted results keep their original
result and use normal shared settlement/finalization.
- Keep identity inspection quiet. Preserve the original foreign-owner
expiry and use the existing scoped finalizer in accepted-result recovery
controls.
- Update the recovery card, validators, execution projection, docs and
access maps. Reuse existing canonical columns; add no migration or
ownership backfill.

## Verification

Current publication head: `71ea76b568de09d6313d8992e803131d9d5c54f3`.

**The current fix has a causal red/green check.** On the test-only
revision, both foreign-local stopped/fenced controller cases failed
because recovery probed saved runner, process-group and provider PIDs in
this host's namespace. This measured the wrong probes; it did not run
duplicate providers. After the fix, the same two cases passed every
no-probe, no-claim, no-controller-stamp, no-stop-receipt and
unchanged-authority assertion. Three existing remote preparation, grace
and fenced-controller progress cases also passed. Total: **5 passed, 0
failed;170 filtered rows excluded**. All three normal affected App
TypeScript programs passed on this head (660,681 and428 roots).

The fix separates a controller wait from execution stop proof.
Independent live/grace evidence still schedules recovery. A
stopped/fenced foreign controller can pass this namespace guard only for
remote execution, which keeps its later checkpoint and never-launched
checks. Foreign local execution stays held before runner or provider PID
inspection.

Earlier source-scoped results remain evidence, not fresh executions on
the current head:

- On `c86dd741`, the complete failed-owner file passed **25/25**, with
no skips or filters. Empty scans wrote no controller stamps. Foreign
ownership kept its original expiry. Normal returned-claim settlement and
attention at the exact deadline passed.
- On `c86dd741`, **15 selected accepted-result/restart controls
passed**. The81 filtered rows are excluded. Both completion cases used
the existing scoped finalizer and kept their accepted result without
another provider turn.
- Trusted CI at synthetic merge `50d072a5` (actual master `1b7fe334`
plus `c86dd741`) passed the complete **17-case maintenance-server
file**. This includes the original90-real-second quiet observation and
two qualified hourly windows. The quiet case took118,918ms. The four
jobs that failed on the earlier publication all passed on that synthetic
merge.
- On `6243b32c`, the complete ownership-report file passed **29/29**.
Native NULL namespace stayed unprovable and generic compatibility
remained. Three selected recovery controls passed;170 filtered rows are
excluded.
- On `f81f2c3c`,356 business cases passed: whole ownership-route221,
recoveryUI70, owner-proof38 and controller-confirmation8; selected
accepted-result authority18; and one real connected-chat containment,
separate authorized Retry, useful Native result and downstream reply
case. The2,024 filtered rows are excluded. A separate earlier
accepted-result causal case kept the original result and completed after
restart without replay.

Normal Shared exports, App programs, UI typecheck, token gates and map
checks passed on their recorded revisions. Unchanged DB, adapter, Eval
and Runner inputs/outputs have explicit carry proofs. The clean normal
merge with fetched master `8fe524f7` preserves all31 exclusive owned
paths and14,827 unrelated master entries. The nine overlapping paths
were reviewed, including the upstream unidentified-run stop action.
Fresh CI must validate that actual merge composition.

PG cases used existing external PG17, fresh owned databases, pools at
most4, one worker and no SQL observer during cases. Registered clients
and recorded process groups closed. Independent final SQL audits found
zero campaign sessions before normal database cleanup. Original failing
fixtures remain retained.

Original failures are preserved. One new test first failed compilation
due to a missing getter import; an import-only correction passed its
full owning programs before the causal red/green check. A local quiet
attempt stopped in the normal prerequisite hook before any business case
and its collector rejected two normal build markers. The later17-case CI
pass establishes quiet recovery; it does not turn that failed local
collector into a pass. An earlier useful case passed before its private
cleanup collector failed on an owned read-only directory; normal cleanup
completed after all owners closed. Earlier runner-shutdown cancellation
and a separate private whole-suite failure remain unexplained.

Current-head checks are complete:57 success,1 neutral and3 skipped,
including the successful aggregate CI gate. The legacy status passed.
Greptile is5/5 and Ponytail gives an explicit5/5 Ship verdict for this
head. All seven review threads are resolved. Full recursive typecheck,
the full test suite and release build were not repeated locally. No
result here proves deployed suspension, a live provider or termination
on another host.

## Risks

- Unknown physical ownership can require an owner/admin action. A false
containment statement can be unsafe.
- New work, reassignment, Stop, renewed authority, accepted results or
pending cleanup can invalidate an action. The operator must refresh.
- Controller confirmation does not prove provider/tool containment.
Completed external actions must not be replayed.
- Generic legacy and child-process compatibility remains separate from
the strict Native controller policy.
- Existing saved state and canonical schema are preserved. Permanent
safety refusals remain held with their normal named recovery path.

## Model Used

OpenAI `gpt-6.1-sol` agents implemented and tested the changes with
reasoning, repository tools and code execution. A GPT-6-based Codex
managing agent reviewed and integrated them. The host does not expose
the manager's exact build or the context-window sizes.

## 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
2026-11-09 12:06:11 -06:00

231 lines
11 KiB
TypeScript

import { createHash, randomUUID } from "node:crypto";
import { execFileSync } from "node:child_process";
import { readFileSync, readlinkSync } from "node:fs";
import { hostname } from "node:os";
import { readProcessStartedAt } from "./hot-restart.js";
import { currentWorkspaceWorker, type WorkspaceWorker } from "./native-runtime/native-workspace-platform-proof.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 ControllerDeployment = { worker: WorkspaceWorker; exclusiveVolume: boolean; volumeId: string | null };
export type ControllerProcess = {
bootId: string; pid: number; hostHash: string; processStartedAt: string | null; deployment?: ControllerDeployment;
};
export function currentControllerDeployment(env: NodeJS.ProcessEnv = process.env): ControllerDeployment | null {
const worker = currentWorkspaceWorker(env);
if (!worker) return null;
const volumeId = env.RAILWAY_VOLUME_ID?.trim() || null;
return { worker, exclusiveVolume: Boolean(volumeId && env.RAILWAY_VOLUME_MOUNT_PATH?.trim()), volumeId };
}
function deploymentField(): { deployment?: ControllerDeployment } {
const deployment = currentControllerDeployment();
return deployment ? { deployment } : {};
}
function readDeployment(value: unknown): ControllerDeployment | null {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const record = value as Record<string, unknown>;
const worker = record.worker as Record<string, unknown> | null | undefined;
if (!worker || typeof worker !== "object" || worker.provider !== "railway") return null;
const ids = [worker.projectId, worker.environmentId, worker.serviceId, worker.deploymentId];
if (ids.some(id => typeof id !== "string" || id.length === 0)) return null;
return { worker: { provider: "railway", projectId: ids[0] as string, environmentId: ids[1] as string,
serviceId: ids[2] as string, deploymentId: ids[3] as string },
exclusiveVolume: record.exclusiveVolume === true,
volumeId: typeof record.volumeId === "string" ? record.volumeId : 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();
export 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 if (process.platform === "darwin") {
// One bounded, read-only kernel identity observation per module. Rounded
// boot-time estimates can collide across hosts and cannot authorize PID
// comparisons. Old weak hashes simply stop matching this stronger proof.
const bootSession = execFileSync("/usr/sbin/sysctl", ["-n", "kern.bootsessionuuid"], {
encoding: "utf8", timeout: 1_500, maxBuffer: 4_096, windowsHide: true,
}).trim().toLowerCase();
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(bootSession)) return UNKNOWN_PROCESS_SPACE;
parts.push(bootSession);
} else {
return UNKNOWN_PROCESS_SPACE;
}
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();
/** OS-observed start time of any PID (epoch ms), or null when it cannot be read. */
export 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;
/** The start time from the last resolved read, for `currentControllerProcessStamp`. */
let resolvedProcessStartedAt: string | null = null;
/** 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;
// Any resolved read also feeds the no-I/O stamp.
if (value !== null) resolvedProcessStartedAt = new Date(value).toISOString();
});
}
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;
}
const stampListeners = new Set<() => void>();
/** Called (synchronously, without I/O) whenever this process stamps ownership of a record. */
export function onControllerStamp(listener: () => void): () => void {
stampListeners.add(listener);
return () => { stampListeners.delete(listener); };
}
function notifyStamp() {
for (const listener of stampListeners) {
try { listener(); } catch { /* a listener never blocks a stamp */ }
}
}
export async function currentControllerProcess(): Promise<ControllerProcess> {
const startedAt = await currentProcessStartedAtMs();
const iso = startedAt === null ? null : new Date(startedAt).toISOString();
resolvedProcessStartedAt = iso;
notifyStamp();
return { bootId, pid: process.pid, hostHash, processStartedAt: iso, ...deploymentField() };
}
/**
* This process's identity without any I/O, for stamps written on the turn
* path. The start time is present only once an earlier call resolved it. A
* stamp without one still proves exit when its PID is gone in this PID space;
* a live PID then stays ambiguous, which fails closed.
*/
export function currentControllerProcessStamp(): ControllerProcess {
notifyStamp();
return { bootId, pid: process.pid, hostHash, processStartedAt: resolvedProcessStartedAt, ...deploymentField() };
}
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;
const deployment = readDeployment(record.deployment);
return { bootId: record.bootId, pid: record.pid, hostHash: record.hostHash,
processStartedAt: typeof record.processStartedAt === "string" ? record.processStartedAt : null,
...(deployment ? { deployment } : {}) };
}
/**
* 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;
// Without a recorded start time a live PID can never prove exit; skip the probe.
if (!Number.isFinite(Date.parse(controller.processStartedAt ?? ""))) return false;
// 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));
}
/** This process's PID-space hash. An unreadable space is stored as
* "unknown", which `sameProcessSpace` never accepts. */
export function currentProcessSpaceHash(): string {
return hostHash;
}
/**
* Whether a PID recorded under `recorded` can be judged in this process.
* True only for the same readable PID space. A different or unreadable space
* is never proof: a dead PID here says nothing about a process elsewhere.
*/
export function sameProcessSpace(recorded: string | null | undefined): boolean {
return typeof recorded === "string" && hostHash !== UNKNOWN_PROCESS_SPACE && recorded === hostHash;
}