Skip to content

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

allow passing cron namespace

Thiago Araujo da Silvadebb71744f9a
diff --git a/backend/e2e-test/cron-job.spec.ts b/backend/e2e-test/cron-job.spec.ts
index a887a82b4f..3871335662 100644
--- a/backend/e2e-test/cron-job.spec.ts
+++ b/backend/e2e-test/cron-job.spec.ts
@@ -7,6 +7,28 @@ import { initLogger } from "@app/lib/logger";
// testRedis is injected by vitest-environment-knex.ts
declare const testRedis: Redis;
+// ── key namespace ─────────────────────────────────────────────────────────────
+
+// `testRedis` is the *same* connection the test server runs on, and
+// vitest-environment-knex.ts starts the server's real cron manager
+// (routes/index.ts calls `cronJob.start()` unconditionally). That manager holds
+// a `{cron}:slot:N` key of its own and re-claims it within `slotRefreshMs` of
+// any deletion, so asserting on the production namespace here would
+// intermittently observe the server's slot and fail.
+//
+// These tests therefore run in their own namespace and clean up by prefix
+// instead of `flushdb()` — a flush would also wipe the shared server's BullMQ
+// queues, keystore caches, and cron leases mid-run.
+const KEY_PREFIX = "{cron-e2e}";
+const SLOT_KEYS = `${KEY_PREFIX}:slot:*`;
+const RUN_KEYS = (name: string) => `${KEY_PREFIX}:run:${name}:*`;
+const PENDING_ZSET = `${KEY_PREFIX}:pending`;
+
+const clearNamespace = async () => {
+ const keys = await testRedis.keys(`${KEY_PREFIX}:*`);
+ if (keys.length) await testRedis.del(...keys);
+};
+
// ── helpers ───────────────────────────────────────────────────────────────────
// Simple in-memory lock manager for test redlock
@@ -42,6 +64,7 @@ const makeFactory = (overrides?: Partial<Parameters<typeof cronJobFactory>[0]>)
return cronJobFactory({
redis,
redlock,
+ keyPrefix: KEY_PREFIX,
slotTtlMs: 500,
slotRefreshMs: 100,
enqueueIntervalMs: 500,
@@ -68,11 +91,26 @@ const factory = (overrides?: Partial<Parameters<typeof cronJobFactory>[0]>) => {
return f;
};
+// A handler that never settles on its own, simulating a wedged network call.
+// The resolver is parked so afterEach can release it: an abandoned handler
+// leaves `withTimeout`'s race unsettled, so its `finally` never runs and its
+// (up to 30s) timer keeps the fork's event loop alive past the test.
+const parkedHandlers: Array<() => void> = [];
+const hangingHandler = () =>
+ vi.fn().mockImplementation(
+ () =>
+ new Promise<void>((resolve) => {
+ parkedHandlers.push(resolve);
+ })
+ );
+
// FAST_PATTERN fires every minute, so a test that waits ~5s and asserts
// "exactly one fire happened" will spuriously see two when the wait crosses a
// minute boundary. This helper pads beforeEach to start the test at least
// MIN_HEADROOM_MS away from the next boundary, so no test wait can straddle it.
-const MIN_HEADROOM_MS = 10_000;
+// Headroom is 3x the longest in-test wait (5s) so an event-loop stall under CI
+// contention still can't push a wait across the boundary.
+const MIN_HEADROOM_MS = 15_000;
const waitForFreshMinute = async () => {
const msUntilNext = 60_000 - (Date.now() % 60_000);
if (msUntilNext < MIN_HEADROOM_MS) {
@@ -87,15 +125,19 @@ beforeAll(() => {
});
beforeEach(async () => {
- await testRedis.flushdb();
+ await clearNamespace();
allFactories.length = 0;
lockManager.clear();
+ parkedHandlers.length = 0;
await waitForFreshMinute();
-}, 20_000);
+}, 25_000);
afterEach(async () => {
+ // Release parked handlers first so stop() drains instead of waiting out
+ // drainTimeoutMs, and so their handler-timeout timers get cleared.
+ parkedHandlers.splice(0).forEach((release) => release());
await Promise.allSettled(allFactories.map((f) => f.stop()));
- await testRedis.flushdb();
+ await clearNamespace();
vi.useRealTimers();
});
@@ -114,7 +156,7 @@ describe("single pod", () => {
});
expect(handler).toHaveBeenCalled();
- const keys = await testRedis.keys("{cron}:run:test-job:*");
+ const keys = await testRedis.keys(RUN_KEYS("test-job"));
expect(keys.length).toBe(1);
const run = await testRedis.hgetall(keys[0]);
expect(run.status).toBe("completed");
@@ -137,7 +179,7 @@ describe("multi-pod single fire", () => {
setTimeout(r, 4000);
});
- const keys = await testRedis.keys("{cron}:run:shared-job:*");
+ const keys = await testRedis.keys(RUN_KEYS("shared-job"));
expect(keys.length).toBe(1);
const run = await testRedis.hgetall(keys[0]);
expect(run.status).toBe("completed");
@@ -148,9 +190,14 @@ describe("multi-pod single fire", () => {
// ── slot exhaustion: N+1 factories, exactly N participate ─────────────────────
+// A slot TTL comfortably longer than these tests, so a slot can only disappear
+// by being explicitly released — never by lapsing during an event-loop stall.
+// That makes the exact-count assertions below safe to state as equalities.
+const STABLE_SLOTS = { slotTtlMs: 30_000, slotRefreshMs: 1_000 };
+
describe("slot exhaustion", () => {
test("only PARTICIPANT_SLOTS=5 out of 6 factories claim a slot", async () => {
- const factories = Array.from({ length: 6 }, () => factory());
+ const factories = Array.from({ length: 6 }, () => factory(STABLE_SLOTS));
factories.forEach((f) => f.register({ name: `j`, pattern: FAST_PATTERN, handler: vi.fn(), runHashTtlS: 3600 }));
factories.forEach((f) => f.start());
@@ -159,8 +206,8 @@ describe("slot exhaustion", () => {
setTimeout(r, 2000);
});
- const slotKeys = await testRedis.keys("{cron}:slot:*");
- expect(slotKeys.length).toBeLessThanOrEqual(5);
+ const slotKeys = await testRedis.keys(SLOT_KEYS);
+ expect(slotKeys.length).toBe(5);
}, 8_000);
});
@@ -168,19 +215,19 @@ describe("slot exhaustion", () => {
describe("slot handover", () => {
test("stopping a participant frees its slot for another factory", async () => {
- const factories = Array.from({ length: 6 }, () => factory());
+ const factories = Array.from({ length: 6 }, () => factory(STABLE_SLOTS));
factories.forEach((f) => f.register({ name: `h`, pattern: FAST_PATTERN, handler: vi.fn(), runHashTtlS: 3600 }));
factories.forEach((f) => f.start());
await new Promise((r) => {
setTimeout(r, 2000);
});
- const slotsBefore = await testRedis.keys("{cron}:slot:*");
- expect(slotsBefore.length).toBeLessThanOrEqual(5);
+ const slotsBefore = await testRedis.keys(SLOT_KEYS);
+ expect(slotsBefore.length).toBe(5);
// Stop all — this releases slots
await Promise.all(factories.map((f) => f.stop()));
- const slotsAfter = await testRedis.keys("{cron}:slot:*");
+ const slotsAfter = await testRedis.keys(SLOT_KEYS);
expect(slotsAfter.length).toBe(0);
}, 8_000);
});
@@ -202,7 +249,7 @@ describe("retry", () => {
setTimeout(r, 4000);
});
- const keys = await testRedis.keys("{cron}:run:retry-job:*");
+ const keys = await testRedis.keys(RUN_KEYS("retry-job"));
expect(keys.length).toBe(1);
const run = await testRedis.hgetall(keys[0]);
// After first failure + retry success, should be completed
@@ -220,7 +267,7 @@ describe("retry", () => {
setTimeout(r, 5000);
});
- const keys = await testRedis.keys("{cron}:run:fail-job:*");
+ const keys = await testRedis.keys(RUN_KEYS("fail-job"));
expect(keys.length).toBe(1);
const run = await testRedis.hgetall(keys[0]);
expect(run.status).toBe("failed");
@@ -237,7 +284,7 @@ describe("handler timeout", () => {
// 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 handler = hangingHandler();
const f = factory({
handlerTimeoutMs: 500,
retryBackoffBaseMs: 100,
@@ -257,14 +304,14 @@ describe("handler timeout", () => {
// no retry can be scheduled for this id.
expect(handler).toHaveBeenCalledTimes(1);
- const keys = await testRedis.keys("{cron}:run:hang-job:*");
+ const keys = await testRedis.keys(RUN_KEYS("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);
+ const pending = await testRedis.zrange(PENDING_ZSET, 0, -1);
expect(pending.filter((s) => s.startsWith("hang-job:"))).toEqual([]);
}, 10_000);
});
@@ -305,10 +352,10 @@ describe("retry backoff", () => {
setTimeout(r, 2_000);
});
- const keys = await testRedis.keys("{cron}:run:score-job:*");
+ const keys = await testRedis.keys(RUN_KEYS("score-job"));
expect(keys.length).toBe(1);
- const id = keys[0].replace("{cron}:run:", "");
- const score = await testRedis.zscore("{cron}:pending", id);
+ const id = keys[0].replace(`${KEY_PREFIX}:run:`, "");
+ const score = await testRedis.zscore(PENDING_ZSET, id);
expect(score).not.toBeNull();
expect(Number(score)).toBeGreaterThan(Date.now());
expect(handler).toHaveBeenCalledTimes(1);
@@ -331,7 +378,7 @@ describe("next-fire guard", () => {
});
expect(handler).toHaveBeenCalledTimes(1);
- const keys = await testRedis.keys("{cron}:run:guard-job:*");
+ const keys = await testRedis.keys(RUN_KEYS("guard-job"));
expect(keys.length).toBe(1);
const run = await testRedis.hgetall(keys[0]);
expect(run.status).toBe("failed");
@@ -352,7 +399,7 @@ describe("ZSET cleanup", () => {
setTimeout(r, 3000);
});
- const pending = await testRedis.zrange("{cron}:pending", 0, -1);
+ const pending = await testRedis.zrange(PENDING_ZSET, 0, -1);
expect(pending.filter((s) => s.startsWith("clean-job:"))).toEqual([]);
}, 10_000);
});
@@ -375,7 +422,7 @@ describe("min-age gate", () => {
setTimeout(r, 700);
});
- const keys = await testRedis.keys("{cron}:run:age-gate-job:*");
+ const keys = await testRedis.keys(RUN_KEYS("age-gate-job"));
expect(keys.length).toBe(1); // run is in Redis
expect(handler).not.toHaveBeenCalled(); // but age gate is holding it back
@@ -446,8 +493,13 @@ describe("graceful shutdown", () => {
// grace window: stop() falls back to lease-TTL crash recovery once the
// drain timer expires.
test("stop() releases the slot even when an in-flight handler hangs past drainTimeoutMs", async () => {
- const handler = vi.fn().mockImplementation(() => new Promise<void>(() => {})); // never resolves
- const f = factory({ leaseDurationMs: 30_000, handlerTimeoutMs: 30_000, drainTimeoutMs: 300 });
+ const handler = hangingHandler(); // never resolves until afterEach releases it
+ const f = factory({
+ ...STABLE_SLOTS,
+ leaseDurationMs: 30_000,
+ handlerTimeoutMs: 30_000,
+ drainTimeoutMs: 300
+ });
f.register({ name: "hang-drain-job", pattern: FAST_PATTERN, handler, runHashTtlS: 3600 });
f.start();
@@ -456,8 +508,8 @@ describe("graceful shutdown", () => {
});
expect(handler).toHaveBeenCalled();
- const slotKeysBefore = await testRedis.keys("{cron}:slot:*");
- expect(slotKeysBefore.length).toBeGreaterThan(0);
+ const slotKeysBefore = await testRedis.keys(SLOT_KEYS);
+ expect(slotKeysBefore.length).toBe(1);
const startedAt = Date.now();
await f.stop();
@@ -466,7 +518,7 @@ describe("graceful shutdown", () => {
// Drain timed out; stop() returned within drainTimeoutMs + buffer rather
// than blocking on the hung handler. The slot was released atomically.
expect(elapsed).toBeLessThan(2_000);
- const slotKeysAfter = await testRedis.keys("{cron}:slot:*");
+ const slotKeysAfter = await testRedis.keys(SLOT_KEYS);
expect(slotKeysAfter.length).toBe(0);
}, 10_000);
});
diff --git a/backend/e2e-test/routes/v1/identity-access-token-redesign.spec.ts b/backend/e2e-test/routes/v1/identity-access-token-redesign.spec.ts
index 1f2e5b4a85..60f028a75f 100644
--- a/backend/e2e-test/routes/v1/identity-access-token-redesign.spec.ts
+++ b/backend/e2e-test/routes/v1/identity-access-token-redesign.spec.ts
@@ -135,6 +135,13 @@ const deleteOrgIdentityMembership = async (identityId: string) => {
await testRedis.incr(KeyStorePrefixes.IdentityRevocationVersion(identityId));
};
+// Clears this identity's cached revocation verdicts, forcing the next request
+// to re-resolve against Postgres.
+const dropRevocationVerdicts = async (identityId: string) => {
+ const keys = await testRedis.keys(`${KeyStorePrefixes.IdentityRevocationVerdict(identityId, "")}*`);
+ if (keys.length) await testRedis.del(...keys);
+};
+
const waitForRevocationRow = async (tokenId: string) => {
const deadline = Date.now() + 10_000;
@@ -455,7 +462,10 @@ describe("Identity Access Token — redesigned JWT flow", () => {
expect(revocation.expiresAt.getTime()).toBeGreaterThanOrEqual(expectedExpiresAtMs - 2_000);
expect(revocation.expiresAt.getTime()).toBeLessThanOrEqual(expectedExpiresAtMs + markerSkewMs + 2_000);
- await testRedis.flushdb("SYNC");
+ // Drop only this identity's cached allow-verdicts so the next call
+ // re-checks Postgres. A flushdb() would also wipe the shared server's
+ // BullMQ queues, keystore, and cron leases mid-run.
+ await dropRevocationVerdicts(identityId);
expect((await callDetailsEndpoint(accessToken)).statusCode).toBe(401);
} finally {
diff --git a/backend/e2e-test/routes/v1/secret-replication.spec.ts b/backend/e2e-test/routes/v1/secret-replication.spec.ts
index b56a8f9a04..395758b92a 100644
--- a/backend/e2e-test/routes/v1/secret-replication.spec.ts
+++ b/backend/e2e-test/routes/v1/secret-replication.spec.ts
@@ -4,6 +4,43 @@ import { createSecretV2, deleteSecretV2, getSecretByNameV2, getSecretsV2 } from
import { seedData1 } from "@app/db/seed-data";
+// Replication runs asynchronously through BullMQ, so the imported secret shows
+// up some time after the write. Poll for it instead of sleeping a fixed 10s: a
+// fixed wait is simultaneously too short (it flakes whenever CI contention
+// pushes replication past the deadline) and too long (it burns the full 10s on
+// every pass, even though replication usually lands in well under a second).
+const REPLICATION_TIMEOUT_MS = 25_000;
+const REPLICATION_POLL_MS = 250;
+
+const waitForReplicatedSecret = async (dto: {
+ workspaceId: string;
+ environmentSlug: string;
+ secretPath: string;
+ key: string;
+ value: string;
+ authToken: string;
+}) => {
+ const deadline = Date.now() + REPLICATION_TIMEOUT_MS;
+ for (;;) {
+ try {
+ // eslint-disable-next-line no-await-in-loop
+ const secret = await getSecretByNameV2(dto);
+ if (secret.secretValue === dto.value) return secret;
+ } catch {
+ // Not replicated yet — getSecretByNameV2 asserts on a 200.
+ }
+ if (Date.now() >= deadline) {
+ throw new Error(
+ `Timed out after ${REPLICATION_TIMEOUT_MS}ms waiting for "${dto.key}" to replicate into ${dto.environmentSlug}${dto.secretPath}`
+ );
+ }
+ // eslint-disable-next-line no-await-in-loop
+ await new Promise((resolve) => {
+ setTimeout(resolve, REPLICATION_POLL_MS);
+ });
+ }
+};
+
// dev <- stage <- prod
describe.each([{ secretPath: "/" }, { secretPath: "/deep" }])(
"Secret replication waterfall pattern testing - %secretPath",
@@ -118,17 +155,13 @@ describe.each([{ secretPath: "/" }, { secretPath: "/deep" }])(
value: "stage-value"
});
- // wait for 10 second for replication to finish
- await new Promise((resolve) => {
- setTimeout(resolve, 10000); // time to breathe for db
- });
-
- const secret = await getSecretByNameV2({
+ const secret = await waitForReplicatedSecret({
environmentSlug: seedData1.environment.slug,
workspaceId: seedData1.projectV3.id,
secretPath: testSuitePath,
authToken: jwtAuthToken,
- key: "STAGING_KEY"
+ key: "STAGING_KEY",
+ value: "stage-value"
});
expect(secret.secretKey).toBe("STAGING_KEY");
@@ -173,17 +206,13 @@ describe.each([{ secretPath: "/" }, { secretPath: "/deep" }])(
value: "prod-value"
});
- // wait for 10 second for replication to finish
- await new Promise((resolve) => {
- setTimeout(resolve, 10000); // time to breathe for db
- });
-
- const secret = await getSecretByNameV2({
+ const secret = await waitForReplicatedSecret({
environmentSlug: seedData1.environment.slug,
workspaceId: seedData1.projectV3.id,
secretPath: testSuitePath,
authToken: jwtAuthToken,
- key: "PROD_KEY"
+ key: "PROD_KEY",
+ value: "prod-value"
});
expect(secret.secretKey).toBe("PROD_KEY");
@@ -217,7 +246,7 @@ describe.each([{ secretPath: "/" }, { secretPath: "/deep" }])(
});
});
},
- { timeout: 30000 }
+ { timeout: 60_000 }
);
// dev <- stage, dev <- prod
@@ -343,17 +372,22 @@ describe.each([{ path: "/" }, { path: "/deep" }])(
value: "prod-value"
});
- // wait for 10 second for replication to finish
- await new Promise((resolve) => {
- setTimeout(resolve, 10000); // time to breathe for db
+ // The listSecrets assertion below covers both imports, so wait for both.
+ const secret = await waitForReplicatedSecret({
+ environmentSlug: seedData1.environment.slug,
+ workspaceId: seedData1.projectV3.id,
+ secretPath: testSuitePath,
+ authToken: jwtAuthToken,
+ key: "STAGING_KEY",
+ value: "stage-value"
});
-
- const secret = await getSecretByNameV2({
+ await waitForReplicatedSecret({
environmentSlug: seedData1.environment.slug,
workspaceId: seedData1.projectV3.id,
secretPath: testSuitePath,
authToken: jwtAuthToken,
- key: "STAGING_KEY"
+ key: "PROD_KEY",
+ value: "prod-value"
});
expect(secret.secretKey).toBe("STAGING_KEY");
@@ -402,5 +436,5 @@ describe.each([{ path: "/" }, { path: "/deep" }])(
});
});
},
- { timeout: 30000 }
+ { timeout: 60_000 }
);
diff --git a/backend/src/lib/cron/cron-job.test.ts b/backend/src/lib/cron/cron-job.test.ts
index 1cde759afc..56bb70ec0c 100644
--- a/backend/src/lib/cron/cron-job.test.ts
+++ b/backend/src/lib/cron/cron-job.test.ts
@@ -28,6 +28,14 @@ const makeRedlock = () => ({
})
});
+// Slot claims/refreshes are serialized through a promise chain, so a tick's
+// Redis write lands several microtasks after the tick itself. A single
+// `await Promise.resolve()` doesn't drain that; this does.
+// `advanceTimersByTimeAsync` yields to the real event loop, which drains the
+// whole pending microtask queue — deterministic, unlike counting `await
+// Promise.resolve()` hops.
+const flushSlotOps = () => vi.advanceTimersByTimeAsync(0);
+
// Use a cast via unknown to satisfy the type system for the mocks
type FakeDeps = {
redis: ReturnType<typeof makeRedis>;
@@ -223,7 +231,7 @@ describe("slot election", () => {
const { start, stop } = makeFactory({ redis });
start();
// Let the immediate claimOrRefreshSlot call in start() complete
- await Promise.resolve();
+ await flushSlotOps();
expect(redis.set).toHaveBeenCalledWith("{cron}:slot:0", expect.any(String), "PX", expect.any(Number), "NX");
await stop();
});
@@ -233,7 +241,7 @@ describe("slot election", () => {
redis.set.mockResolvedValueOnce(null).mockResolvedValueOnce("OK");
const { start, stop } = makeFactory({ redis });
start();
- await Promise.resolve();
+ await flushSlotOps();
expect(redis.set).toHaveBeenNthCalledWith(1, "{cron}:slot:0", expect.any(String), "PX", expect.any(Number), "NX");
expect(redis.set).toHaveBeenNthCalledWith(2, "{cron}:slot:1", expect.any(String), "PX", expect.any(Number), "NX");
await stop();
@@ -245,7 +253,7 @@ describe("slot election", () => {
const { register, start, stop } = makeFactory({ redis });
register({ name: "x", pattern: "0 0 * * *", handler: vi.fn(), runHashTtlS: 3600 });
start();
- await Promise.resolve();
+ await flushSlotOps();
expect(redis.eval).not.toHaveBeenCalled();
await stop();
});
@@ -255,9 +263,9 @@ describe("slot election", () => {
redis.set.mockResolvedValueOnce("OK").mockResolvedValue("OK");
const { start, stop } = makeFactory({ redis });
start();
- await Promise.resolve();
+ await flushSlotOps();
vi.advanceTimersByTime(60);
- await Promise.resolve();
+ await flushSlotOps();
const xxCalls = redis.set.mock.calls.filter((c) => (c as string[]).includes("XX"));
expect(xxCalls.length).toBeGreaterThan(0);
await stop();
@@ -268,12 +276,47 @@ describe("slot election", () => {
redis.set.mockResolvedValueOnce("OK").mockResolvedValueOnce(null).mockResolvedValueOnce("OK");
const { start, stop } = makeFactory({ redis });
start();
+ await flushSlotOps();
vi.advanceTimersByTime(60);
- await Promise.resolve();
+ await flushSlotOps();
+ // Claim (NX) → refresh loses the slot (XX returns null) → re-claim (NX).
const nxCalls = redis.set.mock.calls.filter((c) => (c as string[]).includes("NX"));
expect(nxCalls.length).toBeGreaterThanOrEqual(2);
await stop();
});
+
+ // Regression guard for the double-claim race: two refresh ticks that overlap
+ // must not each run the NX loop and leave the pod holding two slots — only
+ // the last-assigned one would ever be released.
+ test("overlapping refresh ticks never claim two different slots", async () => {
+ const redis = makeRedis();
+ // Models real SET NX/XX semantics against an in-memory slot table, with the
+ // held slot expiring right as the refresh observes it (XX misses). Without
+ // serialization, two ticks both observe the loss, both null `currentSlot`,
+ // and the second walks past the slot the first just re-took.
+ const held = new Map<string, string>();
+ redis.set.mockImplementation(async (key: string, value: string, _px: string, _ttl: number, mode: string) => {
+ if (mode === "NX") {
+ if (held.has(key)) return null;
+ held.set(key, value);
+ return "OK";
+ }
+ held.delete(key); // XX: the slot's TTL lapsed before this refresh landed
+ return null;
+ });
+
+ const { start, stop } = makeFactory({ redis });
+ start();
+ await flushSlotOps();
+
+ // Two refresh intervals fire back-to-back with no drain in between.
+ vi.advanceTimersByTime(50);
+ vi.advanceTimersByTime(50);
+ await flushSlotOps();
+
+ expect([...held.keys()]).toEqual(["{cron}:slot:0"]);
+ await stop();
+ });
});
describe("claim and execute", () => {
@@ -284,10 +327,11 @@ describe("claim and execute", () => {
const { register, start, stop } = makeFactory({ redis });
register({ name: "x", pattern: "0 0 * * *", handler: vi.fn(), runHashTtlS: 3600 });
start();
- await Promise.resolve();
+ await flushSlotOps();
vi.advanceTimersByTime(300);
await Promise.resolve();
const firstCount = redis.eval.mock.calls.length;
+ expect(firstCount).toBeGreaterThan(0);
vi.advanceTimersByTime(30_000);
await Promise.resolve();
expect(redis.eval.mock.calls.length).toBe(firstCount);
diff --git a/backend/src/lib/cron/cron-job.ts b/backend/src/lib/cron/cron-job.ts
index ef907f29f3..72eabf1e33 100644
--- a/backend/src/lib/cron/cron-job.ts
+++ b/backend/src/lib/cron/cron-job.ts
@@ -70,11 +70,10 @@ const DEFAULTS = {
// ── redis schema ──────────────────────────────────────────────────────────────
+// Every key this module writes lives under a single Redis Cluster hash tag so
+// multi-key Lua scripts never return CROSSSLOT. A custom `keyPrefix` must keep
+// that property — see `assertHashTagged`.
const KEY_HASH_TAG = "{cron}";
-const SLOT_KEY = (i: number) => `${KEY_HASH_TAG}:slot:${i}`;
-const RUN_KEY = (id: string) => `${KEY_HASH_TAG}:run:${id}`;
-const LEASE_KEY = (id: string) => `${KEY_HASH_TAG}:lease:${id}`;
-const PENDING_ZSET = `${KEY_HASH_TAG}:pending`;
// Run-hash status values. Stored as plain strings in the hash so we don't
// break Redis tooling, but referenced through this object to avoid drift.
@@ -139,6 +138,17 @@ class HandlerTimeoutError extends Error {
}
}
+// A prefix without a `{...}` hash tag would spread this module's keys across
+// Cluster slots and break every multi-key EVAL. Fail loudly at construction
+// rather than silently at the first enqueue tick.
+const assertHashTagged = (keyPrefix: string) => {
+ const start = keyPrefix.indexOf("{");
+ const end = keyPrefix.indexOf("}", start + 1);
+ if (start < 0 || end <= start + 1) {
+ throw new Error(`cron: keyPrefix "${keyPrefix}" must contain a non-empty Redis Cluster hash tag, e.g. "{cron}"`);
+ }
+};
+
export type TCronJobFactory = ReturnType<typeof cronJobFactory>;
// ── factory ───────────────────────────────────────────────────────────────────
@@ -155,7 +165,8 @@ export const cronJobFactory = ({
handlerTimeoutMs = DEFAULTS.handlerTimeoutMs,
retryBackoffBaseMs = DEFAULTS.retryBackoffBaseMs,
retryBackoffMaxMs = DEFAULTS.retryBackoffMaxMs,
- drainTimeoutMs = DEFAULTS.drainTimeoutMs
+ drainTimeoutMs = DEFAULTS.drainTimeoutMs,
+ keyPrefix = KEY_HASH_TAG
}: {
redis: Redis | Cluster;
redlock: Redlock;
@@ -169,7 +180,20 @@ export const cronJobFactory = ({
retryBackoffBaseMs?: number;
retryBackoffMaxMs?: number;
drainTimeoutMs?: number;
+ /**
+ * Namespace for every Redis key this manager owns. Defaults to the production
+ * `{cron}` namespace. Tests override it so a test-owned manager and the
+ * server's real one can share a Redis without colliding on slot keys.
+ */
+ keyPrefix?: string;
}) => {
+ assertHashTagged(keyPrefix);
+
+ const SLOT_KEY = (i: number) => `${keyPrefix}:slot:${i}`;
+ const RUN_KEY = (id: string) => `${keyPrefix}:run:${id}`;
+ const LEASE_KEY = (id: string) => `${keyPrefix}:lease:${id}`;
+ const PENDING_ZSET = `${keyPrefix}:pending`;
+
const workerId = randomUUID();
const entries = new Map<string, CronEntry>();
const lastEnqueuedAt = new Map<string, number>();
@@ -178,6 +202,9 @@ export const cronJobFactory = ({
let enqueueTimer: ReturnType<typeof setInterval> | null = null;
let processTimer: ReturnType<typeof setInterval> | null = null;
let currentSlot: number | null = null;
+ let stopped = false;
+ // Tail of the serialized slot-operation chain. Never rejects.
+ let slotOp: Promise<void> = Promise.resolve();
// ── helpers ────────────────────────────────────────────────────────────
@@ -340,6 +367,24 @@ export const cronJobFactory = ({
}
};
+ // Runs slot claims/refreshes strictly one at a time.
+ //
+ // `claimOrRefreshSlot` awaits between reading `currentSlot` and writing it,
+ // so two overlapping ticks could both observe a lost slot, both null
+ // `currentSlot`, and then claim two *different* slots — the pod would burn
+ // two of the five participant slots and leak one on shutdown, since only the
+ // last-assigned `currentSlot` is ever released.
+ //
+ // Chaining also gives stop() one handle to await, so it can never read
+ // `currentSlot` mid-handover (skipping the release) or have a late claim land
+ // after the release.
+ const runSlotOp = () => {
+ slotOp = slotOp
+ .then(() => (stopped ? undefined : claimOrRefreshSlot()))
+ .catch((err: unknown) => logger.error({ err }, "cron: slot refresh failed"));
+ return slotOp;
+ };
+
// ── enqueue ─────────────────────────────────────────────────────────────────
// For each registered entry, computes the most recent scheduled fire time
@@ -530,10 +575,11 @@ export const cronJobFactory = ({
// immediately so the pod doesn't wait a full `slotRefreshMs` before
// participating.
const start = () => {
- slotTimer = setInterval(safeTick("slot refresh", claimOrRefreshSlot), slotRefreshMs);
+ stopped = false;
+ slotTimer = setInterval(() => void runSlotOp(), slotRefreshMs);
enqueueTimer = setInterval(safeTick("enqueue tick", enqueueTick), enqueueIntervalMs);
processTimer = setInterval(safeTick("process tick", processTick), processIntervalMs);
- safeTick("initial slot claim", claimOrRefreshSlot)();
+ void runSlotOp();
};
// Stops the timers, drains in-flight handlers, and atomically releases the
@@ -544,6 +590,7 @@ export const cronJobFactory = ({
// aren't aborted mid-execution and graceful redeploys don't leave runs
// stuck in `status='running'` until the lease TTL elapses.
const stop = async () => {
+ stopped = true;
if (slotTimer) clearInterval(slotTimer);
if (enqueueTimer) clearInterval(enqueueTimer);
if (processTimer) clearInterval(processTimer);
@@ -566,9 +613,16 @@ export const cronJobFactory = ({
if (timeoutHandle) clearTimeout(timeoutHandle);
}
}
+
+ // No new slot ops can be queued (timers cleared, `stopped` set), so this is
+ // the final tail. Waiting on it guarantees `currentSlot` is settled and that
+ // nothing can re-create the key after the release below.
+ await slotOp;
+
if (currentSlot !== null) {
await redis.eval(RELEASE_SLOT_IF_MINE_LUA, 1, SLOT_KEY(currentSlot), workerId);
logger.info(`cron: released slot ${currentSlot} [worker=${workerId}]`);
+ currentSlot = null;
}
};