Skip to content

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

28.2 KB
Raw Blame
import type { Redis } from "ioredis";
import { afterEach, beforeAll, beforeEach, describe, expect, test, vi } from "vitest";

import { cronJobFactory } from "@app/lib/cron/cron-job";
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 LAST_KEY = (name: string) => `${KEY_PREFIX}:last:${name}`;

// waitForFreshMinute keeps every test clear of a boundary, so this is FAST_PATTERN's latest fire.
const currentFireMs = () => Math.floor(Date.now() / 60_000) * 60_000;

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
const lockManager = new Map<string, { timeout: NodeJS.Timeout; held: boolean }>();

// Mock Redlock for testing
const createTestRedlock = () => ({
  async using(keys: string[], duration: number, fn: (signal: AbortSignal) => Promise<void>) {
    const lockKey = keys[0];
    const existing = lockManager.get(lockKey);
    if (existing?.held) {
      throw new Error("Lock already held");
    }
    const timeout = setTimeout(() => lockManager.delete(lockKey), duration);
    lockManager.set(lockKey, { timeout, held: true });

    try {
      const controller = new AbortController();
      await fn(controller.signal);
    } finally {
      const lock = lockManager.get(lockKey);
      if (lock?.timeout) {
        clearTimeout(lock.timeout);
      }
      lockManager.delete(lockKey);
    }
  }
});

const makeFactory = (overrides?: Partial<Parameters<typeof cronJobFactory>[0]>) => {
  const redis = testRedis;
  const redlock = createTestRedlock() as unknown as Parameters<typeof cronJobFactory>[0]["redlock"];
  return cronJobFactory({
    redis,
    redlock,
    keyPrefix: KEY_PREFIX,
    slotTtlMs: 500,
    slotRefreshMs: 100,
    enqueueIntervalMs: 500,
    processIntervalMs: 200,
    leaseDurationMs: 5_000,
    retryBackoffBaseMs: 100,
    retryBackoffMaxMs: 500,
    handlerTimeoutMs: 5_000,
    minProcessAgeMs: 0,
    // Off by default so pickup timing is deterministic. Every test here registers against
    // FAST_PATTERN, whose derived window is 15s, while `waitForFreshMinute` leaves the suite
    // starting at an arbitrary point after a minute boundary. A job would therefore be held
    // back by anything from 0 to its full offset depending on when the test happened to run,
    // which makes every "handler was called by Xms" assertion a coin flip. The jitter
    // describe below opts back in.
    maxJitterMs: 0,
    // Keep test cleanup snappy. Production default is 25s to fit Kubernetes'
    // grace period; in tests we'd rather not stall afterEach if a handler
    // happens to be in flight at shutdown.
    drainTimeoutMs: 1_000,
    ...overrides
  });
};

const FAST_PATTERN = "* * * * *"; // fires every minute
const allFactories: ReturnType<typeof makeFactory>[] = [];

// The manager skips the latest fire of a job that has never fired, so by default every job a
// test registers is marked as having fired in the previous minute, which lets it run in the
// current one. NX keeps a value an earlier factory in the same test already wrote. The first
// enqueue tick runs enqueueIntervalMs after start(), long after this write lands.
const factory = (
  overrides?: Partial<Parameters<typeof cronJobFactory>[0]>,
  { existingJobs = true }: { existingJobs?: boolean } = {}
) => {
  const f = makeFactory(overrides);
  allFactories.push(f);
  return {
    ...f,
    register: (entry: Parameters<typeof f.register>[0]) => {
      f.register(entry);
      if (existingJobs) void testRedis.set(LAST_KEY(entry.name), String(currentFireMs() - 60_000), "NX");
    }
  };
};

// For tests about a job's very first registration.
const newJobFactory = (overrides?: Partial<Parameters<typeof cronJobFactory>[0]>) =>
  factory(overrides, { existingJobs: false });

// 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.
// 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) {
    await new Promise<void>((resolve) => {
      setTimeout(resolve, msUntilNext + 200);
    });
  }
};

beforeAll(() => {
  initLogger();
});

beforeEach(async () => {
  await clearNamespace();
  allFactories.length = 0;
  lockManager.clear();
  parkedHandlers.length = 0;
  await waitForFreshMinute();
}, 25_000);

afterEach(async () => {
  parkedHandlers.splice(0).forEach((release) => release());
  await Promise.allSettled(allFactories.map((f) => f.stop()));
  await clearNamespace();
  vi.useRealTimers();
});

