From 2b02c2f91c0c9979578c8b0562700556900715a6 Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 01:30:48 -0500 Subject: [PATCH 1/2] test(memory): drive the clock in the heartbeat freshness test instead of racing it "keeps a lock held longer than staleMs fresh" held a lock for 400 ms with staleMs 100, so the heartbeat refreshed it every 50 ms, and a waiter judged its age against the real clock. When a refresh landed more than 50 ms late (a slow runner's disk or scheduler), the waiter saw a live lock older than staleMs and broke it. Delaying each heartbeat utimes by 120 ms reproduces the CI order [long start, waiter, long end] every time. The heartbeat itself is sound: production keeps a 15 s margin (staleMs 30 s, a beat every 15 s). The test now fakes Date and the heartbeat's interval only. It advances the clock one beat at a time, waits for that beat's refresh to land and for the waiter to look at the lock again, and holds the lock for four times staleMs before releasing it. Timeouts stay real, so the waiter retries on its own. Closes #5680 Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/memory/__tests__/file-lock.test.ts | 112 ++++++++++++++++++++----- 1 file changed, 89 insertions(+), 23 deletions(-) diff --git a/src/memory/__tests__/file-lock.test.ts b/src/memory/__tests__/file-lock.test.ts index 63b5fc719a..259680493a 100644 --- a/src/memory/__tests__/file-lock.test.ts +++ b/src/memory/__tests__/file-lock.test.ts @@ -315,30 +315,96 @@ describe("withFileLock", () => { }); it("keeps a lock held longer than staleMs fresh, so it is not broken", async () => { - const opts = { staleMs: 100, timeoutMs: 5_000, retryMs: 5 }; - const order: string[] = []; - const long = withFileLock( - lockPath, - async () => { - order.push("long start"); - await new Promise((resolve) => setTimeout(resolve, 400)); - order.push("long end"); - }, - opts, - ); - // Let the long holder take the lock before the waiter starts. - await new Promise((resolve) => setTimeout(resolve, 20)); - const waiter = withFileLock( - lockPath, - async () => { - order.push("waiter"); - }, - opts, - ); + // The lock's age is judged against the clock, so the test drives the + // clock rather than racing it (#5680). With real time, a waiter that ran + // while a loaded runner held the next heartbeat back by more than + // staleMs / 2 judged the live lock stale and broke it. Here Date and the + // heartbeat's interval are fake and move only when the test advances + // them; timeouts stay real, so the waiter keeps retrying on its own. Each + // step waits for the refresh it fires to land and for the waiter to look + // at the lock again, so a slow runner only makes the test take longer. A + // heartbeat that stops refreshing the lock fails it on its timeout. + const opts = { staleMs: 100, timeoutMs: 60_000, retryMs: 5 }; + vi.useFakeTimers({ + now: Date.now(), + toFake: ["Date", "setInterval", "clearInterval"], + }); + try { + const realOpen = fs.open; + let judgments = 0; + vi.spyOn(fs, "open").mockImplementation((async ( + ...args: Parameters + ) => { + if (args[0] === lockPath && args[1] === "r") { + judgments++; + } + return realOpen(...args); + }) as typeof fs.open); + const realUtimes = fs.utimes; + let refreshLanded: (() => void) | undefined; + vi.spyOn(fs, "utimes").mockImplementation(async (...args) => { + await realUtimes(...args); + if (args[0] === lockPath) { + refreshLanded?.(); + } + }); + const until = async (done: () => boolean): Promise => { + while (!done()) { + await new Promise((resolve) => setTimeout(resolve, 1)); + } + }; + // Two more opens than were seen means one whole judgment of the lock + // started and finished, and the waiter came back for another. + const waiterLooksAgain = () => { + const seen = judgments; + return until(() => judgments >= seen + 2); + }; - await Promise.all([long, waiter]); - expect(order).toEqual(["long start", "long end", "waiter"]); - }); + const order: string[] = []; + let started!: () => void; + const holding = new Promise((resolve) => (started = resolve)); + let finish!: () => void; + const finished = new Promise((resolve) => (finish = resolve)); + const long = withFileLock( + lockPath, + async () => { + order.push("long start"); + started(); + await finished; + order.push("long end"); + }, + opts, + ); + await holding; + const waiter = withFileLock( + lockPath, + async () => { + order.push("waiter"); + }, + opts, + ); + await waiterLooksAgain(); + + // Hold the lock for four times staleMs, one heartbeat at a time. + const start = Date.now(); + for (let beat = 0; beat < 8; beat++) { + const refreshed = new Promise( + (resolve) => (refreshLanded = resolve), + ); + vi.advanceTimersByTime(opts.staleMs / 2); + await refreshed; + await waiterLooksAgain(); + } + expect(Date.now() - start).toBe(4 * opts.staleMs); + expect(order).toEqual(["long start"]); + + finish(); + await Promise.all([long, waiter]); + expect(order).toEqual(["long start", "long end", "waiter"]); + } finally { + vi.useRealTimers(); + } + }, 30_000); it("stops refreshing a lock that was broken and re-taken while it ran (#5418)", async () => { // Heartbeat every 100 ms, wide enough that the replacement below finishes From d8715927988d122dffda10d395e5f638435bad6c Mon Sep 17 00:00:00 2001 From: cliffhall Date: Mon, 30 Nov 2026 03:13:33 -0500 Subject: [PATCH 2/2] test(memory): bound the heartbeat test's waits and clean up on a failure Review of #5715: a heartbeat that stopped refreshing left the test waiting until Vitest's timeout, which skips the test's finally, so the fake timers and the blocked lock holder outlived it. Each wait now gives up after 10 s of real time with an error that names what it waited for. The finally releases the holder and settles both lock operations, and afterEach restores real timers for a test that times out anyway. Co-Authored-By: Claude Opus 5.5 Signed-off-by: cliffhall --- src/memory/__tests__/file-lock.test.ts | 76 ++++++++++++++++---------- 1 file changed, 48 insertions(+), 28 deletions(-) diff --git a/src/memory/__tests__/file-lock.test.ts b/src/memory/__tests__/file-lock.test.ts index 259680493a..72a1b58a31 100644 --- a/src/memory/__tests__/file-lock.test.ts +++ b/src/memory/__tests__/file-lock.test.ts @@ -33,6 +33,8 @@ describe("withFileLock", () => { }); afterEach(async () => { + // Also runs when a test times out, which skips the test's own finally. + vi.useRealTimers(); vi.restoreAllMocks(); await cleanup(); }); @@ -322,13 +324,18 @@ describe("withFileLock", () => { // heartbeat's interval are fake and move only when the test advances // them; timeouts stay real, so the waiter keeps retrying on its own. Each // step waits for the refresh it fires to land and for the waiter to look - // at the lock again, so a slow runner only makes the test take longer. A - // heartbeat that stops refreshing the lock fails it on its timeout. + // at the lock again, so a slow runner only makes the test take longer. + // Each wait gives up after 10 s of real time, well inside the test's + // timeout, so a heartbeat that stops refreshing the lock fails the test + // by name and the cleanup below still runs. const opts = { staleMs: 100, timeoutMs: 60_000, retryMs: 5 }; vi.useFakeTimers({ now: Date.now(), toFake: ["Date", "setInterval", "clearInterval"], }); + const order: string[] = []; + let finish = () => {}; + const running: Promise[] = []; try { const realOpen = fs.open; let judgments = 0; @@ -341,15 +348,20 @@ describe("withFileLock", () => { return realOpen(...args); }) as typeof fs.open); const realUtimes = fs.utimes; - let refreshLanded: (() => void) | undefined; + let refreshes = 0; vi.spyOn(fs, "utimes").mockImplementation(async (...args) => { await realUtimes(...args); if (args[0] === lockPath) { - refreshLanded?.(); + refreshes++; } }); - const until = async (done: () => boolean): Promise => { + const until = async (what: string, done: () => boolean) => { + // performance.now is not faked, so this bound is real time. + const giveUpAt = performance.now() + 10_000; while (!done()) { + if (performance.now() > giveUpAt) { + throw new Error(`Gave up waiting for ${what}`); + } await new Promise((resolve) => setTimeout(resolve, 1)); } }; @@ -357,52 +369,60 @@ describe("withFileLock", () => { // started and finished, and the waiter came back for another. const waiterLooksAgain = () => { const seen = judgments; - return until(() => judgments >= seen + 2); + return until("the waiter to judge the lock again", () => { + return judgments >= seen + 2; + }); }; - const order: string[] = []; let started!: () => void; const holding = new Promise((resolve) => (started = resolve)); - let finish!: () => void; const finished = new Promise((resolve) => (finish = resolve)); - const long = withFileLock( - lockPath, - async () => { - order.push("long start"); - started(); - await finished; - order.push("long end"); - }, - opts, + running.push( + withFileLock( + lockPath, + async () => { + order.push("long start"); + started(); + await finished; + order.push("long end"); + }, + opts, + ), ); await holding; - const waiter = withFileLock( - lockPath, - async () => { - order.push("waiter"); - }, - opts, + running.push( + withFileLock( + lockPath, + async () => { + order.push("waiter"); + }, + opts, + ), ); await waiterLooksAgain(); // Hold the lock for four times staleMs, one heartbeat at a time. const start = Date.now(); for (let beat = 0; beat < 8; beat++) { - const refreshed = new Promise( - (resolve) => (refreshLanded = resolve), - ); + const seen = refreshes; vi.advanceTimersByTime(opts.staleMs / 2); - await refreshed; + await until(`heartbeat ${beat + 1} to refresh the lock`, () => { + return refreshes > seen; + }); await waiterLooksAgain(); } expect(Date.now() - start).toBe(4 * opts.staleMs); expect(order).toEqual(["long start"]); finish(); - await Promise.all([long, waiter]); + await Promise.all(running); expect(order).toEqual(["long start", "long end", "waiter"]); } finally { + // On a failure, let both lock operations finish before the lock + // directory is removed, so neither outlives the test. vi.useRealTimers(); + finish(); + await Promise.allSettled(running); } }, 30_000);