fix(native): retain LLDB cleanup ownership through client close
This commit is contained in:
@@ -81,6 +81,7 @@ const tracer: NativeCallTracer & { calls: number } = {
|
||||
}),
|
||||
);
|
||||
},
|
||||
close: () => Promise.resolve(ok(null)),
|
||||
};
|
||||
|
||||
it("routes observe_native_calls through MCP with schema-checked input and output", async () => {
|
||||
@@ -88,7 +89,12 @@ it("routes observe_native_calls through MCP with schema-checked input and output
|
||||
const path = join(directory, "Tool");
|
||||
await writeFile(path, machoHeader());
|
||||
const session = createTestBinarySession(
|
||||
new NativeMacOSProvider({}, new NativeFixtureRunner(), "darwin", tracer),
|
||||
new NativeMacOSProvider(
|
||||
{},
|
||||
new NativeFixtureRunner(),
|
||||
"darwin",
|
||||
() => tracer,
|
||||
),
|
||||
);
|
||||
const server = createServer({ kind: "session", session });
|
||||
const client = new Client({ name: "native-calls-mcp-test", version: "1" });
|
||||
@@ -138,6 +144,62 @@ it("routes observe_native_calls through MCP with schema-checked input and output
|
||||
}
|
||||
});
|
||||
|
||||
const partialObservationFor = (options: {
|
||||
readonly path: string;
|
||||
readonly sha256: string;
|
||||
readonly arguments: string[];
|
||||
readonly environment: Record<string, string>;
|
||||
readonly workingDirectory: string;
|
||||
readonly reason: "cancelled" | "cleanup-failure";
|
||||
}) =>
|
||||
nativeCallPartialObservationSchema.parse({
|
||||
kind: "native-call-observation",
|
||||
target: {
|
||||
path: options.path,
|
||||
sha256: options.sha256,
|
||||
architecture: "arm64",
|
||||
arguments: options.arguments,
|
||||
environment: options.environment,
|
||||
working_directory: options.workingDirectory,
|
||||
},
|
||||
process: {
|
||||
pid: 4242,
|
||||
stdout: {
|
||||
text: "partial target output",
|
||||
bytes: 21,
|
||||
truncated: true,
|
||||
complete: false,
|
||||
},
|
||||
stderr: {
|
||||
text: "debugger diagnostic",
|
||||
bytes: 19,
|
||||
truncated: false,
|
||||
complete: false,
|
||||
},
|
||||
other_stops: ["signal SIGSTOP"],
|
||||
},
|
||||
debugger: { version: "lldb-fixture" },
|
||||
events: [
|
||||
{
|
||||
sequence: 0,
|
||||
elapsed_ms: 4,
|
||||
thread_id: 3,
|
||||
breakpoint_index: 0,
|
||||
load_address: "0x1000",
|
||||
file_address: "0x1000",
|
||||
module: "Tool",
|
||||
module_path: options.path,
|
||||
symbol: "open",
|
||||
receiver_class: null,
|
||||
selector: null,
|
||||
registers: [{ name: "x0", value: "0x2" }],
|
||||
backtrace: [],
|
||||
},
|
||||
],
|
||||
coverage: { status: "partial", reason: options.reason },
|
||||
limitations: ["Observation ended before the requested window completed."],
|
||||
});
|
||||
|
||||
it.each([
|
||||
["cancelled", "cancelled", undefined],
|
||||
[
|
||||
@@ -161,57 +223,16 @@ it.each([
|
||||
const launchArguments = ["--fixture", "selected argument"];
|
||||
const launchEnvironment = { REA_NATIVE_FIXTURE: "selected value" };
|
||||
const workingDirectory = directory;
|
||||
const partialObservation = nativeCallPartialObservationSchema.parse({
|
||||
kind: "native-call-observation",
|
||||
target: {
|
||||
path,
|
||||
sha256,
|
||||
architecture: "arm64",
|
||||
arguments: launchArguments,
|
||||
environment: launchEnvironment,
|
||||
working_directory: workingDirectory,
|
||||
},
|
||||
process: {
|
||||
pid: 4242,
|
||||
stdout: {
|
||||
text: "partial target output",
|
||||
bytes: 21,
|
||||
truncated: true,
|
||||
complete: false,
|
||||
},
|
||||
stderr: {
|
||||
text: "debugger diagnostic",
|
||||
bytes: 19,
|
||||
truncated: false,
|
||||
complete: false,
|
||||
},
|
||||
other_stops: ["signal SIGSTOP"],
|
||||
},
|
||||
debugger: { version: "lldb-fixture" },
|
||||
events: [
|
||||
{
|
||||
sequence: 0,
|
||||
elapsed_ms: 4,
|
||||
thread_id: 3,
|
||||
breakpoint_index: 0,
|
||||
load_address: "0x1000",
|
||||
file_address: "0x1000",
|
||||
module: "Tool",
|
||||
module_path: path,
|
||||
symbol: "open",
|
||||
receiver_class: null,
|
||||
selector: null,
|
||||
registers: [{ name: "x0", value: "0x2" }],
|
||||
backtrace: [],
|
||||
},
|
||||
],
|
||||
coverage: {
|
||||
status: "partial",
|
||||
reason: cleanup === undefined ? "cancelled" : "cleanup-failure",
|
||||
},
|
||||
limitations: ["Observation ended before the requested window completed."],
|
||||
const partialObservation = partialObservationFor({
|
||||
path,
|
||||
sha256,
|
||||
arguments: launchArguments,
|
||||
environment: launchEnvironment,
|
||||
workingDirectory,
|
||||
reason: cleanup === undefined ? "cancelled" : "cleanup-failure",
|
||||
});
|
||||
const tracer: NativeCallTracer = {
|
||||
close: () => Promise.resolve(ok(null)),
|
||||
trace: () =>
|
||||
Promise.resolve(
|
||||
err(
|
||||
@@ -231,7 +252,12 @@ it.each([
|
||||
),
|
||||
};
|
||||
const session = createTestBinarySession(
|
||||
new NativeMacOSProvider({}, new NativeFixtureRunner(), "darwin", tracer),
|
||||
new NativeMacOSProvider(
|
||||
{},
|
||||
new NativeFixtureRunner(),
|
||||
"darwin",
|
||||
() => tracer,
|
||||
),
|
||||
);
|
||||
const server = createServer({ kind: "session", session });
|
||||
const client = new Client({
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { spawn } from "node:child_process";
|
||||
import { once } from "node:events";
|
||||
import { access, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { AnalysisCancelledError } from "../../../../src/domain/analysisErrorCore.js";
|
||||
import { ProviderCleanupError } from "../../../../src/domain/providerCleanupError.js";
|
||||
import { ok } from "../../../../src/domain/result.js";
|
||||
import { cleanupOwnedProcessGroup } from "../../../../src/process/ProcessOwnership.js";
|
||||
import { observeProcessStartIdentity } from "../../../../src/process/ProcessOwnershipObservation.js";
|
||||
import {
|
||||
ProviderProcessSupervisor,
|
||||
spawnOwnedProviderProcess,
|
||||
} from "../../../../src/process/ProviderProcess.js";
|
||||
import type { NativeCallTracer } from "../../../../src/native/LldbCallTracer.js";
|
||||
import { LldbCallTracer } from "../../../../src/native/LldbCallTracer.js";
|
||||
import { NativeMacOSProvider } from "../../../../src/native/NativeMacOSProvider.js";
|
||||
import {
|
||||
NativeFixtureRunner,
|
||||
nativeMachoTarget,
|
||||
} from "../../../fixtures/nativeCommands.js";
|
||||
|
||||
const request: Parameters<NativeCallTracer["trace"]>[0] = {
|
||||
executable: "/fixture/target",
|
||||
architecture: "arm64",
|
||||
expectedSha256: "0".repeat(64),
|
||||
input: {
|
||||
breakpoints: [{ kind: "function", name: "main" }],
|
||||
arguments: [],
|
||||
environment: {},
|
||||
duration_ms: 100,
|
||||
max_events: 1,
|
||||
argument_registers: 0,
|
||||
backtrace_frames: 0,
|
||||
},
|
||||
};
|
||||
const tool = { path: process.execPath, sha256: "0".repeat(64) };
|
||||
|
||||
const createTracer = (
|
||||
launch?: ConstructorParameters<typeof LldbCallTracer>[1],
|
||||
): LldbCallTracer =>
|
||||
new LldbCallTracer(process.env, launch, async () => ok(tool));
|
||||
|
||||
const createClient = (tracer: NativeCallTracer) =>
|
||||
new NativeMacOSProvider(
|
||||
{},
|
||||
new NativeFixtureRunner(),
|
||||
"darwin",
|
||||
() => tracer,
|
||||
).createClient(nativeMachoTarget(request.executable));
|
||||
|
||||
const runtimeRoot = (error: ProviderCleanupError): string => {
|
||||
const root = error.cleanupResources.find((resource) =>
|
||||
resource.startsWith(`${tmpdir()}/rea-lldb-`),
|
||||
);
|
||||
if (root === undefined) throw new Error("Expected retained runtime root");
|
||||
return root;
|
||||
};
|
||||
|
||||
const liveChild = async () => {
|
||||
const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], {
|
||||
stdio: "ignore",
|
||||
});
|
||||
await once(child, "spawn");
|
||||
if (child.pid === undefined) throw new Error("Fixture process had no PID");
|
||||
return { child, pid: child.pid };
|
||||
};
|
||||
|
||||
const stopChild = async (child: ReturnType<typeof spawn>) => {
|
||||
if (child.exitCode === null && child.signalCode === null) {
|
||||
const exited = once(child, "exit");
|
||||
child.kill("SIGKILL");
|
||||
await exited;
|
||||
}
|
||||
};
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"retains a real LLDB process owner and runtime until a later cleanup retry succeeds",
|
||||
async () => {
|
||||
let cleanupFailures = 2;
|
||||
let ownedPid: number | undefined;
|
||||
const tracer = createTracer(async (_exe, _args, options) => {
|
||||
const target = spawn(process.execPath, ["-e", "process.exit(0)"], {
|
||||
stdio: "ignore",
|
||||
});
|
||||
await once(target, "exit");
|
||||
if (target.pid === undefined)
|
||||
throw new Error("Fixture target had no PID");
|
||||
await writeFile(options.pidPath, String(target.pid));
|
||||
const launched = await spawnOwnedProviderProcess({
|
||||
command: process.execPath,
|
||||
arguments: ["-e", "setInterval(() => {}, 1000)"],
|
||||
runId: randomUUID(),
|
||||
hostEnvironment: options.environment,
|
||||
});
|
||||
ownedPid = launched.process.pid;
|
||||
const supervisor = new ProviderProcessSupervisor({
|
||||
...launched,
|
||||
ownsProcessLifetime: true,
|
||||
cleanup: async () => {
|
||||
if (cleanupFailures-- > 0)
|
||||
return {
|
||||
cleaned: false,
|
||||
reason: "fixture transient cleanup failure",
|
||||
};
|
||||
return cleanupOwnedProcessGroup(launched.ownership);
|
||||
},
|
||||
});
|
||||
const stopped = await supervisor.stop();
|
||||
return {
|
||||
kind: "exited" as const,
|
||||
targetLaunched: true,
|
||||
exitCode: null,
|
||||
output: "",
|
||||
targetIdentity: undefined,
|
||||
cleanupFailure:
|
||||
stopped.status === "incomplete" ? stopped.reason : undefined,
|
||||
...(stopped.status === "incomplete"
|
||||
? { cleanupOwner: supervisor }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
const client = createClient(tracer);
|
||||
|
||||
try {
|
||||
const trace = await tracer.trace(request);
|
||||
expect(trace.ok).toBe(false);
|
||||
if (trace.ok) throw new Error("Expected incomplete cleanup");
|
||||
expect(trace.error).toBeInstanceOf(ProviderCleanupError);
|
||||
if (!(trace.error instanceof ProviderCleanupError)) return;
|
||||
expect(trace.error.cleanupResources).toContain("lldb-process-group");
|
||||
expect(trace.error.partialObservation).toBeDefined();
|
||||
const root = runtimeRoot(trace.error);
|
||||
await expect(access(root)).resolves.toBeUndefined();
|
||||
if (ownedPid === undefined) throw new Error("Expected owned process PID");
|
||||
const pid = ownedPid;
|
||||
expect(() => process.kill(pid, 0)).not.toThrow();
|
||||
expect((await client.close()).ok).toBe(false);
|
||||
expect(() => process.kill(pid, 0)).not.toThrow();
|
||||
await expect(access(root)).resolves.toBeUndefined();
|
||||
expect((await client.close()).ok).toBe(true);
|
||||
expect(() => process.kill(pid, 0)).toThrow();
|
||||
await expect(access(root)).rejects.toThrow();
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"does not retain a target when cancellation proves LLDB never launched",
|
||||
async () => {
|
||||
const controller = new AbortController();
|
||||
const cancelledTracer = new LldbCallTracer(
|
||||
process.env,
|
||||
undefined,
|
||||
async () => {
|
||||
controller.abort();
|
||||
return ok(tool);
|
||||
},
|
||||
);
|
||||
const result = await cancelledTracer.trace(request, controller.signal);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("Expected cancelled trace");
|
||||
expect(result.error).toBeInstanceOf(AnalysisCancelledError);
|
||||
expect((await cancelledTracer.close()).ok).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"retains an unidentified debuggee and runtime until exit can be confirmed",
|
||||
async () => {
|
||||
const { child, pid } = await liveChild();
|
||||
const tracer = createTracer(async (_exe, _args, options) => {
|
||||
await writeFile(options.pidPath, String(pid));
|
||||
return {
|
||||
kind: "exited",
|
||||
targetLaunched: true,
|
||||
exitCode: 0,
|
||||
output: "",
|
||||
targetIdentity: undefined,
|
||||
cleanupFailure: undefined,
|
||||
};
|
||||
});
|
||||
const client = createClient(tracer);
|
||||
|
||||
try {
|
||||
const trace = await tracer.trace(request);
|
||||
expect(trace.ok).toBe(false);
|
||||
if (trace.ok) throw new Error("Expected unverified target cleanup");
|
||||
expect(trace.error).toBeInstanceOf(ProviderCleanupError);
|
||||
if (!(trace.error instanceof ProviderCleanupError)) return;
|
||||
expect(trace.error.cleanupResources).toContain(`native-target:${pid}`);
|
||||
const root = runtimeRoot(trace.error);
|
||||
await expect(access(root)).resolves.toBeUndefined();
|
||||
expect(() => process.kill(pid, 0)).not.toThrow();
|
||||
expect((await client.close()).ok).toBe(false);
|
||||
expect(() => process.kill(pid, 0)).not.toThrow();
|
||||
await expect(access(root)).resolves.toBeUndefined();
|
||||
await stopChild(child);
|
||||
expect((await client.close()).ok).toBe(true);
|
||||
await expect(access(root)).rejects.toThrow();
|
||||
} finally {
|
||||
await stopChild(child);
|
||||
await client.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"rejects malformed PID authority and retries after the target exits",
|
||||
async () => {
|
||||
const { child, pid } = await liveChild();
|
||||
const identity = await observeProcessStartIdentity(pid);
|
||||
if (identity?.state !== "readable")
|
||||
throw new Error("Host could not read fixture process identity");
|
||||
const tracer = createTracer(async (_exe, _args, options) => {
|
||||
await writeFile(options.pidPath, `${pid}junk`);
|
||||
return {
|
||||
kind: "exited",
|
||||
targetLaunched: true,
|
||||
exitCode: 0,
|
||||
output: "",
|
||||
targetIdentity: identity.identity,
|
||||
cleanupFailure: undefined,
|
||||
};
|
||||
});
|
||||
const client = createClient(tracer);
|
||||
|
||||
try {
|
||||
const trace = await tracer.trace(request);
|
||||
expect(trace.ok).toBe(false);
|
||||
if (trace.ok) throw new Error("Expected malformed PID cleanup failure");
|
||||
expect(trace.error).toBeInstanceOf(ProviderCleanupError);
|
||||
if (!(trace.error instanceof ProviderCleanupError)) return;
|
||||
expect(trace.error.cleanupResources).toContain("native-target:unknown");
|
||||
expect(() => process.kill(pid, 0)).not.toThrow();
|
||||
const root = runtimeRoot(trace.error);
|
||||
await stopChild(child);
|
||||
await writeFile(join(root, "pid"), String(pid));
|
||||
expect((await client.close()).ok).toBe(true);
|
||||
} finally {
|
||||
await stopChild(child);
|
||||
await client.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -12,6 +12,12 @@ import type { NativeCallTracer } from "../../../../src/native/LldbCallTracer.js"
|
||||
import { LldbCallTracer } from "../../../../src/native/LldbCallTracer.js";
|
||||
import { err, ok } from "../../../../src/domain/result.js";
|
||||
import { NativeCommandFailure } from "../../../../src/native/CommandRunner.js";
|
||||
import { NativeMacOSProvider } from "../../../../src/native/NativeMacOSProvider.js";
|
||||
import { createDeferred } from "../../../fixtures/binarySession.js";
|
||||
import {
|
||||
NativeFixtureRunner,
|
||||
nativeMachoTarget,
|
||||
} from "../../../fixtures/nativeCommands.js";
|
||||
|
||||
const EVENT = {
|
||||
sequence: 0,
|
||||
@@ -83,11 +89,13 @@ const fixtureTracer = (
|
||||
return outcome === "cancelled"
|
||||
? {
|
||||
kind: "cancelled",
|
||||
targetLaunched: false,
|
||||
targetIdentity: undefined,
|
||||
cleanupFailure: undefined,
|
||||
}
|
||||
: {
|
||||
kind: "exited",
|
||||
targetLaunched: false,
|
||||
exitCode: 1,
|
||||
output: "bridge reported target integrity failure",
|
||||
targetIdentity: undefined,
|
||||
@@ -108,6 +116,56 @@ const fixtureTracer = (
|
||||
};
|
||||
|
||||
describe("LLDB failure retention through the production tracer", () => {
|
||||
it("waits for an active trace before client close removes its runtime root", async () => {
|
||||
const launchGate = createDeferred<void>();
|
||||
const launchStarted = createDeferred<void>();
|
||||
const tracer = new LldbCallTracer(
|
||||
{},
|
||||
async (_executable, arguments_) => {
|
||||
const { config } = await configFromArguments(arguments_);
|
||||
await writeFile(
|
||||
config.observation_path,
|
||||
`${JSON.stringify({ kind: "event", event: EVENT })}\n`,
|
||||
);
|
||||
await writeFile(config.stdout_capture_path, "captured prefix");
|
||||
launchStarted.resolve();
|
||||
await launchGate.promise;
|
||||
return {
|
||||
kind: "exited",
|
||||
targetLaunched: false,
|
||||
exitCode: 0,
|
||||
output: "",
|
||||
targetIdentity: undefined,
|
||||
cleanupFailure: undefined,
|
||||
};
|
||||
},
|
||||
async () => ok(fakeTool),
|
||||
);
|
||||
const client = new NativeMacOSProvider(
|
||||
{},
|
||||
new NativeFixtureRunner(),
|
||||
"darwin",
|
||||
() => tracer,
|
||||
).createClient(nativeMachoTarget(request.executable));
|
||||
const tracePromise = tracer.trace(request);
|
||||
await launchStarted.promise;
|
||||
let closeFinished = false;
|
||||
const closePromise = client.close().then((result) => {
|
||||
closeFinished = true;
|
||||
return result;
|
||||
});
|
||||
await Promise.resolve();
|
||||
expect(closeFinished).toBe(false);
|
||||
launchGate.resolve();
|
||||
const [trace, close] = await Promise.all([tracePromise, closePromise]);
|
||||
expect(close.ok).toBe(true);
|
||||
if (trace.ok) throw new Error("expected missing LLDB result");
|
||||
expect(trace.error.partialObservation).toMatchObject({
|
||||
events: [EVENT],
|
||||
process: { stdout: { text: "captured prefix", complete: false } },
|
||||
});
|
||||
});
|
||||
|
||||
it("names the missing LLDB requirement instead of asking for another target", async () => {
|
||||
const tracer = new LldbCallTracer(
|
||||
{},
|
||||
|
||||
@@ -108,6 +108,10 @@ class FixtureTracer implements NativeCallTracer {
|
||||
this.requests.push(request);
|
||||
return Promise.resolve(this.outcome);
|
||||
}
|
||||
|
||||
close() {
|
||||
return Promise.resolve(ok(null));
|
||||
}
|
||||
}
|
||||
|
||||
const BREAKPOINTS = [
|
||||
@@ -131,7 +135,7 @@ const observe = async (
|
||||
target?: Awaited<ReturnType<typeof fixtureTarget>>,
|
||||
signal?: AbortSignal,
|
||||
) =>
|
||||
new NativeMacOSProvider({}, new NativeFixtureRunner(), "darwin", tracer)
|
||||
new NativeMacOSProvider({}, new NativeFixtureRunner(), "darwin", () => tracer)
|
||||
.createClient(target ?? (await fixtureTarget()))
|
||||
.execute(
|
||||
"observe_native_calls",
|
||||
@@ -421,7 +425,7 @@ describe("observe_native_calls failures", () => {
|
||||
{},
|
||||
new NativeFixtureRunner(),
|
||||
"darwin",
|
||||
tracer,
|
||||
() => tracer,
|
||||
)
|
||||
.createClient({
|
||||
path: target.path,
|
||||
|
||||
Reference in New Issue
Block a user