Skip to content

Commit ad67390

Browse files
authored
fix(ci): avoid false checkout cleanup failures on macOS (#132204)
Verify zombie-only process groups through the existing checked census while keeping live signal denials and uncertain cleanup fail-closed. Preserve the original cleanup budget and missing-group fast path.\n\nDrive fixture timeouts from tree readiness, observe active POSIX process state, and cover retained zombies plus live signal denial without a production test seam.\n\nRefs: https://github.com/openclaw/openclaw/issues/132184\nRefs: #132194
1 parent ea1a547 commit ad67390

4 files changed

Lines changed: 180 additions & 29 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1426,20 +1426,27 @@ jobs:
14261426
'''
14271427
14281428
1429-
def group_signal(pgid, signum):
1429+
def group_signal(pgid, signum, deadline):
14301430
try:
14311431
os.killpg(pgid, signum)
14321432
except ProcessLookupError:
14331433
pass
1434+
except PermissionError:
1435+
# Darwin can report EPERM for a zombie-only group. Only a checked
1436+
# census proving no live members can authorize continuing.
1437+
if group_alive(pgid, deadline):
1438+
raise
14341439
14351440
14361441
def group_alive(pgid, deadline):
14371442
try:
14381443
os.killpg(pgid, 0)
14391444
except ProcessLookupError:
14401445
return False
1441-
# Linux containers may not reap orphan zombies. They are terminated, not writers.
1442-
# A failed/ambiguous inspection never authorizes checkout reuse.
1446+
except PermissionError:
1447+
pass # EPERM can mean zombie-only; the census must still prove extinction.
1448+
# Zombies are terminated, not writers. A failed/ambiguous inspection
1449+
# never authorizes checkout reuse, including after a denied signal probe.
14431450
result = subprocess.run(
14441451
["ps", "-axo", "pgid=,stat="], stdin=subprocess.DEVNULL,
14451452
stdout=subprocess.PIPE, text=True, check=True,
@@ -1469,20 +1476,20 @@ jobs:
14691476
# The group remains ours after leader exit. Reserve half the existing
14701477
# cleanup allowance for KILL and extinction verification after TERM.
14711478
try:
1472-
group_signal(child.pid, signal.SIGTERM)
1479+
group_signal(child.pid, signal.SIGTERM, deadline)
14731480
kill_at = deadline - cleanup_seconds / 2
14741481
while True:
14751482
child.poll()
14761483
if not group_alive(child.pid, deadline):
14771484
child.wait(timeout=max(0.001, deadline - time.monotonic()))
14781485
return
14791486
if time.monotonic() >= kill_at:
1480-
group_signal(child.pid, signal.SIGKILL)
1487+
group_signal(child.pid, signal.SIGKILL, deadline)
14811488
if time.monotonic() >= deadline:
14821489
raise RuntimeError("Process group cleanup did not complete")
14831490
time.sleep(0.05)
14841491
except Exception:
1485-
group_signal(child.pid, signal.SIGKILL)
1492+
group_signal(child.pid, signal.SIGKILL, deadline)
14861493
child.wait(timeout=max(0.001, deadline - time.monotonic()))
14871494
raise
14881495

‎docs/ci.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ When the check fails, update the PR body instead of pushing another code commit.
157157

158158
The shared Linux Node checkout (`linux_node_checkout_step`) and shared Windows/macOS/iOS checkout (`platform_checkout_step`) use one process owner for every Git command within those anchors. Linux allows five whole-checkout attempts, clearing the workspace before each attempt, with 120-second candidate and trusted workflow-harness fetch deadlines and an increasing five-second backoff. Windows, macOS, and iOS retain 90-second fetch deadlines, three candidate fetch attempts on timeout only, five-second backoff, and one harness fetch attempt. Candidate and harness revisions remain separately pinned; Linux also fetches the optional ratchet base at depth one.
159159

160-
Timeout, cancellation, and leader exit drain the owned POSIX process group or Windows Job Object before workspace deletion, another Git command, or step completion. Cleanup has a ten-second allowance. If ownership inspection or cleanup fails, checkout exits with code 125 without retrying. The bootstrap uses the runner's Python standard library because repository helpers are unavailable before checkout. A fetch timeout alone does not explain why transport stalled.
160+
Timeout, cancellation, and leader exit drain the owned POSIX process group or Windows Job Object before workspace deletion, another Git command, or step completion. Cleanup has a ten-second allowance. POSIX zombie-only groups are terminated, not active writers; a denied signal is tolerated only when checked process inspection proves that no live group members remain. If ownership inspection or cleanup fails, checkout exits with code 125 without retrying. The bootstrap uses the runner's Python standard library because repository helpers are unavailable before checkout. A fetch timeout alone does not explain why transport stalled.
161161

162162
Separate bootstrap and checkout flows in preflight, security, skills-python, ClawHub, and Android still use GNU timeout and are outside these shared anchors' ownership guarantees.
163163

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

Lines changed: 124 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { fork } from "node:child_process";
1+
import { fork, spawnSync } from "node:child_process";
22
import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
33
import { tmpdir } from "node:os";
44
import path from "node:path";
@@ -22,6 +22,20 @@ type Report = {
2222

2323
const fixture = fileURLToPath(new URL("./fixtures/ci-platform-checkout.mjs", import.meta.url));
2424

25+
function readCheckoutRun(linux: boolean): string {
26+
const workflow = parse(readFileSync(".github/workflows/ci.yml", "utf8")) as {
27+
jobs: Record<string, { steps: { name?: string; run?: string }[] }>;
28+
};
29+
const run = workflow.jobs[linux ? "checks-fast-core" : "checks-windows"]?.steps.find(
30+
(step) => step.name === "Checkout",
31+
)?.run;
32+
expect(run).toBeTypeOf("string");
33+
if (!run) {
34+
throw new Error("Missing shared platform checkout shell");
35+
}
36+
return run;
37+
}
38+
2539
// Execute both workflow policies against the same owned tree fixture. A leader's
2640
// exit must not authorize workspace deletion, Git reuse, or final success.
2741
const platformCases = [
@@ -65,32 +79,45 @@ it.each([
6579
"preserves checkout ownership and fixture isolation (Linux=$linux, $scenario)",
6680
async ({ scenario, attempts, code, checkout, linux, deletions }) => {
6781
const setupFailure = scenario.startsWith("non-executable-");
68-
const workflow = parse(readFileSync(".github/workflows/ci.yml", "utf8")) as {
69-
jobs: Record<string, { steps: { name?: string; run?: string }[] }>;
70-
};
71-
const run = workflow.jobs[linux ? "checks-fast-core" : "checks-windows"]?.steps.find(
72-
(step) => step.name === "Checkout",
73-
)?.run;
74-
expect(run).toBeTypeOf("string");
75-
if (!run) {
76-
throw new Error("Missing shared platform checkout shell");
77-
}
82+
const run = readCheckoutRun(linux);
7883

7984
const root = realpathSync(mkdtempSync(path.join(tmpdir(), "ci platform checkout ")));
8085
const workspace = path.join(root, "workspace");
8186
mkdirSync(workspace);
8287
if (linux) {
8388
writeFileSync(path.join(workspace, ".previous-checkout"), "stale\n");
8489
}
85-
// Advance the test clock, not the real OS teardown budget: a subsecond
86-
// cleanup deadline races process scheduling instead of testing ownership.
90+
if (scenario === "recovery") {
91+
// Reproduce startup beyond the old wall-clock budget without delaying other consumers.
92+
writeFileSync(path.join(root, "tree-start-delay-3.json"), "2100");
93+
}
94+
for (const anchor of [
95+
"def run_git(",
96+
"deadline = time.monotonic() + timeout",
97+
"deadline is not None and time.monotonic() >= deadline",
98+
]) {
99+
expect(run, `Missing fetch clock source anchor: ${anchor}`).toContain(anchor);
100+
}
101+
// Only a ready, deliberately stalled tree advances the fetch clock. Real
102+
// process startup and teardown retain their independent wall-clock watchdogs.
87103
const accelerated = run
88104
.replace(/fetch_timeout_seconds = [^\n]+/u, "fetch_timeout_seconds = 2")
105+
.replace(
106+
"def run_git(",
107+
`def fetch_clock():
108+
return 2 * sum(name.startswith("fetch-tick-") and name.endswith(".json")
109+
for name in os.listdir(os.environ["TMPDIR"]))
110+
111+
112+
def run_git(`,
113+
)
114+
.replace("deadline = time.monotonic() + timeout", "deadline = fetch_clock() + timeout")
115+
.replace(
116+
"deadline is not None and time.monotonic() >= deadline",
117+
"deadline is not None and fetch_clock() >= deadline",
118+
)
89119
.replace("kill_at = deadline - cleanup_seconds / 2", "kill_at = time.monotonic()")
90-
.replace(/retry_at = time\.monotonic\(\) \+ [^\n]+/u, "retry_at = time.monotonic() + 0.05")
91-
// Keep the original GNU timeout path executable for the pre-fix regression.
92-
.replace("120s git", "2s git")
93-
.replace("sleep $((attempt * 5))", "sleep 0.05");
120+
.replace(/retry_at = time\.monotonic\(\) \+ [^\n]+/u, "retry_at = time.monotonic() + 0.05");
94121
expect(accelerated).not.toBe(run);
95122
// A broken preflight must never let these negative fixture tests run real Git.
96123
writeFileSync(
@@ -202,3 +229,83 @@ it.each([
202229
},
203230
55_000,
204231
);
232+
233+
it.skipIf(process.platform === "win32")(
234+
"recognizes terminated POSIX groups without accepting live signal denials",
235+
() => {
236+
const owner = expectDefined(
237+
readCheckoutRun(false).split("<<'PYTHON'\n")[1]?.split("\nPYTHON")[0],
238+
"checkout Python owner",
239+
);
240+
const result = spawnSync(
241+
"python3",
242+
[
243+
"-I",
244+
"-S",
245+
"-c",
246+
String.raw`
247+
import ast, errno, json, os, pathlib, signal, subprocess, sys, tempfile, time
248+
249+
# Load only the actual boundary functions; never execute checkout or real Git.
250+
functions = [node for node in ast.parse(sys.stdin.read()).body
251+
if isinstance(node, ast.FunctionDef) and node.name in ("group_alive", "group_signal")]
252+
assert len(functions) == 2
253+
exec(compile(ast.Module(body=functions, type_ignores=[]), "checkout-owner.py", "exec"))
254+
255+
# Retain the Popen handle without polling, so the owned zombie cannot be reaped or reused.
256+
with subprocess.Popen([sys.executable, "-I", "-S", "-c", "pass"], start_new_session=True) as child:
257+
deadline = time.monotonic() + 10
258+
while True:
259+
state = subprocess.run(["ps", "-o", "stat=", "-p", str(child.pid)],
260+
check=True, capture_output=True, text=True).stdout.strip()
261+
if state.startswith("Z"):
262+
break
263+
assert time.monotonic() < deadline, "owned child did not terminate"
264+
time.sleep(0.01)
265+
assert not group_alive(child.pid, deadline), "zombies are terminated, not checkout writers"
266+
group_signal(child.pid, signal.SIGTERM, deadline)
267+
group_signal(child.pid, signal.SIGKILL, deadline)
268+
with tempfile.TemporaryDirectory(prefix="checkout-zombie-") as directory:
269+
root = pathlib.Path(directory)
270+
(root / "workspace").mkdir()
271+
(root / "pids").mkdir()
272+
(root / "lease").write_text("owned")
273+
for pid, role, attempt in [(child.pid, "grandchild", 1), (os.getpid(), "sentinel", 0)]:
274+
(root / "pids" / f"{pid}.json").write_text(json.dumps(dict(pid=pid, role=role, attempt=attempt)))
275+
subprocess.run([sys.argv[1], sys.argv[2], "git", directory, "early-leader-exit",
276+
"-C", str(root / "workspace"), "checkout"], check=True)
277+
observed = json.loads((root / "events.jsonl").read_text())
278+
assert observed["alive"] == [], "fixture counted a terminated zombie as a live writer"
279+
assert observed["sentinelAlive"]
280+
281+
# A denied signal is safe to normalize only if the same census proves extinction.
282+
with subprocess.Popen([sys.executable, "-I", "-S", "-c",
283+
"import sys; print('ready', flush=True); sys.stdin.read()"],
284+
start_new_session=True, stdin=subprocess.PIPE,
285+
stdout=subprocess.PIPE, text=True) as child:
286+
assert child.stdout.readline().strip() == "ready"
287+
actual_killpg = os.killpg
288+
def denied(pgid, signum):
289+
assert pgid == child.pid and signum in (0, signal.SIGTERM)
290+
raise PermissionError(errno.EPERM, "test-owned signal denial")
291+
os.killpg = denied
292+
try:
293+
try:
294+
group_signal(child.pid, signal.SIGTERM, time.monotonic() + 10)
295+
except PermissionError:
296+
pass
297+
else:
298+
raise AssertionError("live denied group was accepted as terminated")
299+
finally:
300+
os.killpg = actual_killpg
301+
print("group contract passed")
302+
`,
303+
process.execPath,
304+
fixture,
305+
],
306+
{ input: owner, encoding: "utf8", timeout: 15_000, killSignal: "SIGKILL" },
307+
);
308+
expect(result.status, result.stderr).toBe(0);
309+
expect(result.stdout).toContain("group contract passed");
310+
},
311+
);

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

Lines changed: 42 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,14 +33,40 @@ function records() {
3333
.map((file) => JSON.parse(fs.readFileSync(path.join(recordsDir, file), "utf8")));
3434
}
3535

36-
function boundary(name) {
36+
function liveRecords() {
3737
const owned = records();
38+
if (process.platform === "win32") {
39+
return owned.filter((entry) => isPidAlive(entry.pid));
40+
}
41+
// PID existence includes macOS zombies; observe active writers in one POSIX snapshot.
42+
const result = spawnSync("/bin/ps", ["-axo", "pid=,stat="], {
43+
encoding: "utf8",
44+
timeout: 1_000,
45+
});
46+
if (result.error || result.status !== 0) {
47+
throw new Error(`Fixture process census failed (${result.error?.code ?? result.status})`);
48+
}
49+
const alive = new Set();
50+
for (const line of result.stdout.trim().split("\n")) {
51+
const [pid, state] = line.trim().split(/\s+/u);
52+
if (!Number.isInteger(Number(pid)) || !state) {
53+
throw new Error("Fixture process census returned an invalid row");
54+
}
55+
if (!state.startsWith("Z")) {
56+
alive.add(Number(pid));
57+
}
58+
}
59+
return owned.filter((entry) => alive.has(entry.pid));
60+
}
61+
62+
function boundary(name) {
63+
const alive = liveRecords();
3864
fs.appendFileSync(
3965
eventsFile,
4066
`${JSON.stringify({
4167
name,
42-
alive: owned.filter((entry) => entry.attempt > 0 && isPidAlive(entry.pid)),
43-
sentinelAlive: owned.some((entry) => entry.role === "sentinel" && isPidAlive(entry.pid)),
68+
alive: alive.filter((entry) => entry.attempt > 0),
69+
sentinelAlive: alive.some((entry) => entry.role === "sentinel"),
4470
})}\n`,
4571
);
4672
}
@@ -105,6 +131,11 @@ async function command() {
105131
process.on("SIGTERM", () => {});
106132
record(process.pid, mode, attempt);
107133
if (mode === "child") {
134+
// Startup faults belong to the caller, not every consumer of this shared fixture.
135+
const startDelay = path.join(root, `tree-start-delay-${attempt}.json`);
136+
if (fs.existsSync(startDelay)) {
137+
await delay(JSON.parse(fs.readFileSync(startDelay, "utf8")));
138+
}
108139
launch("grandchild", attempt);
109140
} else {
110141
publish(`ready-${attempt}.json`, attempt);
@@ -162,6 +193,12 @@ async function command() {
162193
if (scenario === "git-exit-124") {
163194
process.exit(124);
164195
}
196+
// Expire the two-second fetch budget only after the full tree is ready.
197+
// Immutable ticks avoid replacing a clock file held open by Windows readers.
198+
// Cancellation scenarios instead wait for the supervisor's actual signal.
199+
if (!scenario.startsWith("cancel-")) {
200+
publish(`fetch-tick-${attempt}.json`, attempt);
201+
}
165202
return;
166203
} else if (operation === "checkout") {
167204
boundary(cwd === workspace ? "checkout" : "harness-checkout");
@@ -255,11 +292,11 @@ async function supervise() {
255292
}
256293
}
257294
try {
258-
await until(() => records().every((entry) => !isPidAlive(entry.pid)), "fixture cleanup");
295+
await until(() => liveRecords().length === 0, "fixture cleanup");
259296
} catch (err) {
260297
report.error ??= String(err);
261298
}
262-
report.cleanupRemaining = records().filter((entry) => isPidAlive(entry.pid));
299+
report.cleanupRemaining = liveRecords();
263300
report.ownedProcesses = records();
264301
report.boundaries = fs
265302
.readFileSync(eventsFile, "utf8")

0 commit comments

Comments
 (0)