diff --git a/.changeset/calm-workflow-timers.md b/.changeset/calm-workflow-timers.md new file mode 100644 index 000000000..c3cc1886f --- /dev/null +++ b/.changeset/calm-workflow-timers.md @@ -0,0 +1,5 @@ +--- +"@voltagent/core": patch +--- + +Preserve requested durations for workflow sleep steps and retry delays that exceed the Node.js timer limit. diff --git a/packages/core/src/workflow/steps/signal.spec.ts b/packages/core/src/workflow/steps/signal.spec.ts new file mode 100644 index 000000000..3f659ae42 --- /dev/null +++ b/packages/core/src/workflow/steps/signal.spec.ts @@ -0,0 +1,40 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { waitWithSignal } from "./signal"; + +const MAX_TIMEOUT_MS = 2_147_483_647; + +afterEach(() => { + vi.useRealTimers(); +}); + +describe("waitWithSignal", () => { + it("waits for the full duration when it exceeds the timer limit", async () => { + vi.useFakeTimers(); + + const onComplete = vi.fn(); + const wait = waitWithSignal(MAX_TIMEOUT_MS + 100).then(onComplete); + + await vi.advanceTimersByTimeAsync(MAX_TIMEOUT_MS + 99); + expect(onComplete).not.toHaveBeenCalled(); + + await vi.advanceTimersByTimeAsync(1); + await wait; + expect(onComplete).toHaveBeenCalledOnce(); + }); + + it.each([ + ["cancel", { type: "cancelled" }, "WORKFLOW_CANCELLED"], + ["suspend", undefined, "WORKFLOW_SUSPENDED"], + ])("can %s a long wait after the first timer elapses", async (_action, reason, error) => { + vi.useFakeTimers(); + + const controller = new AbortController(); + const wait = waitWithSignal(MAX_TIMEOUT_MS + 100, controller.signal); + + await vi.advanceTimersByTimeAsync(MAX_TIMEOUT_MS); + controller.abort(reason); + + await expect(wait).rejects.toThrow(error); + expect(vi.getTimerCount()).toBe(0); + }); +}); diff --git a/packages/core/src/workflow/steps/signal.ts b/packages/core/src/workflow/steps/signal.ts index 433e86185..13ace0f53 100644 --- a/packages/core/src/workflow/steps/signal.ts +++ b/packages/core/src/workflow/steps/signal.ts @@ -23,9 +23,21 @@ export const throwIfAborted = (signal?: AbortSignal) => { } }; -export const waitWithSignal = (ms: number, signal?: AbortSignal) => { - const durationMs = Number.isFinite(ms) ? Math.max(0, ms) : 0; +// Node.js runs timers above the signed 32-bit limit after just 1 ms. +const MAX_TIMEOUT_MS = 2_147_483_647; +export const waitWithSignal = async (ms: number, signal?: AbortSignal) => { + let remainingMs = Number.isFinite(ms) ? Math.max(0, ms) : 0; + + while (remainingMs > MAX_TIMEOUT_MS) { + await waitForTimer(MAX_TIMEOUT_MS, signal); + remainingMs -= MAX_TIMEOUT_MS; + } + + await waitForTimer(remainingMs, signal); +}; + +const waitForTimer = (durationMs: number, signal?: AbortSignal) => { if (!signal) { return new Promise((resolve) => { setTimeout(resolve, durationMs);