"use strict"; // adpanel:scheduler-failure-streak — consecutive-failure bookkeeping for // recurring scheduler jobs. A repeatable failing for a reason outside the // three permanent disable classes (authorization loss, invalid stored // command, deleted server) used to fail on every tick forever — down to the // 10s interval floor — with no operator surface distinguishing it from a // healthy schedule: a modify_file whose target was deleted, a // planner_next_to_agent whose creator removed their saved AI model, a backup // pinned at the per-server cap. This module is pure bookkeeping: it counts // CONSECUTIVE failed runs per repeatable in the scheduler's own Redis // (sliding TTL — a gap longer than the TTL decays the streak) and reports // when the threshold is reached; the caller owns the disable decision and // routes it through the ONE disable machinery (index.js // disableRecurringScheduleForJob), so a streak-disabled schedule leaves the // same operator surface as the permanent classes. Every call fails open: a // tracking error must never mask the job's own failure or stop a healthy // schedule — worst case is a streak that never reaches the threshold, i.e. // exactly the pre-fix behavior. const crypto = require("node:crypto"); // Tradeoff baked into the default: high enough that a daemon restart or a // short node outage cannot disable a healthy schedule (at the 10s interval // floor, 20 consecutive failures ≈ 200s of CONTINUOUS failure; a daily // schedule needs 20 consecutive bad days), low enough that permanently // broken schedules stop churning the queue. Operators tune it via // SCHEDULER_MAX_CONSECUTIVE_FAILURES; the clamp keeps a nonsense value from // making the disable near-immediate (min 3) or unreachable (max 1000). const DEFAULT_MAX_CONSECUTIVE_FAILURES = 20; const MIN_MAX_CONSECUTIVE_FAILURES = 3; const MAX_MAX_CONSECUTIVE_FAILURES = 1000; // "Consecutive" is measured across fires with a sliding TTL: every bump // re-arms the expiry at bump_time + TTL, so a real Redis key from failure N // is GONE by the time failure N+1 of an interval >= TTL schedule arrives — // the TTL MUST comfortably exceed the schedule interval or the streak can // never accumulate (a 24h TTL silently excluded every daily/weekly/monthly // schedule: their count oscillated 1–2 forever). 45 days covers every // practical recurrence (daily gaps 24h, weekly 168h, monthly up to 31d); // schedules silent longer than 45 days start a fresh streak, and the TTL's // other job is orphaned-key cleanup when a schedule is deleted mid-streak. // Only failures increment, so long memory carries no false-disable risk of // its own. const DEFAULT_STREAK_TTL_SECONDS = 45 * 24 * 60 * 60; // Bookkeeping must never hold a caller hostage: callers race their streak // awaits against this helper with a short deadline so a Redis outage between // the run-claim and the catch cannot wedge a finished job in `active` (the // rethrow happens, the bookkeeping is abandoned). Late rejections are // swallowed — fail-open in every direction. Degenerate deadlines (0, NaN, // negative, Infinity) all degrade FAIL-FAST to the fallback rather than // hanging; production callers pass literal 5000s, and every caller awaits // the race, so the internal timer is always cleared or already fired. const DEFAULT_BOOKKEEPING_DEADLINE_MS = 5000; function raceWithDeadline(promise, deadlineMs = DEFAULT_BOOKKEEPING_DEADLINE_MS, fallback = null) { let timer; const timeout = new Promise((resolve) => { timer = setTimeout(() => resolve(fallback), deadlineMs); }); const guarded = Promise.resolve(promise).catch(() => fallback); return Promise.race([guarded, timeout]).finally(() => clearTimeout(timer)); } function resolveSchedulerMaxConsecutiveFailures(raw) { const parsed = parseInt(String(raw ?? "").trim(), 10); if (!Number.isFinite(parsed)) return DEFAULT_MAX_CONSECUTIVE_FAILURES; return Math.min(MAX_MAX_CONSECUTIVE_FAILURES, Math.max(MIN_MAX_CONSECUTIVE_FAILURES, parsed)); } // The repeat identity can embed the schedule's name JSON (spaces, quotes, // unbounded length), so the key carries a short hash of it: fixed length, no // Redis key-space surprises, and schedules that share nothing never share a // counter. function schedulerFailureStreakKey(repeatKey) { return `adpanel:scheduler-failstreak:${crypto.createHash("sha256").update(String(repeatKey)).digest("hex").slice(0, 32)}`; } // INCR + sliding EXPIRE. Returns { tracked, count, shouldDisable }; tracked // is false whenever the streak could not be honestly maintained (no client, // no repeat identity, Redis error) and shouldDisable is then false too — // the caller must treat untracked as "keep the schedule". async function bumpSchedulerFailureStreak(client, repeatKey, opts = {}) { const untracked = { tracked: false, count: 0, shouldDisable: false }; const threshold = opts.threshold ?? DEFAULT_MAX_CONSECUTIVE_FAILURES; const ttlSeconds = opts.ttlSeconds ?? DEFAULT_STREAK_TTL_SECONDS; if (!client || repeatKey === null || repeatKey === undefined || String(repeatKey) === "") return untracked; try { const key = schedulerFailureStreakKey(repeatKey); const count = await client.incr(key); if (!Number.isFinite(count)) return untracked; // Best-effort: the count was honestly incremented, so a failed TTL // re-arm must not discard it — worst case the streak stops decaying, // and the next successful run or post-disable reset clears it anyway. try { await client.expire(key, ttlSeconds); } catch { } return { tracked: true, count, shouldDisable: count >= threshold }; } catch { return untracked; } } // Success path and post-disable cleanup: any doubt (no client, Redis error) // leaves a stale counter behind at worst — it decays via the TTL and can // never disable a healthy schedule on its own. async function resetSchedulerFailureStreak(client, repeatKey) { if (!client || repeatKey === null || repeatKey === undefined || String(repeatKey) === "") return false; try { await client.del(schedulerFailureStreakKey(repeatKey)); return true; } catch { return false; } } module.exports = { DEFAULT_MAX_CONSECUTIVE_FAILURES, DEFAULT_STREAK_TTL_SECONDS, DEFAULT_BOOKKEEPING_DEADLINE_MS, resolveSchedulerMaxConsecutiveFailures, schedulerFailureStreakKey, bumpSchedulerFailureStreak, resetSchedulerFailureStreak, raceWithDeadline, };