diff --git a/src/memory/__tests__/file-lock.test.ts b/src/memory/__tests__/file-lock.test.ts index 63b5fc719a..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(); }); @@ -315,30 +317,114 @@ 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 }; + // 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. + // 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[] = []; - 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, - ); + let finish = () => {}; + const running: Promise[] = []; + 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 refreshes = 0; + vi.spyOn(fs, "utimes").mockImplementation(async (...args) => { + await realUtimes(...args); + if (args[0] === lockPath) { + refreshes++; + } + }); + 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)); + } + }; + // 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("the waiter to judge the lock again", () => { + return judgments >= seen + 2; + }); + }; - await Promise.all([long, waiter]); - expect(order).toEqual(["long start", "long end", "waiter"]); - }); + let started!: () => void; + const holding = new Promise((resolve) => (started = resolve)); + const finished = new Promise((resolve) => (finish = resolve)); + running.push( + withFileLock( + lockPath, + async () => { + order.push("long start"); + started(); + await finished; + order.push("long end"); + }, + opts, + ), + ); + await holding; + 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 seen = refreshes; + vi.advanceTimersByTime(opts.staleMs / 2); + 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(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); 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