diff --git a/vitest.config.ts b/vitest.config.ts index a7483a8..bdb7301 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,11 +1,14 @@ import path from "node:path"; import { defineConfig } from "vitest/config"; +import { localWorkerLimit } from "./vitest.workers"; -export default defineConfig({ +export default defineConfig(async () => ({ test: { environment: "node", - include: ["src/**/*.test.ts"], + include: ["src/**/*.test.ts", "vitest.workers.test.ts"], testTimeout: 15_000, + // Caps local vitest workers across concurrent runs on one machine; no effect in CI. + ...(await localWorkerLimit()), }, resolve: { alias: { @@ -15,4 +18,4 @@ export default defineConfig({ ), }, }, -}); +})); diff --git a/vitest.workers.test.ts b/vitest.workers.test.ts new file mode 100644 index 0000000..64ece8f --- /dev/null +++ b/vitest.workers.test.ts @@ -0,0 +1,359 @@ +import { type ChildProcess, spawn } from "node:child_process"; +import { + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + chmodSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + acquireSlots, + localWorkerLimit, + resetLocalGrantForTests, + type SlotGrant, +} from "./vitest.workers"; + +const HELPER_URL = pathToFileURL(join(__dirname, "vitest.workers.ts")).href; +const quiet = () => {}; +// Node before 22.18 needs a flag to run the .ts helper in a child process. +const TS_ARGS = (process.features as { typescript?: unknown }).typescript + ? [] + : ["--experimental-strip-types"]; + +let dir: string; +let children: ChildProcess[] = []; +let grants: SlotGrant[] = []; + +beforeEach(() => { + dir = join(mkdtempSync(join(tmpdir(), "vitest-slots-")), "slots"); + resetLocalGrantForTests(); +}); + +afterEach(() => { + for (const g of grants) g.release(); + grants = []; + for (const c of children) c.kill("SIGKILL"); + children = []; + rmSync(join(dir, ".."), { recursive: true, force: true }); +}); + +function liveChild(): Promise { + const child = spawn( + process.execPath, + ["-e", "console.log('up');setInterval(()=>{},1e3)"], + { + stdio: ["ignore", "pipe", "ignore"], + }, + ); + children.push(child); + return new Promise((resolve) => + child.stdout!.once("data", () => resolve(child)), + ); +} + +function claimSlots(owner: number, indexes: number[]) { + for (const i of indexes) { + const slot = join(dir, `slot-${i}`); + mkdirSync(slot, { recursive: true }); + writeFileSync(join(slot, "owner"), String(owner)); + } +} + +function slotNames(): string[] { + return existsSync(dir) + ? readdirSync(dir).filter((n) => /^slot-\d+$/.test(n)) + : []; +} + +describe("localWorkerLimit", () => { + it("returns {} and creates no slot dir when CI is set", async () => { + expect(await localWorkerLimit({ env: { CI: "1" }, dir })).toEqual({}); + expect(existsSync(dir)).toBe(false); + }); + + it("takes the configured want and a second call reuses the same grant", async () => { + const env = { VITEST_HOST_WORKERS: "6", VITEST_MAX_WORKERS: "4" }; + expect(await localWorkerLimit({ env, dir, log: quiet })).toEqual({ + maxWorkers: 4, + }); + expect(slotNames()).toHaveLength(4); + expect(await localWorkerLimit({ env, dir, log: quiet })).toEqual({ + maxWorkers: 4, + }); + expect(slotNames()).toHaveLength(4); + }); + + it("falls back to the default 6 on invalid values and caps want by the budget", async () => { + for (const bad of ["0", "abc"]) { + resetLocalGrantForTests(); + const r = await localWorkerLimit({ + env: { VITEST_HOST_WORKERS: bad }, + dir, + log: quiet, + }); + expect(r).toEqual({ maxWorkers: 6 }); + // release by removing our slots; the next iteration takes them again + rmSync(dir, { recursive: true, force: true }); + } + resetLocalGrantForTests(); + const capped = await localWorkerLimit({ + env: { VITEST_HOST_WORKERS: "6", VITEST_MAX_WORKERS: "10" }, + dir, + log: quiet, + }); + expect(capped).toEqual({ maxWorkers: 6 }); + }); +}); + +describe("localWorkerLimit grant sharing and fallback", () => { + it("a re-imported helper reuses the grant", async () => { + const opts = { env: {}, dir, timeoutMs: 50, pollMs: 5, log: quiet }; + expect(await localWorkerLimit(opts)).toEqual({ maxWorkers: 6 }); + vi.resetModules(); + const fresh = await import("./vitest.workers"); + expect(await fresh.localWorkerLimit(opts)).toEqual({ maxWorkers: 6 }); + expect(slotNames()).toHaveLength(6); + }); + + it("skips the host gate but keeps the cap when the slot dir is unusable", async () => { + const parent = mkdtempSync(join(tmpdir(), "vitest-ro-")); + chmodSync(parent, 0o500); + const warnings: string[] = []; + try { + const result = await localWorkerLimit({ + env: { VITEST_MAX_WORKERS: "3" }, + dir: join(parent, "sub", "slots"), + log: (m) => warnings.push(m), + }); + expect(result).toEqual({ maxWorkers: 3 }); + expect(warnings).toHaveLength(1); + expect(warnings[0]).toMatch(/EACCES|EROFS|EPERM/); + } finally { + chmodSync(parent, 0o700); + rmSync(parent, { recursive: true, force: true }); + } + }); +}); + +describe("acquireSlots", () => { + const base = () => ({ dir, budget: 6, want: 6, pollMs: 5, log: quiet }); + + it("takes 6 slots from an empty dir and writes its pid as owner", async () => { + const g = await acquireSlots(base()); + grants.push(g); + expect(g.count).toBe(6); + for (let i = 0; i < 6; i += 1) { + expect(readFileSync(join(dir, `slot-${i}`, "owner"), "utf8")).toBe( + String(process.pid), + ); + } + }); + + it("grants only the free slots when 4 are held by a live process", async () => { + const child = await liveChild(); + claimSlots(child.pid!, [0, 1, 2, 3]); + const g = await acquireSlots(base()); + grants.push(g); + expect(g.count).toBe(2); + }); + + it("stays pending while all 6 are held by a live process, then resolves with 6 once it dies", async () => { + const child = await liveChild(); + claimSlots(child.pid!, [0, 1, 2, 3, 4, 5]); + let polls = 0; + const warnings: string[] = []; + const pending = acquireSlots({ + ...base(), + log: (m) => { + warnings.push(m); + }, + }); + let settled = false; + void pending.then(() => { + settled = true; + }); + // Hold the exclusion window: let several poll intervals pass while rejected. + while (polls < 3) { + await new Promise((r) => setTimeout(r, 10)); + polls += 1; + } + expect(settled).toBe(false); + expect(warnings).toHaveLength(1); + expect(warnings[0]).toContain(`pids ${child.pid}`); + child.kill("SIGKILL"); + const g = await pending; + grants.push(g); + expect(g.count).toBe(6); + }); + + it("reclaims a slot whose owner pid is dead", async () => { + const child = await liveChild(); + const deadPid = child.pid!; + await new Promise((r) => { + child.once("exit", r); + child.kill("SIGKILL"); + }); + claimSlots(deadPid, [0, 1, 2, 3, 4, 5]); + const g = await acquireSlots(base()); + grants.push(g); + expect(g.count).toBe(6); + expect(readFileSync(join(dir, "slot-0", "owner"), "utf8")).toBe( + String(process.pid), + ); + }); + + it("leaves a slot under a fresh reclaim lock alone", async () => { + const child = await liveChild(); + const deadPid = child.pid!; + await new Promise((r) => { + child.once("exit", r); + child.kill("SIGKILL"); + }); + claimSlots(deadPid, [0, 1, 2, 3, 4, 5]); + mkdirSync(join(dir, "slot-0.lock")); + const g = await acquireSlots(base()); + grants.push(g); + expect(g.count).toBe(5); + expect(readFileSync(join(dir, "slot-0", "owner"), "utf8")).toBe( + String(deadPid), + ); + }); + + it("removes its slot dirs on release", async () => { + const g = await acquireSlots(base()); + expect(slotNames()).toHaveLength(6); + g.release(); + g.release(); + expect(slotNames()).toHaveLength(0); + }); + + it("times out with an error naming the holders", async () => { + const child = await liveChild(); + claimSlots(child.pid!, [0, 1, 2, 3, 4, 5]); + await expect(acquireSlots({ ...base(), timeoutMs: 30 })).rejects.toThrow( + `held by pids ${child.pid}`, + ); + }); +}); + +describe("across processes", () => { + const script = ` + const { acquireSlots } = await import(${JSON.stringify(HELPER_URL)}); + let g; + try { + g = await acquireSlots({ + dir: process.env.SLOT_DIR, budget: 6, want: 6, pollMs: 5, + log: (m) => console.log("WAITING"), + }); + } catch (e) { console.log("ERR " + e.message); process.exit(1); } + console.log("GOT " + g.count); + process.stdin.on("end", () => { g.release(); process.exit(0); }); + process.stdin.resume(); + `; + + function runner(source: string = script): { + child: ChildProcess; + line: (prefix: string) => Promise; + } { + const child = spawn( + process.execPath, + [...TS_ARGS, "--input-type=module", "-e", source], + { + env: { ...process.env, SLOT_DIR: dir }, + stdio: ["pipe", "pipe", "inherit"], + }, + ); + children.push(child); + const lines: string[] = []; + const waiters: Array<() => void> = []; + let buf = ""; + child.stdout!.on("data", (d: Buffer) => { + buf += d.toString(); + let nl: number; + while ((nl = buf.indexOf("\n")) >= 0) { + lines.push(buf.slice(0, nl)); + buf = buf.slice(nl + 1); + } + waiters.splice(0).forEach((w) => w()); + }); + const line = async (prefix: string) => { + for (;;) { + const hit = lines.find((l) => l.startsWith(prefix)); + if (hit) return hit; + await new Promise((r) => waiters.push(r)); + } + }; + return { child, line }; + } + + it("a second process waits until the first exits", async () => { + const first = runner(); + expect(await first.line("GOT")).toBe("GOT 6"); + const second = runner(); + await second.line("WAITING"); + first.child.stdin!.end(); + expect(await second.line("GOT")).toBe("GOT 6"); + }); + // One pass, no waiting: GOT n, NONE (no slot free) or ERR msg (a real failure). + const onePassScript = ` + const { acquireSlots } = await import(${JSON.stringify(HELPER_URL)}); + let g; + try { + g = await acquireSlots({ + dir: process.env.SLOT_DIR, budget: 6, want: 6, pollMs: 5, timeoutMs: 0, + log: () => {}, + }); + } catch (e) { + console.log(e.code ? "ERR " + e.message : "NONE"); + process.exit(0); + } + console.log("GOT " + g.count); + process.stdin.on("end", () => { g.release(); process.exit(0); }); + process.stdin.resume(); + `; + + it("concurrent reclaimers never over-grant", async () => { + const owned = (pid: number) => + slotNames().filter( + (s) => readFileSync(join(dir, s, "owner"), "utf8") === String(pid), + ).length; + for (let round = 0; round < 10; round += 1) { + rmSync(dir, { recursive: true, force: true }); + const dead = await liveChild(); + const deadPid = dead.pid!; + await new Promise((r) => { + dead.once("exit", r); + dead.kill("SIGKILL"); + }); + claimSlots(deadPid, [0, 1, 2, 3, 4, 5]); + const runners = [0, 1, 2, 3].map(() => runner(onePassScript)); + const outcomes = await Promise.all( + runners.map((r) => + Promise.race([r.line("GOT"), r.line("NONE"), r.line("ERR")]), + ), + ); + expect(outcomes.filter((o) => o.startsWith("ERR"))).toEqual([]); + const got = outcomes + .filter((o) => o.startsWith("GOT")) + .reduce((sum, o) => sum + Number(o.split(" ")[1]), 0); + expect(got).toBeLessThanOrEqual(6); + // On-disk ownership must match each runner's claim exactly. + for (const [i, o] of outcomes.entries()) { + if (o.startsWith("GOT")) { + expect(owned(runners[i].child.pid!)).toBe(Number(o.split(" ")[1])); + } + } + for (const r of runners) { + r.child.stdin!.end(); + r.child.kill("SIGKILL"); + } + } + }, 60_000); +}); diff --git a/vitest.workers.ts b/vitest.workers.ts new file mode 100644 index 0000000..9e0cd35 --- /dev/null +++ b/vitest.workers.ts @@ -0,0 +1,266 @@ +// Host-wide cap on vitest workers. Vitest has no env var for the worker count, +// so every config calls localWorkerLimit(). Locally, all vitest runs of the +// user share a budget of slot directories under /tmp (default 6 workers in +// total); a run that finds none free waits. In CI (CI set) nothing changes. +// +// Env: VITEST_HOST_WORKERS (budget, default 6), VITEST_MAX_WORKERS (workers +// wanted by one run, default 6, capped by the budget). `--maxWorkers` on the +// vitest command line still overrides the config. +// +// Keep this file free of TypeScript-only runtime syntax (enums, parameter +// properties): the cross-process test loads it with Node's type stripping. +import { + mkdirSync, + readFileSync, + renameSync, + rmSync, + statSync, + writeFileSync, +} from "node:fs"; +import { userInfo } from "node:os"; +import { join } from "node:path"; + +// Fixed /tmp path, not os.tmpdir(): sessions can have different TMPDIR values, +// which would split the gate. Per uid so users do not share (or block) slots. +export const DEFAULT_SLOT_DIR = `/tmp/vitest-worker-slots-${userInfo().uid}`; +const DEFAULT_BUDGET = 6; +const OWNERLESS_STALE_MS = 10_000; +const DEFAULT_POLL_MS = 1000; +const DEFAULT_TIMEOUT_MS = 60 * 60 * 1000; + +export type SlotGrant = { count: number; release: () => void }; + +export type AcquireOptions = { + dir: string; + budget: number; + want: number; + pollMs?: number; + timeoutMs?: number; + log?: (message: string) => void; +}; + +function readOwner(slot: string): number | undefined { + try { + const pid = Number.parseInt(readFileSync(join(slot, "owner"), "utf8"), 10); + return Number.isInteger(pid) && pid > 0 ? pid : undefined; + } catch { + return undefined; + } +} + +function isAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch (err) { + return (err as NodeJS.ErrnoException).code !== "ESRCH"; + } +} + +// True when the slot's owner is gone (killed, OOM) or never wrote its pid. +function isStale(slot: string): { stale: boolean; owner?: number } { + const owner = readOwner(slot); + if (owner !== undefined) return { stale: !isAlive(owner), owner }; + try { + return { stale: Date.now() - statSync(slot).mtimeMs > OWNERLESS_STALE_MS }; + } catch { + return { stale: false }; + } +} + +let tmpCounter = 0; + +// Reclaim a stale slot. A per-slot lock dir keeps two reclaimers apart: the +// holder re-checks staleness under the lock, then renames the slot away and +// deletes it. A lock left by a killed reclaimer is removed once it is old. +function reclaim(slot: string): void { + const lock = `${slot}.lock`; + try { + mkdirSync(lock); + } catch (err) { + if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err; + try { + if (Date.now() - statSync(lock).mtimeMs > OWNERLESS_STALE_MS) { + rmSync(lock, { recursive: true, force: true }); + } + } catch { + // lock vanished: its holder finished + } + return; + } + try { + if (isStale(slot).stale) { + const tomb = `${slot}.stale-${process.pid}-${tmpCounter++}`; + try { + renameSync(slot, tomb); + rmSync(tomb, { recursive: true, force: true }); + } catch (err) { + if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err; + } + } + } finally { + rmSync(lock, { recursive: true, force: true }); + } +} + +// Publish a slot atomically: the owner file is written into a private dir that +// is renamed to the slot name, so a slot never exists without its owner. +function tryTake(slot: string): boolean { + for (let attempt = 0; attempt < 2; attempt += 1) { + const tmp = `${slot}.tmp-${process.pid}-${tmpCounter++}`; + mkdirSync(tmp); + try { + writeFileSync(join(tmp, "owner"), String(process.pid)); + renameSync(tmp, slot); + return true; + } catch (err) { + rmSync(tmp, { recursive: true, force: true }); + const code = (err as NodeJS.ErrnoException).code; + if (code !== "EEXIST" && code !== "ENOTEMPTY") throw err; + } + if (!isStale(slot).stale) return false; + reclaim(slot); + } + return false; +} + +function holders(dir: string, budget: number): string { + const pids: number[] = []; + for (let i = 0; i < budget; i += 1) { + const pid = readOwner(join(dir, `slot-${i}`)); + if (pid !== undefined) pids.push(pid); + } + return pids.join(", ") || "unknown"; +} + +export async function acquireSlots(opts: AcquireOptions): Promise { + const { dir, budget, want } = opts; + const pollMs = opts.pollMs ?? DEFAULT_POLL_MS; + const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS; + const log = opts.log ?? ((m: string) => process.stderr.write(`${m}\n`)); + mkdirSync(dir, { recursive: true, mode: 0o700 }); + + const startedAt = Date.now(); + let warned = false; + for (;;) { + const held: string[] = []; + for (let i = 0; i < budget && held.length < want; i += 1) { + const slot = join(dir, `slot-${i}`); + if (tryTake(slot)) held.push(slot); + } + if (held.length > 0) { + let released = false; + return { + count: held.length, + release: () => { + if (released) return; + released = true; + for (const slot of held) { + // Only remove a slot that still names us as owner. + if (readOwner(slot) !== process.pid) continue; + const tomb = `${slot}.stale-${process.pid}-${tmpCounter++}`; + try { + renameSync(slot, tomb); + rmSync(tomb, { recursive: true, force: true }); + } catch { + // already gone + } + } + }, + }; + } + if (!warned) { + warned = true; + log( + `[vitest] waiting for a worker slot (${budget} in use by pids ${holders(dir, budget)})`, + ); + } + if (Date.now() - startedAt >= timeoutMs) { + throw new Error( + `[vitest] no worker slot after ${timeoutMs} ms; held by pids ${holders(dir, budget)}`, + ); + } + await new Promise((resolve) => setTimeout(resolve, pollMs)); + } +} + +function positiveInt(raw: string | undefined, fallback: number): number { + if (raw === undefined || !/^\d+$/.test(raw.trim())) return fallback; + const n = Number.parseInt(raw, 10); + return n >= 1 ? n : fallback; +} + +export type LocalLimitOptions = { + env?: Record; + dir?: string; + pollMs?: number; + timeoutMs?: number; + log?: (message: string) => void; +}; + +const GRANT_KEY = Symbol.for("vitest.workers.grant"); +type GrantEntry = { pid: number; grant: Promise }; +type WithGrant = { [GRANT_KEY]?: GrantEntry }; + +// Vite bundles this file into every config load, so each (re)load gets a fresh +// module copy. The grant therefore lives on globalThis, not in module state. +// Test hook: forget the per-process grant (does not release it). +export function resetLocalGrantForTests(): void { + delete (globalThis as WithGrant)[GRANT_KEY]; +} + +export async function localWorkerLimit( + opts: LocalLimitOptions = {}, +): Promise<{ maxWorkers?: number }> { + const env = opts.env ?? process.env; + if (env.CI) return {}; + const budget = positiveInt(env.VITEST_HOST_WORKERS, DEFAULT_BUDGET); + const want = Math.min( + positiveInt(env.VITEST_MAX_WORKERS, DEFAULT_BUDGET), + budget, + ); + const g = globalThis as WithGrant; + let entry = g[GRANT_KEY]; + if (!entry || entry.pid !== process.pid) { + const grant = acquireSlots({ + dir: opts.dir ?? DEFAULT_SLOT_DIR, + budget, + want, + pollMs: opts.pollMs, + timeoutMs: opts.timeoutMs, + log: opts.log, + }); + entry = { pid: process.pid, grant }; + g[GRANT_KEY] = entry; + // Handlers are installed only here, when the entry is first created. + grant.then(installReleaseHandlers, () => { + if (g[GRANT_KEY] === entry) delete g[GRANT_KEY]; + }); + } + try { + const { count } = await entry.grant; + return { maxWorkers: count }; + } catch (err) { + // A filesystem error (EACCES, EROFS, ...) skips the host gate only; the + // cap still applies. The timeout error has no code and is rethrown. + const code = (err as NodeJS.ErrnoException).code; + if (typeof code !== "string") throw err; + const log = opts.log ?? ((m: string) => process.stderr.write(`${m}\n`)); + log( + `[vitest] worker slot gate unavailable (${code}); using maxWorkers=${want} without the host gate`, + ); + return { maxWorkers: want }; + } +} + +function installReleaseHandlers(grant: SlotGrant): void { + process.once("exit", grant.release); + for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"] as const) { + process.once(sig, () => { + grant.release(); + // Our once-listener removed the default; re-raise only if nobody else + // (e.g. vitest's own graceful shutdown) is listening. + if (process.listenerCount(sig) === 0) process.kill(process.pid, sig); + }); + } +}