Cotton code
106 lines · 4.9 KB · TypeScriptRaw
/** * `scripts/ci/with-deadline.sh` — a hung test run is stopped, with its stacks * in the log, instead of holding the Mac's build lock for the whole lane. * 29 Sep 2026: an xctest waited 25 minutes on a deadlocked async test while * every swift and ios check queued behind it. */import { spawnSync } from "node:child_process";import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, beforeEach, describe, expect, it } from "vitest";const ROOT = join(__dirname, "..", "..");const SCRIPT = join(ROOT, "scripts/ci/with-deadline.sh");let scratch: string;let pidFile: string;const ownedPids = () => existsSync(pidFile)  ? readFileSync(pidFile, "utf8").trim().split(/\s+/).filter(Boolean).map(Number)  : [];beforeEach(() => {  scratch = mkdtempSync(join(tmpdir(), "deadline-tree-"));  pidFile = join(scratch, "pids");});afterEach(() => {  for (const pid of ownedPids()) {    try { process.kill(pid, "SIGKILL"); } catch { /* already reaped */ }  }  rmSync(scratch, { recursive: true, force: true });});// A `sample` that answers at once: the real one takes three seconds a process,// longer on a busy Mac, and what is under test is that the stacks reach the log.function quickSample(): string {  const bin = join(scratch, "bin");  mkdirSync(bin, { recursive: true });  writeFileSync(join(bin, "sample"), '#!/bin/bash\nprintf "Call graph:\\n    stack of pid %s\\nTotal number in stack\\n" "$1"\n', { mode: 0o755 });  return `${bin}:${process.env.PATH ?? ""}`;}function run(args: string[], seconds?: number) {  return spawnSync("bash", [SCRIPT, ...args], {    encoding: "utf8",    env: { ...process.env, PATH: quickSample(), PID_FILE: pidFile, ...(seconds === undefined ? {} : { WITH_DEADLINE_SECONDS: String(seconds) }) },    timeout: 30_000,  });}describe("with-deadline.sh", () => {  it("passes a command that finishes in time through, with its own exit status", () => {    expect(run(["5", "true"]).status).toBe(0);    expect(run(["5", "bash", "-c", "exit 3"]).status).toBe(3);  });  it("stops a command past the deadline — the whole tree — says so and exits 124", () => {    const started = Date.now();    const out = run(["1", "bash", "-c", "sleep 300 & sleep 300; wait"], 2);    expect(out.status).toBe(124);    expect(Date.now() - started).toBeLessThan(20_000);    expect(out.stderr).toContain("ran past 1 min");    expect(out.stderr).toMatch(/----- pid \d+: .*sleep 300/);    expect(out.stderr).toMatch(/Call graph:\n    stack of pid \d+/);  });  // RULE: Cancellation guards observe only the tree they started. Multiple  // lanes run this suite on one host; a global command-pattern search mistakes  // another run's sleepers for this run's leaked descendants.  const stopped = () => {    const pids = ownedPids();    expect(pids.length).toBeGreaterThan(0);    for (const pid of pids) {      // Read in-process (scripts/lib/mac_disk_policy.py), never through the setuid `ps` a lane's seatbelt refuses.      const read = spawnSync("python3", ["-I", "-c", `import sys; sys.path.insert(0, sys.argv[1])from mac_disk_policy import process_startseen = process_start(int(sys.argv[2]))print("gone" if seen is None else ("zombie" if seen[1] else "running"))`, join(ROOT, "scripts/lib"), String(pid)], { encoding: "utf8" });      expect(read.status, read.stderr).toBe(0);      const state = read.stdout.trim();      expect(state === "gone" || state === "zombie", `fixture pid ${pid} still runs: ${state}`).toBe(true);    }  };  const tree = (seconds: number) => `echo $$ >> "$PID_FILE"; sleep ${seconds} & echo $! >> "$PID_FILE"; sleep ${seconds} & echo $! >> "$PID_FILE"; wait`;  // RULE: A stop from outside — a lock's yield, a runner's cancel — ends the command's whole tree, which runs in a process group of its own, and exits 143.  it("passes a stop from outside to the whole tree it started", () => {    const out = spawnSync(      "bash",      ["-c", `bash "${SCRIPT}" 5 bash -c '${tree(3017)}' & p=$!; sleep 1; kill -TERM $p; wait $p; echo "status=$?"`],      { encoding: "utf8", timeout: 30_000, env: { ...process.env, PID_FILE: pidFile } },    );    expect(out.stdout).toContain("status=143");    stopped();  });  // RULE: An outer deadline stops an inner deadline's tree too — the Mac steps wrap a build that runs its own `with-deadline.sh 20 swift test`, and nothing may outlive the locks.  it("an outer deadline reaches the tree an inner one started", () => {    const inner = `env -u WITH_DEADLINE_SECONDS bash "${SCRIPT}" 5 bash -c '${tree(3019)}'`;    const out = run(["1", "bash", "-c", inner], 2);    expect(out.status).toBe(124);    stopped();  });  it("refuses a deadline that is not a whole number of minutes, or no command", () => {    expect(run(["ten", "true"]).status).toBe(2);    expect(run(["5"]).status).toBe(2);  });});