Files
Kelx/tests/scheduler-create-deadline.test.js
T
2026-11-30 16:32:37 +00:00

845 lines
40 KiB
JavaScript

"use strict";
// Behavioral + structural pins for the create route's Redis deadline races
// (adpanel:scheduler-create-deadline).
//
// Finding: every Redis await inside withSchedulerCreateLock (the quota's
// fleet pagination, the repeatable scan, the queue add) was a BARE await.
// During a Redis outage node-redis queues commands and the BullMQ client
// retries for minutes, so "Create Task" hung server-side well past the
// browser's 20s abort (bot.js fetchWithServerActionToken timeoutMs: 20000):
// the user saw a failure, the handler stayed inside the cross-process lock
// (the mutex heartbeat kept proving liveness, so nothing stole it), and the
// hung add COMMITTED when Redis recovered — the user's retried click then
// minted a DUPLICATE once-task (once-tasks have no idempotency key; only
// repeatables dedupe, via their name JSON).
//
// Fix: each await is raced against SCHEDULER_CREATE_REDIS_DEADLINE_MS (15s —
// below the browser's 20s so the server answers first; ~1.5x the worst
// healthy cost of the 50-page fleet scan) through the shared
// raceWithDeadline helper; a miss throws a tagged error that the route's
// catch maps to a 503 with a path-free message, and — the point of the fix —
// withSchedulerCreateLock's runExclusive finally RELEASES the lock on that
// throw. The add is the committing step: a raced-out add that settles LATE
// (Redis recovered) is compensating-removed (once-job → job.remove();
// repeatable → schedulerQueue.removeRepeatableByKey(job.repeatJobKey), whose
// Lua removes the schedule AND the next delayed iteration atomically, so NO
// schedule survives); a late reject committed nothing and is swallowed. The
// reads commit nothing: both sit BEFORE the quota check and the add, so a
// timed-out read means the add is never reached.
//
// adpanel:scheduler-create-informed-compensator — the compensator is
// INFORMED, not unconditional: the route snapshots the repeatable keys
// already in Redis (from the SAME raced getRepeatableJobs read, pre-add,
// inside the per-server create lock) and threads the set into the
// compensator. A late-settling repeatable whose key was in the snapshot
// re-asserted a schedule that PRE-EXISTED the attempt (the repeat key
// hashes the job name + repeat options, so a byte-identical re-create
// re-derives the SAME key and BullMQ's override re-stamps that entry —
// addRepeatableJob-2.lua) and must SURVIVE the 503; only a key absent from
// the snapshot was minted by this request and is removed.
//
// Technique (the scheduler-once-timestamp / scheduler-timezone harness
// precedent): the REAL helper block, the REAL withSchedulerCreateLock and
// the REAL locked region + catch arm are sliced from index.js — every anchor
// unique — and composed in route order inside a real async function with the
// route's in-scope bindings injected, then EXECUTED against a stub queue and
// response. The lock is the REAL cross-process mutex (utils/cross-process-
// mutex.js, pure fs), so the release assertions below drive the shipped
// lock machinery, not a mimic. Tests pass a short deadline through the
// helper's test seam (deadlineMs parameter; production passes the 15s
// constant — pinned textually below) so an outage is simulated in
// milliseconds.
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 crypto = require("node:crypto");
const ROOT = path.join(__dirname, "..");
const INDEX_SRC = fs.readFileSync(path.join(ROOT, "index.js"), "utf8");
function sliceFrom(source, startMarker, endMarker, label) {
const start = source.indexOf(startMarker);
assert.notStrictEqual(start, -1, `${label}: start marker not found: ${startMarker}`);
const end = source.indexOf(endMarker, start);
assert.notStrictEqual(end, -1, `${label}: end marker not found after start: ${endMarker}`);
return source.slice(start, end);
}
function sliceInclusive(source, startMarker, endMarker, label) {
const start = source.indexOf(startMarker);
assert.notStrictEqual(start, -1, `${label}: start marker not found: ${startMarker}`);
const end = source.indexOf(endMarker, start);
assert.notStrictEqual(end, -1, `${label}: end marker not found after start: ${endMarker}`);
return source.slice(start, end + endMarker.length);
}
const realStreak = require("../utils/scheduler-failure-streak");
const { schedulerJobBelongsToServer, resolveSchedulerRepeatablesForServer } = require("../services/scheduler-task-scope");
const { createCrossProcessOperationMutex } = require("../utils/cross-process-mutex");
// ---------------------------------------------------------------------------
// The REAL slices
// ---------------------------------------------------------------------------
// The helper block: deadline constant + unavailable message + the race and
// compensating-removal helpers (one contiguous block after
// withSchedulerCreateLock).
const helperBlock = sliceFrom(
INDEX_SRC,
"const SCHEDULER_CREATE_REDIS_DEADLINE_MS = 15000;",
"\n// Server-side twin of the scheduler UI's interval floor",
"create-deadline helper block"
);
// The REAL cross-process lock the create route serializes through.
const lockSlice = sliceFrom(
INDEX_SRC,
"async function withSchedulerCreateLock(serverName, fn) {",
"\n// adpanel:scheduler-create-deadline",
"withSchedulerCreateLock"
);
// The REAL locked region: from the withSchedulerCreateLock call through the
// quota reads, the three queue.add sites and the success response.
const lockedRegion = sliceFrom(
INDEX_SRC,
"await withSchedulerCreateLock(canonicalServer, async () => {",
"\n } catch (err) {",
"create route locked region"
);
// The REAL catch arm: the tagged-503 mapping plus the bare 500 fallback.
const catchRegion = sliceInclusive(
INDEX_SRC,
" } catch (err) {\n // adpanel:scheduler-create-deadline — the deadline race's tagged error",
'return res.status(500).json({ ok: false, error: "internal error" });',
"create route catch arm"
);
// The REAL scheduleToCron (same window the timezone/interval-floor harnesses
// use) so the repeatable-path tests convert schedules with the shipped code.
const { scheduleToCron } = new Function(
sliceFrom(INDEX_SRC, "const SCHEDULER_MIN_INTERVAL_SECONDS", "\nasync function shutdownScheduler(", "scheduleToCron") +
"\nreturn { scheduleToCron };"
)();
// ---------------------------------------------------------------------------
// The composed flow harness
// ---------------------------------------------------------------------------
const TEST_DEADLINE_MS = 100;
const flush = () => new Promise((resolve) => setImmediate(() => setImmediate(resolve)));
function makeCreateFlowHarness({
fetchJobsImpl = async () => [],
getRepeatableJobsImpl = async () => [],
addImpl = async (name, data, opts) => ({ id: `job-${1}`, name, data, opts }),
lookupRequest = async () => null,
now = Date.now,
removeRepeatableByKeyImpl = async () => 0,
route = {},
} = {}) {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-sched-deadline-"));
const lockFilePath = path.join(tmpDir, "scheduler-quota-srv01.lock");
const warnings = [];
const errors = [];
const consoleStub = {
log() {},
warn(...args) { warnings.push(args.map(String).join(" ")); },
error(...args) { errors.push(args.map(String).join(" ")); },
};
const schedulerQueue = {
adds: [],
add: async (name, data, opts) => {
schedulerQueue.adds.push({ name, data, opts });
return addImpl(name, data, opts);
},
getDeduplicationJobId: lookupRequest,
getRepeatableJobs: getRepeatableJobsImpl,
removeRepeatableByKey: async (key) => {
schedulerQueue.removedKeys.push(key);
return removeRepeatableByKeyImpl(key);
},
removedKeys: [],
};
// The REAL helper block, evaluated with the REAL raceWithDeadline and THIS
// harness's queue + console (the compensating removal dials the queue and
// logs loudly through them).
const helpers = new Function(
"raceWithDeadline", "schedulerQueue", "console",
helperBlock + "\nreturn { SCHEDULER_CREATE_REDIS_DEADLINE_MS, SCHEDULER_CREATE_UNAVAILABLE_MESSAGE, awaitSchedulerCreateRedisStep, makeSchedulerCreateUnavailableError };"
)(realStreak.raceWithDeadline, schedulerQueue, consoleStub);
// Production shape: the route calls the helper as (promise, committingServer)
// or (promise, committingServer, preAddRepeatableKeys — the repeatable
// adds' informed-compensator snapshot) and the default deadline is the 15s
// constant. The harness partial-applies ONLY the test deadline — the
// race/throw/compensate logic is the shipped code.
const awaitSchedulerCreateRedisStep = helpers.awaitSchedulerCreateRedisStep;
// The REAL lock, over a fresh per-harness mutex Map and temp lock directory.
const schedulerQuotaMutexes = new Map();
const withSchedulerCreateLock = new Function(
"createCrossProcessOperationMutex", "path", "schedulerQuotaMutexes", "__dirname",
lockSlice + "\nreturn withSchedulerCreateLock;"
)(createCrossProcessOperationMutex, path, schedulerQuotaMutexes, tmpDir);
const activities = [];
const responses = [];
const res = {
status(code) {
return { json(payload) { responses.push({ code, payload }); return payload; } };
},
json(payload) { responses.push({ code: 200, payload }); return payload; },
};
// The REAL locked region + REAL catch arm, composed in route order inside
// the route's try/catch shape, with the route's in-scope bindings injected.
const flowFn = new Function(
"serverEntry", "canonicalServer", "req", "res", "email", "user",
"actionType", "payload", "scheduleType", "scheduleValue", "scheduleTime",
"timezone", "taskName", "scheduledTimestamp", "autoApproveFileEdits",
"schedulerQueue", "fetchAllSchedulerJobsInStates", "resolveSchedulerMaxSchedules", "schedulerJobBelongsToServer", "resolveSchedulerRepeatablesForServer",
"scheduleToCron", "recordActivity", "getRequestIp", "crypto", "isAgentSchedule",
"withSchedulerCreateLock", "awaitSchedulerCreateRedisStep", "console",
"SCHEDULER_CREATE_REDIS_DEADLINE_MS", "SCHEDULER_CREATE_UNAVAILABLE_MESSAGE", "createDeadlineAt", "makeSchedulerCreateUnavailableError", "Date",
`"use strict";
return (async () => {
try {
${lockedRegion}
${catchRegion}
}
})();`
);
const flowArgs = () => [
route.serverEntry ?? { id: 7, name: "srv01" },
"srv01",
{ headers: route.requestKey === undefined ? {} : { "idempotency-key": route.requestKey } },
res,
"creator@example.com",
{ id: 42 },
route.actionType ?? "console_command",
route.payload ?? { command: "say hi" },
route.scheduleType ?? "once",
route.scheduleValue ?? null,
route.scheduleTime ?? null,
route.timezone ?? null,
route.taskName ?? "Probe",
route.scheduledTimestamp,
false,
schedulerQueue,
fetchJobsImpl,
() => route.maxSchedules ?? 50,
schedulerJobBelongsToServer,
resolveSchedulerRepeatablesForServer,
scheduleToCron,
(serverName, type, detail, userName, ip) => activities.push({ serverName, type, detail, userName, ip }),
() => "127.0.0.1",
crypto,
require("../AgentWorker/feature-http").isAgentSchedule,
withSchedulerCreateLock,
awaitSchedulerCreateRedisStep,
consoleStub,
helpers.SCHEDULER_CREATE_REDIS_DEADLINE_MS,
helpers.SCHEDULER_CREATE_UNAVAILABLE_MESSAGE,
now() + TEST_DEADLINE_MS,
helpers.makeSchedulerCreateUnavailableError,
Object.assign(Date.bind(null), { now }),
];
return {
run: () => flowFn(...flowArgs()),
responses,
schedulerQueue,
activities,
warnings,
errors,
lockFilePath,
cleanup: () => { try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch { } },
UNAVAILABLE_MESSAGE: helpers.SCHEDULER_CREATE_UNAVAILABLE_MESSAGE,
};
}
// A never-settling promise: the simulated outage (node-redis queues commands
// while disconnected; the BullMQ client retries).
const hanging = () => new Promise(() => { });
// ---------------------------------------------------------------------------
// Behavioral: reads hang — 503 within the deadline, lock released, no add
// ---------------------------------------------------------------------------
test("the fleet-pagination read hanging answers 503 within the deadline, releases the lock, and never reaches the add", async () => {
const h = makeCreateFlowHarness({ fetchJobsImpl: hanging });
try {
const started = Date.now();
await h.run();
const elapsed = Date.now() - started;
assert.deepStrictEqual(h.responses, [
{ code: 503, payload: { ok: false, error: h.UNAVAILABLE_MESSAGE } },
], "exactly one path-free 503 (the browser's 20s abort must never beat the server's answer)");
assert.ok(elapsed >= TEST_DEADLINE_MS - 20 && elapsed < 5000, `the 503 must land at the deadline (${elapsed}ms), not minutes later`);
assert.strictEqual(h.schedulerQueue.adds.length, 0, "a timed-out read must abort before the add — the reads commit nothing");
assert.strictEqual(fs.existsSync(h.lockFilePath), false, "the deadline throw must release the cross-process lock (runExclusive's finally)");
assert.ok(h.warnings.some((w) => w.includes("deadline miss")), "the deadline miss is operator-visible");
} finally {
h.cleanup();
}
});
test("the repeatable scan hanging answers 503 within the deadline and never reaches the add", async () => {
const h = makeCreateFlowHarness({ getRepeatableJobsImpl: hanging });
try {
await h.run();
assert.deepStrictEqual(h.responses, [
{ code: 503, payload: { ok: false, error: h.UNAVAILABLE_MESSAGE } },
]);
assert.strictEqual(h.schedulerQueue.adds.length, 0, "the second read commits nothing either — no add, no compensation needed");
assert.strictEqual(fs.existsSync(h.lockFilePath), false, "the lock is released on the read deadline too");
} finally {
h.cleanup();
}
});
test("two quota reads share one budget and cannot start an add when it expires", async (t) => {
let clock = Date.now();
const fixture = makeCreateFlowHarness({
now: () => clock,
fetchJobsImpl: async () => { clock += 60; return []; },
getRepeatableJobsImpl: async () => { clock += 60; return []; },
});
t.after(fixture.cleanup);
await fixture.run();
assert.strictEqual(fixture.responses[0].code, 503);
assert.strictEqual(fixture.schedulerQueue.adds.length, 0);
});
test("only a verified recurrence consumes a current server's schedule quota", async (t) => {
const next = 1_700_000_000_000;
const template = { key: "legacy-repeat", name: JSON.stringify({ serverName: "srv01" }), next };
const fixture = makeCreateFlowHarness({
route: { maxSchedules: 1 },
getRepeatableJobsImpl: async () => [template],
});
t.after(fixture.cleanup);
fixture.schedulerQueue.repeat = Promise.resolve(require("bullmq").Repeat.prototype);
fixture.schedulerQueue.getJob = async () => undefined;
await fixture.run();
assert.equal(fixture.responses[0].code, 200, "an orphan is not a task of this server");
assert.equal(fixture.schedulerQueue.adds.length, 1);
fixture.schedulerQueue.getJob = async (id) => {
assert.equal(id, `repeat:${template.key}:${next}`);
return { repeatJobKey: template.key, opts: { prevMillis: next }, data: { serverName: "srv01", serverId: 7 } };
};
await fixture.run();
assert.equal(fixture.responses[1].code, 400);
assert.equal(fixture.responses[1].payload.current, 1);
assert.equal(fixture.schedulerQueue.adds.length, 1, "an owned legacy recurrence still consumes quota");
});
test("retrying a one-time create after its scheduled time reuses the admitted task", async (t) => {
let clock = Date.now();
const scheduledTimestamp = clock + 60_000;
const admitted = new Map();
const fixture = makeCreateFlowHarness({
now: () => clock,
route: { requestKey: "fixture-retry-key", scheduledTimestamp },
lookupRequest: async (key) => admitted.get(key),
addImpl: async (_name, _data, opts) => {
assert.match(opts.jobId, /^once-[a-f0-9]{64}$/);
assert.deepStrictEqual(opts.deduplication, { id: opts.jobId, ttl: 300000 });
admitted.set(opts.deduplication.id, opts.jobId);
return { id: opts.jobId };
},
});
t.after(fixture.cleanup);
await fixture.run();
clock = scheduledTimestamp + 1;
await fixture.run();
assert.strictEqual(fixture.responses[0].code, 200);
assert.deepStrictEqual(fixture.responses[1], { code: 200, payload: { ok: true, replayed: true, task: { id: fixture.responses[0].payload.task.id } } });
assert.strictEqual(fixture.schedulerQueue.adds.length, 1);
assert.strictEqual(fixture.activities.length, 1);
});
test("a one-time request that expires before the add cannot run now without a receipt", async (t) => {
let clock = Date.now();
const fixture = makeCreateFlowHarness({
now: () => clock,
route: { requestKey: "fixture-retry-key", scheduledTimestamp: clock + 10 },
fetchJobsImpl: async () => { clock += 20; return []; },
});
t.after(fixture.cleanup);
await fixture.run();
assert.deepStrictEqual(fixture.responses, [{ code: 400, payload: { ok: false, error: "Scheduled time must be in the future" } }]);
assert.strictEqual(fixture.schedulerQueue.adds.length, 0);
assert.strictEqual(fixture.activities.length, 0);
});
test("a released lock is immediately acquirable: a retry after a deadline miss proceeds normally", async () => {
// The point of the fix: the pre-fix hang kept the lock alive (heartbeat),
// wedging every contender for the same server behind a request the user
// had already seen fail.
let first = true;
const h = makeCreateFlowHarness({
fetchJobsImpl: async () => {
if (first) { first = false; return hanging(); }
return [];
},
});
try {
await h.run(); // deadline miss -> 503 + release
assert.deepStrictEqual(h.responses[0], { code: 503, payload: { ok: false, error: h.UNAVAILABLE_MESSAGE } });
await h.run(); // same mutex instance (the route's Map reuse), healthy reads
assert.strictEqual(h.responses[1].code, 200, "the retry must acquire the released lock and succeed");
assert.strictEqual(h.schedulerQueue.adds.length, 1, "the retried create reaches the add");
} finally {
h.cleanup();
}
});
// ---------------------------------------------------------------------------
// Behavioral: the add hangs — 503 now, compensating removal on a late settle
// ---------------------------------------------------------------------------
function makeLateAddHarness(route = {}, harnessOptions = {}) {
let settleAdd;
const addPromise = new Promise((resolve, reject) => { settleAdd = { resolve, reject }; });
const h = makeCreateFlowHarness({
route,
addImpl: () => addPromise,
...harnessOptions,
});
return { h, settleAdd };
}
test("the once-task add hanging answers 503 inside the lock window, then a LATE RESOLVE is compensated with job.remove()", async () => {
const { h, settleAdd } = makeLateAddHarness();
const removes = [];
try {
const flowPromise = h.run();
// Give the flow time to reach the add and race out at the deadline.
await new Promise((resolve) => setTimeout(resolve, TEST_DEADLINE_MS + 60));
assert.deepStrictEqual(h.responses, [
{ code: 503, payload: { ok: false, error: h.UNAVAILABLE_MESSAGE } },
], "the user is told the create failed");
assert.strictEqual(h.schedulerQueue.adds.length, 1, "the add was attempted (the compensating arm exists for exactly this case)");
assert.strictEqual(fs.existsSync(h.lockFilePath), false, "the lock is released even though the add is still in flight");
// Redis recovers: the raced-out add resolves LATE with a once-job
// (no repeatJobKey, no opts.repeat — BullMQ's plain Job shape).
settleAdd.resolve({
id: "late-once-1",
remove: async () => { removes.push("late-once-1"); return true; },
});
await flush();
assert.deepStrictEqual(removes, ["late-once-1"], "the task the user was told failed must not survive");
assert.deepStrictEqual(h.schedulerQueue.removedKeys, [], "a once-job has no schedule key — removeRepeatableByKey must not be used");
assert.ok(
h.warnings.some((w) => w.includes("removed its one-time task late-once-1")),
"the compensating removal logs loudly (operator-visible truth)"
);
await flowPromise;
} finally {
h.cleanup();
}
});
test("a LATE-RESOLVING REPEATABLE add is compensated with removeRepeatableByKey(job.repeatJobKey) — never job.remove() alone", async () => {
const removes = [];
const { h: h2, settleAdd } = makeLateAddHarness({ scheduleType: "seconds", scheduleValue: "30" });
try {
const flowPromise = h2.run();
await new Promise((resolve) => setTimeout(resolve, TEST_DEADLINE_MS + 60));
assert.strictEqual(h2.responses[0].code, 503);
assert.strictEqual(h2.schedulerQueue.adds.length, 1);
// BullMQ 5.78: a repeatable add resolves with the FIRST delayed ITERATION
// job carrying repeatJobKey (Repeat.updateRepeatableJob → createNextJob).
settleAdd.resolve({
id: "repeat:rk-abc-123:1730000000000",
repeatJobKey: "rk-abc-123",
opts: { repeat: { every: 30000, count: 1 } },
remove: async () => { removes.push("job.remove"); return true; },
});
await flush();
assert.deepStrictEqual(h2.schedulerQueue.removedKeys, ["rk-abc-123"],
"the schedule artifact must go — removeRepeatableByKey's Lua removes the repeatable entry AND the next delayed iteration atomically (job.remove() alone would leave the schedule alive)");
assert.deepStrictEqual(removes, [], "job.remove() must NOT run for a repeatable shape (it would only kill one iteration)");
assert.ok(
h2.warnings.some((w) => w.includes("removed its repeatable schedule") && w.includes("rk-abc-123")),
"the compensating removal logs loudly"
);
await flowPromise;
} finally {
h2.cleanup();
}
});
test("a late-resolving REPEATABLE whose key PRE-EXISTED the attempt (in the pre-add snapshot) is NOT removed — the re-assert of the live schedule lands intact, loudly logged", async () => {
// adpanel:scheduler-create-informed-compensator — the residual this closes:
// an unconditional compensator destroyed a schedule that was running fine
// before the attempt whenever the re-create was byte-identical (same name
// JSON + repeat options → the SAME repeat key) and the add settled late.
const preExistingRepeatables = [{ key: "rk-pre-1", name: '{"serverName":"srv01"}' }];
const { h, settleAdd } = makeLateAddHarness(
{ scheduleType: "seconds", scheduleValue: "30" },
{ getRepeatableJobsImpl: async () => preExistingRepeatables }
);
try {
const flowPromise = h.run();
await new Promise((resolve) => setTimeout(resolve, TEST_DEADLINE_MS + 60));
assert.strictEqual(h.responses[0].code, 503, "the user is told the re-create failed");
assert.strictEqual(h.schedulerQueue.adds.length, 1);
// Byte-identical re-create: BullMQ re-derives the SAME repeat key (name
// JSON + repeat opts → Repeat.getRepeatConcatOptions → hash), so the
// late settle carries exactly the key the pre-add snapshot held.
settleAdd.resolve({
id: "repeat:rk-pre-1:1730000000000",
repeatJobKey: "rk-pre-1",
opts: { repeat: { every: 30000, count: 2 } },
});
await flush();
assert.deepStrictEqual(h.schedulerQueue.removedKeys, [],
"the pre-existing schedule must survive: the late settle merely re-asserted it — removing it would silently destroy a working schedule because the 503 said 'failed'");
assert.ok(
h.warnings.some((w) => w.includes("already existed before this attempt") && w.includes("rk-pre-1") && w.includes("left intact")),
"the re-assert outcome is loud and operator-visible"
);
await flowPromise;
} finally {
h.cleanup();
}
});
test("a late-resolving REPEATABLE whose key is ABSENT from a NON-EMPTY pre-add snapshot is still removed — set membership decides, not snapshot presence", async () => {
const { h, settleAdd } = makeLateAddHarness(
{ scheduleType: "seconds", scheduleValue: "30" },
{ getRepeatableJobsImpl: async () => [{ key: "rk-other-server-or-task" }] }
);
try {
const flowPromise = h.run();
await new Promise((resolve) => setTimeout(resolve, TEST_DEADLINE_MS + 60));
assert.strictEqual(h.responses[0].code, 503);
settleAdd.resolve({
id: "repeat:rk-minted-7:1730000000000",
repeatJobKey: "rk-minted-7",
opts: { repeat: { every: 30000, count: 1 } },
});
await flush();
assert.deepStrictEqual(h.schedulerQueue.removedKeys, ["rk-minted-7"],
"a key the snapshot did not hold was minted by THIS request — the user was told it failed, so it is compensated exactly as before");
assert.ok(
h.warnings.some((w) => w.includes("removed its repeatable schedule") && w.includes("rk-minted-7")),
"the compensating removal still logs loudly"
);
await flowPromise;
} finally {
h.cleanup();
}
});
test("the once-task compensation is unchanged when repeatables pre-exist: the snapshot never reaches the once arm", async () => {
const removes = [];
const { h, settleAdd } = makeLateAddHarness(
{},
{ getRepeatableJobsImpl: async () => [{ key: "rk-pre-2", name: '{"serverName":"srv01"}' }] }
);
try {
const flowPromise = h.run();
await new Promise((resolve) => setTimeout(resolve, TEST_DEADLINE_MS + 60));
assert.strictEqual(h.responses[0].code, 503);
settleAdd.resolve({
id: "late-once-2",
remove: async () => { removes.push("late-once-2"); return true; },
});
await flush();
assert.deepStrictEqual(removes, ["late-once-2"],
"a once-task has no pre-existing identity to re-assert — job.remove() always compensates");
assert.deepStrictEqual(h.schedulerQueue.removedKeys, [],
"the pre-existing repeatable is never touched by a once-task's compensation");
await flowPromise;
} finally {
h.cleanup();
}
});
test("a LATE REJECT of the raced-out add commits nothing and is swallowed (the 503 was the truth)", async () => {
const { h, settleAdd } = makeLateAddHarness();
try {
const flowPromise = h.run();
await new Promise((resolve) => setTimeout(resolve, TEST_DEADLINE_MS + 60));
assert.strictEqual(h.responses[0].code, 503);
settleAdd.reject(new Error("connection reset after recovery"));
await flush();
assert.ok(
h.warnings.some((w) => w.includes("nothing was committed")),
"the late rejection is logged, not surfaced"
);
assert.deepStrictEqual(h.schedulerQueue.removedKeys, []);
assert.deepStrictEqual(h.errors, [], "a late reject must not surface as an error-level compensation failure");
await flowPromise;
} finally {
h.cleanup();
}
});
test("a late settle with no removable job object (BullMQ limit/endDate early return) compensates nothing and does not throw", async () => {
let settleAdd;
const addPromise = new Promise((resolve) => { settleAdd = { resolve }; });
const h = makeCreateFlowHarness({ addImpl: () => addPromise });
try {
const flowPromise = h.run();
await new Promise((resolve) => setTimeout(resolve, TEST_DEADLINE_MS + 60));
assert.strictEqual(h.responses[0].code, 503);
settleAdd.resolve(undefined);
await flush();
assert.ok(h.warnings.some((w) => w.includes("no removable job object")), "logged, not crashed");
assert.deepStrictEqual(h.schedulerQueue.removedKeys, []);
await flowPromise;
} finally {
h.cleanup();
}
});
// ---------------------------------------------------------------------------
// Behavioral: the success path is unchanged, and real failures keep the 500
// ---------------------------------------------------------------------------
test("the healthy once path is byte-identical: one add with the legacy opts, the exact 200 task shape, the activity entry", async () => {
const h = makeCreateFlowHarness();
try {
const before = Date.now();
await h.run();
assert.deepStrictEqual(h.responses, [
{
code: 200,
payload: {
ok: true,
task: { id: "job-1", name: "Probe", actionType: "console_command", scheduleType: "once", createdAt: h.responses[0].payload.task.createdAt },
},
},
]);
assert.deepStrictEqual(
Object.keys(h.responses[0].payload.task).sort(),
["actionType", "createdAt", "id", "name", "scheduleType"],
"the response shape is exactly the shipped one"
);
assert.ok(
h.responses[0].payload.task.createdAt >= before && h.responses[0].payload.task.createdAt <= Date.now(),
"createdAt is the route's Date.now()"
);
assert.strictEqual(h.schedulerQueue.adds.length, 1);
const { name, data, opts } = h.schedulerQueue.adds[0];
assert.strictEqual(name, "scheduled-task");
assert.strictEqual(data.serverName, "srv01");
assert.strictEqual(data.actionType, "console_command");
assert.equal(opts.jobId, undefined);
assert.ok(opts.delay >= 0 && opts.delay < 60000, "run-now delay");
assert.deepStrictEqual(
{ removeOnComplete: opts.removeOnComplete, removeOnFail: opts.removeOnFail },
{ removeOnComplete: { count: 50 }, removeOnFail: { count: 25 } },
"the once add's stored options are untouched by the race"
);
assert.deepStrictEqual(
h.activities.map((a) => a.type),
["scheduler_create"],
"the success path still records the activity"
);
assert.deepStrictEqual(h.schedulerQueue.removedKeys, [], "no compensating removal on success");
} finally {
h.cleanup();
}
});
test("the healthy interval retains its definition and counts and assigns a new instance key", async () => {
const h = makeCreateFlowHarness({ route: { scheduleType: "seconds", scheduleValue: "30" } });
try {
await h.run();
assert.strictEqual(h.responses[0].code, 200);
assert.strictEqual(h.responses[0].payload.task.scheduleType, "seconds");
const { name, data, opts } = h.schedulerQueue.adds[0];
const nameData = JSON.parse(name);
assert.strictEqual(nameData.serverName, "srv01");
assert.strictEqual(nameData.serverId, data.serverId);
assert.strictEqual(nameData.name, "Probe");
assert.strictEqual(nameData.actionType, "console_command");
assert.strictEqual(nameData.payloadHash, crypto.createHash("sha256").update(JSON.stringify({ command: "say hi" })).digest("hex"));
assert.strictEqual(data.serverName, "srv01");
const { key, ...repeat } = opts.repeat;
assert.match(key, /^[a-f0-9-]{36}$/);
assert.deepStrictEqual(repeat, { every: 30000 });
assert.deepStrictEqual(
{ removeOnComplete: opts.removeOnComplete, removeOnFail: opts.removeOnFail },
{ removeOnComplete: { count: 20 }, removeOnFail: { count: 10 } }
);
} finally {
h.cleanup();
}
});
test("a REAL Redis failure (rejection, not a hang) keeps the bare 500 arm — the race must not mask errors into 503", async () => {
const h = makeCreateFlowHarness({ fetchJobsImpl: async () => { throw new Error("redis connection lost"); } });
try {
await h.run();
assert.deepStrictEqual(h.responses, [
{ code: 500, payload: { ok: false, error: "internal error" } },
], "the underlying error propagates unchanged to the existing 500 arm");
assert.strictEqual(h.schedulerQueue.adds.length, 0);
} finally {
h.cleanup();
}
});
test("the add itself failing (not hanging) keeps the 500 arm and compensates nothing", async () => {
const h = makeCreateFlowHarness({ addImpl: async () => { throw new Error("bullmq add failed"); } });
try {
await h.run();
assert.deepStrictEqual(h.responses, [
{ code: 500, payload: { ok: false, error: "internal error" } },
]);
assert.deepStrictEqual(h.schedulerQueue.removedKeys, []);
assert.strictEqual(fs.existsSync(h.lockFilePath), false, "and the lock is released through the same finally");
} finally {
h.cleanup();
}
});
// ---------------------------------------------------------------------------
// Structural: the deadline value, the wrap coverage, the catch mapping, the
// compensating removal's BullMQ semantics
// ---------------------------------------------------------------------------
test("the deadline constant is 15000 — strictly below the browser's 20s abort, above the worst healthy pagination", () => {
assert.ok(INDEX_SRC.includes("const SCHEDULER_CREATE_REDIS_DEADLINE_MS = 15000;"), "the named constant exists in the established style");
assert.ok(15000 < 20000, "the server must answer before bot.js fetchWithServerActionToken aborts at 20000ms");
const doctrine = sliceFrom(
INDEX_SRC,
"// adpanel:scheduler-create-deadline — every Redis await inside the create",
"const SCHEDULER_CREATE_REDIS_DEADLINE_MS",
"deadline doctrine comment"
);
assert.ok(doctrine.includes("timeoutMs:\n// 20000") || doctrine.includes("20000"), "the derivation must document the browser abort it must beat");
assert.ok(doctrine.includes("SCHEDULER_JOB_SCAN_HARD_CAP"), "the derivation must document the fleet-pagination cost it must never false-trip");
assert.ok(doctrine.includes("raceWithDeadline"), "the race must be the shared helper, not a new util");
});
test("every Redis await inside the locked region is wrapped, and only the adds arm the compensation", () => {
assert.strictEqual(
(lockedRegion.match(/await runCreateRedisStep\(/g) || []).length,
7,
"the retry lookup, quota reads and queue adds are all raced"
);
assert.strictEqual((lockedRegion.match(/await schedulerQueue\.add\(/g) || []).length, 0, "no bare add may remain");
assert.strictEqual((lockedRegion.match(/await fetchAllSchedulerJobsInStates\(/g) || []).length, 0, "no bare fleet pagination may remain");
assert.strictEqual((lockedRegion.match(/await schedulerQueue\.getRepeatableJobs\(\)/g) || []).length, 0, "no bare repeatable scan may remain");
// The committing steps pass canonicalServer (arming the compensating
// removal); the reads pass no second argument. The once add passes ONLY
// the server name; the two repeatable adds also thread the pre-add
// repeatable-key snapshot (adpanel:scheduler-create-informed-compensator).
assert.strictEqual(
(lockedRegion.match(/onceRequestId \? undefined : canonicalServer\s*\n\s*\);/g) || []).length,
1,
"a retryable once task must not be compensated away after a lost response"
);
assert.strictEqual(
(lockedRegion.match(/canonicalServer,\n\s*preAddRepeatableKeys\s*\n\s*\);/g) || []).length,
2,
"exactly the two repeatable add wraps thread the pre-add snapshot into the compensator"
);
assert.strictEqual(
(lockedRegion.match(/runCreateRedisStep\(\(\) => (?:fetchAllSchedulerJobsInStates|schedulerQueue\.getRepeatableJobs|resolveSchedulerRepeatablesForServer)\(/g) || []).length,
3,
"all three quota reads are deadline-bound and do not arm compensation"
);
// The success-path literals the race wraps must be untouched.
assert.ok(lockedRegion.includes("removeOnComplete: { count: 50 }") && lockedRegion.includes("removeOnFail: { count: 25 }"), "once add options unchanged");
assert.ok(lockedRegion.includes("repeat: { every: schedule.ms, key: repeatKey }"), "interval scheduling keeps its cadence and binds an instance key");
assert.ok(lockedRegion.includes("repeat: { pattern: schedule, ...(timezone ? { tz: timezone } : {}), key: repeatKey }"), "cron scheduling keeps its optional timezone and binds an instance key");
});
test("the pre-add snapshot is captured from the RACED repeatable read, strictly before any add, exactly once", () => {
// adpanel:scheduler-create-informed-compensator — the compensator's
// decision is only as sound as the snapshot: it must derive from the
// already-raced getRepeatableJobs read (zero extra Redis calls) and
// precede the first add, so "in the set" always means "pre-existed this
// attempt".
const readAt = lockedRegion.indexOf("runCreateRedisStep(() => schedulerQueue.getRepeatableJobs())");
const snapAt = lockedRegion.indexOf("const preAddRepeatableKeys = new Set(repeatableJobs.map((r) => r.key));");
const firstAddAt = lockedRegion.indexOf("schedulerQueue.add(");
assert.notStrictEqual(readAt, -1, "the raced repeatable read exists in the locked region");
assert.notStrictEqual(snapAt, -1, "the snapshot capture exists");
assert.notStrictEqual(firstAddAt, -1, "the once add exists");
assert.ok(snapAt > readAt, "the snapshot derives from the raced read (no second Redis scan)");
assert.ok(firstAddAt > snapAt, "the snapshot is captured BEFORE the first add — pre/add ordering is the compensator's soundness");
assert.strictEqual(
(lockedRegion.match(/new Set\(repeatableJobs\.map/g) || []).length,
1,
"exactly one snapshot capture"
);
});
test("the catch arm maps the tagged error to the path-free 503 and leaves the 500 arm intact", () => {
assert.ok(catchRegion.includes("err.schedulerCreateUnavailable"), "the tag check exists");
assert.ok(catchRegion.includes("res.status(503).json({ ok: false, error: SCHEDULER_CREATE_UNAVAILABLE_MESSAGE })"), "the 503 answers with the constant, never err.text");
assert.ok(catchRegion.includes('return res.status(500).json({ ok: false, error: "internal error" });'), "the bare 500 arm is unchanged for every other error");
const message = INDEX_SRC.match(/const SCHEDULER_CREATE_UNAVAILABLE_MESSAGE = "([^"]+)";/);
assert.ok(message, "the message is a named constant");
assert.ok(
!/redis|bullmq|queue|internal/i.test(message[1].replace(/Scheduler is temporarily unavailable/, "")),
"the client-facing message names no infrastructure internals"
);
assert.match(message[1], /try again/i, "the message is action-oriented");
});
test("the compensating removal picks the correct BullMQ artifact per add shape (5.78 semantics, pinned where they are used)", () => {
assert.ok(helperBlock.includes("job?.repeatJobKey || job?.opts?.repeat?.key"), "the repeatable detection mirrors the route's own job-shape check");
assert.ok(helperBlock.includes("schedulerQueue.removeRepeatableByKey(repeatJobKey)"), "repeatable → removeRepeatableByKey (schedule + next iteration, atomically)");
assert.ok(helperBlock.includes('typeof job.remove === "function"') && helperBlock.includes("job.remove()"), "once → job.remove()");
assert.ok(helperBlock.includes("removeRepeatable-3.lua"), "the BullMQ Lua evidence is documented at the code that relies on it");
assert.ok(helperBlock.includes("failed after the deadline — nothing was committed"), "late rejects are swallowed with an operator-visible log");
});
test("the compensator is INFORMED: it threads the pre-add snapshot and withholds removal for pre-existing keys (adpanel:scheduler-create-informed-compensator)", () => {
assert.ok(
helperBlock.includes("function compensateAbandonedSchedulerAdd(addPromise, canonicalServer, preAddRepeatableKeys)"),
"the compensator takes the pre-add repeatable-key snapshot"
);
assert.ok(
helperBlock.includes("compensateAbandonedSchedulerAdd(promise, committingServerName, preAddRepeatableKeys)"),
"the race helper threads the snapshot through to the compensator"
);
assert.ok(
/async function awaitSchedulerCreateRedisStep\(promise, committingServerName, preAddRepeatableKeys, deadlineMs = SCHEDULER_CREATE_REDIS_DEADLINE_MS\)/.test(helperBlock),
"the snapshot threads before the test-only deadline parameter"
);
assert.ok(
helperBlock.includes("preAddRepeatableKeys.has(repeatJobKey)"),
"the repeatable arm decides on snapshot membership"
);
assert.ok(
helperBlock.includes("already existed before this attempt") && helperBlock.includes("left intact"),
"a withheld removal is logged loudly as a re-assert of a pre-existing schedule"
);
assert.ok(
helperBlock.includes("addRepeatableJob-2.lua"),
"the same-key override evidence (the Lua that re-stamps a pre-existing entry) is documented at the code that relies on it"
);
// The withholding branch must sit INSIDE the repeatable arm and BEFORE the
// removal, so an uninformed caller (no snapshot) keeps the legacy removal.
const armAt = helperBlock.indexOf("if (repeatJobKey) {");
const withholdAt = helperBlock.indexOf("preAddRepeatableKeys.has(repeatJobKey)");
const removeAt = helperBlock.indexOf("schedulerQueue.removeRepeatableByKey(repeatJobKey)");
assert.ok(armAt !== -1 && withholdAt > armAt && removeAt > withholdAt, "withhold guard precedes the removal, inside the repeatable arm");
});