diff --git a/sea-trial/vendor/pi-rpc-readers.vendor.test.ts b/sea-trial/vendor/pi-rpc-readers.vendor.test.ts index 911e073c0..e94e94da2 100644 --- a/sea-trial/vendor/pi-rpc-readers.vendor.test.ts +++ b/sea-trial/vendor/pi-rpc-readers.vendor.test.ts @@ -11,6 +11,7 @@ import { afterEach, describe, expect, test, vi } from "vitest"; import { createPiRuntime, type SessionOptions } from "../../packages/oar/src/index.js"; import { asRecord, parseJson } from "../../packages/oar/src/shared/json.js"; import { killGraceMs } from "../../packages/oar/src/shared/executable/index.js"; +import { holdFixtureDeadline } from "../../tests/fixtures/fixture-deadline.js"; import { eventually, gone } from "../../tests/fixtures/process-tree.js"; const identityModule = new URL("../../tests/fixtures/process-tree.ts", import.meta.url).href; @@ -99,19 +100,21 @@ describe.skipIf(process.env.OAR_TEST !== "pi-rpc-aimock")("native Pi RPC readers const f = await fixture(); const pidFile = path.join(f.root, "stalled.json"), script = path.join(f.root, "stalled-pi.mjs"); const { PI_AI_VERSION } = await import("@earendil-works/pi-ai"); - await writeFile(script, `import { writeFileSync } from "node:fs"; + await writeFile(script, `import { renameSync, writeFileSync } from "node:fs"; import { captureProcess } from ${JSON.stringify(identityModule)}; if (process.argv.includes("--version") && ${JSON.stringify(stage)} !== "version") { console.log(${JSON.stringify(PI_AI_VERSION)}); } -else { writeFileSync(${JSON.stringify(pidFile)}, JSON.stringify({ ...captureProcess(process.pid), directory: process.env.OAR_PI_RPC_DIRECTORY })); setInterval(() => {}, 1000); }`); +else { const file = ${JSON.stringify(pidFile)}; writeFileSync(file + ".tmp", JSON.stringify({ ...captureProcess(process.pid), directory: process.env.OAR_PI_RPC_DIRECTORY })); renameSync(file + ".tmp", file); setInterval(() => {}, 1000); }`); const runtime = createPiRuntime({ execution: "subprocess", command: process.execPath, args: guardedFixtureArgs("--import", import.meta.resolve("tsx"), script) }); try { const options = { cwd: f.cwd, env: f.env, timeoutMs: 8000 }; - if (reader === "models") { - await expect(runtime.listModels(installed, options)).rejects.toThrow("Pi RPC model listing timed out"); - } else { - const result = await runtime.commands(installed, options); - expect(result).toMatchObject({ kind: "unavailable", code: "timeout" }); - } + const waitForFixture = holdFixtureDeadline(); + const outcome = reader === "models" + ? expect(runtime.listModels(installed, options)).rejects.toThrow("Pi RPC model listing timed out") + : expect(runtime.commands(installed, options)).resolves.toMatchObject({ kind: "unavailable", code: "timeout" }); + await waitForFixture(outcome, async () => { + expect(await eventually(() => existsSync(pidFile), 15_000), stage).toBe(true); + }); + await outcome; const child = children(pidFile)[0]; assert.ok(child !== undefined); // Timeout begins the same bounded native shutdown as a session dispose. diff --git a/tests/account-query-deadlines.test.ts b/tests/account-query-deadlines.test.ts index 6a63d8e93..b418c501f 100644 --- a/tests/account-query-deadlines.test.ts +++ b/tests/account-query-deadlines.test.ts @@ -1,5 +1,5 @@ /* oxlint-disable import/max-dependencies -- One real-process regression exercises each affected account entry point. */ -import { readFileSync } from "node:fs"; +import { existsSync, readFileSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { afterEach, expect, test, vi } from "vitest"; @@ -15,7 +15,8 @@ import { readCodexAuthStatus } from "../packages/oar/src/runtimes/codex/login.js import { codebuddyAuthStatus } from "../packages/oar/src/runtimes/codebuddy/auth-status.js"; import { factoryAuthStatus } from "../packages/oar/src/runtimes/factory/account.js"; import { kimiAuthStatus, queryKimiAuth } from "../packages/oar/src/runtimes/kimi/auth-status.js"; -import { fakeAgentBinary, gone, withTreeProbe } from "./fixtures/process-tree.js"; +import { holdFixtureDeadline } from "./fixtures/fixture-deadline.js"; +import { eventually, fakeAgentBinary, gone, withTreeProbe } from "./fixtures/process-tree.js"; const script = fileURLToPath(new URL("fixtures/stalled-account-query.mjs", import.meta.url)); const TIMEOUT = 4000; @@ -51,16 +52,18 @@ test.each(cases)("$name settles at its deadline while owned cleanup continues", ...probe.env, HOME: probe.dir, CODEX_HOME: probe.dir, CODEBUDDY_API_KEY: null, WINDSURF_API_KEY: null, OAR_QUERY_STAGE: stage, OAR_QUERY_REQUESTS: requests, } }).then((value) => ({ value, error: null }), (error: unknown) => ({ value: null, error })); - const tree = await probe.tree(); - // Wait until the fixture reaches the target stage before firing the deadline timer. - await vi.waitFor(() => { - expect(readFileSync(requests, "utf8").trim().split("\n")).toContain(stage); - }, { timeout: 10_000, interval: 10 }); - const deadlineAt = performance.now(); - vi.advanceTimersByTime(TIMEOUT); - vi.useRealTimers(); + let deadlineAt = 0; + const [tree, ready] = await Promise.all([ + probe.tree(), + eventually(() => existsSync(requests) && readFileSync(requests, "utf8").trim().split("\n").includes(stage), 10_000), + ]).finally(() => { + deadlineAt = performance.now(); + vi.advanceTimersByTime(TIMEOUT); + vi.useRealTimers(); + }); const outcome = await result; const settleMs = performance.now() - deadlineAt; + expect(ready, stage).toBe(true); if (name.endsWith("status")) { expect(outcome.value).toMatchObject({ kind: "unknown" }); expect(outcome.value).toHaveProperty("detail", expect.stringContaining("timed out")); @@ -90,11 +93,12 @@ test.skipIf(process.platform === "win32")("login/logout's internal status reader vi.stubEnv("OAR_KILL_GRACE_MS", String(GRACE)); await withTreeProbe({ ignoreSigterm: true }, async (probe) => { const command = fakeAgentBinary(probe.dir, [script]); - const started = performance.now(); + const waitForFixture = holdFixtureDeadline(); const result = readCodexAuthStatus({ kind: "available", via: "executable", command }, { timeoutMs: 1000, env: { ...probe.env, OAR_QUERY_REQUESTS: path.join(probe.dir, "requests") }, }); - const tree = await probe.tree(); + const tree = await waitForFixture(result, async () => probe.tree()); + const started = performance.now(); expect(await result).toMatchObject({ kind: "unknown" }); expect(performance.now() - started).toBeGreaterThanOrEqual(1000 + GRACE - 50); expect(await gone(tree.agent, 0)).toBe(true); @@ -106,10 +110,11 @@ test.skipIf(process.platform === "win32").each(["authenticate", "logout"] as con vi.stubEnv("OAR_KILL_GRACE_MS", String(GRACE)); await withTreeProbe({ ignoreSigterm: true, detachTool: true }, async probe => { const command = fakeAgentBinary(probe.dir, [script]); - const started = performance.now(); + const waitForFixture = holdFixtureDeadline(); const result = queryKimiAuth(command, method, { timeoutMs: 1000, joinCleanup: method === "authenticate", env: { ...probe.env, OAR_QUERY_STAGE: method, OAR_QUERY_REQUESTS: path.join(probe.dir, "requests") } }); - const tree = await probe.tree(); + const tree = await waitForFixture(result, async () => probe.tree()); + const started = performance.now(); expect(await result).toBe("timed_out"); expect(performance.now() - started).toBeGreaterThanOrEqual(1000 + GRACE - 50); expect(await gone(tree.agent, 0)).toBe(true); diff --git a/tests/antigravity/antigravity-plan.test.ts b/tests/antigravity/antigravity-plan.test.ts index 29c53764f..71b3eafb2 100644 --- a/tests/antigravity/antigravity-plan.test.ts +++ b/tests/antigravity/antigravity-plan.test.ts @@ -18,7 +18,8 @@ import { readAntigravityTokenEmail, } from "../../packages/oar/src/runtimes/antigravity/token-email.js"; import { asRecord, parseJson, type JsonRecord } from "../../packages/oar/src/shared/json.js"; -import { fakeAgentBinary, gone, reportedProcess } from "../fixtures/process-tree.js"; +import { holdFixtureDeadline } from "../fixtures/fixture-deadline.js"; +import { eventually, fakeAgentBinary, gone, reportedProcess } from "../fixtures/process-tree.js"; // Recorded agy 1.5.13 ACP initialize and authenticate replies (2026-11-20), identifiers removed. const authFixtureText = readFileSync(path.join(import.meta.dirname, "agy-1.5.13-authenticate.json"), "utf8"); @@ -55,8 +56,8 @@ function writeFakeState(dir: string, options: FakeAccountOptions): void { function fakeAgyScript(config: Record): string { return [ - `import { captureProcess } from ${JSON.stringify(new URL("../fixtures/process-tree.ts", import.meta.url).href)};`, - 'import { appendFileSync, writeFileSync } from "node:fs";', + `import { writeProcessReport } from ${JSON.stringify(new URL("../fixtures/process-tree.ts", import.meta.url).href)};`, + 'import { appendFileSync } from "node:fs";', 'import { createInterface } from "node:readline";', `const cfg = ${JSON.stringify(config)};`, String.raw`const log = (entry) => appendFileSync(cfg.traceFile, JSON.stringify(entry) + "\n");`, @@ -65,13 +66,12 @@ function fakeAgyScript(config: Record): string { 'if (args[0] === "models") { if (!cfg.loggedIn) { console.error("Please sign in to view available models"); process.exit(1); } console.log("gemini-3.8-flash"); process.exit(0); }', 'if (args[0] === "-p" && args[1] === "/usage") { process.stdout.write(JSON.stringify(cfg.usageReply)); process.exit(0); }', 'if (args[0] === "acp") {', - ' writeFileSync(cfg.pidFile, JSON.stringify(captureProcess(process.pid)));', ' createInterface({ input: process.stdin }).on("line", (line) => {', ' const req = JSON.parse(line);', ' log({ kind: "rpc", method: req.method, params: req.params });', String.raw` if (req.method === "initialize") { process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: req.id, result: cfg.initReply }) + "\n"); return; }`, ' if (req.method === "authenticate") {', - ' if (cfg.authMode === "stall") { setInterval(() => {}, 1000); return; }', + ' if (cfg.authMode === "stall") { writeProcessReport(cfg.pidFile, process.pid); setInterval(() => {}, 1000); return; }', String.raw` if (cfg.authMode === "no_browser") { process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: req.id, error: { code: -32603, message: "No browser is available here (this is a remote (SSH) session)." } }) + "\n"); return; }`, String.raw` process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: req.id, result: cfg.authReply }) + "\n");`, ' }', @@ -102,7 +102,7 @@ function fakeAccountAgy(options: FakeAccountOptions = {}) { const env = { HOME: dir, USERPROFILE: dir, DISPLAY: ":99", WAYLAND_DISPLAY: "wayland-0", DBUS_SESSION_BUS_ADDRESS: null, XDG_RUNTIME_DIR: dir }; return { installation: { kind: "available", via: "executable", command: fakeAgentBinary(dir, guardedFixtureArgs(script)), version: "1.5.13" } as const, - env, dir, trace: () => readTrace(traceFile), acpPid: () => reportedProcess(JSON.parse(readFileSync(pidFile, "utf8"))), + env, dir, ready: () => existsSync(pidFile), trace: () => readTrace(traceFile), acpPid: () => reportedProcess(JSON.parse(readFileSync(pidFile, "utf8"))), }; } @@ -212,9 +212,13 @@ test("omits plan when initialize does not advertise tier or authenticate refuses test("kills a stalled ACP tier probe at its short deadline and omits plan", async () => { const stalled = fakeAccountAgy({ persistedMethod: "oauth-personal", authMode: "stall" }); + const waitForFixture = holdFixtureDeadline(); + const plan = readAntigravityPlan(stalled.installation.command, { HOME: stalled.dir, USERPROFILE: stalled.dir }, { timeoutMs: 400 }); + await waitForFixture(plan, async () => { + expect(await eventually(stalled.ready, 10_000), "authenticate published its process identity").toBe(true); + }); const started = performance.now(); - const plan = await readAntigravityPlan(stalled.installation.command, { HOME: stalled.dir, USERPROFILE: stalled.dir }, { timeoutMs: 400 }); - expect(plan).toBeUndefined(); + expect(await plan).toBeUndefined(); expect(performance.now() - started).toBeLessThan(2000); expect(await gone(stalled.acpPid())).toBe(true); }); diff --git a/tests/ci-runtime-scripts.test.ts b/tests/ci-runtime-scripts.test.ts index e4bcc8f61..86de7bede 100644 --- a/tests/ci-runtime-scripts.test.ts +++ b/tests/ci-runtime-scripts.test.ts @@ -1,13 +1,33 @@ -import { spawnSync } from "node:child_process"; +import { globSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { runExecutable } from "../packages/oar/src/shared/executable/run.js"; +import { asRecord, parseJson } from "../packages/oar/src/shared/json.js"; import path from "node:path"; import { expect, test } from "vitest"; import { acceptedPiVersions, checkPiManifestConsistency, satisfiesPublishedRange } from "./fixtures/clean-install-pins.js"; -test("CI candidate scripts preserve failures and install only the frozen local fixture", () => { - const result = spawnSync(process.execPath, - ["--test", "--test-reporter=tap", ".github/scripts/runtime-ci.test.mjs"], { encoding: "utf8", timeout: 90_000, maxBuffer: 2 * 1024 * 1024 }); - expect(result.status, result.stdout + result.stderr).toBe(0); - expect(result.stdout).toMatch(/# fail 0/u); +function fixtureEnvironment(directory: string): NodeJS.ProcessEnv { + const inherited = Object.entries(process.env).filter(([key]) => !/^(?:temp|tmp|tmpdir|runner_temp|npm_config_cache)$/iu.test(key)); + return { ...Object.fromEntries(inherited), TEMP: directory, TMP: directory, TMPDIR: directory, RUNNER_TEMP: directory, + npm_config_cache: path.join(directory, "cache") }; +} + +test("CI candidate scripts preserve failures and install only the frozen local fixture", async () => { + const directory = mkdtempSync(path.join(tmpdir(), "oar-ci-")); + try { + const result = await runExecutable(process.execPath, ["--test", "--test-reporter=tap", ".github/scripts/runtime-ci.test.mjs"], { + timeoutMs: 90_000, env: fixtureEnvironment(directory), + }); + if (!result.ok) { + const reports = globSync("oar-runtime install-test-*/reports/*.json", { cwd: directory }); + const stages = reports.map(file => { + const raw = readFileSync(path.join(directory, file), "utf8"); + return asRecord(parseJson(raw))?.stage; + }); + throw new Error(`CI candidate scripts failed: ${JSON.stringify(result.diagnostics)}, active installer stages ${JSON.stringify(stages)}\n${result.stdout}\n${result.stderr}`); + } + expect(result.stdout).toMatch(/# fail 0/u); + } finally { rmSync(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); } }, 100_000); test("the gate derives Pi and undici pins from the actual accepted workspace graph", () => { diff --git a/tests/executable-probe-pipes.test.ts b/tests/executable-probe-pipes.test.ts index 985081d76..c4f6f0910 100644 --- a/tests/executable-probe-pipes.test.ts +++ b/tests/executable-probe-pipes.test.ts @@ -1,3 +1,4 @@ +import { holdFixtureDeadline } from "./fixtures/fixture-deadline.js"; import { setTimeout as delay } from "node:timers/promises"; import { fileURLToPath } from "node:url"; import { afterEach, expect, test, vi } from "vitest"; @@ -31,14 +32,18 @@ test.skipIf(process.platform === "win32").each(["exited", "running", "cancelled" vi.stubEnv("OAR_KILL_GRACE_MS", "100"); // oxlint-disable-next-line max-statements -- Keep timeout evidence and descendant cleanup in the same real-process observation. await withTreeProbe({ ignoreSigterm: false }, async (probe) => { + const waitForFixture = holdFixtureDeadline(mode !== "cancelled"); const controller = new AbortController(); const result = runExecutable(process.execPath, [fixture], { env: { ...process.env, ...probe.env, OAR_FIXTURE_EARLY_EXIT: mode === "running" ? "0" : "1" }, timeoutMs: mode === "cancelled" ? 60_000 : 2000, signal: controller.signal, }); - const tree = await probe.tree(); - if (mode !== "running") { expect(await gone(tree.agent)).toBe(true); } + const tree = await waitForFixture(result, async () => { + const observed = await probe.tree(); + if (mode !== "running") { expect(await gone(observed.agent)).toBe(true); } + return observed; + }, controller); if (mode === "cancelled") { controller.abort(); } const bounded = await Promise.race([result, delay(5000).then(() => null)]); expect(bounded).toMatchObject({ ok: false, exitCode: null, diagnostics: mode === "cancelled" @@ -56,13 +61,14 @@ test.skipIf(process.platform === "win32").each(["timeout", "cancelled"])( async (mode) => { vi.stubEnv("OAR_KILL_GRACE_MS", "100"); await withTreeProbe({ ignoreSigterm: false }, async (probe) => { + const waitForFixture = holdFixtureDeadline(mode !== "cancelled"); const controller = new AbortController(); const result = runExecutable(process.execPath, [fixture], { env: { ...process.env, ...probe.env, OAR_FIXTURE_CLOSED_PIPES: "1" }, timeoutMs: mode === "cancelled" ? 60_000 : 2000, signal: controller.signal, }); - const tree = await probe.tree(); + const tree = await waitForFixture(result, async () => probe.tree(), controller); if (mode === "cancelled") { controller.abort(); } expect(await result).toMatchObject({ ok: false, exitCode: null }); expect(await gone(tree.agent)).toBe(true); diff --git a/tests/fixture-deadline.test.ts b/tests/fixture-deadline.test.ts new file mode 100644 index 000000000..2294aaf70 --- /dev/null +++ b/tests/fixture-deadline.test.ts @@ -0,0 +1,29 @@ +import { readFile } from "node:fs/promises"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { expect, test, vi } from "vitest"; +import { runExecutable, type ExecutableResult } from "../packages/oar/src/shared/executable/run.js"; +import { holdFixtureDeadline } from "./fixtures/fixture-deadline.js"; +import { gone, withTreeProbe } from "./fixtures/process-tree.js"; + +const fixture = fileURLToPath(new URL("fixtures/probe-background-child.mjs", import.meta.url)); + +test.each(["deadline", "abort"])("a missing readiness file joins the probe on %s before propagating ENOENT", async mode => { + await withTreeProbe({ ignoreSigterm: false }, async probe => { + const controller = new AbortController(); + const waitForFixture = holdFixtureDeadline(); + const settled = vi.fn((result: ExecutableResult) => result); + const pending = runExecutable(process.execPath, [fixture], { + env: { ...process.env, ...probe.env, OAR_FIXTURE_CLOSED_PIPES: "1" }, timeoutMs: mode === "abort" ? 60_000 : 200, signal: controller.signal, + }).then(settled); + await expect(waitForFixture(pending, async () => { + await probe.tree(); + await readFile(join(probe.dir, "missing-ready")); + }, mode === "abort" ? controller : undefined)).rejects.toMatchObject({ code: "ENOENT" }); + expect(settled.mock.calls).toMatchObject([[{ ok: false, diagnostics: mode === "abort" ? { error: { code: "ABORT_ERR" } } : { timeoutMs: 200 } }]]); + vi.useRealTimers(); + const tree = await probe.tree(); + expect(await gone(tree.agent)).toBe(true); + expect(await gone(tree.grandchild)).toBe(true); + }); +}); diff --git a/tests/fixtures/fake-installer.mjs b/tests/fixtures/fake-installer.mjs index dd3b68f46..51a91c085 100644 --- a/tests/fixtures/fake-installer.mjs +++ b/tests/fixtures/fake-installer.mjs @@ -9,6 +9,7 @@ // failed), "prompt" asks on stdin and installs nothing without an answer, // "hang" starts a worker that holds the output pipes and never finishes. import { captureProcess } from "./process-tree.ts"; +import saveLoginState from "./login-state.mjs"; import { spawn } from "node:child_process"; import { chmodSync, readFileSync, writeFileSync } from "node:fs"; @@ -16,7 +17,7 @@ const [stateFile] = process.argv.slice(2); const state = JSON.parse(readFileSync(stateFile, "utf8")); function save(changes) { - writeFileSync(stateFile, JSON.stringify({ ...state, ...changes })); + saveLoginState(stateFile, { ...state, ...changes }); } function installRuntime() { diff --git a/tests/fixtures/fixture-deadline.ts b/tests/fixtures/fixture-deadline.ts new file mode 100644 index 000000000..a335494c9 --- /dev/null +++ b/tests/fixtures/fixture-deadline.ts @@ -0,0 +1,41 @@ +import assert from "node:assert/strict"; +import { onTestFinished, vi } from "vitest"; +import { eventually } from "./process-tree.js"; + +/** Hold the caller's deadline during real child startup. Always release it + * when readiness settles. On a failed setup, join the operation before the + * error can reach test teardown and discard its timers. + */ +export function holdFixtureDeadline(hold = true) { + if (hold) { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] }); + onTestFinished(() => { vi.useRealTimers(); }); + } + // oxlint-disable-next-line max-statements -- Release the clock and join the same operation on every readiness failure. + return async function waitForFixture(pending: Promise, ready: () => Promise, controller?: AbortController): Promise { + const finished = Promise.allSettled([pending]); + let prepared = false; + try { + const value = await ready(); + prepared = true; + return value; + } finally { + if (hold) { vi.setTimerTickMode("interval"); } + if (!prepared) { + controller?.abort(); + await finished; + // A probe may return when its pipes close, before its force-kill timer. + if (hold) { await vi.runOnlyPendingTimersAsync(); } + } + } + }; +} + +export async function withFixtureDeadline(ready: () => boolean, operation: () => Promise): Promise { + const waitForFixture = holdFixtureDeadline(); + const pending = operation(); + await waitForFixture(pending, async () => { + assert.ok(await eventually(ready, 10_000), "The fixture never published readiness"); + }); + return pending; +} diff --git a/tests/fixtures/probe-background-child.mjs b/tests/fixtures/probe-background-child.mjs index 4fa3f55bd..1cf2b4e1d 100644 --- a/tests/fixtures/probe-background-child.mjs +++ b/tests/fixtures/probe-background-child.mjs @@ -11,11 +11,19 @@ process.on("SIGTERM", () => {}); process.send("ready"); setTimeout(() => { process.exit(0); }, 60_000); `], { stdio: ["ignore", process.env.OAR_FIXTURE_CLOSED_PIPES === "1" ? "ignore" : "inherit", process.env.OAR_FIXTURE_CLOSED_PIPES === "1" ? "ignore" : "inherit", "ipc"] }); -grandchild.once("message", () => { +function publishTree() { const file = process.env.OAR_FIXTURE_PIDS; - if (file === undefined) { throw new Error("missing pid file"); } - writeFileSync(`${file}.tmp`, JSON.stringify({ agent: captureProcess(process.pid), grandchild: captureProcess(grandchild.pid) })); - renameSync(`${file}.tmp`, file); + try { + if (file === undefined) { throw new Error("missing pid file"); } + writeFileSync(`${file}.tmp`, JSON.stringify({ agent: captureProcess(process.pid), grandchild: captureProcess(grandchild.pid) })); + renameSync(`${file}.tmp`, file); + } catch (error) { + grandchild.kill("SIGKILL"); + throw error; + } +} +grandchild.once("message", () => { + publishTree(); const flood = process.env.OAR_FIXTURE_FLOOD; if (flood === "stdout" || flood === "stderr") { process[flood].write("x".repeat(2 * 1024 * 1024 + 1)); diff --git a/tests/install.test.ts b/tests/install.test.ts index b9ddc8e06..2ca4536b5 100644 --- a/tests/install.test.ts +++ b/tests/install.test.ts @@ -1,3 +1,4 @@ +import { withFixtureDeadline } from "./fixtures/fixture-deadline.js"; import guardedFixtureArgs from "./fixtures/guard-processes.js"; import assert from "node:assert/strict"; import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; @@ -14,6 +15,7 @@ import { type InstallHost, type ScriptInstallMethod, } from "../packages/oar/src/shared/install.js"; +// oxlint-disable-next-line import/max-dependencies -- The installer test checks both the resulting installation and its worker identity. import { executableInstallation } from "../packages/oar/src/shared/installation.js"; let dir = ""; @@ -161,8 +163,8 @@ test("an installer that prompts reads end of input instead of waiting", async () test.skipIf(process.platform === "win32")("a timed out installer is stopped with everything it started", async () => { const fake = fakeInstall("hangs", "hang"); - // Long enough for the fake installer to start its worker on a loaded machine. - const result = await planInstaller(fake.probe, fake.plan)({ timeoutMs: 5000 }); + const result = await withFixtureDeadline(() => fake.read().workerPid !== undefined, + async () => planInstaller(fake.probe, fake.plan)({ timeoutMs: 5000 })); assert.ok(result.kind === "failed"); assert.equal(result.exitCode, null); assert.match(result.output, /stopped the installer after 5000 ms/u); diff --git a/tests/login/claude-login.test.ts b/tests/login/claude-login.test.ts index 0e8a268fc..2405261f3 100644 --- a/tests/login/claude-login.test.ts +++ b/tests/login/claude-login.test.ts @@ -7,6 +7,8 @@ import { claudeAuthStatus } from "../../packages/oar/src/runtimes/claude/auth-st import { claudeLogin } from "../../packages/oar/src/runtimes/claude/login.js"; import { fakeLoginCli, reportedIdentity, type FakeCli } from "../fixtures/login-fixtures.js"; import { recordedInteraction } from "../fixtures/login-interaction.js"; +import { withFixtureDeadline } from "../fixtures/fixture-deadline.js"; +// oxlint-disable-next-line import/max-dependencies -- Collect real PID liveness as well as the login protocol and deadline. import { gone } from "../fixtures/process-tree.js"; const CODE = "fixture-authorization-code#fixture-state"; @@ -157,7 +159,8 @@ test("a failure in claude's own words is reported in them, and `Login failed: In test("a deadline after `Login successful.` is not a timeout: the stored login is confirmed by the status", async () => { const fake = fakeClaude({ mode: "linger" }); - const result = await claudeLogin(installation(fake), recordedInteraction([CODE]), { timeoutMs: 1500 }); + const result = await withFixtureDeadline(() => fake.read().pid !== undefined, + async () => claudeLogin(installation(fake), recordedInteraction([CODE]), { timeoutMs: 1500 })); expect(result).toMatchInlineSnapshot(` { "account": { @@ -206,7 +209,8 @@ test("a command that cannot be spawned fails at once", async () => { test("past the deadline the login is stopped with everything it started", async () => { const fake = fakeClaude({ mode: "hang" }); - const result = await claudeLogin(installation(fake), recordedInteraction(["never"]), { timeoutMs: 1000 }); + const result = await withFixtureDeadline(() => fake.read().workerPid !== undefined, + async () => claudeLogin(installation(fake), recordedInteraction(["never"]), { timeoutMs: 1000 })); expect(result).toMatchInlineSnapshot(` { "detail": "no sign-in within 1000 ms", diff --git a/tests/login/claude-logout.test.ts b/tests/login/claude-logout.test.ts index fa2604b86..df72186a2 100644 --- a/tests/login/claude-logout.test.ts +++ b/tests/login/claude-logout.test.ts @@ -5,6 +5,7 @@ import path from "node:path"; import { afterAll, beforeAll, expect, test } from "vitest"; import { claudeLogout } from "../../packages/oar/src/runtimes/claude/logout.js"; import { fakeLoginCli, reportedIdentity, type FakeCli } from "../fixtures/login-fixtures.js"; +import { withFixtureDeadline } from "../fixtures/fixture-deadline.js"; import { gone } from "../fixtures/process-tree.js"; let dir = ""; @@ -95,7 +96,8 @@ test("a status that cannot tell leaves claude's own report: a logout that succee test("past the deadline the logout is stopped with everything it started, and the status decides", async () => { const fake = fakeClaude({ logoutMode: "hang" }); - expect(await claudeLogout(installation(fake), { timeoutMs: 1000 })).toMatchInlineSnapshot(` + expect(await withFixtureDeadline(() => fake.read().workerPid !== undefined, + async () => claudeLogout(installation(fake), { timeoutMs: 1000 }))).toMatchInlineSnapshot(` { "detail": "claude auth logout did not finish within 1000 ms", "kind": "failed", diff --git a/tests/login/codebuddy-login.test.ts b/tests/login/codebuddy-login.test.ts index 455ed9df0..41dd09c85 100644 --- a/tests/login/codebuddy-login.test.ts +++ b/tests/login/codebuddy-login.test.ts @@ -7,11 +7,18 @@ import { codebuddyLogin } from "../../packages/oar/src/runtimes/codebuddy/login. import { codebuddyAuthStatus, readCodebuddyAuthStatus, projectCodebuddyAuthStatus } from "../../packages/oar/src/runtimes/codebuddy/auth-status.js"; import { codebuddyLogout } from "../../packages/oar/src/runtimes/codebuddy/logout.js"; import { allLoginsExited, fakeLoginCli, reportedLogins } from "../fixtures/login-fixtures.js"; +import { withFixtureDeadline } from "../fixtures/fixture-deadline.js"; +// oxlint-disable-next-line import/max-dependencies -- Login interaction recording and the real child deadline share this fixture. import { recordedInteraction } from "../fixtures/login-interaction.js"; // oxlint-disable-next-line import/no-namespace, import/max-dependencies -- Record the real cleanup reads without making an extra request during login. import * as processTables from "../../packages/oar/src/shared/executable/process-table-async.js"; +function fakeRequestsReached(fake: ReturnType, count: number): boolean { + const { requests } = fake.read(); + return Array.isArray(requests) && requests.length >= count; +} + const directories: string[] = []; beforeEach(() => { vi.stubEnv("CODEBUDDY_API_KEY", undefined); }); // A timed-out status query returns at its deadline, before its process is gone (#703): on Windows that process may still hold or write the directory. @@ -111,12 +118,14 @@ it("redacts known account identity from native control errors", async () => { it.each(["timeout", "native-timeout"])("%s settles as timed_out and stops the login process", async (mode) => { const { fake, installation } = await fixture(mode); - const result = await codebuddyLogin(installation, recordedInteraction([]), { timeoutMs: 1500 }); + const result = await withFixtureDeadline(() => fakeRequestsReached(fake, 2), + async () => codebuddyLogin(installation, recordedInteraction([]), { timeoutMs: 1500 })); + expect(reportedLogins(fake)).toHaveLength(1); expect(result).toMatchObject({ kind: "failed", reason: "timed_out" }); expect(fake.read().loggedIn).toBe(false); expect(allLoginsExited(fake)).toBe(true); expect(JSON.stringify(result)).not.toContain("synthetic-private-codebuddy-access-token"); -}, 5000); +}); it("native cancellation is not mislabeled as a timeout or denial", async () => { const { installation } = await fixture("native-cancelled"); @@ -189,7 +198,9 @@ it("a silent confirmation shares the whole login deadline and cannot contradict return result; }); try { - expect(await codebuddyLogin(installation, recordedInteraction([]), { timeoutMs: 1500 })).toEqual({ kind: "logged_in" }); + const result = await withFixtureDeadline(() => fakeRequestsReached(fake, 3), + async () => codebuddyLogin(installation, recordedInteraction([]), { timeoutMs: 1500 })); + expect(result).toEqual({ kind: "logged_in" }); const logins = reportedLogins(fake); expect(logins).toHaveLength(2); const after = await observe(); @@ -202,7 +213,7 @@ it("a silent confirmation shares the whole login deadline and cannot contradict } } finally { capture.mockRestore(); } expect(fake.read().loggedIn).toBe(true); -}, 10_000); +}); it("logout is CodeBuddy's stream-json logout, confirmed by initialize.account", async () => { const { fake, installation } = await fixture("success", true); diff --git a/tests/login/codex-login.test.ts b/tests/login/codex-login.test.ts index 19e195886..117a867ea 100644 --- a/tests/login/codex-login.test.ts +++ b/tests/login/codex-login.test.ts @@ -6,6 +6,7 @@ import { afterAll, afterEach, beforeAll, beforeEach, expect, test, vi } from "vi import { codexAuthStatus, codexLogin, projectCodexLoginStatus } from "../../packages/oar/src/runtimes/codex/login.js"; import { fakeLoginCli, reportedIdentity, type FakeCli } from "../fixtures/login-fixtures.js"; import { recordedInteraction } from "../fixtures/login-interaction.js"; +import { withFixtureDeadline } from "../fixtures/fixture-deadline.js"; import { gone } from "../fixtures/process-tree.js"; let dir = ""; @@ -196,7 +197,8 @@ test("a command that cannot be spawned fails at once", async () => { test("past the deadline the app-server is stopped with everything it started", async () => { const fake = fakeCodex({ mode: "hang" }); - const result = await codexLogin(installation(fake), recordedInteraction([]), { timeoutMs: 1000 }); + const result = await withFixtureDeadline(() => fake.read().workerPid !== undefined, + async () => codexLogin(installation(fake), recordedInteraction([]), { timeoutMs: 1000 })); assert.deepEqual(result, { kind: "failed", reason: "timed_out", detail: "no sign-in within 1000 ms" }); assert.ok(await gone(reportedIdentity(fake, "pid")), "the app-server outlived the deadline"); assert.ok(await gone(reportedIdentity(fake, "workerPid")), "a process the app-server started outlived the deadline"); diff --git a/tests/login/codex-logout.test.ts b/tests/login/codex-logout.test.ts index 606e911cc..0a3327b9b 100644 --- a/tests/login/codex-logout.test.ts +++ b/tests/login/codex-logout.test.ts @@ -5,6 +5,7 @@ import path from "node:path"; import { afterAll, beforeAll, expect, test } from "vitest"; import { codexLogout } from "../../packages/oar/src/runtimes/codex/logout.js"; import { fakeLoginCli, reportedIdentity, type FakeCli } from "../fixtures/login-fixtures.js"; +import { withFixtureDeadline } from "../fixtures/fixture-deadline.js"; import { gone } from "../fixtures/process-tree.js"; let dir = ""; @@ -65,7 +66,8 @@ test("codex's failure is rejected in its words; a status still logged in is stil test("past the deadline the logout is stopped with everything it started (its tree on Windows)", async () => { const fake = fakeCodex({ logoutMode: "hang" }); - expect(await codexLogout(installation(fake), { timeoutMs: 1000 })).toMatchInlineSnapshot(` + expect(await withFixtureDeadline(() => fake.read().workerPid !== undefined, + async () => codexLogout(installation(fake), { timeoutMs: 1000 }))).toMatchInlineSnapshot(` { "detail": "codex logout did not finish within 1000 ms", "kind": "failed", diff --git a/tests/opencode/provider-auth.test.ts b/tests/opencode/provider-auth.test.ts index e7a8ad6b4..d983ddb20 100644 --- a/tests/opencode/provider-auth.test.ts +++ b/tests/opencode/provider-auth.test.ts @@ -1,6 +1,8 @@ import { afterEach, expect, test, vi } from "vitest"; import type { LoginProvider } from "../../packages/oar/src/contracts/provider-auth.js"; import { createOpencodeProviderAuth, OpencodeProviderAuthError } from "../../packages/oar/src/runtimes/opencode/provider-auth.js"; +import { holdFixtureDeadline } from "../fixtures/fixture-deadline.js"; +import { eventually } from "../fixtures/process-tree.js"; import { recordedInteraction } from "../fixtures/login-interaction.js"; import { fakeCalls, fakeConnections, fakeList, opencodeAuthFixture, rejectionOf, removeOpencodeAuthFixtures, serverRunning } from "../fixtures/opencode-provider-auth.js"; @@ -179,17 +181,23 @@ test("a 401 from serve is an authentication failure at once, not a timeout", asy expect(Date.now() - started).toBeLessThan(5000); }); +// oxlint-disable-next-line max-statements -- Measure the shared budget from the real server startup through the hanging HTTP request. test("startup and readiness share one timeoutMs: a late listen leaves readiness only the rest", async () => { vi.stubEnv("OAR_KILL_GRACE_MS", "3000"); const { create, fake } = await opencodeAuthFixture({ listenDelayMs: 1200, hangPlugin: true }); - const started = Date.now(); - const error = await rejectionOf(create({ timeoutMs: 2000 })); - const elapsed = Date.now() - started; + const waitForFixture = holdFixtureDeadline(); + const pending = rejectionOf(create({ timeoutMs: 2000 })); + await waitForFixture(pending, async () => { + expect(await eventually(() => fake.read().serverPid !== undefined, 10_000), "The server published its identity").toBe(true); + }); + const started = performance.now(); + const error = await pending; + const elapsed = performance.now() - started; expect(error).toMatchObject({ kind: "timed_out" }); // A full timeoutMs for the hanging read would end after about 3.2 s. expect(elapsed, `ended after ${String(elapsed)} ms`).toBeLessThan(2800); expect(fakeCalls(fake)).toContainEqual({ method: "GET", path: "/api/plugin" }); - await expect.poll(() => serverRunning(fake), { timeout: 10_000 }).toBe(false); + expect(await eventually(() => !serverRunning(fake), 10_000)).toBe(true); }); test("a crashed or silent start is reported with OpenCode's first line", async () => { diff --git a/tests/process-held-pipes.test.ts b/tests/process-held-pipes.test.ts index c20f03193..85af94b0a 100644 --- a/tests/process-held-pipes.test.ts +++ b/tests/process-held-pipes.test.ts @@ -1,3 +1,4 @@ +import { holdFixtureDeadline } from "./fixtures/fixture-deadline.js"; import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; @@ -7,6 +8,7 @@ import { assertRan } from "../packages/oar/src/shared/executable/diagnostics.js" import { runExecutable } from "../packages/oar/src/shared/executable/run.js"; import { spawnLineProcess, type LineProcess } from "../packages/oar/src/shared/executable/process.js"; import { PIPE_CLOSE_MS } from "../packages/oar/src/shared/executable/pipe-close.js"; +// oxlint-disable-next-line import/max-dependencies -- Verify real holder identities alongside the pipe-close and observation seams. import { eventually, gone, fixtureIdentityPath, reportedProcess, reportShellChild, type ProcessIdentity, signalFixture } from "./fixtures/process-tree.js"; // Seams: an unreadable process table, slow cleanup reads, a failing pipe wait. @@ -192,9 +194,13 @@ test.skipIf(!posix)("a command with no deadline whose root exits leaving a holde test.skipIf(!posix)("a timed-out command whose holder OAR may not signal (EPERM) settles instead of waiting for it", async () => { vi.stubEnv("OAR_KILL_GRACE_MS", "200"); const pids = path.join(scratchDir(), "pids"); + const waitForFixture = holdFixtureDeadline(); const pending = runExecutable("sh", ["-c", `sleep 60 & ${reportShellChild} > "$OAR_TEST_PIDS"; cat > /dev/null`], { timeoutMs: 1500, env: { ...process.env, OAR_TEST_PIDS: pids } }); - const { holder, root } = await recordedPids(pids); - holderOutOfReach(() => root, () => holder.pid); + const holder = await waitForFixture(pending, async () => { + const pidsRead = await recordedPids(pids); + holderOutOfReach(() => pidsRead.root, () => pidsRead.holder.pid); + return pidsRead.holder; + }); const result = await within(pending); expect(result === HUNG ? result : { ok: result.ok, timeoutMs: result.diagnostics?.timeoutMs, holders: result.diagnostics?.cleanup?.heldPipes?.holders }) .toEqual({ ok: false, timeoutMs: 1500, holders: [holder.pid] }); @@ -205,8 +211,9 @@ test.skipIf(!posix)("a stopped command's wait for its pipes starts at the SIGKIL // Each cleanup read takes longer than the kill grace plus the limit, as on a loaded machine. seams.cleanupReadDelayMs = PIPE_CLOSE_MS + 500; const pids = path.join(scratchDir(), "pids"); + const waitForFixture = holdFixtureDeadline(); const pending = runExecutable("sh", ["-c", `(trap "" TERM; exec sleep 60) & ${reportShellChild} > "$OAR_TEST_PIDS"; exec sleep 60`], { timeoutMs: 300, env: { ...process.env, OAR_TEST_PIDS: pids } }); - const { holder } = await recordedPids(pids); + const { holder } = await waitForFixture(pending, async () => recordedPids(pids)); const result = await within(pending, 20_000); expect(result === HUNG ? result : { ok: result.ok, timeoutMs: result.diagnostics?.timeoutMs, cleanup: result.diagnostics?.cleanup }).toEqual({ ok: false, timeoutMs: 300, cleanup: undefined }); expect(await gone(holder)).toBe(true); diff --git a/tests/process-table-command.test.ts b/tests/process-table-command.test.ts index 39055e29b..f6e43e847 100644 --- a/tests/process-table-command.test.ts +++ b/tests/process-table-command.test.ts @@ -1,6 +1,8 @@ +import { existsSync, readFileSync } from "node:fs"; +import { holdFixtureDeadline } from "./fixtures/fixture-deadline.js"; import { setImmediate as nextTurn } from "node:timers/promises"; import { afterEach, expect, test, vi } from "vitest"; -import { reportedProcess, signalFixture } from "./fixtures/process-tree.js"; +import { eventually, gone, reportedProcess, signalFixture } from "./fixtures/process-tree.js"; import { processTableCommand } from "../packages/oar/src/shared/executable/process-table-command.js"; import { processTableFailure } from "../packages/oar/src/shared/executable/process-tree.js"; @@ -34,11 +36,32 @@ test("query deadline includes pipes held after the query root exits", async () = const dir = await mkdtemp(path.join(tmpdir(), "oar-query-pipe-")); const file = path.join(dir, "tool.pid"); const identityPath = path.resolve(import.meta.dirname, "fixtures/process-tree.ts"); - const source = `const { captureProcess } = require(${JSON.stringify(identityPath)}); const {spawn} = require('node:child_process'); const fs = require('node:fs'); const tool = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 60000)'], {stdio: ['ignore', 1, 'ignore'], detached: true}); fs.writeFileSync(process.argv[1], JSON.stringify(captureProcess(tool.pid))); process.exit(0);`; + const source = ` + const { writeProcessReport } = require(${JSON.stringify(identityPath)}); + const { spawn } = require("node:child_process"); + const tool = spawn(process.execPath, ["-e", "setTimeout(() => {}, 60000)"], { stdio: ["ignore", 1, "ignore"], detached: true }); + try { + writeProcessReport(process.argv[1] + ".root", process.pid); + writeProcessReport(process.argv[1], tool.pid); + } catch (error) { + tool.kill("SIGKILL"); + throw error; + } + process.exit(0); + `; try { + const waitForFixture = holdFixtureDeadline(); + const pending = Promise.allSettled([processTableCommand(process.execPath, ["-e", source, file])]); + await waitForFixture(pending, async () => { + expect(await eventually(() => existsSync(file), 10_000), "The child published its identity").toBe(true); + const root = readFileSync(`${file}.root`, "utf8"); + const rootIdentity = reportedProcess(JSON.parse(root)); + expect(await gone(rootIdentity), "The root exited while its child held stdout").toBe(true); + }); const started = performance.now(); - const failure = await processTableCommand(process.execPath, ["-e", source, file]).catch((error: unknown) => processTableFailure(error, "ps", 1)); + const [result] = await pending; + const failure = result.status === "rejected" ? processTableFailure(result.reason, "ps", 1) : result.value; expect(failure).toEqual({ ok: false, source: "ps", elapsedMs: 1, reason: "timeout", code: "ETIMEDOUT", timeoutMs: 5000 }); expect(performance.now() - started).toBeLessThan(10_000); } finally { diff --git a/tests/windows-auxiliary-cleanup.test.ts b/tests/windows-auxiliary-cleanup.test.ts index 800fd12b0..3005133da 100644 --- a/tests/windows-auxiliary-cleanup.test.ts +++ b/tests/windows-auxiliary-cleanup.test.ts @@ -1,3 +1,4 @@ +import { holdFixtureDeadline } from "./fixtures/fixture-deadline.js"; import { setTimeout as delay } from "node:timers/promises"; import { fileURLToPath } from "node:url"; import { expect, test } from "vitest"; @@ -31,7 +32,9 @@ async function stopTerminal( } windowsTest.each(["timeout", "cancelled", "stdout", "stderr", "closed-timeout", "closed-cancelled"])("a %s probe ends its launcher and descendants", async (mode) => { + // oxlint-disable-next-line max-statements -- Observe readiness, stop and liveness on the same Windows tree. await withTreeProbe({ ignoreSigterm: false }, async (probe) => { + const waitForFixture = holdFixtureDeadline(mode.endsWith("timeout")); const controller = new AbortController(); const pending = runExecutable(fakeAgentBinary(probe.dir, [fixture]), [], { env: { @@ -42,7 +45,7 @@ windowsTest.each(["timeout", "cancelled", "stdout", "stderr", "closed-timeout", timeoutMs: mode.endsWith("timeout") ? 3000 : 60_000, signal: controller.signal, }); - const tree = await probe.tree(); + const tree = await waitForFixture(pending, async () => probe.tree(), controller); if (mode.endsWith("cancelled")) { controller.abort(); } const result = await bounded(pending); expect(result, "the stopped probe settles while its descendants would otherwise hold its pipes").not.toBeNull();