|
| 1 | +import fs from "node:fs/promises"; |
| 2 | +import path from "node:path"; |
| 3 | +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; |
| 4 | +import { createNoopLogger, createCronStoreHarness } from "./service.test-harness.js"; |
| 5 | +import { createCronServiceState } from "./service/state.js"; |
| 6 | +import { armTimer, onTimer } from "./service/timer.js"; |
| 7 | +import type { CronJob } from "./types.js"; |
| 8 | + |
| 9 | +const noopLogger = createNoopLogger(); |
| 10 | +const { makeStorePath } = createCronStoreHarness({ prefix: "openclaw-cron-tight-loop-" }); |
| 11 | + |
| 12 | +/** |
| 13 | + * Create a cron job that is past-due AND has a stuck `runningAtMs` marker. |
| 14 | + * This combination causes `findDueJobs` to return `[]` (blocked by |
| 15 | + * `runningAtMs`) while `nextWakeAtMs` still returns the past-due timestamp, |
| 16 | + * which before the fix resulted in a `setTimeout(0)` tight loop. |
| 17 | + */ |
| 18 | +function createStuckPastDueJob(params: { id: string; nowMs: number; pastDueMs: number }): CronJob { |
| 19 | + const pastDueAt = params.nowMs - params.pastDueMs; |
| 20 | + return { |
| 21 | + id: params.id, |
| 22 | + name: "stuck-job", |
| 23 | + enabled: true, |
| 24 | + deleteAfterRun: false, |
| 25 | + createdAtMs: pastDueAt - 60_000, |
| 26 | + updatedAtMs: pastDueAt - 60_000, |
| 27 | + schedule: { kind: "cron", expr: "*/15 * * * *" }, |
| 28 | + sessionTarget: "isolated", |
| 29 | + wakeMode: "next-heartbeat", |
| 30 | + payload: { kind: "agentTurn", message: "monitor" }, |
| 31 | + delivery: { mode: "none" }, |
| 32 | + state: { |
| 33 | + nextRunAtMs: pastDueAt, |
| 34 | + // Stuck: set from a previous execution that was interrupted. |
| 35 | + // Not yet old enough for STUCK_RUN_MS (2 h) to clear it. |
| 36 | + runningAtMs: pastDueAt + 1, |
| 37 | + }, |
| 38 | + }; |
| 39 | +} |
| 40 | + |
| 41 | +describe("CronService - armTimer tight loop prevention", () => { |
| 42 | + beforeEach(() => { |
| 43 | + noopLogger.debug.mockClear(); |
| 44 | + noopLogger.info.mockClear(); |
| 45 | + noopLogger.warn.mockClear(); |
| 46 | + noopLogger.error.mockClear(); |
| 47 | + }); |
| 48 | + |
| 49 | + afterEach(() => { |
| 50 | + vi.clearAllMocks(); |
| 51 | + }); |
| 52 | + |
| 53 | + it("enforces a minimum delay when the next wake time is in the past", () => { |
| 54 | + const timeoutSpy = vi.spyOn(globalThis, "setTimeout"); |
| 55 | + const now = Date.parse("2026-02-28T12:32:00.000Z"); |
| 56 | + const pastDueMs = 17 * 60 * 1000; // 17 minutes past due |
| 57 | + |
| 58 | + const state = createCronServiceState({ |
| 59 | + storePath: "/tmp/test-cron/jobs.json", |
| 60 | + cronEnabled: true, |
| 61 | + log: noopLogger, |
| 62 | + nowMs: () => now, |
| 63 | + enqueueSystemEvent: vi.fn(), |
| 64 | + requestHeartbeatNow: vi.fn(), |
| 65 | + runIsolatedAgentJob: vi.fn().mockResolvedValue({ status: "ok" }), |
| 66 | + }); |
| 67 | + state.store = { |
| 68 | + version: 1, |
| 69 | + jobs: [createStuckPastDueJob({ id: "monitor", nowMs: now, pastDueMs })], |
| 70 | + }; |
| 71 | + |
| 72 | + armTimer(state); |
| 73 | + |
| 74 | + expect(state.timer).not.toBeNull(); |
| 75 | + const delays = timeoutSpy.mock.calls |
| 76 | + .map(([, delay]) => delay) |
| 77 | + .filter((d): d is number => typeof d === "number"); |
| 78 | + |
| 79 | + // Before the fix, delay would be 0 (tight loop). |
| 80 | + // After the fix, delay must be >= MIN_REFIRE_GAP_MS (2000 ms). |
| 81 | + expect(delays.length).toBeGreaterThan(0); |
| 82 | + for (const d of delays) { |
| 83 | + expect(d).toBeGreaterThanOrEqual(2_000); |
| 84 | + } |
| 85 | + |
| 86 | + timeoutSpy.mockRestore(); |
| 87 | + }); |
| 88 | + |
| 89 | + it("does not add extra delay when the next wake time is in the future", () => { |
| 90 | + const timeoutSpy = vi.spyOn(globalThis, "setTimeout"); |
| 91 | + const now = Date.parse("2026-02-28T12:32:00.000Z"); |
| 92 | + |
| 93 | + const state = createCronServiceState({ |
| 94 | + storePath: "/tmp/test-cron/jobs.json", |
| 95 | + cronEnabled: true, |
| 96 | + log: noopLogger, |
| 97 | + nowMs: () => now, |
| 98 | + enqueueSystemEvent: vi.fn(), |
| 99 | + requestHeartbeatNow: vi.fn(), |
| 100 | + runIsolatedAgentJob: vi.fn().mockResolvedValue({ status: "ok" }), |
| 101 | + }); |
| 102 | + state.store = { |
| 103 | + version: 1, |
| 104 | + jobs: [ |
| 105 | + { |
| 106 | + id: "future-job", |
| 107 | + name: "future-job", |
| 108 | + enabled: true, |
| 109 | + deleteAfterRun: false, |
| 110 | + createdAtMs: now, |
| 111 | + updatedAtMs: now, |
| 112 | + schedule: { kind: "cron", expr: "*/15 * * * *" }, |
| 113 | + sessionTarget: "isolated" as const, |
| 114 | + wakeMode: "next-heartbeat" as const, |
| 115 | + payload: { kind: "agentTurn" as const, message: "test" }, |
| 116 | + delivery: { mode: "none" as const }, |
| 117 | + state: { nextRunAtMs: now + 10_000 }, // 10 seconds in the future |
| 118 | + }, |
| 119 | + ], |
| 120 | + }; |
| 121 | + |
| 122 | + armTimer(state); |
| 123 | + |
| 124 | + const delays = timeoutSpy.mock.calls |
| 125 | + .map(([, delay]) => delay) |
| 126 | + .filter((d): d is number => typeof d === "number"); |
| 127 | + |
| 128 | + // The natural delay (10 s) should be used, not the floor. |
| 129 | + expect(delays).toContain(10_000); |
| 130 | + |
| 131 | + timeoutSpy.mockRestore(); |
| 132 | + }); |
| 133 | + |
| 134 | + it("breaks the onTimer→armTimer hot-loop with stuck runningAtMs", async () => { |
| 135 | + const timeoutSpy = vi.spyOn(globalThis, "setTimeout"); |
| 136 | + const store = await makeStorePath(); |
| 137 | + const now = Date.parse("2026-02-28T12:32:00.000Z"); |
| 138 | + const pastDueMs = 17 * 60 * 1000; |
| 139 | + |
| 140 | + await fs.mkdir(path.dirname(store.storePath), { recursive: true }); |
| 141 | + await fs.writeFile( |
| 142 | + store.storePath, |
| 143 | + JSON.stringify( |
| 144 | + { |
| 145 | + version: 1, |
| 146 | + jobs: [createStuckPastDueJob({ id: "monitor", nowMs: now, pastDueMs })], |
| 147 | + }, |
| 148 | + null, |
| 149 | + 2, |
| 150 | + ), |
| 151 | + "utf-8", |
| 152 | + ); |
| 153 | + |
| 154 | + const state = createCronServiceState({ |
| 155 | + storePath: store.storePath, |
| 156 | + cronEnabled: true, |
| 157 | + log: noopLogger, |
| 158 | + nowMs: () => now, |
| 159 | + enqueueSystemEvent: vi.fn(), |
| 160 | + requestHeartbeatNow: vi.fn(), |
| 161 | + runIsolatedAgentJob: vi.fn().mockResolvedValue({ status: "ok" }), |
| 162 | + }); |
| 163 | + |
| 164 | + // Simulate the onTimer path: it will find no runnable jobs (blocked by |
| 165 | + // runningAtMs) and re-arm the timer in its finally block. |
| 166 | + await onTimer(state); |
| 167 | + |
| 168 | + expect(state.running).toBe(false); |
| 169 | + expect(state.timer).not.toBeNull(); |
| 170 | + |
| 171 | + // The re-armed timer must NOT use delay=0. It should use at least |
| 172 | + // MIN_REFIRE_GAP_MS to prevent the hot-loop. |
| 173 | + const allDelays = timeoutSpy.mock.calls |
| 174 | + .map(([, delay]) => delay) |
| 175 | + .filter((d): d is number => typeof d === "number"); |
| 176 | + |
| 177 | + // The last setTimeout call is from the finally→armTimer path. |
| 178 | + const lastDelay = allDelays[allDelays.length - 1]; |
| 179 | + expect(lastDelay).toBeGreaterThanOrEqual(2_000); |
| 180 | + |
| 181 | + timeoutSpy.mockRestore(); |
| 182 | + await store.cleanup(); |
| 183 | + }); |
| 184 | +}); |
0 commit comments