Skip to content

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

feat(cron): enforce 5-field pattern requirement and improve logging

Victor Hugo dos Santosf3118956d879
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index a05ec9a31a..380073da93 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -663,7 +663,7 @@ Recurring work runs through the cron manager in `src/lib/cron/cron-job.ts` (`cro
- Failures (non-timeout) retry with exponential backoff (base 30 s, max 5 min) up to `maxAttempts`, but only if the retry would still fit before the next scheduled fire. Otherwise the next fire is treated as the natural retry.
- Long-running handlers should override `handlerTimeoutMs` / `leaseDurationMs` per-entry (must satisfy `handlerTimeoutMs <= leaseDurationMs`).
- **A fire is not picked up at its scheduled time; it is picked up at a deterministic offset past it.** Cron patterns cluster hard, so without a spread one pod claims a dozen handlers in a single tick. Two knobs bound that, both in `cronJobFactory`:
- - **Jitter** spreads pickup, and is *derived, never configured*: a job's window is `JITTER_INTERVAL_FRACTION` (0.25) of its own cron interval, capped by the factory's `maxJitterMs` (5 min), so a `*/5` job gets 75s and anything past a 20-minute interval gets the full 5 min. Two things follow from the fraction being below 1: a run can never reach its own next fire, and the first retry always fits (worst case `0.25 x interval + 30s backoff + 1s`, under `interval` for anything above ~41s, and cron cannot fire faster than every 60s). The offset within the window is `sha256(name) % window`, never random: every pod computes a run's eligibility independently and the run id is keyed on the *unjittered* fire, so a per-pod offset would break the Redis enqueue dedup and the lease logic. Only the pending-zset score carries the offset; the run id and `scheduled_at` are unchanged. Development wiring passes `maxJitterMs: 0` so a job runs when its pattern says.
+ - **Jitter** spreads pickup, and is *derived, never configured*: a job's window is `JITTER_INTERVAL_FRACTION` (0.25) of its own cron interval, capped by the factory's `maxJitterMs` (5 min), so a `*/5` job gets 75s and anything at or past a 20-minute interval gets the full 5 min. Two things follow from the fraction being below 1: a run can never reach its own next fire, and the first retry always fits (worst case `0.25 x interval + 30s backoff + 1s`, under `interval` for anything above ~41s, and cron cannot fire faster than every 60s). The offset within the window is `sha256(name) % window`, never random: every pod computes a run's eligibility independently and the run id is keyed on the *unjittered* fire, so a per-pod offset would break the Redis enqueue dedup and the lease logic. Only the pending-zset score carries the offset; the run id and `scheduled_at` are unchanged. Development wiring passes `maxJitterMs: 0` so a job runs when its pattern says. `register` rejects anything but a 5-field pattern: the retry model assumes minute granularity, and a 6-field pattern firing every 30s would have its first retry land past its own next fire. Sub-minute recurring work belongs on a `setInterval` or a queue, as the event outbox relay does.
- **`maxConcurrentHandlers`** bounds accumulation across *overlapping* ticks, the failure mode when a handler runs long. **It does not bound a burst**, because the `processTick` loop is serial (`await processCandidate` per id), so one tick works through its whole batch back to back on a single pod whatever the cap is. `PROCESS_BATCH_SIZE` still bounds the zset scan, not execution.
**When to use cron vs. queue**:
diff --git a/backend/src/lib/cron/cron-job.test.ts b/backend/src/lib/cron/cron-job.test.ts
index 88b1b3548c..941a9a0a14 100644
--- a/backend/src/lib/cron/cron-job.test.ts
+++ b/backend/src/lib/cron/cron-job.test.ts
@@ -1085,6 +1085,52 @@ describe("handler concurrency cap", () => {
await stopPromise;
});
+ // The retry model assumes minute granularity. A 6-field pattern firing every 30s would get a
+ // 7.5s window whose first retry lands at 38.5s, past its own next fire, and be marked
+ // failed-final instead of retried. Reject it at registration rather than degrade quietly.
+ test("rejects a sub-minute (6-field) pattern", () => {
+ const { register } = makeFactory();
+ expect(() => register({ name: "x", pattern: "*/30 * * * * *", handler: vi.fn(), runHashTtlS: 3600 })).toThrow(
+ /must have 5 fields/
+ );
+ });
+
+ test("accepts the 5-field patterns the codebase registers", () => {
+ const { register } = makeFactory();
+ ["*/5 * * * *", "0 0 * * *", "0 0 19 2,5,8,11 *", "23 3 * * *"].forEach((pattern, i) => {
+ expect(() => register({ name: `x${i}`, pattern, handler: vi.fn(), runHashTtlS: 3 * 24 * 60 * 60 })).not.toThrow();
+ });
+ });
+
+ // The pod defers on every tick while saturated, so the line is throttled. Without it a long
+ // backlog emits one info line per processIntervalMs, for every pod, for as long as it lasts.
+ test("the at-capacity line is throttled, not emitted every tick", async () => {
+ vi.setSystemTime(new Date("2024-01-01T00:00:30Z"));
+ const redis = makeRedis();
+ setupPendingRuns(redis, 4);
+ const { handler, resolvers } = makeBlockingHandler();
+ const redlock = makeRedlock();
+ vi.mocked(logger.info).mockClear();
+
+ const f = makeCappedFactory(redis, redlock, 1);
+ f.register({ name: "x", pattern: "* * * * *", handler, runHashTtlS: 60 * 60 });
+ f.start();
+
+ // ~30 process ticks (processIntervalMs=100 here) inside one throttle window.
+ await vi.advanceTimersByTimeAsync(3_000);
+
+ const capacityLines = vi
+ .mocked(logger.info)
+ .mock.calls.map(([m]) => m)
+ .filter((m) => typeof m === "string" && m.includes("at handler capacity"));
+ expect(capacityLines.length).toBe(1);
+
+ resolvers.forEach((resolve) => resolve());
+ const stopPromise = f.stop();
+ await vi.advanceTimersByTimeAsync(100);
+ await stopPromise;
+ });
+
test("factory rejects a cap below 1", () => {
expect(() =>
cronJobFactory({
diff --git a/backend/src/lib/cron/cron-job.ts b/backend/src/lib/cron/cron-job.ts
index 64a386316d..c1cca36197 100644
--- a/backend/src/lib/cron/cron-job.ts
+++ b/backend/src/lib/cron/cron-job.ts
@@ -65,6 +65,7 @@ export const CronJobName = {
// Raising this past ~0.48 would start costing short-interval jobs their retry.
const JITTER_INTERVAL_FRACTION = 0.25;
+const CRON_FIELD_COUNT = 5;
const PARTICIPANT_SLOTS = 5;
const PROCESS_BATCH_SIZE = 50;
// Safety buffer in `fitsBeforeNextFire`: if the retry's nextAttemptAt is within
@@ -248,6 +249,11 @@ export const cronJobFactory = ({
}
const workerId = randomUUID();
+ // A saturated pod defers on every tick, so logging per tick would emit a line every
+ // `processIntervalMs` for as long as the backlog lasts. Throttled so a sustained backlog
+ // stays visible without burying every other cron line.
+ const CAPACITY_LOG_INTERVAL_MS = 60_000;
+ let lastCapacityLogAtMs = 0;
const entries = new Map<string, CronEntry>();
const lastEnqueuedAt = new Map<string, number>();
const inFlight = new Set<Promise<unknown>>();
@@ -412,6 +418,11 @@ export const cronJobFactory = ({
}
if (entries.has(name)) throw new Error(`cron[${name}] already registered`);
CronExpressionParser.parse(pattern, { tz: "UTC" }); // validate at registration
+ if (pattern.trim().split(/\s+/).length !== CRON_FIELD_COUNT) {
+ throw new Error(
+ `cron[${name}] pattern "${pattern}" must have ${CRON_FIELD_COUNT} fields. The cron manager schedules at minute granularity; sub-minute work belongs on a setInterval or a queue`
+ );
+ }
if (runHashTtlS * 1000 <= maxJitterMs) {
throw new Error(
@@ -628,12 +639,12 @@ export const cronJobFactory = ({
return;
}
+ if (atHandlerCapacity()) return;
+
if (isStalled) {
logger.info(`cron[${data.name}]: re-claiming stalled run [id=${id}] [previous_worker=${data.worker_id}]`);
}
- if (atHandlerCapacity()) return;
-
// 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.
@@ -666,11 +677,15 @@ export const cronJobFactory = ({
for (let i = 0; i < ids.length; i += 1) {
if (atHandlerCapacity()) {
- logger.info(
- `cron: at handler capacity (${maxConcurrentHandlers}), deferring ${
- ids.length - i
- } due run(s) [worker=${workerId}]`
- );
+ const now = Date.now();
+ if (now - lastCapacityLogAtMs >= CAPACITY_LOG_INTERVAL_MS) {
+ lastCapacityLogAtMs = now;
+ logger.info(
+ `cron: at handler capacity (${maxConcurrentHandlers}), deferring ${
+ ids.length - i
+ } due run(s) [worker=${workerId}]`
+ );
+ }
break;
}
try {