"use strict"; // Structure pins for adpanel:scheduler-worker-leader — the pm2-cluster leader // election that runs the per-process scheduler machinery (the BullMQ worker + // QueueEvents, and the AI agent job pump) in exactly ONE process per host. // // index.js is a ~56k-line application bundle (module side effects, DB and // network at require time — never require() it from a test), so these tests // pin the wiring structurally on well-anchored source windows, matching the // convention of tests/scheduler-redis-decouple.test.js. // // The regressions each pin exists to prevent: // 1. the worker (or the AI agent pump) being constructed in every process // again — the fleet-wide in-process caps (SCHEDULER_MAX_CONCURRENT_ // BACKUPS, AI_AGENT_JOB_CONCURRENCY) would silently degrade to // per-process 2 x N on real multi-instance installs // (scripts/generate-ecosystem.sh: INSTANCES = cores - 2, regenerated on // every boot by scripts/adpanel-runtime.sh); // 2. the queue CLIENT becoming leader-gated — scheduler routes // (create/delete/list/status) run in every process and call // schedulerQueue directly, so a leader-gated client would 503 the // routes on N-1 of N workers; // 3. the leader lock never being released on graceful shutdown (a pm2 // reload would pause all scheduled work for the whole drain); // 4. the election becoming conditional on SCHEDULER_ENABLED — the agent // pump must be elected even with the BullMQ scheduler off (interactive // chats enqueue agent jobs regardless). const test = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const path = require("node:path"); const ROOT = path.join(__dirname, ".."); const INDEX_SRC = fs.readFileSync(path.join(ROOT, "index.js"), "utf8"); const LEADER_SRC = fs.readFileSync(path.join(ROOT, "utils", "scheduler-leader.js"), "utf8"); function windowBetween(src, startAnchor, endAnchor, label) { const start = src.indexOf(startAnchor); assert.notStrictEqual(start, -1, `${label}: start anchor not found: ${startAnchor}`); const end = src.indexOf(endAnchor, start + startAnchor.length); assert.notStrictEqual(end, -1, `${label}: end anchor not found after start: ${endAnchor}`); return src.slice(start, end); } // ─── 1. The worker + QueueEvents are leader-only; the queue client is not ──── test("the BullMQ Worker and QueueEvents are constructed inside the leader-only initializeScheduler", () => { assert.strictEqual( (INDEX_SRC.match(/async function initializeScheduler\(/g) || []).length, 1, "the leader-only machinery function must be defined exactly once" ); const bootIdx = INDEX_SRC.indexOf("schedulerLeaderElection = startSchedulerLeaderElection({"); assert.notStrictEqual(bootIdx, -1, "the boot must start the leader election"); const fnIdx = INDEX_SRC.indexOf("async function initializeScheduler() {"); const workerAt = INDEX_SRC.indexOf('schedulerWorker = new Worker("adpanel-scheduler"'); const queueEventsAt = INDEX_SRC.indexOf('schedulerQueueEvents = new QueueEvents("adpanel-scheduler"'); assert.ok(fnIdx !== -1 && workerAt > fnIdx, "the Worker construction must live in initializeScheduler (leader-only)"); assert.ok(queueEventsAt > fnIdx, "the QueueEvents construction must live in initializeScheduler (leader-only)"); // initializeScheduler is called ONLY from the election's onBecameLeader // callback: its only call site sits between the election start and the end // of the boot wiring, inside the SCHEDULER_ENABLED gate. const callSites = []; let at = INDEX_SRC.indexOf("await initializeScheduler();"); while (at !== -1) { callSites.push(at); at = INDEX_SRC.indexOf("await initializeScheduler();", at + 1); } assert.strictEqual(callSites.length, 1, "initializeScheduler must have exactly one call site"); assert.ok( callSites[0] > bootIdx, "the only initializeScheduler call must come from the leader-election boot wiring, not an ungated boot path" ); }); test("the queue CLIENT is process-wide: constructed in a separate function called for every boot, outside onBecameLeader", () => { assert.strictEqual( (INDEX_SRC.match(/async function initializeSchedulerQueueClient\(/g) || []).length, 1, "the queue-client function must be defined exactly once" ); const fnIdx = INDEX_SRC.indexOf("async function initializeSchedulerQueueClient() {"); const queueAt = INDEX_SRC.indexOf('schedulerQueue = new Queue("adpanel-scheduler"'); assert.ok(fnIdx !== -1 && queueAt > fnIdx, "the Queue client construction must live in initializeSchedulerQueueClient"); const bootIdx = INDEX_SRC.indexOf("schedulerLeaderElection = startSchedulerLeaderElection({"); const clientCallAt = INDEX_SRC.indexOf("await initializeSchedulerQueueClient();"); assert.notStrictEqual(clientCallAt, -1, "the boot must start the queue client"); assert.ok( clientCallAt < bootIdx, "the queue client must start BEFORE/outside the election callback — routes construct it in every process" ); // The client's boot call keeps the scheduler gate (it is scheduler config), // while the election start below it is deliberately ungated. const clientWindow = windowBetween( INDEX_SRC, "if (SCHEDULER_ENABLED && SCHEDULER_REDIS_URL) {\n setTimeout(async () => {\n try {\n await initializeSchedulerQueueClient();", "schedulerLeaderElection = startSchedulerLeaderElection({", "boot queue-client window" ); assert.ok(clientWindow.includes("SCHEDULER_ENABLED"), "the queue client keeps its scheduler config gate"); }); test("the election starts independent of SCHEDULER_ENABLED, and the worker start inside onBecameLeader is additionally gated", () => { const bootWindow = windowBetween( INDEX_SRC, "schedulerLeaderElection = startSchedulerLeaderElection({", "// F6 crash recovery: roll back transfers orphaned by a previous crash/kill.", "boot election window" ); assert.ok(bootWindow.includes("lockFilePath: path.join(__dirname, \"scheduler-leader.lock\")"), "the leader lock must live in the shared panel cwd"); assert.doesNotMatch(bootWindow, /startLeaderAiAgentJobPumpPoll\(|agentRuntime\.start\(/, "the Scheduler leader must not start the Agent worker"); const workerGateAt = bootWindow.indexOf("if (SCHEDULER_ENABLED && SCHEDULER_REDIS_URL) {"); const workerCallAt = bootWindow.indexOf("await initializeScheduler();"); assert.ok(workerGateAt !== -1 && workerCallAt > workerGateAt, "the worker start must remain gated by SCHEDULER_ENABLED && SCHEDULER_REDIS_URL inside onBecameLeader"); }); // ─── 2. The AI agent pump runs only in the leader ──────────────────────────── test("Agent reconciliation is independent of Scheduler leadership and only the SQL lock holder pumps jobs", () => { assert.doesNotMatch(INDEX_SRC, /function isSchedulerLeaderProcess\(/, "Agent must not use the old web-worker leadership gate"); assert.strictEqual((INDEX_SRC.match(/agentRuntime\.start\(\)/g) || []).length, 1); assert.ok(INDEX_SRC.indexOf("agentRuntime.start()") < INDEX_SRC.indexOf("schedulerLeaderElection = startSchedulerLeaderElection({")); assert.doesNotMatch(INDEX_SRC, /\b(?:createServerAgentJobPump|scheduleAiAgentPump|enqueueAiAgentJob)\s*\(/); const worker = fs.readFileSync(require.resolve("../AgentWorker/worker"), "utf8"); const lockAt = worker.indexOf("SELECT GET_LOCK(?, 0)"); const verifyAt = worker.indexOf("SELECT IS_USED_LOCK(?) = CONNECTION_ID()"); const pumpAt = worker.indexOf("await Promise.all([pumpLive(), pumpBackground()]);"); assert.ok(lockAt >= 0 && lockAt < verifyAt && verifyAt < pumpAt); assert.match(worker, /if \(Number\(lock\.acquired\) !== 1\) throw/); assert.match(worker, /if \(Number\(ownership\.owned\) !== 1/); }); // ─── 3. Graceful shutdown releases leadership first ────────────────────────── test("shutdownScheduler releases leadership before closing BullMQ; panel shutdown separately closes Agent RPC", () => { const body = windowBetween(INDEX_SRC, "async function shutdownScheduler() {", "if (schedulerWorker) {", "shutdown head"); assert.ok( body.includes("schedulerLeaderElection.releaseLeadership()"), "graceful shutdown must release leadership so a pm2 reload fails over instantly" ); assert.doesNotMatch(body, /stopLeaderAiAgentJobPumpPoll\(|agentRuntime\.stop\(/); assert.match(INDEX_SRC, /await agentRuntime\.stop\(\)\.catch\(/); }); // ─── 4. One home, honest comments ───────────────────────────────────────────── test("the election has ONE module home and ONE require/call site; the false instances: 1 premise is gone", () => { assert.strictEqual( LEADER_SRC.split("function startSchedulerLeaderElection(").length - 1, 1, "utils/scheduler-leader.js must be the ONE home of the election" ); assert.strictEqual( (INDEX_SRC.match(/require\("\.\/utils\/scheduler-leader"\)/g) || []).length, 1, "index.js must require the election module exactly once" ); assert.strictEqual( (INDEX_SRC.match(/startSchedulerLeaderElection\(\{/g) || []).length, 1, "exactly one election start (the boot wiring) — no second election path" ); // The starvation guard's premise comment must cite the leader election and // the scripts evidence, not the false "instances: 1" justification. const starvationWindow = windowBetween( INDEX_SRC, "adpanel:scheduler-backup-starvation — the queue \"adpanel-scheduler\" runs", "function resolveSchedulerMaxConcurrentBackups", "starvation premise" ); assert.ok( starvationWindow.includes("adpanel:scheduler-worker-leader"), "the fleet-wide cap must be justified by the leader election" ); assert.ok( starvationWindow.includes("generate-ecosystem.sh") && starvationWindow.includes("cores - 2"), "the comment must cite the real multi-instance evidence" ); assert.ok( !starvationWindow.includes("instances: 1"), "the false 'instances: 1' premise must be gone from the cap's justification" ); // The boot wiring documents the failover + fail-open semantics. const bootWindow = windowBetween( INDEX_SRC, "adpanel:scheduler-worker-leader — leader election, DELIBERATELY", "schedulerLeaderElection = startSchedulerLeaderElection({", "boot election comment" ); assert.ok(bootWindow.includes("INDEPENDENT of SCHEDULER_ENABLED"), "the election's independence from the scheduler gate must be documented"); assert.ok(bootWindow.includes("stale-steals"), "the crash failover must be documented"); assert.ok(bootWindow.includes("fail-open"), "the fail-open degradation must be documented"); }); test("the election module composes the shared cross-process mutex (no forked lock internals)", () => { assert.ok( LEADER_SRC.includes('require("./cross-process-mutex")') && LEADER_SRC.includes("createCrossProcessOperationMutex"), "the election must acquire exclusion through the ONE cross-process mutex factory" ); const code = LEADER_SRC.split("\n").filter((line) => !line.trim().startsWith("//")).join("\n"); assert.ok( !code.includes("openSync(") && !code.includes("/proc/") && !code.includes("startTicks") && !code.includes("readFileSync(lockFilePath"), "the election must not re-implement O_EXCL owner records / stale-steal / /proc liveness — the mutex owns those primitives" ); assert.ok(code.includes("tryAcquire()"), "leadership is won through the mutex's public tryAcquire"); assert.ok(code.includes("FAIL-OPEN"), "the fail-open fallback must be loud on the wire"); });