Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

fix(cron): update handler timeout behavior to prevent zombie concurrency and ensure failed-final status

Victor Hugo dos Santos312bd1d1d0c4
diff --git a/backend/e2e-test/cron-job.spec.ts b/backend/e2e-test/cron-job.spec.ts
index fca1c34dc9..b0de6dd25e 100644
--- a/backend/e2e-test/cron-job.spec.ts
+++ b/backend/e2e-test/cron-job.spec.ts
@@ -217,8 +217,11 @@ describe("retry", () => {
// ── handler timeout ────────────────────────────────────────────────────────────
describe("handler timeout", () => {
- test("hung handler is aborted after handlerTimeoutMs and run flips to pending with timeout error", async () => {
- // Handler never resolves — simulates a wedged network call.
+ test("hung handler is marked failed-final (no retry on same fire) to prevent zombie concurrency", async () => {
+ // Handler never resolves — simulates a wedged network call. After
+ // handlerTimeoutMs fires, the zombie is still running in this process,
+ // so the run must NOT be re-picked-up by this or another pod — the next
+ // scheduled fire (separate id) is the natural retry.
const handler = vi.fn().mockImplementation(() => new Promise<void>(() => {}));
const f = factory({
handlerTimeoutMs: 500,
@@ -229,17 +232,25 @@ describe("handler timeout", () => {
f.start();
// Enqueue (~500ms) + first attempt hangs for handlerTimeoutMs (500ms) +
- // backoff (100ms) + second attempt window. Wait long enough to observe
- // the timeout-driven retry without burning all attempts.
+ // generous post-timeout window. The next minute boundary is well past
+ // 2500ms of real time, so no second fire is expected within this window.
await new Promise((r) => {
setTimeout(r, 2500);
});
- expect(handler.mock.calls.length).toBeGreaterThanOrEqual(2);
+ // Exactly one handler invocation: timeout marks the run failed-final, so
+ // no retry can be scheduled for this id.
+ expect(handler).toHaveBeenCalledTimes(1);
+
const keys = await testRedis.keys("cron:run:hang-job:*");
expect(keys.length).toBe(1);
const run = await testRedis.hgetall(keys[0]);
+ expect(run.status).toBe("failed");
expect(run.last_error).toContain("exceeded");
+
+ // The id is removed from the pending zset so no further tick can re-process it.
+ const pending = await testRedis.zrange("cron:pending", 0, -1);
+ expect(pending.filter((s) => s.startsWith("hang-job:"))).toEqual([]);
}, 10_000);
});
diff --git a/backend/src/lib/cron/cron-job.test.ts b/backend/src/lib/cron/cron-job.test.ts
index 1e2458150c..975dac4eea 100644
--- a/backend/src/lib/cron/cron-job.test.ts
+++ b/backend/src/lib/cron/cron-job.test.ts
@@ -250,7 +250,7 @@ describe("retry backoff and handler timeout", () => {
await stop();
});
- test("hung handler is aborted after handlerTimeoutMs and last_error includes 'exceeded'", async () => {
+ test("hung handler is marked failed-final (not pending-retry) to prevent zombie concurrency", async () => {
vi.setSystemTime(new Date("2024-01-01T00:00:30Z"));
const redis = makeRedis();
setupPendingRun(redis, Date.parse("2024-01-01T00:00:00Z"));
@@ -287,6 +287,16 @@ describe("retry backoff and handler timeout", () => {
);
expect(wroteTimeoutError).toBe(true);
+ // Regression guard: handlerTimeoutMs must mark the run failed-final so a
+ // retry doesn't race with the still-running zombie. zrem (failed-final
+ // path) must fire; zadd (pending-retry path) must NOT.
+ const wroteFailed = redis.hset.mock.calls.some((c) =>
+ (c as unknown[]).some((arg, i, arr) => arg === "status" && arr[i + 1] === "failed")
+ );
+ expect(wroteFailed).toBe(true);
+ expect(redis.zrem).toHaveBeenCalled();
+ expect(redis.zadd).not.toHaveBeenCalled();
+
// Advance past drainTimeoutMs so stop() can resolve via the drain timeout.
const stopPromise = f.stop();
await vi.advanceTimersByTimeAsync(100);
diff --git a/backend/src/lib/cron/cron-job.ts b/backend/src/lib/cron/cron-job.ts
index 952ff86afc..34412d3f64 100644
--- a/backend/src/lib/cron/cron-job.ts
+++ b/backend/src/lib/cron/cron-job.ts
@@ -82,8 +82,14 @@ const RELEASE_SLOT_IF_MINE_LUA = `if redis.call('get', KEYS[1]) == ARGV[1] then
// ── types ─────────────────────────────────────────────────────────────────────
-type Handler = (signal: AbortSignal) => Promise<void>;
+type Handler = () => Promise<void>;
type CronEntry = { name: string; pattern: string; maxAttempts: number; handler: Handler; runHashTtlS: number };
+class HandlerTimeoutError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "HandlerTimeoutError";
+ }
+}
export type TCronJobFactory = ReturnType<typeof cronJobFactory>;
@@ -139,22 +145,23 @@ export const cronJobFactory = ({
}
};
- // Races `task` against a timeout. If the timeout wins, aborts `ac` (so
- // well-behaved handlers can short-circuit network calls) and rejects with a
- // descriptive error. Used for HANG recovery — see executeUnderLease for the
- // two-knob recovery model that justifies racing on top of redlock.using.
- const withTimeout = async (task: (signal: AbortSignal) => Promise<void>, ac: AbortController, timeoutMs: number) => {
+ // Races `task` against a timeout. If the timeout wins, throws a
+ // HandlerTimeoutError so executeUnderLease's catch can mark the run
+ // failed-final (rather than pending-retry) and prevent another pod from
+ // running the handler concurrently with the still-executing zombie.
+ const withTimeout = async (task: () => Promise<void>, timeoutMs: number) => {
let timer: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<never>((_, reject) => {
timer = setTimeout(() => {
- ac.abort();
- reject(new Error(`handler exceeded ${timeoutMs}ms`));
+ reject(new HandlerTimeoutError(`handler exceeded ${timeoutMs}ms`));
}, timeoutMs);
});
+ const taskPromise = task();
try {
- await Promise.race([task(ac.signal), timeout]);
+ await Promise.race([taskPromise, timeout]);
} finally {
if (timer) clearTimeout(timer);
+ taskPromise.catch(() => {});
}
};
@@ -307,25 +314,17 @@ export const cronJobFactory = ({
// ── process ─────────────────────────────────────────────────────────────────
- // Executes one attempt of `entry` under an already-acquired redlock. Wires
- // up the AbortController, writes the running state, races the handler
- // against handlerTimeoutMs, and branches into success / retry / final
- // failure on completion.
+ // Executes one attempt of `entry` under an already-acquired redlock. Writes
+ // the running state, races the handler against handlerTimeoutMs, and
+ // branches into success / retry / final failure on completion.
//
// Two-knob recovery model:
// leaseDurationMs → governs CRASH recovery. When the holder pod dies,
// its lease key TTLs out and other pods see the run as
// stalled via the isStalled path in processCandidate.
- // handlerTimeoutMs → governs HANG recovery. When a handler wedges in a
- // live pod, redlock would auto-extend the lease
- // forever. The withTimeout race fires ac.abort() after
- // handlerTimeoutMs and rejects, so the catch runs,
- // status flips back to pending, and redlock.using
- // releases the lease on return.
- const executeUnderLease = async (entry: CronEntry, id: string, attempt: number, leaseSignal: AbortSignal) => {
- const ac = new AbortController();
- leaseSignal.addEventListener?.("abort", () => ac.abort());
-
+ // handlerTimeoutMs → bounds the LEASE for HANG recovery. On timeout we release the lease and
+ // mark the run failed-final — a retry would race with the still-running zombie handler. The next scheduled fire is the natural retry.
+ const executeUnderLease = async (entry: CronEntry, id: string, attempt: number) => {
try {
await markRunning(id, attempt);
} catch (err) {
@@ -337,10 +336,12 @@ export const cronJobFactory = ({
logger.info(`cron[${entry.name}]: start (attempt ${attempt}/${entry.maxAttempts}) [id=${id}]`);
try {
- await withTimeout((sig) => entry.handler(sig), ac, handlerTimeoutMs);
+ await withTimeout(() => entry.handler(), handlerTimeoutMs);
await markCompleted(id);
logger.info(`cron[${entry.name}]: complete [id=${id}] [duration_ms=${Date.now() - startMs}]`);
} catch (err) {
+ const isHandlerTimeout = err instanceof HandlerTimeoutError;
+
// Exponential backoff: 1×, 2×, 4× ... capped at retryBackoffMaxMs.
const backoffMs = Math.min(retryBackoffBaseMs * 2 ** (attempt - 1), retryBackoffMaxMs);
const nextAttemptAt = Date.now() + backoffMs;
@@ -349,7 +350,7 @@ export const cronJobFactory = ({
// Avoids overlapping attempts of the same cron and avoids squashing
// backoff to ~0 near the end of an interval.
const fitsBeforeNextFire = nextAttemptAt + NEXT_FIRE_BUFFER_MS < nextFireMs(entry.pattern);
- const final = attempt >= entry.maxAttempts || !fitsBeforeNextFire;
+ const final = isHandlerTimeout || attempt >= entry.maxAttempts || !fitsBeforeNextFire;
try {
if (final) await markFailedFinal(id, err);
@@ -363,7 +364,11 @@ export const cronJobFactory = ({
logger.error(
{ err },
- `cron[${entry.name}]: attempt ${attempt} failed (${final ? "giving up" : "will retry"}) [id=${id}]`
+ `cron[${entry.name}]: attempt ${attempt} ${
+ isHandlerTimeout
+ ? "timed out (no retry, wait for next fire)"
+ : `failed (${final ? "giving up" : "will retry"})`
+ } [id=${id}]`
);
}
};
@@ -409,9 +414,7 @@ export const cronJobFactory = ({
// Track the in-flight run so stop() can wait for it to settle before
// tearing down. Lock-contention rejections settle within a tick, so they
// don't measurably delay shutdown drain.
- const tracked = redlock.using([LEASE_KEY(id)], leaseDurationMs, (signal) =>
- executeUnderLease(entry, id, attempts + 1, signal as AbortSignal)
- );
+ const tracked = redlock.using([LEASE_KEY(id)], leaseDurationMs, () => executeUnderLease(entry, id, attempts + 1));
inFlight.add(tracked);
try {
await tracked;