Files
reverse-engineering-anything/src/process/TokenOwnedTermination.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

202 lines
6.4 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import { failedInspectionDescriptor } from "../../tests/fixtures/processInspectionCleanup.js";
import type {
ProcessIdentityObservation,
ProcessOwnershipHost,
ProcessTableEntry,
} from "./ProcessOwnership.js";
import { terminateTokenOwnedProcesses } from "./TokenOwnedTermination.js";
interface FakeProcess extends ProcessTableEntry {
readonly runId?: string;
}
/** A process table whose members exit when SIGTERM reaches them, unless they ignore it. */
const fakeHost = (
processes: readonly FakeProcess[],
ignoresTerm: ReadonlySet<number> = new Set(),
groupUnread: ReadonlySet<number> = new Set(),
) => {
const live = new Map(processes.map((entry) => [entry.pid, entry]));
const terminate = (pid: number) => {
if (!ignoresTerm.has(pid)) live.delete(pid);
};
const signalGroup = vi.fn((group: number) => {
for (const entry of live.values())
if (entry.processGroupId === group) terminate(entry.pid);
});
const signalProcess = vi.fn((pid: number) => {
terminate(pid);
});
const ownership: ProcessOwnershipHost = {
platform: "linux",
listProcesses: async () => [...live.values()],
environment: async (pid) => {
const runId = live.get(pid)?.runId;
return runId === undefined ? {} : { REA_PROCESS_RUN_ID: runId };
},
processIdentities: async (rows) =>
new Map(
rows.map(({ pid }): [number, ProcessIdentityObservation] => {
const entry = live.get(pid);
return [
pid,
entry === undefined
? { state: "absent", reason: "not-found-in-caller-pid-namespace" }
: {
state: "readable",
identity: `start:${String(pid)}`,
lifecycle: { state: "observed", lifecycle: "non-zombie" },
relation: groupUnread.has(pid)
? { state: "unavailable", reason: "stat unreadable" }
: {
state: "observed",
parentPid: entry.parentPid,
processGroupId: entry.processGroupId,
},
},
];
}),
),
signalGroup,
};
return { host: { ownership, signalProcess }, signalGroup, signalProcess };
};
const row = (
pid: number,
processGroupId: number,
runId?: string,
): FakeProcess => ({
pid,
parentPid: 1,
processGroupId,
state: "S",
command: "fixture",
...(runId === undefined ? {} : { runId }),
});
describe("terminateTokenOwnedProcesses", () => {
it("preserves the already-delivered group signal and exact owner when exit polling fails", async () => {
const file = await failedInspectionDescriptor();
const { host, signalGroup, signalProcess } = fakeHost(
[row(100, 100, "run")],
new Set([100]),
);
const identities = host.ownership.processIdentities!;
host.ownership.processIdentities = async (...args) => {
if (signalGroup.mock.calls.length > 0) throw file.failure;
return identities(...args);
};
const result = await terminateTokenOwnedProcesses(
{ runId: "run", processGroupId: 100 },
1_000,
host,
);
expect(result).toMatchObject({
ok: false,
error: { launchGroupSignalled: true },
});
if (result.ok) throw new Error("Polling failure must remain explicit");
expect(result.error.cause).toBe(file.failure);
expect(signalGroup.mock.calls).toEqual([[100, "SIGTERM"]]);
expect(signalProcess).not.toHaveBeenCalled();
expect(file.handle.fd).toBeGreaterThanOrEqual(0);
});
it("sends SIGTERM to the launch group and to token carriers that left it, never to others", async () => {
const { host, signalGroup, signalProcess } = fakeHost([
row(100, 100, "run"),
row(101, 100),
row(200, 200, "run"),
row(300, 300, "other-run"),
row(400, 400),
]);
expect(
await terminateTokenOwnedProcesses(
{ runId: "run", processGroupId: 100 },
1_000,
host,
),
).toEqual({ ok: true, value: { launchGroupSignalled: true } });
expect(signalGroup.mock.calls).toEqual([[100, "SIGTERM"]]);
expect(signalProcess.mock.calls).toEqual([[200, "SIGTERM"]]);
expect(
(await host.ownership.listProcesses()).map(({ pid }) => pid),
).toEqual([300, 400]);
});
it("does not signal the launch group when no member is proven to carry the token", async () => {
const { host, signalGroup, signalProcess } = fakeHost([
row(101, 100),
row(200, 200, "run"),
]);
expect(
await terminateTokenOwnedProcesses(
{ runId: "run", processGroupId: 100 },
1_000,
host,
),
).toEqual({ ok: true, value: { launchGroupSignalled: false } });
expect(signalGroup).not.toHaveBeenCalled();
expect(signalProcess.mock.calls).toEqual([[200, "SIGTERM"]]);
});
it("signals a carrier whose current group is unknown on its own, not through the launch group", async () => {
const { host, signalGroup, signalProcess } = fakeHost(
[row(100, 100, "run")],
new Set(),
new Set([100]),
);
expect(
await terminateTokenOwnedProcesses(
{ runId: "run", processGroupId: 100 },
1_000,
host,
),
).toEqual({ ok: true, value: { launchGroupSignalled: false } });
expect(signalGroup).not.toHaveBeenCalled();
expect(signalProcess.mock.calls).toEqual([[100, "SIGTERM"]]);
});
it("does not report a refused group signal as delivered and still stops other token carriers", async () => {
const { host, signalGroup } = fakeHost([
row(100, 100, "run"),
row(200, 200, "run"),
]);
signalGroup.mockImplementation(() => {
throw Object.assign(new Error("Signal refused"), { code: "EPERM" });
});
expect(
await terminateTokenOwnedProcesses(
{ runId: "run", processGroupId: 100 },
1_000,
host,
),
).toEqual({ ok: true, value: { launchGroupSignalled: false } });
expect(
(await host.ownership.listProcesses()).map(({ pid }) => pid),
).toEqual([100]);
});
it("waits for the grace period when a process ignores SIGTERM", async () => {
const { host } = fakeHost([row(100, 100, "run")], new Set([100]));
const started = performance.now();
await terminateTokenOwnedProcesses(
{ runId: "run", processGroupId: 100 },
300,
host,
);
expect(performance.now() - started).toBeGreaterThanOrEqual(250);
});
});