fix: record Linux process birth from kernel ticks

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-06 13:52:35 -05:00
1 parent d26ff52272
commit 9fdcefcc34
10 files changed
+149 -22

No files matched your search

@@ -305,6 +305,14 @@ the lease TTL to match its required revocation bound.
## Restart and reconciliation
Local Linux process receipts use the kernel's `/proc/PID/stat` start ticks,
`/proc/stat` boot time and `CLK_TCK` to record process birth. The server and
retained Runner maintenance use the same reader. `/proc/PID` directory ctime
can differ from birth and must not grant process ownership. Invalid or missing
birth metadata fails closed. PID, process group and owner checks remain required.
Drain active Linux runs before updating or rolling back across the previous
ctime-based receipt format; do not rewrite a live receipt to force adoption.
A socket drop keeps the same Rust process and in-memory lease. The process
reconnects and reloads the mock-core command and event cursor.
+1
View File
@@ -66,6 +66,7 @@ export {
type RunnerdCodexTransportOptions,
} from "./live/runnerd-codex-transport.js";
export * from "./live/workspace-file-reference.js";
export { readLinuxProcessStartedAt, type LinuxProcessStartOptions } from "./live/linux-process-start.js";
export * from "./protocol/replay-contract.js";
export * from "./protocol/replay-loader.js";
export * from "./protocol/result-normalization.js";
@@ -4,5 +4,6 @@ export * from "./live-session.js";
export * from "./durable-live-session-store.js";
export * from "./runnerd-codex-transport.js";
export * from "./turn-stream.js";
export * from "./linux-process-start.js";
export { probeAcpxClaudeInstallation, probeAcpxGrokInstallation, probeAcpxPiInstallation } from "../drivers/acpx/installation-integrity.js";
@@ -0,0 +1,41 @@
import { spawn } from "node:child_process";
import { expect, it } from "vitest";
import { readLinuxProcessStartedAt } from "./linux-process-start.js";
const stat = (ticks: string, command = "runner") => `123 (${command}) S ${Array(18).fill("0").join(" ")} ${ticks}\n`;
const options = (processStat = stat("123"), systemStat = "btime 1785546000\n", clockTicksPerSecond = 100) => ({
clockTicksPerSecond,
readFile: (path: string) => path === "/proc/123/stat" ? processStat : systemStat,
});
it("uses kernel birth ticks even when the command contains spaces and parentheses", () => {
expect(readLinuxProcessStartedAt(123, options(stat("123", "a ) b ( c"))))
.toBe(new Date(1785546001230).toISOString());
expect(readLinuxProcessStartedAt(123, options(stat("124"))))
.not.toBe(readLinuxProcessStartedAt(123, options()));
});
it.each([
[stat("bad"), "btime 1785546000\n", 100],
[stat("123").replace("123 (", "124 ("), "btime 1785546000\n", 100],
["123 (runner) S", "btime 1785546000\n", 100],
[stat("123"), "btime invalid\n", 100],
[stat("123"), "btime 1785546000\n", 0],
[stat("123"), "btime 1785546000\n", Number.NaN],
[stat("123"), "btime 999999999999999999999\n", 100],
])("fails closed on malformed birth metadata or clock frequency", (processStat, systemStat, frequency) => {
expect(() => readLinuxProcessStartedAt(123, options(processStat, systemStat, frequency))).toThrow();
});
it.skipIf(process.platform !== "linux")("keeps the actual owned child's birth identity stable through a delayed observation", async () => {
const child = spawn("/bin/sleep", ["10"], { stdio: "ignore" });
const closed = new Promise<void>(resolve => child.once("close", () => resolve()));
try {
expect(child.pid).toBeGreaterThan(0);
const first = readLinuxProcessStartedAt(child.pid!);
await new Promise(resolve => setTimeout(resolve, 1100));
expect(readLinuxProcessStartedAt(child.pid!)).toBe(first);
child.kill("SIGTERM"); await closed;
expect(() => readLinuxProcessStartedAt(child.pid!)).toThrow();
} finally { child.kill("SIGTERM"); await closed; }
}, 5000);
@@ -0,0 +1,40 @@
import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
let clockTicksPerSecond: number | undefined;
export interface LinuxProcessStartOptions {
readFile?: (path: string) => string;
clockTicksPerSecond?: number;
}
/** /proc/PID directory ctime is lookup metadata, not the process's birth time. */
export function readLinuxProcessStartedAt(pid: number, options: LinuxProcessStartOptions = {}): string {
if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error("Invalid Linux process PID");
const readFile = options.readFile ?? ((path: string) => readFileSync(path, "utf8"));
const processStat = readFile(`/proc/${pid}/stat`);
// comm can contain spaces and parentheses. Fields after its final ')' start
// at field 3 (state), so field 22 (starttime) is index 19 in this suffix.
const end = processStat.lastIndexOf(") ");
const fields = end >= 0 ? processStat.slice(end + 2).trim().split(/\s+/) : [];
const startTicks = fields[19];
const bootSeconds = /^btime (\d+)$/m.exec(readFile("/proc/stat"))?.[1];
if (!processStat.startsWith(`${pid} (`) || !/^\d+$/.test(startTicks ?? "") || !bootSeconds) {
throw new Error("Invalid Linux process birth metadata");
}
let ticks = options.clockTicksPerSecond;
if (ticks === undefined) {
clockTicksPerSecond ??= Number(execFileSync("getconf", ["CLK_TCK"], {
encoding: "utf8", timeout: 1_500, windowsHide: true,
env: { PATH: "/usr/bin:/bin", LANG: "C", LC_ALL: "C" },
}).trim());
ticks = clockTicksPerSecond;
}
if (!Number.isSafeInteger(ticks) || ticks <= 0) throw new Error("Invalid Linux clock tick frequency");
const milliseconds = BigInt(bootSeconds) * 1_000n + BigInt(startTicks!) * 1_000n / BigInt(ticks);
const value = Number(milliseconds);
if (!Number.isSafeInteger(value) || !Number.isFinite(new Date(value).getTime())) {
throw new Error("Invalid Linux process birth timestamp");
}
return new Date(value).toISOString();
}
@@ -5,6 +5,7 @@ import { waitForWarmAttachmentReadiness } from "./warm-attachment-readiness.js";
import { codexExecutableReadOnlyRoots } from "../drivers/codex/codex-security-config.js";
import { isCanonicalProviderEventType } from "../provider-events.js";
import { execFileSync } from "node:child_process";
import { readLinuxProcessStartedAt } from "./linux-process-start.js";
import { createHash, randomUUID } from "node:crypto";
import {
appendFileSync,
@@ -96,7 +97,7 @@ function readLocalProcessStartedAt(pid: number): string | null {
if (!Number.isInteger(pid) || pid <= 0) return null;
try {
if (process.platform === "linux") {
return new Date(statSync(`/proc/${pid}`).ctimeMs).toISOString();
return readLinuxProcessStartedAt(pid);
}
if (
["darwin", "freebsd", "openbsd", "aix", "sunos"].includes(