Files
reverse-engineering-anything/src/process/ProcessInspectionTermination.test.ts
T
morluto ab84ba6839 fix(process)!: retain inspection cancellation and cleanup ownership (#10113)
* fix(process): preserve producer-owned inspection cancellation

Prototype the explicit inspection origin and retained file/batch owner protocol. Downstream adapter migration and lease binding remain required before integration.

* fix(process): type inspection ownership handoffs precisely

* fix(process): retain plain inspection preparation cancellation

* fix(process): retain explicit inspection cleanup and cancellation facts

* fix(process): require explicit inspection facts and cleanup scope

* refactor(process): remove redundant cleanup forwarding wrapper

* fix(firmware): retain inspection cancellation and cleanup ownership

* fix(wakaru): retain typed inspection outcomes and caller scope

* fix(ghidra): preserve inspection facts and launch cleanup scope

* fix(providers): preserve typed process inspection outcomes

* refactor(process): remove obsolete inspection cancellation re-export

* fix(native): preserve inspection preparation cleanup and cancellation

* fix(registration): retain typed inspection cleanup during Git discovery

* fix(process): preserve inspection deadline origin in adapter handoff

* fix(process): consume the canonical inspection selector in binding

* fix(native): preserve inspection deadlines and cleanup retry completion

* test(process): narrow the retained Darwin preparation owner

* fix(providers): preserve preparation ownership and timeout policy

Narrow preparation facts through their canonical owner, preserve actual cleanup capabilities and recorded cancellation, and keep enclosing command deadlines authoritative. Retain raw inspection records through Java refusal and configuration projections without changing availability fallback policy.

* refactor(process): use one inspection failure type owner

* fix(providers): retain recorded secondary failures when rebinding

* fix(ghidra): preserve normalized inspection facts through public projection

* fix(process): normalize native process listing cancellation

* docs(development): clarify failure provenance and cleanup verification

* fix(process): preserve direct inspection cancellation facts

* fix(process): retain inspection owners through termination

* fix(process): preserve command inspection cleanup provenance

* fix(desktop): preserve inspection facts after cleanup retry

* refactor(process)!: migrate desktop capture with inspection producers

* fix(desktop)!: preserve capture failure origins and cleanup owners (#10115)

* fix(desktop): preserve capture failure origins and cleanup

* fix(desktop): type keyring cleanup cancellation

* fix(kuna)!: retain copy cleanup before retiring workspaces (#10114)

* fix(kuna): own copy cancellation and descriptor cleanup

* fix(kuna): close copy descriptors before workspace removal

* test(kuna): type copy lifecycle gates for project library

* docs(kuna): explain retained copy-file cleanup and staging ownership

* docs(kuna): separate cache publication, integrity and cleanup guidance

* fix(desktop): retain sampling inspection owners before release

* fix(process): preserve capture file read cancellation origin

* fix(process): retain capture inspection cancellation and cleanup owners

* fix(process): retain sampling inspection failures in capture scope

* fix(process): retain inspection failures through mandatory cleanup

* fix(process): distinguish sampler shutdown from capture cancellation

* fix(browser): retain startup EOF before later cancellation

* fix(process): bind capture inspection cleanup to the owning run

* test(process): migrate cancellation fixtures to typed owners

Record explicit preparation and command cancellation facts, retain exact opaque reasons and physical causes, and guard the mocked version probe from native preparation. Keep the live Wakaru command control while adding a recording equivalent for bounded source verification.

* fix(process): own sampling reads and settle inspection peers

* fix(errors): retain authored recovery through cleanup composition

* fix(process): retain all sampling inspection leaves for final cleanup

* test(browser): report recording cleanup signal outcome

* fix(process): keep inspection error context out of implicit JSON

* fix(desktop): retain normalized sampling cleanup ownership

* test(process): assert tagged startup cancellation
2026-11-11 16:37:48 -05:00

271 lines
9.1 KiB
TypeScript

import { EventEmitter } from "node:events";
import { expect, it, onTestFinished, vi } from "vitest";
import { failedInspectionDescriptor } from "../../tests/fixtures/processInspectionCleanup.js";
import { OwnedCommandFailure, runOwnedCommand } from "./OwnedCommand.js";
import {
ProcessOwnershipIdentityBatchFailure,
ProcessOwnershipInspectionCancelled,
} from "./ProcessInspectionCancellation.js";
import { retainOwnedCommandCleanup } from "../providers/OwnedCommandCleanup.js";
import { ProviderProcessSupervisor } from "./ProviderProcess.js";
import { terminateTokenOwnedProcesses } from "./TokenOwnedTermination.js";
it("preserves the exact failed inspection descriptor when graceful termination cannot inspect identity", async () => {
const file = await failedInspectionDescriptor();
const listProcesses = vi.fn(async () => [
{
pid: 42,
parentPid: 1,
processGroupId: 42,
state: "S",
command: "fixture",
},
]);
const signalGroup = vi.fn(() => {
throw new Error("Unexpected group signal");
});
const signalProcess = vi.fn(() => {
throw new Error("Unexpected PID signal");
});
const result = await terminateTokenOwnedProcesses(
{ runId: "authored-run", processGroupId: 42 },
0,
{
ownership: {
platform: "linux",
listProcesses,
environment: async () => ({ REA_PROCESS_RUN_ID: "authored-run" }),
processIdentities: async () => {
throw file.failure;
},
signalGroup,
},
signalProcess,
},
);
expect(result).toMatchObject({
ok: false,
error: { launchGroupSignalled: false },
});
if (result.ok)
throw new Error(
"Unknown identity must not report successful termination inspection",
);
expect(result.error.cause).toBe(file.failure);
expect(file.handle.fd).toBeGreaterThanOrEqual(0);
expect(listProcesses).toHaveBeenCalledOnce();
expect(signalGroup).not.toHaveBeenCalled();
expect(signalProcess).not.toHaveBeenCalled();
});
it("retries the original inspection descriptor before fresh process cleanup and never reports a blocked close as verified", async () => {
const file = await failedInspectionDescriptor();
const child = Object.assign(new EventEmitter(), {
pid: 42,
stdout: null,
stderr: null,
exitCode: 0,
signalCode: null,
kill: vi.fn(() => {
throw new Error("Unexpected child signal");
}),
});
let cleanupCalls = 0;
const supervisor = new ProviderProcessSupervisor({
process: child,
ownsProcessLifetime: true,
cleanup: async () => {
cleanupCalls += 1;
if (cleanupCalls === 1) throw file.failure;
return { cleaned: true, signaled: false };
},
});
child.emit("close", 0, null);
onTestFinished(() => supervisor.dispose());
const initial = await supervisor.stop();
expect(initial.status).toBe("incomplete");
if (initial.status !== "incomplete")
throw new Error("Expected retained inspection cleanup");
expect(initial.inspectionCleanup?.causes).toEqual([file.failure]);
const retried = await supervisor.stop();
expect(retried.status).toBe("incomplete");
if (retried.status !== "incomplete")
throw new Error("Expected blocked descriptor retry");
expect(retried.inspectionCleanup?.causes[0]).toBe(file.failure);
expect(retried.inspectionCleanup?.failures[0]?.failure).toBe(file.failure);
expect(retried.inspectionCleanup?.failures[0]?.cause).not.toBe(
initial.inspectionCleanup?.failures[0]?.cause,
);
expect(file.handle.fd).toBeGreaterThanOrEqual(0);
expect(cleanupCalls).toBe(1);
file.allow();
expect((await supervisor.stop()).status).toBe("verified-cleanup");
expect(file.handle.fd).toBe(-1);
expect(cleanupCalls).toBe(2);
expect(child.kill).not.toHaveBeenCalled();
});
it("retries all mixed inspection owners and keeps original and retry errors live until the last exact owner releases", async () => {
const first = await failedInspectionDescriptor();
const second = await failedInspectionDescriptor();
const foreign = await failedInspectionDescriptor();
const observations = new Map([
[44, { state: "unavailable" as const, reason: "not yet observed" }],
]);
const batch = new ProcessOwnershipIdentityBatchFailure(
[
{ pid: 42, requestIndex: 0, cause: first.failure },
{ pid: 42, requestIndex: 1, cause: second.failure },
{
pid: 44,
requestIndex: 2,
cause: new ProcessOwnershipInspectionCancelled(foreign.failure),
},
],
observations,
);
const child = Object.assign(new EventEmitter(), {
stdout: null,
stderr: null,
exitCode: 0,
signalCode: null,
kill: () => {
throw new Error("Unexpected child signal");
},
});
let cleanupCalls = 0;
const supervisor = new ProviderProcessSupervisor({
process: child,
ownsProcessLifetime: true,
cleanup: async () => {
if (++cleanupCalls === 1) throw batch;
return { cleaned: true, signaled: false };
},
});
child.emit("close", 0, null);
onTestFinished(() => supervisor.dispose());
const initial = await supervisor.stop();
if (initial.status !== "incomplete")
throw new Error("Expected mixed cleanup failure");
expect(initial.inspectionCleanup?.causes[0]).toBe(batch);
expect(batch.observations).toBe(observations);
const command = new OwnedCommandFailure(
"process",
"physical command failure",
null,
initial.reason,
{},
[first.path, second.path],
supervisor,
);
const retained: { close(): Promise<void> }[] = [];
const errors = retainOwnedCommandCleanup(
command,
{
retain: (owner) => retained.push(owner),
run: (work) => work(),
},
"fixture",
"inspect",
);
expect(errors).toHaveLength(1);
expect(errors[0]?.cleanupIncomplete).toBe(true);
first.allow();
const partial = await supervisor.stop();
if (partial.status !== "incomplete")
throw new Error("Second owner must remain unresolved");
expect(first.handle.fd).toBe(-1);
expect(second.handle.fd).toBeGreaterThanOrEqual(0);
expect(
partial.inspectionCleanup?.failures.map(({ failure }) => failure),
).toEqual([second.failure]);
expect(partial.inspectionCleanup?.causes[0]).toBe(batch);
expect(cleanupCalls).toBe(1);
const firstCloses = first.closes();
const retryError: unknown = await retained[0]!
.close()
.catch((cause: unknown) => cause);
expect(retryError).toMatchObject({ cleanupIncomplete: true });
expect(errors[0]?.cleanupIncomplete).toBe(true);
expect(first.closes()).toBe(firstCloses);
expect(foreign.closes()).toBe(1);
second.allow();
await retained[0]!.close();
expect(second.handle.fd).toBe(-1);
expect(first.closes()).toBe(firstCloses);
expect(cleanupCalls).toBe(2);
expect(errors[0]?.cleanupIncomplete).toBe(false);
expect(retryError).toMatchObject({ cleanupIncomplete: false });
expect(foreign.handle.fd).toBeGreaterThanOrEqual(0);
expect(foreign.closes()).toBe(1);
});
it("retains stop-only inspection facts on the actual command failure after its supervisor releases the descriptor", async () => {
const file = await failedInspectionDescriptor();
const observations = new Map([
[
44,
{
state: "unavailable" as const,
reason: "retained identity observation",
},
],
]);
const batch = new ProcessOwnershipIdentityBatchFailure(
[{ pid: 42, requestIndex: 0, cause: file.failure }],
observations,
);
const child = Object.assign(new EventEmitter(), {
pid: 42,
stdout: null,
stderr: null,
exitCode: 0,
signalCode: null,
kill: () => {
throw new Error("Unexpected child signal");
},
});
let cleanupCalls = 0;
const failure: unknown = await runOwnedCommand(
{ command: "recorded-command", arguments: [], runId: "recorded-run" },
{
timeoutMs: null,
diagnosticBytes: 1024,
},
{
launcher: async () => {
setImmediate(() => child.emit("close", 0, null));
return {
process: child,
ownership: {
runId: "recorded-run",
leaderPid: 42,
processGroupId: 42,
},
cleanup: async () => {
if (++cleanupCalls === 1) throw batch;
return { cleaned: true, signaled: false };
},
};
},
},
).catch((cause: unknown) => cause);
expect(failure).toBeInstanceOf(OwnedCommandFailure);
if (!(failure instanceof OwnedCommandFailure)) throw failure;
onTestFinished(() => failure.cleanupOwner?.dispose());
expect(failure.inspectionCleanup?.causes[0]).toBe(batch);
expect(failure.inspectionCleanup?.failures[0]?.failure).toBe(file.failure);
expect(batch.observations).toBe(observations);
expect(file.handle.fd).toBeGreaterThanOrEqual(0);
file.allow();
expect((await failure.cleanupOwner!.stop()).status).toBe("verified-cleanup");
expect(file.handle.fd).toBe(-1);
expect(cleanupCalls).toBe(2);
expect(failure.inspectionCleanup?.causes[0]).toBe(batch);
const retained = failure.inspectionCleanup?.causes[0];
if (!(retained instanceof ProcessOwnershipIdentityBatchFailure))
throw new Error("Expected retained batch after release");
expect(retained.observations).toBe(observations);
});