Skip to content

Commit 0d7e1c9

Browse files
committed
test(ci): retain observed checkout process lifetimes
1 parent 894b8e9 commit 0d7e1c9

2 files changed

Lines changed: 92 additions & 22 deletions

File tree

‎test/scripts/ci-platform-checkout.test.ts‎

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,52 @@ def run_git(`,
252252
55_000,
253253
);
254254

255+
it("does not revive an observed-dead fixture instance when its PID is reused", () => {
256+
const result = spawnSync(
257+
process.platform === "win32" ? "python" : "python3",
258+
[
259+
"-I",
260+
"-S",
261+
"-c",
262+
String.raw`
263+
import json, os, pathlib, subprocess, sys, tempfile
264+
265+
with tempfile.TemporaryDirectory(prefix="checkout-pid-reuse-") as directory:
266+
root = pathlib.Path(directory).resolve()
267+
workspace = root / "workspace"
268+
workspace.mkdir()
269+
records = root / "pids"
270+
records.mkdir()
271+
(root / "lease").write_text("owned")
272+
with subprocess.Popen([sys.executable, "-I", "-S", "-c", "pass"]) as child:
273+
child.wait(timeout=10)
274+
retired = dict(pid=child.pid, role="grandchild", attempt=1, instance="retired")
275+
current = dict(pid=os.getpid(), role="grandchild", attempt=2, instance="current")
276+
(records / "retired.json").write_text(json.dumps(retired))
277+
(records / "current.json").write_text(json.dumps(current))
278+
279+
def observe():
280+
subprocess.run([sys.argv[1], sys.argv[2], "git", str(root), "early-leader-exit",
281+
"-C", str(workspace), "checkout"], cwd=workspace, check=True)
282+
return json.loads((root / "events.jsonl").read_text().splitlines()[-1])["alive"]
283+
284+
assert observe() == [current], "first boundary must observe real child termination"
285+
# Fault-inject PID reuse only after actual death was observed. The fresh
286+
# instance at that live PID must remain visible, never hidden by retirement.
287+
retired["pid"] = current["pid"]
288+
(records / "retired.json").write_text(json.dumps(retired))
289+
assert observe() == [current], "a retired instance was revived by a reused PID"
290+
print("fixture lifetime contract passed")
291+
`,
292+
process.execPath,
293+
fixture,
294+
],
295+
{ encoding: "utf8", timeout: 15_000, killSignal: "SIGKILL" },
296+
);
297+
expect(result.status, result.stderr).toBe(0);
298+
expect(result.stdout).toContain("fixture lifetime contract passed");
299+
});
300+
255301
it.skipIf(process.platform === "win32")(
256302
"recognizes terminated POSIX groups without accepting live signal denials",
257303
() => {
@@ -293,7 +339,7 @@ with subprocess.Popen([sys.executable, "-I", "-S", "-c", "pass"], start_new_sess
293339
(root / "pids").mkdir()
294340
(root / "lease").write_text("owned")
295341
for pid, role, attempt in [(child.pid, "grandchild", 1), (os.getpid(), "sentinel", 0)]:
296-
(root / "pids" / f"{pid}.json").write_text(json.dumps(dict(pid=pid, role=role, attempt=attempt)))
342+
(root / "pids" / f"{pid}.json").write_text(json.dumps(dict(pid=pid, role=role, attempt=attempt, instance=str(pid))))
297343
subprocess.run([sys.argv[1], sys.argv[2], "git", directory, "early-leader-exit",
298344
"-C", str(root / "workspace"), "checkout"], cwd=root / "workspace", check=True)
299345
observed = json.loads((root / "events.jsonl").read_text())

‎test/scripts/fixtures/ci-platform-checkout.mjs‎

Lines changed: 45 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,17 @@
11
import { spawn, spawnSync } from "node:child_process";
2+
import { randomUUID } from "node:crypto";
23
import { once } from "node:events";
34
import fs from "node:fs";
45
import path from "node:path";
56
import { setTimeout as delay } from "node:timers/promises";
67
import { fileURLToPath } from "node:url";
7-
import { getProcessStartTime, isPidAlive } from "../../../src/shared/pid-alive.ts";
8+
import { getProcessStartTime } from "../../../src/shared/pid-alive.ts";
89

910
const [mode, root, policyScenario, ...args] = process.argv.slice(2);
1011
const linux = policyScenario.startsWith("linux:");
1112
const scenario = linux ? policyScenario.slice("linux:".length) : policyScenario;
1213
const fixture = fileURLToPath(import.meta.url);
14+
const instance = randomUUID();
1315
const workspace = path.join(root, "workspace");
1416
const lease = path.join(root, "lease");
1517
const recordsDir = path.join(root, "pids");
@@ -41,7 +43,7 @@ function publish(name, value) {
4143
}
4244

4345
function record(pid, role, attempt = 0) {
44-
publish(`pids/${pid}.json`, { pid, role, attempt });
46+
publish(`pids/${pid}.json`, { pid, role, attempt, instance: `${instance}-${pid}` });
4547
}
4648

4749
function records() {
@@ -54,29 +56,51 @@ function records() {
5456
}
5557

5658
function liveRecords() {
57-
const owned = records();
58-
if (process.platform === "win32") {
59-
return owned.filter((entry) => isPidAlive(entry.pid));
60-
}
61-
// PID existence includes macOS zombies; observe active writers in one POSIX snapshot.
62-
const result = spawnSync("/bin/ps", ["-axo", "pid=,stat="], {
63-
encoding: "utf8",
64-
timeout: 1_000,
65-
});
66-
if (result.error || result.status !== 0) {
67-
throw new Error(`Fixture process census failed (${result.error?.code ?? result.status})`);
68-
}
59+
const owned = records().filter(
60+
(entry) => !fs.existsSync(path.join(recordsDir, `${entry.instance}.dead`)),
61+
);
6962
const alive = new Set();
70-
for (const line of result.stdout.trim().split("\n")) {
71-
const [pid, state] = line.trim().split(/\s+/u);
72-
if (!Number.isInteger(Number(pid)) || !state) {
73-
throw new Error("Fixture process census returned an invalid row");
63+
if (process.platform === "win32") {
64+
for (const { pid } of owned) {
65+
try {
66+
process.kill(pid, 0);
67+
alive.add(pid);
68+
} catch (error) {
69+
if (error.code === "EPERM") {
70+
alive.add(pid);
71+
} else if (error.code !== "ESRCH") {
72+
throw error;
73+
}
74+
}
75+
}
76+
} else {
77+
// PID existence includes macOS zombies; observe active writers in one POSIX snapshot.
78+
const result = spawnSync("/bin/ps", ["-axo", "pid=,stat="], {
79+
encoding: "utf8",
80+
timeout: 1_000,
81+
});
82+
if (result.error || result.status !== 0) {
83+
throw new Error(`Fixture process census failed (${result.error?.code ?? result.status})`);
7484
}
75-
if (!state.startsWith("Z")) {
76-
alive.add(Number(pid));
85+
for (const line of result.stdout.trim().split("\n")) {
86+
const [pid, state] = line.trim().split(/\s+/u);
87+
if (!Number.isInteger(Number(pid)) || !state) {
88+
throw new Error("Fixture process census returned an invalid row");
89+
}
90+
if (!state.startsWith("Z")) {
91+
alive.add(Number(pid));
92+
}
7793
}
7894
}
79-
return owned.filter((entry) => alive.has(entry.pid));
95+
return owned.filter((entry) => {
96+
if (alive.has(entry.pid)) {
97+
return true;
98+
}
99+
// Separate command processes share this observed-dead fact. PID reuse cannot
100+
// revive that instance, while a newly registered instance is still checked.
101+
fs.writeFileSync(path.join(recordsDir, `${entry.instance}.dead`), "");
102+
return false;
103+
});
80104
}
81105

82106
function boundary(name) {

0 commit comments

Comments
 (0)