"use strict"; // Behavioral + structural pins for the once-task timestamp validation at the // scheduler create route (adpanel:scheduler-nan-timestamp). // // A NaN timestamp compares false against every inequality, so the client's // future check passed it and JSON.stringify shipped it as null — and the // route's contract treats an ABSENT timestamp as run-now (explicit null was // indistinguishable from absent). The route therefore rejects any // PRESENT-but-non-finite scheduledTimestamp (null, "", garbage, non-number) // with 400 and keeps run-now ONLY for the truly absent key, while the client // rejects the NaN before the future check (see // tests/bot-scheduler-nan-timestamp.test.js). // // Technique (the scheduler-timezone.test.js harness precedent): the REAL // once-timestamp gate and the REAL once branch are each sliced out of // index.js — every anchor is unique in the file — and composed in route // order (gate first, branch second) inside a real async function with the // route's in-scope bindings injected, then EXECUTED against a stub // queue/response. The gate lives ABOVE withSchedulerCreateLock (between the // scheduleType whitelist and the timezone block) so request-shape garbage // never pays the quota's fleet pagination nor holds the cross-process lock; // source pins keep it above the lock and wired before the run-now fallback. 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"); 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); } // The once-timestamp shape gate, hoisted above the create lock // (adpanel:scheduler-nan-timestamp). const timestampGate = sliceFrom( INDEX_SRC, "// adpanel:scheduler-nan-timestamp — a PRESENT-but-non-finite", "// adpanel:timezone", "create route once-timestamp shape gate" ); // The once branch of the create route, up to the recurring else. Its // assignments target the route's `let job;` — declared in the wrapper. const onceBranch = sliceFrom( INDEX_SRC, 'if (scheduleType === "once") {', "} else {", "create route once branch" ); // The gate slice ends at the timezone comment that follows it; the once // branch slice stops before `} else {`, whose leading `}` closes the once // branch itself — the wrapper re-supplies it. The two slices are composed in // route order (gate above the lock, branch inside it). `scheduleType` is // injected (the once-branch slice includes the `if` condition, exactly like // the timezone harness's bindings). const runOnceBranch = new Function( "scheduleType", "scheduledTimestamp", "jobData", "schedulerQueue", "res", "console", "canonicalServer", "runCreateRedisStep", "isAgentSchedule", "actionType", "crypto", "onceRequestId", `"use strict"; let job; return (async () => { ${timestampGate} ${onceBranch} } return job; })();` ); const runOncePath = (scheduleType, timestamp, jobData, schedulerQueue, res, logger, serverName, runStep) => runOnceBranch(scheduleType, timestamp, jobData, schedulerQueue, res, logger, serverName, (operation, ...options) => runStep(operation(), ...options), require("../AgentWorker/feature-http").isAgentSchedule, "console_command", require("node:crypto"), null); // adpanel:scheduler-create-deadline — the once branch's queue.add is now // deadline-raced through the route's shared helper, so the harness binds the // REAL sliced helper (with the real raceWithDeadline) instead of a mimic. // These tests resolve the add immediately, so the production deadline (15s) // never fires here. const { awaitSchedulerCreateRedisStep } = new Function( "raceWithDeadline", "schedulerQueue", "console", sliceFrom( INDEX_SRC, "const SCHEDULER_CREATE_REDIS_DEADLINE_MS = 15000;", "\n// Server-side twin of the scheduler UI's interval floor", "create-deadline helpers" ) + "\nreturn { awaitSchedulerCreateRedisStep };" )( require("../utils/scheduler-failure-streak").raceWithDeadline, { removeRepeatableByKey: async () => 0 }, // never reached: no abandonment in these tests { warn() {}, error() {}, log() {} } ); function makeStubs() { const adds = []; const responses = []; return { schedulerQueue: { add: async (name, data, opts) => { adds.push({ name, data, opts }); return { id: `job-${adds.length}` }; } }, res: { status: (code) => ({ json: (payload) => { responses.push({ code, payload }); } }) }, adds, responses }; } function consoleStub() { return { log() {}, warn() {}, error() {} }; } test("a PRESENT non-finite scheduledTimestamp is rejected 400, never run-now", async () => { for (const bad of [null, "", "not-a-date", Number.NaN, "12345abc"]) { const { schedulerQueue, res, adds, responses } = makeStubs(); const job = await runOncePath("once", bad, { name: "x" }, schedulerQueue, res, consoleStub(), "srv01", awaitSchedulerCreateRedisStep); assert.strictEqual(adds.length, 0, `a ${String(bad)} timestamp must never reach the queue`); assert.strictEqual(responses.length, 1, `a ${String(bad)} timestamp must be answered with exactly one error response`); assert.strictEqual(responses[0].code, 400); assert.deepStrictEqual(responses[0].payload, { ok: false, error: "invalid scheduledTimestamp" }); assert.strictEqual(job, undefined); } }); test("an ABSENT scheduledTimestamp keeps the documented run-now contract", async () => { const { schedulerQueue, res, adds, responses } = makeStubs(); const before = Date.now(); const job = await runOncePath("once", undefined, { name: "x" }, schedulerQueue, res, consoleStub(), "srv01", awaitSchedulerCreateRedisStep); assert.strictEqual(responses.length, 0, "an absent key must not be rejected"); assert.strictEqual(adds.length, 1, "an absent key still enqueues exactly one one-time job"); assert.strictEqual(adds[0].name, "scheduled-task"); assert.ok(Number.isFinite(adds[0].opts.delay) && adds[0].opts.delay >= 0 && adds[0].opts.delay < 60000, "an absent key runs now (delay ~0)"); assert.ok(job && job.id === "job-1"); assert.ok(Date.now() - before < 60000); }); test("a finite future timestamp is queued with the computed delay", async () => { const { schedulerQueue, res, adds, responses } = makeStubs(); const target = Date.now() + 3600000; await runOncePath("once", target, { name: "x" }, schedulerQueue, res, consoleStub(), "srv01", awaitSchedulerCreateRedisStep); assert.strictEqual(responses.length, 0); assert.strictEqual(adds.length, 1); assert.ok(Math.abs(adds[0].opts.delay - 3600000) < 5000, "the delay must equal runAt - now"); }); test("the present-but-non-finite gate sits ABOVE the create lock, before the run-now fallback", () => { assert.ok( timestampGate.includes("adpanel:scheduler-nan-timestamp"), "the hoisted gate must carry the adpanel:scheduler-nan-timestamp constraint comment" ); const gateAt = INDEX_SRC.indexOf("// adpanel:scheduler-nan-timestamp — a PRESENT-but-non-finite"); const lockAt = INDEX_SRC.indexOf("await withSchedulerCreateLock(canonicalServer"); const onceAt = INDEX_SRC.indexOf('if (scheduleType === "once") {'); assert.notStrictEqual(gateAt, -1, "the hoisted present-but-non-finite gate is missing"); assert.notStrictEqual(lockAt, -1, "the create lock is missing"); assert.ok(gateAt < lockAt, "the shape gate must sit ABOVE withSchedulerCreateLock so garbage input never pays the quota pagination nor holds the lock"); assert.ok(gateAt < onceAt, "the gate must run before the once branch — hoisted above the lock, not merely moved within the locked branch"); assert.ok( !onceBranch.includes("adpanel:scheduler-nan-timestamp"), "the gate must not remain (or be re-added) inside the locked once branch" ); // Same behavior, earlier position: the gate condition stays byte-identical // and still precedes the run-now fallback in composed route order. const composed = timestampGate + onceBranch; const gateAt2 = composed.indexOf('scheduledTimestamp !== undefined && (typeof scheduledTimestamp !== "number" || !Number.isFinite(scheduledTimestamp))'); assert.notStrictEqual(gateAt2, -1, "the present-but-non-finite gate condition is missing"); const runNowAt = composed.indexOf("Date.now();"); assert.notStrictEqual(runNowAt, -1, "the run-now fallback is missing"); assert.ok(gateAt2 < runNowAt, "the gate must precede the run-now fallback so garbage never degrades to run-now"); });