Cotton code
434 lines · 17.1 KB · TypeScriptRaw
// The machine-wide build mutex keeps a WAIT LOG, and this is its format guard.//// The lock's rule is "waiting is correct", and it is right, but for its whole// life the lock measured nothing: the only trace a wait left was the word// "waiting" on somebody's stderr, gone with the shell. So nobody could answer// what queueing on this Mac actually costs, nor tell a healthy queue from the// two-hour self-deadlock `build-lock-reentrant.test.ts` exists for — the two// look identical from outside, and the difference is exactly "who was it// waiting behind".//// One TAB-separated line per ACQUIRE answers both:////   <iso8601-Z>\t<label>\t<seconds waited>\t<label it waited on, or ->//// These tests hold the format, because the format is the contract: `sort` and// `awk` are the entire reporting layer, so a field that moves or a label with// a space in it breaks every reader at once. They also hold the two silences// that matter — a re-entrant call writes NOTHING (it takes no lock, so it// waited on nobody, and a line for it would only dilute the file), and a log// that cannot be written never fails the build but is never swallowed either.import { execFileSync, spawn, spawnSync, type ChildProcess } from "node:child_process";import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { dirname, join, resolve } from "node:path";import { fileURLToPath } from "node:url";import { afterAll, beforeAll, describe, expect, it } from "vitest";import { publishBuildPeaks, publishDiskReading } from "./helpers/disk-reading";const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../..");const LOCK_SCRIPT = join(REPO_ROOT, "scripts", "with-build-lock.sh");type Fixture = { lock: string; log: string; home: string };/** A lock path and a log path of this test's own — never the machine's. */function fixture(): Fixture {  const home = mkdtempSync(join(tmpdir(), "build-lock-log-"));  return { lock: join(home, "lock"), log: join(home, "build-lock.log"), home };}/** * A `date` on PATH whose seconds LEAP forward on every reading — seven per read, * from a fixed epoch. * * The lock reads the clock by forking `date`, so anything that times an acquire * by reading it before and after really times the forks. On an idle Mac those * two forks land in the same second and the number is 0; on a CI runner with * sixteen jobs on it they straddle one, and the log claims a wait nobody did — * which is how this file's first test failed on run #2880 with "expected 1 to be * +0". A clock that jumps turns that into something a test can decide, instead * of a machine being slow enough on the day. * * Only `+%s` is faked; every other format is the real `date`, so the stamp in * the log stays a stamp. */function leapingClock(home: string): string {  const shims = join(home, "shims");  mkdirSync(shims, { recursive: true });  const shim = join(shims, "date");  writeFileSync(    shim,    [      "#!/bin/bash",      'here="$(dirname "$0")"',      'if [ "${1:-}" = "+%s" ]; then',      '  ticks=$(( $(cat "$here/ticks" 2>/dev/null || echo 0) + 1 ))',      '  printf "%s\\n" "$ticks" >"$here/ticks"',      '  printf "%s\\n" "$(( 1700000000 + ticks * 7 ))"',      "  exit 0",      "fi",      'exec /bin/date "$@"',      "",    ].join("\n"),  );  chmodSync(shim, 0o755);  return shims;}type Run = { status: number; stdout: string; stderr: string };function runLock(args: string[], env: Record<string, string>): Run {  // A scratch HOME with a fresh device reading beside the lock: on a Mac the  // wrapper admits through the device policy, which reads it there — never the person's HOME.  const home = join(dirname(env.BUILD_LOCK_DIR), "home");  publishDiskReading(home);  // A byte of RAM per build: admission must not turn on the machine's free RAM.  publishBuildPeaks(home);  const done = spawnSync("/bin/bash", [LOCK_SCRIPT, ...args], {    cwd: REPO_ROOT,    encoding: "utf8",    env: { ...process.env, HOME: home, BUILD_LOCK_MEMORY_BYTES: "17179869184", ...env },  });  return { status: done.status ?? -1, stdout: done.stdout ?? "", stderr: done.stderr ?? "" };}type Line = { when: string; label: string; waited: number; on: string };/** The log, parsed the way a reader would: split on tabs, nothing clever. */function lines(log: string): Line[] {  return readFileSync(log, "utf8")    .split("\n")    .filter((line) => line.length > 0)    .map((line) => {      const fields = line.split("\t");      expect(fields, `a line with ${fields.length} fields: ${JSON.stringify(line)}`).toHaveLength(4);      const waited = Number(fields[2]);      expect(Number.isInteger(waited), `seconds waited is not a whole number: ${fields[2]}`).toBe(        true,      );      return { when: fields[0], label: fields[1], waited, on: fields[3] };    });}describe("with-build-lock.sh's wait log", () => {  it("writes one line per acquire, in four tab-separated fields", () => {    const { lock, log } = fixture();    const run = runLock(["true"], {      BUILD_LOCK_DIR: lock,      BUILD_LOCK_LABEL: "ci-swift-mac",      BUILD_LOCK_LOG: log,    });    expect(run.status, run.stderr).toBe(0);    const [entry, ...rest] = lines(log);    expect(rest, "one acquire, one line").toHaveLength(0);    // A stamp `sort` orders correctly and a human can read: UTC, to the second.    expect(entry.when).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/);    expect(entry.label).toBe("ci-swift-mac");    expect(entry.waited, "nothing held the lock").toBe(0);    expect(entry.on, "a hyphen, not an empty field — the line keeps its shape").toBe("-");  });  it("logs no wait at all when it never queued, however slow the machine is", () => {    const { lock, log, home } = fixture();    // Seven seconds pass between any two readings of the clock here, and the    // lock is free the whole time. The seconds field counts QUEUEING, so the    // only honest answer is 0: a call that took the lock on its first `mkdir`    // waited for nobody, and must not be able to report otherwise because the    // machine was busy between two forks.    const run = runLock(["true"], {      BUILD_LOCK_DIR: lock,      BUILD_LOCK_LABEL: "ci-checks",      BUILD_LOCK_LOG: log,      PATH: `${leapingClock(home)}:${process.env.PATH ?? ""}`,    });    expect(run.status, run.stderr).toBe(0);    const [entry] = lines(log);    expect(entry.label).toBe("ci-checks");    expect(entry.waited, "a wait invented out of the clock, not out of a queue").toBe(0);    expect(entry.on).toBe("-");  });  it("creates the log's folder rather than needing one", () => {    const { lock, home } = fixture();    const log = join(home, "not", "yet", "build-lock.log");    const run = runLock(["true"], {      BUILD_LOCK_DIR: lock,      BUILD_LOCK_LABEL: "first-ever-build",      BUILD_LOCK_LOG: log,    });    expect(run.status, run.stderr).toBe(0);    expect(lines(log)[0].label).toBe("first-ever-build");  });  it("appends, never truncates", () => {    const { lock, log } = fixture();    for (const label of ["one", "two", "three"]) {      const run = runLock(["true"], {        BUILD_LOCK_DIR: lock,        BUILD_LOCK_LABEL: label,        BUILD_LOCK_LOG: log,      });      expect(run.status, run.stderr).toBe(0);    }    expect(lines(log).map((entry) => entry.label)).toEqual(["one", "two", "three"]);  });  it("names the label it queued behind, and counts the seconds it spent there", () => {    const { lock, log } = fixture();    // A DEAD holder: the wait loop reads the label off the lock it found, sees    // the pid is gone and reclaims at once — the one way to exercise the    // contended path without paying the 30-second poll. The seconds are    // whatever they were; the LABEL is the field this test exists for, because    // "behind whom" is the question the log was added to answer.    execFileSync("/bin/mkdir", ["-p", lock]);    // A pid no process can have (`kill -0` fails), so the reclaim is immediate.    writeFileSync(join(lock, "pid"), "2147483647\n");    writeFileSync(join(lock, "label"), "ci-ios\n");    const run = runLock(["true"], {      BUILD_LOCK_DIR: lock,      BUILD_LOCK_LABEL: "ci-swift-mac",      BUILD_LOCK_LOG: log,    });    expect(run.status, run.stderr).toBe(0);    const [entry] = lines(log);    expect(entry.label).toBe("ci-swift-mac");    expect(entry.on).toBe("ci-ios");    expect(entry.waited).toBeGreaterThanOrEqual(0);  }, 30_000);  it("does count the seconds when it really did queue", () => {    const { lock, log, home } = fixture();    // The same leaping clock, against a call that DOES find the lock taken (a    // dead holder, reclaimed on the first pass). The zero above is the absence    // of a queue, not a field that always answers zero: here the clock moved    // while this call was in the wait loop, and the log says so.    execFileSync("/bin/mkdir", ["-p", lock]);    writeFileSync(join(lock, "pid"), "2147483647\n");    writeFileSync(join(lock, "label"), "ci-ios\n");    const run = runLock(["true"], {      BUILD_LOCK_DIR: lock,      BUILD_LOCK_LABEL: "ci-checks",      BUILD_LOCK_LOG: log,      PATH: `${leapingClock(home)}:${process.env.PATH ?? ""}`,    });    expect(run.status, run.stderr).toBe(0);    const [entry] = lines(log);    expect(entry.on).toBe("ci-ios");    expect(entry.waited, "a real wait reported as none").toBeGreaterThan(0);  }, 30_000);  it("keeps a label with a space in it inside one field", () => {    const { lock, log } = fixture();    const run = runLock(["true"], {      BUILD_LOCK_DIR: lock,      BUILD_LOCK_LABEL: "a session's own build",      BUILD_LOCK_LOG: log,    });    expect(run.status, run.stderr).toBe(0);    // `lines` asserts the field count, so reaching here is the guarantee; the    // label is readable rather than mangled beyond recognition.    expect(lines(log)[0].label).toBe("a-session's-own-build");  });  it("writes nothing for a re-entrant call — it took no lock and waited on nobody", () => {    const { lock, log } = fixture();    const run = runLock(      ["bash", "-c", `BUILD_LOCK_LABEL=inner /bin/bash "${LOCK_SCRIPT}" true`],      { BUILD_LOCK_DIR: lock, BUILD_LOCK_LABEL: "outer", BUILD_LOCK_LOG: log },    );    expect(run.status, run.stderr).toBe(0);    expect(run.stderr).toContain("re-entered under 'outer'");    expect(lines(log).map((entry) => entry.label), "the nested call left a line").toEqual(["outer"]);  }, 30_000);  it("says so on stderr, and still runs the build, when the log cannot be written", () => {    const { lock, home } = fixture();    // A FILE where the log's folder would be: `mkdir -p` cannot make a folder    // out of it, which is the same failure a read-only home gives.    const blocker = join(home, "blocked");    writeFileSync(blocker, "not a folder\n");    const log = join(blocker, "build-lock.log");    const run = runLock(["echo", "THE-BUILD-RAN"], {      BUILD_LOCK_DIR: lock,      BUILD_LOCK_LABEL: "ci-swift-mac",      BUILD_LOCK_LOG: log,    });    expect(run.status, "a log is a record of builds, not a precondition for one").toBe(0);    expect(run.stdout).toContain("THE-BUILD-RAN");    expect(run.stderr).toContain(`could not append to ${log}`);    // The line it could not write is on stderr instead of nowhere.    expect(run.stderr).toContain("unrecorded:");    expect(existsSync(log)).toBe(false);  });});describe("a wait that is really waiting", () => {  /** A live process that is nobody's ancestor: a holder the lock must honour. */  let sibling: ChildProcess;  beforeAll(() => {    sibling = spawn("/bin/sleep", ["120"], { stdio: "ignore" });  });  afterAll(() => {    sibling.kill("SIGKILL");  });  it("writes no line when it gave up without the lock", () => {    const { lock, log } = fixture();    execFileSync("/bin/mkdir", ["-p", lock]);    writeFileSync(join(lock, "pid"), `${sibling.pid}\n`);    writeFileSync(join(lock, "label"), "somebody-else\n");    // A zero-minute budget: the wait ends at once with EX_TEMPFAIL. The log is    // a record of ACQUIRES — a run that never held the lock and never built    // must not appear as one that did.    const run = runLock(["echo", "THE-BUILD-RAN"], {      BUILD_LOCK_DIR: lock,      BUILD_LOCK_LABEL: "ci-swift-mac",      BUILD_LOCK_LOG: log,      BUILD_LOCK_TIMEOUT_MIN: "0",    });    expect(run.status).toBe(75);    expect(run.stdout).not.toContain("THE-BUILD-RAN");    expect(existsSync(log), "a timeout wrote a line").toBe(false);  }, 30_000);});describe("a cross-user or unreclaimable holder", () => {  function shim(home: string, name: string, body: string): string {    const shims = join(home, "shims");    mkdirSync(shims, { recursive: true });    const path = join(shims, name);    writeFileSync(path, `#!/bin/bash\n${body}\n`);    chmodSync(path, 0o755);    return shims;  }  function bashEnvWithoutKillBuiltin(home: string): string {    const path = join(home, "disable-kill-builtin.sh");    writeFileSync(path, "enable -n kill\n");    return path;  }  it("honours a live process when the shell kill command fails", () => {    const { lock, log, home } = fixture();    const pid = String(process.pid);    execFileSync("/bin/mkdir", ["-p", lock]);    writeFileSync(join(lock, "pid"), `${pid}\n`);    writeFileSync(join(lock, "label"), "live-ci-runner\n");    const shims = shim(home, "kill", "exit 1");    const run = runLock(["echo", "THE-BUILD-RAN"], {      BUILD_LOCK_DIR: lock,      BUILD_LOCK_LABEL: "local-gradle",      BUILD_LOCK_LOG: log,      BUILD_LOCK_TIMEOUT_MIN: "0",      BASH_ENV: bashEnvWithoutKillBuiltin(home),      PATH: `${shims}:${process.env.PATH ?? ""}`,    });    expect(run.status).toBe(75);    expect(run.stdout).not.toContain("THE-BUILD-RAN");    expect(run.stderr).not.toContain("is dead — reclaiming lock");    expect(readFileSync(join(lock, "pid"), "utf8").trim()).toBe(pid);  }, 30_000);  it("does not spin or bypass timeout when a dead holder's directory cannot be reclaimed", () => {    const { lock, log, home } = fixture();    execFileSync("/bin/mkdir", ["-p", lock]);    writeFileSync(join(lock, "pid"), "2147483647\n");    writeFileSync(join(lock, "label"), "unreclaimable\n");    const attempts = join(home, "rm-attempts");    const shims = shim(      home,      "rm",      `case "$*" in "-rf ${lock}") printf 'attempt\\n' >> '${attempts}'; exit 1 ;; esac\nexec /bin/rm "$@"`,    );    const run = runLock(["echo", "THE-BUILD-RAN"], {      BUILD_LOCK_DIR: lock,      BUILD_LOCK_LABEL: "local-gradle",      BUILD_LOCK_LOG: log,      BUILD_LOCK_TIMEOUT_MIN: "0",      // PINNED LOCAL. Under CI=true the caller ranks as a check job, files a      // claim while it waits, and removes it on exit — a second, legitimate      // `rm` this shim would count as a reclaim retry (build-lock-ci-first).      BUILD_LOCK_CLASS: "local",      PATH: `${shims}:${process.env.PATH ?? ""}`,    });    expect(run.status).toBe(75);    expect(run.stdout).not.toContain("THE-BUILD-RAN");    expect(run.stderr).toContain("could not reclaim");    expect(readFileSync(attempts, "utf8").trim().split("\n")).toEqual([      "attempt",    ]);    expect(existsSync(lock)).toBe(true);  }, 30_000);  it("uses GNU stat for an ownerless stale lock instead of treating it as newly created", () => {    const { lock, log, home } = fixture();    execFileSync("/bin/mkdir", ["-p", lock]);    const shims = shim(      home,      "stat",      'if [ "${1:-}" = "-c" ]; then printf "0\\n"; exit 0; fi\nexit 1',    );    const run = runLock(["echo", "THE-BUILD-RAN"], {      BUILD_LOCK_DIR: lock,      BUILD_LOCK_LABEL: "stale-reclaimer",      BUILD_LOCK_LOG: log,      BUILD_LOCK_STALE_MIN: "1",      BUILD_LOCK_TIMEOUT_MIN: "0",      PATH: `${shims}:${process.env.PATH ?? ""}`,    });    expect(run.status, run.stderr).toBe(0);    expect(run.stdout).toContain("THE-BUILD-RAN");    expect(existsSync(lock)).toBe(false);  }, 30_000);  it("falls back to BSD stat when GNU stat is unavailable", () => {    const { lock, log, home } = fixture();    execFileSync("/bin/mkdir", ["-p", lock]);    const shims = shim(      home,      "stat",      'if [ "${1:-}" = "-f" ] && [ "${2:-}" = "%m" ]; then printf "0\n"; exit 0; fi\nexit 1',    );    const run = runLock(["echo", "THE-BUILD-RAN"], {      BUILD_LOCK_DIR: lock,      BUILD_LOCK_LABEL: "bsd-stale-reclaimer",      BUILD_LOCK_LOG: log,      BUILD_LOCK_STALE_MIN: "1",      BUILD_LOCK_TIMEOUT_MIN: "0",      PATH: `${shims}:${process.env.PATH ?? ""}`,    });    expect(run.status, run.stderr).toBe(0);    expect(run.stdout).toContain("THE-BUILD-RAN");    expect(existsSync(lock)).toBe(false);  }, 30_000);});// RULE: The build lock records the actual Cargo target, including an explicit target on detached worktrees, so cleanup cannot evict a build in flight.it("records the caller's Cargo target rather than guessing its branch", () => {  const { lock, log, home } = fixture();  const target = join(home, "actual-target");  mkdirSync(target);  const result = runLock(["bash", "-c", 'cat "$BUILD_LOCK_DIR/target"'], { BUILD_LOCK_DIR: lock, BUILD_LOCK_LOG: log, CARGO_TARGET_DIR: target });  expect(result.status, result.stderr).toBe(0);  expect(result.stdout.trim()).toBe("actual-target");});