Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

fix(process): gate launch and retain cancellation provenance

morlutod6ca7b3f20a2
diff --git a/src/process/capture/ProcessCaptureError.ts b/src/process/capture/ProcessCaptureError.ts
index 6d13c8f75..404a5e16b 100644
--- a/src/process/capture/ProcessCaptureError.ts
+++ b/src/process/capture/ProcessCaptureError.ts
@@ -102,8 +102,11 @@ export const describeProcessCaptureExecutionFailure = (
};
/** Caller-visible cancellation without exposing capture implementation state. */
-export const processCaptureCancelled = (): ProcessCaptureError =>
+export const processCaptureCancelled = (
+ reason?: unknown,
+): ProcessCaptureError =>
new ProcessCaptureError("process capture was cancelled", {
+ cause: reason,
userCategory: "cancelled",
reason: "cancelled",
userMessage: "Process capture was cancelled. Start it again when ready.",
@@ -142,6 +145,6 @@ export const normalizeCaptureFailure = (
(cause === signal.reason ||
(cause instanceof Error && cause.name === "AbortError"))
)
- return processCaptureCancelled();
+ return processCaptureCancelled(signal.reason);
return cause;
};
diff --git a/src/process/capture/ProcessHarness.test.ts b/src/process/capture/ProcessHarness.test.ts
index be0a57d21..12cbab964 100644
--- a/src/process/capture/ProcessHarness.test.ts
+++ b/src/process/capture/ProcessHarness.test.ts
@@ -42,6 +42,7 @@ const incompleteFilesystemCoverage = {
} satisfies typeof emptyFilesystemCoverage;
it("retains cancellation and cleanup facts when ownership baseline inspection aborts", async () => {
const controller = new AbortController();
+ const reason = new Error("ownership baseline caller cancellation");
const scenario = processScenarioSchema.parse({
executable: process.execPath,
});
@@ -58,7 +59,7 @@ it("retains cancellation and cleanup facts when ownership baseline inspection ab
{
createTemporaryRoot: async () => "/fixture/allocated-root",
captureOwnershipBaseline: async () => {
- controller.abort();
+ controller.abort(reason);
controller.signal.throwIfAborted();
return [];
},
@@ -67,6 +68,7 @@ it("retains cancellation and cleanup facts when ownership baseline inspection ab
),
).rejects.toMatchObject({
reason: "cancelled",
+ cause: reason,
message: "process capture was cancelled",
cleanupReport: {
temporary_root: { state: "cleaned", reason: null },
diff --git a/src/process/capture/ProcessHarness.ts b/src/process/capture/ProcessHarness.ts
index 5a1697d38..9b10d1a0c 100644
--- a/src/process/capture/ProcessHarness.ts
+++ b/src/process/capture/ProcessHarness.ts
@@ -285,6 +285,9 @@ const startCaptureRuntime = async (
normalizeText,
options.recordEvent,
);
+ // Completed executable facts do not authorize launch after cancellation
+ // during the sampler's final metadata read or descriptor cleanup.
+ assertNotCancelled(options.signal);
terminal = spawn(scenario.executable, [...scenario.arguments], {
cwd: scenario.working_directory,
env: makeProcessCaptureEnvironment(options),
@@ -404,7 +407,7 @@ const finishProcessRun = async (options: {
: await options.resourceScope.release(cleanupOptions);
let { capture, executionFailure } = options;
if (executionFailure === undefined && options.signal?.aborted)
- executionFailure = processCaptureCancelled();
+ executionFailure = processCaptureCancelled(options.signal.reason);
const observedExit =
options.observations?.exit.state === "available"
? options.observations.exit.value.reason
@@ -448,7 +451,7 @@ const finishProcessRun = async (options: {
// Cancellation remains authoritative until finalization has settled, even
// when the workload exited normally before cleanup began.
if (executionFailure === undefined && options.signal?.aborted)
- executionFailure = processCaptureCancelled();
+ executionFailure = processCaptureCancelled(options.signal.reason);
return resolveProcessResult(
cleanupFailure === undefined ? verifiedCapture : capture,
executionFailure,
@@ -483,7 +486,8 @@ const completeCapture = async (options: {
`${stage} failed: ${cause instanceof Error ? cause.message : "unknown failure"}`;
const { runtime, scenario } = options;
const { reason } = options.exit;
- if (reason === "cancelled") throw processCaptureCancelled();
+ if (reason === "cancelled")
+ throw processCaptureCancelled(options.signal?.reason);
let settlement: Awaited<ReturnType<typeof observeSettlement>>;
try {
settlement = await observeSettlement(
@@ -751,7 +755,8 @@ const runProcessScenario = async (
state: "unavailable",
reason: `The captured process exit was not observed because the finalization SIGKILL could not be delivered (initiating reason: ${exit.reason}).`,
};
- if (exit.reason === "cancelled") throw processCaptureCancelled();
+ if (exit.reason === "cancelled")
+ throw processCaptureCancelled(signal?.reason);
throw new Error(
"The captured process exit was not observed because the finalization SIGKILL could not be delivered.",
);
diff --git a/src/process/capture/ProcessScenarioRuntimeValidation.ts b/src/process/capture/ProcessScenarioRuntimeValidation.ts
index 6d2978b5b..e8a19771a 100644
--- a/src/process/capture/ProcessScenarioRuntimeValidation.ts
+++ b/src/process/capture/ProcessScenarioRuntimeValidation.ts
@@ -119,5 +119,5 @@ const osFailure = (cause: unknown): string => {
/** Reject cancellation before a process capture operation begins. */
export const assertNotCancelled = (signal: AbortSignal | undefined): void => {
- if (signal?.aborted === true) throw processCaptureCancelled();
+ if (signal?.aborted === true) throw processCaptureCancelled(signal.reason);
};
diff --git a/tests/boundary/process/processCaptureCallerReason.test.ts b/tests/boundary/process/processCaptureCallerReason.test.ts
new file mode 100644
index 000000000..d201e7fbd
--- /dev/null
+++ b/tests/boundary/process/processCaptureCallerReason.test.ts
@@ -0,0 +1,48 @@
+import { expect } from "vitest";
+
+import { parseProcessScenario } from "../../../src/domain/process/processScenario.js";
+import { captureProcessScenario } from "../../../src/process/capture/ProcessHarness.js";
+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+import { itWithCaptureCapability } from "./processCaptureCapability.js";
+
+itWithCaptureCapability(
+ "retains completed capture facts and the exact reason when cleanup reporting cancels",
+ async () => {
+ const root = await createTestTempDirectory("rea-capture-reason-");
+ const controller = new AbortController();
+ const reason = { request: "cancel after cleanup completed" };
+ let cleanupReported = false;
+ const result = await captureProcessScenario(
+ parseProcessScenario({
+ executable: process.execPath,
+ arguments: ["--eval", "console.log('completed capture')"],
+ working_directory: root,
+ settle_ms: 0,
+ }),
+ controller.signal,
+ process.platform,
+ process.env,
+ undefined,
+ undefined,
+ {
+ report: async (update) => {
+ if (update.phase === "cleanup" && update.terminal === true) {
+ cleanupReported = true;
+ controller.abort(reason);
+ }
+ },
+ },
+ );
+ expect(cleanupReported).toBe(true);
+ if (result.ok) throw new Error("Expected finalization cancellation");
+ expect(result.error.cause).toBe(reason);
+ expect(result.error).toMatchObject({
+ reason: "cancelled",
+ partialObservation: {
+ capture: { exit: { code: 0 } },
+ cleanup: { temporary_root: { state: "cleaned" } },
+ },
+ });
+ },
+ 20_000,
+);
diff --git a/tests/boundary/process/selectedExecutableCancellation.test.ts b/tests/boundary/process/selectedExecutableCancellation.test.ts
index 238737a58..849729288 100644
--- a/tests/boundary/process/selectedExecutableCancellation.test.ts
+++ b/tests/boundary/process/selectedExecutableCancellation.test.ts
@@ -4,6 +4,7 @@ import { observeSelectedExecutable } from "../../../src/process/capture/ProcessC
it("cancels after real metadata IO without creating an already-aborted stream or leaking the file handle", async () => {
const controller = new AbortController();
+ const reason = new Error("cancel after executable path metadata");
let opened: FileHandle | undefined;
await expect(
observeSelectedExecutable(process.execPath, controller.signal, {
@@ -13,10 +14,10 @@ it("cancels after real metadata IO without creating an already-aborted stream or
},
async stat(path) {
const metadata = await stat(path, { bigint: true });
- controller.abort();
+ controller.abort(reason);
return metadata;
},
}),
- ).rejects.toMatchObject({ reason: "cancelled" });
+ ).rejects.toMatchObject({ reason: "cancelled", cause: reason });
expect(opened?.fd).toBe(-1);
});
diff --git a/tests/process-global/processPrelaunchCancellation.test.ts b/tests/process-global/processPrelaunchCancellation.test.ts
new file mode 100644
index 000000000..453a88cb4
--- /dev/null
+++ b/tests/process-global/processPrelaunchCancellation.test.ts
@@ -0,0 +1,149 @@
+import { rm, stat, type FileHandle } from "node:fs/promises";
+import { afterEach, expect, it, vi } from "vitest";
+
+import { captureProcessScenario } from "../../src/process/capture/ProcessHarness.js";
+import { parseProcessScenario } from "../../src/domain/process/processScenario.js";
+import { emptyProcessCapture } from "../../src/domain/process/processCapture.fixture.js";
+
+const control = vi.hoisted(() => ({
+ stage: "none" as "none" | "before" | "open" | "final-stat" | "close",
+ controller: undefined as AbortController | undefined,
+ reason: undefined as Error | undefined,
+ handle: undefined as FileHandle | undefined,
+ sampled: false,
+ closed: false,
+ launches: 0,
+}));
+
+// Exercise the actual startup decision without creating a target process.
+vi.mock("@lydell/node-pty", () => ({
+ spawn: () => {
+ control.launches += 1;
+ throw new Error("PTY launch sentinel");
+ },
+}));
+
+// Native ownership inspection is outside this portable launch-boundary test.
+vi.mock("../../src/process/ProcessOwnershipObservation.js", async (load) => {
+ const original =
+ await load<
+ typeof import("../../src/process/ProcessOwnershipObservation.js")
+ >();
+ return {
+ ...original,
+ prepareProcessOwnershipInspection: async () => {},
+ systemProcessOwnershipHost: {
+ ...original.systemProcessOwnershipHost,
+ captureBaseline: async () => [],
+ },
+ };
+});
+
+vi.mock("node:fs/promises", async (load) => {
+ const original = await load<typeof import("node:fs/promises")>();
+ return {
+ ...original,
+ open: async (...args: Parameters<typeof original.open>) => {
+ const handle = await original.open(...args);
+ if (args[0] !== process.execPath) return handle;
+ control.handle = handle;
+ const nativeStat = handle.stat.bind(handle);
+ const nativeClose = handle.close.bind(handle);
+ const nativeStream = handle.createReadStream.bind(handle);
+ handle.createReadStream = (options) => {
+ const stream = nativeStream(options);
+ stream.once("end", () => (control.sampled = true));
+ return stream;
+ };
+ handle.stat = (async (...parameters: Parameters<typeof handle.stat>) => {
+ const metadata = await nativeStat(...parameters);
+ if (control.sampled && control.stage === "final-stat")
+ control.controller?.abort(control.reason);
+ return metadata;
+ }) as typeof handle.stat;
+ handle.close = async () => {
+ await nativeClose();
+ control.closed = true;
+ if (control.stage === "close")
+ control.controller?.abort(control.reason);
+ };
+ if (control.stage === "open") control.controller?.abort(control.reason);
+ return handle;
+ },
+ };
+});
+
+afterEach(() => {
+ control.controller = undefined;
+ control.reason = undefined;
+ control.handle = undefined;
+});
+
+it.each(["none", "before", "open", "final-stat", "close"] as const)(
+ "gates launch on cancellation at %s while releasing startup resources",
+ async (stage) => {
+ const controller = new AbortController();
+ const reason = new Error(`cancel at ${stage}`);
+ Object.assign(control, {
+ stage,
+ controller,
+ reason,
+ sampled: false,
+ closed: false,
+ launches: 0,
+ });
+ if (stage === "before") controller.abort(reason);
+ const removed: string[] = [];
+ const result = await captureProcessScenario(
+ parseProcessScenario({
+ executable: process.execPath,
+ arguments: ["--eval", "process.exit(0)"],
+ working_directory: process.cwd(),
+ settle_ms: 0,
+ }),
+ controller.signal,
+ "linux",
+ {},
+ async () => ({
+ files: [],
+ truncated: false,
+ completeRoots: [],
+ coverage: emptyProcessCapture().truncation_details.filesystem_before,
+ }),
+ {
+ platform: "linux",
+ cleanupProcessGroup: async () => {
+ throw new Error("No process should have been acquired");
+ },
+ verifyTokenOwnedProcesses: async () => {
+ throw new Error("No process should have been acquired");
+ },
+ removeTemporaryRoot: async (path) => {
+ await rm(path, { recursive: true });
+ removed.push(path);
+ },
+ },
+ );
+ expect(control.launches).toBe(stage === "none" ? 1 : 0);
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error("Expected sentinel failure or cancellation");
+ if (stage === "none")
+ expect(String(result.error.cause)).toContain("PTY launch sentinel");
+ else {
+ expect(result.error).toMatchObject({ reason: "cancelled" });
+ expect(result.error.cause).toBe(reason);
+ }
+ if (stage === "before") {
+ expect(control.handle).toBeUndefined();
+ expect(removed).toEqual([]);
+ } else {
+ expect(control.closed).toBe(true);
+ expect(control.handle?.fd).toBe(-1);
+ expect(removed).toHaveLength(1);
+ const removedRoot = removed[0];
+ if (removedRoot === undefined) throw new Error("Expected removed root");
+ await expect(stat(removedRoot)).rejects.toMatchObject({ code: "ENOENT" });
+ expect(control.sampled).toBe(stage !== "open");
+ }
+ },
+);