feat(process): bound a finalization interval before forced capture timeout
Add optional finalization_ms to keep observing a captured root after SIGTERM, record the actual finalizer exit and each signal attempt, and escalate once when needed. Bind the initial root identity to captured ownership and preserve observations through cleanup uncertainty. Fixes #1253. Co-authored-by: Mykola Dementiev <16836724+nikolay-dementiev@users.noreply.github.com> Co-authored-by: N0zoM1z0 <161784452+N0zoM1z0@users.noreply.github.com>
This commit is contained in:
co-authored by
Mykola Dementiev
N0zoM1z0
parent
1e51c732bb
commit
c1efa6467d
@@ -0,0 +1,560 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { access, readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { expect, onTestFinished } from "vitest";
|
||||
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { toolContract } from "../../../src/contracts/toolContracts.js";
|
||||
import { partialProcessCaptureObservationSchema } from "../../../src/domain/process/processCapture.js";
|
||||
import { observeProcessStartIdentity } from "../../../src/process/ProcessOwnershipObservation.js";
|
||||
import {
|
||||
parseProcessCapture,
|
||||
type ProcessCapture,
|
||||
} from "../../../src/domain/process/processCaptureParsing.js";
|
||||
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
|
||||
import { runCliJson } from "../../fixtures/cliJsonProcess.js";
|
||||
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { itWithCaptureCapability as captureTest } from "../../boundary/process/processCaptureCapability.js";
|
||||
import { expectSerializedUnverifiedHostCleanup } from "../../support/hostCleanup.js";
|
||||
|
||||
const finalizationFixture = fileURLToPath(
|
||||
new URL("../../fixtures/processFinalization.mjs", import.meta.url),
|
||||
);
|
||||
|
||||
type CaptureScenario = Record<string, unknown>;
|
||||
type CaptureOutcome =
|
||||
| { readonly kind: "capture"; readonly capture: ProcessCapture }
|
||||
| { readonly kind: "partial"; readonly partial: unknown };
|
||||
|
||||
const captureScenario = (
|
||||
mode: "cooperative" | "ignoring" | "descendant",
|
||||
root: string,
|
||||
additions: CaptureScenario = {},
|
||||
finalExitCode?: number,
|
||||
): CaptureScenario => ({
|
||||
executable: process.execPath,
|
||||
arguments: [
|
||||
finalizationFixture,
|
||||
mode,
|
||||
root,
|
||||
...(finalExitCode === undefined ? [] : [String(finalExitCode)]),
|
||||
],
|
||||
working_directory: root,
|
||||
filesystem_observation_paths: [root],
|
||||
idle_timeout_ms: 10_000,
|
||||
...additions,
|
||||
});
|
||||
|
||||
const captureViaCli = async (
|
||||
root: string,
|
||||
scenario: CaptureScenario,
|
||||
): Promise<CaptureOutcome> => {
|
||||
const scenarioPath = join(root, "scenario.json");
|
||||
await writeFile(scenarioPath, JSON.stringify(scenario));
|
||||
const document = await runCliJson([
|
||||
"capture-process",
|
||||
scenarioPath,
|
||||
"--format",
|
||||
"json",
|
||||
]);
|
||||
if (
|
||||
typeof document === "object" &&
|
||||
document !== null &&
|
||||
"code" in document &&
|
||||
document.code === "cleanup_incomplete"
|
||||
)
|
||||
return {
|
||||
kind: "partial",
|
||||
partial: expectSerializedUnverifiedHostCleanup({ error: document }),
|
||||
};
|
||||
if (typeof document === "object" && document !== null && "code" in document)
|
||||
throw new Error(
|
||||
`CLI capture returned an unexpected error: ${JSON.stringify(document).slice(0, 1_000)}`,
|
||||
);
|
||||
return {
|
||||
kind: "capture",
|
||||
capture: parseProcessCapture(parseEvidence(document).normalized_result),
|
||||
};
|
||||
};
|
||||
|
||||
const captureViaMcp = async (
|
||||
scenario: CaptureScenario,
|
||||
): Promise<CaptureOutcome> => {
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const response = await call("capture_process_scenario", scenario);
|
||||
if (response.isError === true) {
|
||||
const parsed = parseMcpToolError(response);
|
||||
if (parsed.error.code === "cleanup_incomplete")
|
||||
return {
|
||||
kind: "partial",
|
||||
partial: expectSerializedUnverifiedHostCleanup(parsed),
|
||||
};
|
||||
throw new Error(
|
||||
`MCP capture returned an unexpected error: ${JSON.stringify(parsed).slice(0, 1_000)}`,
|
||||
);
|
||||
}
|
||||
return {
|
||||
kind: "capture",
|
||||
capture: parseProcessCapture(
|
||||
parseEvidence(
|
||||
toolContract("capture_process_scenario").outputSchema.parse(
|
||||
response.structuredContent,
|
||||
),
|
||||
).normalized_result,
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
const waitFor = async (
|
||||
description: string,
|
||||
predicate: () => Promise<boolean>,
|
||||
deadlineMs = 7_500,
|
||||
): Promise<void> => {
|
||||
const deadline = Date.now() + deadlineMs;
|
||||
while (!(await predicate())) {
|
||||
if (Date.now() >= deadline)
|
||||
throw new Error(`timed out waiting for ${description}`);
|
||||
await delay(25);
|
||||
}
|
||||
};
|
||||
|
||||
const fixturePid = async (root: string): Promise<number> => {
|
||||
let pid = Number.NaN;
|
||||
await waitFor("the finalization fixture PID", async () => {
|
||||
try {
|
||||
pid = Number.parseInt(await readFile(join(root, "pid.txt"), "utf8"), 10);
|
||||
return Number.isSafeInteger(pid) && pid > 0;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
return pid;
|
||||
};
|
||||
|
||||
const waitForFinalization = async (root: string): Promise<number> => {
|
||||
// The fixture writes the PID before it can receive SIGTERM, so once the
|
||||
// marker exists the PID file is complete.
|
||||
await waitFor("the finalization fixture to receive SIGTERM", async () => {
|
||||
try {
|
||||
await access(join(root, "sigterm-received"));
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
return fixturePid(root);
|
||||
};
|
||||
|
||||
const waitForProcessExit = async (pid: number): Promise<void> =>
|
||||
waitFor(`finalization fixture ${String(pid)} to exit`, async () => {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return false;
|
||||
} catch (error: unknown) {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"code" in error &&
|
||||
error.code === "ESRCH"
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const finalizationFromPartial = (partial: unknown) => {
|
||||
const parsed = partialProcessCaptureObservationSchema.parse(partial);
|
||||
if ("capture" in parsed) return parsed.capture.exit.finalization;
|
||||
return parsed.observations.exit.state === "available"
|
||||
? parsed.observations.exit.value.finalization
|
||||
: undefined;
|
||||
};
|
||||
|
||||
const completedCaptureFromOutcome = (outcome: CaptureOutcome) => {
|
||||
if (outcome.kind === "capture") return outcome.capture;
|
||||
const partial = partialProcessCaptureObservationSchema.parse(outcome.partial);
|
||||
expect(partial.execution_failure).toBeNull();
|
||||
if (!("capture" in partial))
|
||||
throw new Error("host cleanup uncertainty omitted the completed capture");
|
||||
return partial.capture;
|
||||
};
|
||||
|
||||
const expectCooperativeFinalization = (
|
||||
outcome: CaptureOutcome,
|
||||
expectedExitCode = 0,
|
||||
): void => {
|
||||
const capture = completedCaptureFromOutcome(outcome);
|
||||
expect(capture.exit.reason, "the deadline remains the exit reason").toBe(
|
||||
"timeout",
|
||||
);
|
||||
expect(capture.exit.code, "a deadline exit has no normal code").toBeNull();
|
||||
expect(
|
||||
capture.exit.finalization,
|
||||
"the cooperative target receives only SIGTERM",
|
||||
).toMatchObject({
|
||||
requested_ms: 1_500,
|
||||
signals: [{ signal: "SIGTERM", delivery: "signaled" }],
|
||||
});
|
||||
expect(
|
||||
capture.exit.finalization?.signals,
|
||||
"cooperative finalization does not send SIGKILL",
|
||||
).toHaveLength(1);
|
||||
expect(
|
||||
capture.exit.finalization?.elapsed_ms,
|
||||
"the cooperative target exits within its interval",
|
||||
).toBeLessThan(1_500);
|
||||
expect(
|
||||
capture.exit.finalization?.exit_code,
|
||||
"the code the finalizer exited with is recorded",
|
||||
).toBe(expectedExitCode);
|
||||
expect(
|
||||
capture.frames.map(({ data }) => data).join(""),
|
||||
"finalization output is captured",
|
||||
).toContain("finalized");
|
||||
expect(
|
||||
capture.files_after.find(({ path }) => path.endsWith("final.json"))?.sha256,
|
||||
"the final filesystem snapshot hashes the final report",
|
||||
).toMatch(/^[0-9a-f]{64}$/u);
|
||||
expect(
|
||||
capture.manifest.scenario.finalization_ms,
|
||||
"the scenario commitment retains finalization_ms",
|
||||
).toBe(1_500);
|
||||
expect(
|
||||
capture.manifest.comparison_contract.finalization_ms,
|
||||
"the comparison contract retains finalization_ms",
|
||||
).toBe(1_500);
|
||||
};
|
||||
|
||||
const expectIgnoringFinalization = (outcome: CaptureOutcome): void => {
|
||||
const capture = completedCaptureFromOutcome(outcome);
|
||||
expect(capture.exit.reason, "the deadline remains the exit reason").toBe(
|
||||
"timeout",
|
||||
);
|
||||
expect(capture.exit.signal, "the ignoring child ends on SIGKILL").toBe(9);
|
||||
expect(
|
||||
capture.exit.finalization?.signals,
|
||||
"SIGTERM is followed by exactly one SIGKILL",
|
||||
).toMatchObject([
|
||||
{ signal: "SIGTERM", delivery: "signaled" },
|
||||
{ signal: "SIGKILL", delivery: "signaled" },
|
||||
]);
|
||||
expect(
|
||||
capture.exit.finalization?.signals,
|
||||
"the ignoring child has exactly two finalization attempts",
|
||||
).toHaveLength(2);
|
||||
expect(
|
||||
capture.exit.finalization?.signals[1]?.sent_at_ms,
|
||||
"SIGKILL waits for the requested interval",
|
||||
).toBeGreaterThanOrEqual(1_500);
|
||||
expect(
|
||||
capture.exit.finalization?.elapsed_ms,
|
||||
"the elapsed finalization duration is observed",
|
||||
).toEqual(expect.any(Number));
|
||||
expect(
|
||||
capture.exit.finalization?.exit_code,
|
||||
"an exit ended by SIGKILL records no code",
|
||||
).toBeNull();
|
||||
expect(
|
||||
capture.files_after.find(({ path }) => path.endsWith("final.json")),
|
||||
"an ignoring child does not write a final report",
|
||||
).toBeUndefined();
|
||||
};
|
||||
|
||||
captureTest.each(["CLI", "MCP"] as const)(
|
||||
"captures a cooperative finalizer through the compiled %s workflow",
|
||||
async (adapter) => {
|
||||
const root = await createTestTempDirectory("rea-finalization-accept-");
|
||||
const scenario = captureScenario("cooperative", root, {
|
||||
timeout_ms: 1_500,
|
||||
finalization_ms: 1_500,
|
||||
});
|
||||
const outcome =
|
||||
adapter === "CLI"
|
||||
? await captureViaCli(root, scenario)
|
||||
: await captureViaMcp(scenario);
|
||||
expectCooperativeFinalization(outcome);
|
||||
},
|
||||
20_000,
|
||||
);
|
||||
|
||||
captureTest.each(["CLI", "MCP"] as const)(
|
||||
"records the non-zero exit code of a finalizer through the compiled %s workflow",
|
||||
async (adapter) => {
|
||||
const root = await createTestTempDirectory("rea-finalization-accept-");
|
||||
const scenario = captureScenario(
|
||||
"cooperative",
|
||||
root,
|
||||
{ timeout_ms: 1_500, finalization_ms: 1_500 },
|
||||
3,
|
||||
);
|
||||
const outcome =
|
||||
adapter === "CLI"
|
||||
? await captureViaCli(root, scenario)
|
||||
: await captureViaMcp(scenario);
|
||||
expectCooperativeFinalization(outcome, 3);
|
||||
},
|
||||
20_000,
|
||||
);
|
||||
|
||||
captureTest.each(["CLI", "MCP"] as const)(
|
||||
"forces SIGKILL after the finalization interval through the compiled %s workflow",
|
||||
async (adapter) => {
|
||||
const root = await createTestTempDirectory("rea-finalization-accept-");
|
||||
const scenario = captureScenario("ignoring", root, {
|
||||
timeout_ms: 1_500,
|
||||
finalization_ms: 1_500,
|
||||
});
|
||||
const outcome =
|
||||
adapter === "CLI"
|
||||
? await captureViaCli(root, scenario)
|
||||
: await captureViaMcp(scenario);
|
||||
expectIgnoringFinalization(outcome);
|
||||
},
|
||||
20_000,
|
||||
);
|
||||
|
||||
captureTest(
|
||||
"retains finalization facts with omitted digests and cleans the owned descendant",
|
||||
async () => {
|
||||
const root = await createTestTempDirectory("rea-finalization-descendant-");
|
||||
const childDirectory = join(root, "descendant");
|
||||
const outcome = await captureViaMcp(
|
||||
captureScenario("descendant", root, {
|
||||
timeout_ms: 1_500,
|
||||
finalization_ms: 1_500,
|
||||
settle_ms: 100,
|
||||
limits: { file_bytes: 1 },
|
||||
}),
|
||||
);
|
||||
const capture = completedCaptureFromOutcome(outcome);
|
||||
expect(capture.exit).toMatchObject({
|
||||
reason: "timeout",
|
||||
code: null,
|
||||
finalization: {
|
||||
exit_code: 0,
|
||||
signals: [{ signal: "SIGTERM", delivery: "signaled" }],
|
||||
},
|
||||
});
|
||||
expect(capture.exit.finalization?.signals).toHaveLength(1);
|
||||
expect(capture.settlement).toMatchObject({
|
||||
state: "alive_at_deadline",
|
||||
cleanup_outcome: "cleaned",
|
||||
});
|
||||
expect(capture.frames.map(({ data }) => data).join("")).toContain(
|
||||
"finalized",
|
||||
);
|
||||
const final = capture.files_after.find(({ path }) =>
|
||||
path.endsWith(":final.json"),
|
||||
);
|
||||
expect(final).toMatchObject({ type: "file", sha256: null });
|
||||
expect(capture.truncation_details.filesystem_after).toMatchObject({
|
||||
enumeration_truncated: false,
|
||||
hash_budget_bytes: 1,
|
||||
hash_omissions: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
path: final?.path,
|
||||
reason: "file_bytes_budget",
|
||||
}),
|
||||
]),
|
||||
});
|
||||
expect(
|
||||
JSON.parse(await readFile(join(root, "final.json"), "utf8")),
|
||||
).toEqual({
|
||||
phase: "final",
|
||||
});
|
||||
await expect(
|
||||
access(join(childDirectory, "sigterm-received")),
|
||||
).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
const childPid = await fixturePid(childDirectory);
|
||||
await expect(
|
||||
observeProcessStartIdentity(childPid),
|
||||
).resolves.toBeUndefined();
|
||||
},
|
||||
20_000,
|
||||
);
|
||||
|
||||
captureTest.each(["CLI", "MCP"] as const)(
|
||||
"keeps the default identity through the compiled %s workflow without finalization_ms",
|
||||
async (adapter) => {
|
||||
const root = await createTestTempDirectory("rea-finalization-default-");
|
||||
const scenario = captureScenario("ignoring", root, { timeout_ms: 500 });
|
||||
const outcome =
|
||||
adapter === "CLI"
|
||||
? await captureViaCli(root, scenario)
|
||||
: await captureViaMcp(scenario);
|
||||
if (outcome.kind === "partial") {
|
||||
expect(
|
||||
finalizationFromPartial(outcome.partial),
|
||||
"the cleanup-flake partial observation has no default finalization",
|
||||
).toBeUndefined();
|
||||
return;
|
||||
}
|
||||
expect(
|
||||
outcome.capture.exit,
|
||||
"default captures have no finalization evidence",
|
||||
).not.toHaveProperty("finalization");
|
||||
expect(
|
||||
outcome.capture.manifest.scenario,
|
||||
"the committed scenario keeps its legacy identity",
|
||||
).not.toHaveProperty("finalization_ms");
|
||||
expect(
|
||||
outcome.capture.manifest.comparison_contract,
|
||||
"the comparison contract keeps its legacy identity",
|
||||
).not.toHaveProperty("finalization_ms");
|
||||
},
|
||||
20_000,
|
||||
);
|
||||
|
||||
captureTest.each(["CLI", "MCP"] as const)(
|
||||
"rejects an unrepresentable combined capture budget through the compiled %s workflow",
|
||||
async (adapter) => {
|
||||
const root = await createTestTempDirectory("rea-finalization-budget-");
|
||||
const scenario = captureScenario("cooperative", root, {
|
||||
timeout_ms: Number.MAX_SAFE_INTEGER,
|
||||
finalization_ms: 1,
|
||||
settle_ms: 0,
|
||||
});
|
||||
if (adapter === "CLI") {
|
||||
const scenarioPath = join(root, "scenario.json");
|
||||
await writeFile(scenarioPath, JSON.stringify(scenario));
|
||||
const response = await runCliJson([
|
||||
"capture-process",
|
||||
scenarioPath,
|
||||
"--format",
|
||||
"json",
|
||||
]);
|
||||
expect(
|
||||
JSON.stringify(response),
|
||||
"CLI rejects the combined budget",
|
||||
).toContain("timeout_ms + finalization_ms + settle_ms");
|
||||
} else {
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const response = await call("capture_process_scenario", scenario);
|
||||
expect(response.isError, "MCP rejects the combined budget").toBe(true);
|
||||
expect(
|
||||
JSON.stringify(response),
|
||||
"MCP explains the combined budget",
|
||||
).toContain("timeout_ms + finalization_ms + settle_ms");
|
||||
}
|
||||
await expect(
|
||||
access(join(root, "periodic.json")),
|
||||
"invalid budgets are rejected before launching the fixture",
|
||||
).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
|
||||
captureTest(
|
||||
"cancels the compiled CLI and MCP workflows during finalization without waiting for grace",
|
||||
async () => {
|
||||
const cliRoot = await createTestTempDirectory(
|
||||
"rea-finalization-cli-cancel-",
|
||||
);
|
||||
const cliScenarioPath = join(cliRoot, "scenario.json");
|
||||
await writeFile(
|
||||
cliScenarioPath,
|
||||
JSON.stringify(
|
||||
captureScenario("ignoring", cliRoot, {
|
||||
timeout_ms: 300,
|
||||
finalization_ms: 20_000,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const cli = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
"scripts/rea.mjs",
|
||||
"capture-process",
|
||||
cliScenarioPath,
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
{ stdio: ["ignore", "pipe", "pipe"] },
|
||||
);
|
||||
let stdout = "";
|
||||
cli.stdout.on("data", (chunk: Buffer) => {
|
||||
stdout += chunk.toString();
|
||||
});
|
||||
cli.stderr.resume();
|
||||
const cliClosed = new Promise<{ readonly code: number | null }>(
|
||||
(resolve, reject) => {
|
||||
cli.once("error", reject);
|
||||
cli.once("close", (code) => resolve({ code }));
|
||||
},
|
||||
);
|
||||
onTestFinished(async () => {
|
||||
if (cli.exitCode === null && cli.signalCode === null) cli.kill("SIGKILL");
|
||||
await cliClosed;
|
||||
});
|
||||
const cliFixturePid = await waitForFinalization(cliRoot);
|
||||
const cliStarted = Date.now();
|
||||
cli.kill("SIGINT");
|
||||
const cliExit = await cliClosed;
|
||||
await waitForProcessExit(cliFixturePid);
|
||||
expect(cliExit.code, "SIGINT produces the CLI cancellation status").toBe(
|
||||
130,
|
||||
);
|
||||
expect(
|
||||
Date.now() - cliStarted,
|
||||
"CLI cancellation does not wait for the grace interval",
|
||||
).toBeLessThan(8_000);
|
||||
const cliDocument: unknown = JSON.parse(stdout);
|
||||
if (
|
||||
typeof cliDocument === "object" &&
|
||||
cliDocument !== null &&
|
||||
"code" in cliDocument &&
|
||||
cliDocument.code === "cleanup_incomplete"
|
||||
) {
|
||||
const partial = expectSerializedUnverifiedHostCleanup({
|
||||
error: cliDocument,
|
||||
});
|
||||
expect(
|
||||
finalizationFromPartial(partial),
|
||||
"CLI cleanup-flake partial observation records SIGKILL",
|
||||
).toMatchObject({
|
||||
signals: [{ signal: "SIGTERM" }, { signal: "SIGKILL" }],
|
||||
});
|
||||
} else {
|
||||
expect(cliDocument, "CLI returns a typed cancelled result").toMatchObject(
|
||||
{
|
||||
code: "cancelled",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const mcpRoot = await createTestTempDirectory(
|
||||
"rea-finalization-mcp-cancel-",
|
||||
);
|
||||
const { client } = await connectLocalToolsMcp();
|
||||
const controller = new AbortController();
|
||||
const call = client.callTool(
|
||||
{
|
||||
name: "capture_process_scenario",
|
||||
arguments: captureScenario("ignoring", mcpRoot, {
|
||||
timeout_ms: 300,
|
||||
finalization_ms: 20_000,
|
||||
}),
|
||||
},
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
const mcpFixturePid = await waitForFinalization(mcpRoot);
|
||||
const mcpStarted = Date.now();
|
||||
controller.abort(new Error("cancel finalization acceptance fixture"));
|
||||
await expect(
|
||||
call,
|
||||
"MCP cancellation rejects the pending SDK request",
|
||||
).rejects.toThrow("cancel finalization acceptance fixture");
|
||||
await waitForProcessExit(mcpFixturePid);
|
||||
await expect(
|
||||
client.listTools(),
|
||||
"the server accepts a follow-up request after cancelling the capture",
|
||||
).resolves.toMatchObject({ tools: expect.any(Array) });
|
||||
expect(
|
||||
Date.now() - mcpStarted,
|
||||
"MCP cancellation does not wait for the grace interval",
|
||||
).toBeLessThan(8_000);
|
||||
},
|
||||
20_000,
|
||||
);
|
||||
@@ -8,10 +8,14 @@ import { expect } from "vitest";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { itWithCaptureCapability } from "./processCaptureCapability.js";
|
||||
|
||||
import { captureProcessScenario } from "../../../src/process/capture/ProcessHarness.js";
|
||||
import {
|
||||
captureProcessScenario,
|
||||
type FinalizationHost,
|
||||
} from "../../../src/process/capture/ProcessHarness.js";
|
||||
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
|
||||
import { snapshotRoots } from "../../../src/process/capture/FilesystemSnapshot.js";
|
||||
import { ProcessCaptureError } from "../../../src/process/capture/ProcessCaptureError.js";
|
||||
import { expectUnverifiedHostCleanup } from "../../support/hostCleanup.js";
|
||||
import {
|
||||
type ProcessCaptureCleanupHost,
|
||||
observeLaunchedExecutable,
|
||||
@@ -36,35 +40,6 @@ type PartialCapture = Extract<
|
||||
>["capture"];
|
||||
const emptyFilesystemCoverage =
|
||||
emptyProcessCapture().truncation_details.filesystem_before;
|
||||
const expectUnverifiedHostCleanup = (error: ProcessCaptureError): void => {
|
||||
const report = error.cleanupReport;
|
||||
expect(error.reason, error.message).toBe("cleanup_incomplete");
|
||||
expect(report?.owned_process_group.state).toBe("unverified");
|
||||
const [summary, diagnostics] = (
|
||||
report?.owned_process_group.reason ?? ""
|
||||
).split(": ");
|
||||
expect(summary).toMatch(
|
||||
/^process ownership token could not be read for [1-9][0-9]* live process\(es\)$/u,
|
||||
);
|
||||
const [breakdown, liveCandidates] =
|
||||
diagnostics?.split("; live candidates ") ?? [];
|
||||
const categories = breakdown?.split(", ") ?? [];
|
||||
expect(categories.length).toBeGreaterThan(0);
|
||||
const expectedCategory =
|
||||
process.platform === "linux"
|
||||
? /^environment_errno_(?:EACCES|EPERM)=[1-9][0-9]*$/u
|
||||
: /^environment_unavailable=[1-9][0-9]*$/u;
|
||||
for (const category of categories) expect(category).toMatch(expectedCategory);
|
||||
expect(liveCandidates).toMatch(
|
||||
/^(?:[1-9][0-9]*=(?:environment_unavailable|environment_errno_(?:EACCES|EPERM)))(?:, [1-9][0-9]*=(?:environment_unavailable|environment_errno_(?:EACCES|EPERM)))*$/u,
|
||||
);
|
||||
expect(report?.terminal_renderer.state).toBe("cleaned");
|
||||
expect(report?.temporary_root).toEqual({
|
||||
state: "unverified",
|
||||
reason: `temporary root retained because owned process cleanup is unverified: ${report?.owned_process_group.reason}`,
|
||||
});
|
||||
};
|
||||
|
||||
const captureObservations = (
|
||||
result: CaptureRun,
|
||||
): {
|
||||
@@ -289,6 +264,10 @@ itWithCaptureCapability(
|
||||
if (partial === undefined || !("observations" in partial))
|
||||
throw new Error("expected incomplete process observations");
|
||||
const observations = partial.observations;
|
||||
expect(
|
||||
Object.keys(observations),
|
||||
"a default scenario keeps the base observation keys through the run path",
|
||||
).not.toContain("finalization");
|
||||
expect(observations.frames.state).toBe("available");
|
||||
if (observations.frames.state !== "available")
|
||||
throw new Error("expected terminal output observations");
|
||||
@@ -484,6 +463,367 @@ itWithCaptureCapability(
|
||||
},
|
||||
);
|
||||
|
||||
const finalizationFixture = fileURLToPath(
|
||||
new URL("../../fixtures/processFinalization.mjs", import.meta.url),
|
||||
);
|
||||
|
||||
const captureFinalizationFixture = async (
|
||||
mode: "cooperative" | "ignoring" | "exits",
|
||||
scenario: Readonly<Record<string, unknown>>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<{ readonly result: CaptureRun; readonly root: string }> => {
|
||||
const root = await createTestTempDirectory("rea-finalization-");
|
||||
const result = await captureProcessScenario(
|
||||
parseProcessScenario({
|
||||
executable: process.execPath,
|
||||
arguments: [finalizationFixture, mode, root],
|
||||
working_directory: root,
|
||||
filesystem_observation_paths: [root],
|
||||
idle_timeout_ms: 10_000,
|
||||
...scenario,
|
||||
}),
|
||||
signal,
|
||||
);
|
||||
return { result, root };
|
||||
};
|
||||
|
||||
const observedFile = (
|
||||
capture: ProcessCapture | PartialCapture,
|
||||
name: string,
|
||||
): { readonly sha256: string | null } | undefined =>
|
||||
capture.files_after.find((file) => file.path.endsWith(name));
|
||||
|
||||
itWithCaptureCapability(
|
||||
"lets a cooperative target write its final report within the finalization interval",
|
||||
async () => {
|
||||
// The deadline leaves Node enough time to register its SIGTERM handler.
|
||||
const { result } = await captureFinalizationFixture("cooperative", {
|
||||
timeout_ms: 1_500,
|
||||
finalization_ms: 1_500,
|
||||
});
|
||||
const { capture } = captureObservations(result);
|
||||
|
||||
expect(capture.exit.reason, "initiating deadline stays the reason").toBe(
|
||||
"timeout",
|
||||
);
|
||||
expect(
|
||||
capture.exit.code,
|
||||
"a deadline reason never declares a normal exit code",
|
||||
).toBeNull();
|
||||
expect(capture.exit.finalization, "finalization is recorded").toMatchObject(
|
||||
{
|
||||
requested_ms: 1_500,
|
||||
exit_code: 0,
|
||||
signals: [{ signal: "SIGTERM", delivery: "signaled" }],
|
||||
},
|
||||
);
|
||||
expect(
|
||||
capture.exit.finalization?.elapsed_ms,
|
||||
"a cooperative exit ends before the interval does",
|
||||
).toBeLessThan(1_500);
|
||||
expect(
|
||||
observedFile(capture, "final.json")?.sha256,
|
||||
"final report is retained with a digest",
|
||||
).toMatch(/^[0-9a-f]{64}$/u);
|
||||
expect(
|
||||
capture.frames.map(({ data }) => data).join(""),
|
||||
"output written during finalization is captured",
|
||||
).toContain("finalized");
|
||||
},
|
||||
15_000,
|
||||
);
|
||||
|
||||
itWithCaptureCapability(
|
||||
"records no finalization when the target exits before any deadline",
|
||||
async () => {
|
||||
const { result } = await captureFinalizationFixture("exits", {
|
||||
finalization_ms: 1_500,
|
||||
});
|
||||
const { capture } = captureObservations(result);
|
||||
|
||||
expect(capture.exit.reason, "the target exited on its own").toBe("exited");
|
||||
expect(capture.exit.code, "its exit code is kept").toBe(0);
|
||||
expect(
|
||||
capture.exit,
|
||||
"no deadline fired, so nothing was finalized",
|
||||
).not.toHaveProperty("finalization");
|
||||
},
|
||||
15_000,
|
||||
);
|
||||
|
||||
itWithCaptureCapability(
|
||||
"starts finalization when the idle deadline fires",
|
||||
async () => {
|
||||
const { result } = await captureFinalizationFixture("cooperative", {
|
||||
timeout_ms: 10_000,
|
||||
idle_timeout_ms: 1_500,
|
||||
finalization_ms: 1_200,
|
||||
});
|
||||
const { capture } = captureObservations(result);
|
||||
|
||||
expect(capture.exit.reason, "idle deadline is the initiating reason").toBe(
|
||||
"idle_timeout",
|
||||
);
|
||||
expect(
|
||||
capture.exit.finalization,
|
||||
"idle finalization is recorded",
|
||||
).toMatchObject({
|
||||
requested_ms: 1_200,
|
||||
signals: [{ signal: "SIGTERM", delivery: "signaled" }],
|
||||
});
|
||||
expect(
|
||||
observedFile(capture, "final.json")?.sha256,
|
||||
"final report is retained with a digest",
|
||||
).toMatch(/^[0-9a-f]{64}$/u);
|
||||
},
|
||||
15_000,
|
||||
);
|
||||
|
||||
itWithCaptureCapability(
|
||||
"forces the kill when the target ignores the finalization signal",
|
||||
async () => {
|
||||
const { result } = await captureFinalizationFixture("ignoring", {
|
||||
timeout_ms: 500,
|
||||
finalization_ms: 1_500,
|
||||
});
|
||||
const { capture } = captureObservations(result);
|
||||
|
||||
expect(capture.exit.reason, "initiating deadline stays the reason").toBe(
|
||||
"timeout",
|
||||
);
|
||||
expect(
|
||||
capture.exit.finalization,
|
||||
"finalization attempts are recorded",
|
||||
).toMatchObject({
|
||||
requested_ms: 1_500,
|
||||
signals: [
|
||||
{ signal: "SIGTERM", delivery: "signaled" },
|
||||
{ signal: "SIGKILL", delivery: "signaled" },
|
||||
],
|
||||
});
|
||||
expect(
|
||||
capture.exit.signal,
|
||||
"the target that ignores SIGTERM and SIGINT ends on SIGKILL",
|
||||
).toBe(9);
|
||||
expect(
|
||||
capture.exit.finalization?.elapsed_ms,
|
||||
"the whole interval elapsed before the kill",
|
||||
).toBeGreaterThanOrEqual(1_500);
|
||||
expect(
|
||||
capture.exit.finalization?.elapsed_ms,
|
||||
"the kill followed the interval promptly",
|
||||
).toBeLessThan(4_000);
|
||||
expect(
|
||||
observedFile(capture, "final.json"),
|
||||
"an ignored signal writes no final report",
|
||||
).toBeUndefined();
|
||||
},
|
||||
15_000,
|
||||
);
|
||||
|
||||
itWithCaptureCapability(
|
||||
"keeps the immediate kill when no finalization interval is configured",
|
||||
async () => {
|
||||
const { result } = await captureFinalizationFixture("cooperative", {
|
||||
timeout_ms: 500,
|
||||
});
|
||||
const { capture } = captureObservations(result);
|
||||
|
||||
expect(capture.exit.reason, "deadline reason is unchanged").toBe("timeout");
|
||||
expect(
|
||||
capture.exit.signal,
|
||||
"the default deadline still ends on SIGKILL",
|
||||
).toBe(9);
|
||||
expect(
|
||||
capture.exit,
|
||||
"default captures carry no finalization record",
|
||||
).not.toHaveProperty("finalization");
|
||||
expect(
|
||||
observedFile(capture, "final.json"),
|
||||
"SIGKILL leaves no final report",
|
||||
).toBeUndefined();
|
||||
},
|
||||
15_000,
|
||||
);
|
||||
|
||||
itWithCaptureCapability(
|
||||
"cancels before any deadline without starting finalization",
|
||||
async () => {
|
||||
const controller = new AbortController();
|
||||
setTimeout(() => controller.abort(), 1_500);
|
||||
const started = Date.now();
|
||||
const { result } = await captureFinalizationFixture(
|
||||
"ignoring",
|
||||
{ timeout_ms: 20_000, finalization_ms: 20_000 },
|
||||
controller.signal,
|
||||
);
|
||||
|
||||
if (result.ok) throw new Error("expected cancellation");
|
||||
if (!(result.error instanceof ProcessCaptureError)) throw result.error;
|
||||
const partial = result.error.partialObservation;
|
||||
if (partial === undefined || !("observations" in partial))
|
||||
throw new Error("expected cancelled process observations");
|
||||
expect(
|
||||
partial.observations.exit,
|
||||
"cancellation before any deadline is not a finalization",
|
||||
).toMatchObject({ state: "available", value: { reason: "cancelled" } });
|
||||
expect(
|
||||
partial.observations.exit,
|
||||
"no SIGTERM interval ran, so no finalization record exists",
|
||||
).not.toHaveProperty("value.finalization");
|
||||
expect(
|
||||
Date.now() - started,
|
||||
"cancellation does not wait for either deadline",
|
||||
).toBeLessThan(10_000);
|
||||
},
|
||||
15_000,
|
||||
);
|
||||
|
||||
itWithCaptureCapability(
|
||||
"cancels immediately while a finalization interval is running",
|
||||
async () => {
|
||||
const controller = new AbortController();
|
||||
// Abort well after the 300 ms deadline so finalization is already running.
|
||||
setTimeout(() => controller.abort(), 2_000);
|
||||
const started = Date.now();
|
||||
const { result } = await captureFinalizationFixture(
|
||||
"ignoring",
|
||||
{ timeout_ms: 300, finalization_ms: 20_000 },
|
||||
controller.signal,
|
||||
);
|
||||
|
||||
if (result.ok) throw new Error("expected cancellation");
|
||||
if (!(result.error instanceof ProcessCaptureError)) throw result.error;
|
||||
const partial = result.error.partialObservation;
|
||||
if (partial === undefined || !("observations" in partial))
|
||||
throw new Error("expected cancelled process observations");
|
||||
expect(
|
||||
partial.observations.exit,
|
||||
"cancellation is the exit reason and signal attempts are recorded",
|
||||
).toMatchObject({
|
||||
state: "available",
|
||||
value: {
|
||||
reason: "cancelled",
|
||||
finalization: {
|
||||
requested_ms: 20_000,
|
||||
signals: [
|
||||
{ signal: "SIGTERM", delivery: "signaled" },
|
||||
{ signal: "SIGKILL", delivery: "signaled" },
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(
|
||||
partial.observations.finalization,
|
||||
"the attempts are published beside the exit, also for a failed run",
|
||||
).toMatchObject({
|
||||
state: "available",
|
||||
value: {
|
||||
requested_ms: 20_000,
|
||||
signals: [
|
||||
{ signal: "SIGTERM", delivery: "signaled" },
|
||||
{ signal: "SIGKILL" },
|
||||
],
|
||||
},
|
||||
});
|
||||
if (result.error.cleanupIncomplete) {
|
||||
expectUnverifiedHostCleanup(result.error);
|
||||
expect(
|
||||
result.error.executionFailure,
|
||||
"the host cleanup error wraps the cancellation",
|
||||
).toBe("process capture was cancelled");
|
||||
}
|
||||
const cancellation = result.error.cleanupIncomplete
|
||||
? result.error.cause
|
||||
: result.error;
|
||||
expect(cancellation, "cancellation wins over finalization").toMatchObject({
|
||||
reason: "cancelled",
|
||||
userCategory: "cancelled",
|
||||
});
|
||||
expect(
|
||||
Date.now() - started,
|
||||
"cancellation does not wait for the finalization interval",
|
||||
).toBeLessThan(8_000);
|
||||
},
|
||||
15_000,
|
||||
);
|
||||
|
||||
itWithCaptureCapability(
|
||||
"keeps the attempts when the escalation cannot be delivered through the retained identity",
|
||||
async () => {
|
||||
const calls: string[] = [];
|
||||
let observedAt: number | undefined;
|
||||
let firstSignalAt: number | undefined;
|
||||
const finalizationHost: FinalizationHost = {
|
||||
observe: async () => {
|
||||
observedAt ??= performance.now();
|
||||
return { state: "readable" as const, identity: "launch" };
|
||||
},
|
||||
signal: async (_pid, identity, signal) => {
|
||||
firstSignalAt ??= performance.now();
|
||||
calls.push(`${identity}:${signal}`);
|
||||
return signal === "SIGTERM" ? "signaled" : "unverified";
|
||||
},
|
||||
};
|
||||
const root = await createTestTempDirectory("rea-finalization-host-");
|
||||
const result = await captureProcessScenario(
|
||||
parseProcessScenario({
|
||||
executable: process.execPath,
|
||||
arguments: [finalizationFixture, "ignoring", root],
|
||||
working_directory: root,
|
||||
filesystem_observation_paths: [root],
|
||||
idle_timeout_ms: 10_000,
|
||||
timeout_ms: 500,
|
||||
finalization_ms: 500,
|
||||
}),
|
||||
undefined,
|
||||
process.platform,
|
||||
process.env,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
finalizationHost,
|
||||
);
|
||||
|
||||
if (result.ok) throw new Error("expected an unobserved exit");
|
||||
if (!(result.error instanceof ProcessCaptureError)) throw result.error;
|
||||
if (result.error.cleanupIncomplete)
|
||||
expectUnverifiedHostCleanup(result.error);
|
||||
expect(
|
||||
calls,
|
||||
"both finalization signals went through the identity-checked host",
|
||||
).toEqual(["launch:SIGTERM", "launch:SIGKILL"]);
|
||||
expect(
|
||||
(firstSignalAt ?? 0) - (observedAt ?? Number.POSITIVE_INFINITY),
|
||||
"the start identity was read at launch, well before the 500 ms deadline signalled",
|
||||
).toBeGreaterThanOrEqual(300);
|
||||
const partial = result.error.partialObservation;
|
||||
if (partial === undefined || !("observations" in partial))
|
||||
throw new Error("expected incomplete process observations");
|
||||
expect(
|
||||
partial.observations.finalization,
|
||||
"the attempts and their delivery results are published for a failed capture",
|
||||
).toMatchObject({
|
||||
state: "available",
|
||||
value: {
|
||||
requested_ms: 500,
|
||||
elapsed_ms: null,
|
||||
exit_code: null,
|
||||
signals: [
|
||||
{ signal: "SIGTERM", delivery: "signaled" },
|
||||
{ signal: "SIGKILL", delivery: "unverified" },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(
|
||||
partial.observations.exit.state,
|
||||
"no exit is invented when the escalation was not delivered",
|
||||
).toBe("unavailable");
|
||||
},
|
||||
15_000,
|
||||
);
|
||||
|
||||
itWithCaptureCapability(
|
||||
"classifies cancellation raised by the initial filesystem snapshot",
|
||||
async () => {
|
||||
|
||||
@@ -9,6 +9,7 @@ import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { compareProcessCaptures } from "../../../src/domain/process/processComparison.js";
|
||||
import { parseProcessCapture } from "../../../src/domain/process/processCaptureParsing.js";
|
||||
import { parseProcessScenario } from "../../../src/domain/process/processScenario.js";
|
||||
import { FINALIZED_PROCESS_CAPTURE_EXAMPLE } from "../../../src/domain/process/processCaptureExample.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
@@ -60,6 +61,27 @@ const captureViaMcp = async (scenario: Record<string, unknown>) => {
|
||||
return evidence;
|
||||
};
|
||||
|
||||
it("documents a finalization scenario and exit record that match the contract", async () => {
|
||||
const document = await readFile("docs/process-capture.md", "utf8");
|
||||
const blocks = [
|
||||
...(document.split("### Finalization interval")[1] ?? "").matchAll(
|
||||
/```json\n([\s\S]*?)\n```/gu,
|
||||
),
|
||||
].map((match) => match[1]);
|
||||
const [scenario, exit] = blocks;
|
||||
if (scenario === undefined || exit === undefined)
|
||||
throw new Error("Missing finalization examples");
|
||||
|
||||
expect(
|
||||
parseProcessScenario(JSON.parse(scenario)).finalization_ms,
|
||||
"the documented scenario is accepted and carries the interval",
|
||||
).toBe(1_500);
|
||||
expect(
|
||||
JSON.parse(exit),
|
||||
"the documented exit record is the canonical finalized example",
|
||||
).toEqual(FINALIZED_PROCESS_CAPTURE_EXAMPLE.exit);
|
||||
});
|
||||
|
||||
itWithCaptureCapability.each(["cli", "mcp"] as const)(
|
||||
"hashes the documented complete report despite omitted terminal output through %s",
|
||||
async (adapter) => {
|
||||
|
||||
Vendored
+43
-18
@@ -1,6 +1,7 @@
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import type { ValidateFunction } from "ajv";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { expect, onTestFinished } from "vitest";
|
||||
import { z } from "zod";
|
||||
@@ -27,31 +28,55 @@ export async function connectLocalToolsMcp() {
|
||||
});
|
||||
await client.connect(transport);
|
||||
const tools = (await client.listTools()).tools;
|
||||
const validators = new Map(
|
||||
tools.flatMap((tool) => {
|
||||
new Ajv2020({ strict: false, validateFormats: false }).compile(
|
||||
tool.inputSchema,
|
||||
const schemaValidator = new Ajv2020({
|
||||
strict: false,
|
||||
validateFormats: false,
|
||||
});
|
||||
for (const tool of tools)
|
||||
for (const [kind, schema] of [
|
||||
["inputSchema", tool.inputSchema],
|
||||
["outputSchema", tool.outputSchema],
|
||||
] as const) {
|
||||
if (schema === undefined) continue;
|
||||
const valid = schemaValidator.validateSchema(
|
||||
z.record(z.string(), z.unknown()).parse(schema),
|
||||
);
|
||||
return tool.outputSchema === undefined
|
||||
? []
|
||||
: [
|
||||
[
|
||||
tool.name,
|
||||
new Ajv2020({ strict: false, validateFormats: false }).compile(
|
||||
z.record(z.string(), z.unknown()).parse(tool.outputSchema),
|
||||
),
|
||||
] as const,
|
||||
];
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
valid,
|
||||
`${tool.name}.${kind}: ${schemaValidator.errorsText(schemaValidator.errors)}`,
|
||||
).toBe(true);
|
||||
}
|
||||
const definitions = new Map(tools.map((tool) => [tool.name, tool]));
|
||||
const compiledInputs = new Set<string>();
|
||||
const validators = new Map<string, ValidateFunction<unknown>>();
|
||||
const call = async (name: string, arguments_: Record<string, unknown>) => {
|
||||
const definition = definitions.get(name);
|
||||
if (definition !== undefined && !compiledInputs.has(name)) {
|
||||
new Ajv2020({ strict: false, validateFormats: false }).compile(
|
||||
definition.inputSchema,
|
||||
);
|
||||
compiledInputs.add(name);
|
||||
}
|
||||
const response = await client.callTool({ name, arguments: arguments_ });
|
||||
const validate = validators.get(name);
|
||||
if (response.structuredContent !== undefined && validate !== undefined)
|
||||
if (
|
||||
response.structuredContent !== undefined &&
|
||||
definition?.outputSchema !== undefined
|
||||
) {
|
||||
let validate = validators.get(name);
|
||||
if (validate === undefined) {
|
||||
validate = new Ajv2020({
|
||||
strict: false,
|
||||
validateFormats: false,
|
||||
}).compile<unknown>(
|
||||
z.record(z.string(), z.unknown()).parse(definition.outputSchema),
|
||||
);
|
||||
validators.set(name, validate);
|
||||
}
|
||||
expect(
|
||||
validate(response.structuredContent),
|
||||
JSON.stringify(validate.errors),
|
||||
).toBe(true);
|
||||
}
|
||||
return response;
|
||||
};
|
||||
return { client, call };
|
||||
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
// Writes a periodic report, then behaves by mode:
|
||||
// - "cooperative": stays alive; SIGTERM prints a line, writes a final report
|
||||
// and exits cleanly.
|
||||
// - "ignoring": stays alive and swallows SIGTERM and SIGINT, so only SIGKILL
|
||||
// ends the process.
|
||||
// - "exits": exits on its own at once.
|
||||
// - "descendant": cooperates while leaving a SIGTERM-ignoring child for owned cleanup.
|
||||
// An optional third argument is the exit code a cooperative finalizer uses.
|
||||
const [mode, directory, finalExitCode = "0"] = process.argv.slice(2);
|
||||
|
||||
writeFileSync(join(directory, "pid.txt"), String(process.pid));
|
||||
writeFileSync(
|
||||
join(directory, "periodic.json"),
|
||||
JSON.stringify({ phase: "periodic" }),
|
||||
);
|
||||
|
||||
if (mode === "exits") process.exit(0);
|
||||
|
||||
if (mode === "descendant") {
|
||||
const childDirectory = join(directory, "descendant");
|
||||
mkdirSync(childDirectory);
|
||||
spawn(
|
||||
process.execPath,
|
||||
[fileURLToPath(import.meta.url), "ignoring", childDirectory],
|
||||
{ detached: true, stdio: "ignore" },
|
||||
);
|
||||
}
|
||||
|
||||
if (mode === "ignoring") {
|
||||
process.on("SIGTERM", () => {
|
||||
writeFileSync(join(directory, "sigterm-received"), "received");
|
||||
});
|
||||
process.on("SIGINT", () => undefined);
|
||||
} else {
|
||||
process.on("SIGTERM", () => {
|
||||
writeFileSync(join(directory, "sigterm-received"), "received");
|
||||
process.stdout.write("finalized\n");
|
||||
writeFileSync(
|
||||
join(directory, "final.json"),
|
||||
JSON.stringify({ phase: "final" }),
|
||||
);
|
||||
process.exit(Number(finalExitCode));
|
||||
});
|
||||
}
|
||||
|
||||
setInterval(() => undefined, 1_000);
|
||||
@@ -0,0 +1,120 @@
|
||||
import { expect } from "vitest";
|
||||
|
||||
import type { ProcessCaptureError } from "../../src/process/capture/ProcessCaptureError.js";
|
||||
|
||||
type SerializedCleanupReport = {
|
||||
readonly owned_process_group: {
|
||||
readonly state: unknown;
|
||||
readonly reason: unknown;
|
||||
};
|
||||
readonly terminal_renderer: { readonly state: unknown };
|
||||
readonly temporary_root: {
|
||||
readonly state: unknown;
|
||||
readonly reason: unknown;
|
||||
};
|
||||
};
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null;
|
||||
|
||||
const isSerializedCleanupReport = (
|
||||
value: unknown,
|
||||
): value is SerializedCleanupReport =>
|
||||
isRecord(value) &&
|
||||
isRecord(value.owned_process_group) &&
|
||||
"state" in value.owned_process_group &&
|
||||
"reason" in value.owned_process_group &&
|
||||
isRecord(value.terminal_renderer) &&
|
||||
"state" in value.terminal_renderer &&
|
||||
isRecord(value.temporary_root) &&
|
||||
"state" in value.temporary_root &&
|
||||
"reason" in value.temporary_root;
|
||||
|
||||
const expectHostCleanupReport = (report: {
|
||||
readonly owned_process_group: {
|
||||
readonly state: unknown;
|
||||
readonly reason: unknown;
|
||||
};
|
||||
readonly terminal_renderer: { readonly state: unknown };
|
||||
readonly temporary_root: {
|
||||
readonly state: unknown;
|
||||
readonly reason: unknown;
|
||||
};
|
||||
}): void => {
|
||||
expect(report.owned_process_group.state).toBe("unverified");
|
||||
const reason = report.owned_process_group.reason;
|
||||
expect(typeof reason).toBe("string");
|
||||
if (typeof reason !== "string")
|
||||
throw new Error("cleanup report omitted reason");
|
||||
const category =
|
||||
process.platform === "linux"
|
||||
? "environment_errno_(?:EACCES|EPERM)"
|
||||
: "environment_unavailable";
|
||||
const candidate =
|
||||
"[1-9][0-9]*=(?:environment_unavailable|environment_errno_(?:EACCES|EPERM))";
|
||||
expect(reason).toMatch(
|
||||
new RegExp(
|
||||
`^process ownership token could not be read for [1-9][0-9]* live process\\(es\\): ` +
|
||||
`${category}=[1-9][0-9]*(?:, ${category}=[1-9][0-9]*)*; ` +
|
||||
`live candidates ${candidate}(?:, ${candidate})*$`,
|
||||
"u",
|
||||
),
|
||||
);
|
||||
expect(report.terminal_renderer.state).toBe("cleaned");
|
||||
// The temporary root is retained while owned process cleanup is unverified.
|
||||
expect(report.temporary_root).toEqual({
|
||||
state: "unverified",
|
||||
reason: `temporary root retained because owned process cleanup is unverified: ${reason}`,
|
||||
});
|
||||
};
|
||||
|
||||
/** Permit only the host ownership-token cleanup flake seen by real captures. */
|
||||
export const expectUnverifiedHostCleanup = (
|
||||
error: ProcessCaptureError,
|
||||
): void => {
|
||||
expect(error.reason, error.message).toBe("cleanup_incomplete");
|
||||
const report = error.cleanupReport;
|
||||
expect(report).toBeDefined();
|
||||
if (report === undefined)
|
||||
throw new Error("cleanup-incomplete error omitted report");
|
||||
expectHostCleanupReport(report);
|
||||
};
|
||||
|
||||
/**
|
||||
* Assert the same narrowly-defined cleanup flake after CLI/MCP serialization
|
||||
* and return the observations that callers must continue to verify.
|
||||
*/
|
||||
export const expectSerializedUnverifiedHostCleanup = (
|
||||
value: unknown,
|
||||
): unknown => {
|
||||
expect(typeof value).toBe("object");
|
||||
expect(value).not.toBeNull();
|
||||
if (typeof value !== "object" || value === null || !("error" in value))
|
||||
throw new Error("cleanup error omitted its serialized error envelope");
|
||||
const error = value.error;
|
||||
expect(typeof error).toBe("object");
|
||||
expect(error).not.toBeNull();
|
||||
if (
|
||||
typeof error !== "object" ||
|
||||
error === null ||
|
||||
!("code" in error) ||
|
||||
!("details" in error)
|
||||
)
|
||||
throw new Error("cleanup error omitted its serialized details");
|
||||
expect(error.code).toBe("cleanup_incomplete");
|
||||
const details = error.details;
|
||||
expect(typeof details).toBe("object");
|
||||
expect(details).not.toBeNull();
|
||||
if (
|
||||
typeof details !== "object" ||
|
||||
details === null ||
|
||||
!("cleanup_report" in details) ||
|
||||
!("partial_observation" in details)
|
||||
)
|
||||
throw new Error("cleanup error omitted report or partial observation");
|
||||
const cleanupReport = details.cleanup_report;
|
||||
if (!isSerializedCleanupReport(cleanupReport))
|
||||
throw new Error("cleanup error report is incomplete");
|
||||
expectHostCleanupReport(cleanupReport);
|
||||
return details.partial_observation;
|
||||
};
|
||||
Reference in New Issue
Block a user