|
| 1 | +// Live-proof harness for PR #92037 (cron `on-exit` schedule kind). |
| 2 | +// |
| 3 | +// Drives the REAL gateway exit-watcher (`createCronExitWatchers`) against the |
| 4 | +// REAL ProcessSupervisor (`getProcessSupervisor`) with a REAL short-lived child |
| 5 | +// command, and captures the actual arm -> exit -> persist-before-fire -> fire |
| 6 | +// lifecycle. The persistCompletion/fireOnExit sinks mirror the real wiring in |
| 7 | +// server-cron.ts (disable-before-fire; force-run after exit) and only RECORD/LOG. |
| 8 | +// |
| 9 | +// Run: pnpm exec tsx scripts/proof-cron-on-exit.mts |
| 10 | +// |
| 11 | +// All identifiers are synthetic. No real Telegram chat ids / session keys. |
| 12 | + |
| 13 | +import type { CronJob } from "../src/cron/types.js"; |
| 14 | +import { |
| 15 | + createCronExitWatchers, |
| 16 | + resolveExitWatchShell, |
| 17 | +} from "../src/gateway/cron-exit-watchers.js"; |
| 18 | +import { getProcessSupervisor } from "../src/process/supervisor/index.js"; |
| 19 | + |
| 20 | +const isWin = process.platform === "win32"; |
| 21 | +// Commands phrased for the shell the watcher actually resolves on this host |
| 22 | +// (cmd.exe /d /s /c on Windows, bash -lc on POSIX). |
| 23 | +const delayThenExit = (code: number) => |
| 24 | + isWin ? `ping -n 3 127.0.0.1 > nul & exit ${code}` : `sleep 2; exit ${code}`; |
| 25 | +const longRunning = () => (isWin ? `ping -n 31 127.0.0.1 > nul` : `sleep 30`); |
| 26 | + |
| 27 | +type FireEvent = { jobId: string; exitCode: number | null }; |
| 28 | + |
| 29 | +const events: { armed: string[]; persisted: string[]; fired: FireEvent[] } = { |
| 30 | + armed: [], |
| 31 | + persisted: [], |
| 32 | + fired: [], |
| 33 | +}; |
| 34 | +// Monotonic call-order log so we can assert persist-before-fire directly |
| 35 | +// (the watcher's fail-closed guarantee), not merely that both happened. |
| 36 | +const order: string[] = []; |
| 37 | + |
| 38 | +const logger = { |
| 39 | + info: (obj: unknown, msg?: string) => { |
| 40 | + const o = obj as { jobId?: string; exitCode?: number | null; reason?: string }; |
| 41 | + if (msg?.includes("watcher armed") && o.jobId) { |
| 42 | + events.armed.push(o.jobId); |
| 43 | + } |
| 44 | + console.log(`[cron-exit] ${msg ?? ""} ${JSON.stringify(obj)}`); |
| 45 | + }, |
| 46 | + warn: (obj: unknown, msg?: string) => |
| 47 | + console.log(`[cron-exit][warn] ${msg ?? ""} ${JSON.stringify(obj)}`), |
| 48 | +}; |
| 49 | + |
| 50 | +const watchers = createCronExitWatchers({ |
| 51 | + getProcessSupervisor, |
| 52 | + // Real wiring disables the one-shot job in the store before firing. |
| 53 | + persistCompletion: async (jobId) => { |
| 54 | + events.persisted.push(jobId); |
| 55 | + order.push(`persist:${jobId}`); |
| 56 | + console.log(`[cron-exit] persistCompletion (job disabled, enabled=false) jobId=${jobId}`); |
| 57 | + }, |
| 58 | + // Real wiring routes this into cron.run(job.id, "force"). |
| 59 | + fireOnExit: (job, exit) => { |
| 60 | + events.fired.push({ jobId: job.id, exitCode: exit.exitCode }); |
| 61 | + order.push(`fire:${job.id}`); |
| 62 | + console.log(`[gateway/cron] cron.run force jobId=${job.id}`); |
| 63 | + }, |
| 64 | + logger, |
| 65 | +}); |
| 66 | + |
| 67 | +function onExitJob(id: string, command: string, extra?: Partial<CronJob>): CronJob { |
| 68 | + return { |
| 69 | + id, |
| 70 | + enabled: true, |
| 71 | + schedule: { kind: "on-exit", command }, |
| 72 | + sessionKey: `agent:main:telegram:direct:SYN:thread:SYN`, |
| 73 | + payload: { text: `on-exit[${id}]` }, |
| 74 | + ...extra, |
| 75 | + } as unknown as CronJob; |
| 76 | +} |
| 77 | + |
| 78 | +const sleep = (ms: number) => |
| 79 | + new Promise<void>((r) => { |
| 80 | + setTimeout(r, ms); |
| 81 | + }); |
| 82 | +async function waitFor(pred: () => boolean, timeoutMs: number, pollMs = 100): Promise<boolean> { |
| 83 | + const start = Date.now(); |
| 84 | + while (Date.now() - start < timeoutMs) { |
| 85 | + if (pred()) { |
| 86 | + return true; |
| 87 | + } |
| 88 | + await sleep(pollMs); |
| 89 | + } |
| 90 | + return pred(); |
| 91 | +} |
| 92 | + |
| 93 | +let failures = 0; |
| 94 | +function assert(label: string, cond: boolean): void { |
| 95 | + console.log(` ${cond ? "PASS" : "FAIL"}: ${label}`); |
| 96 | + if (!cond) { |
| 97 | + failures++; |
| 98 | + } |
| 99 | +} |
| 100 | + |
| 101 | +async function run(): Promise<void> { |
| 102 | + const shell = resolveExitWatchShell(); |
| 103 | + console.log(`=== PR #92037 on-exit live proof (real watcher + real ProcessSupervisor) ===`); |
| 104 | + console.log( |
| 105 | + `platform=${process.platform} shell=${shell.command} argv=${JSON.stringify(shell.argsFor("<cmd>"))}`, |
| 106 | + ); |
| 107 | + |
| 108 | + // Scenario A: arm a real watcher; the watched command runs ~2s then exits 7. |
| 109 | + // Expect: armed -> exited -> persistCompletion BEFORE fire -> fire with exitCode 7. |
| 110 | + console.log(`\n=== A. arm -> watched command exits (code 7) -> force-run fires ===`); |
| 111 | + const a = onExitJob("onexit-A", delayThenExit(7)); |
| 112 | + watchers.reconcile([a]); |
| 113 | + assert( |
| 114 | + "watcher is active immediately after reconcile", |
| 115 | + watchers.activeJobIds().includes("onexit-A"), |
| 116 | + ); |
| 117 | + const aFired = await waitFor(() => events.fired.some((e) => e.jobId === "onexit-A"), 15000); |
| 118 | + assert("watcher armed (logged) for onexit-A", events.armed.includes("onexit-A")); |
| 119 | + assert("job fired after the command exited", aFired); |
| 120 | + const aEvt = events.fired.find((e) => e.jobId === "onexit-A"); |
| 121 | + assert("exit code 7 captured from the real child", aEvt?.exitCode === 7); |
| 122 | + assert( |
| 123 | + "persistCompletion ran BEFORE fire (fail-closed ordering)", |
| 124 | + order.includes("persist:onexit-A") && |
| 125 | + order.indexOf("persist:onexit-A") < order.indexOf("fire:onexit-A"), |
| 126 | + ); |
| 127 | + assert("fire routed to the cron force-run sink", aEvt?.jobId === a.id); |
| 128 | + |
| 129 | + // Scenario B: arm a long-running watcher, cancel before exit -> NO fire. |
| 130 | + console.log(`\n=== B. arm -> cancel before exit -> no fire (revocation) ===`); |
| 131 | + const b = onExitJob("onexit-B", longRunning()); |
| 132 | + watchers.reconcile([b]); |
| 133 | + await waitFor(() => events.armed.includes("onexit-B"), 8000); |
| 134 | + assert("watcher armed for onexit-B", events.armed.includes("onexit-B")); |
| 135 | + watchers.cancel("onexit-B"); |
| 136 | + assert( |
| 137 | + "watcher removed from active set after cancel", |
| 138 | + !watchers.activeJobIds().includes("onexit-B"), |
| 139 | + ); |
| 140 | + await sleep(2500); |
| 141 | + assert("cancelled watcher never fired", !events.fired.some((e) => e.jobId === "onexit-B")); |
| 142 | + |
| 143 | + // Scenario C: reconcile without the job cancels its watcher. |
| 144 | + console.log(`\n=== C. reconcile-removal cancels the watcher ===`); |
| 145 | + const c = onExitJob("onexit-C", longRunning()); |
| 146 | + watchers.reconcile([c]); |
| 147 | + await waitFor(() => watchers.activeJobIds().includes("onexit-C"), 8000); |
| 148 | + assert("watcher active for onexit-C", watchers.activeJobIds().includes("onexit-C")); |
| 149 | + watchers.reconcile([]); // job gone |
| 150 | + assert("reconcile([]) cancelled onexit-C", !watchers.activeJobIds().includes("onexit-C")); |
| 151 | +} |
| 152 | + |
| 153 | +async function main(): Promise<void> { |
| 154 | + try { |
| 155 | + await run(); |
| 156 | + } finally { |
| 157 | + // Always tear down watchers so a thrown assertion can't leak the |
| 158 | + // long-running ping/sleep children (B, C) until their 24h timeout. |
| 159 | + watchers.cancelAll(); |
| 160 | + await sleep(300); |
| 161 | + } |
| 162 | + console.log(`\n=== RESULT: ${failures === 0 ? "ALL PASS" : `${failures} FAILURE(S)`} ===`); |
| 163 | + process.exit(failures === 0 ? 0 : 1); |
| 164 | +} |
| 165 | + |
| 166 | +main().catch((err: unknown) => { |
| 167 | + console.error("proof harness crashed:", err); |
| 168 | + watchers.cancelAll(); |
| 169 | + process.exit(1); |
| 170 | +}); |
0 commit comments