test(integration): stop the rate-limit reset test racing its own window

The window-reset test burned its budget in a 50 ms window: four sequential
round-trips to a containerised Postgres had to finish inside a twentieth of a
second or the window closed under them, the counter reset, and the fourth call
came back allowed. Three failures in thirty days, two of them on `main` — run
33614804032 shows `expected true to be false` at rate-limit.test.ts:56 in a file
that took 1278 ms to run.

The short window bought nothing: the expiry this test is about is forced by hand
a few lines further down, by writing `reset_at` into the past. The burn now runs
in a 60 s window, so no round-trip can outlast it, and the test asserts the row's
count is 4 after the denial — a window that closed mid-burn would also have
produced three allowed calls, and the old assertion could not tell the two
apart.

Gates:

  pnpm exec vitest run --config vitest.integration.config.mts \
    tests/integration/rate-limit.test.ts

  three consecutive runs, 2 passed / 2 passed / 2 passed.

  Mutation: with the burn window back at 1 ms the run fails exactly as CI did —
  "AssertionError: expected true to be false" on the denial assertion.
This commit is contained in:
Marc-André Bombeck committed 2026-09-09 22:55:53 +02:00
1 parent 69aac232b4
commit 7ca69ec671
1 file changed
+19 -3
+19 -3
View File
@@ -47,14 +47,30 @@ describe("checkRateLimit (real Postgres)", () => {
const key = "test:reset:1.2.3.4";
const limit = 3;
// Burn the budget with a short 50ms window.
// Burn the budget in a window wide enough that it cannot close under the
// four calls that fill it. It used to be 50 ms, which asked the four
// round-trips to a containerised Postgres to finish inside a twentieth of
// a second: on a loaded runner the window expired mid-burn, the counter
// reset, and the fourth call came back allowed — three failures in thirty
// days, two of them on `main` (run 33614804032, `expected true to be
// false` on the line below, in a file that took 1278 ms to run). The short
// window bought nothing either way, because the expiry this test is about
// is forced by hand a few lines down rather than waited for.
const windowMs = 60_000;
for (let i = 0; i < 3; i++) {
const r = await checkRateLimit(key, limit, 50);
const r = await checkRateLimit(key, limit, windowMs);
expect(r.allowed).toBe(true);
}
const denied = await checkRateLimit(key, limit, 50);
const denied = await checkRateLimit(key, limit, windowMs);
expect(denied.allowed).toBe(false);
// The denial has to be the cap, not a window that closed under the burn —
// a reset would also have produced three allowed calls before it.
const burned = await getPrismaClient().rateLimit.findUnique({
where: { key },
});
expect(burned?.count).toBe(4);
// Manually expire the window: cheaper than sleeping and avoids
// flaky timing on slow CI runners. The branch under test compares
// `reset_at < NOW()`, so any past timestamp triggers the reset.