// ── single-pod: handler runs and completes ─────────────────────────────────────

describe("single pod", () => {
  test("handler is called and run hash ends up completed", async () => {
    const handler = vi.fn().mockResolvedValue(undefined);
    const f = factory();
    f.register({ name: "test-job", pattern: FAST_PATTERN, handler, runHashTtlS: 3600 });
    f.start();

    // Give the tick time to fire (slot acquisition + enqueue + claim + execute)
    await new Promise((r) => {
      setTimeout(r, 3000);
    });

    expect(handler).toHaveBeenCalled();
    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");
  }, 10_000);
});

// ── two pods: exactly one handler invocation per fire boundary ─────────────────

describe("multi-pod single fire", () => {
  test("exactly one handler invocation across two factory instances", async () => {
    const handler = vi.fn().mockResolvedValue(undefined);
    const f1 = factory();
    const f2 = factory();
    f1.register({ name: "shared-job", pattern: FAST_PATTERN, handler, runHashTtlS: 3600 });
    f2.register({ name: "shared-job", pattern: FAST_PATTERN, handler, runHashTtlS: 3600 });
    f1.start();
    f2.start();

    await new Promise((r) => {
      setTimeout(r, 4000);
    });

    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");
    // Handler should have been called exactly once across both pods
    expect(handler).toHaveBeenCalledTimes(1);
  }, 12_000);
});

// ── 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(STABLE_SLOTS));
    factories.forEach((f) => f.register({ name: `j`, pattern: FAST_PATTERN, handler: vi.fn(), runHashTtlS: 3600 }));
    factories.forEach((f) => f.start());

    // Allow slot acquisition to propagate
    await new Promise((r) => {
      setTimeout(r, 2000);
    });

    const slotKeys = await testRedis.keys(SLOT_KEYS);
    expect(slotKeys.length).toBe(5);
  }, 8_000);
});

// ── slot handover on stop ──────────────────────────────────────────────────────

describe("slot handover", () => {
  test("stopping a participant frees its slot for another factory", async () => {
    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(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(SLOT_KEYS);
    expect(slotsAfter.length).toBe(0);
  }, 8_000);
});

// ── retry on failure ──────────────────────────────────────────────────────────

describe("retry", () => {
  test("failed handler flips status back to pending with last_error populated", async () => {
    let calls = 0;
    const handler = vi.fn().mockImplementation(async () => {
      calls += 1;
      if (calls === 1) throw new Error("transient failure");
    });
    const f = factory();
    f.register({ name: "retry-job", pattern: FAST_PATTERN, handler, maxAttempts: 3, runHashTtlS: 3600 });
    f.start();

    await new Promise((r) => {
      setTimeout(r, 4000);
    });

    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
    expect(run.status).toBe("completed");
    expect(handler).toHaveBeenCalledTimes(2);
  }, 12_000);

  test("after maxAttempts failures status becomes failed", async () => {
    const handler = vi.fn().mockRejectedValue(new Error("always fails"));
    const f = factory();
    f.register({ name: "fail-job", pattern: FAST_PATTERN, handler, maxAttempts: 2, runHashTtlS: 3600 });
    f.start();

    await new Promise((r) => {
      setTimeout(r, 5000);
    });

    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");
    expect(run.last_error).toContain("always fails");
    expect(handler).toHaveBeenCalledTimes(2);
  }, 15_000);
});

// ── handler timeout ────────────────────────────────────────────────────────────

describe("handler timeout", () => {
  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 = hangingHandler();
    const f = factory({
      handlerTimeoutMs: 500,
      retryBackoffBaseMs: 100,
      retryBackoffMaxMs: 200
    });
    f.register({ name: "hang-job", pattern: FAST_PATTERN, handler, maxAttempts: 5, runHashTtlS: 3600 });
    f.start();

    // Enqueue (~500ms) + first attempt hangs for handlerTimeoutMs (500ms) +
    // 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);
    });

    // 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(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(PENDING_ZSET, 0, -1);
    expect(pending.filter((s) => s.startsWith("hang-job:"))).toEqual([]);
  }, 10_000);
});

// ── retry backoff spacing ──────────────────────────────────────────────────────

