diff --git a/src/process/capture/ProcessCaptureLifecycle.test.ts b/src/process/capture/ProcessCaptureLifecycle.test.ts index e2c518a74d..4a41321212 100644 --- a/src/process/capture/ProcessCaptureLifecycle.test.ts +++ b/src/process/capture/ProcessCaptureLifecycle.test.ts @@ -9,6 +9,13 @@ import { awaitTerminalExit } from "./ProcessCaptureLifecycle.js"; import type { ProcessTimer } from "./ProcessTimer.js"; import { monotonicProcessCaptureClock } from "./ProcessCaptureClock.js"; +// Keep native promise timers. Capture their outcomes so even an unref'ed +// grace wait has observable cancellation. +vi.mock("node:timers/promises", async (importOriginal) => { + const timers = await importOriginal(); + return { ...timers, setTimeout: vi.fn(timers.setTimeout) }; +}); + type Delivery = ProcessCaptureFinalization["signals"][number]["delivery"]; interface FakeExit { @@ -63,6 +70,7 @@ const fakePollingClock = () => { afterEach(() => { vi.useRealTimers(); + vi.mocked(delay).mockClear(); }); const observed = ( @@ -312,16 +320,22 @@ it("returns at once when a cancellation kill cannot be delivered", async () => { expect(result.unobserved, "the capture does not wait for an exit").toBe(true); }); -it("waits for a pending delivery before reporting an observed exit", async () => { +it("joins a pending delivery after an observed exit and cancels its grace waits", async () => { let release: () => void = () => undefined; const hold = new Promise((resolve) => { release = resolve; }); const fake = fakeTerminal({ SIGTERM: "signaled" }, hold); const pending = start(fake, { timeout_ms: 100, finalization_ms: 5_000 }); + let graceWaits = Promise.resolve[]>([]); try { await expect.poll(() => fake.signals).toContain("SIGTERM"); fake.deliverExit({ exitCode: 0, signal: 0 }); + const startedWaits = vi + .mocked(delay) + .mock.results.map(({ value }) => value); + graceWaits = Promise.allSettled(startedWaits); + const result = await Promise.race([ pending, new Promise((resolve) => setImmediate(resolve)), @@ -340,6 +354,14 @@ it("waits for a pending delivery before reporting an observed exit", async () => exit.finalization?.signals, "the delivery result is complete in the published record", ).toMatchObject([{ signal: "SIGTERM", delivery: "signaled" }]); + const waits = await graceWaits; + expect(waits).not.toHaveLength(0); + for (const wait of waits) { + expect(wait).toMatchObject({ + status: "rejected", + reason: { name: "AbortError" }, + }); + } }); it("stops waiting for a hung delivery once the exit is observed", async () => { @@ -450,25 +472,6 @@ it("stops waiting when the escalation delivery never settles and no exit arrives }); }); -const activeTimers = (): number => - process.getActiveResourcesInfo().filter((name) => name === "Timeout").length; - -it("cancels the bounded-wait timer once deliveries settle after an exit", async () => { - const fake = fakeTerminal(); - const before = activeTimers(); - const pending = start(fake, { timeout_ms: 100, finalization_ms: 5_000 }); - await expect.poll(() => fake.signals).toContain("SIGTERM"); - fake.deliverExit({ exitCode: 0, signal: 0 }); - - await pending; - await new Promise((resolve) => setImmediate(resolve)); - - expect( - activeTimers(), - "no one-second grace timer outlives the finalized exit", - ).toBeLessThanOrEqual(before); -}); - it("keeps a non-empty reason when a signal delivery throws without a message", async () => { const fake = fakeTerminal(); let signalStarted = false; diff --git a/tests/acceptance/process/processFinalization.test.ts b/tests/acceptance/process/processFinalization.test.ts index f3317d9a89..a5a2b43db0 100644 --- a/tests/acceptance/process/processFinalization.test.ts +++ b/tests/acceptance/process/processFinalization.test.ts @@ -2,7 +2,6 @@ import { spawn } from "node:child_process"; import { createHash } from "node:crypto"; import { access, readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; -import { setTimeout as delay } from "node:timers/promises"; import { fileURLToPath } from "node:url"; import { expect, onTestFinished } from "vitest"; @@ -23,6 +22,7 @@ import { itWithCaptureCapability as captureTest, } from "../../boundary/process/processCaptureCapability.js"; import { expectSerializedUnverifiedHostCleanup } from "../../support/hostCleanup.js"; +import { waitFor } from "../../support/testWait.js"; const finalizationFixture = fileURLToPath( new URL("../../fixtures/processFinalization.mjs", import.meta.url), @@ -117,60 +117,27 @@ const captureViaMcp = async ( }; }; -const waitFor = async ( - description: string, - predicate: () => Promise, - deadlineMs = 7_500, -): Promise => { - const deadline = Date.now() + deadlineMs; - while (!(await predicate())) { - if (Date.now() >= deadline) - throw new Error(`timed out waiting for ${description}`); - await delay(25); - } -}; - -const fixturePid = async (root: string): Promise => { - let pid = Number.NaN; - await waitFor("the finalization fixture PID", async () => { - try { - pid = Number.parseInt(await readFile(join(root, "pid.txt"), "utf8"), 10); - return Number.isSafeInteger(pid) && pid > 0; - } catch { - return false; - } +const fixturePid = (root: string): Promise => + waitFor(async () => { + const pid = Number(await readFile(join(root, "pid.txt"), "utf8")); + expect(Number.isSafeInteger(pid) && pid > 0, "fixture PID").toBe(true); + return pid; }); - return pid; -}; const waitForFinalization = async (root: string): Promise => { // The fixture writes the PID before it can receive SIGTERM, so once the // marker exists the PID file is complete. - await waitFor("the finalization fixture to receive SIGTERM", async () => { - try { - await access(join(root, "sigterm-received")); - return true; - } catch { - return false; - } - }); + await waitFor(() => access(join(root, "sigterm-received"))); return fixturePid(root); }; -const waitForProcessExit = async (pid: number): Promise => - waitFor(`finalization fixture ${String(pid)} to exit`, async () => { - try { - process.kill(pid, 0); - return false; - } catch (error: unknown) { - return ( - typeof error === "object" && - error !== null && - "code" in error && - error.code === "ESRCH" - ); - } +const waitForProcessExit = async (pid: number): Promise => { + await waitFor(() => { + expect(() => process.kill(pid, 0), "the captured PID has exited").toThrow( + expect.objectContaining({ code: "ESRCH" }), + ); }); +}; const finalizationFromPartial = (partial: unknown) => { const parsed = partialProcessCaptureObservationSchema.parse(partial); @@ -192,7 +159,7 @@ const completedCaptureFromOutcome = (outcome: CaptureOutcome) => { const expectCooperativeFinalization = async ( outcome: CaptureOutcome, root: string, - expectedExitCode = 0, + expectedExitCode: number, ): Promise => { const capture = completedCaptureFromOutcome(outcome); expect(capture.exit.reason, "the deadline remains the exit reason").toBe( @@ -274,37 +241,24 @@ const expectIgnoringFinalization = (outcome: CaptureOutcome): void => { ).toBeUndefined(); }; -cliCaptureTest.for(["CLI", "MCP"] as const)( - "captures a cooperative finalizer through the compiled %s workflow", - async (adapter, { cli }) => { - const root = await createTestTempDirectory("rea-finalization-accept-"); - const scenario = captureScenario("cooperative", root, { - timeout_ms: 1_500, - finalization_ms: 1_500, - }); - const outcome = - adapter === "CLI" - ? await captureViaCli(cli, root, scenario) - : await captureViaMcp(scenario); - await expectCooperativeFinalization(outcome, root); - }, -); - -cliCaptureTest.for(["CLI", "MCP"] as const)( - "records the non-zero exit code of a finalizer through the compiled %s workflow", - async (adapter, { cli }) => { +cliCaptureTest.for([ + { adapter: "CLI", exitCode: 0 }, + { adapter: "MCP", exitCode: 3 }, +] as const)( + "captures a cooperative finalizer with exit $exitCode through the compiled $adapter workflow", + async ({ adapter, exitCode }, { cli }) => { const root = await createTestTempDirectory("rea-finalization-accept-"); const scenario = captureScenario( "cooperative", root, { timeout_ms: 1_500, finalization_ms: 1_500 }, - 3, + exitCode, ); const outcome = adapter === "CLI" ? await captureViaCli(cli, root, scenario) : await captureViaMcp(scenario); - await expectCooperativeFinalization(outcome, root, 3); + await expectCooperativeFinalization(outcome, root, exitCode); }, ); @@ -493,7 +447,7 @@ captureTest( await cliClosed; }); const cliFixturePid = await waitForFinalization(cliRoot); - const cliStarted = Date.now(); + const cliStarted = performance.now(); cli.kill("SIGINT"); const cliExit = await cliClosed; await waitForProcessExit(cliFixturePid); @@ -501,7 +455,7 @@ captureTest( 130, ); expect( - Date.now() - cliStarted, + performance.now() - cliStarted, "CLI cancellation does not wait for the grace interval", ).toBeLessThan(8_000); const cliDocument: unknown = JSON.parse(stdout); @@ -562,7 +516,7 @@ captureTest( }), ]); const mcpFixturePid = await waitForFinalization(mcpRoot); - const mcpStarted = Date.now(); + const mcpStarted = performance.now(); controller.abort(new Error("cancel finalization acceptance fixture")); await expect( call, @@ -574,7 +528,7 @@ captureTest( "the server accepts a follow-up request after cancelling the capture", ).resolves.toMatchObject({ tools: expect.any(Array) }); expect( - Date.now() - mcpStarted, + performance.now() - mcpStarted, "MCP cancellation does not wait for the grace interval", ).toBeLessThan(8_000); },