fix(reverse): reconcile cleanup ownership and mutation diagnostics (#2799)
* feat(process): add owned debugger shutdown lifecycle * feat(reverse): add local inspection commands * feat(gdb): add persistent debugger integration * feat(cutter): add Cutter bridge integration * test(reverse): enforce complete integration coverage * fix(process): preserve debugger shutdown ownership * fix(reverse): retain evidence across interrupted commands * fix(gdb): honor captured provider environment * test(process): cover debugger shutdown retries * fix(reverse): retain evidence for interrupted providers * test(process): cover debugger shutdown retries * fix(reverse): retain evidence for interrupted providers * fix(server): snapshot provider environment at creation * fix(reverse): close review gaps with complete coverage * fix(reverse): address inspection review findings * fix(gdb): bound sessions and retain cleanup ownership * fix(ci): require reverse-tools quality lane * fix(process): unref inherited debugger output pipes * fix(reverse): address remaining PR 1960 findings * fix(gdb): address remaining PR 1961 findings * fix(reverse): account for unrestricted provider execution * fix(process): retain debugger ownership until safe shutdown * fix(process): preserve replacement debugger sessions * fix(reverse): preserve admission and output provenance * fix(process): retain exited debugger until output settles * fix(mcp): bound provider admission and debugger cleanup * fix(reverse): preserve failure provenance and classify E2BIG * fix(gdb): preserve startup cleanup and detach safety * fix(process): retain debugger ownership after detach failure * fix(reverse): preserve mutation and failure provenance * fix(gdb): address debugger review findings * fix(reverse): rebind sessions after external mutation * fix(process): cap debugger output after exit * fix(gdb): protect one-shot detach verification * feat(debugger): add reverse tool coverage gate * test(debugger): cover integrated failure paths * fix(gdb): bound and preserve session observations * fix(gdb): address review regressions * style: format merged integration files * fix(reverse): preserve session and output evidence * refactor(gdb): share repeated test and partial result setup * fix(gdb): invalidate TTY proof for Python aliases * fix(reverse): retain failure output byte counts * test(process): synchronize late debugger output * fix(gdb): invalidate TTY proof for wrapped commands * fix(gdb): recognize wit command abbreviation * test(reverse): wait for cancelled descendant readiness * test(reverse): bound descendant cancellation cleanup * style(reverse): format integration tests and adapters * style: format reverse engineering integration files * test(reverse): remove duplicate environment harness * test(gdb): share session startup assertions * fix(gdb): invalidate output proof for command abbreviations * test(reverse): share composition edge case scenarios * fix(ci): recognize verification and mutation tool entries * test(rizin): cover successful fake inferior detach * test(cli): align full output failure envelope * test(cli): isolate reverse command lifecycle service * test(process): share debugger output fixture setup * fix(binary): preserve high-bit Windows signature bytes * style(binary): format Windows signature parser * test(mcp): preserve call coverage in unchanged comparison * fix(ci): include reverse tools Vitest configs in lint cache * fix(mcp): preserve target content on delivery errors * ci: align duplication ceiling with expanded suite * test(reverse): allow signal admission mutants * fix(reverse): bound retained cleanup failures to process owners * fix(test): replace drifting mutation ranges with owned selectors * fix(reverse): admit persistent commands and retain cleanup ownership * fix(cutter): recover timed-out commands from exact receipts * fix(cutter): reject unsupported bridge request kinds * fix(ci): repair client format and shared verification fixtures * fix(native): preserve debugger cleanup ownership and bridge authentication * test(native): retain diagnostics without perfect coverage requirements * chore(licenses): refresh locked dependency inventory and notices * fix(test): exclude transient command locks from mutation sandboxes * fix(gdb): admit only platforms with safe detach verification * fix(cutter): retain bounded completion receipts until acknowledgement * fix(cutter): acknowledge commands rejected before UI dispatch * test(reverse): fail cancellation checks before fixture teardown * test(gdb): clean up the retained broken-stdin fixture owner * docs(test): clarify focused provider verification scope * fix(rizin): retain close cleanup failures * fix(gdb): wait for inferior stop and bound MI buffering * fix(cutter): retain failed receipt acknowledgements * fix(rizin): return retained session identity on rebind failure * fix(gdb): preserve startup cancellation and lossy status * fix(rizin): retain launch provenance and assemble frames once * fix(cutter): recover receipts across callers and bound discovery * docs: describe debugger evidence and bridge recovery * fix(process): keep cleanup incomplete while writers remain Stopping a debugger no longer reports success when inherited output streams stay open, so BinarySession cannot reopen a binary a child is still changing. Concurrent Cutter cleanup retries share one receipt acknowledgement instead of treating a consumed receipt as failure. * fix(debuggers): recover cleanup with captured process identities * fix(analysis): retire sessions after unrestricted commands * fix(cli): preserve completed evidence after cleanup recovery * fix(cutter): bound frame collection and coalesce cleanup * fix(windows): resolve selected provider paths absolutely * fix(gdb): report decoding loss in failed startup evidence * fix(rizin): scope decoding loss to collected command frames * test(mcp): cover snapshot retirement in reverse tools CI --------- Co-authored-by: Daniel Gonçalves Araujo <47118053+dandgabr@users.noreply.github.com> Co-authored-by: REA Maintainers <noreply@github.com> Co-authored-by: OpenAI Codex <codex@users.noreply.github.com> Co-authored-by: Cursor Agent <cursoragent@cursor.com>
This commit is contained in:
co-authored by
Daniel Gonçalves Araujo
REA Maintainers
OpenAI Codex
Cursor Agent
parent
2ad2a044d4
commit
4aa51bfe19
@@ -0,0 +1,288 @@
|
||||
import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { TestReverseEngineeringService as ReverseEngineeringService } from "../support/reverseEngineeringService.js";
|
||||
|
||||
type PromiseOutcome<Value> =
|
||||
| { readonly status: "fulfilled"; readonly value: Value }
|
||||
| { readonly status: "rejected"; readonly reason: unknown }
|
||||
| { readonly status: "timeout" };
|
||||
|
||||
const settleWithin = async <Value>(
|
||||
promise: Promise<Value>,
|
||||
timeoutMs: number,
|
||||
): Promise<PromiseOutcome<Value>> => {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
return await Promise.race([
|
||||
promise.then(
|
||||
(value): PromiseOutcome<Value> => ({ status: "fulfilled", value }),
|
||||
(reason: unknown): PromiseOutcome<Value> => ({
|
||||
status: "rejected",
|
||||
reason,
|
||||
}),
|
||||
),
|
||||
new Promise<PromiseOutcome<Value>>((resolve) => {
|
||||
timer = setTimeout(() => resolve({ status: "timeout" }), timeoutMs);
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
if (timer !== undefined) clearTimeout(timer);
|
||||
}
|
||||
};
|
||||
|
||||
const processIsRunning = (pid: number): boolean => {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (cause) {
|
||||
return !(
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
cause.code === "ESRCH"
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const waitForProcessExit = async (
|
||||
pid: number,
|
||||
timeoutMs: number,
|
||||
): Promise<boolean> => {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
if (!processIsRunning(pid)) return true;
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
}
|
||||
return !processIsRunning(pid);
|
||||
};
|
||||
|
||||
const killProcessAndWait = async (
|
||||
pid: number,
|
||||
timeoutMs: number,
|
||||
): Promise<boolean> => {
|
||||
try {
|
||||
process.kill(pid, "SIGKILL");
|
||||
} catch (cause) {
|
||||
if (!(cause instanceof Error && "code" in cause && cause.code === "ESRCH"))
|
||||
throw cause;
|
||||
}
|
||||
return waitForProcessExit(pid, timeoutMs);
|
||||
};
|
||||
|
||||
type CancellationResult = Awaited<
|
||||
ReturnType<ReverseEngineeringService["executeRizinCommand"]>
|
||||
>;
|
||||
|
||||
interface CancellationProcessMarkers {
|
||||
readonly providerPid: string;
|
||||
readonly descendantPid: string;
|
||||
readonly descendantStarted: string;
|
||||
}
|
||||
|
||||
interface CancellationProcessIds {
|
||||
readonly providerPid: number;
|
||||
readonly descendantPid: number;
|
||||
}
|
||||
|
||||
const readProcessMarker = async (path: string): Promise<number | undefined> => {
|
||||
const text = await readFile(path, "utf8").catch(() => "");
|
||||
const pid = Number(text);
|
||||
return Number.isSafeInteger(pid) && pid > 0 ? pid : undefined;
|
||||
};
|
||||
|
||||
const waitForCancellationProcesses = async (
|
||||
markers: CancellationProcessMarkers,
|
||||
): Promise<CancellationProcessIds> => {
|
||||
for (let attempt = 0; attempt < 500; attempt += 1) {
|
||||
const [providerPid, descendantPid, descendantStarted] = await Promise.all([
|
||||
readProcessMarker(markers.providerPid),
|
||||
readProcessMarker(markers.descendantPid),
|
||||
readFile(markers.descendantStarted).then(
|
||||
() => true,
|
||||
() => false,
|
||||
),
|
||||
]);
|
||||
if (
|
||||
providerPid !== undefined &&
|
||||
descendantPid !== undefined &&
|
||||
descendantStarted
|
||||
)
|
||||
return { providerPid, descendantPid };
|
||||
await new Promise((resolveDelay) => setTimeout(resolveDelay, 10));
|
||||
}
|
||||
throw new Error("Rizin provider and descendant did not start in time.");
|
||||
};
|
||||
|
||||
const killCancellationProcesses = async (
|
||||
ids: CancellationProcessIds,
|
||||
): Promise<void> => {
|
||||
expect(await killProcessAndWait(ids.providerPid, 2_000)).toBe(true);
|
||||
expect(await killProcessAndWait(ids.descendantPid, 2_000)).toBe(true);
|
||||
};
|
||||
|
||||
const settleCancelledProvider = async (
|
||||
pending: Promise<CancellationResult>,
|
||||
): Promise<CancellationResult> => {
|
||||
const outcome = await settleWithin(pending, 7_000);
|
||||
if (outcome.status === "timeout")
|
||||
throw new Error("Rizin cancellation did not settle before its deadline");
|
||||
if (outcome.status === "rejected") throw outcome.reason;
|
||||
return outcome.value;
|
||||
};
|
||||
|
||||
const expectCancelledResult = (result: CancellationResult): void => {
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error._tag).toBe("AnalysisCancelledError");
|
||||
expect(result.error.cleanup).toBeUndefined();
|
||||
expect(result.error.capturedOutput).toMatchObject({
|
||||
stdout: "provider output before cancellation",
|
||||
stderr: "",
|
||||
truncated: false,
|
||||
exit_code: null,
|
||||
signal: "SIGKILL",
|
||||
});
|
||||
expect(result.error.cause).toBeInstanceOf(Error);
|
||||
expect(result.error.partialObservation).toMatchObject({
|
||||
raw_result: {
|
||||
stdout: "provider output before cancellation",
|
||||
completion_status: "unknown",
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const cleanupCancellationScenario = async (options: {
|
||||
readonly controller: AbortController;
|
||||
readonly pending: Promise<CancellationResult> | undefined;
|
||||
readonly service: ReverseEngineeringService;
|
||||
readonly processIds: CancellationProcessIds | undefined;
|
||||
readonly directory: string;
|
||||
}): Promise<void> => {
|
||||
options.controller.abort();
|
||||
try {
|
||||
if (options.pending !== undefined) {
|
||||
try {
|
||||
if (options.processIds !== undefined)
|
||||
await settleCancelledProvider(options.pending);
|
||||
else await settleWithin(options.pending, 10_000);
|
||||
} catch {
|
||||
// Main assertions report operation failures; continue cleanup.
|
||||
}
|
||||
}
|
||||
let cleanup = await settleWithin(options.service.close(), 7_000);
|
||||
if (cleanup.status === "timeout" && options.processIds !== undefined) {
|
||||
await killCancellationProcesses(options.processIds);
|
||||
cleanup = await settleWithin(options.service.close(), 3_000);
|
||||
}
|
||||
if (cleanup.status === "timeout")
|
||||
throw new Error("Service cleanup did not settle within its deadline.");
|
||||
if (cleanup.status === "rejected") throw cleanup.reason;
|
||||
if (options.processIds !== undefined) {
|
||||
for (const pid of [
|
||||
options.processIds.providerPid,
|
||||
options.processIds.descendantPid,
|
||||
]) {
|
||||
if (processIsRunning(pid)) await killProcessAndWait(pid, 2_000);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await rm(options.directory, { recursive: true, force: true });
|
||||
}
|
||||
};
|
||||
|
||||
it("uses stoppable process mode for caller-selected provider commands", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-rizin-stoppable-"));
|
||||
const path = join(directory, "fixture.bin");
|
||||
await writeFile(path, "fixture");
|
||||
let received: Record<string, unknown> | undefined;
|
||||
const service = new ReverseEngineeringService({
|
||||
run: async (_command, _args, options) => {
|
||||
received = options as Record<string, unknown>;
|
||||
return { stdout: "", stderr: "" };
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await service.executeRizinCommand({ path, command: "iI" });
|
||||
expect(received?.stopSignal).toBe("SIGTERM");
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"waits for a cancelled Rizin process to exit before returning",
|
||||
async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-rizin-cancel-settle-"));
|
||||
const path = join(directory, "fixture.bin");
|
||||
const providerPidMarker = join(directory, "provider-pid");
|
||||
const descendantStartedMarker = join(directory, "descendant-started");
|
||||
const descendantPidMarker = join(directory, "descendant-pid");
|
||||
const provider = join(directory, "slow-rizin.mjs");
|
||||
const descendantScript = [
|
||||
"const fs = require('node:fs');",
|
||||
"process.on('SIGTERM', () => {});",
|
||||
"fs.writeFileSync(process.env.REA_TEST_DESCENDANT_STARTED, 'started');",
|
||||
"setInterval(() => {}, 1000);",
|
||||
].join("\n");
|
||||
await writeFile(path, "before");
|
||||
await writeFile(
|
||||
provider,
|
||||
`#!${process.execPath}
|
||||
import { spawn } from "node:child_process";
|
||||
import { writeFileSync } from "node:fs";
|
||||
writeFileSync(process.env.REA_TEST_PROVIDER_PID, String(process.pid));
|
||||
process.stdout.write("provider output before cancellation");
|
||||
const child = spawn(process.execPath, ["-e", ${JSON.stringify(descendantScript)}], { env: process.env, stdio: "ignore" });
|
||||
writeFileSync(process.env.REA_TEST_DESCENDANT_PID, String(child.pid));
|
||||
setInterval(() => {}, 1000);
|
||||
`,
|
||||
);
|
||||
await chmod(provider, 0o755);
|
||||
const controller = new AbortController();
|
||||
const service = new ReverseEngineeringService({
|
||||
environment: {
|
||||
REA_RIZIN_COMMAND: provider,
|
||||
REA_TEST_ARTIFACT: path,
|
||||
REA_TEST_PROVIDER_PID: providerPidMarker,
|
||||
REA_TEST_DESCENDANT_STARTED: descendantStartedMarker,
|
||||
REA_TEST_DESCENDANT_PID: descendantPidMarker,
|
||||
},
|
||||
});
|
||||
|
||||
let pending: ReturnType<typeof service.executeRizinCommand> | undefined;
|
||||
let processIds: CancellationProcessIds | undefined;
|
||||
try {
|
||||
pending = service.executeRizinCommand(
|
||||
{ path, command: "sleep" },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
processIds = await waitForCancellationProcesses({
|
||||
providerPid: providerPidMarker,
|
||||
descendantPid: descendantPidMarker,
|
||||
descendantStarted: descendantStartedMarker,
|
||||
});
|
||||
controller.abort();
|
||||
|
||||
expectCancelledResult(await settleCancelledProvider(pending));
|
||||
expect(await readFile(path, "utf8")).toBe("before");
|
||||
expect(await waitForProcessExit(processIds.descendantPid, 2_000)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(await waitForProcessExit(processIds.providerPid, 2_000)).toBe(
|
||||
true,
|
||||
);
|
||||
} finally {
|
||||
await cleanupCancellationScenario({
|
||||
controller,
|
||||
pending,
|
||||
service,
|
||||
processIds,
|
||||
directory,
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
Reference in New Issue
Block a user