describe("retry backoff", () => {
  test("retries are spaced out by backoffBase, not back-to-back", async () => {
    const callTimes: number[] = [];
    const handler = vi.fn().mockImplementation(async () => {
      callTimes.push(Date.now());
      throw new Error("boom");
    });
    const f = factory({ retryBackoffBaseMs: 700, retryBackoffMaxMs: 2_000 });
    f.register({ name: "backoff-job", pattern: FAST_PATTERN, handler, maxAttempts: 4, runHashTtlS: 3600 });
    f.start();

    // Two failures separated by ~700ms backoff = ~1.4s + enqueue overhead.
    await new Promise((r) => {
      setTimeout(r, 3_500);
    });

    expect(callTimes.length).toBeGreaterThanOrEqual(2);
    const gap = callTimes[1] - callTimes[0];
    // Tolerance: backoff is 700ms; allow some scheduling slop on either side.
    expect(gap).toBeGreaterThanOrEqual(500);
  }, 10_000);

  test("non-final failure updates zset score to next_attempt_at (future)", async () => {
    const handler = vi.fn().mockRejectedValue(new Error("boom"));
    const f = factory({ retryBackoffBaseMs: 5_000, retryBackoffMaxMs: 10_000 });
    f.register({ name: "score-job", pattern: FAST_PATTERN, handler, maxAttempts: 3, runHashTtlS: 3600 });
    f.start();

    // Give time for one failure to be processed and re-scored, but not for the
    // 5s backoff to elapse.
    await new Promise((r) => {
      setTimeout(r, 2_000);
    });

    const keys = await testRedis.keys(RUN_KEYS("score-job"));
    expect(keys.length).toBe(1);
    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);
  }, 10_000);
});

// ── next-fire guard ────────────────────────────────────────────────────────────

describe("next-fire guard", () => {
  test("failure with backoff > cron interval is marked final immediately", async () => {
    const handler = vi.fn().mockRejectedValue(new Error("boom"));
    // backoffBase (65s) > 60s cron interval — guard should mark this final on
    // the very first failure regardless of maxAttempts.
    const f = factory({ retryBackoffBaseMs: 65_000, retryBackoffMaxMs: 65_000 });
    f.register({ name: "guard-job", pattern: FAST_PATTERN, handler, maxAttempts: 5, runHashTtlS: 3600 });
    f.start();

    await new Promise((r) => {
      setTimeout(r, 2_000);
    });

    expect(handler).toHaveBeenCalledTimes(1);
    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");
    expect(run.last_error).toContain("boom");
  }, 10_000);
});

// ── ZSET cleared on success ────────────────────────────────────────────────────

describe("ZSET cleanup", () => {
  test("{cron}:pending ZSET is empty after successful execution", async () => {
    const handler = vi.fn().mockResolvedValue(undefined);
    const f = factory();
    f.register({ name: "clean-job", pattern: FAST_PATTERN, handler, runHashTtlS: 3600 });
    f.start();

    await new Promise((r) => {
      setTimeout(r, 3000);
    });

    const pending = await testRedis.zrange(PENDING_ZSET, 0, -1);
    expect(pending.filter((s) => s.startsWith("clean-job:"))).toEqual([]);
  }, 10_000);
});

// ── min-age gate ───────────────────────────────────────────────────────────────

describe("min-age gate", () => {
  test("run is enqueued but handler is withheld until minProcessAgeMs elapses", async () => {
    const handler = vi.fn().mockResolvedValue(undefined);
    // Override only the age gate; all other timings stay at their e2e defaults.
    const f = factory({ minProcessAgeMs: 500 });
    f.register({ name: "age-gate-job", pattern: FAST_PATTERN, handler, runHashTtlS: 3600 });
    f.start();

    // Wait for the enqueue tick (enqueueIntervalMs=500ms) + buffer so the run
    // hash is present in Redis, but NOT long enough for the 500ms age gate to
    // clear. Enqueue fires at ~500ms; at 700ms the run is only ~200ms old and
    // the process ticks at 600ms / 800ms both skip it.
    await new Promise((r) => {
      setTimeout(r, 700);
    });

    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

    // Earliest possible pickup: enqueue at ~500ms + minProcessAgeMs 500ms = ~1000ms.
    // Allow until 2500ms total to absorb any scheduling jitter.
    await new Promise((r) => {
      setTimeout(r, 1800);
    });

    expect(handler).toHaveBeenCalled();
  }, 10_000);
});

// ── jitter ─────────────────────────────────────────────────────────────────────

