diff --git a/tests/unit/http-execution-v3.test.ts b/tests/unit/http-execution-v3.test.ts index ee085b00..bf5a2f60 100644 --- a/tests/unit/http-execution-v3.test.ts +++ b/tests/unit/http-execution-v3.test.ts @@ -972,8 +972,29 @@ describe("terminal owner classification at every wait", () => { type Owner = "CALLER" | "SCOPE_FENCE" | "DEADLINE"; const hang = () => new Promise(() => {}); + /** + * Blocks this thread for `ms` of real time, as a loaded machine does + * between two steps. A fake clock does not move meanwhile. + */ + const stallRealTime = (ms: number) => + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); async function endWaitAt(phase: Phase, owner: Owner) { + // The deadline fires on a fake clock once the wait under test is reached. + // On the real clock a 30ms deadline raced the machine: a transport failure + // or a 503 handled after 30ms found no time left to back off, and the + // request ended as that failure instead of TIMEOUT (seen at load 31). + // The backoff phases stall 40ms of real time before answering, so a real + // deadline here fails every time. + if (owner === "DEADLINE") vi.useFakeTimers(); + try { + return await endWaitAtOnClock(phase, owner); + } finally { + if (owner === "DEADLINE") vi.useRealTimers(); + } + } + + async function endWaitAtOnClock(phase: Phase, owner: Owner) { const caller = new AbortController(); const fence = new AbortController(); const fencedScope = Object.freeze({ @@ -1008,6 +1029,7 @@ describe("terminal owner classification at every wait", () => { ? (reach(), hang()) : { kind: "READY", headers: {} }, fetcher: vi.fn(async () => { + if (owner === "DEADLINE" && phase.endsWith("backoff")) stallRealTime(40); switch (phase) { case "transport backoff": throw new TypeError("network down"); @@ -1043,12 +1065,17 @@ describe("terminal owner classification at every wait", () => { ...(execution === undefined ? {} : { execution }), }, ); - if (owner !== "DEADLINE") { - await vi.waitFor(() => - expect(reached || execution?.traffic.concurrency.queued === 1).toBe( - true, - ), - ); + const waiting = () => + reached || execution?.traffic.concurrency.queued === 1; + if (owner === "DEADLINE") { + // vi.waitFor would advance the fake clock on every check. + for (let turn = 0; turn < 100 && !waiting(); turn += 1) { + await flushMicrotasks(); + } + expect(waiting()).toBe(true); + await vi.advanceTimersByTimeAsync(30); + } else { + await vi.waitFor(() => expect(waiting()).toBe(true)); (owner === "CALLER" ? caller : fence).abort(); } const outcome = await pending;