diff --git a/tests/lane-decisions-matrix.test.ts b/tests/lane-decisions-matrix.test.ts index b16d0c2401..552f01b1c7 100644 --- a/tests/lane-decisions-matrix.test.ts +++ b/tests/lane-decisions-matrix.test.ts @@ -14,6 +14,7 @@ import { _resetPluginStateForTest } from "../src/plugin.ts"; import { _resetSessionsForTest } from "../src/session.ts"; import { _setForTest } from "../src/registry.ts"; import { resetToolRingForTest } from "../src/tool-ring.ts"; +import { closeServers } from "./server-close-guard.ts"; // #3417 lane-decisions truth table (characterization pass): pin the CURRENT // compress-surface behavior (standing prompt + nudge) per lane across all four @@ -81,20 +82,6 @@ function historyTexts(): string[] { // teachTokens: what the fake upstream REPORTS as input_tokens on every reply. // The loop adopts it as the next turn's tokenCount (usage-grade baseline), so // this is how each row dials context usage against the 64k declared window. -const CLOSE_TIMEOUT_MS = 5_000; -// #3731: bound the teardown 'close' await. Under Windows runner-pool load a delayed -// or lost 'close' makes `await once(server,"close")` a handle-less dangling await that -// drains the event loop, so node --test aborts the WHOLE file and records every sibling -// subtest as cancelledByParent with ZERO assertion failures. The live timer keeps the -// loop alive so the promise always settles; per-test/--test-timeout do NOT rescue this -// (node:test's timer is unref'd). closeAllConnections already freed every socket. -const settledClose = (srv: http.Server): Promise => { - let timer: ReturnType | undefined = undefined; - const timeout = new Promise((resolve) => { timer = setTimeout(resolve, CLOSE_TIMEOUT_MS); }); - return Promise.race([once(srv, "close"), timeout]).then(() => { - if (timer !== undefined) clearTimeout(timer); - }); -}; async function harness(wire: Wire, lane: Lane, toolNames: string[], injectTool = true, teachTokens = 50_000) { // Windows CI flake class (seen on runners, not on dev VMs): listen(0) @@ -194,12 +181,7 @@ async function harness(wire: Wire, lane: Lane, toolNames: string[], injectTool = }; const close = async () => { store.cancelAll(); - // closeAllConnections destroys keep-alive sockets that close() alone - // would wait on forever (server.close only completes once every - // connection ends) — belt-and-suspenders against teardown hangs. - proxy.close(); proxy.closeIdleConnections?.(); proxy.closeAllConnections?.(); - upstream.close(); upstream.closeIdleConnections?.(); upstream.closeAllConnections?.(); - await Promise.all([settledClose(proxy), settledClose(upstream)]); + await closeServers([proxy, upstream], "lane-decisions harness"); }; return { send, forwarded, close }; } diff --git a/tests/pi-omp-fork-adopt.test.ts b/tests/pi-omp-fork-adopt.test.ts index 1e1819d548..b11e107099 100644 --- a/tests/pi-omp-fork-adopt.test.ts +++ b/tests/pi-omp-fork-adopt.test.ts @@ -17,6 +17,7 @@ import { resetToolRingForTest } from "../src/tool-ring.ts"; import { incomingCoreMessages } from "../src/fork-adoption.ts"; import { anthropicBodyToCore, chatBodyToCore, createForkAdopter, forkIdentityHashOf, openaiBodyToCore, resetForkCapabilityCacheForTest, responsesBodyToCore, tryForkAdoption, type ForkAdoptInput } from "../src/agent/fork-adopt.ts"; import { FORK_SEED_MIN_REPLAYED_MESSAGES, createBiliPlugin, replayedMessageCount } from "../src/agent/pi.ts"; +import { closeServers } from "./server-close-guard.ts"; process.env.NODE_ENV = "test"; const testRoot = mkdtempSync(join(tmpdir(), "bili-piomp-fork-")); @@ -319,7 +320,7 @@ async function harness() { await once(proxy, "listening"); const paddr = proxy.address(); assert(paddr && typeof paddr === "object"); - return { dir, store, upstreamUrl, origin: `http://127.0.0.1:${paddr.port}`, close: async () => { store.cancelAll(); proxy.close(); proxy.closeIdleConnections?.(); proxy.closeAllConnections?.(); upstream.close(); upstream.closeIdleConnections?.(); upstream.closeAllConnections?.(); await Promise.all([once(proxy, "close"), once(upstream, "close")]); } }; + return { dir, store, upstreamUrl, origin: `http://127.0.0.1:${paddr.port}`, close: async () => { store.cancelAll(); await closeServers([proxy, upstream], "fork-adopt harness"); } }; } async function seedParent(h: Awaited>, conversationId: string) { diff --git a/tests/plugin-bypass.test.ts b/tests/plugin-bypass.test.ts index 00d4680661..90a70dfe0c 100644 --- a/tests/plugin-bypass.test.ts +++ b/tests/plugin-bypass.test.ts @@ -12,6 +12,7 @@ import type { ProxyOptions } from "../src/config.ts"; import { SessionStore, _setStoreForTest } from "../src/persist.ts"; import { _setForTest as setRegistryForTest } from "../src/registry.ts"; import { _resetPluginStateForTest } from "../src/plugin.ts"; +import { closeServers } from "./server-close-guard.ts"; interface Harness { proxyPort: number; @@ -69,13 +70,7 @@ mitm: { enabled: false, domains: [] }, upstreamPort, captured, close: async () => { - proxy.close(); - proxy.closeIdleConnections?.(); - proxy.closeAllConnections?.(); - upstream.close(); - upstream.closeIdleConnections?.(); - upstream.closeAllConnections?.(); - await Promise.allSettled([once(proxy, "close"), once(upstream, "close")]); + await closeServers([proxy, upstream], "plugin-bypass harness"); }, }; } diff --git a/tests/plugin-fork.test.ts b/tests/plugin-fork.test.ts index 7955462527..d534a8a514 100644 --- a/tests/plugin-fork.test.ts +++ b/tests/plugin-fork.test.ts @@ -18,6 +18,7 @@ import { _resetSessionsForTest, getSession, markDirty } from "../src/session.ts" import { _setForTest } from "../src/registry.ts"; import { recordToolWitness, resetToolRingForTest } from "../src/tool-ring.ts"; import { contentStoreOf } from "../src/store.ts"; +import { closeServers } from "./server-close-guard.ts"; process.env.NODE_ENV = "test"; const testRoot = mkdtempSync(join(tmpdir(), "bili-fork-")); @@ -113,7 +114,7 @@ async function harness(persist = false, seedParent = true, compressExtra: Record assert.equal(r.status, 200); await r.text(); } - return { request, messages, forwarded, dir, store, upstreamUrl, origin, close: async () => { store.cancelAll(); proxy.close(); upstream.close(); proxy.closeIdleConnections?.(); proxy.closeAllConnections?.(); upstream.closeIdleConnections?.(); upstream.closeAllConnections?.(); await Promise.all([once(proxy, "close"), once(upstream, "close")]); } }; + return { request, messages, forwarded, dir, store, upstreamUrl, origin, close: async () => { store.cancelAll(); await closeServers([proxy, upstream], "plugin-fork harness"); } }; } test("plain proxy panel snapshots do not change raw-history persistence", { timeout: 60_000 }, async () => { diff --git a/tests/server-close-guard.ts b/tests/server-close-guard.ts new file mode 100644 index 0000000000..dd95f62924 --- /dev/null +++ b/tests/server-close-guard.ts @@ -0,0 +1,47 @@ +// #3356/#3525: bounded teardown for in-test http servers. +// +// The win22 drain-cancel flake family (#3356): a harness awaits a server's +// 'close' event after close(); if 'close' never fires (connection accounting +// stuck under load), that promise stays pending with ZERO active handles — +// the event loop drains and node:test cancels the whole file with +// "Promise resolution is still pending but the event loop has already +// resolved", before any per-test timeout can even start ticking. Two +// structural gaps this closes: +// 1. once(server, "close") attached AFTER close() can miss an early +// emission; capturing server.close(cb) synchronously cannot. +// 2. An unbounded await has no backstop; a ref'd guard timer keeps the +// loop alive for the window, so a residual hang surfaces as a named +// error instead of a silent drain-cancel cascade. + +import type { Server } from "node:http"; + +const HARNESS_CLOSE_TIMEOUT_MS = 10_000; + +export async function closeServers(servers: Server[], label = "harness"): Promise { + const closings = servers.map((s) => new Promise((resolve, reject) => { + s.close((err) => (err ? reject(err) : resolve())); + })); + // closeAllConnections destroys keep-alive sockets that close() alone + // would wait on forever (server.close only completes once every + // connection ends). + for (const s of servers) { + s.closeIdleConnections?.(); + s.closeAllConnections?.(); + } + const all = Promise.all(closings); + all.catch(() => {}); // the guard may win first; a late rejection must not leak unhandled + let timer: ReturnType | undefined; + const guard = new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error( + `${label}: server 'close' did not fire within ${HARNESS_CLOSE_TIMEOUT_MS}ms — #3356 win22 teardown-hang class; name the stuck server instead of retrying blindly`, + )), + HARNESS_CLOSE_TIMEOUT_MS, + ); + }); + try { + await Promise.race([all, guard]); + } finally { + clearTimeout(timer); + } +}