describe("jitter", () => {
  // Asserted on the zset score rather than on wall-clock pickup: the score is written once at
  // enqueue and is what actually holds a run back, so this pins the behaviour against real
  // Redis without depending on where in the minute the test happens to start.
  const readEnqueued = async (name: string) => {
    const keys = await testRedis.keys(RUN_KEYS(name));
    expect(keys.length).toBe(1);
    const id = keys[0].replace(`${KEY_PREFIX}:run:`, "");
    const [score, scheduledAt] = await Promise.all([
      testRedis.zscore(PENDING_ZSET, id),
      testRedis.hget(`${KEY_PREFIX}:run:${id}`, "scheduled_at")
    ]);
    expect(score).not.toBeNull();
    expect(scheduledAt).not.toBeNull();
    return { eligibleAt: Number(score), scheduledAt: Number(scheduledAt), id };
  };

  // processIntervalMs is parked past the test so nothing claims the run and clears the zset
  // entry out from under the assertion.
  const enqueueOnly = { processIntervalMs: 60_000 };

  test("a jittered run is scored past its scheduled fire, and the id still keys on the fire", async () => {
    const f = factory({ ...enqueueOnly, maxJitterMs: 5 * 60_000 });
    f.register({ name: "jitter-job", pattern: FAST_PATTERN, handler: vi.fn(), runHashTtlS: 3600 });
    f.start();
    await new Promise((r) => {
      setTimeout(r, 900);
    });

    const { eligibleAt, scheduledAt, id } = await readEnqueued("jitter-job");
    expect(eligibleAt).toBeGreaterThan(scheduledAt);
    // FAST_PATTERN's window is a quarter of its 60s interval.
    expect(eligibleAt - scheduledAt).toBeLessThan(15_000);
    // Run identity stays on the unjittered fire, which is what the dedup and lease keys use.
    expect(id).toBe(`jitter-job:${scheduledAt}`);
  }, 10_000);

  test("maxJitterMs: 0 scores the run at its exact scheduled fire", async () => {
    const f = factory({ ...enqueueOnly, maxJitterMs: 0 });
    f.register({ name: "no-jitter-job", pattern: FAST_PATTERN, handler: vi.fn(), runHashTtlS: 3600 });
    f.start();
    await new Promise((r) => {
      setTimeout(r, 900);
    });

    const { eligibleAt, scheduledAt } = await readEnqueued("no-jitter-job");
    expect(eligibleAt).toBe(scheduledAt);
  }, 10_000);
});

// ── dedup across restarts ──────────────────────────────────────────────────────

describe("dedup across restarts", () => {
  const sleep = (ms: number) =>
    new Promise((r) => {
      setTimeout(r, ms);
    });
  // Only Date is faked, so the manager's timers keep running in real time while every enqueue
  // tick sees the same distance from the fire. afterEach restores the real clock.
  const freezeClockAfterFire = (ms: number) => {
    const fire = currentFireMs();
    vi.useFakeTimers({ toFake: ["Date"] });
    vi.setSystemTime(fire + ms);
    return fire;
  };

  test("a restart after the run hash expires does not run the same fire again", async () => {
    const first = vi.fn().mockResolvedValue(undefined);
    const f1 = factory();
    f1.register({ name: "restart-job", pattern: FAST_PATTERN, handler: first, runHashTtlS: 3600 });
    f1.start();
    await sleep(2000);
    expect(first).toHaveBeenCalledTimes(1);
    await f1.stop();

    const runKeys = await testRedis.keys(RUN_KEYS("restart-job"));
    await testRedis.del(...runKeys);

    const second = vi.fn().mockResolvedValue(undefined);
    const f2 = factory();
    f2.register({ name: "restart-job", pattern: FAST_PATTERN, handler: second, runHashTtlS: 3600 });
    f2.start();
    await sleep(1500);

    expect(second).not.toHaveBeenCalled();
    expect(await testRedis.keys(RUN_KEYS("restart-job"))).toEqual([]);
  }, 10_000);

  // Migration, part 1 of 2 (see ENQUEUE_RUN_LUA): remove with that branch.
  test("a run hash written without a last value is recorded instead of enqueued again", async () => {
    const scheduledAt = currentFireMs();
    await testRedis.hset(
      `${KEY_PREFIX}:run:backfill-job:${scheduledAt}`,
      "name",
      "backfill-job",
      "status",
      "completed"
    );

    const handler = vi.fn().mockResolvedValue(undefined);
    const f = newJobFactory();
    f.register({ name: "backfill-job", pattern: FAST_PATTERN, handler, runHashTtlS: 3600 });
    f.start();
    await sleep(1500);

    expect(handler).not.toHaveBeenCalled();
    expect(await testRedis.get(LAST_KEY("backfill-job"))).toBe(String(scheduledAt));
  }, 10_000);

  test("a job that has never fired skips the fire due before it and waits for the next one", async () => {
    const fire = freezeClockAfterFire(30_000);
    const handler = vi.fn().mockResolvedValue(undefined);
    const f = newJobFactory();
    f.register({ name: "new-job", pattern: FAST_PATTERN, handler, runHashTtlS: 3600 });
    f.start();
    await sleep(1500);

    expect(handler).not.toHaveBeenCalled();
    expect(await testRedis.keys(RUN_KEYS("new-job"))).toEqual([]);
    expect(await testRedis.get(LAST_KEY("new-job"))).toBe(String(fire));
  }, 10_000);

  // Migration, part 2 of 2 (see ENQUEUE_RUN_LUA): remove with that branch. Jobs that ran before
  // the last key existed have no last value either. When the first deploy that writes it lands
  // just after a boundary, no pod may have enqueued that fire yet, and treating the job as new
  // would silently drop it.
  test("a job with no last value still runs a fire that only just became due", async () => {
    freezeClockAfterFire(100);
    const handler = vi.fn().mockResolvedValue(undefined);
    const f = newJobFactory();
    f.register({ name: "boundary-job", pattern: FAST_PATTERN, handler, runHashTtlS: 3600 });
    f.start();
    await sleep(2000);

    expect(handler).toHaveBeenCalledTimes(1);
  }, 10_000);
});

