feat(process): record provider and verifier run lineage

This commit is contained in:
morluto
2026-07-22 14:01:47 +00:00
parent f5b3e22e72
commit 513fa294a4
200 changed files with 2808 additions and 546 deletions
+82 -7
View File
@@ -32,6 +32,12 @@ describe("binary session", () => {
const [first] = await targets();
const session = new BinarySession(cacheProvider([]));
expect((await session.open(first)).ok).toBe(true);
expect(session.status()).toMatchObject({
analysis_run: {
run_id: expect.any(String),
process_lineage: { status: "not_observed" },
},
});
expect(session.listUnknowns()).toEqual([]);
const identity = session.providerIdentity();
Reflect.set(identity, "id", "forged");
@@ -90,13 +96,36 @@ describe("binary session", () => {
limitations: [],
},
],
createClient: () => ({
execute: (operation) => {
operations.push(operation);
return Promise.resolve(ok(operation));
},
close: () => Promise.resolve(),
}),
createClient: (_target, _profile, context) => {
if (context === undefined)
throw new Error("missing analysis run context");
return {
execute: (operation) => {
operations.push(operation);
return Promise.resolve(ok(operation));
},
runtimeLineageSnapshots: () => [
{
provider: provider.identity(),
observation: {
status: "verified",
observedAt: "2026-07-22T10:00:00.000Z",
lineage: {
schemaVersion: 1,
runId: context.runId,
launcherPid: 100,
launcherParentPid: 1,
processGroupId: 100,
descendants: [
{ pid: 101, parentPid: 100, processGroupId: 100 },
],
},
},
},
],
close: () => Promise.resolve(),
};
},
};
const session = new BinarySession(provider);
expect((await session.open(first)).ok).toBe(true);
@@ -131,11 +160,57 @@ describe("binary session", () => {
},
},
],
analysis_run: {
run_id: expect.stringMatching(
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u,
),
process_lineage: {
status: "snapshots",
snapshots: [
{
provider: { id: "fixture", name: "Fixture", version: "1" },
observation: {
status: "verified",
observed_at: "2026-07-22T10:00:00.000Z",
schema_version: 1,
launcher_pid: 100,
launcher_parent_pid: 1,
process_group_id: 100,
descendants: [
{ pid: 101, parent_pid: 100, process_group_id: 100 },
],
},
},
],
},
},
});
expect(operations).toEqual(["health", "address_name"]);
await session.close();
});
it("allocates one fresh run identity per provider client lifetime", async () => {
const [first, second] = await targets();
const provider = cacheProvider([]);
const createClient = provider.createClient.bind(provider);
const runIds: string[] = [];
provider.createClient = (target, profile, context) => {
if (context === undefined)
throw new Error("missing analysis run context");
runIds.push(context.runId);
return createClient(target, profile, context);
};
const session = new BinarySession(provider);
expect((await session.open(first)).ok).toBe(true);
expect((await session.open(first)).ok).toBe(true);
expect((await session.open(second)).ok).toBe(true);
expect(runIds).toHaveLength(2);
expect(new Set(runIds).size).toBe(2);
await session.close();
});
it("replays exact immutable calls from a matching provider-neutral snapshot", async () => {
const [first, second] = await targets();
const initialCalls: string[] = [];
+70
View File
@@ -14,6 +14,21 @@ const evidenceId = (digit: string): string => `ev_${digest(digit)}`;
const report = (): CompletionVerifierReport => ({
schema_version: 1,
verifier: { id: "managed-conformance", version: "1" },
verifier_run: {
schema_version: 1,
run_id: "11111111-1111-4111-8111-111111111111",
verifier_pid: 100,
parent_pid: 1,
process_lineage: {
status: "verified",
schema_version: 1,
observed_at: "2026-07-22T10:00:00.000Z",
launcher_pid: 100,
launcher_parent_pid: 1,
process_group_id: 100,
descendants: [{ pid: 101, parent_pid: 100, process_group_id: 100 }],
},
},
environment: {
platform: "linux",
architecture: "x64",
@@ -84,6 +99,61 @@ describe("completion ledger generation", () => {
expect(generate(reversed)).toEqual(generate(input));
});
it("keeps ephemeral verifier run identity out of generated commitments", () => {
const first = report();
const second = {
...first,
verifier_run: {
...first.verifier_run,
run_id: "22222222-2222-4222-8222-222222222222",
verifier_pid: 200,
process_lineage: {
status: "unavailable" as const,
observed_at: "2026-07-22T11:00:00.000Z",
launcher_pid: 200,
launcher_parent_pid: 1,
process_group_id: null,
reason: "Windows verifier lineage ownership is unavailable",
},
},
};
expect(generate(second)).toEqual(generate(first));
});
it("requires a typed verifier-process identity", () => {
const input = report();
expect(
completionVerifierReportSchema.safeParse({
...input,
verifier_run: { ...input.verifier_run, run_id: "not-a-uuid" },
}).success,
).toBe(false);
});
it("rejects malformed verified descendant lineage", () => {
const input = report();
expect(
completionVerifierReportSchema.safeParse({
...input,
verifier_run: {
...input.verifier_run,
process_lineage: {
status: "verified",
schema_version: 1,
observed_at: "2026-07-22T10:00:00.000Z",
launcher_pid: 100,
launcher_parent_pid: 1,
process_group_id: 100,
descendants: [
{ pid: 101, parent_pid: 100, process_group_id: null },
],
},
},
}).success,
).toBe(false);
});
it.each([
[
"artifact",
+95 -1
View File
@@ -1,4 +1,7 @@
import { describe, expect, it } from "vitest";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { BinarySession } from "../src/application/BinarySession.js";
import { CompositeProvider } from "../src/application/CompositeProvider.js";
@@ -19,6 +22,13 @@ const target: BinaryTarget = {
sha256: "0".repeat(64),
};
let directory: string | undefined;
afterEach(async () => {
if (directory !== undefined)
await rm(directory, { recursive: true, force: true });
directory = undefined;
});
describe("composite analysis provider", () => {
it("routes disjoint operations and does not start children during health", async () => {
const hopperCalls: string[] = [];
@@ -80,8 +90,92 @@ describe("composite analysis provider", () => {
]),
).toThrow(/Multiple providers declare operation address_name/u);
});
it("retains lineage snapshots from two lazily started dynamic providers", async () => {
directory = await mkdtemp(join(tmpdir(), "rea-composite-lineage-"));
const targetPath = join(directory, "fixture.hop");
await writeFile(targetPath, "fixture");
const first = dynamicProvider("first", "address_name", 100);
const second = dynamicProvider("second", "analyze_function", 200);
const session = new BinarySession(new CompositeProvider([second, first]));
expect((await session.open(targetPath)).ok).toBe(true);
expect(await session.execute("address_name", {})).toMatchObject({
ok: true,
});
expect(await session.execute("analyze_function", {})).toMatchObject({
ok: true,
});
expect(session.status()).toMatchObject({
analysis_run: {
process_lineage: {
status: "snapshots",
snapshots: [
{
provider: { id: "first" },
observation: {
status: "verified",
observed_at: "2026-07-22T10:00:00.000Z",
launcher_pid: 100,
},
},
{
provider: { id: "second" },
observation: {
status: "verified",
observed_at: "2026-07-22T10:00:00.000Z",
launcher_pid: 200,
},
},
],
},
},
});
await session.close();
});
});
const dynamicProvider = (
id: string,
operation: Exclude<AnalysisOperation, "health">,
launcherPid: number,
): AnalysisProvider => {
const identity: ProviderIdentity = { id, name: id, version: "1" };
return {
identity: () => identity,
capabilities: () => [capability(identity, operation)],
createClient: (_target, _profile, context) => {
if (context === undefined)
throw new Error("missing analysis run context");
return {
execute: (called) =>
Promise.resolve(
ok(createAnalysisExecution(`${id}:${called}`, identity)),
),
runtimeLineageSnapshots: () => [
{
provider: identity,
observation: {
status: "verified",
observedAt: "2026-07-22T10:00:00.000Z",
lineage: {
schemaVersion: 1,
runId: context.runId,
launcherPid,
launcherParentPid: 1,
processGroupId: launcherPid,
descendants: [],
},
},
},
],
close: () => Promise.resolve(),
};
},
};
};
const provider = (
id: string,
operation: Exclude<AnalysisOperation, "health">,
+20
View File
@@ -1,3 +1,5 @@
import { spawn } from "node:child_process";
const [mode, value = "0"] = process.argv.slice(2);
const keepAlive = () => {
@@ -35,6 +37,24 @@ switch (mode) {
await write(process.stdout, "ready\n");
keepAlive();
break;
case "detached-child": {
const child = spawn(
process.execPath,
[
"-e",
"setInterval(() => undefined, 1000); setTimeout(() => process.exit(0), 10000)",
],
{ detached: true, stdio: "ignore" },
);
await new Promise((resolve, reject) => {
child.once("spawn", resolve);
child.once("error", reject);
});
await write(process.stdout, `ready:${child.pid}\n`);
child.unref();
keepAlive();
break;
}
default:
process.stderr.write(`unknown provider-process fixture mode: ${mode}\n`);
process.exitCode = 64;
+37 -1
View File
@@ -7,7 +7,7 @@ const fixturePath = fileURLToPath(
/** Spawn one deterministic process-lifecycle fixture with piped diagnostics. */
export const spawnProviderProcessFixture = (
mode: "burst" | "exit" | "graceful" | "stubborn",
mode: "burst" | "detached-child" | "exit" | "graceful" | "stubborn",
value?: number,
): ChildProcess =>
spawn(
@@ -52,6 +52,42 @@ export const waitForProviderProcessReady = (
child.once("exit", onExit);
});
/** Read the distinct process-group leader created by the detached-child mode. */
export const waitForDetachedProviderChild = (
child: ChildProcess,
timeoutMs = 2_000,
): Promise<number> =>
new Promise((resolve, reject) => {
const stdout = child.stdout;
if (stdout === null) {
reject(new Error("Provider process fixture stdout is unavailable"));
return;
}
let output = "";
const detach = (): void => {
clearTimeout(timer);
stdout.off("data", onData);
child.off("exit", onExit);
};
const onData = (chunk: Buffer | string): void => {
output += chunk.toString();
const match = /(?:^|\n)ready:(\d+)\n/u.exec(output);
if (match?.[1] === undefined) return;
detach();
resolve(Number(match[1]));
};
const onExit = (): void => {
detach();
reject(new Error("Provider process fixture exited before readiness"));
};
const timer = setTimeout(() => {
detach();
reject(new Error("Provider process fixture readiness timed out"));
}, timeoutMs);
stdout.on("data", onData);
child.once("exit", onExit);
});
/** Kill a fixture if necessary and wait for its process handle to settle. */
export const stopProviderProcessFixture = async (
child: ChildProcess,
+6 -1
View File
@@ -95,6 +95,7 @@ const clientFor = (
readonly requestTimeoutMs?: number;
readonly onDiagnostic?: (event: GhidraDiagnostic) => void;
readonly transport?: GhidraTransportKind;
readonly runId?: string;
} = {},
): GhidraClient => {
const client = new GhidraClient({
@@ -106,6 +107,7 @@ const clientFor = (
profileDigest: PROFILE_DIGEST,
startupTimeoutMs: options.startupTimeoutMs ?? 1_000,
requestTimeoutMs: options.requestTimeoutMs ?? 100,
...(options.runId === undefined ? {} : { runId: options.runId }),
...(options.onDiagnostic === undefined
? {}
: { onDiagnostic: options.onDiagnostic }),
@@ -388,7 +390,9 @@ describe("GhidraClient", () => {
it("retains actionable runtime coordinates after successful cleanup", async () => {
const launcher = new FixtureLauncher();
const client = clientFor(launcher);
const client = clientFor(launcher, {
runId: "11111111-1111-4111-8111-111111111111",
});
await expect(client.start()).resolves.toMatchObject({ ok: true });
await client.close();
@@ -399,6 +403,7 @@ describe("GhidraClient", () => {
endpoint_path: launcher.endpointPaths[0],
project_root: join(launcher.runtimeRoots[0] ?? "", "project"),
process_id: expect.any(Number),
run_id: "11111111-1111-4111-8111-111111111111",
});
await expect(access(launcher.runtimeRoots[0] ?? "")).rejects.toMatchObject({
code: "ENOENT",
+10 -2
View File
@@ -210,11 +210,12 @@ describe("Ghidra provider", () => {
}),
);
const start = vi.fn().mockResolvedValue(ok(sessionInfo()));
const ghidra = provider(installationHost(), () => ({
const clientFactory = vi.fn(() => ({
start,
callTool,
close: () => Promise.resolve(),
}));
const ghidra = provider(installationHost(), clientFactory);
const resolved = await ghidra.resolveAnalysisProfile(
executableTarget("elf", "x86_64"),
);
@@ -238,8 +239,15 @@ describe("Ghidra provider", () => {
});
const result = await ghidra
.createClient(executableTarget("elf", "x86_64"), resolved.value.profile)
.createClient(executableTarget("elf", "x86_64"), resolved.value.profile, {
runId: "11111111-1111-4111-8111-111111111111",
})
.execute("list_procedures", {});
expect(clientFactory).toHaveBeenCalledWith(
expect.objectContaining({
runId: "11111111-1111-4111-8111-111111111111",
}),
);
expect(callTool).toHaveBeenCalledWith(
"list_procedures",
{ document: null, offset: 0, limit: 100 },
+15
View File
@@ -22,6 +22,7 @@ const fixturePath = fileURLToPath(
class FixtureLauncher implements BridgeLauncher {
socketPaths: string[] = [];
directories: string[] = [];
runIds: string[] = [];
processes: ChildProcess[] = [];
constructor(readonly tokenOverride?: string) {}
@@ -29,6 +30,7 @@ class FixtureLauncher implements BridgeLauncher {
launch(session: BridgeSession) {
this.socketPaths.push(session.socketPath);
this.directories.push(session.directory);
this.runIds.push(session.runId);
const child = spawn(
process.execPath,
[
@@ -164,6 +166,19 @@ afterEach(async () => {
});
describe("HopperClient", () => {
it("uses the caller-assigned provider run identity", async () => {
const launcher = new FixtureLauncher();
const client = new HopperClient({
launcher,
runId: "11111111-1111-4111-8111-111111111111",
startupTimeoutMs: 1_000,
});
clients.push(client);
expect((await client.start()).ok).toBe(true);
expect(launcher.runIds).toEqual(["11111111-1111-4111-8111-111111111111"]);
});
it("keeps the native socket path below macOS sockaddr_un limits", async () => {
const launcher = new FixtureLauncher();
const client = new HopperClient({ launcher, startupTimeoutMs: 1_000 });
+266 -8
View File
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest";
import {
cleanupOwnedProcessGroup,
cleanupWindowsProcessTree,
observeOwnedProcessLineage,
observeOwnedProcessGroup,
parseProcessEnvironment,
selectCapturedProcessGroupIds,
@@ -24,7 +25,7 @@ const host = (
const signalGroup = vi.fn();
return {
adapter: {
listMembers: () =>
listProcesses: () =>
Promise.resolve(
Object.keys(environments).map((pid) => ({
pid: Number(pid),
@@ -72,6 +73,264 @@ describe("owned process-group cleanup", () => {
expect(signalGroup).toHaveBeenCalledWith(100, "SIGKILL");
});
it("validates and signals rooted descendant groups once, root first", async () => {
const processes = [
{ pid: 100, parentPid: 1, processGroupId: 100 },
{ pid: 110, parentPid: 100, processGroupId: 100 },
{ pid: 101, parentPid: 100, processGroupId: 101 },
{ pid: 102, parentPid: 101, processGroupId: 102 },
{ pid: 103, parentPid: 102, processGroupId: 102 },
].map((process) => ({
...process,
state: "S",
command: "fixture",
}));
const signalGroup = vi.fn();
const adapter: ProcessOwnershipHost = {
listProcesses: () => Promise.resolve(processes),
environment: () => Promise.resolve({ REA_PROCESS_RUN_ID: "run-token" }),
signalGroup,
};
await expect(cleanupOwnedProcessGroup(ownership, adapter)).resolves.toEqual(
{ cleaned: true, signaled: true },
);
expect(signalGroup.mock.calls).toEqual([
[100, "SIGKILL"],
[101, "SIGKILL"],
[102, "SIGKILL"],
]);
});
it("fails before signaling when any descendant-group member is unowned", async () => {
const signalGroup = vi.fn();
const adapter: ProcessOwnershipHost = {
listProcesses: () =>
Promise.resolve([
{
pid: 100,
parentPid: 1,
processGroupId: 100,
state: "S",
command: "fixture",
},
{
pid: 101,
parentPid: 100,
processGroupId: 101,
state: "S",
command: "child-session",
},
{
pid: 104,
parentPid: 101,
processGroupId: 101,
state: "S",
command: "child-helper",
},
]),
environment: (pid) =>
Promise.resolve({
REA_PROCESS_RUN_ID: pid === 104 ? "other-run" : "run-token",
}),
signalGroup,
};
await expect(cleanupOwnedProcessGroup(ownership, adapter)).resolves.toEqual(
{
cleaned: false,
reason: "process tree contains an unowned or PID-reused process",
failures: [{ pid: 104, reason: "run-token-mismatch" }],
},
);
expect(signalGroup).not.toHaveBeenCalled();
});
it("fails before signaling when a descendant group leader is not rooted", async () => {
const signalGroup = vi.fn();
const adapter: ProcessOwnershipHost = {
listProcesses: () =>
Promise.resolve([
{
pid: 100,
parentPid: 1,
processGroupId: 100,
state: "S",
command: "fixture",
},
{
pid: 105,
parentPid: 100,
processGroupId: 101,
state: "S",
command: "descendant",
},
{
pid: 101,
parentPid: 999,
processGroupId: 101,
state: "S",
command: "unrelated-group-leader",
},
]),
environment: () => Promise.resolve({ REA_PROCESS_RUN_ID: "run-token" }),
signalGroup,
};
await expect(cleanupOwnedProcessGroup(ownership, adapter)).resolves.toEqual(
{
cleaned: false,
reason:
"descendant process-group leader identity could not be verified",
},
);
expect(signalGroup).not.toHaveBeenCalled();
});
it("records sorted launcher and descendant lineage after token checks", async () => {
const { adapter } = host({
102: { REA_PROCESS_RUN_ID: "run-token" },
100: { REA_PROCESS_RUN_ID: "run-token" },
101: { REA_PROCESS_RUN_ID: "run-token" },
});
await expect(
observeOwnedProcessLineage(ownership, adapter),
).resolves.toEqual({
status: "verified",
observedAt: expect.any(String),
lineage: {
schemaVersion: 1,
runId: "run-token",
launcherPid: 100,
launcherParentPid: 1,
processGroupId: 100,
descendants: [
{ pid: 101, parentPid: 100, processGroupId: 100 },
{ pid: 102, parentPid: 100, processGroupId: 100 },
],
},
});
});
it("walks the PPID tree across process-group boundaries", async () => {
const environment = vi.fn((pid: number) =>
Promise.resolve({
REA_PROCESS_RUN_ID: pid === 103 ? "unrelated-run" : "run-token",
}),
);
const adapter: ProcessOwnershipHost = {
listProcesses: () =>
Promise.resolve([
{
pid: 103,
parentPid: 999,
processGroupId: 100,
state: "S",
command: "unrelated-same-group",
},
{
pid: 102,
parentPid: 101,
processGroupId: 102,
state: "S",
command: "grandchild-session",
},
{
pid: 100,
parentPid: 1,
processGroupId: 100,
state: "S",
command: "fixture",
},
{
pid: 101,
parentPid: 100,
processGroupId: 101,
state: "S",
command: "child-group",
},
]),
environment,
signalGroup: vi.fn(),
};
await expect(
observeOwnedProcessLineage(ownership, adapter),
).resolves.toEqual({
status: "verified",
observedAt: expect.any(String),
lineage: {
schemaVersion: 1,
runId: "run-token",
launcherPid: 100,
launcherParentPid: 1,
processGroupId: 100,
descendants: [
{ pid: 101, parentPid: 100, processGroupId: 101 },
{ pid: 102, parentPid: 101, processGroupId: 102 },
],
},
});
expect(environment.mock.calls.map(([pid]) => pid)).toEqual([100, 101, 102]);
});
it("fails closed when a descendant in another process group lacks the token", async () => {
const adapter: ProcessOwnershipHost = {
listProcesses: () =>
Promise.resolve([
{
pid: 100,
parentPid: 1,
processGroupId: 100,
state: "S",
command: "fixture",
},
{
pid: 101,
parentPid: 100,
processGroupId: 101,
state: "S",
command: "child-session",
},
]),
environment: (pid) =>
Promise.resolve({
REA_PROCESS_RUN_ID: pid === 100 ? "run-token" : "other-run",
}),
signalGroup: vi.fn(),
};
await expect(
observeOwnedProcessLineage(ownership, adapter),
).resolves.toEqual({
status: "unavailable",
observedAt: expect.any(String),
runId: "run-token",
launcherPid: 100,
processGroupId: 100,
reason: "process lineage contains an unowned or PID-reused process",
});
});
it("does not publish lineage when any member fails ownership checks", async () => {
const { adapter } = host({
100: { REA_PROCESS_RUN_ID: "run-token" },
101: { REA_PROCESS_RUN_ID: "other-run" },
});
await expect(
observeOwnedProcessLineage(ownership, adapter),
).resolves.toEqual({
status: "unavailable",
observedAt: expect.any(String),
runId: "run-token",
launcherPid: 100,
processGroupId: 100,
reason: "process lineage contains an unowned or PID-reused process",
});
});
it("fails closed for stale metadata or an unrelated concurrent process", async () => {
const { adapter, signalGroup } = host({
100: { REA_PROCESS_RUN_ID: "run-token" },
@@ -79,7 +338,7 @@ describe("owned process-group cleanup", () => {
});
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
cleaned: false,
reason: "process group contains an unowned or PID-reused process",
reason: "process tree contains an unowned or PID-reused process",
failures: [{ pid: 101, reason: "run-token-mismatch" }],
});
expect(signalGroup).not.toHaveBeenCalled();
@@ -97,7 +356,7 @@ describe("owned process-group cleanup", () => {
});
const signalGroup = vi.fn();
const adapter: ProcessOwnershipHost = {
listMembers: () =>
listProcesses: () =>
Promise.resolve(
[100, 101, 102].map((pid) => ({
pid,
@@ -113,7 +372,7 @@ describe("owned process-group cleanup", () => {
expect(await cleanupOwnedProcessGroup(ownership, adapter)).toEqual({
cleaned: false,
reason: "process group contains an unowned or PID-reused process",
reason: "process tree contains an unowned or PID-reused process",
failures: [
{ pid: 100, reason: "environment-unreadable" },
{ pid: 101, reason: "run-token-mismatch" },
@@ -129,7 +388,7 @@ describe("owned process-group cleanup", () => {
);
const signalGroup = vi.fn();
const adapter: ProcessOwnershipHost = {
listMembers: () =>
listProcesses: () =>
Promise.resolve([
{
pid: 100,
@@ -154,15 +413,14 @@ describe("owned process-group cleanup", () => {
cleaned: true,
signaled: true,
});
expect(environment).toHaveBeenCalledTimes(1);
expect(environment).toHaveBeenCalledWith(100);
expect(environment.mock.calls).toEqual([[100], [100]]);
expect(signalGroup).toHaveBeenCalledWith(100, "SIGKILL");
});
it("observes a zombie-only group as settled", async () => {
const environment = vi.fn(() => Promise.resolve({}));
const adapter: ProcessOwnershipHost = {
listMembers: () =>
listProcesses: () =>
Promise.resolve([
{
pid: 101,
+77
View File
@@ -8,6 +8,10 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { PendingOperations } from "../src/process/PendingOperations.js";
import { PrivateRuntimeRoot } from "../src/process/PrivateRuntimeRoot.js";
import { ProviderStartupDeadline } from "../src/process/ProviderDeadline.js";
import {
cleanupOwnedProcessGroup,
observeOwnedProcessLineage,
} from "../src/process/ProcessOwnership.js";
import {
ProviderProcessSupervisor,
spawnOwnedProviderProcess,
@@ -16,6 +20,7 @@ import {
import {
spawnProviderProcessFixture,
stopProviderProcessFixture,
waitForDetachedProviderChild,
waitForProviderProcessReady,
} from "./fixtures/providerProcess.js";
@@ -23,6 +28,24 @@ const processFixturePath = fileURLToPath(
new URL("./fixtures/providerProcess.mjs", import.meta.url),
);
const waitForPidExit = async (
pid: number,
timeoutMs = 2_000,
): Promise<void> => {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
try {
process.kill(pid, 0);
} catch (cause: unknown) {
if (cause instanceof Error && "code" in cause && cause.code === "ESRCH")
return;
throw cause;
}
await new Promise((resolve) => setTimeout(resolve, 10));
}
throw new Error(`Process ${String(pid)} did not exit within the test bound`);
};
afterEach(() => {
vi.useRealTimers();
});
@@ -254,6 +277,60 @@ describe("provider process lifecycle primitives", () => {
}
});
it.skipIf(process.platform === "win32")(
"cleans a real descendant that starts a distinct process group",
async () => {
const spawned = await spawnOwnedProviderProcess({
command: process.execPath,
arguments: [processFixturePath, "detached-child"],
runId: "provider-process-lineage-run",
});
let detachedChildPid: number | undefined;
try {
detachedChildPid = await waitForDetachedProviderChild(spawned.process);
const observation = await observeOwnedProcessLineage(spawned.ownership);
expect(observation).toEqual({
status: "verified",
observedAt: expect.stringMatching(
/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/u,
),
lineage: {
schemaVersion: 1,
runId: "provider-process-lineage-run",
launcherPid: spawned.process.pid,
launcherParentPid: process.pid,
processGroupId: spawned.process.pid,
descendants: [
{
pid: detachedChildPid,
parentPid: spawned.process.pid,
processGroupId: detachedChildPid,
},
],
},
});
await expect(
cleanupOwnedProcessGroup(spawned.ownership),
).resolves.toEqual({ cleaned: true, signaled: true });
await Promise.all([
waitForPidExit(spawned.ownership.leaderPid),
waitForPidExit(detachedChildPid),
]);
} finally {
await cleanupOwnedProcessGroup(spawned.ownership);
if (detachedChildPid !== undefined)
await cleanupOwnedProcessGroup({
runId: spawned.ownership.runId,
leaderPid: detachedChildPid,
processGroupId: detachedChildPid,
});
await waitForPidExit(spawned.ownership.leaderPid);
if (detachedChildPid !== undefined)
await waitForPidExit(detachedChildPid);
}
},
);
it("allows interpreter launchers to rely on parent and run-token identity", async () => {
const spawned = await spawnOwnedProviderProcess({
command: process.execPath,
+7
View File
@@ -62,6 +62,7 @@ describe("provider selection over MCP", () => {
);
expect(before.result).toMatchObject({
open: false,
analysis_run: null,
analysis_provider_binding: null,
analysis_provider_candidates: [
{
@@ -128,6 +129,12 @@ describe("provider selection over MCP", () => {
);
expect(status.result).toMatchObject({
open: true,
analysis_run: {
run_id: expect.stringMatching(
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u,
),
process_lineage: { status: "not_observed" },
},
analysis_provider_binding: {
provider: { id: "beta", version: "1" },
selection_source: "request",
+138
View File
@@ -0,0 +1,138 @@
import { execFile, spawn, type ChildProcess } from "node:child_process";
import { promisify } from "node:util";
import { describe, expect, it } from "vitest";
import {
completeVerifierRun,
createVerifierRun,
} from "../scripts/lib/verifier-run.mjs";
const execFileAsync = promisify(execFile);
describe.sequential("verifier run identity", () => {
it("allocates, propagates, and reuses one process-local identity", async () => {
const previousRunId = process.env.REA_PROCESS_RUN_ID;
process.env.REA_PROCESS_RUN_ID = "11111111-1111-4111-8111-111111111111";
try {
const first = createVerifierRun();
const nested = createVerifierRun();
expect(first).toEqual({
schema_version: 1,
run_id: expect.stringMatching(
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u,
),
verifier_pid: process.pid,
parent_pid: process.ppid,
});
expect(nested.run_id).toBe(first.run_id);
expect(first.run_id).not.toBe("11111111-1111-4111-8111-111111111111");
expect(process.env.REA_PROCESS_RUN_ID).toBe(first.run_id);
const { stdout } = await execFileAsync(process.execPath, [
"-e",
"process.stdout.write(process.env.REA_PROCESS_RUN_ID ?? '')",
]);
expect(stdout).toBe(first.run_id);
const { stdout: nestedProcessRunId } = await execFileAsync(
process.execPath,
[
"--input-type=module",
"-e",
"import { createVerifierRun } from './scripts/lib/verifier-run.mjs'; process.stdout.write(createVerifierRun().run_id)",
],
);
expect(nestedProcessRunId).not.toBe(first.run_id);
} finally {
restoreRunId(previousRunId);
}
});
it.runIf(process.platform !== "win32")(
"reports token-verified live descendants",
async () => {
const previousRunId = process.env.REA_PROCESS_RUN_ID;
delete process.env.REA_PROCESS_RUN_ID;
const run = createVerifierRun();
const child = spawnReadyChild(process.env);
try {
await childReady(child);
const completed = await completeVerifierRun(run);
expect(completed.process_lineage).toMatchObject({
status: "verified",
schema_version: 1,
observed_at: expect.stringMatching(/Z$/u),
launcher_pid: process.pid,
launcher_parent_pid: process.ppid,
process_group_id: expect.any(Number),
descendants: expect.arrayContaining([
{
pid: child.pid,
parent_pid: process.pid,
process_group_id: expect.any(Number),
},
]),
});
} finally {
await stopChild(child);
restoreRunId(previousRunId);
}
},
);
it.runIf(process.platform !== "win32")(
"reports unavailable when a live descendant lacks the run token",
async () => {
const previousRunId = process.env.REA_PROCESS_RUN_ID;
delete process.env.REA_PROCESS_RUN_ID;
const run = createVerifierRun();
const child = spawnReadyChild({ ...process.env, REA_PROCESS_RUN_ID: "" });
try {
await childReady(child);
const completed = await completeVerifierRun(run);
expect(completed.process_lineage).toMatchObject({
status: "unavailable",
observed_at: expect.stringMatching(/Z$/u),
launcher_pid: process.pid,
launcher_parent_pid: process.ppid,
process_group_id: expect.any(Number),
reason: `descendant ${String(child.pid)} run token did not match`,
});
} finally {
await stopChild(child);
restoreRunId(previousRunId);
}
},
);
});
const spawnReadyChild = (env: NodeJS.ProcessEnv): ChildProcess =>
spawn(
process.execPath,
["-e", "process.stdout.write('ready'); setInterval(() => {}, 1000)"],
{ env, stdio: ["ignore", "pipe", "ignore"] },
);
const childReady = async (child: ChildProcess): Promise<void> => {
await new Promise<void>((resolve, reject) => {
child.once("error", reject);
child.stdout?.once("data", () => resolve());
child.once("exit", (code) =>
reject(new Error(`verifier child exited early with ${String(code)}`)),
);
});
};
const stopChild = async (child: ChildProcess): Promise<void> => {
if (child.exitCode !== null || child.signalCode !== null) return;
const exited = new Promise<void>((resolve) =>
child.once("exit", () => resolve()),
);
child.kill("SIGTERM");
await exited;
};
const restoreRunId = (runId: string | undefined): void => {
if (runId === undefined) delete process.env.REA_PROCESS_RUN_ID;
else process.env.REA_PROCESS_RUN_ID = runId;
};