Cotton code
168 lines · 7.2 KB · TypeScriptRaw
/** * ON A MAC A CARGO STEP ALSO TAKES THE MACHINE'S BUILD MUTEX. ON LINUX IT MUST * NOT. * * `with-cargo-lock.sh` keeps two cargos off one target directory, which is the * whole of what a dedicated Linux CI host needs — PR #938 went to some trouble * to make four Cotton jobs really run there at once, and a machine-wide mutex * would undo it in one line. * * A Mac is the other case: it runs a desktop, Xcode, agent sessions and this * workflow's `swift` and `ios` jobs, all of which queue behind * /tmp/tinmen-build.lock. So `rust` on a Mac queues there too, through this * wrapper. * * WHY THE WRAPPER IS A SEPARATE SCRIPT, and this file is where that is * recorded: the first attempt put the branch inside `with-cargo-lock.sh`, which * the script tests call — and `pnpm test:scripts` then blocked on the REAL * machine lock while another worktree was building. A CI wrapper belongs where * CI calls it. Nothing here touches the real lock: `with-build-lock.sh` is * stubbed on the throwaway root, and the machine is stubbed too so both halves * are decidable on either OS. */import { execFileSync, spawnSync } from "node:child_process";import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { afterAll, describe, expect, it } from "vitest";const ROOT = join(__dirname, "..", "..");const SCRIPT = join(ROOT, "scripts", "ci", "with-machine-lock.sh");const CALLER_CLASS = join(ROOT, "scripts", "lib", "caller-class.sh");const temps: string[] = [];afterAll(() => {  for (const dir of temps.splice(0)) rmSync(dir, { recursive: true, force: true });});function run(os: string, command: string[], label?: string, extra: NodeJS.ProcessEnv = {}) {  const dir = mkdtempSync(join(tmpdir(), "machine-lock-"));  temps.push(dir);  const scripts = join(dir, "scripts", "ci");  mkdirSync(scripts, { recursive: true });  // The script finds its sibling from its OWN location, so the copy has to sit  // where the real one does.  const copy = join(scripts, "with-machine-lock.sh");  writeFileSync(copy, readFileSync(SCRIPT));  // The caller's rank is read from the one helper both wrappers share.  mkdirSync(join(dir, "scripts", "lib"), { recursive: true });  if (!extra.COTTON_TEST_DROP_CALLER_CLASS) {    writeFileSync(join(dir, "scripts", "lib", "caller-class.sh"), readFileSync(CALLER_CLASS));  }  writeFileSync(join(dir, "scripts", "lib", "mac_disk_policy.py"), readFileSync(join(ROOT, "scripts", "lib", "mac_disk_policy.py")));  writeFileSync(join(dir, "scripts", "lib", "evidence.py"), readFileSync(join(ROOT, "scripts", "lib", "evidence.py")));  const marker = join(dir, "wrapped");  writeFileSync(    join(dir, "scripts", "with-build-lock.sh"),    [      "#!/usr/bin/env bash",      `printf '%s' "\${BUILD_LOCK_LABEL:-none}" > ${JSON.stringify(marker)}`,      'exec "$@"',      "",    ].join("\n"),  );  chmodSync(join(dir, "scripts", "with-build-lock.sh"), 0o755);  const result = spawnSync("bash", [copy, ...command], {    encoding: "utf8",    timeout: 60_000,    env: {      ...process.env,      COTTON_MACHINE_LOCK_OS: os,      ...(label === undefined ? { BUILD_LOCK_LABEL: "" } : { BUILD_LOCK_LABEL: label }),      ...extra,    },  });  return {    status: result.status,    stdout: result.stdout ?? "",    stderr: result.stderr ?? "",    wrapped: existsSync(marker),    label: existsSync(marker) ? readFileSync(marker, "utf8") : "",  };}describe("with-machine-lock.sh", () => {  it("takes the machine mutex on a Mac, and names who is asking", () => {    const r = run("Darwin", ["bash", "-c", "echo the-command-ran"]);    expect(r.wrapped).toBe(true);    expect(r.label).toBe("ci-rust-mac");    expect(r.stdout).toContain("the-command-ran");    expect(r.status).toBe(0);  });  it("keeps a label the caller chose", () => {    const r = run("Darwin", ["bash", "-c", "true"], "ci-rust-clippy");    expect(r.label).toBe("ci-rust-clippy");  });  it("does NOT take it on the Linux host, where four jobs run at once", () => {    const r = run("Linux", ["bash", "-c", "echo the-command-ran"]);    expect(r.wrapped).toBe(false);    expect(r.stdout).toContain("the-command-ran");    expect(r.status).toBe(0);  });  it("reports the wrapped command's own exit status on both machines", () => {    expect(run("Darwin", ["bash", "-c", "exit 42"]).status).toBe(42);    expect(run("Linux", ["bash", "-c", "exit 42"]).status).toBe(42);  });  it("refuses an empty command rather than taking a lock around nothing", () => {    const r = run("Darwin", []);    expect(r.status).toBe(2);    expect(r.wrapped).toBe(false);  });});/** * ON THE LINUX HOST A CHECK JOB OUTRANKS A BUILDER'S LOCAL RUN — BY THE * SCHEDULER, since there is no lock to rank. On 28 Sep 2026 the CI host read * load 49 on 16 cores from builders' local test runs, each at one test thread * per core at nice 0, and `rust-job-sizing.sh` then sized the check jobs DOWN. * A local run now gets nice 19 and four threads; a check job is untouched. */describe("with-machine-lock.sh — a local run on Linux yields the machine", () => {  const probe = [    "bash",    "-c",    'echo "nice=$(python3 -c \'import os;print(os.getpriority(os.PRIO_PROCESS,0))\') jobs=${CARGO_BUILD_JOBS:-unset} tests=${NEXTEST_TEST_THREADS:-unset} rust=${RUST_TEST_THREADS:-unset}"',  ];  const clean = { CARGO_BUILD_JOBS: "", NEXTEST_TEST_THREADS: "", RUST_TEST_THREADS: "" };  const parentNice = Number(execFileSync("python3", ["-c", "import os;print(os.getpriority(os.PRIO_PROCESS," + process.pid + "))"], { encoding: "utf8" }).trim());  it("runs a local caller at nice 19 with four build jobs and four test threads", () => {    const r = run("Linux", probe, undefined, { ...clean, BUILD_LOCK_CLASS: "local" });    expect(r.status, r.stderr).toBe(0);    expect(r.stdout).toContain("nice=19 jobs=4 tests=4 rust=4");    expect(r.stderr).toContain("check jobs go first");    expect(r.wrapped).toBe(false);  });  it("keeps a parallelism the local caller chose itself", () => {    const r = run("Linux", probe, undefined, { ...clean, BUILD_LOCK_CLASS: "local", CARGO_BUILD_JOBS: "2" });    expect(r.stdout).toContain("jobs=2 tests=4");  });  it("runs a check job exactly as before — its own niceness, no caps", () => {    const r = run("Linux", probe, undefined, { ...clean, BUILD_LOCK_CLASS: "ci" });    expect(r.status, r.stderr).toBe(0);    expect(r.stdout).toContain(`nice=${parentNice} jobs=unset tests=unset rust=unset`);    expect(r.stderr).not.toContain("check jobs go first");  });  it("reads the rank from the runner's own variables when nothing overrides it", () => {    const r = run("Linux", probe, undefined, { ...clean, BUILD_LOCK_CLASS: "", CI: "true" });    expect(r.stdout).toContain(`nice=${parentNice} `);    const local = run("Linux", probe, undefined, { ...clean, BUILD_LOCK_CLASS: "", CI: "", GITHUB_ACTIONS: "" });    expect(local.stdout).toContain("nice=19 ");  });  it("refuses to run unranked when the helper is missing", () => {    const r = run("Linux", probe, undefined, { BUILD_LOCK_CLASS: "local", COTTON_TEST_DROP_CALLER_CLASS: "1" });    expect(r.status).toBe(2);    expect(r.stdout).not.toContain("nice=");  });});