From 3a3631100480109a7d2ef8b9ac8ff1f58df5904e Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 22 Nov 2026 04:26:24 -0500 Subject: [PATCH] fix(process): retain synchronous command launch failures (#13350) --- src/process/BoundedOutputExcerpt.test.ts | 57 +++------ src/process/ExecFileBoundedOutput.test.ts | 120 ++++++++++-------- src/process/ExecFileBoundedOutput.ts | 22 +++- .../ProcessInspectionCancellation.test.ts | 18 +-- src/process/SignalAbort.test.ts | 35 +++-- src/process/capturedProviderOutput.test.ts | 31 +++-- src/process/classifyProviderOutcome.test.ts | 94 ++++++-------- .../process/providerProcessOutput.test.ts | 29 ----- 8 files changed, 171 insertions(+), 235 deletions(-) diff --git a/src/process/BoundedOutputExcerpt.test.ts b/src/process/BoundedOutputExcerpt.test.ts index ae90e25903..12e21b9f21 100644 --- a/src/process/BoundedOutputExcerpt.test.ts +++ b/src/process/BoundedOutputExcerpt.test.ts @@ -96,48 +96,21 @@ describe("bounded output excerpts", () => { }); describe("bounded output ring buffer", () => { - it("matches head and tail bytes across repeated small writes wrapping the ring buffer", () => { - const limit = 19; - const headLimit = Math.ceil(limit / 2); - const tailLimit = limit - headLimit; - const excerpt = new BoundedOutputExcerpt(limit); - const chunks = Array.from({ length: 120 }, (_, index) => - Buffer.from(index % 7 === 0 ? `🙂${index}` : `_${index}_`), - ); - for (const chunk of chunks) excerpt.append(chunk); - const full = Buffer.concat(chunks); - const expectedHead = full.subarray(0, headLimit).toString("utf8"); - const expectedTail = full - .subarray(full.length - tailLimit) - .toString("utf8"); - expect(expectedHead).toBe("🙂0_1__2"); - expect(expectedTail).toBe("8_🙂119"); - expect(excerpt.truncated).toBe(true); - expect(full.length).toBeGreaterThan(headLimit + tailLimit); - expect(excerpt.text).toBe( - `${expectedHead} … [output omitted] … ${expectedTail}`, - ); - }); - - it("drops split UTF-8 bytes at a wrapped ring tail boundary", () => { - const limit = 13; - const headLimit = Math.ceil(limit / 2); - const tailLimit = limit - headLimit; - const excerpt = new BoundedOutputExcerpt(limit); - const chunks = Array.from({ length: 120 }, (_, index) => - Buffer.from(index % 7 === 0 ? `🙂${index}` : `_${index}_`), - ); - for (const chunk of chunks) excerpt.append(chunk); - const full = Buffer.concat(chunks); - const rawHead = full.subarray(0, headLimit); - const rawTail = full.subarray(full.length - tailLimit); - expect(rawHead.toString("utf8")).toBe("🙂0_1"); - // The 6-byte tail starts inside the 4-byte "🙂" before "119". - expect([...rawTail.subarray(0, 3)]).toEqual([0x9f, 0x99, 0x82]); - expect(rawTail.subarray(3).toString("utf8")).toBe("119"); - expect(excerpt.truncated).toBe(true); - expect(excerpt.text).toBe("🙂0_1 … [output omitted] … 119"); - }); + it.each([ + [19, "🙂0_1__2 … [output omitted] … 8_🙂119"], + [13, "🙂0_1 … [output omitted] … 119"], + ])( + "retains complete head and tail characters after wrapping the %i byte buffer", + (limit, expected) => { + const excerpt = new BoundedOutputExcerpt(limit); + for (let index = 0; index < 120; index += 1) + excerpt.append( + Buffer.from(index % 7 === 0 ? `🙂${index}` : `_${index}_`), + ); + expect(excerpt.truncated).toBe(true); + expect(excerpt.text).toBe(expected); + }, + ); it("handles zero budget and oversized tail replacement after partial writes", () => { const empty = new BoundedOutputExcerpt(0); diff --git a/src/process/ExecFileBoundedOutput.test.ts b/src/process/ExecFileBoundedOutput.test.ts index 50a22bb17b..2b4c372a00 100644 --- a/src/process/ExecFileBoundedOutput.test.ts +++ b/src/process/ExecFileBoundedOutput.test.ts @@ -1,66 +1,76 @@ +import { join } from "node:path"; import { describe, expect, it } from "vitest"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { execFileBoundedOutput } from "./ExecFileBoundedOutput.js"; +it.skipIf(process.platform === "win32")( + "returns the errno and empty capture when a parent of the executable is a regular file", + async () => { + const command = join(process.execPath, "not-a-directory"); + await expect( + execFileBoundedOutput(command, [], { env: {}, limit: 8 }), + ).resolves.toEqual({ + exitCode: "ENOTDIR", + stdout: "", + stderr: "", + outputTruncated: false, + }); + }, +); + describe("execFileBoundedOutput", () => { - it("retains complete UTF-8 characters at both sides of truncated command output", async () => { - const text = `A🙂${"x".repeat(30)}🙂Z`; - const result = await execFileBoundedOutput( - process.execPath, - [ - "-e", - `process.stdout.write(${JSON.stringify(text)}); process.stderr.write(${JSON.stringify(text)});`, - ], - { env: {}, limit: 8 }, - ); - expect(result.exitCode).toBe(0); - expect(result.stdout).toBe("A … [output omitted] … Z"); - expect(result.stderr).toBe("A … [output omitted] … Z"); - expect(result.outputTruncated).toBe(true); - }); + const limit = 64 * 1024; + const half = limit / 2; - it("lets a command finish after its output exceeds the capture limit", async () => { - const result = await execFileBoundedOutput( - process.execPath, - [ - "-e", - "process.stdout.write('x'.repeat(70000)); process.stderr.write('failure detail');", - ], - { env: {}, limit: 64 * 1024 }, - ); - expect(result.exitCode).toBe(0); - expect(Buffer.byteLength(result.stdout)).toBeLessThan(64 * 1024 + 50); - expect(result.stdout).toContain("[output omitted]"); - expect(result.stderr).toBe("failure detail"); - expect(result.outputTruncated).toBe(true); - }); - - it("retains a failing command's status and stderr after verbose stdout", async () => { - const result = await execFileBoundedOutput( - process.execPath, - [ - "-e", + it.each([ + { + stream: "stdout", + script: "process.stdout.write('x'.repeat(70000)); process.stderr.write('package conflict'); process.exitCode = 1;", - ], - { env: {}, limit: 64 * 1024 }, - ); - expect(result.exitCode).toBe(1); - expect(result.stderr).toBe("package conflict"); - expect(result.outputTruncated).toBe(true); + expected: { + exitCode: 1, + stdout: `${"x".repeat(half)} … [output omitted] … ${"x".repeat(half)}`, + stderr: "package conflict", + }, + }, + { + stream: "stderr", + script: + "process.stderr.write('w'.repeat(70000)); process.stderr.write('final warning'); process.stdout.write('ready');", + expected: { + exitCode: 0, + stdout: "ready", + stderr: `${"w".repeat(half)} … [output omitted] … ${"w".repeat(half - "final warning".length)}final warning`, + }, + }, + ])( + "drains overflowing $stream and preserves the other stream and exit status", + async ({ script, expected }) => { + await expect( + execFileBoundedOutput(process.execPath, ["-e", script], { + env: {}, + limit, + }), + ).resolves.toEqual({ ...expected, outputTruncated: true }); + }, + ); + + it("returns a missing executable's errno and empty capture", async () => { + const directory = await createTestTempDirectory("rea-command-launch-"); + await expect( + execFileBoundedOutput(join(directory, "missing"), [], { env: {}, limit }), + ).resolves.toEqual({ + exitCode: "ENOENT", + stdout: "", + stderr: "", + outputTruncated: false, + }); }); - it("retains a final error after a long prefix in the same stream", async () => { - const result = await execFileBoundedOutput( - process.execPath, - [ - "-e", - "process.stderr.write('warning '.repeat(10000)); process.stderr.write('error: final conflict'); process.exitCode = 1;", - ], - { env: {}, limit: 64 * 1024 }, - ); - expect(result.exitCode).toBe(1); - expect(result.stderr).toContain("[output omitted]"); - expect(result.stderr).toContain("error: final conflict"); - expect(result.outputTruncated).toBe(true); + it("rejects invalid spawn input", async () => { + await expect( + execFileBoundedOutput("bad\0path", [], { env: {}, limit }), + ).rejects.toMatchObject({ code: "ERR_INVALID_ARG_VALUE" }); }); }); diff --git a/src/process/ExecFileBoundedOutput.ts b/src/process/ExecFileBoundedOutput.ts index a7d01e6411..ef037dc3f0 100644 --- a/src/process/ExecFileBoundedOutput.ts +++ b/src/process/ExecFileBoundedOutput.ts @@ -1,5 +1,6 @@ import { spawn } from "node:child_process"; import { BoundedOutputExcerpt } from "./BoundedOutputExcerpt.js"; +import { launcherFailureOf } from "./launchFailure.js"; export interface BoundedCommandOutput { readonly exitCode: string | number | null; @@ -18,10 +19,23 @@ export const execFileBoundedOutput = ( }, ): Promise => new Promise((resolve) => { - const child = spawn(executable, [...args], { - env: options.env, - stdio: ["ignore", "pipe", "pipe"], - }); + let child; + try { + child = spawn(executable, [...args], { + env: options.env, + stdio: ["ignore", "pipe", "pipe"], + }); + } catch (cause) { + const code = launcherFailureOf(cause)?.code; + if (code === undefined) throw cause; + resolve({ + exitCode: code, + stdout: "", + stderr: "", + outputTruncated: false, + }); + return; + } const stdout = new BoundedOutputExcerpt(options.limit); const stderr = new BoundedOutputExcerpt(options.limit); child.stdout.on("data", (chunk: Buffer) => stdout.append(chunk)); diff --git a/src/process/ProcessInspectionCancellation.test.ts b/src/process/ProcessInspectionCancellation.test.ts index a47e7c6396..b884ab92f2 100644 --- a/src/process/ProcessInspectionCancellation.test.ts +++ b/src/process/ProcessInspectionCancellation.test.ts @@ -1,27 +1,13 @@ -import { access, readFile } from "node:fs/promises"; +import { access } from "node:fs/promises"; import { join } from "node:path"; import { expect, it, vi } from "vitest"; import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { AnalysisOutputError } from "../domain/analysisErrorCore.js"; -import { - isProcessOwnershipInspectionCancellation, - ProcessOwnershipInspectionCancelled, -} from "./ProcessInspectionCancellation.js"; +import { ProcessOwnershipInspectionCancelled } from "./ProcessInspectionCancellation.js"; import { systemProcessOwnershipHost } from "./ProcessOwnershipObservation.js"; import { spawnOwnedProviderProcess } from "./ProviderProcess.js"; -it("does not turn a physical OS read failure into inspection cancellation when reused as the abort reason", async () => { - const root = await createTestTempDirectory("rea-inspection-origin-"); - const failure = await readFile(join(root, "missing")).catch( - (cause: unknown) => cause, - ); - expect(failure).toMatchObject({ code: "ENOENT" }); - const controller = new AbortController(); - controller.abort(failure); - expect(isProcessOwnershipInspectionCancellation(failure)).toBe(false); -}); - it("wraps an opaque non-cancellation analysis error at already-aborted spawn admission without launching", async () => { const root = await createTestTempDirectory("rea-inspection-admission-"); const marker = join(root, "launched"); diff --git a/src/process/SignalAbort.test.ts b/src/process/SignalAbort.test.ts index 9b13f69863..4432ec595d 100644 --- a/src/process/SignalAbort.test.ts +++ b/src/process/SignalAbort.test.ts @@ -3,26 +3,23 @@ import { fileURLToPath } from "node:url"; import { expect, it } from "vitest"; import { isAbortOf, isAbortWithReason } from "./SignalAbort.js"; -it("recognises Node's abort error for this signal's reason", async () => { - const controller = new AbortController(); - const reason = { caller: "stop" }; - controller.abort(reason); - const cause = await readFile(fileURLToPath(import.meta.url), { - signal: controller.signal, - }).catch((failure: unknown) => failure); - expect(isAbortOf(cause, controller.signal)).toBe(true); - expect(isAbortOf(reason, controller.signal)).toBe(true); -}); +it.each([ + { kind: "object", reason: { caller: "stop" } }, + { kind: "NaN", reason: Number.NaN }, +])( + "recognises a $kind reason and Node's envelope around it", + async ({ reason }) => { + const controller = new AbortController(); + controller.abort(reason); + const cause = await readFile(fileURLToPath(import.meta.url), { + signal: controller.signal, + }).catch((failure: unknown) => failure); -it("recognises a NaN abort reason, which === never matches", async () => { - const controller = new AbortController(); - controller.abort(Number.NaN); - const cause = await readFile(fileURLToPath(import.meta.url), { - signal: controller.signal, - }).catch((failure: unknown) => failure); - expect(isAbortOf(cause, controller.signal)).toBe(true); - expect(isAbortOf(Number.NaN, controller.signal)).toBe(true); -}); + expect(cause).toMatchObject({ name: "AbortError", code: "ABORT_ERR" }); + expect(isAbortOf(cause, controller.signal)).toBe(true); + expect(isAbortOf(reason, controller.signal)).toBe(true); + }, +); it("does not claim another reason's abort or an unaborted signal", () => { const foreign = new DOMException("aborted", "AbortError"); diff --git a/src/process/capturedProviderOutput.test.ts b/src/process/capturedProviderOutput.test.ts index a8a07c6ac9..6bfc0e2a25 100644 --- a/src/process/capturedProviderOutput.test.ts +++ b/src/process/capturedProviderOutput.test.ts @@ -30,16 +30,23 @@ it("keeps the retained text beside the bytes the process wrote", () => { }); }); -it("narrows to the three fields a successful result declares", () => { - expect( - providerResultDiagnostics( - capturedProviderOutput(snapshot({ exitCode: 0, signal: null })), - ), - ).toStrictEqual({ stdout: "head", stderr: "", truncated: false }); -}); - -it("reports exit facts and an untruncated capture as observed", () => { - expect( - capturedProviderOutput(snapshot({ exitCode: 2, signal: null })), - ).toMatchObject({ exit_code: 2, signal: null, truncated: false }); +it("narrows a complete process capture to the fields a result declares", () => { + const complete = capturedProviderOutput( + snapshot({ + stdout: { text: "head", bytes: 4, observedBytes: 4 }, + exitCode: 2, + signal: null, + }), + ); + expect(complete).toMatchObject({ + stdout_bytes: 4, + exit_code: 2, + signal: null, + truncated: false, + }); + expect(providerResultDiagnostics(complete)).toStrictEqual({ + stdout: "head", + stderr: "", + truncated: false, + }); }); diff --git a/src/process/classifyProviderOutcome.test.ts b/src/process/classifyProviderOutcome.test.ts index 5a5ed5fd7c..1905e376e0 100644 --- a/src/process/classifyProviderOutcome.test.ts +++ b/src/process/classifyProviderOutcome.test.ts @@ -8,6 +8,7 @@ import { type ProviderDialectOutcome, type ProviderOutcomeContext, } from "./classifyProviderOutcome.js"; +import { capturedProviderOutput } from "./capturedProviderOutput.js"; import type { ProviderProcessSnapshot } from "./ProviderProcess.js"; const snapshot: ProviderProcessSnapshot = { @@ -22,20 +23,19 @@ const context = ( ): ProviderOutcomeContext => ({ providerId: "example", operation: "inspect_target", - capturedOutput: (retained) => ({ - stdout: retained.stdout.text, - stderr: retained.stderr.text, - truncated: false, - }), + capturedOutput: capturedProviderOutput, timeout: { ms: 1000 }, outputLimit: { limits: null, recovery: {} }, dialect, }); /** A dialect that recognises nothing and reports its phase. */ -const unrecognised = context((_outcome, _details, unclassified) => - unclassified({ diagnostics: { phase: "worker" } }), -); +const unrecognised = { + ...context((_outcome, _details, unclassified) => + unclassified({ diagnostics: { phase: "worker" } }), + ), + details: { diagnostics: { receipt: "finalization failed" } }, +}; describe("an outcome the provider dialect does not recognise", () => { const cases: readonly { @@ -49,17 +49,24 @@ describe("an outcome the provider dialect does not recognise", () => { kind: "exited", cause: new Error("exited with 3"), message: "exited with 3", - output: { snapshot, truncated: true }, + output: { + snapshot: { + ...snapshot, + diagnosticTruncated: true, + stderr: { ...snapshot.stderr, observedBytes: 4096 }, + }, + truncated: true, + }, exitCode: 3, signal: null, - stopRequested: false, + stopRequested: true, }, examined: { failure_kind: "exited", reason: "exited with 3", exit_code: 3, signal: null, - stop_requested: false, + stop_requested: true, output_truncated: true, }, }, @@ -83,66 +90,37 @@ describe("an outcome the provider dialect does not recognise", () => { "reports $name with the examined outcome", ({ outcome, examined }) => { const failure = classifyProviderOutcome(outcome, unrecognised); + const diagnostics = { + receipt: "finalization failed", + phase: "worker", + ...examined, + }; + const captured = { + stdout: "", + stderr: "unrecognised diagnostic", + stdout_bytes: 0, + stderr_bytes: outcome.kind === "exited" ? 4096 : 23, + exit_code: 3, + signal: null, + truncated: outcome.kind === "exited", + }; expect(failure).toBeInstanceOf(UnclassifiedProviderFailure); + expect(failure.cause).toBe(outcome.cause); expect(failure).toMatchObject({ _tag: "ProviderAdapterError", providerId: "example", operation: "inspect_target", examined, - diagnostics: { phase: "worker", ...examined }, - cause: outcome.cause, + diagnostics, + capturedOutput: captured, }); expect(projectAnalysisError(failure)).toMatchObject({ code: "execution_failure", - details: { diagnostics: { phase: "worker", ...examined } }, + details: { diagnostics, captured_output: captured }, }); }, ); - it("keeps the retained output beside the examined outcome by default", () => { - const failure = classifyProviderOutcome( - { - kind: "exited", - cause: new Error("exited with 3"), - message: "exited with 3", - output: { snapshot, truncated: false }, - exitCode: 3, - signal: null, - stopRequested: true, - }, - context((_outcome, _details, unclassified) => unclassified()), - ); - expect(failure.capturedOutput).toMatchObject({ - stderr: "unrecognised diagnostic", - }); - expect(failure.diagnostics).toMatchObject({ stop_requested: true }); - }); - - it("adds the provider's diagnostics to the context's diagnostics", () => { - const failure = classifyProviderOutcome( - { - kind: "exited", - cause: new Error("exited with 3"), - message: "exited with 3", - output: { snapshot, truncated: false }, - exitCode: 3, - signal: null, - stopRequested: false, - }, - { - ...context((_outcome, _details, unclassified) => - unclassified({ diagnostics: { phase: "worker" } }), - ), - details: { diagnostics: { receipt: "finalization failed" } }, - }, - ); - expect(failure.diagnostics).toMatchObject({ - receipt: "finalization failed", - phase: "worker", - failure_kind: "exited", - }); - }); - it("does not report an outcome the dialect classified", () => { const failure = classifyProviderOutcome( { diff --git a/tests/boundary/process/providerProcessOutput.test.ts b/tests/boundary/process/providerProcessOutput.test.ts index 42f3f60982..cb90dce540 100644 --- a/tests/boundary/process/providerProcessOutput.test.ts +++ b/tests/boundary/process/providerProcessOutput.test.ts @@ -1,8 +1,6 @@ import { expect, it, vi } from "vitest"; import type { Socket } from "node:net"; import type { Writable } from "node:stream"; -import { EventEmitter } from "node:events"; -import { PassThrough } from "node:stream"; import { ProviderProcessSupervisor, type ProviderProcessDiagnostic, @@ -100,30 +98,3 @@ it("bounds capture before diagnostic callbacks while draining both output stream await stopProviderProcessFixture(child); } }); - -it("bounds additional late output while retaining observed byte counts", () => { - const child = Object.assign(new EventEmitter(), { - stdout: new PassThrough(), - stderr: new PassThrough(), - exitCode: null as number | null, - signalCode: null as NodeJS.Signals | null, - kill: vi.fn(() => true), - }); - const supervisor = new ProviderProcessSupervisor({ - process: child, - ownsProcessLifetime: true, - }); - - supervisor.limitAdditionalOutputBytes(5); - child.stdout.write("abc"); - supervisor.limitAdditionalOutputBytes(5); - child.stdout.write("defgh"); - child.stderr.write("ijkl"); - - const snapshot = supervisor.snapshot(); - expect(snapshot.stdout.text + snapshot.stderr.text).toHaveLength(5); - expect(snapshot.stdout.observedBytes).toBe(8); - expect(snapshot.stderr.observedBytes).toBe(4); - expect(snapshot.diagnosticTruncated).toBe(true); - supervisor.dispose(); -});