diff --git a/src/application/ClientConfigurationToml.test.ts b/src/application/ClientConfigurationToml.test.ts new file mode 100644 index 00000000000..2e4d2921578 --- /dev/null +++ b/src/application/ClientConfigurationToml.test.ts @@ -0,0 +1,140 @@ +import { describe, expect, it } from "vitest"; +import { PRODUCT_IDENTITY } from "../identity.js"; +import { + parseClientToml, + serializeCodexConfiguration, + serializeGrokConfiguration, +} from "./ClientConfigurationToml.js"; + +const KEY = PRODUCT_IDENTITY.mcpServerKey; + +describe("parseClientToml", () => { + it("keeps TOML integers distinct from integral floats as bigints", () => { + const parsed = parseClientToml("count = 42\nratio = 42.0\n"); + expect(parsed).toEqual({ count: 42n, ratio: 42 }); + expect(typeof parsed.count).toBe("bigint"); + expect(typeof parsed.ratio).toBe("number"); + }); + + it("accepts signed 64-bit integer bounds and rejects out-of-range integers", () => { + const bounds = parseClientToml( + "min = -9223372036854775808\nmax = 9223372036854775807\n", + ); + expect(bounds).toEqual({ + min: -(2n ** 63n), + max: 2n ** 63n - 1n, + }); + expect(() => parseClientToml("overflow = 9223372036854775808\n")).toThrow( + SyntaxError, + ); + expect(() => parseClientToml("underflow = -9223372036854775809\n")).toThrow( + SyntaxError, + ); + }); + + it("rejects malformed TOML syntax", () => { + expect(() => parseClientToml("[unterminated\nkey = 1\n")).toThrow(); + }); +}); + +describe("serializeCodexConfiguration", () => { + it("preserves comments, unrelated tables, and quoted sibling server keys", () => { + const original = [ + "# Top user comment", + 'model = "o3"', + "", + '[mcp_servers."rea.env"]', + 'command = "other"', + "", + `[mcp_servers.${KEY}]`, + 'command = "old-npx"', + 'args = ["old"]', + "", + "[mcp_servers.other]", + 'command = "keep-me"', + "", + ].join("\n"); + + const updated = { + model: "o3", + mcp_servers: { + "rea.env": { command: "other" }, + [KEY]: { command: "npx", args: ["-y", "rea-agents@latest", "mcp"] }, + other: { command: "keep-me" }, + }, + }; + + const first = serializeCodexConfiguration(updated, original); + expect(first).toContain("# Top user comment"); + expect(first).toContain('[mcp_servers."rea.env"]'); + expect(first).toContain('command = "keep-me"'); + expect(parseClientToml(first)).toEqual(updated); + + // Repeating the same serialization must be idempotent. + const second = serializeCodexConfiguration(updated, first); + expect(second).toBe(first); + }); + + it("removes the REA server section cleanly while preserving other settings", () => { + const original = [ + "# Keep comment", + "retries = 3", + "", + `[mcp_servers.${KEY}]`, + 'command = "npx"', + "", + ].join("\n"); + + const removed = serializeCodexConfiguration({ retries: 3n }, original); + expect(removed).toContain("# Keep comment"); + expect(parseClientToml(removed)).toEqual({ retries: 3n }); + }); + + it("serializes from scratch when original text is absent or blank", () => { + const doc = { + mcp_servers: { + [KEY]: { command: "npx", args: ["rea-agents", "mcp"] }, + }, + }; + const fromUndefined = serializeCodexConfiguration(doc, undefined); + const fromBlank = serializeCodexConfiguration(doc, " \n "); + expect(parseClientToml(fromUndefined)).toEqual(doc); + expect(parseClientToml(fromBlank)).toEqual(doc); + }); +}); + +describe("serializeGrokConfiguration", () => { + it("updates the REA server section while preserving unrelated Grok sections", () => { + const original = [ + "# Grok config", + 'theme = "dark"', + "", + "[mcp_servers.custom]", + 'command = "custom-mcp"', + "", + ].join("\n"); + + const doc = { + theme: "dark", + mcp_servers: { + custom: { command: "custom-mcp" }, + [KEY]: { command: "npx", args: ["rea-agents", "mcp"] }, + }, + }; + + const serialized = serializeGrokConfiguration(doc, original); + expect(serialized).toContain("# Grok config"); + expect(parseClientToml(serialized)).toEqual(doc); + }); + + it("serializes a fresh document when original text is undefined", () => { + const doc = { + mcp_servers: { + [KEY]: { command: "npx", args: ["rea-agents", "mcp"] }, + }, + }; + expect(parseClientToml(serializeGrokConfiguration(doc, undefined))).toEqual( + doc, + ); + }); +}); diff --git a/src/application/analysisView/NativeObservationViews.test.ts b/src/application/analysisView/NativeObservationViews.test.ts index b576bf2c31f..cf82237a2f5 100644 --- a/src/application/analysisView/NativeObservationViews.test.ts +++ b/src/application/analysisView/NativeObservationViews.test.ts @@ -506,6 +506,7 @@ it("orders canonical numeric graph depths before nonnumeric keys across pages", value.parent_operation !== "get_call_graph" ) throw new Error("Expected graph page"); + expect(value.items.rows.length).toBeGreaterThan(0); expect(value.items.rows.every((row) => row.source_index === 0)).toBe(true); expect(value.coverage).toMatchObject({ total: 8, diff --git a/src/artifacts/UnityFsArtifactReader.boundaries.test.ts b/src/artifacts/UnityFsArtifactReader.boundaries.test.ts index 71f6564460a..6d59ea641cd 100644 --- a/src/artifacts/UnityFsArtifactReader.boundaries.test.ts +++ b/src/artifacts/UnityFsArtifactReader.boundaries.test.ts @@ -1,6 +1,7 @@ import { collectEntries } from "../../tests/fixtures/artifactEntries.js"; import { artifactPreparationRecoveryCases, + artifactSourcePreparationBoundaryCases, boundedArchiveStreamCases, } from "../../tests/fixtures/artifactReaderLifecycle.js"; import { truncate, writeFile } from "node:fs/promises"; @@ -13,7 +14,6 @@ import { awaitAcknowledgement } from "../../tests/fixtures/lifecycleAcknowledgem import { buildUnityFs } from "../../tests/fixtures/unityfs.js"; import { openRegularFile } from "../filesystem/RegularFile.js"; import { UnityFsArtifactReader } from "./UnityFsArtifactReader.js"; -import { ArtifactFileSource } from "../resources/index.js"; const fixture = (bytes: Buffer): Promise => createTestTempFile("rea-unity-boundary-", "bundle", bytes); @@ -37,70 +37,10 @@ const repeatedBlock = (data: Buffer): Buffer => { ]); }; -it("retries UnityFs preparation cancelled during file reading", async () => { - const path = await fixture(buildUnityFs([{ path: "a", data: "x" }])); - const admitted = await openRegularFile(path, { symlinks: "reject" }); - const reader = new UnityFsArtifactReader(path, admitted); - const controller = new AbortController(); - const reason = { stage: "header read" }; - const nativeRead = admitted.handle.read.bind(admitted.handle); - const read = vi.spyOn(admitted.handle, "read").mockImplementation((async ( - ...args: unknown[] - ) => { - const result = await Reflect.apply(nativeRead, admitted.handle, args); - controller.abort(reason); - return result; - }) as typeof admitted.handle.read); - try { - await expect( - (async () => { - for await (const _ of reader.entries(controller.signal)) { - } - })(), - ).rejects.toMatchObject({ reason: "cancelled", cause: reason }); - read.mockRestore(); - expect((await collectEntries(reader)).map((entry) => entry.path)).toEqual([ - "a", - ]); - } finally { - read.mockRestore(); - await reader.close(); - await admitted.handle.close(); - } -}); - -it("does not publish UnityFs entries when final source verification fails", async () => { - const path = await fixture(buildUnityFs([{ path: "a", data: "x" }])); - const control = new UnityFsArtifactReader(path); - const reader = new UnityFsArtifactReader(path); - const expected = (await collectEntries(control))[0]!; - const nativeRead = ArtifactFileSource.prototype.read; - const physical = Object.assign( - new Error("final source verification failed"), - { code: "EIO" }, - ); - let calls = 0; - const read = vi - .spyOn(ArtifactFileSource.prototype, "read") - .mockImplementation(function (this: ArtifactFileSource, ...args) { - calls += 1; - if (calls === 2) return Promise.reject(physical); - return nativeRead.apply(this, args); - }); - try { - await expect(collectEntries(reader)).rejects.toBe(physical); - await expect(reader.open(expected)).rejects.toMatchObject({ - reason: "integrity", - }); - read.mockRestore(); - expect((await collectEntries(reader)).map((entry) => entry.path)).toEqual([ - "a", - ]); - } finally { - read.mockRestore(); - await reader.close(); - await control.close(); - } +artifactSourcePreparationBoundaryCases({ + label: "UnityFs", + image: () => buildUnityFs([{ path: "a", data: "x" }]), + createReader: (path, admitted) => new UnityFsArtifactReader(path, admitted), }); describe("UnityFS declared container bounds", () => { diff --git a/src/artifacts/WxapkgArtifactReader.boundaries.test.ts b/src/artifacts/WxapkgArtifactReader.boundaries.test.ts index 97e83486856..dc19cce5f4c 100644 --- a/src/artifacts/WxapkgArtifactReader.boundaries.test.ts +++ b/src/artifacts/WxapkgArtifactReader.boundaries.test.ts @@ -1,6 +1,7 @@ import { collectEntries } from "../../tests/fixtures/artifactEntries.js"; import { artifactPreparationRecoveryCases, + artifactSourcePreparationBoundaryCases, boundedArchiveStreamCases, } from "../../tests/fixtures/artifactReaderLifecycle.js"; import { once } from "node:events"; @@ -19,70 +20,10 @@ import { ArtifactFileSource } from "../resources/index.js"; const fixture = (bytes: Buffer): Promise => createTestTempFile("rea-wxapkg-boundary-", "package.wxapkg", bytes); -it("retries Wxapkg preparation cancelled during file reading", async () => { - const path = await fixture(buildWxapkg([{ path: "a", data: "x" }])); - const admitted = await openRegularFile(path, { symlinks: "reject" }); - const reader = new WxapkgArtifactReader(path, admitted); - const controller = new AbortController(); - const reason = { stage: "header read" }; - const nativeRead = admitted.handle.read.bind(admitted.handle); - const read = vi.spyOn(admitted.handle, "read").mockImplementation((async ( - ...args: unknown[] - ) => { - const result = await Reflect.apply(nativeRead, admitted.handle, args); - controller.abort(reason); - return result; - }) as typeof admitted.handle.read); - try { - await expect( - (async () => { - for await (const _ of reader.entries(controller.signal)) { - } - })(), - ).rejects.toMatchObject({ reason: "cancelled", cause: reason }); - read.mockRestore(); - expect((await collectEntries(reader)).map((entry) => entry.path)).toEqual([ - "a", - ]); - } finally { - read.mockRestore(); - await reader.close(); - await admitted.handle.close(); - } -}); - -it("does not publish Wxapkg entries when final source verification fails", async () => { - const path = await fixture(buildWxapkg([{ path: "a", data: "x" }])); - const control = new WxapkgArtifactReader(path); - const reader = new WxapkgArtifactReader(path); - const expected = (await collectEntries(control))[0]!; - const nativeRead = ArtifactFileSource.prototype.read; - const physical = Object.assign( - new Error("final source verification failed"), - { code: "EIO" }, - ); - let calls = 0; - const read = vi - .spyOn(ArtifactFileSource.prototype, "read") - .mockImplementation(function (this: ArtifactFileSource, ...args) { - calls += 1; - if (calls === 2) return Promise.reject(physical); - return nativeRead.apply(this, args); - }); - try { - await expect(collectEntries(reader)).rejects.toBe(physical); - await expect(reader.open(expected)).rejects.toMatchObject({ - reason: "integrity", - }); - read.mockRestore(); - expect((await collectEntries(reader)).map((entry) => entry.path)).toEqual([ - "a", - ]); - } finally { - read.mockRestore(); - await reader.close(); - await control.close(); - } +artifactSourcePreparationBoundaryCases({ + label: "Wxapkg", + image: () => buildWxapkg([{ path: "a", data: "x" }]), + createReader: (path, admitted) => new WxapkgArtifactReader(path, admitted), }); describe("wxapkg allocation and malformed-input boundaries", () => { diff --git a/src/artifacts/apple/AppleAssetCatalogAnalysis.test.ts b/src/artifacts/apple/AppleAssetCatalogAnalysis.test.ts index a529ce57ae5..5d7f27e0c63 100644 --- a/src/artifacts/apple/AppleAssetCatalogAnalysis.test.ts +++ b/src/artifacts/apple/AppleAssetCatalogAnalysis.test.ts @@ -6,6 +6,7 @@ import { describe, expect, it, onTestFinished } from "vitest"; import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js"; import { spawnFailure } from "../../../tests/support/process/spawnFailure.js"; +import { processHasStopped } from "../../../tests/support/process/observePosixProcess.js"; import { OwnedCommandFailure } from "../../process/OwnedCommand.js"; import { spawnOwnedProviderProcess } from "../../process/ProviderProcess.js"; import { cleanupOwnedProcessGroup } from "../../process/ProcessOwnership.js"; @@ -64,15 +65,6 @@ const standInAssetUtil = ( return Object.assign(launcher, { pids }); }; -const alive = (pid: number): boolean => { - try { - process.kill(pid, 0); - return true; - } catch { - return false; - } -}; - /** A completed assetutil run the owned command reports as failed. */ const assetUtilCommandFailure = ( reason: OwnedCommandFailure["reason"], @@ -538,7 +530,9 @@ describe("Apple asset catalog and Interface Builder concurrency", () => { cause: "stop asset inspection", }); expect(launcher.pids).toHaveLength(1); - expect(launcher.pids.filter(alive)).toEqual([]); + expect(launcher.pids.length).toBeGreaterThan(0); + for (const pid of launcher.pids) + expect(await processHasStopped(pid)).toBe(true); } finally { controller.abort("stop asset inspection"); await settled; diff --git a/src/cliMcpRegistration.test.ts b/src/cliMcpRegistration.test.ts index c2aba818e72..aab6159635d 100644 --- a/src/cliMcpRegistration.test.ts +++ b/src/cliMcpRegistration.test.ts @@ -3,7 +3,7 @@ import { mkdir, writeFile } from "node:fs/promises"; import { delimiter, join } from "node:path"; import { pathToFileURL } from "node:url"; import { Ajv2020 } from "ajv/dist/2020.js"; -import { beforeAll, expect, it } from "vitest"; +import { expect, it } from "vitest"; import { z } from "zod"; import { mcpRegistrationReportSchema } from "./contracts/mcpRegistration.js"; @@ -198,7 +198,6 @@ const captureRegistration = async () => { process.execPath, ["--import", "tsx", entry], { - timeoutMs: 20_000, env: { ...registrationChildEnvironment(home), PATH: join(root, "bin") + delimiter + process.env.PATH, @@ -215,12 +214,12 @@ const captureRegistration = async () => { } }; -let observed: z.infer; -beforeAll(async () => { - observed = await captureRegistration(); -}, 30_000); +let observedPromise: Promise> | undefined; +const getObserved = (): Promise> => + (observedPromise ??= captureRegistration()); -it("validates named input/output schemas against every registration report", () => { +it("validates named input/output schemas against every registration report", async () => { + const observed = await getObserved(); const schemas = z .object({ inputSchema: z.record(z.string(), z.unknown()), @@ -253,7 +252,8 @@ it("validates named input/output schemas against every registration report", () ); }); -it("preserves default and mixed launcher facts, metadata, backups and no-op identity", () => { +it("preserves default and mixed launcher facts, metadata, backups and no-op identity", async () => { + const observed = await getObserved(); const all = mcpRegistrationReportSchema.parse(observed.all.document); expect(observed.all.exitCode).toBe(0); expect(all.ok).toBe(true); @@ -329,7 +329,8 @@ it("preserves default and mixed launcher facts, metadata, backups and no-op iden ).toBe(true); }); -it("retains actionable failures and completed siblings in either order", () => { +it("retains actionable failures and completed siblings in either order", async () => { + const observed = await getObserved(); const firstFailure = mcpRegistrationReportSchema.parse( observed.failedThenSuccess.document, ); @@ -354,7 +355,8 @@ it("retains actionable failures and completed siblings in either order", () => { expect(client.error.reason).toContain(".cursor"); }); -it("refuses remote transport and project-scope escalation before writes", () => { +it("refuses remote transport and project-scope escalation before writes", async () => { + const observed = await getObserved(); for (const invocation of observed.remote) { expect(invocation.exitCode).toBe(1); expect(invocation.document).toMatchObject({ @@ -377,7 +379,8 @@ it("refuses remote transport and project-scope escalation before writes", () => expect(observed.refusalDidNotWrite).toBe(true); }); -it("preserves runner launcher data without acquisition or ambient writes", () => { +it("preserves runner launcher data without acquisition or ambient writes", async () => { + const observed = await getObserved(); for (const { runner, invocation, entry } of observed.runners) { expect(invocation.exitCode).toBe(0); const report = mcpRegistrationReportSchema.parse(invocation.document); diff --git a/src/domain/apiContract/parseGraphqlContract.test.ts b/src/domain/apiContract/parseGraphqlContract.test.ts index dbd20684f24..bc90e4f4462 100644 --- a/src/domain/apiContract/parseGraphqlContract.test.ts +++ b/src/domain/apiContract/parseGraphqlContract.test.ts @@ -112,6 +112,7 @@ it("uses declared roots and interface/inline-fragment type scopes", () => { expect(report.types.find((row) => row.name === "User")?.interfaces).toEqual([ "Node", ]); + expect(report.references.length).toBeGreaterThan(0); expect(report.references.every((row) => row.state === "resolved")).toBe(true); }); @@ -343,5 +344,6 @@ it("matches full SDK field scope while pruning variable defaults, arguments and row.result_type, ]), ).toEqual(expected); + expect(report.references.length).toBeGreaterThan(0); expect(report.references.every((row) => row.state === "resolved")).toBe(true); }); diff --git a/src/domain/linux/systemdJournal.test.ts b/src/domain/linux/systemdJournal.test.ts new file mode 100644 index 00000000000..b685fb89663 --- /dev/null +++ b/src/domain/linux/systemdJournal.test.ts @@ -0,0 +1,158 @@ +import { describe, expect, it } from "vitest"; +import { + createJournalDecoder, + hasSystemdJournalHeader, + JOURNAL_INLINE_OBJECT_LIMIT, +} from "./systemdJournal.js"; + +const MAGIC = Buffer.from("LPKSHHRH", "ascii"); +const HEADER_SIZE = 208; + +const makeJournalHeader = ( + overrides: { + readonly compatibleFlags?: number; + readonly incompatibleFlags?: number; + readonly state?: number; + readonly headerSize?: bigint; + readonly arenaSize?: bigint; + readonly tailObjectOffset?: bigint; + readonly nObjects?: bigint; + } = {}, +): Buffer => { + const buf = Buffer.alloc(HEADER_SIZE); + MAGIC.copy(buf, 0); + buf.writeUInt32LE(overrides.compatibleFlags ?? 0, 8); + buf.writeUInt32LE(overrides.incompatibleFlags ?? 0, 12); + buf[16] = overrides.state ?? 1; // online + buf.writeBigUInt64LE(overrides.headerSize ?? BigInt(HEADER_SIZE), 88); + buf.writeBigUInt64LE(overrides.arenaSize ?? 0n, 96); + buf.writeBigUInt64LE(overrides.tailObjectOffset ?? 0n, 136); + buf.writeBigUInt64LE(overrides.nObjects ?? 0n, 144); + return buf; +}; + +const makeObject = (type: number, payloadBytes: number): Buffer => { + const total = 16 + payloadBytes; + const aligned = (total + 7) & ~7; + const buf = Buffer.alloc(aligned); + buf[0] = type; + buf[1] = 0; // flags + buf.writeBigUInt64LE(BigInt(total), 8); + return buf; +}; + +const decodeAll = (bytes: Buffer, objectHeaderStart = 0, chunkSize = 64) => { + const created = createJournalDecoder(bytes.length, objectHeaderStart); + if (!created.ok) throw new Error(created.error.message); + const decoder = created.value; + for (let offset = 0; offset < bytes.length; offset += chunkSize) { + const step = decoder.write(bytes.subarray(offset, offset + chunkSize)); + if (!step.ok) return step; + } + return decoder.finish(); +}; + +describe("hasSystemdJournalHeader", () => { + it("recognizes the 8-byte LPKSHHRH signature and rejects shorter or mismatched prefixes", () => { + expect(hasSystemdJournalHeader(MAGIC)).toBe(true); + expect(hasSystemdJournalHeader(makeJournalHeader())).toBe(true); + expect(hasSystemdJournalHeader(MAGIC.subarray(0, 7))).toBe(false); + expect(hasSystemdJournalHeader(Buffer.from("NOTJRNAL", "ascii"))).toBe( + false, + ); + }); +}); + +describe("createJournalDecoder", () => { + it("rejects negative or non-integer file size and object header start", () => { + expect(createJournalDecoder(-1).ok).toBe(false); + expect(createJournalDecoder(100, -1).ok).toBe(false); + expect(createJournalDecoder(1.5).ok).toBe(false); + expect(createJournalDecoder(Number.MAX_SAFE_INTEGER + 1).ok).toBe(false); + }); + + it("rejects input without a valid journal signature", () => { + const result = decodeAll(Buffer.alloc(HEADER_SIZE, 0x41)); + expect(result.ok).toBe(false); + }); + + it("parses header facts and distinguishes boot_id from tail_entry_boot_id via compatible flags", () => { + const legacy = decodeAll(makeJournalHeader({ compatibleFlags: 0 })); + if (!legacy.ok) throw new Error(legacy.error.message); + expect(legacy.value.metadata.kind).toBe("systemd-journal"); + expect(legacy.value.metadata.header.state).toBe("online"); + expect(legacy.value.metadata.header.boot_id).not.toBeNull(); + expect(legacy.value.metadata.header.tail_entry_boot_id).toBeNull(); + + // COMPATIBLE_TAIL_ENTRY_BOOT_ID = 1 << 1 = 2 + const withTailBoot = decodeAll(makeJournalHeader({ compatibleFlags: 2 })); + if (!withTailBoot.ok) throw new Error(withTailBoot.error.message); + expect(withTailBoot.value.metadata.header.boot_id).toBeNull(); + expect( + withTailBoot.value.metadata.header.tail_entry_boot_id, + ).not.toBeNull(); + }); + + it("inventories valid and unknown-type objects streamed across small chunks", () => { + const dataObj = makeObject(1, 8); // DATA + const unknownObj = makeObject(99, 4); // unknown type + const arenaSize = BigInt(dataObj.length + unknownObj.length); + const header = makeJournalHeader({ + arenaSize, + tailObjectOffset: BigInt(HEADER_SIZE + dataObj.length), + nObjects: 2n, + }); + const file = Buffer.concat([header, dataObj, unknownObj]); + + const result = decodeAll(file, 0, 17); + if (!result.ok) throw new Error(result.error.message); + expect(result.value.metadata.object_count).toBe(2); + expect(result.value.metadata.valid_object_count).toBe(2); + expect(result.value.metadata.unknown_type_object_count).toBe(1); + expect(result.value.metadata.truncated_object_count).toBe(0); + expect(result.value.metadata.trailing_bytes).toBe(0); + }); + + it("bounds retained object headers to JOURNAL_INLINE_OBJECT_LIMIT and supports windowing", () => { + const count = JOURNAL_INLINE_OBJECT_LIMIT + 5; + const objects = Array.from({ length: count }, () => makeObject(1, 8)); + const arenaSize = BigInt(objects.reduce((sum, b) => sum + b.length, 0)); + const tailObjectOffset = BigInt( + HEADER_SIZE + objects.slice(0, -1).reduce((sum, b) => sum + b.length, 0), + ); + const file = Buffer.concat([ + makeJournalHeader({ + arenaSize, + tailObjectOffset, + nObjects: BigInt(count), + }), + ...objects, + ]); + + const firstPage = decodeAll(file, 0); + if (!firstPage.ok) throw new Error(firstPage.error.message); + expect(firstPage.value.metadata.object_count).toBe(count); + expect(firstPage.value.metadata.object_headers).toHaveLength( + JOURNAL_INLINE_OBJECT_LIMIT, + ); + expect(firstPage.value.metadata.omitted_object_headers).toBe(5); + + const secondPage = decodeAll(file, JOURNAL_INLINE_OBJECT_LIMIT); + if (!secondPage.ok) throw new Error(secondPage.error.message); + expect(secondPage.value.metadata.object_headers).toHaveLength(5); + }); + + it("clamps uint64 fields beyond Number.MAX_SAFE_INTEGER and records a limitation", () => { + const header = makeJournalHeader({ + nObjects: BigInt(Number.MAX_SAFE_INTEGER) + 100n, + }); + const result = decodeAll(header); + if (!result.ok) throw new Error(result.error.message); + expect(result.value.metadata.header.n_objects).toBe( + Number.MAX_SAFE_INTEGER, + ); + expect( + result.value.limitations.some((line) => line.includes("n_objects")), + ).toBe(true); + }); +}); diff --git a/src/ghidra/GhidraJavaProbe.test.ts b/src/ghidra/GhidraJavaProbe.test.ts index c7ecffeb9b5..1ada8e5f60d 100644 --- a/src/ghidra/GhidraJavaProbe.test.ts +++ b/src/ghidra/GhidraJavaProbe.test.ts @@ -414,6 +414,7 @@ it("preserves each prerequisite cleanup retry outcome until the same owner relea } await retained[0]!.close(); expect(attempt).toBe(4); + expect(failures.length).toBeGreaterThan(0); expect(failures.every((failure) => !failure.cleanupIncomplete)).toBe(true); expect(result.error.cleanupIncomplete).toBe(false); }); diff --git a/src/hopper/HopperMachOImage.test.ts b/src/hopper/HopperMachOImage.test.ts index 9c8c5fa47b0..a421ae42a92 100644 --- a/src/hopper/HopperMachOImage.test.ts +++ b/src/hopper/HopperMachOImage.test.ts @@ -171,6 +171,7 @@ it("retains Hopper FAT selection across short header, table and slice reads", as }); expect(actual).toEqual(expected); expect(shortReads).toBeGreaterThan(5); + expect(handles.length).toBeGreaterThan(0); expect(handles.every((handle) => handle.fd === -1)).toBe(true); }); diff --git a/src/javascript/analysis/JavaScriptAnalysisWorker.startup.test.ts b/src/javascript/analysis/JavaScriptAnalysisWorker.startup.test.ts index a5f01f461b8..7aa5ac60595 100644 --- a/src/javascript/analysis/JavaScriptAnalysisWorker.startup.test.ts +++ b/src/javascript/analysis/JavaScriptAnalysisWorker.startup.test.ts @@ -12,6 +12,7 @@ import { spawnOwnedProviderProcess } from "../../process/ProviderProcess.js"; import { WorkerFrameSignal } from "../../process/WorkerFrameSignal.js"; import { EventEmitter } from "node:events"; import { phaseArrival } from "../../../tests/support/lifecycleHarness.js"; +import { processHasStopped } from "../../../tests/support/process/observePosixProcess.js"; const text = "export const observed = 1;"; const file: JavaScriptArtifactFile = { @@ -26,15 +27,6 @@ const file: JavaScriptArtifactFile = { }; const budget = { nodes: 100, unknowns: 100 }; -const alive = (pid: number): boolean => { - try { - process.kill(pid, 0); - return true; - } catch { - return false; - } -}; - /** Launch a stand-in worker script under the real owned-process launcher. */ const standInWorker = (script: string) => { const pids: number[] = []; @@ -69,7 +61,9 @@ it("refuses a worker that emits facts before its ready frame and stops it", asyn expect(worker.canReuse()).toBe(false); // The refusal itself stops the child; close() is only teardown. expect(fixture.pids).toHaveLength(1); - expect(fixture.pids.filter(alive)).toEqual([]); + expect(fixture.pids.length).toBeGreaterThan(0); + for (const pid of fixture.pids) + expect(await processHasStopped(pid)).toBe(true); }); it("times out a worker whose ready frame never arrives and stops it", async () => { @@ -101,7 +95,9 @@ it("times out a worker whose ready frame never arrives and stops it", async () = expect(refused.error.error.cleanupIncomplete).toBe(false); // The refusal itself stops the child; close() is only teardown. expect(fixture.pids).toHaveLength(1); - expect(fixture.pids.filter(alive)).toEqual([]); + expect(fixture.pids.length).toBeGreaterThan(0); + for (const pid of fixture.pids) + expect(await processHasStopped(pid)).toBe(true); }); it("wakes a silent worker on an owned memory refusal before the deadline", async () => { diff --git a/src/kuna/KunaCopy.test.ts b/src/kuna/KunaCopy.test.ts index f5b3fa6ba7b..287f25ad339 100644 --- a/src/kuna/KunaCopy.test.ts +++ b/src/kuna/KunaCopy.test.ts @@ -135,6 +135,7 @@ it.each(["read", "write"] as const)( controller.abort(reason); await new Promise((resolve) => setImmediate(resolve)); expect(settled).toBe(false); + expect(handles.length).toBeGreaterThan(0); expect(handles.every(({ fd }) => fd >= 0)).toBe(true); held.release(); const failure = await result; diff --git a/src/native/NativeMacosErrorProjection.test.ts b/src/native/NativeMacosErrorProjection.test.ts new file mode 100644 index 00000000000..351ff62155f --- /dev/null +++ b/src/native/NativeMacosErrorProjection.test.ts @@ -0,0 +1,242 @@ +import { describe, expect, it } from "vitest"; +import { AnalysisOutputError } from "../domain/analysisErrorCore.js"; +import { InternalInvariantError } from "../domain/internalInvariant.js"; +import { ParseFailureError } from "../domain/parseFailure.js"; +import { ProviderCleanupError } from "../domain/providerCleanupError.js"; +import type { ProviderProcessSupervisor } from "../process/ProviderProcess.js"; +import type { NativeCommandCapture } from "../providers/NativeCommandRunner.js"; +import { + codeSignArchitectures, + isNativeOperation, + isNonzeroUnsignedObservation, + nativeCommandCleanupFailure, + nativeOutputFailure, + parseEntitlements, + xmlSyntaxRefusal, +} from "./NativeMacosErrorProjection.js"; + +const makeCapture = ( + overrides: Partial = {}, +): NativeCommandCapture => ({ + tool: "codesign", + executable: "/usr/bin/codesign", + arguments: ["-dvv", "/tmp/snapshot.bin"], + toolVersion: null, + versionReason: null, + executableSha256: "a".repeat(64), + exitCode: 1, + signal: null, + stdout: "", + stderr: "/tmp/snapshot.bin: code object is not signed at all\n", + stdoutBytes: 0, + stderrBytes: 51, + ...overrides, +}); + +describe("nativeOutputFailure", () => { + it("rethrows InternalInvariantError instead of wrapping it as output parsing", () => { + const invariant = new InternalInvariantError("broken assumption"); + expect(() => nativeOutputFailure("inspect_macho", invariant)).toThrow( + invariant, + ); + }); + + it("wraps ordinary producer errors in AnalysisOutputError with cause preserved", () => { + const cause = new SyntaxError("unexpected token"); + const projected = nativeOutputFailure("inspect_macho", cause); + expect(projected).toBeInstanceOf(AnalysisOutputError); + if (!(projected instanceof AnalysisOutputError)) + throw new Error("Expected AnalysisOutputError"); + expect(projected.operation).toBe("inspect_macho"); + expect(projected.cause).toBe(cause); + }); +}); + +describe("isNonzeroUnsignedObservation", () => { + const snapshot = "/tmp/snapshot.bin"; + + it("accepts exact unsigned diagnostics with or without verified Executable prefix", () => { + expect(isNonzeroUnsignedObservation(makeCapture(), snapshot, [])).toBe( + true, + ); + expect( + isNonzeroUnsignedObservation( + makeCapture({ + stderr: `Executable=/app/bin\r\n${snapshot}: code object is not signed at all\r\n`, + }), + snapshot, + ["/app/bin"], + ), + ).toBe(true); + }); + + it("rejects zero exit, signals, stdout noise, operand mismatch, and spoofed stderr", () => { + expect( + isNonzeroUnsignedObservation(makeCapture({ exitCode: 0 }), snapshot, []), + ).toBe(false); + expect( + isNonzeroUnsignedObservation( + makeCapture({ exitCode: null }), + snapshot, + [], + ), + ).toBe(false); + expect( + isNonzeroUnsignedObservation( + makeCapture({ signal: "SIGTERM" }), + snapshot, + [], + ), + ).toBe(false); + expect( + isNonzeroUnsignedObservation( + makeCapture({ stdout: "unexpected" }), + snapshot, + [], + ), + ).toBe(false); + expect( + isNonzeroUnsignedObservation( + makeCapture({ arguments: ["-dvv", "/other/path"] }), + snapshot, + [], + ), + ).toBe(false); + expect( + isNonzeroUnsignedObservation( + makeCapture({ + stderr: `Executable=/unverified/bin\n${snapshot}: code object is not signed at all\n`, + }), + snapshot, + ["/app/bin"], + ), + ).toBe(false); + }); +}); + +describe("codeSignArchitectures", () => { + const baseTarget = { + kind: "executable" as const, + path: "/tmp/app", + canonicalPath: "/tmp/app", + size: 1024, + sha256: "a".repeat(64), + format: "mach-o" as const, + architecture: "arm64" as const, + availableArchitectures: ["arm64", "x86"] as const, + }; + + it("reports unknownSlices when universal target lacks slice inventory", () => { + expect( + codeSignArchitectures(null, { + ...baseTarget, + format: "mach-o-universal", + universalSlice: { + offset: 0, + size: 1024, + }, + }), + ).toEqual({ architectures: [], unknownSlices: true }); + }); + + it("deduplicates architecture names from Mach-O universal format strings", () => { + expect( + codeSignArchitectures( + "Mach-O universal (x86_64 arm64 x86_64)", + baseTarget, + ), + ).toEqual({ architectures: ["x86_64", "arm64"], unknownSlices: false }); + }); + + it("maps x86 to i386 for thin Mach-O targets without thin format prefix", () => { + expect(codeSignArchitectures(null, baseTarget)).toEqual({ + architectures: ["arm64", "i386"], + unknownSlices: false, + }); + }); + + it("returns empty architectures for Mach-O thin format strings", () => { + expect(codeSignArchitectures("Mach-O thin (arm64)", baseTarget)).toEqual({ + architectures: [], + unknownSlices: false, + }); + }); +}); + +describe("parseEntitlements", () => { + it("returns null value with no limitations when no XML plist envelope exists", () => { + expect(parseEntitlements("Executable=/app/bin\n")).toEqual({ + value: null, + limitations: [], + }); + }); + + it("parses XML plist entitlements embedded in codesign output", () => { + const xml = [ + "Executable=/app/bin", + '', + '', + "com.apple.security.app-sandbox", + "com.apple.security.app-sandbox", + "", + ].join("\n"); + const parsed = parseEntitlements(xml); + expect(parsed.value).toEqual({ + "com.apple.security.app-sandbox": false, + }); + expect(parsed.limitations.length).toBeGreaterThan(0); + }); +}); + +describe("xmlSyntaxRefusal", () => { + it("extracts refusal message only for malformed xml ParseFailureError inside AnalysisOutputError", () => { + const malformedXml = new AnalysisOutputError("inspect_plist", "failed", { + cause: new ParseFailureError({ + kind: "malformed", + format: "xml", + detail: "unclosed tag", + }), + }); + expect(xmlSyntaxRefusal(malformedXml)).toContain("unclosed tag"); + + const nonXml = new AnalysisOutputError("inspect_plist", "failed", { + cause: new ParseFailureError({ + kind: "malformed", + format: "plist", + detail: "bad dict", + }), + }); + expect(xmlSyntaxRefusal(nonXml)).toBeUndefined(); + expect(xmlSyntaxRefusal(new Error("plain"))).toBeUndefined(); + }); +}); + +describe("nativeCommandCleanupFailure & isNativeOperation", () => { + it("deduplicates cleanup resources across multiple failures", () => { + const owner = {} as ProviderProcessSupervisor; + const failure = nativeCommandCleanupFailure([ + { + owner, + reason: "pid 1 stuck", + resources: ["process:1", "root:/tmp/a"], + }, + { + owner, + reason: "pid 2 stuck", + resources: ["root:/tmp/a", "process:2"], + }, + ]); + expect(failure).toBeInstanceOf(ProviderCleanupError); + expect(failure.cleanupResources).toEqual([ + "process:1", + "root:/tmp/a", + "process:2", + ]); + }); + + it("distinguishes registered native operations from unrelated ones", () => { + expect(isNativeOperation("inspect_signature")).toBe(true); + expect(isNativeOperation("inspect_plist")).toBe(true); + expect(isNativeOperation("open_binary" as never)).toBe(false); + }); +}); diff --git a/src/oci/OciImageLayoutParser.test.ts b/src/oci/OciImageLayoutParser.test.ts index 2728809b916..196884c456e 100644 --- a/src/oci/OciImageLayoutParser.test.ts +++ b/src/oci/OciImageLayoutParser.test.ts @@ -154,6 +154,7 @@ it("inventories a single-platform layout and keeps Env values by default", async OCI_IMAGE_LAYOUT_LIMITATIONS.envRedacted, ); const hashed = report.blobs.filter((blob) => blob.hashed); + expect(hashed.length).toBeGreaterThan(0); expect(hashed.every((blob) => blob.sha256 !== null)).toBe(true); }); @@ -868,6 +869,7 @@ it("records nested index depth as a finding once the bound is exceeded", async ( expect.objectContaining({ kind: "nested_index_depth_exceeded" }), ]), ); + expect(report.indexes.length).toBeGreaterThan(0); expect(report.indexes.every((index) => index.depth <= 1)).toBe(true); expect(report.coverage.status).toBe("partial"); }); diff --git a/src/process/ExecFileOutput.test.ts b/src/process/ExecFileOutput.test.ts index 508f46ab7fe..0dfa34139a7 100644 --- a/src/process/ExecFileOutput.test.ts +++ b/src/process/ExecFileOutput.test.ts @@ -5,6 +5,7 @@ import { join } from "node:path"; import { describe, expect, it, vi } from "vitest"; import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; +import { processHasStopped } from "../../tests/support/process/observePosixProcess.js"; import { testWaitDeadline } from "../../tests/support/testWait.js"; import { @@ -170,9 +171,7 @@ describe("execFileOutput", () => { [`${stream}Bytes`]: 64, }); const pid = Number(await readFile(identity, "utf8")); - expect(() => process.kill(pid, 0)).toThrow( - expect.objectContaining({ code: "ESRCH" }), - ); + expect(await processHasStopped(pid)).toBe(true); } finally { await vi.runAllTimersAsync(); vi.useRealTimers(); diff --git a/src/process/LinuxResourceLimits.test.ts b/src/process/LinuxResourceLimits.test.ts index 478fa95f449..f39bc5de57a 100644 --- a/src/process/LinuxResourceLimits.test.ts +++ b/src/process/LinuxResourceLimits.test.ts @@ -295,6 +295,7 @@ it("clamps all inherited ceilings after positive short report reads", async () = }); expect(kernel.reads.at(-1)?.position).toBe(Buffer.byteLength(text)); expect(kernel.reads.length).toBeGreaterThan(2); + expect(kernel.handles.length).toBeGreaterThan(0); expect(kernel.handles.every((handle) => handle.fd === -1)).toBe(true); }); diff --git a/src/server/DeferredEvidenceMcpServer.test.ts b/src/server/DeferredEvidenceMcpServer.test.ts index ca70716ee17..2bd6b3abd5b 100644 --- a/src/server/DeferredEvidenceMcpServer.test.ts +++ b/src/server/DeferredEvidenceMcpServer.test.ts @@ -619,7 +619,11 @@ it("cancels in-flight initialization when the server closes", async () => { it("retains failed cleanup for retry without loading a replacement runtime", async () => { let denied = true; const f = await fixture({ failClose: () => denied }); - await f.client.callTool({ name: "fixture", arguments: {} }); + const callResult = await f.client.callTool({ + name: "fixture", + arguments: {}, + }); + expect(callResult.isError).not.toBe(true); await expect(f.server.close()).rejects.toThrow("cleanup"); await expect(f.server.ensureRuntime()).rejects.toThrow("closed"); denied = false; @@ -683,7 +687,8 @@ it("keeps one accepted settings snapshot through a deferred handler while the ne await Promise.allSettled([pending]); } expect((await pending).isError).not.toBe(true); - await f.client.callTool({ name: "fixture", arguments: {} }); + const second = await f.client.callTool({ name: "fixture", arguments: {} }); + expect(second.isError).not.toBe(true); expect(seen).toEqual([undefined, 33554432]); }); @@ -692,6 +697,7 @@ it("suggests advertised deferred tools for an unknown tool call without loading let message = ""; try { await f.client.callTool({ name: "fixture-call", arguments: {} }); + expect.unreachable("expected unknown tool call to fail"); } catch (error) { expect(error).toMatchObject({ code: -32602 }); message = error instanceof Error ? error.message : String(error); diff --git a/src/server/ProgressiveToolCatalog.test.ts b/src/server/ProgressiveToolCatalog.test.ts index 4db01e77b91..a2cbf8abbd0 100644 --- a/src/server/ProgressiveToolCatalog.test.ts +++ b/src/server/ProgressiveToolCatalog.test.ts @@ -351,6 +351,7 @@ it("points unknown tool calls to discover_tools and only suggests currently adve let reconnectMessage = ""; try { await nextClient.callTool({ name: "alpha-sqlite", arguments: {} }); + expect.unreachable("expected unknown tool call after reconnect to fail"); } catch (error) { expect(error).toMatchObject({ code: -32602 }); reconnectMessage = error instanceof Error ? error.message : String(error); diff --git a/src/wasm/WabtArtifactProvider.test.ts b/src/wasm/WabtArtifactProvider.test.ts index 06ac60f85d9..d29247a6003 100644 --- a/src/wasm/WabtArtifactProvider.test.ts +++ b/src/wasm/WabtArtifactProvider.test.ts @@ -4,6 +4,7 @@ import { access, chmod, readFile, realpath, writeFile } from "node:fs/promises"; import { join, resolve } from "node:path"; import { expect, it, onTestFinished, vi } from "vitest"; import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; +import { processHasStopped } from "../../tests/support/process/observePosixProcess.js"; import { WabtArtifactProvider } from "./WabtArtifactProvider.js"; import { WasmArtifactService } from "../application/wasm/WasmArtifactService.js"; import { @@ -1720,9 +1721,7 @@ const runOwnedArtifactOutcome = async ( if (acquiredPid === undefined) throw new Error("The cancelled command did not report an acquired PID"); const pid = acquiredPid; - expect(() => process.kill(pid, 0)).toThrow( - expect.objectContaining({ code: "ESRCH" }), - ); + expect(await processHasStopped(pid)).toBe(true); } }; diff --git a/tests/acceptance/applications/javascriptConfigurationReadsCli.test.ts b/tests/acceptance/applications/javascriptConfigurationReadsCli.test.ts index 021964670d7..3589b66bdea 100644 --- a/tests/acceptance/applications/javascriptConfigurationReadsCli.test.ts +++ b/tests/acceptance/applications/javascriptConfigurationReadsCli.test.ts @@ -53,6 +53,7 @@ cliTest.for(["CLI", "stdio MCP"] as const)( ["environment", "REA_ENDPOINT"], ["environment", "REA_MISSING"], ]); + expect(sources.length).toBeGreaterThan(0); expect(sources.every((node) => node.properties.value === null)).toBe(true); const endpoint = graph.nodes.find( (node) => node.kind === "binding" && node.label === "endpoint", diff --git a/tests/acceptance/process/processFinalization.test.ts b/tests/acceptance/process/processFinalization.test.ts index a5a2b43db06..d935c273ecd 100644 --- a/tests/acceptance/process/processFinalization.test.ts +++ b/tests/acceptance/process/processFinalization.test.ts @@ -22,6 +22,7 @@ import { itWithCaptureCapability as captureTest, } from "../../boundary/process/processCaptureCapability.js"; import { expectSerializedUnverifiedHostCleanup } from "../../support/hostCleanup.js"; +import { processHasStopped } from "../../support/process/observePosixProcess.js"; import { waitFor } from "../../support/testWait.js"; const finalizationFixture = fileURLToPath( @@ -132,9 +133,9 @@ const waitForFinalization = async (root: string): Promise => { }; const waitForProcessExit = async (pid: number): Promise => { - await waitFor(() => { - expect(() => process.kill(pid, 0), "the captured PID has exited").toThrow( - expect.objectContaining({ code: "ESRCH" }), + await waitFor(async () => { + expect(await processHasStopped(pid), "the captured PID has exited").toBe( + true, ); }); }; diff --git a/tests/boundary/android/jadxArchiveLifecycle.test.ts b/tests/boundary/android/jadxArchiveLifecycle.test.ts index c04fbfcb2dd..0f496a5717c 100644 --- a/tests/boundary/android/jadxArchiveLifecycle.test.ts +++ b/tests/boundary/android/jadxArchiveLifecycle.test.ts @@ -74,6 +74,7 @@ it.each(["valid", "malformed", "missing-classes"] as const)( expect(f.launches).toEqual([]); allowClose = true; await f.provider.close(); + expect(handles.size).toBeGreaterThan(0); expect([...handles].every((owner) => owner.handle.fd === -1)).toBe(true); expect(error.cleanupIncomplete).toBe(false); expect(error.cleanupResources).toEqual([]); @@ -365,6 +366,7 @@ it("clears an analysis admission error once its prerequisite archive descriptor expect(handles.size).toBe(1); allowClose = true; await f.provider.close(); + expect(handles.size).toBeGreaterThan(0); expect([...handles].every((owner) => owner.handle.fd === -1)).toBe(true); expect(result.error.cleanupIncomplete).toBe(false); expect(f.launches).toEqual([]); diff --git a/tests/boundary/android/jadxConfiguration.test.ts b/tests/boundary/android/jadxConfiguration.test.ts index 4975332f18b..c03dd11b9df 100644 --- a/tests/boundary/android/jadxConfiguration.test.ts +++ b/tests/boundary/android/jadxConfiguration.test.ts @@ -3,6 +3,7 @@ import { AnalysisSettings } from "../../../src/application/AnalysisSettings.js"; import { JadxProvider } from "../../../src/android/JadxProvider.js"; import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js"; import { createInspectionResources } from "../../fixtures/inspectionResources.js"; +import { processHasStopped } from "../../support/process/observePosixProcess.js"; import { chmod, mkdir, @@ -549,26 +550,17 @@ fs.renameSync(ready + ".pending", ready); () => false, ); let pid: number | undefined; - const absent = () => { - if (pid === undefined) return true; - try { - process.kill(pid, 0); - return false; - } catch (cause: unknown) { - if (cause instanceof Error && "code" in cause && cause.code === "ESRCH") - return true; - throw cause; - } - }; + const absent = async () => + pid === undefined ? true : processHasStopped(pid); try { await expect.poll(() => fileExists(ready)).toBe(true); pid = Number(await readFile(ready, "utf8")); caller.abort({ caller: "readiness cancellation" }); const outcome = await pending; expect(outcome).toMatchObject({ error: { cause: caller.signal.reason } }); - // A zero-signal observation is conservative under PID reuse and never - // grants cleanup authority; only the fixture's release file requests exit. - expect(absent()).toBe(true); + // Process observation never grants cleanup authority; only the fixture's + // release file requests exit. + expect(await absent()).toBe(true); } finally { caller.abort(); await writeFile(release, "release"); diff --git a/tests/boundary/binaryDiagnostics/pwntoolsLayoutProvider.test.ts b/tests/boundary/binaryDiagnostics/pwntoolsLayoutProvider.test.ts index 8f99aec5783..c64e45ef65c 100644 --- a/tests/boundary/binaryDiagnostics/pwntoolsLayoutProvider.test.ts +++ b/tests/boundary/binaryDiagnostics/pwntoolsLayoutProvider.test.ts @@ -10,6 +10,7 @@ import { PwntoolsLayoutProvider } from "../../../src/native/pwntools/PwntoolsLay import { PWNTOOLS_PROVIDER_IDENTITY } from "../../../src/native/pwntools/PwntoolsProviderIdentity.js"; import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js"; import { waitForProviderProcessReady } from "../../fixtures/providerProcess.js"; +import { processHasStopped } from "../../support/process/observePosixProcess.js"; import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js"; import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js"; import { binaryLayoutFixture } from "../../fixtures/binaryDiagnostics/layout.js"; @@ -418,9 +419,7 @@ it.runIf(!unsupportedHost).each(["cancelled", "output-limit", "process"])( }); if (pid === undefined) throw new Error("Decoder was not acquired"); const acquiredPid = pid; - expect(() => process.kill(acquiredPid, 0)).toThrow( - expect.objectContaining({ code: "ESRCH" }), - ); + expect(await processHasStopped(acquiredPid)).toBe(true); await expect(access(ownedPath)).rejects.toMatchObject({ code: "ENOENT" }); expect(await readFile(path, "utf8")).toBe("source-owned-seam-bytes"); }, diff --git a/tests/boundary/captures/captureDescriptorCleanup.test.ts b/tests/boundary/captures/captureDescriptorCleanup.test.ts index 9366ab8a670..9120cf79d62 100644 --- a/tests/boundary/captures/captureDescriptorCleanup.test.ts +++ b/tests/boundary/captures/captureDescriptorCleanup.test.ts @@ -1,16 +1,11 @@ -import { - descriptorFailurePath, - expectRetainedDescriptor, -} from "../../fixtures/descriptorCloseFailure.js"; -import { expect, it, onTestFinished, vi } from "vitest"; -import { lstat, writeFile } from "node:fs/promises"; import type { FileHandle } from "node:fs/promises"; -import { join } from "node:path"; +import { it, vi } from "vitest"; import { TsharkCaptureProvider } from "../../../src/captures/TsharkCaptureProvider.js"; import { PacketCaptureService } from "../../../src/application/captures/PacketCaptureService.js"; -import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js"; -import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js"; -import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { + DESCRIPTOR_CLEANUP_MEMBERS, + runCliToolDescriptorCleanupScenario, +} from "../../fixtures/cliToolDescriptorCleanup.js"; const cleanup = vi.hoisted(() => ({ path: "", @@ -24,127 +19,34 @@ vi.mock("node:fs/promises", async (importOriginal) => { return withDescriptorCloseFailure(filesystem, cleanup); }); -it - .runIf(process.platform === "linux") - .each([ - "capture", - "tool", - "limiter", - "kernel", - "field-tool", - "field-limiter", - "field-kernel", - ])( +it.runIf(process.platform === "linux").each(DESCRIPTOR_CLEANUP_MEMBERS)( "retains failed %s descriptors and retries them before further acquisition and shutdown", async (member) => { - const directory = await createTestTempDirectory("rea-capture-descriptor-"); - const path = join(directory, "recording.pcap"); - const command = join(directory, "tshark.mjs"); - const limiter = join(directory, "limiter"); - await writeFile(path, "recording bytes"); - await writeFile(limiter, "limiter", { mode: 0o700 }); - await writeFile( - command, - `if(process.argv.includes('--version'))console.log('TShark (Wireshark) 4.0.17');else console.log('[{"_source":{"layers":{"frame.number":["1"]}}}]');`, - { mode: 0o700 }, - ); - let launches = 0; - let runtimeRoot: PrivateRuntimeRoot | undefined; - const provider = new TsharkCaptureProvider( - { - ...process.env, - REA_TSHARK_COMMAND: command, - REA_TSHARK_PRLIMIT_COMMAND: limiter, - }, - (input) => { - launches += 1; - return spawnOwnedProviderProcess({ - ...input, - command: process.execPath, - arguments: [command, ...input.arguments], - expectedCommand: process.execPath, - }); - }, - async () => { - runtimeRoot = await PrivateRuntimeRoot.create({ parent: directory }); - return runtimeRoot; - }, - ); - const discovery = member.startsWith("field-"); - const resource = discovery ? member.slice(6) : member; - const operation = discovery - ? "inspect_packet_fields" - : "inspect_packet_capture"; - cleanup.path = descriptorFailurePath(resource, { - capture: path, - tool: command, - limiter, - }); - cleanup.denied = true; - cleanup.handles = []; - onTestFinished(async () => { - cleanup.denied = false; - await provider.close(); - for (const handle of cleanup.handles) await handle.close(); - cleanup.path = ""; - }); - const service = new PacketCaptureService(provider); - const first = discovery - ? await service.inspectFields({ query: "usb" }) - : await service.inspect({ path, fields: ["frame.number"] }); - expectRetainedDescriptor( - first, + await runCliToolDescriptorCleanupScenario({ cleanup, - operation, - runtimeRoot === undefined ? [] : [runtimeRoot.path], - ); - if (first.ok) throw new Error("Expected retained descriptor cleanup"); - const originatingCause = first.error.cause; - if (resource === "capture") { - expect(runtimeRoot).toBeDefined(); - await expect(lstat(runtimeRoot!.path)).resolves.toBeDefined(); - } - const launchCount = launches; - expect( - await service.inspect({ path, fields: ["frame.number"] }), - ).toMatchObject({ - ok: false, - error: { cleanupIncomplete: true, operation }, + member, + tempPrefix: "rea-capture-descriptor-", + recordingFileName: "recording.pcap", + commandFileName: "tshark.mjs", + commandSource: `if(process.argv.includes('--version'))console.log('TShark (Wireshark) 4.0.17');else console.log('[{"_source":{"layers":{"frame.number":["1"]}}}]');`, + commandEnvKey: "REA_TSHARK_COMMAND", + limiterEnvKey: "REA_TSHARK_PRLIMIT_COMMAND", + primaryOperation: "inspect_packet_capture", + discoveryOperation: "inspect_packet_fields", + createFixture: ({ env, spawn, createRuntimeRoot, recordingPath }) => { + const provider = new TsharkCaptureProvider( + env, + spawn, + createRuntimeRoot, + ); + const service = new PacketCaptureService(provider); + return { + close: () => provider.close(), + runPrimary: () => + service.inspect({ path: recordingPath, fields: ["frame.number"] }), + runDiscovery: () => service.inspectFields({ query: "usb" }), + }; + }, }); - expect(cleanup.handles).toHaveLength(1); - expect(launches).toBe(launchCount); - let closingOperation = operation; - if (discovery) { - cleanup.denied = false; - const recovered = await service.inspect({ - path, - fields: ["frame.number"], - }); - expect(recovered.ok).toBe(true); - expect(cleanup.handles.every((handle) => handle.fd === -1)).toBe(true); - expect(launches).toBeGreaterThan(launchCount); - cleanup.denied = true; - expect( - await service.inspect({ path, fields: ["frame.number"] }), - ).toMatchObject({ - ok: false, - error: { cleanupIncomplete: true, operation: "inspect_packet_capture" }, - }); - expect(cleanup.handles.at(-1)?.fd).toBeGreaterThanOrEqual(0); - closingOperation = "inspect_packet_capture"; - } - await expect(provider.close()).rejects.toMatchObject({ - cleanupIncomplete: true, - operation: closingOperation, - }); - cleanup.denied = false; - await provider.close(); - expect(first.error.cleanupIncomplete).toBe(false); - expect(first.error.cause).toBe(originatingCause); - if (runtimeRoot !== undefined) - await expect(lstat(runtimeRoot.path)).rejects.toMatchObject({ - code: "ENOENT", - }); - expect(cleanup.handles.every((handle) => handle.fd === -1)).toBe(true); }, ); diff --git a/tests/boundary/cli/debuggerOneShotExit.test.ts b/tests/boundary/cli/debuggerOneShotExit.test.ts index f13ab3f3e2c..7be618558b0 100644 --- a/tests/boundary/cli/debuggerOneShotExit.test.ts +++ b/tests/boundary/cli/debuggerOneShotExit.test.ts @@ -6,6 +6,10 @@ import { describe, expect, onTestFinished } from "vitest"; import { MCP_SHUTDOWN_FAILED } from "../../../src/main/messages.js"; import { retainedDebuggerRemediation } from "../../../src/process/ownedDebuggerCleanupError.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { + expectProcessRunning, + processHasStopped, +} from "../../support/process/observePosixProcess.js"; import { cliProcessEnvironment, cliTest, @@ -146,15 +150,6 @@ type FakeMode = "clean" | "malformed" | "unanswered"; const EXIT_DEADLINE_MS = 20_000; -const isAlive = (pid: number): boolean => { - try { - process.kill(pid, 0); - return true; - } catch { - return false; - } -}; - /** Launch the compiled CLI against one fake debugger, on any POSIX host. */ const prepareLaunch = async ( name: DebuggerName, @@ -183,7 +178,8 @@ const prepareLaunch = async ( }; onTestFinished(async () => { const pid = await debuggerPid().catch(() => undefined); - if (pid !== undefined && isAlive(pid)) process.kill(pid, "SIGKILL"); + if (pid !== undefined && !(await processHasStopped(pid))) + process.kill(pid, "SIGKILL"); expect( (await notes()).filter((note) => note.startsWith("unmodeled ")), ).toEqual([]); @@ -307,7 +303,7 @@ describe.skipIf(process.platform === "win32")( // closes its command stream; that is the only thing it sees from REA. await expect.poll(launch.notes).toContain("stdin-end"); expect(await launch.notes()).not.toContain("sigterm"); - expect(isAlive(pid)).toBe(true); + await expectProcessRunning(pid); }, ); @@ -330,7 +326,7 @@ describe.skipIf(process.platform === "win32")( }); expect(result.stdout).not.toContain("retained_debugger_pids"); const pid = await launch.debuggerPid(); - await expect.poll(() => isAlive(pid)).toBe(false); + await expect.poll(() => processHasStopped(pid)).toBe(true); }, ); @@ -361,7 +357,7 @@ describe.skipIf(process.platform === "win32")( pid, ); expect(await launch.notes()).not.toContain("sigterm"); - expect(isAlive(pid)).toBe(true); + await expectProcessRunning(pid); }, ); @@ -406,7 +402,7 @@ describe.skipIf(process.platform === "win32")( expect.objectContaining({ msg, retained_debugger_pids: [pid] }), ); expect(await launch.notes()).not.toContain("sigterm"); - expect(isAlive(pid)).toBe(true); + await expectProcessRunning(pid); }, ); }, diff --git a/tests/boundary/cli/doctorCancellation.test.ts b/tests/boundary/cli/doctorCancellation.test.ts index d3e53c690e8..5baf58890cd 100644 --- a/tests/boundary/cli/doctorCancellation.test.ts +++ b/tests/boundary/cli/doctorCancellation.test.ts @@ -3,6 +3,7 @@ import { mkdir, readFile, writeFile } from "node:fs/promises"; import { join, resolve } from "node:path"; import { expect } from "vitest"; import { cliTest } from "../../support/cli/cliFixture.js"; +import { processHasStopped } from "../../support/process/observePosixProcess.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { writeJadxJarInventory } from "../../fixtures/android/jadxJar.js"; import { observeOwnedProcessGroups } from "../../../src/process/ProcessOwnershipObservation.js"; @@ -139,9 +140,7 @@ setTimeout(() => process.exit(99), 20000); }); } else { // Do not invent a group owner from the probe PID. - expect(() => process.kill(observed.pid, 0)).toThrowError( - expect.objectContaining({ code: "ESRCH" }), - ); + expect(await processHasStopped(observed.pid)).toBe(true); } expect(result, stderr).toEqual({ code: expected, signal: null }); } finally { diff --git a/tests/boundary/evm/evmCleanupRetry.test.ts b/tests/boundary/evm/evmCleanupRetry.test.ts index 2dfea5b9b3d..218d209e9fa 100644 --- a/tests/boundary/evm/evmCleanupRetry.test.ts +++ b/tests/boundary/evm/evmCleanupRetry.test.ts @@ -4,6 +4,10 @@ import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterAll, beforeAll, expect, it, vi } from "vitest"; +import { + processHasStopped, + expectProcessRunning, +} from "../../support/process/observePosixProcess.js"; const LIMITS_PATH = "/proc/self/limits"; const limitReport = [ @@ -64,7 +68,6 @@ import { waitForProviderProcessReady } from "../../fixtures/providerProcess.js"; import { EvmInterfaceService } from "../../../src/application/evm/EvmInterfaceService.js"; import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; -import { expectProcessRunning } from "../../support/process/observePosixProcess.js"; let limitsWorkspace = ""; beforeAll(async () => { @@ -657,9 +660,7 @@ it("preserves an active cancellation through denied owned-group cleanup and late }); expect(cleanupAttempts).toBe(2); expect(original.cleanupResources).toEqual([rootPath]); - expect(() => process.kill(ownedPid, 0)).toThrow( - expect.objectContaining({ code: "ESRCH" }), - ); + expect(await processHasStopped(ownedPid)).toBe(true); await provider.close(); expect(original.cleanupIncomplete).toBe(false); diff --git a/tests/boundary/evm/evmoleInterfaceProvider.test.ts b/tests/boundary/evm/evmoleInterfaceProvider.test.ts index 701af4be716..47da3643892 100644 --- a/tests/boundary/evm/evmoleInterfaceProvider.test.ts +++ b/tests/boundary/evm/evmoleInterfaceProvider.test.ts @@ -11,6 +11,7 @@ import { EvmoleInterfaceProvider } from "../../../src/evm/EvmoleInterfaceProvide import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js"; import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js"; import { waitForProviderProcessReady } from "../../fixtures/providerProcess.js"; +import { processHasStopped } from "../../support/process/observePosixProcess.js"; import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js"; import { parseEvidence } from "../../../src/domain/evidence.js"; import { EvmInterfaceService } from "../../../src/application/evm/EvmInterfaceService.js"; @@ -668,9 +669,7 @@ it.runIf(!unsupportedHost).each(["cancelled", "output-limit", "process"])( }); if (pid === undefined) throw new Error("worker not acquired"); const acquiredPid = pid; - expect(() => process.kill(acquiredPid, 0)).toThrow( - expect.objectContaining({ code: "ESRCH" }), - ); + expect(await processHasStopped(acquiredPid)).toBe(true); await expect(access(ownedRoot)).rejects.toMatchObject({ code: "ENOENT" }); }, ); diff --git a/tests/boundary/filesystem/nativePascalVerifier.test.ts b/tests/boundary/filesystem/nativePascalVerifier.test.ts index b04a9d6eb1b..92fbafaba9c 100644 --- a/tests/boundary/filesystem/nativePascalVerifier.test.ts +++ b/tests/boundary/filesystem/nativePascalVerifier.test.ts @@ -12,6 +12,7 @@ import { basename, join } from "node:path"; import { expect, it } from "vitest"; import { createCanonicalTemporaryDirectory } from "../../../scripts/lib/canonical-temporary-directory.mjs"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { processHasStopped } from "../../support/process/observePosixProcess.js"; it("uses the canonical spelling for a verifier directory allocated through a symlink", async () => { const root = await createTestTempDirectory("rea-pascal-verifier-path-"); @@ -104,10 +105,7 @@ it.skipIf(process.platform !== "darwin")( verifier.once("close", (code, signal) => resolve({ code, signal })); }); expect(result).toEqual({ code: 143, signal: null }); - for (const pid of pids) - expect(() => process.kill(pid, 0)).toThrow( - expect.objectContaining({ code: "ESRCH" }), - ); + for (const pid of pids) expect(await processHasStopped(pid)).toBe(true); expect( (await readdir(root)).filter((name) => name.startsWith("rea-pascal-calls-"), diff --git a/tests/boundary/filesystem/referenceSourceMetadataCleanup.test.ts b/tests/boundary/filesystem/referenceSourceMetadataCleanup.test.ts index afa72cc3c0b..8cbfbf3553b 100644 --- a/tests/boundary/filesystem/referenceSourceMetadataCleanup.test.ts +++ b/tests/boundary/filesystem/referenceSourceMetadataCleanup.test.ts @@ -422,6 +422,7 @@ it.each([ ).toBe(true); allowClose = true; await resources.close(); + expect(handles.length).toBeGreaterThan(0); expect(handles.every((handle) => handle.fd === -1)).toBe(true); expect(resources.hasPending).toBe(false); } finally { diff --git a/tests/boundary/filesystem/setupClientConfigCleanupOwnership.test.ts b/tests/boundary/filesystem/setupClientConfigCleanupOwnership.test.ts index 1341736ab27..374ef2dc770 100644 --- a/tests/boundary/filesystem/setupClientConfigCleanupOwnership.test.ts +++ b/tests/boundary/filesystem/setupClientConfigCleanupOwnership.test.ts @@ -1131,6 +1131,7 @@ it("keeps a supplied maintenance scope responsible for a refresh-check read whos released = true; await resources.close(); expect(resources.hasPending).toBe(false); + expect(closeAttempts.length).toBeGreaterThan(0); expect(closeAttempts.every((handle) => handle.fd === -1)).toBe(true); expect(execute).not.toHaveBeenCalled(); } finally { diff --git a/tests/boundary/mcp/artifactMcp.test.ts b/tests/boundary/mcp/artifactMcp.test.ts index f2f82880f83..4a9be1e5521 100644 --- a/tests/boundary/mcp/artifactMcp.test.ts +++ b/tests/boundary/mcp/artifactMcp.test.ts @@ -1306,7 +1306,7 @@ it("discovers artifact target prerequisites and preserves typed MCP refusals", a error: { code: "unsupported_target" }, }); } - await client.callTool({ name: "close_binary", arguments: {} }); + await callOk(client, "close_binary"); } await writeFile( join(contents, "state.plist"), @@ -1337,7 +1337,7 @@ it("discovers artifact target prerequisites and preserves typed MCP refusals", a arguments: { path: "Contents/state.plist" }, }); expect(inspected.isError, JSON.stringify(inspected)).not.toBe(true); - await client.callTool({ name: "close_binary", arguments: {} }); + await callOk(client, "close_binary"); } } finally { await mcp.close(); @@ -1556,7 +1556,7 @@ it("evaluates hypotheses for an unchanged artifact member the comparison omits f inventories.push( await inspectArtifactInventoryThroughMcp(client, archive), ); - await client.callTool({ name: "close_binary", arguments: {} }); + await callOk(client, "close_binary"); } const [left, right] = inventories; if (left === undefined || right === undefined) diff --git a/tests/boundary/mcp/buildComputerMcp.test.ts b/tests/boundary/mcp/buildComputerMcp.test.ts index 2b7d4c7c040..f724c4f2d36 100644 --- a/tests/boundary/mcp/buildComputerMcp.test.ts +++ b/tests/boundary/mcp/buildComputerMcp.test.ts @@ -182,10 +182,7 @@ it("renders a build bundle from a request with REA's payload and starts it", asy const { computer_id: computerId } = toolContract( "start_build_computer", ).outputSchema.parse(started.structuredContent); - await client.callTool({ - name: "close_build_computer", - arguments: { computer_id: computerId }, - }); + await callOk(client, "close_build_computer", { computer_id: computerId }); expect(computer.calls.map(({ name }) => name)).toEqual([ "computer_screenshot", ]); diff --git a/tests/boundary/mcp/buildWitnessMcp.test.ts b/tests/boundary/mcp/buildWitnessMcp.test.ts index 3c1e524107f..588ae5caf56 100644 --- a/tests/boundary/mcp/buildWitnessMcp.test.ts +++ b/tests/boundary/mcp/buildWitnessMcp.test.ts @@ -551,10 +551,11 @@ it("takes the after_reset stage after a reset whose screenshot the computer refu const { app, check, client, computer, id } = witness; await throughNearMiss(witness); computer.refuseNext("computer_screenshot", "no display to capture"); - await client.callTool({ + const reset = await client.callTool({ name: "act_on_build_computer", arguments: { computer_id: id, action: "reset", screenshot: true }, }); + expect(reset.isError, JSON.stringify(reset)).not.toBe(true); expect(app.state).toEqual(app.seed); const checked = await check({ stage: "after_reset" }); expect(checked.isError, JSON.stringify(checked)).not.toBe(true); diff --git a/tests/boundary/mcp/commandObservationViews.test.ts b/tests/boundary/mcp/commandObservationViews.test.ts index d63831168cf..f311a680138 100644 --- a/tests/boundary/mcp/commandObservationViews.test.ts +++ b/tests/boundary/mcp/commandObservationViews.test.ts @@ -18,6 +18,7 @@ import { TestReverseEngineeringService } from "../../support/reverseEngineeringS import { ownedOutput } from "../../support/reverseEngineeringCompositionFixtures.js"; import { advertisedMcpToolSchemas } from "../../fixtures/advertisedMcpTool.js"; import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js"; +import { callOk } from "../../support/mcp/toolResult.js"; const sessionId = "00000000-0000-4000-8000-000000000001"; const capture = { @@ -161,10 +162,7 @@ it("delivers ordered GDB records once and queries their retained parent after cl expect(selected.normalized_result).not.toHaveProperty("summary.console"); expect(selected.normalized_result).not.toHaveProperty("summary.target"); expect(selected.normalized_result).not.toHaveProperty("summary.log"); - await client.callTool({ - name: "close_gdb_session", - arguments: { session_id: sessionId }, - }); + await callOk(client, "close_gdb_session", { session_id: sessionId }); const queried = await client.callTool( { name: "inspect_analysis_view", diff --git a/tests/boundary/mcp/deferredRuntime.test.ts b/tests/boundary/mcp/deferredRuntime.test.ts index 2a92a03070a..7fd84089acc 100644 --- a/tests/boundary/mcp/deferredRuntime.test.ts +++ b/tests/boundary/mcp/deferredRuntime.test.ts @@ -20,6 +20,7 @@ import { removeTestWorkspace, } from "../../support/workspace/workspaceFixture.js"; import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js"; +import { callOk } from "../../support/mcp/toolResult.js"; import { PROMPT_CONTRACTS } from "../../../src/contracts/promptContracts.js"; import { toolContract } from "../../../src/contracts/toolContracts.js"; import { evidenceSchema } from "../../../src/domain/evidence.js"; @@ -331,10 +332,7 @@ it.each([ let discovery = await client.listTools(); await client.listPrompts(); if (environment.REA_MCP_TOOL_CATALOG_PROFILE === "hot-cold") { - await client.callTool({ - name: "discover_tools", - arguments: { names: ["list_unknowns"] }, - }); + await callOk(client, "discover_tools", { names: ["list_unknowns"] }); discovery = await client.listTools(); } expect(await loadedModules()).toEqual( diff --git a/tests/boundary/mcp/enhancedTools.04-uses-complete-inventories-inline.test.ts b/tests/boundary/mcp/enhancedTools.04-uses-complete-inventories-inline.test.ts index a803f607c51..fa37bc3f1b4 100644 --- a/tests/boundary/mcp/enhancedTools.04-uses-complete-inventories-inline.test.ts +++ b/tests/boundary/mcp/enhancedTools.04-uses-complete-inventories-inline.test.ts @@ -757,14 +757,16 @@ it("forwards max_input_bytes from the MCP tool to the binary metadata operation" ); }, }); - await client.callTool({ + const withLimit = await client.callTool({ name: "inspect_native_dispatch_metadata", arguments: { max_input_bytes: 134217728 }, }); - await client.callTool({ + expect(withLimit.isError).toBe(true); + const withDefault = await client.callTool({ name: "inspect_native_dispatch_metadata", arguments: {}, }); + expect(withDefault.isError).toBe(true); expect(received).toEqual([ { max_records: 5000, max_input_bytes: 134217728 }, { max_records: 5000 }, diff --git a/tests/boundary/mcp/officialTools.test.ts b/tests/boundary/mcp/officialTools.test.ts index c8c91f6f480..33ac05eaad4 100644 --- a/tests/boundary/mcp/officialTools.test.ts +++ b/tests/boundary/mcp/officialTools.test.ts @@ -1,4 +1,5 @@ import { connectFixtureClient } from "../../support/mcp/mcpFixture.js"; +import { callOk } from "../../support/mcp/toolResult.js"; import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; import { Ajv2020 } from "ajv/dist/2020.js"; import { afterEach, describe, expect, it } from "vitest"; @@ -142,14 +143,11 @@ describe("official tool input contracts", () => { const client = await connect({ execute: (name, arguments_) => { invocations.push({ name, arguments_ }); - return Promise.resolve(ok(null)); + return Promise.resolve(ok({})); }, }); const names = JSON.parse('{"0x1000":"entry","__proto__":"other"}'); - await client.callTool({ - name: "set_addresses_names", - arguments: { names }, - }); + await callOk(client, "set_addresses_names", { names }); expect(invocations).toEqual([ { name: "set_addresses_names", arguments_: { names } }, ]); @@ -176,7 +174,7 @@ describe("official tool input contracts", () => { const client = await connect({ execute: (name, arguments_) => { invocations.push({ name, arguments_ }); - return Promise.resolve(ok(null)); + return Promise.resolve(ok({})); }, }); const { tools } = await client.listTools(); diff --git a/tests/boundary/mcp/serverIdentity.test.ts b/tests/boundary/mcp/serverIdentity.test.ts index 7b0ae5b0aa8..5356c195d29 100644 --- a/tests/boundary/mcp/serverIdentity.test.ts +++ b/tests/boundary/mcp/serverIdentity.test.ts @@ -1,4 +1,5 @@ import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; +import { callOk } from "../../support/mcp/toolResult.js"; import { ok as resultOk } from "../../../src/domain/result.js"; import { mkdir, readFile, symlink, writeFile } from "node:fs/promises"; import { createHash } from "node:crypto"; @@ -366,7 +367,7 @@ describe("active-target availability over MCP", () => { inspect_artifact: "available", inspect_managed_artifact: "available", }); - await client.callTool({ name: "close_binary", arguments: {} }); + await callOk(client, "close_binary"); await openTarget(client, executable); const native = await readStatus(client); expect(activeTargetReasons(native)).toEqual({ @@ -375,7 +376,7 @@ describe("active-target availability over MCP", () => { inspect_managed_artifact: "available", }); expect(await client.listTools()).toEqual(listed); - await client.callTool({ name: "close_binary", arguments: {} }); + await callOk(client, "close_binary"); const closed = await readStatus(client); expect(activeTargetReasons(closed).inspect_macho).toBe("target_required"); for (const status of [artifact, native, closed]) diff --git a/tests/boundary/model/modelArtifact.test.ts b/tests/boundary/model/modelArtifact.test.ts index 4bfa87efdbc..c1df0ffdbc3 100644 --- a/tests/boundary/model/modelArtifact.test.ts +++ b/tests/boundary/model/modelArtifact.test.ts @@ -351,11 +351,9 @@ it("retains the absolute header budget for GGUF without allocating that extent", await file.truncate(MODEL_HEADER_BYTES + 9); const reader = new ModelHeaderReader(file, MODEL_HEADER_BYTES + 9); expect(() => reader.guarantee(MODEL_HEADER_BYTES)).not.toThrow(); - expect(() => reader.guarantee(MODEL_HEADER_BYTES + 1)).toThrow( - ParseFailureError, - ); try { reader.guarantee(MODEL_HEADER_BYTES + 1); + expect.unreachable("Expected a model header capacity failure"); } catch (cause) { expect(cause).toBeInstanceOf(ParseFailureError); if (!(cause instanceof ParseFailureError)) diff --git a/tests/boundary/native/pwndbgReplyFinalization.test.ts b/tests/boundary/native/pwndbgReplyFinalization.test.ts index c526e738eea..36d4e17f069 100644 --- a/tests/boundary/native/pwndbgReplyFinalization.test.ts +++ b/tests/boundary/native/pwndbgReplyFinalization.test.ts @@ -195,6 +195,7 @@ it.each([ expect(result.error.partialObservation).toEqual(completed); } } + expect(replyClose.handles.length).toBeGreaterThan(0); expect(replyClose.handles.every((handle) => handle.fd === -1)).toBe(true); }, ); @@ -250,6 +251,7 @@ it.each(["malformed JSON", "malformed UTF-8", "producer refusal"])( await selected.resources.close(); expect(error.cleanupIncomplete).toBe(false); expect(error.cleanupResources).toEqual([]); + expect(replyClose.handles.length).toBeGreaterThan(0); expect(replyClose.handles.every((handle) => handle.fd === -1)).toBe(true); }, ); diff --git a/tests/boundary/process/deepseekVerifierInterruption.test.ts b/tests/boundary/process/deepseekVerifierInterruption.test.ts index 61b5a38acb0..a8499526935 100644 --- a/tests/boundary/process/deepseekVerifierInterruption.test.ts +++ b/tests/boundary/process/deepseekVerifierInterruption.test.ts @@ -6,6 +6,10 @@ import { fileURLToPath } from "node:url"; import { expect } from "vitest"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { + expectProcessRunning, + processHasStopped, +} from "../../support/process/observePosixProcess.js"; import { waitForTestPidFile } from "../../support/process/pidFile.js"; import { processTest } from "../../support/process/processFixture.js"; import { runningTestDeadline } from "../../support/runningTestDeadline.js"; @@ -16,17 +20,6 @@ const verifier = fileURLToPath( const finalLine = '{"type":"final","text":"REA_CLIENT_COMPATIBILITY_OK"}\n'; -const alive = (pid: number) => { - try { - process.kill(pid, 0); - return true; - } catch (cause) { - if (cause instanceof Error && "code" in cause && cause.code === "ESRCH") - return false; - throw cause; - } -}; - processTest .skipIf(process.platform === "win32") .for(["SIGINT", "SIGTERM"] as const)( @@ -89,13 +82,14 @@ if (process.argv.includes("--version")) { ); }), ]); - expect(alive(pid)).toBe(true); + await expectProcessRunning(pid); expect(child.kill(signal)).toBe(true); const status = await result; - expect(alive(pid), "owned client survived verifier interruption").toBe( - false, - ); + expect( + await processHasStopped(pid), + "owned client survived verifier interruption", + ).toBe(true); expect(status).toEqual({ code: 1, terminationSignal: null }); const receipt = JSON.parse(stdout); expect(receipt).toMatchObject({ diff --git a/tests/boundary/process/fridaBindingReadiness.test.ts b/tests/boundary/process/fridaBindingReadiness.test.ts index 41a4462467a..f0fc9676002 100644 --- a/tests/boundary/process/fridaBindingReadiness.test.ts +++ b/tests/boundary/process/fridaBindingReadiness.test.ts @@ -5,6 +5,7 @@ import { describe, expect, it } from "vitest"; import { UpdateCommandRunner } from "../../../src/application/UpdateCommandRunner.js"; import { fridaBindingReadiness } from "../../../src/frida/FridaBindingReadiness.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { processHasStopped } from "../../support/process/observePosixProcess.js"; const readinessFixture = async (source?: string) => { const root = await createTestTempDirectory("rea-frida-readiness-"); @@ -224,9 +225,7 @@ describe("Frida resolution and repair ownership", () => { const assertStopped = async (pidPath: string) => { const pid = Number(await readFile(pidPath, "utf8")); expect(Number.isSafeInteger(pid) && pid > 0).toBe(true); - expect(() => process.kill(pid, 0)).toThrow( - expect.objectContaining({ code: "ESRCH" }), - ); + expect(await processHasStopped(pid)).toBe(true); }; describe("Frida probe process failure diagnostics", () => { diff --git a/tests/boundary/process/http3VerifierNodeTests.test.ts b/tests/boundary/process/http3VerifierNodeTests.test.ts index 0e7be7fa6ee..543a1542d33 100644 --- a/tests/boundary/process/http3VerifierNodeTests.test.ts +++ b/tests/boundary/process/http3VerifierNodeTests.test.ts @@ -20,12 +20,11 @@ const runNodeTests = async (file: string): Promise => { it("runs HTTP/3 capture assertion regressions", async () => { await runNodeTests("scripts/lib/http3-capture-assertions.test.mjs"); -}, 60_000); +}); it.skipIf(process.platform === "win32")( "runs POSIX HTTP/3 lifecycle regressions", async () => { await runNodeTests("scripts/lib/http3-verifier-lifecycle.test.mjs"); }, - 60_000, ); diff --git a/tests/boundary/process/inspectorVerifierStartup.test.ts b/tests/boundary/process/inspectorVerifierStartup.test.ts index b4d35baff41..dd7cdac60c8 100644 --- a/tests/boundary/process/inspectorVerifierStartup.test.ts +++ b/tests/boundary/process/inspectorVerifierStartup.test.ts @@ -4,6 +4,7 @@ import { expect } from "vitest"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { processTest } from "../../support/process/processFixture.js"; +import { processHasStopped } from "../../support/process/observePosixProcess.js"; processTest( "refuses a silent Inspector startup and retires its exact child", @@ -69,8 +70,6 @@ globalThis.setTimeout = (callback, delay, ...args) => expect(await readFile(stopped, "utf8")).toBe("SIGTERM"); const pid = Number(await readFile(marker, "utf8")); expect(pid).toBeGreaterThan(0); - expect(() => process.kill(pid, 0)).toThrowError( - expect.objectContaining({ code: "ESRCH" }), - ); + expect(await processHasStopped(pid)).toBe(true); }, ); diff --git a/tests/boundary/process/jadxIntegration.test.ts b/tests/boundary/process/jadxIntegration.test.ts index e53f702aecf..de23639e8b0 100644 --- a/tests/boundary/process/jadxIntegration.test.ts +++ b/tests/boundary/process/jadxIntegration.test.ts @@ -3,6 +3,7 @@ import { canonicalOutputSchema } from "../../fixtures/canonicalOutputSchema.js"; import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js"; import { SdkErrorCode } from "@modelcontextprotocol/client"; import { packagedJadxBridgeIdentity } from "../../support/packagedJadxBridge.js"; +import { processGroupHasStopped } from "../../support/process/observePosixProcess.js"; import { ArtifactResourceScope } from "../../../src/resources/ArtifactResourceScope.js"; import { expect, it as test, onTestFinished, vi } from "vitest"; import { @@ -1140,10 +1141,7 @@ it("bounds each upstream call by the selected deadline instead of a fixed limit" await session.close(); } expect(pids).toHaveLength(1); - for (const pid of pids) - expect(() => process.kill(-pid, 0)).toThrowError( - expect.objectContaining({ code: "ESRCH" }), - ); + for (const pid of pids) expect(await processGroupHasStopped(pid)).toBe(true); }); it("reports missing explicit tools without trying to install or launch them", async () => { diff --git a/tests/boundary/process/jadxJavaLifecycle.test.ts b/tests/boundary/process/jadxJavaLifecycle.test.ts index 8bacc3ed68a..838f2da5d22 100644 --- a/tests/boundary/process/jadxJavaLifecycle.test.ts +++ b/tests/boundary/process/jadxJavaLifecycle.test.ts @@ -12,6 +12,7 @@ import { prepareProcessOwnershipInspection, } from "../../../src/process/ProcessOwnershipObservation.js"; import { createInspectionResources } from "../../fixtures/inspectionResources.js"; +import { processHasStopped } from "../../support/process/observePosixProcess.js"; import { writeFile, readFile, stat } from "node:fs/promises"; import { dirname, join } from "node:path"; import { createJadxProtocolFixture } from "../../fixtures/android/jadx.js"; @@ -380,9 +381,7 @@ setTimeout(() => process.exit(99), 10000); }); for (const pid of await pids()) { // Observation only; cleanup remains with each command's run identity. - expect(() => process.kill(pid, 0)).toThrowError( - expect.objectContaining({ code: "ESRCH" }), - ); + expect(await processHasStopped(pid)).toBe(true); } } finally { doctor.abort(); diff --git a/tests/boundary/process/ownedCommand.test.ts b/tests/boundary/process/ownedCommand.test.ts index f1df9b6c846..d3e05642f37 100644 --- a/tests/boundary/process/ownedCommand.test.ts +++ b/tests/boundary/process/ownedCommand.test.ts @@ -9,6 +9,10 @@ import { EventEmitter } from "node:events"; import { PassThrough, Writable } from "node:stream"; import { setTimeout as delay } from "node:timers/promises"; import { beforeAll, expect, it, vi } from "vitest"; +import { + processHasStopped, + expectProcessRunning, +} from "../../support/process/observePosixProcess.js"; import { OwnedCommandFailure, OwnedCommandStdoutBytes, @@ -30,7 +34,6 @@ import { liveProcesses } from "../../../src/process/ProcessOwnershipProcessTree. import { waitForProviderProcessReady } from "../../fixtures/providerProcess.js"; import { createDeferred } from "../../fixtures/binarySession.js"; import { phaseArrival, phaseGate } from "../../support/lifecycleHarness.js"; -import { expectProcessRunning } from "../../support/process/observePosixProcess.js"; const command = (script: string) => ({ command: process.execPath, @@ -693,9 +696,7 @@ it.each([5_000, null])( }); if (pid === undefined) throw new Error("Process was not acquired"); const acquiredPid = pid; - expect(() => process.kill(acquiredPid, 0)).toThrow( - expect.objectContaining({ code: "ESRCH" }), - ); + expect(await processHasStopped(acquiredPid)).toBe(true); }, ); diff --git a/tests/boundary/process/processCaptureProgress.test.ts b/tests/boundary/process/processCaptureProgress.test.ts index c33faf7d8fe..d45007034df 100644 --- a/tests/boundary/process/processCaptureProgress.test.ts +++ b/tests/boundary/process/processCaptureProgress.test.ts @@ -15,6 +15,7 @@ import { silentLogger } from "../../../src/logger.js"; import { createApplicationMcpHarness } from "../../fixtures/applicationMcpHarness.js"; import { createTestBinarySession } from "../../fixtures/binarySession.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { callOk } from "../../support/mcp/toolResult.js"; import { itWithCaptureCapability } from "./processCaptureCapability.js"; const PROGRESS_INTERVAL_MS = 100; @@ -585,7 +586,7 @@ itWithCaptureCapability( const cancelling = await connectProgressClient(true); // Prepare the SDK's full output-schema cache before timing capture control. - await cancelling.client.callTool({ name: "binary_session", arguments: {} }); + await callOk(cancelling.client, "binary_session"); const controller = new AbortController(); const stall = setTimeout(() => controller.abort(), 5_000); onTestFinished(() => clearTimeout(stall)); diff --git a/tests/boundary/process/processCli.test.ts b/tests/boundary/process/processCli.test.ts index 2d0d980dfd4..921f9183eb4 100644 --- a/tests/boundary/process/processCli.test.ts +++ b/tests/boundary/process/processCli.test.ts @@ -9,6 +9,7 @@ import { promisify } from "node:util"; import { describe, expect, it } from "vitest"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { expectProcessRunning } from "../../support/process/observePosixProcess.js"; import { cliTest } from "../../support/cli/cliFixture.js"; import { captureProcessScenarioFile } from "../../../src/application/process/ProcessCli.js"; @@ -156,9 +157,7 @@ describe("process CLI cleanup errors", () => { }); const targetPid = Number(await readFile(marker, "utf8")); expect(Number.isSafeInteger(targetPid) && targetPid > 0).toBe(true); - expect(process.kill(targetPid, 0), "the target remains alive").toBe( - true, - ); + await expectProcessRunning(targetPid); expect(result.exitCode, result.stdout || result.stderr).toBe(1); const retained = (await readdir(root)).filter((name) => /^rea-process-(?!token-)/u.test(name), diff --git a/tests/boundary/providers/RizinDebugSessionInferiorStdin.test.ts b/tests/boundary/providers/RizinDebugSessionInferiorStdin.test.ts index 1b320c84e41..c49664b94e6 100644 --- a/tests/boundary/providers/RizinDebugSessionInferiorStdin.test.ts +++ b/tests/boundary/providers/RizinDebugSessionInferiorStdin.test.ts @@ -1,4 +1,5 @@ import { createCommandCli } from "../../support/cli/commandCli.js"; +import { expectProcessRunning } from "../../support/process/observePosixProcess.js"; import { cliCommand } from "../../../src/cli/commandRegistry.js"; import { execFileSync, type ChildProcess } from "node:child_process"; import { rizinDebugMcpServer } from "../../fixtures/debuggerMcp.js"; @@ -272,7 +273,7 @@ const expectRunningOnTerminal = async ( pid: number, terminal: Terminal, ): Promise => { - expect(() => process.kill(pid, 0)).not.toThrow(); + await expectProcessRunning(pid); const [stdin, selected] = await Promise.all([ stat(`/proc/${String(pid)}/fd/0`), stat(terminal.path), diff --git a/tests/boundary/providers/RizinInferiorTty.test.ts b/tests/boundary/providers/RizinInferiorTty.test.ts index 467510f94ab..32b2356a9d3 100644 --- a/tests/boundary/providers/RizinInferiorTty.test.ts +++ b/tests/boundary/providers/RizinInferiorTty.test.ts @@ -5,6 +5,10 @@ import { join } from "node:path"; import { spawn } from "@lydell/node-pty"; import { afterEach, expect, it } from "vitest"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { + expectProcessRunning, + waitForPosixProcessStopped, +} from "../../support/process/observePosixProcess.js"; import { assertRizinProcessStartTimeStable, @@ -16,7 +20,6 @@ import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess. import { rizinTestInferiorTty } from "./RizinTestInferiorTty.js"; import { createInjectedProcess } from "./RizinDebugSessionCoverage.fixtures.js"; import { waitForTestPidFile } from "../../support/process/pidFile.js"; -import { waitForPosixProcessStopped } from "../../support/process/observePosixProcess.js"; let terminal: ReturnType | undefined; let manager: RizinDebugSessionManager | undefined; @@ -169,7 +172,7 @@ it.skipIf(process.platform !== "linux")( await readFile(join(testDirectory!, "detach-readback"), "utf8"), ).toBe("o- 3"); expect(inferiorPid).toBeDefined(); - expect(() => process.kill(inferiorPid!, 0)).not.toThrow(); + await expectProcessRunning(inferiorPid); const stat = await readFile(`/proc/${inferiorPid!}/stat`, "utf8"); const commandEnd = stat.lastIndexOf(") "); expect(commandEnd).toBeGreaterThan(0); @@ -310,7 +313,7 @@ it.skipIf(process.platform !== "linux")( await waitForPosixProcessStopped(providerPid!); // The target was never signalled: it keeps running after owned cleanup. expect(inferiorPid).toBeDefined(); - expect(() => process.kill(inferiorPid!, 0)).not.toThrow(); + await expectProcessRunning(inferiorPid); const stat = await readFile(`/proc/${inferiorPid!}/stat`, "utf8"); const commandEnd = stat.lastIndexOf(") "); expect(commandEnd).toBeGreaterThan(0); @@ -378,7 +381,7 @@ it.skipIf( const closed = await closing; expect(closed.ok, closed.ok ? "" : closed.error.message).toBe(true); inferiorPid = await waitForTestPidFile(pidPath, 5_000); - expect(() => process.kill(inferiorPid!, 0)).not.toThrow(); + await expectProcessRunning(inferiorPid); await writeFile(releasePath, "release after close"); const outputDeadline = Date.now() + 3_000; while ( @@ -389,7 +392,7 @@ it.skipIf( await new Promise((resolveDelay) => setTimeout(resolveDelay, 25)); expect(terminalOutput).toContain("REA_RIZIN_STDOUT_MARKER"); expect(terminalOutput).toContain("REA_RIZIN_STDERR_MARKER"); - expect(() => process.kill(inferiorPid!, 0)).not.toThrow(); + await expectProcessRunning(inferiorPid); }, ); diff --git a/tests/boundary/providers/adb/adbServerLifetime.test.ts b/tests/boundary/providers/adb/adbServerLifetime.test.ts index e55ed6e2a1f..de1ed23a43e 100644 --- a/tests/boundary/providers/adb/adbServerLifetime.test.ts +++ b/tests/boundary/providers/adb/adbServerLifetime.test.ts @@ -4,19 +4,14 @@ import { expect, onTestFinished, test } from "vitest"; import { AdbProvider } from "../../../../src/adb/AdbProvider.js"; import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js"; +import { + expectProcessRunning, + processHasStopped, +} from "../../../support/process/observePosixProcess.js"; import { waitFor } from "../../../support/testWait.js"; const posix = test.skipIf(process.platform === "win32"); -const alive = (pid: number): boolean => { - try { - process.kill(pid, 0); - return true; - } catch { - return false; - } -}; - /** * A Node adb stand-in. `start-server` forks a detached server, as adb forks * its daemon into a new session, and records its PID. Device commands log @@ -103,9 +98,9 @@ posix( const server = Number(await readFile(join(root, "server.pid"), "utf8")); // The device command's owned cleanup has finished; the server REA // started is an external shared service and keeps running. - expect(alive(server)).toBe(true); + await expectProcessRunning(server); await provider.close(); - expect(alive(server)).toBe(true); + await expectProcessRunning(server); }, ); @@ -120,7 +115,7 @@ posix( const replacement = Number( await readFile(join(root, "replacement-server.pid"), "utf8"), ); - expect(alive(replacement)).toBe(true); + await expectProcessRunning(replacement); }, ); @@ -135,7 +130,9 @@ posix( const descendant = Number( await readFile(join(root, "descendant.pid"), "utf8"), ); - await waitFor(() => expect(alive(descendant)).toBe(false)); + await waitFor(async () => + expect(await processHasStopped(descendant)).toBe(true), + ); }, ); diff --git a/tests/boundary/providers/ghidra/ghidraBridgeHelpers.test.ts b/tests/boundary/providers/ghidra/ghidraBridgeHelpers.test.ts index 0c5a1987409..be494c13a25 100644 --- a/tests/boundary/providers/ghidra/ghidraBridgeHelpers.test.ts +++ b/tests/boundary/providers/ghidra/ghidraBridgeHelpers.test.ts @@ -37,7 +37,7 @@ beforeAll(async () => { if (jdk === undefined) return; workspace = await createTestWorkspace("rea-ghidra-bridge-helpers-"); probe = await compileBridgeProbe(jdk, workspace.root); -}, 60_000); +}); afterAll(async () => { if (workspace !== undefined) { diff --git a/tests/boundary/providers/ghidra/ghidraCheckpointLifecycle.test.ts b/tests/boundary/providers/ghidra/ghidraCheckpointLifecycle.test.ts index 3b2bff2dfaf..fad632a0911 100644 --- a/tests/boundary/providers/ghidra/ghidraCheckpointLifecycle.test.ts +++ b/tests/boundary/providers/ghidra/ghidraCheckpointLifecycle.test.ts @@ -838,10 +838,14 @@ it.skipIf(process.platform === "win32")( expect((await f.client.start()).ok).toBe(true); const manifestPath = join(f.selection.directory, "current.json"); const before = await readFile(manifestPath, "utf8"); - await f.client.callTool("set_address_name", { - address: "0x1000", - name: "changed", - }); + expect( + ( + await f.client.callTool("set_address_name", { + address: "0x1000", + name: "changed", + }) + ).ok, + ).toBe(true); const actual = await vi.importActual( "node:fs/promises", @@ -993,10 +997,14 @@ it.skipIf(process.platform === "win32")( async () => { const f = await fixture("checkpoint_hold_close_hang_tool"); expect((await f.client.start()).ok).toBe(true); - await f.client.callTool("set_address_name", { - address: "0x1000", - name: "changed", - }); + expect( + ( + await f.client.callTool("set_address_name", { + address: "0x1000", + name: "changed", + }) + ).ok, + ).toBe(true); const controller = new AbortController(); const active = f.client.callTool( "list_documents", diff --git a/tests/boundary/providers/kuna/kunaDoctor.test.ts b/tests/boundary/providers/kuna/kunaDoctor.test.ts index 25d273a8e21..9865654df59 100644 --- a/tests/boundary/providers/kuna/kunaDoctor.test.ts +++ b/tests/boundary/providers/kuna/kunaDoctor.test.ts @@ -12,6 +12,7 @@ import { expect, it as test, vi } from "vitest"; import { inspectKunaProviderOwned as inspectKunaProvider } from "./kunaResourceScope.js"; import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js"; +import { processHasStopped } from "../../../support/process/observePosixProcess.js"; import { fakeKunaCalls, writeFakeKuna } from "./fakeKuna.js"; import { createSystemDoctorHost } from "../../../../src/doctorRuntime.js"; import { runDoctorOwned } from "../../../../src/application/Doctor.js"; @@ -376,9 +377,7 @@ it.each(["caller", "host"] as const)( source === "caller" ? reason : OwnerCancellation.startupOwnerClosed, ); // Cancellation only settles once execFile has reaped its direct child. - expect(() => process.kill(probe.pid, 0)).toThrowError( - expect.objectContaining({ code: "ESRCH" }), - ); + expect(await processHasStopped(probe.pid)).toBe(true); await closing; expect(await fakeKunaCalls(kuna)).toHaveLength(1); } finally { diff --git a/tests/boundary/providers/kuna/kunaHashOwnerPropagation.test.ts b/tests/boundary/providers/kuna/kunaHashOwnerPropagation.test.ts index e37e883ab2c..2e911ecf465 100644 --- a/tests/boundary/providers/kuna/kunaHashOwnerPropagation.test.ts +++ b/tests/boundary/providers/kuna/kunaHashOwnerPropagation.test.ts @@ -1102,6 +1102,7 @@ it.skipIf(process.platform === "win32").each( await resources.close(); if (client !== undefined) expect((await client.close()).ok).toBe(true); expect(failure?.cleanupIncomplete ?? false).toBe(false); + expect(injected.handles.length).toBeGreaterThan(0); expect(injected.handles.every((handle) => handle.fd < 0)).toBe(true); } }, diff --git a/tests/boundary/providers/kuna/kunaInstallation.test.ts b/tests/boundary/providers/kuna/kunaInstallation.test.ts index 97795bcb4aa..879ce089827 100644 --- a/tests/boundary/providers/kuna/kunaInstallation.test.ts +++ b/tests/boundary/providers/kuna/kunaInstallation.test.ts @@ -20,6 +20,7 @@ import { } from "../../../../src/kuna/KunaConfiguration.js"; import { inspectKunaInstallationOwned as inspectKunaInstallation } from "./kunaResourceScope.js"; import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js"; +import { processHasStopped } from "../../../support/process/observePosixProcess.js"; import { fakeKunaCalls, writeFakeKuna } from "./fakeKuna.js"; import { makeLauncher, ownedGroupCleanup } from "./kunaVersionProbeProcess.js"; @@ -315,10 +316,9 @@ it("stops a version probe that ignores SIGTERM instead of waiting on it", async }); // The stop escalated past the ignored SIGTERM; waiting on the probe instead // would hang until the test deadline names it. - const pid = (await fakeKunaCalls(kuna))[0]?.pid ?? 0; - expect(() => process.kill(pid, 0)).toThrow( - expect.objectContaining({ code: "ESRCH" }), - ); + const pid = (await fakeKunaCalls(kuna))[0]?.pid; + expect(pid).toBeTypeOf("number"); + expect(await processHasStopped(pid!)).toBe(true); }); it("keeps a version deadline ahead of cancellation during its joined stop", async () => { diff --git a/tests/boundary/providers/kuna/kunaInstallationCancellation.test.ts b/tests/boundary/providers/kuna/kunaInstallationCancellation.test.ts index 8fda08e5303..60ed00ac683 100644 --- a/tests/boundary/providers/kuna/kunaInstallationCancellation.test.ts +++ b/tests/boundary/providers/kuna/kunaInstallationCancellation.test.ts @@ -2,6 +2,7 @@ import { writeFile } from "node:fs/promises"; import { join } from "node:path"; import { expect, it as test } from "vitest"; import { ProviderCleanupError } from "../../../../src/domain/providerCleanupError.js"; +import { processHasStopped } from "../../../support/process/observePosixProcess.js"; import { fakeKunaCalls, setFakeKunaBehavior } from "./fakeKuna.js"; import { session } from "./kunaSessionFixture.js"; @@ -32,16 +33,6 @@ const gatedInstallation = async () => { }; }; -const gone = (pid: number) => { - try { - process.kill(pid, 0); - return false; - } catch (cause) { - if ((cause as NodeJS.ErrnoException).code !== "ESRCH") throw cause; - return true; - } -}; - it("lets one caller leave acquisition with its exact reason while a peer keeps the probe", async () => { const fixture = await gatedInstallation(); const client = fixture.open(); @@ -64,7 +55,7 @@ it("lets one caller leave acquisition with its exact reason while a peer keeps t cleanupIncomplete: false, }); expect(result.error.cause).toBe(reason); - expect(gone(probe.pid)).toBe(false); + expect(await processHasStopped(probe.pid)).toBe(false); await fixture.release(); expect((await peer).ok).toBe(true); expect((await fakeKunaCalls(fixture.kuna)).length).toBe(2); @@ -99,7 +90,7 @@ it.each([null, "caller stopped"])( cleanupIncomplete: false, }); expect(result.error.cause).toBe(reason); - expect(gone(probe.pid)).toBe(true); + expect(await processHasStopped(probe.pid)).toBe(true); await fixture.release(); expect((await client.execute("health", {})).ok).toBe(true); expect((await fakeKunaCalls(fixture.kuna)).length).toBe(3); @@ -129,7 +120,7 @@ it("close cancels and joins an installation probe while callers wait", async () const result = await pending; if (result.ok) throw new Error("Expected cancellation"); expect(result.error._tag).toBe("AnalysisCancelledError"); - expect(gone(probe.pid)).toBe(true); + expect(await processHasStopped(probe.pid)).toBe(true); } finally { await fixture.release(); await Promise.all([pending, closing]); diff --git a/tests/boundary/providers/kuna/kunaProjectCache.test.ts b/tests/boundary/providers/kuna/kunaProjectCache.test.ts index 82ec7b60c30..7bcdff03b38 100644 --- a/tests/boundary/providers/kuna/kunaProjectCache.test.ts +++ b/tests/boundary/providers/kuna/kunaProjectCache.test.ts @@ -27,6 +27,7 @@ import { kunaProjectKey } from "../../../../src/kuna/KunaCacheManifest.js"; import { KunaProjectCache } from "../../../../src/kuna/KunaProjectCache.js"; import type { KunaExportStatus } from "../../../../src/kuna/KunaProjectExport.js"; import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js"; +import { processHasStopped } from "../../../support/process/observePosixProcess.js"; import { phaseGate } from "../../../support/lifecycleHarness.js"; import { OwnedFileHandle } from "../../../../src/filesystem/OwnedFileHandle.js"; import { RegularFileCleanupFailure } from "../../../../src/filesystem/OwnedRegularFile.js"; @@ -103,15 +104,6 @@ const callsOf = async (kuna: string, subcommand: string) => const entries = (cacheRoot: string, area: string) => readdir(join(cacheRoot, area)).catch(() => []); -const processGone = (pid: number): boolean => { - try { - process.kill(pid, 0); - return false; - } catch { - return true; - } -}; - it.each([1, 2, 3, "release"] as const)( "regenerates layout %s once and retires it without touching unrelated cache resources", async (layout) => { @@ -766,7 +758,7 @@ it("stops the run only when every waiting request is cancelled", async () => { }); if (firstResult.ok) throw new Error("Expected first waiter cancellation"); // The other request still owns the run. - expect(processGone(pid)).toBe(false); + expect(await processHasStopped(pid)).toBe(false); const secondReason = { caller: "last waiter" }; secondCaller.abort(secondReason); @@ -777,7 +769,7 @@ it("stops the run only when every waiting request is cancelled", async () => { }); if (secondResult.ok) throw new Error("Expected last waiter cancellation"); expect(await cache.close()).toEqual({ ok: true, value: null }); - expect(processGone(pid)).toBe(true); + expect(await processHasStopped(pid)).toBe(true); expect(await entries(cacheRoot, "staging")).toEqual([]); expect(await entries(cacheRoot, "projects")).toEqual([]); expect(firstResult.error.cause).toBe(firstReason); @@ -803,7 +795,8 @@ it("applies one deadline to the inventory and the export together", async () => error: { _tag: "AnalysisTimeoutError", timeoutMs: 800 }, }); const [exported] = await callsOf(kuna, "decompile-project"); - expect(processGone(exported?.pid ?? 0)).toBe(true); + expect(exported?.pid).toBeTypeOf("number"); + expect(await processHasStopped(exported!.pid)).toBe(true); expect(await entries(cacheRoot, "staging")).toEqual([]); await setFakeKunaBehavior(kuna, { inventory: "hang" }); diff --git a/tests/boundary/providers/kuna/kunaProvider.test.ts b/tests/boundary/providers/kuna/kunaProvider.test.ts index 541621fae6f..627832df1e8 100644 --- a/tests/boundary/providers/kuna/kunaProvider.test.ts +++ b/tests/boundary/providers/kuna/kunaProvider.test.ts @@ -12,6 +12,7 @@ import { join } from "node:path"; import { expect, it as test, vi } from "vitest"; import { phaseGate } from "../../../support/lifecycleHarness.js"; +import { processHasStopped } from "../../../support/process/observePosixProcess.js"; import type { BinaryTarget } from "../../../../src/domain/binaryTargetTypes.js"; import type { JsonValue } from "../../../../src/domain/jsonValue.js"; @@ -810,13 +811,12 @@ it("stops the export it alone wanted before reporting itself closed", async () = const client = open(); await run(client, "procedure_pseudo_code", { procedure: "main" }); await expect.poll(() => exportsOf(kuna)).toHaveLength(1); - const pid = (await exportsOf(kuna))[0]?.pid ?? 0; + const pid = (await exportsOf(kuna))[0]?.pid; + expect(pid).toBeTypeOf("number"); expect(await client.close()).toEqual({ ok: true, value: null }); - expect(() => process.kill(pid, 0)).toThrow( - expect.objectContaining({ code: "ESRCH" }), - ); + expect(await processHasStopped(pid!)).toBe(true); expect(await readdir(join(cacheRoot, "staging"))).toEqual([]); expect(await client.close()).toEqual({ ok: true, value: null }); expect( @@ -846,10 +846,9 @@ it.each([false, true])( const call = (await fakeKunaCalls(kuna)).find( ({ argv }) => argv[0] === "decompile", ); + expect(call?.pid).toBeTypeOf("number"); expect(await client.close()).toEqual({ ok: true, value: null }); - expect(() => process.kill(call?.pid ?? 0, 0)).toThrow( - expect.objectContaining({ code: "ESRCH" }), - ); + expect(await processHasStopped(call!.pid)).toBe(true); expect(await request).toMatchObject({ ok: false, error: { _tag: "AnalysisCancelledError" }, diff --git a/tests/boundary/providers/native/LldbCallTracer.cleanup.test.ts b/tests/boundary/providers/native/LldbCallTracer.cleanup.test.ts index a605bb6dc48..9dfdb674a5a 100644 --- a/tests/boundary/providers/native/LldbCallTracer.cleanup.test.ts +++ b/tests/boundary/providers/native/LldbCallTracer.cleanup.test.ts @@ -24,7 +24,10 @@ import { NativeFixtureRunner, nativeMachoTarget, } from "../../../fixtures/nativeCommands.js"; -import { expectProcessRunning } from "../../../support/process/observePosixProcess.js"; +import { + expectProcessRunning, + processHasStopped, +} from "../../../support/process/observePosixProcess.js"; const request: Parameters[0] = { executable: "/fixture/target", @@ -158,9 +161,7 @@ it.skipIf(process.platform === "win32")( await expectProcessRunning(pid); await expect(access(root)).resolves.toBeUndefined(); expect((await client.close()).ok).toBe(true); - expect(() => process.kill(pid, 0)).toThrow( - expect.objectContaining({ code: "ESRCH" }), - ); + expect(await processHasStopped(pid)).toBe(true); await expect(access(root)).rejects.toMatchObject({ code: "ENOENT" }); } finally { if (ownedProcess !== undefined) await stopTestChild(ownedProcess); diff --git a/tests/boundary/signals/recordingDescriptorCleanup.test.ts b/tests/boundary/signals/recordingDescriptorCleanup.test.ts index 618e3404fc8..bc319d49b39 100644 --- a/tests/boundary/signals/recordingDescriptorCleanup.test.ts +++ b/tests/boundary/signals/recordingDescriptorCleanup.test.ts @@ -1,16 +1,11 @@ -import { - descriptorFailurePath, - expectRetainedDescriptor, -} from "../../fixtures/descriptorCloseFailure.js"; -import { expect, it, onTestFinished, vi } from "vitest"; -import { lstat, writeFile } from "node:fs/promises"; import type { FileHandle } from "node:fs/promises"; -import { join } from "node:path"; +import { it, vi } from "vitest"; import { SigrokRecordingProvider } from "../../../src/signals/SigrokRecordingProvider.js"; import { SignalRecordingService } from "../../../src/application/signals/SignalRecordingService.js"; -import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js"; -import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js"; -import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { + DESCRIPTOR_CLEANUP_MEMBERS, + runCliToolDescriptorCleanupScenario, +} from "../../fixtures/cliToolDescriptorCleanup.js"; const cleanup = vi.hoisted(() => ({ path: "", @@ -24,105 +19,34 @@ vi.mock("node:fs/promises", async (importOriginal) => { return withDescriptorCloseFailure(filesystem, cleanup); }); -it - .runIf(process.platform === "linux") - .each([ - "capture", - "tool", - "limiter", - "kernel", - "field-tool", - "field-limiter", - "field-kernel", - ])( +it.runIf(process.platform === "linux").each(DESCRIPTOR_CLEANUP_MEMBERS)( "retains failed %s descriptors and retries them before further acquisition and shutdown", async (member) => { - const directory = await createTestTempDirectory("rea-signal-descriptor-"); - const path = join(directory, "recording.vcd"); - const command = join(directory, "sigrok.mjs"); - const limiter = join(directory, "limiter"); - await writeFile(path, "recording bytes"); - await writeFile(limiter, "limiter", { mode: 0o700 }); - await writeFile( - command, - `if(process.argv.includes('--version'))console.log('sigrok-cli 0.7.2\\nlibsigrokdecode 0.5.3');else console.log('10-20 uart-1: 42');`, - { mode: 0o700 }, - ); - let launches = 0; - let runtimeRoot: PrivateRuntimeRoot | undefined; - const provider = new SigrokRecordingProvider( - { - ...process.env, - REA_SIGROK_COMMAND: command, - REA_SIGROK_PRLIMIT_COMMAND: limiter, - }, - (input) => { - launches += 1; - return spawnOwnedProviderProcess({ - ...input, - command: process.execPath, - arguments: [command, ...input.arguments], - expectedCommand: process.execPath, - }); - }, - async () => { - runtimeRoot = await PrivateRuntimeRoot.create({ parent: directory }); - return runtimeRoot; - }, - ); - const discovery = member.startsWith("field-"); - const resource = discovery ? member.slice(6) : member; - const operation = discovery - ? "inspect_signal_decoders" - : "decode_signal_recording"; - cleanup.path = descriptorFailurePath(resource, { - capture: path, - tool: command, - limiter, - }); - cleanup.denied = true; - cleanup.handles = []; - onTestFinished(async () => { - cleanup.denied = false; - await provider.close(); - for (const handle of cleanup.handles) await handle.close(); - cleanup.path = ""; - }); - const service = new SignalRecordingService(provider); - const first = discovery - ? await service.inspectDecoders({ query: "uart" }) - : await service.decode({ path, decoders: "uart" }); - expectRetainedDescriptor( - first, + await runCliToolDescriptorCleanupScenario({ cleanup, - operation, - runtimeRoot === undefined ? [] : [runtimeRoot.path], - ); - if (first.ok) throw new Error("Expected retained descriptor cleanup"); - const originatingCause = first.error.cause; - if (resource === "capture") { - expect(runtimeRoot).toBeDefined(); - await expect(lstat(runtimeRoot!.path)).resolves.toBeDefined(); - } - const launchCount = launches; - expect(await service.decode({ path, decoders: "uart" })).toMatchObject({ - ok: false, - error: { cleanupIncomplete: true, operation }, + member, + tempPrefix: "rea-signal-descriptor-", + recordingFileName: "recording.vcd", + commandFileName: "sigrok.mjs", + commandSource: `if(process.argv.includes('--version'))console.log('sigrok-cli 0.7.2\\nlibsigrokdecode 0.5.3');else console.log('10-20 uart-1: 42');`, + commandEnvKey: "REA_SIGROK_COMMAND", + limiterEnvKey: "REA_SIGROK_PRLIMIT_COMMAND", + primaryOperation: "decode_signal_recording", + discoveryOperation: "inspect_signal_decoders", + createFixture: ({ env, spawn, createRuntimeRoot, recordingPath }) => { + const provider = new SigrokRecordingProvider( + env, + spawn, + createRuntimeRoot, + ); + const service = new SignalRecordingService(provider); + return { + close: () => provider.close(), + runPrimary: () => + service.decode({ path: recordingPath, decoders: "uart" }), + runDiscovery: () => service.inspectDecoders({ query: "uart" }), + }; + }, }); - expect(cleanup.handles).toHaveLength(1); - expect(launches).toBe(launchCount); - await expect(provider.close()).rejects.toMatchObject({ - cleanupIncomplete: true, - operation, - }); - cleanup.denied = false; - await provider.close(); - expect(first.error.cleanupIncomplete).toBe(false); - expect(first.error.cause).toBe(originatingCause); - if (runtimeRoot !== undefined) - await expect(lstat(runtimeRoot.path)).rejects.toMatchObject({ - code: "ENOENT", - }); - expect(cleanup.handles[0]?.fd).toBe(-1); }, ); diff --git a/tests/boundary/sqlite/sqliteDatabaseProvider.test.ts b/tests/boundary/sqlite/sqliteDatabaseProvider.test.ts index 4131d25483c..7c141b5f1c0 100644 --- a/tests/boundary/sqlite/sqliteDatabaseProvider.test.ts +++ b/tests/boundary/sqlite/sqliteDatabaseProvider.test.ts @@ -1,5 +1,6 @@ import { createHash } from "node:crypto"; import { sha256 as digestForTest } from "../../support/sha256.js"; +import { processHasStopped } from "../../support/process/observePosixProcess.js"; import { execFile } from "node:child_process"; import { access, lstat, readFile, symlink, writeFile } from "node:fs/promises"; import { DatabaseSync } from "node:sqlite"; @@ -1350,9 +1351,7 @@ nativeTest( expect(result.error.cause).toBe(reason); if (pid === undefined) throw new Error("SQLite worker not acquired"); const acquiredPid = pid; - expect(() => process.kill(acquiredPid, 0)).toThrow( - expect.objectContaining({ code: "ESRCH" }), - ); + expect(await processHasStopped(acquiredPid)).toBe(true); await expectPrivateRootRemoved(ownedRoot); }, ); diff --git a/tests/composition/reverseEngineeringCancellation.test.ts b/tests/composition/reverseEngineeringCancellation.test.ts index 8e2b9732aef..1ee89573e84 100644 --- a/tests/composition/reverseEngineeringCancellation.test.ts +++ b/tests/composition/reverseEngineeringCancellation.test.ts @@ -5,6 +5,7 @@ import { expect, it } from "vitest"; import { TestReverseEngineeringService as ReverseEngineeringService } from "../support/reverseEngineeringService.js"; import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; +import { processHasStopped } from "../support/process/observePosixProcess.js"; type PromiseOutcome = | { readonly status: "fulfilled"; readonly value: Value } @@ -34,29 +35,16 @@ const settleWithin = async ( } }; -const processIsRunning = (pid: number): boolean => { - try { - process.kill(pid, 0); - return true; - } catch (cause) { - return !( - cause instanceof Error && - "code" in cause && - cause.code === "ESRCH" - ); - } -}; - const waitForProcessExit = async ( pid: number, timeoutMs: number, ): Promise => { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { - if (!processIsRunning(pid)) return true; + if (await processHasStopped(pid)) return true; await new Promise((resolve) => setTimeout(resolve, 10)); } - return !processIsRunning(pid); + return processHasStopped(pid); }; const killProcessAndWait = async ( @@ -184,7 +172,7 @@ const cleanupCancellationScenario = async (options: { options.processIds.providerPid, options.processIds.descendantPid, ]) { - if (processIsRunning(pid)) await killProcessAndWait(pid, 2_000); + if (!(await processHasStopped(pid))) await killProcessAndWait(pid, 2_000); } } }; diff --git a/tests/fixtures/artifactReaderLifecycle.ts b/tests/fixtures/artifactReaderLifecycle.ts index f2af7615c51..a346737d9ef 100644 --- a/tests/fixtures/artifactReaderLifecycle.ts +++ b/tests/fixtures/artifactReaderLifecycle.ts @@ -10,6 +10,7 @@ import { type StableRegularFileDescriptor, } from "../../src/filesystem/RegularFile.js"; import { OwnedFileHandle } from "../../src/filesystem/OwnedFileHandle.js"; +import { ArtifactFileSource } from "../../src/resources/index.js"; import { createTestTempFile } from "./temporaryDirectory.js"; import { createDeferred } from "./binarySession.js"; import { awaitAcknowledgement } from "./lifecycleAcknowledgement.js"; @@ -394,3 +395,106 @@ export const artifactPreparationRecoveryCases = ({ }, ); }; + +/** + * Shared preparation boundary regressions for archive readers backed by + * `ArtifactFileSource`: cancellation during file reading must allow clean + * retry, and a final source verification failure must not publish entries. + */ +export const artifactSourcePreparationBoundaryCases = ({ + label, + image, + createReader, + expectedPath = "a", +}: LifecycleFixture & { + readonly label: string; + readonly expectedPath?: string; +}): void => { + it(`retries ${label} preparation cancelled during file reading`, async () => { + const path = await fixture(image()); + const admitted = await openRegularFile(path, { symlinks: "reject" }); + const reader = createReader(path, admitted); + const controller = new AbortController(); + const reason = { stage: "header read" }; + const nativeRead = admitted.handle.read.bind(admitted.handle); + const read = vi.spyOn(admitted.handle, "read").mockImplementation((async ( + ...args: unknown[] + ) => { + const result = await Reflect.apply(nativeRead, admitted.handle, args); + controller.abort(reason); + return result; + }) as typeof admitted.handle.read); + try { + await expect( + (async () => { + for await (const _ of reader.entries(controller.signal)) { + } + })(), + ).rejects.toMatchObject({ reason: "cancelled", cause: reason }); + read.mockRestore(); + expect((await collectEntries(reader)).map((entry) => entry.path)).toEqual( + [expectedPath], + ); + } finally { + read.mockRestore(); + await reader.close(); + await admitted.handle.close(); + } + }); + + it(`does not publish ${label} entries when final source verification fails`, async () => { + const path = await fixture(image()); + const control = createReader(path); + const admitted = await openRegularFile(path, { symlinks: "reject" }); + const reader = createReader(path, admitted); + const expected = (await collectEntries(control))[0]!; + const nativeSourceRead = ArtifactFileSource.prototype.read; + const nativeHandleRead = admitted.handle.read.bind(admitted.handle); + const physical = Object.assign( + new Error("final source verification failed"), + { code: "EIO" }, + ); + let targetSource: ArtifactFileSource | undefined; + let fileReadsCompleted = false; + let injected = false; + const handleRead = vi + .spyOn(admitted.handle, "read") + .mockImplementation((async (...args: unknown[]) => { + const result = await Reflect.apply( + nativeHandleRead, + admitted.handle, + args, + ); + fileReadsCompleted = true; + return result; + }) as typeof admitted.handle.read); + const sourceRead = vi + .spyOn(ArtifactFileSource.prototype, "read") + .mockImplementation(function (this: ArtifactFileSource, ...args) { + if (targetSource === undefined) targetSource = this; + if (this === targetSource && fileReadsCompleted && !injected) { + injected = true; + return Promise.reject(physical); + } + return nativeSourceRead.apply(this, args); + }); + try { + await expect(collectEntries(reader)).rejects.toBe(physical); + expect(injected).toBe(true); + await expect(reader.open(expected)).rejects.toMatchObject({ + reason: "integrity", + }); + sourceRead.mockRestore(); + handleRead.mockRestore(); + expect((await collectEntries(reader)).map((entry) => entry.path)).toEqual( + [expectedPath], + ); + } finally { + sourceRead.mockRestore(); + handleRead.mockRestore(); + await reader.close(); + await admitted.handle.close(); + await control.close(); + } + }); +}; diff --git a/tests/fixtures/cliToolDescriptorCleanup.ts b/tests/fixtures/cliToolDescriptorCleanup.ts new file mode 100644 index 00000000000..144d6d0382c --- /dev/null +++ b/tests/fixtures/cliToolDescriptorCleanup.ts @@ -0,0 +1,172 @@ +import { lstat, writeFile } from "node:fs/promises"; +import type { FileHandle } from "node:fs/promises"; +import { join } from "node:path"; +import { expect, onTestFinished } from "vitest"; +import type { AnalysisError } from "../../src/domain/analysisErrorBase.js"; +import type { Result } from "../../src/domain/result.js"; +import { PrivateRuntimeRoot } from "../../src/process/PrivateRuntimeRoot.js"; +import { spawnOwnedProviderProcess } from "../../src/process/ProviderProcess.js"; +import { + descriptorFailurePath, + expectRetainedDescriptor, +} from "./descriptorCloseFailure.js"; +import { createTestTempDirectory } from "./temporaryDirectory.js"; + +export interface DescriptorCleanupFixtureState { + path: string; + denied: boolean; + handles: FileHandle[]; +} + +export const DESCRIPTOR_CLEANUP_MEMBERS = [ + "capture", + "tool", + "limiter", + "kernel", + "field-tool", + "field-limiter", + "field-kernel", +] as const; + +export type DescriptorCleanupMember = + (typeof DESCRIPTOR_CLEANUP_MEMBERS)[number]; + +export interface CliToolDescriptorCleanupOptions { + readonly cleanup: DescriptorCleanupFixtureState; + readonly member: DescriptorCleanupMember; + readonly tempPrefix: string; + readonly recordingFileName: string; + readonly commandFileName: string; + readonly commandSource: string; + readonly commandEnvKey: string; + readonly limiterEnvKey: string; + readonly primaryOperation: string; + readonly discoveryOperation: string; + readonly createFixture: (options: { + readonly env: NodeJS.ProcessEnv; + readonly spawn: ( + input: Parameters[0], + ) => ReturnType; + readonly createRuntimeRoot: () => Promise; + readonly recordingPath: string; + }) => { + readonly close: () => Promise; + readonly runPrimary: () => Promise>; + readonly runDiscovery: () => Promise>; + }; +} + +/** + * Shared Linux descriptor-close-denial regression for CLI-backed capture and + * signal providers: verifies failed close retains the exact OS descriptor and + * runtime root, blocks replacement launches until released, and clears on retry. + */ +export const runCliToolDescriptorCleanupScenario = async ( + options: CliToolDescriptorCleanupOptions, +): Promise => { + const { cleanup, member } = options; + const directory = await createTestTempDirectory(options.tempPrefix); + const path = join(directory, options.recordingFileName); + const command = join(directory, options.commandFileName); + const limiter = join(directory, "limiter"); + await writeFile(path, "recording bytes"); + await writeFile(limiter, "limiter", { mode: 0o700 }); + await writeFile(command, options.commandSource, { mode: 0o700 }); + let launches = 0; + let runtimeRoot: PrivateRuntimeRoot | undefined; + const fixture = options.createFixture({ + env: { + ...process.env, + [options.commandEnvKey]: command, + [options.limiterEnvKey]: limiter, + }, + spawn: (input) => { + launches += 1; + return spawnOwnedProviderProcess({ + ...input, + command: process.execPath, + arguments: [command, ...input.arguments], + expectedCommand: process.execPath, + }); + }, + createRuntimeRoot: async () => { + runtimeRoot = await PrivateRuntimeRoot.create({ parent: directory }); + return runtimeRoot; + }, + recordingPath: path, + }); + + const discovery = member.startsWith("field-"); + const resource = discovery ? member.slice(6) : member; + const operation = discovery + ? options.discoveryOperation + : options.primaryOperation; + cleanup.path = descriptorFailurePath(resource, { + capture: path, + tool: command, + limiter, + }); + cleanup.denied = true; + cleanup.handles = []; + onTestFinished(async () => { + cleanup.denied = false; + await fixture.close(); + for (const handle of cleanup.handles) await handle.close(); + cleanup.path = ""; + }); + + const first = discovery + ? await fixture.runDiscovery() + : await fixture.runPrimary(); + expectRetainedDescriptor( + first, + cleanup, + operation, + runtimeRoot === undefined ? [] : [runtimeRoot.path], + ); + if (first.ok) throw new Error("Expected retained descriptor cleanup"); + const originatingCause = first.error.cause; + if (resource === "capture") { + expect(runtimeRoot).toBeDefined(); + await expect(lstat(runtimeRoot!.path)).resolves.toBeDefined(); + } + const launchCount = launches; + expect(await fixture.runPrimary()).toMatchObject({ + ok: false, + error: { cleanupIncomplete: true, operation }, + }); + expect(cleanup.handles).toHaveLength(1); + expect(launches).toBe(launchCount); + + let closingOperation = operation; + if (discovery) { + cleanup.denied = false; + const recovered = await fixture.runPrimary(); + expect(recovered.ok).toBe(true); + expect(cleanup.handles.length).toBeGreaterThan(0); + expect(cleanup.handles.every((handle) => handle.fd === -1)).toBe(true); + expect(launches).toBeGreaterThan(launchCount); + cleanup.denied = true; + expect(await fixture.runPrimary()).toMatchObject({ + ok: false, + error: { cleanupIncomplete: true, operation: options.primaryOperation }, + }); + expect(cleanup.handles.at(-1)?.fd).toBeGreaterThanOrEqual(0); + closingOperation = options.primaryOperation; + } + + await expect(fixture.close()).rejects.toMatchObject({ + cleanupIncomplete: true, + operation: closingOperation, + }); + cleanup.denied = false; + await fixture.close(); + expect(first.error.cleanupIncomplete).toBe(false); + expect(first.error.cause).toBe(originatingCause); + if (runtimeRoot !== undefined) + await expect(lstat(runtimeRoot.path)).rejects.toMatchObject({ + code: "ENOENT", + }); + expect(cleanup.handles.length).toBeGreaterThan(0); + expect(cleanup.handles.every((handle) => handle.fd === -1)).toBe(true); +}; diff --git a/tests/process-global/dmgCancellationReason.test.ts b/tests/process-global/dmgCancellationReason.test.ts index c23e7c72057..4da47d247b3 100644 --- a/tests/process-global/dmgCancellationReason.test.ts +++ b/tests/process-global/dmgCancellationReason.test.ts @@ -3,6 +3,7 @@ import { join } from "node:path"; import { setTimeout as delay } from "node:timers/promises"; import { expect, it, vi } from "vitest"; import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; +import { processHasStopped } from "../support/process/observePosixProcess.js"; const state = vi.hoisted(() => ({ marker: "", @@ -114,9 +115,7 @@ it.skipIf(process.platform !== "darwin").each([false, true])( (failure.cause as OwnedCommandFailure).cancellation?.reason, ).toBe(reason); const pid = Number(await readFile(state.marker, "utf8")); - expect(() => process.kill(pid, 0)).toThrow( - expect.objectContaining({ code: "ESRCH" }), - ); + expect(await processHasStopped(pid)).toBe(true); // hdiutil is asked to stop with SIGTERM before owned cleanup kills it. expect(await readFile(`${state.marker}.term`, "utf8")).toBe( "rolled back", diff --git a/tests/process-global/firmwareFileLifetime.test.ts b/tests/process-global/firmwareFileLifetime.test.ts index fca69809a9d..d132d76f303 100644 --- a/tests/process-global/firmwareFileLifetime.test.ts +++ b/tests/process-global/firmwareFileLifetime.test.ts @@ -947,6 +947,7 @@ it("waits through selected-range snapshot finalization when shutdown starts duri length: 4, sha256: createHash("sha256").update("irmw").digest("hex"), }); + expect(fault.handles.length).toBeGreaterThan(0); expect(fault.handles.every((handle) => handle.fd === -1)).toBe(true); } finally { sourceClose.release(); @@ -1022,6 +1023,7 @@ it.each(["source-first", "tree-first"])( await fixture.context.files.close(); await Promise.all(fixture.retained.map((lease) => lease.release())); expect(error.cleanupIncomplete).toBe(false); + expect(fault.handles.length).toBeGreaterThan(0); expect(fault.handles.every((handle) => handle.fd === -1)).toBe(true); }, ); diff --git a/tests/process-global/pwntoolsCleanup.test.ts b/tests/process-global/pwntoolsCleanup.test.ts index 8d26f94414d..8c9d713b1d6 100644 --- a/tests/process-global/pwntoolsCleanup.test.ts +++ b/tests/process-global/pwntoolsCleanup.test.ts @@ -10,12 +10,15 @@ import { cleanupOwnedProcessGroup } from "../../src/process/ProcessOwnership.js" import { prepareProcessOwnershipInspection } from "../../src/process/ProcessOwnershipObservation.js"; import { stopProviderProcessFixture } from "../fixtures/providerProcess.js"; import { phaseGate } from "../support/lifecycleHarness.js"; +import { + processHasStopped, + expectProcessRunning, +} from "../support/process/observePosixProcess.js"; import { projectAnalysisError } from "../../src/domain/analysisErrorProjection.js"; import { createTestWorkspace, removeTestWorkspace, } from "../support/workspace/workspaceFixture.js"; -import { expectProcessRunning } from "../support/process/observePosixProcess.js"; const supportedHost = process.platform !== "win32"; @@ -139,9 +142,7 @@ it.runIf(supportedHost)( await expect(provider.close()).rejects.toMatchObject({ cleanupIncomplete: true, }); - expect(() => process.kill(workerPid, 0)).toThrow( - expect.objectContaining({ code: "ESRCH" }), - ); + expect(await processHasStopped(workerPid)).toBe(true); expect(result.error.cleanupResources).toEqual([ownedPath]); expect(result.error.cleanupIncomplete).toBe(true); rootRemovalAllowed = true; diff --git a/tests/process-global/pwntoolsStageRetirement.test.ts b/tests/process-global/pwntoolsStageRetirement.test.ts index 477fa93de15..6b5da006620 100644 --- a/tests/process-global/pwntoolsStageRetirement.test.ts +++ b/tests/process-global/pwntoolsStageRetirement.test.ts @@ -10,6 +10,10 @@ import { import { join } from "node:path"; import { fileURLToPath } from "node:url"; import { afterEach, beforeAll, expect, it, onTestFinished, vi } from "vitest"; +import { + processHasStopped, + expectProcessRunning, +} from "../support/process/observePosixProcess.js"; import { z } from "zod"; import { projectAnalysisError } from "../../src/domain/analysisErrorProjection.js"; import { primaryAnalysisError } from "../../src/domain/analysisErrorBase.js"; @@ -36,7 +40,6 @@ import { createTestWorkspace, removeTestWorkspace, } from "../support/workspace/workspaceFixture.js"; -import { expectProcessRunning } from "../support/process/observePosixProcess.js"; const supportedHost = process.platform !== "win32"; const worker = fileURLToPath( @@ -364,9 +367,7 @@ it.runIf(supportedHost)( await expectProcessRunning(debuggerPid); cleanupAllowed = true; await provider.close(); - expect(() => process.kill(debuggerPid, 0)).toThrow( - expect.objectContaining({ code: "ESRCH" }), - ); + expect(await processHasStopped(debuggerPid)).toBe(true); await expect(access(root.path)).rejects.toMatchObject({ code: "ENOENT" }); }, ); diff --git a/tests/process-global/shortFileReads.test.ts b/tests/process-global/shortFileReads.test.ts index f8954e6051e..f4338a1ff61 100644 --- a/tests/process-global/shortFileReads.test.ts +++ b/tests/process-global/shortFileReads.test.ts @@ -140,6 +140,7 @@ it.each([ ["plutil", "-lint", "--", operand], ]); expect(fault.reads).toBe(bytes.length); + expect(fault.handles.length).toBeGreaterThan(0); expect(fault.handles.every((handle) => handle.fd === -1)).toBe(true); } finally { await client.close(); @@ -174,6 +175,7 @@ it("preserves a native plist probe read denial over a simultaneous abort", async expect(result.error).not.toBeInstanceOf(AnalysisCancelledError); expect(result.error.cause).toBe(physical); expect(fault.reads).toBe(2); + expect(fault.handles.length).toBeGreaterThan(0); expect(fault.handles.every((handle) => handle.fd === -1)).toBe(true); } finally { await client.close(); @@ -212,6 +214,7 @@ it.each([false, true])( expect(await client.close()).toEqual({ ok: true, value: null }); expect(result.error.cleanupIncomplete).toBe(false); } + expect(fault.handles.length).toBeGreaterThan(0); expect(fault.handles.every((handle) => handle.fd === -1)).toBe(true); } finally { fault.closeFailure = undefined; @@ -264,6 +267,7 @@ it.each([ await parseBinaryTarget(path, { cwd: root, hostArchitecture: "arm64" }), ).toEqual(expected); expect(fault.reads).toBeGreaterThan(5); + expect(fault.handles.length).toBeGreaterThan(0); expect(fault.handles.every((handle) => handle.fd === -1)).toBe(true); }, ); @@ -329,6 +333,7 @@ it("keeps fuse sentinel offsets, states and complete-file digest across short re ); expect(scanned.slices[0]?.sentinels[0]?.sentinel_offset).toBe(32); expect(fault.reads).toBeGreaterThan(10); + expect(fault.handles.length).toBeGreaterThan(0); expect(fault.handles.every((handle) => handle.fd === -1)).toBe(true); } finally { await provider.close(); @@ -351,6 +356,7 @@ it("reports changed dyld header facts when short positive data ends before the m failure: { kind: "changed", format: "macho" }, }); expect(fault.reads).toBeGreaterThan(1); + expect(fault.handles.length).toBeGreaterThan(0); expect(fault.handles.every((handle) => handle.fd === -1)).toBe(true); } finally { await resources.close(); @@ -392,6 +398,7 @@ it("preserves cancellation during continued short reads and releases the descrip expect(result.error).toBeInstanceOf(AnalysisCancelledError); expect(result.error.cause).toBe(reason); expect(fault.reads).toBe(2); + expect(fault.handles.length).toBeGreaterThan(0); expect(fault.handles.every((handle) => handle.fd === -1)).toBe(true); } finally { await provider.close(); @@ -438,6 +445,7 @@ it.each(["cancelled", "eof", "io"] as const)( expect(failure).toBeInstanceOf(RegularFileChangedError); else expect(failure).toMatchObject({ reason: "cancelled" }); expect(controller.signal.aborted).toBe(true); + expect(fault.handles.length).toBeGreaterThan(0); expect(fault.handles.every((handle) => handle.fd === -1)).toBe(true); }, );