fix(process)!: require current captures and preserve cleanup failures
Remove v3 capture conversion and require explicit executable identity and event journals. Preserve cancellation, execution diagnostics, snapshots, and cleanup outcomes from preparation through CLI delivery.
This commit is contained in:
@@ -189,13 +189,9 @@ export const cleanupWindowsProcessTree = async (
|
||||
const result = await host.terminateTree(rootPid);
|
||||
return { cleaned: true, signaled: result === "terminated" };
|
||||
} catch (cause: unknown) {
|
||||
// The reason string is a pinned validation contract; keep it stable and
|
||||
// do not interpolate the cause into caller-visible diagnostics here.
|
||||
void cause;
|
||||
return {
|
||||
cleaned: false,
|
||||
reason:
|
||||
"Windows P0 process-tree termination failed; Job Object ownership is unavailable",
|
||||
reason: `Windows process-tree termination failed for PID ${String(rootPid)}: ${errorMessage(cause)}`,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
@@ -306,7 +306,7 @@ describe("Windows P0 process-tree cleanup", () => {
|
||||
await expect(cleanupWindowsProcessTree(42, failing)).resolves.toEqual({
|
||||
cleaned: false,
|
||||
reason:
|
||||
"Windows P0 process-tree termination failed; Job Object ownership is unavailable",
|
||||
"Windows process-tree termination failed for PID 42: taskkill failed",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { DarwinProcessOwnershipInspectionError } from "../DarwinProcessRunTokenReader.js";
|
||||
import { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import type {
|
||||
PartialProcessCaptureObservation,
|
||||
@@ -61,3 +62,20 @@ export const processCaptureCancelled = (): ProcessCaptureError =>
|
||||
reason: "cancelled",
|
||||
userMessage: "Process capture was cancelled. Start it again when ready.",
|
||||
});
|
||||
|
||||
/** Preserve typed process-inspection preflight failures at the capture boundary. */
|
||||
export const normalizeCaptureFailure = (
|
||||
cause: unknown,
|
||||
signal: AbortSignal | undefined,
|
||||
): unknown => {
|
||||
if (cause instanceof ProcessCaptureError) return cause;
|
||||
if (cause instanceof DarwinProcessOwnershipInspectionError)
|
||||
return new ProcessCaptureError(cause.message, { cause });
|
||||
if (
|
||||
signal?.aborted === true &&
|
||||
(cause === signal.reason ||
|
||||
(cause instanceof Error && cause.name === "AbortError"))
|
||||
)
|
||||
return processCaptureCancelled();
|
||||
return cause;
|
||||
};
|
||||
|
||||
@@ -37,6 +37,7 @@ import { classifyFilesystemEffects } from "./ProcessFilesystemEffects.js";
|
||||
import {
|
||||
cleanupOwnedProcessGroup,
|
||||
verifyNoTokenOwnedProcesses,
|
||||
type OwnedProcessGroup,
|
||||
type ProcessCleanupResult,
|
||||
type ProcessOwnershipBaseline,
|
||||
} from "../ProcessOwnership.js";
|
||||
@@ -47,6 +48,7 @@ import {
|
||||
} from "../ProcessOwnershipObservation.js";
|
||||
import {
|
||||
describeProcessCaptureExecutionFailure,
|
||||
normalizeCaptureFailure,
|
||||
ProcessCaptureError,
|
||||
} from "./ProcessCaptureError.js";
|
||||
import { assertNotCancelled } from "./ProcessScenarioRuntimeValidation.js";
|
||||
@@ -685,6 +687,66 @@ const verifyTokenOwnedProcessesUntilSettled = async (
|
||||
return result;
|
||||
};
|
||||
|
||||
const releaseCapturedProcessGroup = async (
|
||||
ownership: OwnedProcessGroup,
|
||||
host: ProcessCaptureCleanupHost,
|
||||
): Promise<ProcessCaptureCleanupReport["owned_process_group"]> => {
|
||||
if (host.platform === "win32")
|
||||
return {
|
||||
state: "unverified",
|
||||
reason:
|
||||
"owned process cleanup is unverifiable on Windows without process-job authority",
|
||||
};
|
||||
let outcome: ProcessCaptureCleanupReport["owned_process_group"] = {
|
||||
state: "cleaned",
|
||||
reason: null,
|
||||
};
|
||||
const unverified: Array<{
|
||||
readonly pid: number;
|
||||
readonly diagnostic: string;
|
||||
}> = [];
|
||||
try {
|
||||
const cleaned = await host.cleanupProcessGroup(ownership);
|
||||
unverified.push(...(cleaned.unverified ?? []));
|
||||
if (!cleaned.cleaned) {
|
||||
outcome = { state: "unverified", reason: cleaned.reason };
|
||||
} else {
|
||||
const verified = await verifyTokenOwnedProcessesUntilSettled(() =>
|
||||
host.verifyTokenOwnedProcesses(
|
||||
ownership.runId,
|
||||
undefined,
|
||||
ownership.captureBaseline,
|
||||
ownership,
|
||||
),
|
||||
);
|
||||
unverified.push(...(verified.unverified ?? []));
|
||||
if (!verified.cleaned)
|
||||
outcome = { state: "unverified", reason: verified.reason };
|
||||
}
|
||||
} catch (cause: unknown) {
|
||||
outcome = {
|
||||
state: "failed",
|
||||
reason:
|
||||
cause instanceof Error
|
||||
? cause.message || cause.name || "owned process cleanup failed"
|
||||
: "owned process cleanup failed",
|
||||
};
|
||||
}
|
||||
return unverified.length === 0
|
||||
? outcome
|
||||
: {
|
||||
...outcome,
|
||||
unverified_processes: [
|
||||
...new Map(
|
||||
unverified.map(({ pid, diagnostic }) => [
|
||||
`${String(pid)}:${diagnostic}`,
|
||||
{ pid, reason: diagnostic },
|
||||
]),
|
||||
).values(),
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
export const releaseProcessResources = async (options: {
|
||||
readonly timers: ReadonlySet<ProcessTimer>;
|
||||
readonly terminal: Pick<IPty, "pid"> | undefined;
|
||||
@@ -712,68 +774,24 @@ export const releaseProcessResources = async (options: {
|
||||
: "renderer dispose failed",
|
||||
};
|
||||
}
|
||||
let ownedProcessGroup: ProcessCaptureCleanupReport["owned_process_group"] = {
|
||||
state: options.terminal === undefined ? "not_required" : "cleaned",
|
||||
reason: null,
|
||||
};
|
||||
if (options.terminal !== undefined) {
|
||||
if (host.platform === "win32") {
|
||||
ownedProcessGroup = {
|
||||
state: "unverified",
|
||||
reason:
|
||||
"owned process cleanup is unverifiable on Windows without process-job authority",
|
||||
};
|
||||
} else {
|
||||
const terminalPid = options.terminal.pid;
|
||||
const relation = {
|
||||
leaderPid: terminalPid,
|
||||
processGroupId: terminalPid,
|
||||
...(options.sampledProcessGroupIds === undefined
|
||||
? {}
|
||||
: { sampledProcessGroupIds: options.sampledProcessGroupIds }),
|
||||
};
|
||||
const cleaned = await host.cleanupProcessGroup({
|
||||
runId: options.runId,
|
||||
leaderPid: terminalPid,
|
||||
processGroupId: terminalPid,
|
||||
sweepTokenOwnedProcesses: true,
|
||||
...(options.sampledProcessGroupIds === undefined
|
||||
? {}
|
||||
: { sampledProcessGroupIds: options.sampledProcessGroupIds }),
|
||||
...(options.captureBaseline === undefined
|
||||
? {}
|
||||
: { captureBaseline: options.captureBaseline }),
|
||||
});
|
||||
const unverified = [...(cleaned.unverified ?? [])];
|
||||
if (!cleaned.cleaned) {
|
||||
ownedProcessGroup = { state: "unverified", reason: cleaned.reason };
|
||||
} else {
|
||||
const verified = await verifyTokenOwnedProcessesUntilSettled(() =>
|
||||
host.verifyTokenOwnedProcesses(
|
||||
options.runId,
|
||||
undefined,
|
||||
options.captureBaseline,
|
||||
relation,
|
||||
),
|
||||
const ownedProcessGroup =
|
||||
options.terminal === undefined
|
||||
? { state: "not_required" as const, reason: null }
|
||||
: await releaseCapturedProcessGroup(
|
||||
{
|
||||
runId: options.runId,
|
||||
leaderPid: options.terminal.pid,
|
||||
processGroupId: options.terminal.pid,
|
||||
sweepTokenOwnedProcesses: true,
|
||||
...(options.sampledProcessGroupIds === undefined
|
||||
? {}
|
||||
: { sampledProcessGroupIds: options.sampledProcessGroupIds }),
|
||||
...(options.captureBaseline === undefined
|
||||
? {}
|
||||
: { captureBaseline: options.captureBaseline }),
|
||||
},
|
||||
host,
|
||||
);
|
||||
unverified.push(...(verified.unverified ?? []));
|
||||
if (!verified.cleaned)
|
||||
ownedProcessGroup = { state: "unverified", reason: verified.reason };
|
||||
}
|
||||
if (unverified.length > 0)
|
||||
ownedProcessGroup = {
|
||||
...ownedProcessGroup,
|
||||
unverified_processes: [
|
||||
...new Map(
|
||||
unverified.map(({ pid, diagnostic }) => [
|
||||
`${String(pid)}:${diagnostic}`,
|
||||
{ pid, reason: diagnostic },
|
||||
]),
|
||||
).values(),
|
||||
],
|
||||
};
|
||||
}
|
||||
}
|
||||
let temporaryRoot: ProcessCaptureCleanupReport["temporary_root"] = {
|
||||
state: "cleaned",
|
||||
reason: null,
|
||||
@@ -1018,16 +1036,36 @@ export const prepareProcessCapture = async (
|
||||
await host.prepareOwnershipInspector?.(signal);
|
||||
assertNotCancelled(signal);
|
||||
const before = await captureSnapshot(scenario, signal);
|
||||
const runId = randomUUID();
|
||||
const temporaryRoot = await host.createTemporaryRoot();
|
||||
try {
|
||||
assertNotCancelled(signal);
|
||||
const runId = randomUUID();
|
||||
const ownershipBaseline =
|
||||
(await host.captureOwnershipBaseline?.(signal)) ?? [];
|
||||
assertNotCancelled(signal);
|
||||
return { temporaryRoot, runId, ownershipBaseline, before };
|
||||
} catch (cause: unknown) {
|
||||
await host.cleanup(temporaryRoot);
|
||||
const cleanup = await releaseProcessResources({
|
||||
timers: new Set(),
|
||||
terminal: undefined,
|
||||
renderer: undefined,
|
||||
runId,
|
||||
temporaryRoot,
|
||||
host: { ...processCaptureCleanupHost, removeTemporaryRoot: host.cleanup },
|
||||
});
|
||||
resolveProcessResult(
|
||||
undefined,
|
||||
normalizeCaptureFailure(cause, signal),
|
||||
cleanup,
|
||||
createProcessCaptureObservationBuffer({
|
||||
frames: [],
|
||||
interactions: [],
|
||||
samples: [],
|
||||
eventJournal: [],
|
||||
before,
|
||||
}),
|
||||
{ scenario },
|
||||
);
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -3,7 +3,6 @@ import { processScenarioSchema } from "../../domain/process/processScenario.js";
|
||||
import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js";
|
||||
import {
|
||||
captureProcessScenario,
|
||||
normalizeCaptureFailure,
|
||||
ProcessCaptureError,
|
||||
} from "./ProcessHarness.js";
|
||||
import { settleProcessCaptureJournal } from "./ProcessCaptureLifecycle.js";
|
||||
@@ -16,14 +15,105 @@ import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../domain/process/processCaptu
|
||||
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
|
||||
import { emptyProcessCapture } from "../../domain/process/processCapture.fixture.js";
|
||||
import { analysisErrorProjectionSchema } from "../../contracts/errorSchemas.js";
|
||||
import { processCaptureCancelled } from "./ProcessCaptureError.js";
|
||||
import {
|
||||
normalizeCaptureFailure,
|
||||
processCaptureCancelled,
|
||||
} from "./ProcessCaptureError.js";
|
||||
import {
|
||||
releaseProcessResources,
|
||||
prepareProcessCapture,
|
||||
resolveProcessResult,
|
||||
type ProcessCaptureCleanupHost,
|
||||
} from "./ProcessCaptureLifecycle.js";
|
||||
import { DarwinProcessOwnershipInspectionError } from "../DarwinProcessRunTokenReader.js";
|
||||
|
||||
it("retains cancellation and cleanup facts when ownership baseline inspection aborts", async () => {
|
||||
const controller = new AbortController();
|
||||
const scenario = processScenarioSchema.parse({
|
||||
executable: process.execPath,
|
||||
});
|
||||
await expect(
|
||||
prepareProcessCapture(
|
||||
scenario,
|
||||
controller.signal,
|
||||
async () => ({ files: [], truncated: false, completeRoots: [] }),
|
||||
{
|
||||
createTemporaryRoot: async () => "/fixture/allocated-root",
|
||||
captureOwnershipBaseline: async () => {
|
||||
controller.abort();
|
||||
controller.signal.throwIfAborted();
|
||||
return [];
|
||||
},
|
||||
cleanup: async () => undefined,
|
||||
},
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
reason: "cancelled",
|
||||
message: "process capture was cancelled",
|
||||
cleanupReport: {
|
||||
temporary_root: { state: "cleaned", reason: null },
|
||||
},
|
||||
partialObservation: {
|
||||
observations: {
|
||||
filesystem_snapshots: {
|
||||
before: {
|
||||
state: "available",
|
||||
value: { files: [], truncated: false },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps prelaunch snapshot evidence and the ownership failure when root cleanup throws", async () => {
|
||||
const ownershipFailure = new Error("process identity baseline denied");
|
||||
const scenario = processScenarioSchema.parse({
|
||||
executable: process.execPath,
|
||||
});
|
||||
try {
|
||||
await prepareProcessCapture(
|
||||
scenario,
|
||||
undefined,
|
||||
async () => ({ files: [], truncated: true, completeRoots: [] }),
|
||||
{
|
||||
createTemporaryRoot: async () => "/fixture/allocated-root",
|
||||
captureOwnershipBaseline: async () => {
|
||||
throw ownershipFailure;
|
||||
},
|
||||
cleanup: async () => {
|
||||
throw new Error("root removal denied");
|
||||
},
|
||||
},
|
||||
);
|
||||
throw new Error("expected preparation failure");
|
||||
} catch (cause: unknown) {
|
||||
if (!(cause instanceof ProcessCaptureError)) throw cause;
|
||||
expect(cause.cause).toBe(ownershipFailure);
|
||||
expect(
|
||||
analysisErrorProjectionSchema.parse(projectAnalysisError(cause)),
|
||||
).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
execution_failure: ownershipFailure.message,
|
||||
cleanup_report: {
|
||||
temporary_root: { state: "failed", reason: "root removal denied" },
|
||||
},
|
||||
partial_observation: {
|
||||
observations: {
|
||||
filesystem_snapshots: {
|
||||
before: {
|
||||
state: "available",
|
||||
value: { files: [], truncated: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects legacy replay output instead of silently discarding it", () => {
|
||||
expect(
|
||||
processCaptureSchema.safeParse({
|
||||
@@ -100,6 +190,74 @@ it("keeps empty cleanup exception messages actionable in the report", async () =
|
||||
expect(report.temporary_root).toEqual({ state: "failed", reason: "Error" });
|
||||
});
|
||||
|
||||
it.each(["termination", "verification"] as const)(
|
||||
"retains observations and releases the temporary root when process %s throws",
|
||||
async (stage) => {
|
||||
const cleanupFailure = new Error(`${stage} inspection failed`);
|
||||
const removeTemporaryRoot = vi.fn(async () => undefined);
|
||||
const host: ProcessCaptureCleanupHost = {
|
||||
platform: "linux",
|
||||
cleanupProcessGroup: async () => {
|
||||
if (stage === "termination") throw cleanupFailure;
|
||||
return {
|
||||
cleaned: true,
|
||||
signaled: true,
|
||||
unverified: [{ pid: 900, diagnostic: "environment unavailable" }],
|
||||
};
|
||||
},
|
||||
verifyTokenOwnedProcesses: async () => {
|
||||
throw cleanupFailure;
|
||||
},
|
||||
removeTemporaryRoot,
|
||||
};
|
||||
const cleanup = await releaseProcessResources({
|
||||
timers: new Set(),
|
||||
terminal: { pid: 321 },
|
||||
renderer: undefined,
|
||||
runId: "fixture-run",
|
||||
temporaryRoot: "/fixture/root",
|
||||
host,
|
||||
});
|
||||
|
||||
expect(removeTemporaryRoot).toHaveBeenCalledWith("/fixture/root");
|
||||
expect(cleanup.temporary_root).toEqual({ state: "cleaned", reason: null });
|
||||
expect(cleanup.owned_process_group).toMatchObject({
|
||||
state: "failed",
|
||||
reason: cleanupFailure.message,
|
||||
});
|
||||
if (stage === "verification")
|
||||
expect(cleanup.owned_process_group.unverified_processes).toEqual([
|
||||
{ pid: 900, reason: "environment unavailable" },
|
||||
]);
|
||||
|
||||
const executionFailure = new Error("capture snapshot failed");
|
||||
const capture = parseProcessCapture({
|
||||
...emptyProcessCapture(),
|
||||
frames: [{ sequence: 0, at_ms: 0, data: "collected before failure" }],
|
||||
event_journal: [],
|
||||
});
|
||||
try {
|
||||
resolveProcessResult(capture, executionFailure, cleanup);
|
||||
throw new Error("expected cleanup failure");
|
||||
} catch (cause: unknown) {
|
||||
if (!(cause instanceof ProcessCaptureError)) throw cause;
|
||||
expect(cause.cause).toBe(executionFailure);
|
||||
expect(
|
||||
analysisErrorProjectionSchema.parse(projectAnalysisError(cause)),
|
||||
).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
cleanup_report: cleanup,
|
||||
execution_failure: "capture snapshot failed",
|
||||
partial_observation: {
|
||||
capture: { frames: [{ data: "collected before failure" }] },
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("waits for token-owned processes to exit after one cleanup signal", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
|
||||
@@ -16,6 +16,7 @@ import { type AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import {
|
||||
describeProcessCaptureExecutionFailure,
|
||||
ProcessCaptureError,
|
||||
normalizeCaptureFailure,
|
||||
processCaptureCancelled,
|
||||
} from "./ProcessCaptureError.js";
|
||||
export { ProcessCaptureError } from "./ProcessCaptureError.js";
|
||||
@@ -55,7 +56,6 @@ import { makeProcessCaptureEnvironment } from "./ProcessCaptureEnvironment.js";
|
||||
import { classifyFilesystemEffects } from "./ProcessFilesystemEffects.js";
|
||||
import { processCaptureOwnershipUnavailableReason } from "./ProcessCaptureCapability.js";
|
||||
import type { ProcessOwnershipBaseline } from "../ProcessOwnership.js";
|
||||
import { DarwinProcessOwnershipInspectionError } from "../DarwinProcessRunTokenReader.js";
|
||||
export { probeProcessCaptureCapability } from "./ProcessCaptureCapability.js";
|
||||
|
||||
interface StartedCaptureRuntime {
|
||||
@@ -89,7 +89,6 @@ const cleanupFailedStartup = async (options: {
|
||||
options.observations.process_samples.value,
|
||||
).filter((groupId) => groupId !== options.terminal?.pid)
|
||||
: undefined;
|
||||
options.terminal?.kill("SIGKILL");
|
||||
if (options.observations !== undefined && options.renderer !== undefined) {
|
||||
try {
|
||||
options.observations.rendered_frames = {
|
||||
@@ -322,23 +321,6 @@ const finishProcessRun = async (options: {
|
||||
);
|
||||
};
|
||||
|
||||
/** Preserve typed process-inspection preflight failures at the capture boundary. */
|
||||
export const normalizeCaptureFailure = (
|
||||
cause: unknown,
|
||||
signal: AbortSignal | undefined,
|
||||
): unknown => {
|
||||
if (cause instanceof ProcessCaptureError) return cause;
|
||||
if (cause instanceof DarwinProcessOwnershipInspectionError)
|
||||
return new ProcessCaptureError(cause.message, { cause });
|
||||
if (
|
||||
signal?.aborted === true &&
|
||||
(cause === signal.reason ||
|
||||
(cause instanceof Error && cause.name === "AbortError"))
|
||||
)
|
||||
return processCaptureCancelled();
|
||||
return cause;
|
||||
};
|
||||
|
||||
const completeCapture = async (options: {
|
||||
readonly scenario: ProcessScenario;
|
||||
readonly hostPlatform: NodeJS.Platform;
|
||||
@@ -572,7 +554,6 @@ const runProcessScenario = async (
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
runtime?.terminal.kill("SIGKILL");
|
||||
executionFailure = normalizeCaptureFailure(cause, signal);
|
||||
if (
|
||||
runtime !== undefined &&
|
||||
|
||||
Reference in New Issue
Block a user