"use strict"; // Tests for utils/scheduler-leader.js: cross-process leader election for the // scheduler's per-process machinery (BullMQ worker + AI agent job pump). // // Contract locked here: // - exactly ONE contender wins: the winner constructs its machinery // (onBecameLeader fired once), the loser follows and never fires it; // - the winner's release (graceful shutdown) or a provably dead owner // (ESRCH / recycled PID) lets a follower acquire on its next poll — // the documented failover paths; // - an unwritable lock location fails OPEN (acting leader, loud warn, // no re-election) — availability beats the resource cap; // - a lock path that cannot be CLAIMED while its directory stays writable // (a directory at the path, a stale owner record the mutex could neither // verify nor steal) fails open the same way but with an ACCURATE // diagnosis ("not usable", the path, the fix) — never the false // "another process is the leader" follower livelock; // - a writable location with transient contention keeps polling // (self-healing), it is NOT fail-open; // - while held, the underlying mutex heartbeats (long-held leadership is // not mistaken for a stale lock); // - releaseLeadership is idempotent, terminal, and never unlinks a foreign // owner's lock; // - REAL cross-process election: concurrent child processes on one lock // file never act as leader at the same time, and the follower takes // over after the first leader releases. const test = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const os = require("node:os"); const path = require("node:path"); const childProcess = require("node:child_process"); const { startSchedulerLeaderElection } = require("./scheduler-leader"); function makeTempDir() { return fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-sched-leader-")); } function readLock(lockPath) { return JSON.parse(fs.readFileSync(lockPath, "utf8")); } function writeLock(lockPath, owner) { fs.writeFileSync(lockPath, JSON.stringify(owner), "utf8"); } function readProcStartTicks(pid) { const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8"); const fields = stat.slice(stat.lastIndexOf(")") + 2).trim().split(" "); return Number(fields[19]); } const canReadProc = (() => { try { fs.readFileSync("/proc/self/stat", "utf8"); return true; } catch (_) { return false; } })(); test("two contenders: the first wins and fires onBecameLeader once, the second follows and never does", () => { const dir = makeTempDir(); try { const lockPath = path.join(dir, "scheduler-leader.lock"); let firstFired = 0; let secondFired = 0; const first = startSchedulerLeaderElection({ label: "[t-first]", lockFilePath: lockPath, onBecameLeader: () => { firstFired += 1; }, }); const second = startSchedulerLeaderElection({ label: "[t-second]", lockFilePath: lockPath, onBecameLeader: () => { secondFired += 1; }, }); assert.equal(first.isLeader(), true, "the first contender must win the election"); assert.equal(first.role(), "leader"); assert.equal(firstFired, 1, "the winner's callback fires exactly once"); assert.equal(second.isLeader(), false, "the second contender must follow"); assert.equal(second.role(), "follower"); assert.equal(secondFired, 0, "the follower must not run the per-process machinery"); assert.ok(fs.existsSync(lockPath), "the leader lock file must exist while held"); first.releaseLeadership(); assert.equal(fs.existsSync(lockPath), false, "release must remove the leader lock"); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("graceful release: the follower acquires on its next poll and fires its own callback (instant failover)", async () => { const dir = makeTempDir(); try { const lockPath = path.join(dir, "scheduler-leader.lock"); let fired = 0; const first = startSchedulerLeaderElection({ label: "[t-a]", lockFilePath: lockPath }); const second = startSchedulerLeaderElection({ label: "[t-b]", lockFilePath: lockPath, pollMs: 40, onBecameLeader: () => { fired += 1; }, }); assert.equal(first.isLeader(), true); assert.equal(second.isLeader(), false); first.releaseLeadership(); // Wait up to ~2s for the follower's poll to win the freed lock. for (let i = 0; i < 100 && !second.isLeader(); i += 1) { await new Promise((resolve) => setTimeout(resolve, 20)); } assert.equal(second.isLeader(), true, "the follower must take over after the leader releases"); assert.equal(fired, 1, "the takeover must run the per-process machinery exactly once"); assert.equal(readLock(lockPath).pid, process.pid); second.releaseLeadership(); assert.equal(fs.existsSync(lockPath), false); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("crash failover: a follower takes over a SIGKILLed leader's lock on its next poll (dead-PID steal)", async () => { const dir = makeTempDir(); try { const lockPath = path.join(dir, "scheduler-leader.lock"); // The initial leader is a REAL foreign process holding the same lock via // the same mutex, then SIGKILLed — exactly a pm2 worker dying mid-flight. const childSource = ` const { createCrossProcessOperationMutex } = require(process.env.SL_MUTEX_PATH); const mutex = createCrossProcessOperationMutex({ label: "[crashed-leader]", lockFilePath: process.env.SL_LOCK_PATH, heartbeatMs: 80, staleAfterMs: 5000, }); const release = mutex.tryAcquire(); if (!release) process.exit(2); console.log("HELD"); setInterval(() => {}, 250); // hold the lock until killed `; const leader = childProcess.spawn(process.execPath, ["-e", childSource], { stdio: ["ignore", "pipe", "inherit"], env: { ...process.env, SL_MUTEX_PATH: require.resolve("./cross-process-mutex"), SL_LOCK_PATH: lockPath }, }); let leaderOut = ""; leader.stdout.on("data", (d) => { leaderOut += String(d); }); for (let i = 0; i < 100 && !leaderOut.includes("HELD"); i += 1) { await new Promise((resolve) => setTimeout(resolve, 20)); } assert.ok(leaderOut.includes("HELD"), "the foreign leader must hold the lock first"); const heldToken = readLock(lockPath).token; let fired = 0; const follower = startSchedulerLeaderElection({ label: "[t-steal]", lockFilePath: lockPath, pollMs: 40, onBecameLeader: () => { fired += 1; }, }); assert.equal(follower.isLeader(), false, "the follower must follow a live leader"); leader.kill("SIGKILL"); for (let i = 0; i < 100 && !follower.isLeader(); i += 1) { await new Promise((resolve) => setTimeout(resolve, 20)); } assert.equal(follower.isLeader(), true, "a dead leader's lock must be stolen without waiting for the TTL"); assert.equal(fired, 1); assert.notEqual(readLock(lockPath).token, heldToken, "the takeover must re-create the lock under the new owner"); follower.releaseLeadership(); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("recycled-PID steal: a follower recovers a lock whose owner pid was reused (startTicks mismatch)", async () => { if (!canReadProc) return; const dir = makeTempDir(); try { const lockPath = path.join(dir, "scheduler-leader.lock"); // Same (alive) pid as this process but recorded start ticks that no // longer match: exactly what a recycled PID looks like. writeLock(lockPath, { pid: process.pid, token: "recycled-leader", acquiredAt: Date.now(), startTicks: readProcStartTicks(process.pid) + 1000, }); const follower = startSchedulerLeaderElection({ label: "[t-recycle]", lockFilePath: lockPath, pollMs: 40, }); for (let i = 0; i < 100 && !follower.isLeader(); i += 1) { await new Promise((resolve) => setTimeout(resolve, 20)); } assert.equal(follower.isLeader(), true, "a recycled-PID leader lock must be recovered promptly"); follower.releaseLeadership(); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("a live leader's lock is never stolen from: the follower keeps polling while the heartbeat renews", async () => { const dir = makeTempDir(); try { const lockPath = path.join(dir, "scheduler-leader.lock"); const leader = startSchedulerLeaderElection({ label: "[t-hold]", lockFilePath: lockPath, heartbeatMs: 80, staleAfterMs: 45000, pollMs: 40, }); const follower = startSchedulerLeaderElection({ label: "[t-wait]", lockFilePath: lockPath, heartbeatMs: 80, staleAfterMs: 45000, pollMs: 40, }); assert.equal(leader.isLeader(), true); const first = readLock(lockPath); // Longer than several heartbeats AND several follower polls: the leader // must keep the lock (renewed acquiredAt) and the follower must keep // losing the re-election. await new Promise((resolve) => setTimeout(resolve, 500)); assert.equal(leader.isLeader(), true, "the live leader must keep leadership"); assert.equal(follower.isLeader(), false, "the follower must not steal from a live leader"); const second = readLock(lockPath); assert.equal(second.token, first.token, "the heartbeat must keep the owner token"); assert.ok(second.acquiredAt > first.acquiredAt, "the heartbeat must renew acquiredAt while leadership is held"); leader.releaseLeadership(); follower.releaseLeadership(); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("unwritable lock location: fail-open acting leader with a loud warn, no re-election attempts", () => { const dir = makeTempDir(); try { // A path UNDER a regular file: every fs operation on it fails with // ENOTDIR — a durably broken lock location, the fail-open trigger. const notADir = path.join(dir, "not-a-dir"); fs.writeFileSync(notADir, "x", "utf8"); const lockPath = path.join(notADir, "scheduler-leader.lock"); const warns = []; const originalWarn = console.warn; console.warn = (...args) => warns.push(args.join(" ")); let fired = 0; let election; try { election = startSchedulerLeaderElection({ label: "[t-failopen]", lockFilePath: lockPath, pollMs: 40, onBecameLeader: () => { fired += 1; }, }); } finally { console.warn = originalWarn; } assert.equal(election.isLeader(), true, "a broken election must fail OPEN — the machinery still runs"); assert.equal(election.role(), "leader-failopen"); assert.equal(fired, 1, "the fail-open acting leader must run the machinery"); assert.ok( warns.some((l) => l.includes("[t-failopen]") && l.includes("not writable") && l.includes("FAIL-OPEN")), `the fail-open must be loud; got: ${JSON.stringify(warns)}` ); // The fail-open posture is terminal: after a wait spanning many poll // intervals the role is unchanged (no re-election loop). return new Promise((resolve) => { setTimeout(() => { assert.equal(election.role(), "leader-failopen", "fail-open must persist for the process lifetime"); assert.equal(fired, 1); election.releaseLeadership(); resolve(); }, 200); }); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("transient contention on a writable location is NOT fail-open: the follower keeps its role and its poll", async () => { const dir = makeTempDir(); try { const lockPath = path.join(dir, "scheduler-leader.lock"); // A live foreign owner (this process, fresh record) holds the lock. writeLock(lockPath, { pid: process.pid, token: "live-foreign", acquiredAt: Date.now() }); const warns = []; const originalWarn = console.warn; console.warn = (...args) => warns.push(args.join(" ")); let election; try { election = startSchedulerLeaderElection({ label: "[t-busy]", lockFilePath: lockPath, pollMs: 40, }); } finally { console.warn = originalWarn; } assert.equal(election.isLeader(), false, "contention must be followed, not failed open"); assert.equal(election.role(), "follower"); assert.equal(warns.length, 0, "ordinary contention must not log the fail-open warning"); // Self-healing: once the foreign record is removed, the poll wins. fs.unlinkSync(lockPath); for (let i = 0; i < 100 && !election.isLeader(); i += 1) { await new Promise((resolve) => setTimeout(resolve, 20)); } assert.equal(election.isLeader(), true, "the poll must acquire once the lock frees"); election.releaseLeadership(); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("a directory at the lock path is classified UNUSABLE: terminal acting leader with an accurate warn, never 'another leader'", () => { const dir = makeTempDir(); try { const lockPath = path.join(dir, "scheduler-leader.lock"); // The finding: the lock location is writable (a sibling probe succeeds) // but the lock PATH itself is a directory — every O_EXCL create and every // steal fails forever, so this must NOT read as "another process is the // leader". fs.mkdirSync(lockPath); const warns = []; const logs = []; const originalWarn = console.warn; const originalLog = console.log; console.warn = (...args) => warns.push(args.join(" ")); console.log = (...args) => logs.push(args.join(" ")); let fired = 0; let election; try { election = startSchedulerLeaderElection({ label: "[t-unusable-dir]", lockFilePath: lockPath, pollMs: 40, onBecameLeader: () => { fired += 1; }, }); } finally { console.warn = originalWarn; console.log = originalLog; } assert.equal(election.isLeader(), true, "an unclaimable lock path must fail OPEN — the machinery still runs"); assert.equal(election.role(), "leader-failopen"); assert.equal(fired, 1, "the acting leader must run the machinery"); assert.ok( warns.some((l) => l.includes("[t-unusable-dir]") && l.includes("not usable") && l.includes(lockPath) && l.includes("directory") && l.includes("remove or fix") && l.includes("FAIL-OPEN")), `the warn must name the directory at the lock path and the fix; got: ${JSON.stringify(warns)}` ); assert.ok( !warns.concat(logs).some((l) => l.includes("another process is the leader")), `the false "another leader" diagnostic must never fire; got: ${JSON.stringify([...warns, ...logs])}` ); // Terminal: many poll intervals later the role is unchanged (no follower // loop, no re-election, no second machinery start). return new Promise((resolve) => { setTimeout(() => { assert.equal(election.role(), "leader-failopen", "the unusable classification must persist for the process lifetime"); assert.equal(fired, 1); assert.ok( !warns.concat(logs).some((l) => l.includes("another process is the leader")), "the false diagnostic must not appear later either" ); election.releaseLeadership(); resolve(); }, 200); }); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("an unparseable lock file with a fresh mtime stays the ordinary follower path (the mutex's mid-create window is not misread as unusable)", async () => { const dir = makeTempDir(); try { const lockPath = path.join(dir, "scheduler-leader.lock"); // Garbage content with a fresh mtime: exactly what the mutex's own // staleness fallback treats as held (a lock being created right now never // looks stale) — the follower diagnosis must stay byte-identical. fs.writeFileSync(lockPath, "{not-json", "utf8"); const warns = []; const logs = []; const originalWarn = console.warn; const originalLog = console.log; console.warn = (...args) => warns.push(args.join(" ")); console.log = (...args) => logs.push(args.join(" ")); let election; try { election = startSchedulerLeaderElection({ label: "[t-fresh-garbage]", lockFilePath: lockPath, pollMs: 40, }); } finally { console.warn = originalWarn; console.log = originalLog; } assert.equal(election.isLeader(), false, "a held-looking fresh lock must be followed, not failed open"); assert.equal(election.role(), "follower"); assert.equal(warns.length, 0, "an unparseable-but-fresh lock must not log the unusable warning"); assert.ok( logs.some((l) => l.includes("another process is the leader")), "the ordinary contention diagnosis stays for a held-looking lock" ); // Self-healing unchanged: once the garbage file is removed, the poll wins. fs.unlinkSync(lockPath); for (let i = 0; i < 100 && !election.isLeader(); i += 1) { await new Promise((resolve) => setTimeout(resolve, 20)); } assert.equal(election.isLeader(), true); election.releaseLeadership(); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("a stale-aged owner is still stolen by the mutex on the first attempt, not classified unusable", () => { const dir = makeTempDir(); try { const lockPath = path.join(dir, "scheduler-leader.lock"); // A claimable regular file aged past the TTL: the mutex's stale-steal runs // INSIDE tryAcquire and wins, so the election becomes leader immediately — // the unusable classification is only for records the steal cannot claim. writeLock(lockPath, { pid: process.pid, token: "aged-owner", acquiredAt: Date.now() - 60000 }); const election = startSchedulerLeaderElection({ label: "[t-aged-steal]", lockFilePath: lockPath, pollMs: 40, }); assert.equal(election.isLeader(), true, "a stale claimable owner must be stolen, not followed"); assert.equal(election.role(), "leader"); assert.notEqual(readLock(lockPath).token, "aged-owner", "the steal must re-create the lock under the new owner"); election.releaseLeadership(); assert.equal(fs.existsSync(lockPath), false); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("releaseLeadership is idempotent, terminal, and never unlinks a foreign owner's lock", async () => { const dir = makeTempDir(); try { const lockPath = path.join(dir, "scheduler-leader.lock"); const election = startSchedulerLeaderElection({ label: "[t-release]", lockFilePath: lockPath }); assert.equal(election.isLeader(), true); election.releaseLeadership(); assert.equal(fs.existsSync(lockPath), false); election.releaseLeadership(); // second call: silent no-op, must not throw assert.equal(election.isLeader(), false, "release is terminal — no re-acquisition"); // A follower's release (never won) must not disturb the real holder. const holder = startSchedulerLeaderElection({ label: "[t-holder]", lockFilePath: lockPath }); const follower = startSchedulerLeaderElection({ label: "[t-never]", lockFilePath: lockPath, pollMs: 40 }); assert.equal(holder.isLeader(), true); assert.equal(follower.isLeader(), false); const before = readLock(lockPath); follower.releaseLeadership(); assert.ok(fs.existsSync(lockPath), "a never-won process's release must not remove the leader's lock"); assert.equal(readLock(lockPath).token, before.token); holder.releaseLeadership(); assert.equal(fs.existsSync(lockPath), false); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("REAL cross-process election: concurrent children never act as leader at the same time and the follower takes over", async () => { const dir = makeTempDir(); try { const lockPath = path.join(dir, "scheduler-leader.lock"); const logPath = path.join(dir, "leadership-log.txt"); fs.writeFileSync(logPath, "", "utf8"); const childSource = ` const fs = require("fs"); const { startSchedulerLeaderElection } = require(process.env.SL_UTIL_PATH); const log = () => fs.appendFileSync(process.env.SL_LOG_PATH, process.env.SL_EVT + "\\n"); const election = startSchedulerLeaderElection({ label: "[child-" + process.env.SL_ID + "]", lockFilePath: process.env.SL_LOCK_PATH, pollMs: 100, heartbeatMs: 80, staleAfterMs: 5000, onBecameLeader() { process.env.SL_EVT = "leader" + process.env.SL_ID; log(); setTimeout(() => { process.env.SL_EVT = "released" + process.env.SL_ID; election.releaseLeadership(); log(); process.exit(0); }, Number(process.env.SL_HOLD_MS)); }, }); const deadline = Date.now() + 20000; // A ref'd keep-alive: the election's own timers are unref'd (a panel // process is held alive by its HTTP server; this bare child must hold // its own loop open until it wins or the budget expires). const keepAlive = setInterval(() => { }, 250); const t = setInterval(() => { if (election.isLeader()) return; // onBecameLeader drives the exit if (Date.now() > deadline) { process.env.SL_EVT = "never-leader" + process.env.SL_ID; log(); process.exit(1); } }, 50); if (typeof t.unref === "function") t.unref(); `; // Child 1 holds leadership for 600ms, releases (graceful failover), and // exits; child 2 starts in the same instant and must follow until the // lock frees, then win. The shared log is the ground truth. const holdMs = 600; const children = [1, 2].map((id) => new Promise((resolve, reject) => { const child = childProcess.spawn( process.execPath, ["-e", childSource], { stdio: ["ignore", "inherit", "inherit"], env: { ...process.env, SL_UTIL_PATH: require.resolve("./scheduler-leader"), SL_LOCK_PATH: lockPath, SL_LOG_PATH: logPath, SL_ID: String(id), SL_HOLD_MS: String(holdMs), }, } ); child.on("exit", (code) => (code === 0 ? resolve() : reject(new Error(`child ${id} exited ${code}`)))); child.on("error", reject); })); await Promise.all(children); const events = fs.readFileSync(logPath, "utf8").split("\n").filter(Boolean); assert.equal(events.length, 4, `each child must become leader once and release once: ${JSON.stringify(events)}`); let depth = 0; for (const evt of events) { if (evt.startsWith("leader") || evt.startsWith("released")) { depth += evt.startsWith("leader") ? 1 : -1; assert.ok(depth === 0 || depth === 1, `leadership overlap detected: ${JSON.stringify(events)}`); } else { assert.fail(`unexpected event: ${evt}`); } } assert.equal(depth, 0, "every leadership must have been released"); assert.equal(fs.existsSync(lockPath), false, "the lock file must be gone after both children finish"); } finally { fs.rmSync(dir, { recursive: true, force: true }); } });