// ── graceful shutdown ──────────────────────────────────────────────────────────

describe("graceful shutdown", () => {
  // End-to-end regression guard for the BullMQ Worker.close() drain semantics:
  // stop() must wait for in-flight handlers to finish before releasing the
  // slot. Without this, redeploys would tear down active handlers mid-flight
  // (risking half-applied destructive operations like rotations) and leave
  // run hashes stuck in `status='running'` until the lease TTL elapses.
  test("stop() waits for in-flight handler to complete before resolving", async () => {
    let releaseHandler: () => void = () => {};
    let handlerStartedAt = 0;
    const handler = vi.fn().mockImplementation(
      () =>
        new Promise<void>((resolve) => {
          handlerStartedAt = Date.now();
          releaseHandler = resolve;
        })
    );

    const f = factory({ leaseDurationMs: 30_000, handlerTimeoutMs: 30_000, drainTimeoutMs: 5_000 });
    f.register({ name: "drain-job", pattern: FAST_PATTERN, handler, runHashTtlS: 3600 });
    f.start();

    // Wait for the enqueue + process pipeline to dispatch the handler.
    await new Promise((r) => {
      setTimeout(r, 1500);
    });
    expect(handler).toHaveBeenCalled();
    expect(handlerStartedAt).toBeGreaterThan(0);

    // Begin stop() but don't await yet. The drain race must keep it pending
    // until we release the handler.
    let stopResolvedAt = 0;
    const stopPromise = f.stop().then(() => {
      stopResolvedAt = Date.now();
    });

    // Sample the still-pending state. stop() should not have resolved yet
    // because the handler is still in flight.
    await new Promise((r) => {
      setTimeout(r, 200);
    });
    expect(stopResolvedAt).toBe(0);

    // Release the handler and capture the completion timestamp.
    const handlerCompletedAt = Date.now();
    releaseHandler();
    await stopPromise;

    // stop() must resolve at-or-after handler completion, never before.
    expect(stopResolvedAt).toBeGreaterThanOrEqual(handlerCompletedAt);
  }, 10_000);

  // Ensures a hung handler can't block shutdown past the orchestrator's
  // 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 = 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();

    await new Promise((r) => {
      setTimeout(r, 1500);
    });
    expect(handler).toHaveBeenCalled();

    const slotKeysBefore = await testRedis.keys(SLOT_KEYS);
    expect(slotKeysBefore.length).toBe(1);

    const startedAt = Date.now();
    await f.stop();
    const elapsed = Date.now() - startedAt;

    // 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(SLOT_KEYS);
    expect(slotKeysAfter.length).toBe(0);
  }, 10_000);
});