"use strict"; // adpanel:scheduler-worker-leader — cross-process leader election for the // scheduler's per-process machinery (the BullMQ worker, its QueueEvents, and // the AI agent job pump). // // WHY THIS EXISTS: the per-process scheduler machinery used to start in EVERY // pm2 cluster worker. The fleet-wide backup cap // (SCHEDULER_MAX_CONCURRENT_BACKUPS in index.js) is an in-process counter, and // its "the shipped ecosystem.config.js is instances: 1" premise was false on // real installs: scripts/generate-ecosystem.sh computes INSTANCES = cores - 2 // (RAM-reduced) for any host with > 2 cores, and scripts/adpanel-runtime.sh // regenerates ecosystem.config.js on every boot — so an 8-core host runs six // panel processes, each running its own worker (concurrency 5) and its own // AI agent pump (AI_AGENT_JOB_CONCURRENCY, default 2): the backup cap // degrades to 2 x N and the agent concurrency to 2 x N. Multi-instance pm2 is // a legitimate deployment; the code must be correct under it. The fix runs // the per-process machinery in exactly ONE elected process per host: with a // single leader, the in-process counters ARE fleet-wide, unchanged. // // MECHANISM: leadership is a lock file held for the process lifetime, backed // by the SAME primitives as every other cross-process lock in this panel — // this module COMPOSES utils/cross-process-mutex.js through its public API // (O_EXCL owner-stamped create, heartbeat renewal, PID-liveness stale-steal // via /proc start-ticks + kill(2), token-checked release) and adds the // leadership semantics on top; it deliberately does not re-implement any of // those internals. The lock file lives in the panel cwd, the same shared-cwd // assumption every other .lock in index.js already makes. Split-brain // between two processes on the same host is impossible while the filesystem // works: ownership is granted only by winning an O_EXCL create of the lock // file, and a holder keeps its ownership only while its heartbeat token stays // on disk — there is no other grant path to diverge from. // // SEMANTICS (all load-bearing): // - ELECTION: at start, and then every pollMs while a follower, the process // tries to win the lock. Winner → onBecameLeader() fires exactly once. // - FAILOVER on leader death: a follower that finds the lock held by a // provably dead owner (ESRCH, zombie, recycled PID via start ticks) // steals it on its next poll — with the default pollMs the scheduler // pause on a leader crash is at most one poll interval plus the steal // itself (near-instant on Linux where /proc liveness is readable). The // mutex's staleAfterMs TTL (default 12000ms) is checked BEFORE the PID // probes (isOwnerStale tests it first), so the steal fires both for // deaths the PID probes cannot see (non-Linux, hidepid) and for a live // holder whose heartbeat has stalled past the TTL — the blocked-event- // loop DEPOSED case below; on a pm2 // restart the restarting process itself re-contends immediately at boot. // - GRACEFUL SHUTDOWN: releaseLeadership() drops the lock (token-checked, // never unlinks a foreign owner's lock) so a pm2 cluster reload's // incoming workers can win leadership while the old process drains its // in-flight job — the scheduler's per-job run-claim and the agent pump's // DB-atomic claims make that brief overlap safe. // - FAIL-OPEN on election-machinery failure: if the lock location is not // writable (probed with a throwaway file next to the lock), the election // cannot arbitrate, and refusing to elect would silently pause every // schedule fleet-wide. Instead every process becomes an ACTING leader // (today's pre-fix behavior: each runs its worker and pump, caps degrade // to per-process) and logs ONE loud warning. Availability beats the // resource cap. A fail-open process stays fail-open for its lifetime (no // re-election attempts, so a healed filesystem cannot multiply leaders // mid-flight); the next process restart re-elects properly. A transient // create error with a still-writable directory is NOT fail-open: it is // retried on the next poll like ordinary contention, so the election // self-heals. // - DEPOSED holders (only possible when a holder's event loop is blocked // past the TTL): the mutex detects the theft on its next heartbeat tick, // logs one loud error and stops renewing; the deposed process cannot be // demoted from outside the mutex API and keeps serving alongside the new // leader — the same bounded, documented fail-open state — until pm2 // restarts it. The new leader arbitrates the lock from then on. // // NOT reentrant and not re-acquirable: releaseLeadership() is terminal for // this instance (callers release exactly once, in their shutdown path). const fs = require("fs"); const { createCrossProcessOperationMutex } = require("./cross-process-mutex"); const DEFAULT_HEARTBEAT_MS = 3000; const DEFAULT_STALE_MS = 12000; const DEFAULT_POLL_MS = 5000; function positiveInt(value, fallback) { const n = Number(value); return Number.isInteger(n) && n > 0 ? n : fallback; } /** * Starts the leader election for one lock file. * * @param {object} options * @param {string} options.lockFilePath absolute lock file path (shared cwd) * @param {string} [options.label] log prefix (default "[scheduler-leader]") * @param {number} [options.heartbeatMs] held-lock refresh interval (default 3000) * @param {number} [options.staleAfterMs] steal TTL fallback for ambiguous * owner deaths (default 12000) * @param {number} [options.pollMs] follower re-election cadence; also the * upper bound of the crash failover * window (default 5000) * @param {Function} [options.onBecameLeader] called once when this process * wins (immediately, or on a later * poll after failover); also called * for the fail-open acting leader. * @returns {{ isLeader: () => boolean, role: () => string, * releaseLeadership: () => void }} * isLeader() is true for both the elected leader and the fail-open acting * leader (both run the per-process machinery). releaseLeadership() is * idempotent and terminal; it is a safe no-op for a process that never won. */ function startSchedulerLeaderElection(options) { const opts = options || {}; const lockFilePath = String(opts.lockFilePath || ""); if (!lockFilePath) { throw new Error("startSchedulerLeaderElection: lockFilePath is required"); } const label = String(opts.label || "[scheduler-leader]"); const heartbeatMs = positiveInt(opts.heartbeatMs, DEFAULT_HEARTBEAT_MS); const staleAfterMs = positiveInt(opts.staleAfterMs, DEFAULT_STALE_MS); const pollMs = positiveInt(opts.pollMs, DEFAULT_POLL_MS); const onBecameLeader = typeof opts.onBecameLeader === "function" ? opts.onBecameLeader : () => { }; const mutex = createCrossProcessOperationMutex({ label, lockFilePath, heartbeatMs, staleAfterMs, }); let role = "pending"; // "leader" | "follower" | "leader-failopen" | "released" let pollTimer = null; let releaseFn = null; let released = false; function stopPolling() { if (pollTimer) { clearInterval(pollTimer); pollTimer = null; } } // The election can only arbitrate while the lock location is writable. // Probed with a throwaway sibling file — never the lock file itself — so a // probe cannot disturb a live owner. A failed write is the fail-open // classification (the fs is durably broken for lock files here); a // successful write followed by a failed unlink still proves writability. function lockLocationWritable() { const probePath = `${lockFilePath}.probe`; try { fs.writeFileSync(probePath, String(process.pid), "utf8"); } catch (_) { return false; } try { fs.unlinkSync(probePath); } catch (_) { } return true; } function becomeLeader(newRole, release) { role = newRole; stopPolling(); releaseFn = release; try { onBecameLeader(); } catch (err) { // The machinery callbacks own their error handling; a throwing callback // must not crash the boot path that started the election. console.error(`${label} onBecameLeader callback failed: ${err && err.message}`); } } // Fail-open: every process runs the machinery with today's (pre-fix) // per-process scoping. Loud, once — this is a degraded deployment signal, // not a silent fallback. function becomeFailOpenLeader(reason) { console.warn( `${label} leader election unavailable (${reason}) — FAIL-OPEN: falling back to per-process ` + `scheduler machinery in EVERY worker (backup/agent concurrency caps degrade to ` + `per-process) until the lock location ${lockFilePath} is writable and processes restart` ); becomeLeader("leader-failopen", () => { }); } // The same terminal fail-open posture as becomeFailOpenLeader (every process // an acting leader, ONE loud warn, no re-election) with an ACCURATE // diagnosis: the lock path itself cannot be claimed and NO other process // holds leadership — the operator must fix the path, not hunt a phantom // leader. function becomeUnusableLockLeader(reason) { console.warn( `${label} scheduler leader lock path is not usable: ${lockFilePath} ${reason} — ` + `remove or fix it, then restart. FAIL-OPEN: falling back to per-process ` + `scheduler machinery in EVERY worker (backup/agent concurrency caps degrade ` + `to per-process) until it is fixed and processes restart` ); becomeLeader("leader-failopen", () => { }); } // adpanel:scheduler-leader-lock-classification — an EEXIST from the mutex // does NOT prove another process is the leader: the lock PATH itself can be // unclaimable while the surrounding directory stays writable (the probe // above only exercises a SIBLING file). A directory at the lock path — or // any non-regular entry, or a dangling symlink the mutex's staleness // fallback cannot see (it stats THROUGH the link and reads ENOENT) — makes // every O_EXCL create fail forever and every steal fail with it: before // this classification every worker stayed "follower" for its whole lifetime, // logging "another process is the leader" about a leader that does not // exist — a fleet-wide livelock (no scheduler machinery anywhere, the // fail-open arm never reached) with a false diagnostic. So a null // tryAcquire with a writable location is classified from stat evidence // only: // - the entry at the lock path is not a regular file (directory, fifo, // socket, device, dangling symlink) → UNUSABLE; // - a regular file whose mtime aged past staleAfterMs → the mutex's // isOwnerStale falls back to exactly that mtime when an owner record is // unreadable/unparseable, and its stale-steal ran inside THIS tryAcquire // call and still failed → UNUSABLE (an owner that can be neither // verified nor stolen is not a leader). // UNUSABLE takes the terminal fail-open posture with the accurate message // above. Everything ambiguous stays the ordinary follower path, // byte-identical: a vanished path (the next poll's create decides), a fresh // mtime (a live owner — its heartbeat renews mtime on every tick well // inside the TTL — or the mutex's mid-create window). Unusable is terminal, // so it is entered only on positive evidence. The mutex's grant/steal // semantics are untouched: this reads stat metadata only — no lock content, // no /proc, no O_EXCL re-implementation (the wiring test pins that // boundary). function describeLockEntryKind(st) { if (st.isDirectory()) return "a directory"; if (st.isFIFO()) return "a FIFO"; if (st.isSocket()) return "a socket"; if (st.isBlockDevice()) return "a block device"; if (st.isCharacterDevice()) return "a character device"; return "not a regular file"; } // Returns the reason phrase (composed after the lock path in the warn) when // the lock path is POSITIVELY unclaimable, or null when the null result is // ordinary contention or transient (the follower path decides). function classifyUnclaimableLock() { let st; try { st = fs.lstatSync(lockFilePath); } catch (_) { return null; // gone between the EEXIST and this check: the next poll's create decides } if (st.isSymbolicLink()) { try { st = fs.statSync(lockFilePath); // reads/writes/unlink all follow the link: classify its target } catch (_) { // Dangling symlink: O_EXCL keeps failing on the link itself while the // mutex's staleness fallback (which stats THROUGH the link) can never // see it — such a lock would never be stolen. Positively unclaimable. return "is a dangling symbolic link (its target is missing)"; } } if (!st.isFile()) { return `is ${describeLockEntryKind(st)}`; } // Regular file. The mutex judges an owner record it cannot read or parse // by the file's mtime (its isOwnerStale fallback), and a live owner's // heartbeat renews mtime on every tick — so mtime age is the same // evidence the mutex just used inside THIS tryAcquire call. Aged past the // TTL means the stale-steal ran and still failed to claim the path. let mtimeMs; try { mtimeMs = fs.statSync(lockFilePath).mtimeMs; } catch (_) { return null; // vanished mid-classification: transient } if (Date.now() - mtimeMs <= staleAfterMs) return null; // fresh: held (a live owner or the mid-create window) return `holds a lock record that cannot be verified and could not be stolen (stale past ${staleAfterMs}ms)`; } function attempt() { if (role === "leader" || role === "leader-failopen" || role === "released") return; let release = null; try { // The mutex's contract: tryAcquire never throws — a release function on // a won O_EXCL create (including a stale steal of a provably dead // owner), null on contention or on an fs error it has already logged. release = mutex.tryAcquire(); } catch (err) { // Defensive: outside the documented contract. Classify via the probe // like a null result instead of crashing the caller's boot path. console.error(`${label} unexpected election error: ${err && err.message}`); release = null; } if (release) { becomeLeader("leader", release); return; } if (!lockLocationWritable()) { becomeFailOpenLeader(`lock location ${lockFilePath} is not writable`); return; } const unclaimableReason = classifyUnclaimableLock(); if (unclaimableReason) { becomeUnusableLockLeader(unclaimableReason); return; } // Writable location, claimable lock path, no lock won = ordinary // contention (a live leader, a steal race we lost, or a transient fs // error the next poll retries) — every unusable shape was classified and // returned above. if (role !== "follower") { role = "follower"; console.log(`${label} another process is the leader; this worker will take over on its next poll if it dies (every ${pollMs}ms)`); } if (!pollTimer) { pollTimer = setInterval(attempt, pollMs); // A follower must never keep a pm2 worker alive just by waiting. if (typeof pollTimer.unref === "function") pollTimer.unref(); } } function releaseLeadership() { if (released) return; // idempotent: the shutdown path can run twice released = true; stopPolling(); role = "released"; if (releaseFn) { const fn = releaseFn; releaseFn = null; // The mutex's release is token-checked (never unlinks a lock this // holder does not own — e.g. after a deposed theft) and swallows its // own fs errors; it cannot throw. fn(); } } attempt(); return { isLeader: () => role === "leader" || role === "leader-failopen", role: () => role, releaseLeadership, }; } module.exports = { startSchedulerLeaderElection };