Files
morlutoandCursor Agent aad296795c fix(session): settle snapshot, shutdown, and cleanup-retry races (#14757)
* fix(session): settle snapshot, shutdown, and cleanup-retry races

- Invalidate the analysis snapshot only when an external mutation retires a
  bound engine. Without a target there is no analysis to retire, and the
  lingering flag made the next open discard a snapshot staged meanwhile.
- Let a deferred MCP server's close cancel in-flight runtime startup instead
  of waiting for it to finish before cleanup can run.
- Keep a concurrently confirmed command cleanup owner confirmed when a peer
  retry's stale stop reports it incomplete.
- Re-check provider registry closing after every wait so a selection is never
  admitted while a newer close is in progress.

* fix(session): stop cleanup owners registered while a retry is in flight

retryCleanup visits owners that appear during a stop await and returns
success only when none remain pending. An incomplete stop still cannot
replace an owner a concurrent retry has already confirmed.

* fix(mcp): keep a failed deferred startup failed when close aborts cleanup

The eager result classifies cancellation before its cleanup await. A close
that aborts during that await no longer treats a nonzero startup result as
a cancelled success.

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
2026-11-26 16:46:08 +00:00

1546 lines
48 KiB
TypeScript

import { spawnFailure } from "../support/process/spawnFailure.js";
import { createHash } from "node:crypto";
import { readFile, rm } from "node:fs/promises";
import type { Stats } from "node:fs";
import { expect, it, vi } from "vitest";
import { registerSharedReverseEngineeringEdgeCaseTests } from "../support/reverseEngineeringCompositionEdgeCases.js";
import { registerOwnedRizinCommandEvidenceTests } from "../support/ownedRizinCommandEvidenceTests.js";
import {
createArtifact,
ownedFailure,
ownedOutput,
providerSnapshot,
} from "../support/reverseEngineeringCompositionFixtures.js";
import {
findsNoExecutable,
TestReverseEngineeringService as ReverseEngineeringService,
} from "../support/reverseEngineeringService.js";
import {
AnalysisCapabilityUnavailableError,
AnalysisResourceConstraintError,
} from "../../src/domain/analysisErrorCore.js";
import {
ReverseEngineeringService as CoreReverseEngineeringService,
type FileDigestBounds,
POST_RUN_ARTIFACT_UNREADABLE,
postRunArtifactDigestDeadline,
} from "../../src/application/reverse/ReverseEngineeringService.js";
import { createReverseEngineeringCommandPort } from "../../src/composition/reverseEngineering.js";
import { objdumpCommand } from "../../src/objdump/ObjdumpCommand.js";
import {
OwnedCommandFailure,
runOwnedCommand,
} from "../../src/process/OwnedCommand.js";
import type { ProviderProcessSupervisor } from "../../src/process/ProviderProcess.js";
import { REVERSE_ENGINEERING_TOOL_CONTRACTS } from "../../src/contracts/reverseEngineeringToolContracts.js";
import { awaitAcknowledgement } from "../fixtures/lifecycleAcknowledgement.js";
import { waitFor } from "../support/testWait.js";
import { withVerifierCleanup } from "../../scripts/lib/verifier-cleanup.mjs";
registerSharedReverseEngineeringEdgeCaseTests();
registerOwnedRizinCommandEvidenceTests({ sweepTokenOwnedProcesses: true });
it.each(["objdump", "rizin"] as const)(
"retains %s output-limit Evidence when owned cleanup remains incomplete",
async (provider) => {
const { directory, path } = await createArtifact();
const service = new ReverseEngineeringService({
runOwned: async (_spawn, limits) => {
expect(limits.diagnosticBytes).toBe(16 * 1024 * 1024);
throw new OwnedCommandFailure(
"output-limit",
"diagnostic output exceeded its budget",
providerSnapshot({
exitCode: null,
signal: "SIGTERM",
diagnosticTruncated: true,
}),
"owned descendant remains",
undefined,
["run-id", "pid:42"],
);
},
});
try {
const result =
provider === "objdump"
? await service.inspectWithObjdump({ path, operation: "symbols" })
: await service.executeRizinCommand({ path, command: "iI" });
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisOutputError",
cleanupIncomplete: true,
cleanup: {
reason: "owned descendant remains",
resources: ["run-id", "pid:42"],
},
partialObservation: {
normalized_result: {
stdout: "captured owned output",
exit_code: null,
signal: "SIGTERM",
output_truncated: true,
completion_status: "unknown",
artifact_sha256_after: null,
artifact_changed: null,
},
raw_result: null,
limitations: expect.arrayContaining([
expect.stringContaining("max_output_bytes=16777216"),
]),
},
},
});
} finally {
await rm(directory, { recursive: true, force: true });
}
},
);
it("records pathless objdump architecture support as provider capability evidence", async () => {
const { directory, path } = await createArtifact();
expect(objdumpCommand({ operation: "architectures" })).toEqual(["-i"]);
const digest = vi.fn(async () => "a".repeat(64));
const service = new CoreReverseEngineeringService({
commands: createReverseEngineeringCommandPort(process.env),
digest,
processes: {
lookup: findsNoExecutable,
runOwned: async () => ownedOutput("elf64-x86-64"),
},
});
try {
const result = await service.inspectWithObjdump({
operation: "architectures",
});
if (!result.ok) throw result.error;
expect(result.value.subject.identity.kind).toBe("unknown");
expect(result.value.parameters).not.toHaveProperty("path");
expect(result.value.parameters).not.toHaveProperty(
"artifact_sha256_before",
);
expect(result.value.normalized_result).toMatchObject({
artifact_sha256_after: null,
artifact_changed: null,
});
const contract = REVERSE_ENGINEERING_TOOL_CONTRACTS.find(
({ name }) => name === "inspect_with_objdump",
);
expect(contract?.outputSchema.safeParse(result.value).success).toBe(true);
expect(digest).not.toHaveBeenCalled();
expect(
await service.inspectWithObjdump({ path, operation: "architectures" }),
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
const ordinaryInspection = await service.inspectWithObjdump({
path,
operation: "file_headers",
});
expect(ordinaryInspection.ok).toBe(true);
expect(digest).toHaveBeenCalledTimes(2);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("uses the host environment when the service environment is omitted", async () => {
const { directory, path } = await createArtifact();
const key = "REA_REVERSE_TOOLS_ENV_FALLBACK_TEST";
const previous = process.env[key];
process.env[key] = "host-value";
let observedEnvironment: NodeJS.ProcessEnv | undefined;
const service = new CoreReverseEngineeringService({
commands: createReverseEngineeringCommandPort(process.env),
processes: {
lookup: findsNoExecutable,
runOwned: async (spawn) => {
observedEnvironment = spawn.env;
return ownedOutput("ok");
},
},
});
try {
const result = await service.inspectWithObjdump({
path,
operation: "file_headers",
});
expect(result.ok).toBe(true);
expect(observedEnvironment?.[key]).toBe("host-value");
} finally {
if (previous === undefined) delete process.env[key];
else process.env[key] = previous;
await rm(directory, { recursive: true, force: true });
}
});
it.each(["cancellation", "deadline"] as const)(
"interrupts a pending stat on %s and observes its eventual rejection",
async (interruption) => {
const { directory, path } = await createArtifact();
const controller = new AbortController();
let rejectStat: ((cause: Error) => void) | undefined;
let announceStat: (() => void) | undefined;
const statStarted = new Promise<void>((resolve) => {
announceStat = resolve;
});
const service = new ReverseEngineeringService({
stat: async () => {
announceStat?.();
return await new Promise<Stats>((_resolve, reject) => {
rejectStat = reject;
});
},
runOwned: async () => ownedOutput(),
});
const resultPromise = service.inspectWithObjdump(
{ path, operation: "file_headers", command_timeout_ms: 1_000 },
{ signal: controller.signal },
);
await withVerifierCleanup(async () => {
await awaitAcknowledgement(statStarted, resultPromise, "stat request");
if (interruption === "cancellation") controller.abort();
await expect(resultPromise).resolves.toMatchObject({
ok: false,
error: {
_tag:
interruption === "cancellation"
? "AnalysisCancelledError"
: "AnalysisTimeoutError",
},
});
rejectStat?.(new Error("late stat failure"));
await Promise.resolve();
}, [
() => {
controller.abort();
rejectStat?.(new Error("stat fixture cleanup"));
},
async () => {
await resultPromise;
},
async () => {
await rm(directory, { recursive: true, force: true });
},
]);
},
);
it("handles cancellation that races with stat listener registration", async () => {
const { directory, path } = await createArtifact();
let aborted = false;
const signal = {
get aborted() {
return aborted;
},
addEventListener: (
_type: string,
listener: Parameters<EventTarget["addEventListener"]>[1],
) => {
aborted = true;
if (typeof listener === "function") listener(new Event("abort"));
else listener.handleEvent(new Event("abort"));
},
removeEventListener: () => {},
dispatchEvent: () => true,
onabort: null,
reason: undefined,
throwIfAborted: () => {},
} as AbortSignal;
const stat = vi.fn(async () => ({ isFile: () => true }) as unknown as Stats);
const runOwned = vi.fn(async () => ownedOutput());
const service = new ReverseEngineeringService({ stat, runOwned });
try {
const result = await service.inspectWithObjdump(
{ path, operation: "file_headers" },
{ signal },
);
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
expect(stat).not.toHaveBeenCalled();
expect(runOwned).not.toHaveBeenCalled();
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("handles a synchronous stat provider throw as an artifact input failure", async () => {
const { directory, path } = await createArtifact();
const stat = vi.fn(() => {
throw Object.assign(new Error("stat failed before returning a promise"), {
code: "ENOENT",
});
});
const runOwned = vi.fn(async () => ownedOutput());
const service = new ReverseEngineeringService({
stat: stat as unknown as (path: string) => Promise<Stats>,
runOwned,
});
try {
const result = await service.inspectWithObjdump({
path,
operation: "file_headers",
});
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
expect(stat).toHaveBeenCalledTimes(1);
expect(runOwned).not.toHaveBeenCalled();
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("cancels a hash when the signal aborts while its listener is added", async () => {
const { directory, path } = await createArtifact();
let aborted = false;
// A signal that aborts as the hash adds its listener, before it reports
// the abort through `aborted`.
const signal = {
get aborted() {
return aborted;
},
addEventListener: (
_type: string,
listener: Parameters<EventTarget["addEventListener"]>[1],
) => {
aborted = true;
if (typeof listener === "function") listener(new Event("abort"));
else listener.handleEvent(new Event("abort"));
},
removeEventListener: () => {},
dispatchEvent: () => true,
onabort: null,
reason: undefined,
throwIfAborted: () => {},
} as AbortSignal;
const stat = vi.fn(async () => ({ isFile: () => true }) as unknown as Stats);
const runOwned = vi.fn(async () => ownedOutput());
const service = new ReverseEngineeringService({ stat, runOwned });
try {
const result = await service.inspectWithObjdump(
{ path, operation: "file_headers" },
{ signal },
);
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
expect(stat).not.toHaveBeenCalled();
expect(runOwned).not.toHaveBeenCalled();
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("cancels a hash before it opens the file when the signal aborts during stat", async () => {
const { directory, path } = await createArtifact();
const controller = new AbortController();
const stat = vi.fn(async () => {
controller.abort("stop after stat");
return { isFile: () => true } as unknown as Stats;
});
const runOwned = vi.fn(async () => ownedOutput());
const service = new ReverseEngineeringService({ stat, runOwned });
try {
const result = await service.inspectWithObjdump(
{ path, operation: "file_headers" },
{ signal: controller.signal },
);
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError", cause: "stop after stat" },
});
expect(stat).toHaveBeenCalledTimes(1);
expect(runOwned).not.toHaveBeenCalled();
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("rejects malformed Rizin requests before touching the provider", async () => {
const runOwned = vi.fn(async () => ownedOutput());
const service = new ReverseEngineeringService({ runOwned });
const result = await service.executeRizinCommand({ path: "sample.bin" });
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisInputError",
operation: "execute_rizin_command",
issues: [
{ path: ["command"], reason: "missing_argument", expected: "string" },
],
},
});
expect(runOwned).not.toHaveBeenCalled();
});
it("rejects new operations after service shutdown begins", async () => {
const { directory, path } = await createArtifact();
const runOwned = vi.fn(async () => ownedOutput());
const service = new ReverseEngineeringService({ runOwned });
try {
await service.close();
const result = await service.executeRizinCommand({ path, command: "iI" });
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error._tag).toBe("AnalysisOutputError");
expect(result.error.message).toContain(
"Reverse-engineering service is closed.",
);
}
expect(runOwned).not.toHaveBeenCalled();
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("rejects work after reaching the concurrent provider-operation limit", async () => {
const { directory, path } = await createArtifact();
let releaseProviders: (() => void) | undefined;
const providerGate = new Promise<void>((resolve) => {
releaseProviders = resolve;
});
let providerCalls = 0;
const service = new ReverseEngineeringService({
runOwned: async () => {
providerCalls += 1;
await providerGate;
return ownedOutput("ok");
},
});
const admitted = Array.from({ length: 8 }, () =>
service.executeRizinCommand({ path, command: "iI" }),
);
await withVerifierCleanup(async () => {
const rejection = service.executeRizinCommand({ path, command: "iI" });
await awaitAcknowledgement(
rejection,
Promise.all(admitted),
"capacity response",
);
const rejected = await rejection;
expect(rejected.ok).toBe(false);
if (!rejected.ok) {
expect(rejected.error._tag).toBe("AnalysisResourceConstraintError");
expect(rejected.error).toBeInstanceOf(AnalysisResourceConstraintError);
if (rejected.error instanceof AnalysisResourceConstraintError)
expect(rejected.error.reportedLimits).toMatchObject({
max_concurrent_operations: 8,
active_operations: 8,
});
}
expect(providerCalls).toBe(0);
releaseProviders?.();
const results = await Promise.all(admitted);
expect(results.every((result) => result.ok)).toBe(true);
expect(providerCalls).toBe(8);
}, [
() => releaseProviders?.(),
async () => {
await Promise.allSettled(admitted);
},
async () => {
await rm(directory, { recursive: true, force: true });
},
]);
});
it("cancels when an AbortSignal becomes aborted during listener registration", async () => {
const { directory, path } = await createArtifact();
const controller = new AbortController();
let abortedReads = 0;
const signal = new Proxy(controller.signal, {
get(target, property) {
if (property === "aborted") return ++abortedReads > 1;
const value = Reflect.get(target, property, target) as unknown;
return typeof value === "function" ? value.bind(target) : value;
},
});
const runOwned = vi.fn(async () => ownedOutput());
const service = new ReverseEngineeringService({ runOwned });
try {
const result = await service.inspectWithObjdump(
{ path, operation: "file_headers" },
{ signal },
);
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
expect(abortedReads).toBe(2);
expect(runOwned).not.toHaveBeenCalled();
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("drains an active provider operation before service shutdown resolves", async () => {
const { directory, path } = await createArtifact();
let signal: AbortSignal | undefined;
let releaseRun!: () => void;
const runGate = new Promise<void>((resolve) => {
releaseRun = resolve;
});
let runStarted: (() => void) | undefined;
const started = new Promise<void>((resolve) => {
runStarted = resolve;
});
const service = new ReverseEngineeringService({
runOwned: async (_spawn, _limits, options) => {
signal = options?.signal;
runStarted?.();
await runGate;
return ownedOutput("finished");
},
});
const operation = service.executeRizinCommand({ path, command: "iI" });
let closing: Promise<void> | undefined;
await withVerifierCleanup(async () => {
await awaitAcknowledgement(started, operation, "provider command");
let closed = false;
closing = service.close().then(() => {
closed = true;
});
expect(signal?.aborted).toBe(true);
expect(closed).toBe(false);
releaseRun();
await closing;
expect(closed).toBe(true);
await expect(operation).resolves.toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
}, [
releaseRun,
async () => {
await operation;
},
async () => {
await closing;
},
() => service.close(),
() => rm(directory, { recursive: true, force: true }),
]);
});
it("relays caller cancellation to the admitted provider signal", async () => {
const { directory, path } = await createArtifact();
const controller = new AbortController();
const addAbortListener = vi.spyOn(controller.signal, "addEventListener");
let announceStarted: (() => void) | undefined;
const started = new Promise<void>((resolve) => {
announceStarted = resolve;
});
let releaseRun!: () => void;
const runGate = new Promise<void>((resolve) => {
releaseRun = resolve;
});
let providerSignal: AbortSignal | undefined;
const service = new CoreReverseEngineeringService({
commands: createReverseEngineeringCommandPort(process.env),
processes: {
lookup: findsNoExecutable,
runOwned: async (_spawn, _limits, options) => {
providerSignal = options?.signal;
announceStarted?.();
await runGate;
return ownedOutput("captured");
},
},
});
const operation = service.inspectWithObjdump(
{ path, operation: "file_headers" },
{ signal: controller.signal },
);
await withVerifierCleanup(async () => {
await awaitAcknowledgement(started, operation, "provider command");
controller.abort();
expect(addAbortListener).toHaveBeenCalledWith(
"abort",
expect.any(Function),
{ once: true },
);
expect(providerSignal?.aborted).toBe(true);
releaseRun();
await expect(operation).resolves.toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
}, [
() => controller.abort(),
releaseRun,
async () => {
await operation;
},
() => service.close(),
() => rm(directory, { recursive: true, force: true }),
]);
});
it("passes an AbortSignal-like caller value through without relaying it", async () => {
const { directory, path } = await createArtifact();
const signal = {
aborted: false,
addEventListener: vi.fn(() => {
throw new Error(
"A non-native signal must not register a relay listener.",
);
}),
removeEventListener: vi.fn(),
} as unknown as AbortSignal;
const digest = vi.fn(async (_path: string, bounds?: FileDigestBounds) => {
expect(bounds?.signal).toBe(signal);
return "a".repeat(64);
});
const runOwned = vi.fn<typeof runOwnedCommand>(
async (_spawn, _limits, options) => {
expect(options?.signal).toBe(signal);
return ownedOutput("ok");
},
);
const service = new CoreReverseEngineeringService({
commands: createReverseEngineeringCommandPort(process.env),
digest,
processes: { lookup: findsNoExecutable, runOwned },
});
try {
const result = await service.inspectWithObjdump(
{ path, operation: "file_headers" },
{ signal },
);
expect(result.ok).toBe(true);
expect(signal.addEventListener).not.toHaveBeenCalled();
expect(signal.removeEventListener).toHaveBeenCalledTimes(1);
expect(digest).toHaveBeenCalledTimes(2);
expect(runOwned).toHaveBeenCalledTimes(1);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("cancels after operation admission and before starting the artifact digest", async () => {
const { directory, path } = await createArtifact();
let reads = 0;
const signal = {
get aborted() {
reads += 1;
return reads > 1;
},
addEventListener() {},
removeEventListener() {},
throwIfAborted() {},
onabort: null,
reason: undefined,
dispatchEvent: () => true,
} as AbortSignal;
let digestStarted = false;
const service = new ReverseEngineeringService({
digest: async () => {
digestStarted = true;
return "a".repeat(64);
},
});
try {
const result = await service.inspectWithObjdump(
{ path, operation: "file_headers" },
{ signal },
);
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
expect(reads).toBeGreaterThanOrEqual(2);
expect(digestStarted).toBe(false);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("preserves raw retained byte counts when output text replaces invalid UTF-8", async () => {
const { directory, path } = await createArtifact();
const snapshot = providerSnapshot({
stdout: { text: "�", bytes: 1, observedBytes: 1, invalidUtf8: true },
stderr: { text: "�", bytes: 2, observedBytes: 2, invalidUtf8: true },
exitCode: 7,
});
const service = new ReverseEngineeringService({
runOwned: async () => {
throw new OwnedCommandFailure(
"cancelled",
"Command was cancelled after output capture",
snapshot,
);
},
});
try {
const result = await service.executeRizinCommand({ path, command: "iI" });
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCancelledError",
capturedOutput: {
stdout: "�",
stderr: "�",
stdout_bytes: 1,
stderr_bytes: 2,
},
},
});
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("preserves the provider remediation when owned process preparation fails", async () => {
const { directory, path } = await createArtifact();
const remediation = new AnalysisCapabilityUnavailableError(
"rizin",
"execute_rizin_command",
"Rizin needs permission to inspect this process",
{ userMessage: "Grant process inspection permission, then retry." },
);
const service = new ReverseEngineeringService({
runOwned: async () => {
throw new OwnedCommandFailure(
"process",
"Could not prepare process ownership",
null,
null,
{ cause: remediation },
);
},
});
try {
const result = await service.executeRizinCommand({ path, command: "iI" });
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCapabilityUnavailableError",
providerId: "rizin",
reason: remediation.reason,
userMessage: remediation.userMessage,
},
});
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it.each([
["Error", new Error("cleanup state unknown"), "cleanup state unknown"],
["non-Error", "cleanup state unknown", "cleanup state unknown"],
] as const)(
"preserves a thrown %s cleanup reason while blocking new provider work",
async (_label, cause, expectedReason) => {
const { directory, path } = await createArtifact();
const cleanupOwner = {
stop: vi.fn(async () => Promise.reject(cause)),
} as unknown as ProviderProcessSupervisor;
const runOwned = vi.fn<typeof runOwnedCommand>(async () => {
throw new OwnedCommandFailure(
"cancelled",
"command cancelled",
providerSnapshot({ exitCode: null }),
"cleanup pending",
undefined,
["run-id", "pid:42"],
cleanupOwner,
);
});
const service = new ReverseEngineeringService({ runOwned });
try {
const first = await service.executeRizinCommand({ path, command: "iI" });
expect(first.ok).toBe(false);
const blocked = await service.executeRizinCommand({
path,
command: "iI",
});
expect(blocked).toMatchObject({
ok: false,
error: {
_tag: "AnalysisOutputError",
cleanup: { reason: expectedReason, resources: ["run-id", "pid:42"] },
},
});
await expect(service.close()).rejects.toMatchObject({
cleanup: { reason: expectedReason, resources: ["run-id", "pid:42"] },
});
expect(cleanupOwner.stop).toHaveBeenCalledTimes(2);
expect(runOwned).toHaveBeenCalledTimes(1);
} finally {
await service.close().catch(() => undefined);
await rm(directory, { recursive: true, force: true });
}
},
);
it("releases a retained provider owner after cleanup succeeds", async () => {
const { directory, path } = await createArtifact();
const cleanupOwner = {
stop: vi.fn(async () => ({ status: "verified-cleanup" as const })),
} as unknown as ProviderProcessSupervisor;
const runOwned = vi
.fn<typeof runOwnedCommand>()
.mockRejectedValueOnce(
new OwnedCommandFailure(
"cancelled",
"command cancelled",
providerSnapshot({ exitCode: null }),
"cleanup pending",
undefined,
["run-id", "pid:42"],
cleanupOwner,
),
)
.mockResolvedValue(providerSnapshot());
const service = new ReverseEngineeringService({ runOwned });
try {
const first = await service.executeRizinCommand({ path, command: "iI" });
expect(first.ok).toBe(false);
const recovered = await service.executeRizinCommand({
path,
command: "iI",
});
expect(recovered.ok).toBe(true);
expect(cleanupOwner.stop).toHaveBeenCalledTimes(1);
expect(runOwned).toHaveBeenCalledTimes(2);
} finally {
await service.close().catch(() => undefined);
await rm(directory, { recursive: true, force: true });
}
});
it("keeps a cleanup owner confirmed when a concurrent retry observed it incomplete", async () => {
const { directory, path } = await createArtifact();
let releaseVerifiedStop: () => void = () => undefined;
const verifiedStop = new Promise<{ status: "verified-cleanup" }>(
(resolve) => {
releaseVerifiedStop = () => resolve({ status: "verified-cleanup" });
},
);
type Stop = Awaited<ReturnType<ProviderProcessSupervisor["stop"]>>;
let releaseStaleStop: () => void = () => undefined;
const staleStop = new Promise<Stop>((resolve) => {
releaseStaleStop = () =>
resolve({ status: "incomplete", reason: "stale concurrent stop" });
});
const incomplete = (reason: string): Promise<Stop> =>
Promise.resolve({ status: "incomplete", reason });
const queued: Array<() => Promise<Stop>> = [];
let stops = 0;
const cleanupOwner = {
stop: vi.fn(() => {
stops += 1;
return (queued.shift() ?? (() => incomplete("group remains")))();
}),
} as unknown as ProviderProcessSupervisor;
const runOwned = vi
.fn<typeof runOwnedCommand>()
.mockRejectedValueOnce(
new OwnedCommandFailure(
"process",
"objdump cleanup could not be verified",
providerSnapshot({ exitCode: null }),
"group remains",
undefined,
["run-id", "pid:42"],
cleanupOwner,
),
)
.mockResolvedValue(providerSnapshot());
const service = new ReverseEngineeringService({ runOwned });
try {
const first = await service.inspectWithObjdump({
path,
operation: "symbols",
});
expect(first).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
});
// The first retry verifies the stop while a second, concurrent retry's
// stop reports the group as still present.
const before = stops;
queued.push(
() => verifiedStop,
() => staleStop,
);
const confirming = service.retryCleanup();
await waitFor(() => expect(stops).toBe(before + 1));
const stale = service.retryCleanup();
await waitFor(() => expect(stops).toBe(before + 2));
releaseVerifiedStop();
expect(await confirming).toEqual({ ok: true, value: null });
// The concurrent stop reports only after the owner was confirmed.
releaseStaleStop();
await stale;
// The confirmed owner is gone: a later retry has nothing left to stop.
expect(await service.retryCleanup()).toEqual({ ok: true, value: null });
expect(stops).toBe(before + 2);
} finally {
releaseVerifiedStop();
releaseStaleStop();
await service.close().catch(() => undefined);
await rm(directory, { recursive: true, force: true });
}
});
it("stops an owner registered during cleanup retry before admitting another command", async () => {
const { directory, path } = await createArtifact();
let releaseFirst: () => void = () => undefined;
const firstHeld = new Promise<void>((resolve) => {
releaseFirst = resolve;
});
let releaseSecond: () => void = () => undefined;
const secondHeld = new Promise<void>((resolve) => {
releaseSecond = resolve;
});
let releaseVerifiedStop: (
value: Awaited<ReturnType<ProviderProcessSupervisor["stop"]>>,
) => void = () => undefined;
const verifiedStop = new Promise<
Awaited<ReturnType<ProviderProcessSupervisor["stop"]>>
>((resolve) => {
releaseVerifiedStop = resolve;
});
const ownerA = {
stop: vi.fn(() => verifiedStop),
} as unknown as ProviderProcessSupervisor;
const ownerB = {
stop: vi.fn(async () => ({
status: "incomplete" as const,
reason: "owner b remains",
})),
} as unknown as ProviderProcessSupervisor;
const retained = (
reason: string,
resources: readonly string[],
owner: ProviderProcessSupervisor,
) =>
new OwnedCommandFailure(
"process",
reason,
providerSnapshot({ exitCode: null }),
reason,
undefined,
resources,
owner,
);
let entered = 0;
const runOwned = vi.fn<typeof runOwnedCommand>(async () => {
entered += 1;
if (entered === 1) {
await firstHeld;
throw retained("owner a remains", ["owner-a", "pid:41"], ownerA);
}
if (entered === 2) {
await secondHeld;
throw retained("owner b remains", ["owner-b", "pid:42"], ownerB);
}
return providerSnapshot();
});
const service = new ReverseEngineeringService({ runOwned });
const pending: Array<Promise<unknown>> = [];
try {
const first = service.inspectWithObjdump({ path, operation: "symbols" });
pending.push(first);
await waitFor(() => expect(entered).toBe(1));
const second = service.inspectWithObjdump({ path, operation: "symbols" });
pending.push(second);
await waitFor(() => expect(entered).toBe(2));
releaseFirst();
expect(await first).toMatchObject({
ok: false,
error: {
_tag: "AnalysisOutputError",
cleanupIncomplete: true,
cleanup: { resources: ["owner-a", "pid:41"] },
},
});
const third = service.inspectWithObjdump({ path, operation: "symbols" });
pending.push(third);
await waitFor(() => expect(ownerA.stop).toHaveBeenCalledTimes(1));
releaseSecond();
expect(await second).toMatchObject({
ok: false,
error: {
_tag: "AnalysisOutputError",
cleanupIncomplete: true,
cleanup: { resources: ["owner-b", "pid:42"] },
},
});
releaseVerifiedStop({ status: "verified-cleanup" });
expect(await third).toMatchObject({
ok: false,
error: {
_tag: "AnalysisOutputError",
operation: "inspect_with_objdump",
cleanupIncomplete: true,
cleanup: {
reason: "owner b remains",
resources: ["owner-b", "pid:42"],
},
},
});
expect(entered).toBe(2);
expect(ownerB.stop).toHaveBeenCalledTimes(1);
// The admission that observed the incomplete stop binds the cleanup error.
// A later retry keeps that owner and its resources.
expect(await service.retryCleanup()).toMatchObject({
ok: false,
error: {
_tag: "AnalysisOutputError",
operation: "inspect_with_objdump",
cleanupIncomplete: true,
cleanup: {
reason: "owner b remains",
resources: ["owner-b", "pid:42"],
},
},
});
expect(ownerB.stop).toHaveBeenCalledTimes(2);
expect(ownerA.stop).toHaveBeenCalledTimes(1);
} finally {
releaseFirst();
releaseSecond();
releaseVerifiedStop({ status: "verified-cleanup" });
await Promise.allSettled(pending);
await service.close().catch(() => undefined);
await rm(directory, { recursive: true, force: true });
}
});
it("retains an objdump command's unverified process owner until a later inspection stops it", async () => {
const { directory, path } = await createArtifact();
let stopped = false;
const cleanupOwner = {
stop: vi.fn(async () =>
stopped
? { status: "verified-cleanup" as const }
: { status: "incomplete" as const, reason: "objdump group remains" },
),
} as unknown as ProviderProcessSupervisor;
const runOwned = vi
.fn<typeof runOwnedCommand>()
.mockRejectedValueOnce(
new OwnedCommandFailure(
"process",
"objdump cleanup could not be verified",
providerSnapshot({ exitCode: null }),
"objdump group remains",
undefined,
["run-id", "pid:42"],
cleanupOwner,
),
)
.mockResolvedValue(providerSnapshot());
const service = new ReverseEngineeringService({ runOwned });
try {
const first = await service.inspectWithObjdump({
path,
operation: "symbols",
});
if (first.ok) throw new Error("Expected retained objdump cleanup");
expect(first.error.cleanupIncomplete).toBe(true);
expect(first.error.cleanup).toMatchObject({
reason: "objdump group remains",
resources: ["run-id", "pid:42"],
});
const blocked = await service.inspectWithObjdump({
path,
operation: "symbols",
});
expect(blocked).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
});
expect(runOwned).toHaveBeenCalledOnce();
stopped = true;
const recovered = await service.inspectWithObjdump({
path,
operation: "symbols",
});
if (!recovered.ok) throw recovered.error;
expect(first.error.cleanupIncomplete).toBe(false);
expect(cleanupOwner.stop).toHaveBeenCalledTimes(2);
expect(runOwned).toHaveBeenCalledTimes(2);
} finally {
await service.close().catch(() => undefined);
await rm(directory, { recursive: true, force: true });
}
});
it("retains a capability failure when its injected owned runner also reports incomplete cleanup", async () => {
const { directory, path } = await createArtifact();
const capability = new AnalysisCapabilityUnavailableError(
"rizin",
"execute_rizin_command",
"Ownership inspection is unavailable.",
{ diagnostics: { source: "owned-runner" } },
);
const cleanupOwner = {
stop: vi.fn(async () => ({ status: "verified-cleanup" as const })),
} as unknown as ProviderProcessSupervisor;
const runOwned = vi
.fn<typeof runOwnedCommand>()
.mockRejectedValueOnce(
new OwnedCommandFailure(
"process",
"Ownership inspection failed after launch.",
null,
"owned descendant remains",
{ cause: capability },
["run-id", "pid:42"],
cleanupOwner,
),
)
.mockResolvedValue(providerSnapshot());
const service = new ReverseEngineeringService({ runOwned });
try {
const first = await service.executeRizinCommand({ path, command: "iI" });
if (first.ok) throw new Error("Expected the capability failure");
expect(first.error._tag).toBe("AnalysisCapabilityUnavailableError");
expect(first.error).toBeInstanceOf(AnalysisCapabilityUnavailableError);
// The selected executable, as the command port resolves it here.
const selected = createReverseEngineeringCommandPort(process.env).rizin({
path,
command: "iI",
});
if (!selected.ok) throw new Error("Expected the configured Rizin command");
expect(first.error.diagnostics).toEqual({
source: "owned-runner",
provider_executable: selected.value.executable,
artifact_path: path,
artifact_sha256: createHash("sha256")
.update(await readFile(path))
.digest("hex"),
});
expect(first.error.cleanupIncomplete).toBe(true);
expect(first.error.cleanup).toMatchObject({
reason: "owned descendant remains",
resources: ["run-id", "pid:42"],
});
const recovered = await service.executeRizinCommand({
path,
command: "iI",
});
if (!recovered.ok) throw recovered.error;
expect(cleanupOwner.stop).toHaveBeenCalledOnce();
expect(first.error.cleanupIncomplete).toBe(false);
expect(runOwned).toHaveBeenCalledTimes(2);
} finally {
await service.close().catch(() => undefined);
await rm(directory, { recursive: true, force: true });
}
});
it("preserves a provider timeout when cancellation arrives during the final digest", async () => {
const { directory, path } = await createArtifact();
const controller = new AbortController();
let digests = 0;
const service = new ReverseEngineeringService({
digest: async () => {
digests += 1;
if (digests === 2) controller.abort();
return "a".repeat(64);
},
runOwned: async () => {
throw ownedFailure(
"timeout",
ownedOutput("partial timeout output", "timeout diagnostic", {
exitCode: null,
}),
);
},
});
try {
const result = await service.executeRizinCommand(
{ path, command: "iI" },
{ signal: controller.signal },
);
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisTimeoutError",
capturedOutput: {
stdout: "partial timeout output",
stderr: "timeout diagnostic",
},
partialObservation: {
normalized_result: {
stdout: "partial timeout output",
completion_status: "unknown",
},
raw_result: null,
limitations: expect.arrayContaining([
expect.stringContaining("AnalysisTimeoutError"),
]),
},
},
});
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("classifies E2BIG as a provider command resource constraint", async () => {
const { directory, path } = await createArtifact();
// The owned supervisor rethrows the launcher's spawn error unchanged.
const runOwned = vi
.fn<typeof runOwnedCommand>()
.mockImplementationOnce(async (spawn) => {
throw spawnFailure("E2BIG", spawn.command);
})
.mockResolvedValue(providerSnapshot());
const service = new ReverseEngineeringService({
runOwned,
});
try {
const result = await service.executeRizinCommand({ path, command: "iI" });
if (result.ok) throw new Error("Expected an argument-list constraint");
expect(result.error).toBeInstanceOf(AnalysisResourceConstraintError);
expect(result.error).toMatchObject({
resource: "transport",
operation: "execute_rizin_command",
reportedLimits: {
spawn_error: "E2BIG",
argument_bytes: expect.any(Number),
},
retryable: false,
});
expect(result.error.cleanupIncomplete).toBe(false);
const retried = await service.executeRizinCommand({ path, command: "iI" });
expect(retried.ok).toBe(true);
expect(runOwned).toHaveBeenCalledTimes(2);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it("preserves completed command Evidence while its post-run digest awaits cleanup", async () => {
const { directory, path } = await createArtifact();
const service = new ReverseEngineeringService({
runOwned: async () => {
throw new OwnedCommandFailure(
"process",
"Owned process cleanup remains incomplete.",
providerSnapshot({ exitCode: 0 }),
"descendant remains active",
undefined,
["run-id", "pid:42"],
);
},
});
try {
const result = await service.executeRizinCommand({ path, command: "iI" });
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisOutputError",
partialObservation: {
normalized_result: {
exit_code: 0,
completion_status: "complete",
artifact_sha256_after: null,
artifact_changed: null,
},
raw_result: null,
limitations: expect.arrayContaining([
expect.stringContaining(
"owned provider cleanup was incomplete at observation time",
),
]),
},
},
});
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it.each(["objdump", "rizin"] as const)(
"keeps a %s post-run digest deadline and its recovery beside complete output",
async (provider) => {
const { directory, path } = await createArtifact();
let digests = 0;
const service = new ReverseEngineeringService({
digest: async () => {
digests += 1;
if (digests === 1) return "a".repeat(64);
// The read finished, but the close a stalled mount holds did not.
throw Object.assign(new Error("digest close reached the deadline"), {
code: "ETIMEDOUT",
});
},
runOwned: async () => ownedOutput("observed"),
});
try {
const result =
provider === "objdump"
? await service.inspectWithObjdump({
path,
operation: "file_headers",
command_timeout_ms: 1_500,
})
: await service.executeRizinCommand({
path,
command: "iI",
command_timeout_ms: 1_500,
});
expect(digests).toBe(2);
expect(result).toMatchObject({
ok: true,
value: {
normalized_result: {
stdout: "observed",
completion_status: "complete",
artifact_sha256_after: null,
artifact_changed: null,
},
raw_result: null,
},
});
if (!result.ok) return;
expect(result.value.limitations).toContain(
postRunArtifactDigestDeadline(provider, 1_500),
);
expect(result.value.limitations).not.toContain(
POST_RUN_ARTIFACT_UNREADABLE,
);
// The limitation names the setting that stopped the hash, its value
// and the error, so the caller can raise that setting.
const deadline = postRunArtifactDigestDeadline(provider, 1_500);
for (const fact of ["command_timeout_ms", "1500", "ETIMEDOUT"])
expect(deadline).toContain(fact);
} finally {
await rm(directory, { recursive: true, force: true });
}
},
);
it("records an explicit loss marker when provider bytes are invalid UTF-8", async () => {
const { directory, path } = await createArtifact();
const service = new ReverseEngineeringService({
runOwned: async () =>
providerSnapshot({
stdout: {
text: "captured � output",
bytes: 17,
observedBytes: 17,
invalidUtf8: true,
},
}),
});
try {
const result = await service.executeRizinCommand({ path, command: "iI" });
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value).toMatchObject({
normalized_result: { stdout: "captured � output" },
raw_result: null,
});
expect(result.value.limitations).toContainEqual(
expect.stringMatching(
/stdout bytes.*invalid or incomplete UTF-8.*replacement characters.*do not preserve the original bytes/iu,
),
);
}
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it.each([
[
"stderr only",
{
stderr: {
text: "diagnostic � output",
bytes: 22,
observedBytes: 22,
invalidUtf8: true,
},
},
"stderr",
],
[
"both streams",
{
stdout: {
text: "captured � output",
bytes: 17,
observedBytes: 17,
invalidUtf8: true,
},
stderr: {
text: "diagnostic � output",
bytes: 22,
observedBytes: 22,
invalidUtf8: true,
},
},
"stdout and stderr",
],
[
"stdout of a nonzero exit",
{
exitCode: 2,
stdout: {
text: "captured � output",
bytes: 17,
observedBytes: 17,
invalidUtf8: true,
},
},
"stdout",
],
] as const)(
"records invalid UTF-8 loss for %s",
async (_label, overrides, streams) => {
const { directory, path } = await createArtifact();
const service = new ReverseEngineeringService({
runOwned: async () => providerSnapshot(overrides),
});
try {
const result = await service.executeRizinCommand({ path, command: "iI" });
expect(result.ok).toBe(true);
if (result.ok)
expect(result.value.limitations).toContainEqual(
expect.stringMatching(
new RegExp(
`${streams} bytes.*invalid or incomplete UTF-8.*replacement characters.*do not preserve the original bytes`,
"iu",
),
),
);
} finally {
await rm(directory, { recursive: true, force: true });
}
},
);
it.each(["objdump", "rizin"] as const)(
"preserves successful %s output-loss facts independently of process completion",
async (provider) => {
const { directory, path } = await createArtifact();
const service = new ReverseEngineeringService({
runOwned: async () => providerSnapshot({ diagnosticTruncated: true }),
});
try {
const result =
provider === "objdump"
? await service.inspectWithObjdump({ path, operation: "symbols" })
: await service.executeRizinCommand({ path, command: "iI" });
if (!result.ok) throw result.error;
expect(result.value.normalized_result).toMatchObject({
exit_code: 0,
output_truncated: true,
completion_status: "complete",
});
expect(result.value.limitations).toContainEqual(
expect.stringMatching(
/output is partial.*bytes were omitted.*process completion.*separately/iu,
),
);
} finally {
await service.close();
await rm(directory, { recursive: true, force: true });
}
},
);
it.each(["during", "after"] as const)(
"keeps invalid UTF-8 flags when cancellation ends a command %s its run",
async (when) => {
const { directory, path } = await createArtifact();
const controller = new AbortController();
const snapshot = providerSnapshot({
stdout: {
text: "captured � output",
bytes: 17,
observedBytes: 17,
invalidUtf8: true,
},
});
const service = new ReverseEngineeringService({
runOwned: async () => {
controller.abort("stop the command");
if (when === "during")
throw new OwnedCommandFailure(
"cancelled",
"Command cancelled.",
snapshot,
null,
{ cancellation: { reason: "stop the command" } },
);
return snapshot;
},
});
try {
const result = await service.executeRizinCommand(
{ path, command: "iI" },
{ signal: controller.signal },
);
if (result.ok) throw new Error("Expected cancellation to end the call");
expect(result.error._tag).toBe("AnalysisCancelledError");
expect(result.error.capturedOutput).toMatchObject({
stdout: "captured � output",
stdout_invalid_utf8: true,
});
expect(result.error.capturedOutput).not.toHaveProperty(
"stderr_invalid_utf8",
);
} finally {
await rm(directory, { recursive: true, force: true });
}
},
);