fix(producer): a dead render's folder is cleaned up reliably, never another machine's (#8538)

* test(producer): a dead render's dir is reclaimed when the boot estimate rounds the other way

* fix(producer): a dead render's dir is reclaimed though the boot estimate rounds the other way

* fix(producer): a render owner's boot is stamped in seconds on this machine's own id

* test(producer): the machine-id tools run by absolute path

* fix(producer): the machine id comes from the system's own tool at its fixed path

* test(producer): a system root on the current drive runs no machine-id tool

* fix(producer): the Windows system root must be a full drive path to run reg.exe
This commit is contained in:
Miguel Ángel
2026-11-22 23:44:08 +00:00
committed by GitHub
parent 513dcce820
commit 3ee763267c
3 changed files with 207 additions and 10 deletions
@@ -0,0 +1,124 @@
import { spawnSync } from "node:child_process";
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
vi.mock("node:os", async (load) => {
const os = await load<typeof import("node:os")>();
return { ...os, uptime: () => 5_000 };
});
// A Mac: no /proc, so the owner stamp's boot is an estimate and the machine is named by its platform UUID.
vi.mock("node:fs", async (load) => {
const fs = await load<typeof import("node:fs")>();
const noProc = (path: unknown) => {
if (String(path).startsWith("/proc/"))
throw Object.assign(new Error("no /proc"), { code: "ENOENT" });
};
return {
...fs,
readFileSync: ((path: string, ...rest: never[]) => {
noProc(path);
return fs.readFileSync(path, ...rest);
}) as typeof fs.readFileSync,
readlinkSync: ((path: string, ...rest: never[]) => {
noProc(path);
return fs.readlinkSync(path, ...rest);
}) as typeof fs.readlinkSync,
};
});
const tools = vi.hoisted(() => ({ ran: [] as string[] }));
vi.mock("node:child_process", async (load) => {
const cp = await load<typeof import("node:child_process")>();
const ioreg =
'+-o J316sAP <class IOPlatformExpertDevice>\n "IOPlatformUUID" = "11111111-2222-3333-4444-555555555555"\n';
return {
...cp,
execFileSync: ((file: string, ...rest: never[]) => {
tools.ran.push(file);
if (file === "/usr/sbin/ioreg") return ioreg;
if (/reg\.exe$/i.test(file)) return " MachineGuid REG_SZ aaaa-bbbb\r\n";
return cp.execFileSync(file, ...rest);
}) as typeof cp.execFileSync,
};
});
const { createOwnedRenderDir, listAbandonedRenderDirs } = await import("./renderDirOwner.js");
const platform = process.platform;
const MINUTE = 60_000;
// Boot estimate = now - uptime; uptime ticks in whole seconds, so the estimate moves with the clock.
const at = (bootMinutes: number) => vi.setSystemTime(bootMinutes * MINUTE + 5_000 * 1000);
let parent: string;
beforeEach(() => {
Object.defineProperty(process, "platform", { value: "darwin" });
vi.useFakeTimers({ toFake: ["Date"] });
parent = mkdtempSync(join(tmpdir(), "hf-render-owner-boot-"));
});
afterEach(() => {
Object.defineProperty(process, "platform", { value: platform });
vi.useRealTimers();
rmSync(parent, { recursive: true, force: true });
});
function deadRenderDir(stamp: Record<string, unknown> = {}): string {
const dir = createOwnedRenderDir(join(parent, "hf-render-"));
const owner = JSON.parse(readFileSync(join(dir, "owner.json"), "utf-8"));
const dead = spawnSync(process.execPath, ["-e", ""]).pid;
writeFileSync(join(dir, "owner.json"), JSON.stringify({ ...owner, pid: dead, ...stamp }));
return dir;
}
// fails without the fix: the minute estimate stamped 1000 and read 1001 back, so the dead render's dir stayed.
it("reclaims a dead render's dir when the boot estimate rounds the other way at the next look", () => {
at(1000.49998);
const dir = deadRenderDir();
at(1000.50002);
expect(listAbandonedRenderDirs(parent)).toEqual([dir]);
});
it("reclaims a dead render's dir across the uptime's whole-second tick", () => {
at(1000.2);
const dir = deadRenderDir();
vi.setSystemTime(Date.now() + 999);
expect(listAbandonedRenderDirs(parent)).toEqual([dir]);
});
// fails without the fix (the previous head): another Mac of the same name on a shared folder, booted a minute away,
// counted as this one, so its live render's dir was listed as abandoned.
it.each([
["a boot a minute apart", () => at(1001.2), {}],
[
"another machine with the same name and boot",
() => {},
{ machine: "99999999-8888-7777-6666-555555555555" },
],
["an older stamp that names no machine", () => {}, { machine: undefined, boot: "1000" }],
])("keeps a dead owner's dir from %s", (_, later, stamp) => {
at(1000.2);
deadRenderDir(stamp);
later();
expect(listAbandonedRenderDirs(parent)).toEqual([]);
});
// fails without the fix: the tools ran by bare name, which Windows can resolve from the project folder, and a
// root that is not a fully qualified drive path (current drive, UNC share, drive-relative) passed as a system one.
it.each([
["darwin", undefined, ["/usr/sbin/ioreg"]],
["win32", "C:\\Windows", ["C:\\Windows\\System32\\reg.exe"]],
["win32", "Windows", []],
["win32", "\\Windows", []],
["win32", "\\\\server\\share", []],
["win32", "C:Windows", []],
])("asks %s's own tool by its absolute path (system root %s)", async (os, systemRoot, expected) => {
Object.defineProperty(process, "platform", { value: os });
vi.stubEnv("SystemRoot", systemRoot);
tools.ran.length = 0;
vi.resetModules();
const fresh = await import("./renderDirOwner.js");
fresh.createOwnedRenderDir(join(parent, `hf-render-${os}-`));
vi.unstubAllEnvs();
expect(tools.ran).toEqual(expected);
});
@@ -38,6 +38,22 @@ vi.mock("node:fs", async (actual) => {
};
});
// A Mac names itself by its platform UUID.
vi.mock("node:child_process", async (actual) => {
const cp = await actual<typeof import("node:child_process")>();
const ioreg = ' "IOPlatformUUID" = "11111111-2222-3333-4444-555555555555"\n';
return {
...cp,
execFileSync: ((file: string, ...rest: unknown[]) =>
file === "/usr/sbin/ioreg"
? ioreg
: (cp.execFileSync as (...args: unknown[]) => unknown)(
file,
...rest,
)) as typeof cp.execFileSync,
};
});
const { createOwnedRenderDir, createRenderWorkDir } = await import("./renderDirOwner.js");
const JOB = "0f8c2b1e-5d3a-4c7b-9e21-6a4f0d8b3c19";
@@ -7,8 +7,9 @@ import {
rmSync,
writeFileSync,
} from "node:fs";
import { execFileSync } from "node:child_process";
import { hostname, uptime } from "node:os";
import { basename, dirname, join } from "node:path";
import { basename, dirname, join, win32 } from "node:path";
import { RENDER_TEMP_DIR } from "@hyperframes/core/project-folders";
import { createStagingDir } from "@hyperframes/core/atomic-file";
@@ -18,11 +19,49 @@ export const TRANSACTION_BACKUP = "backup";
/** A `--debug` render's work dir, named by its job id. */
export const RENDER_JOB_DIR = /^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;
let machineIdRead: { platform: string; id: string | undefined } | undefined;
/** This machine's own id where there is no /proc boot id, from the system's own tool at its fixed path. */
function machineId(): string | undefined {
const read = (file: string, args: string[], pattern: RegExp) => {
try {
const out = execFileSync(file, args, {
encoding: "utf-8",
timeout: 2_000,
windowsHide: true,
});
return pattern.exec(out)?.[1];
} catch {
return undefined;
}
};
if (machineIdRead?.platform === process.platform) return machineIdRead.id;
const systemRoot = process.env.SystemRoot;
machineIdRead = {
platform: process.platform,
id:
process.platform === "darwin"
? read(
"/usr/sbin/ioreg",
["-rd1", "-c", "IOPlatformExpertDevice"],
/"IOPlatformUUID" = "([^"]+)"/,
)
: process.platform === "win32" && systemRoot && /^[A-Za-z]:\\/.test(systemRoot)
? read(
win32.join(systemRoot, "System32", "reg.exe"),
["query", "HKLM\\SOFTWARE\\Microsoft\\Cryptography", "/v", "MachineGuid"],
/MachineGuid\s+REG_SZ\s+(\S+)/,
)
: undefined,
};
return machineIdRead.id;
}
/**
* Where a pid means this process: host and boot, plus the Linux pid namespace. Containers and machines on a shared
* folder can share a hostname, and every normal Linux host has the same root pid namespace id.
*/
function pidScope(): { host: string; boot?: string; pidns?: string } {
function pidScope(): { host: string; boot?: string; pidns?: string; machine?: string } {
const attempt = (read: () => string) => {
try {
return read();
@@ -30,13 +69,13 @@ function pidScope(): { host: string; boot?: string; pidns?: string } {
return undefined;
}
};
const bootId = attempt(() => readFileSync("/proc/sys/kernel/random/boot_id", "utf-8").trim());
return {
host: hostname(),
// Without /proc (macOS, Windows) the boot time, to the minute, stands in for the boot id.
boot:
attempt(() => readFileSync("/proc/sys/kernel/random/boot_id", "utf-8").trim()) ??
attempt(() => String(Math.round(Date.now() / 60_000 - uptime() / 60))),
// Without /proc (macOS, Windows) the boot time in seconds stands in for the boot id, on this machine's own id.
boot: bootId ?? attempt(() => `s:${Math.round(Date.now() / 1000 - uptime())}`),
pidns: attempt(() => readlinkSync("/proc/self/ns/pid")),
machine: bootId === undefined ? machineId() : undefined,
};
}
@@ -57,22 +96,40 @@ function alive(pid: number): boolean {
}
}
type OwnerRecord = { pid?: unknown; host?: unknown; boot?: unknown; pidns?: unknown };
type OwnerRecord = {
pid?: unknown;
host?: unknown;
boot?: unknown;
pidns?: unknown;
machine?: unknown;
};
function knownPidScope(): ReturnType<typeof pidScope> | undefined {
const scope = pidScope();
const unknown =
scope.boot === undefined || (process.platform === "linux" && scope.pidns === undefined);
scope.boot === undefined ||
(process.platform === "linux" && scope.pidns === undefined) ||
(scope.boot.startsWith("s:") && scope.machine === undefined);
return unknown ? undefined : scope;
}
/** A boot id matches exactly; a boot estimate in seconds moves with uptime's whole-second tick, so within 2 s. */
function sameBoot(stamped: unknown, current: string | undefined): boolean {
if (stamped === current) return true;
const seconds = (boot: unknown) =>
typeof boot === "string" ? /^s:(\d+)$/.exec(boot)?.[1] : undefined;
const [a, b] = [seconds(stamped), seconds(current)];
return a !== undefined && b !== undefined && Math.abs(Number(a) - Number(b)) <= 2;
}
function inThisPidScope(owner: OwnerRecord): boolean {
const scope = knownPidScope();
return (
scope !== undefined &&
owner.host === scope.host &&
owner.boot === scope.boot &&
owner.pidns === scope.pidns
sameBoot(owner.boot, scope.boot) &&
owner.pidns === scope.pidns &&
owner.machine === scope.machine
);
}