refactor(artifacts): reuse the positional reader for iNES prefixes (#13481)

* refactor(artifacts): reuse the positional reader for iNES prefixes

* test(ghidra): verify Java timeout after doctor settles

* test(ghidra): join Java fixture teardown after failed assertions

* test(hopper): prepare native ownership before late-handoff deadlines
This commit is contained in:
morluto authored and GitHub committed 2026-11-22 17:55:15 +00:00
1 parent d979c1849c
commit b6ffec43ad
7 files changed
+118 -188

No files matched your search

+2 -2
View File
@@ -11,7 +11,7 @@ import {
abortIfNeeded,
ArtifactResourceScope,
} from "../resources/index.js";
import { readFileHandlePrefix } from "../filesystem/readFileHandlePrefix.js";
import { readFileHandleRange } from "../filesystem/readFileHandleRange.js";
import { Transform, pipeline, type Readable } from "node:stream";
import {
parseInesLayout,
@@ -72,7 +72,7 @@ export class InesArtifactReader implements ArtifactReader {
): AsyncIterable<ArtifactEntry> {
const layout = await this.#scope.run(async () => {
await this.#verifySource(signal);
const prefix = await readFileHandlePrefix(this.source.handle, 16, () =>
const prefix = await readFileHandleRange(this.source.handle, 0, 16, () =>
abortIfNeeded(signal),
);
abortIfNeeded(signal);
-25
View File
@@ -1,25 +0,0 @@
import type { FileHandle } from "node:fs/promises";
/** Fill a positional prefix until its bound or true EOF, preserving caller cancellation errors. */
export const readFileHandlePrefix = async (
handle: Pick<FileHandle, "read">,
length: number,
checkCancellation: () => void,
): Promise<Buffer> => {
const prefix = Buffer.alloc(length);
let offset = 0;
while (offset < length) {
checkCancellation();
// A rejected native read remains primary if cancellation arrived in flight.
const { bytesRead } = await handle.read(
prefix,
offset,
length - offset,
offset,
);
checkCancellation();
if (bytesRead === 0) break;
offset += bytesRead;
}
return prefix.subarray(0, offset);
};
@@ -14,7 +14,9 @@ import { z } from "zod";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { awaitAcknowledgement } from "../../fixtures/lifecycleAcknowledgement.js";
import { workspaceCliTest } from "../../support/cli/workspaceCliFixture.js";
import type { TestWorkspace } from "../../support/workspace/workspaceFixture.js";
import { acquireHopperTargetLease } from "../../../src/hopper/HopperLease.js";
import { createSystemProcessOwnershipHost } from "../../../src/process/ProcessOwnershipObservation.js";
import { waitFor } from "../../support/testWait.js";
import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js";
@@ -264,33 +266,48 @@ test("recovers a denied Hopper launch through the same stdio MCP session and CLI
).toBe(false);
});
const prepareLateHandoff = async (
workspace: TestWorkspace,
launchMode: "handoff" | "not-found",
) => {
const startupTimeoutMs = 10_000;
const mode = await workspace.write("mode", launchMode);
const receipt = workspace.path("bootstrap-path");
const environment = {
...workspace.environment,
PATH: process.env.PATH ?? "",
REA_ANALYSIS_PROVIDER: "hopper",
HOPPER_LAUNCHER_PATH: process.execPath,
HOPPER_LOADER_ARGS_JSON: JSON.stringify([
resolve("tests/fixtures/hopperLaunchAdmission.mjs"),
mode,
receipt,
]),
REA_HOPPER_STARTUP_TIMEOUT_MS: String(startupTimeoutMs),
REA_LOG_LEVEL: "silent",
};
// Cold Swift preparation belongs in setup for this late-handoff scenario.
// The real subprocess will authenticate the same workspace-owned cache.
const ownership = createSystemProcessOwnershipHost("darwin", environment);
await withVerifierCleanup(
() => ownership.prepare?.(),
[() => ownership.close?.()],
);
return { environment, mode, receipt, startupTimeoutMs };
};
test.for(["handoff", "not-found"] as const)(
"preserves an unconfirmed %s handoff and closes only a late bridge with matching run identity",
"retains ownership after %s and closes only a late bridge with matching run identity",
async (launchMode, { workspace }) => {
const target = workspace.path("target");
await copyFile("/usr/bin/true", target);
// Budget the complete native startup, including cold helper preparation.
// The scenario below requires observed handoff, not a pre-launch timeout.
const startupTimeoutMs = 10_000;
const mode = await workspace.write("mode", launchMode);
const receipt = workspace.path("bootstrap-path");
const { environment, mode, receipt, startupTimeoutMs } =
await prepareLateHandoff(workspace, launchMode);
const transport = new StdioClientTransport({
command: process.execPath,
args: [resolve("dist/main.js")],
stderr: "pipe",
env: {
...workspace.environment,
PATH: process.env.PATH ?? "",
REA_ANALYSIS_PROVIDER: "hopper",
HOPPER_LAUNCHER_PATH: process.execPath,
HOPPER_LOADER_ARGS_JSON: JSON.stringify([
resolve("tests/fixtures/hopperLaunchAdmission.mjs"),
mode,
receipt,
]),
REA_HOPPER_STARTUP_TIMEOUT_MS: String(startupTimeoutMs),
REA_LOG_LEVEL: "silent",
},
env: environment,
});
const mcp = new Client(
{ name: "hopper-late-readiness", version: "1" },
@@ -317,7 +334,14 @@ test.for(["handoff", "not-found"] as const)(
const initial = parseMcpToolError(await call("current_document"));
// Capture ownership evidence before result assertions so teardown retains
// the runtime even when the asserted failure stage regresses.
const bootstrapPath = await readFile(receipt, "utf8");
const bootstrapPath = await readFile(receipt, "utf8").catch(
(cause: unknown) => {
throw new Error(
`Launcher did not acknowledge handoff: ${JSON.stringify(initial.error)}`,
{ cause },
);
},
);
runtime = dirname(bootstrapPath);
expect(initial.error).toMatchObject({
code: "cleanup_incomplete",
@@ -368,9 +392,12 @@ test.for(["handoff", "not-found"] as const)(
}),
});
status.parse((await call("binary_session")).structuredContent);
expect(parseMcpToolError(await call("close_binary")).error.code).toBe(
"cleanup_incomplete",
);
// A missing endpoint uses the full reconnect window. The not-found case
// exercises that outcome before both variants check live foreign bridges.
if (launchMode === "not-found")
expect(parseMcpToolError(await call("close_binary")).error.code).toBe(
"cleanup_incomplete",
);
const bootstrap = await readFile(bootstrapPath, "utf8");
const setting = (name: string): string => {
const line = bootstrap
+43 -63
View File
@@ -1,14 +1,12 @@
import { chmod, mkdir, readFile, symlink, writeFile } from "node:fs/promises";
import { delimiter, isAbsolute, join } from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import { expect } from "vitest";
import { z } from "zod";
import { elf, thinMach } from "../../../src/domain/binaryTarget.fixture.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
import {
observeOwnedProcessGroups,
systemProcessOwnershipHost,
} from "../../../src/process/ProcessOwnershipObservation.js";
import { observeOwnedProcessGroups } from "../../../src/process/ProcessOwnershipObservation.js";
import { testWaitDeadline, waitFor } from "../../support/testWait.js";
import { resolveProcessScenarioRuntimePaths } from "../../../src/process/capture/ProcessScenarioRuntimeValidation.js";
import { processScenarioSchema } from "../../../src/domain/process/processScenario.js";
@@ -145,49 +143,39 @@ process.on("SIGTERM", () => {});
fs.writeFileSync(${JSON.stringify(`${started}.tmp`)}, JSON.stringify({ pid: process.pid, runId: process.env.REA_PROCESS_RUN_ID }));
fs.renameSync(${JSON.stringify(`${started}.tmp`)}, ${JSON.stringify(started)});
setInterval(() => { if (fs.existsSync(${JSON.stringify(release)})) process.exit(0); }, 50);
setTimeout(() => process.exit(92), 12000);
setTimeout(() => process.exit(92), ${testWaitDeadline()});
`,
{ mode: 0o700 },
);
const pending = cli.run({
arguments: ["doctor", "--provider", "ghidra", "--json"],
environment: {
JAVA_HOME: jdk,
GHIDRA_INSTALL_DIR: install,
REA_LOG_LEVEL: "silent",
},
const receipt = z.object({
pid: z.number().int().positive(),
runId: z.string().min(1),
});
// Capture the actual group while the selected process is alive; the PID
// alone is never used as cleanup authority. Release is a private protocol.
let identity: { pid: number; runId: string } | undefined;
let processGroupId: number | undefined;
try {
for (let attempt = 0; attempt < 80; attempt++) {
try {
identity = JSON.parse(
await readFile(started, "utf8"),
) as typeof identity;
} catch (cause: unknown) {
if (
!(
cause instanceof Error &&
"code" in cause &&
cause.code === "ENOENT"
)
)
throw cause;
}
if (identity !== undefined) break;
await delay(50);
const readAcknowledgement = async () => {
try {
return receipt.parse(JSON.parse(await readFile(started, "utf8")));
} catch (cause: unknown) {
if (
cause instanceof Error &&
"code" in cause &&
cause.code === "ENOENT"
)
return undefined;
throw cause;
}
if (identity === undefined)
throw new Error("Selected Java command did not start");
expect(identity.runId).toEqual(expect.any(String));
processGroupId = (await systemProcessOwnershipHost.listProcesses()).find(
(entry) => entry.pid === identity?.pid,
)?.processGroupId;
expect(processGroupId).toBeDefined();
const result = await pending;
};
const observeGroup = async ({ pid, runId }: z.infer<typeof receipt>) =>
(await observeOwnedProcessGroups(runId, [pid])).get(pid);
let identity: z.infer<typeof receipt> | undefined;
try {
const result = await cli.run({
arguments: ["doctor", "--provider", "ghidra", "--json"],
environment: {
JAVA_HOME: jdk,
GHIDRA_INSTALL_DIR: install,
REA_LOG_LEVEL: "silent",
},
});
expect(result.exitCode, `${result.stdout}\n${result.stderr}`).toBe(1);
expect(result.signal).toBeNull();
expect(result.json).toMatchObject({
@@ -206,28 +194,20 @@ setTimeout(() => process.exit(92), 12000);
}),
]),
});
if (processGroupId !== undefined) {
const observed = await observeOwnedProcessGroups(identity.runId, [
processGroupId,
]);
expect(observed.get(processGroupId)).toEqual({ state: "empty" });
}
// The POSIX owned-command launcher starts Java as its process-group leader.
// Read the durable acknowledgement after doctor settles, with the run ID
// that identifies the owned group even if its leader has already exited.
identity = await readAcknowledgement();
if (identity === undefined)
throw new Error("Selected Java command did not start");
expect(await observeGroup(identity)).toEqual({ state: "empty" });
} finally {
await writeFile(release, "release");
await pending;
if (identity !== undefined && processGroupId !== undefined) {
for (let attempt = 0; attempt < 40; attempt++) {
const observed = await observeOwnedProcessGroups(identity.runId, [
processGroupId,
]);
if (observed.get(processGroupId)?.state === "empty") break;
await delay(50);
}
const observed = await observeOwnedProcessGroups(identity.runId, [
processGroupId,
]);
expect(observed.get(processGroupId)).toEqual({ state: "empty" });
}
const acknowledged = identity ?? (await readAcknowledgement());
if (acknowledged !== undefined)
await waitFor(async () => {
expect(await observeGroup(acknowledged)).toEqual({ state: "empty" });
});
}
},
);
@@ -1,5 +1,4 @@
import * as rootHash from "../../../src/resources/StableRootArtifact.js";
import { readFileHandlePrefix } from "../../../src/filesystem/readFileHandlePrefix.js";
import { createHash } from "node:crypto";
import {
lstat,
@@ -863,60 +862,3 @@ it.each(["target", "inventory", "reader"])(
}
},
);
it.each(["eof", "cancelled"])(
"preserves %s while filling a short prefix",
async (mode) => {
const root = await createTestTempDirectory("rea-prefix-boundary-");
const path = join(root, "source");
const bytes = Buffer.from(
mode === "eof" ? "NES\x1a" : "NES\x1a123456789012",
);
await writeFile(path, bytes);
const handle = await open(path, "r");
const prototype = Object.getPrototypeOf(handle) as {
read(
buffer: Buffer,
offset: number,
length: number,
position: number,
): Promise<{ bytesRead: number; buffer: Buffer }>;
};
const original = prototype.read;
const controller = new AbortController();
let reads = 0;
const read = vi.spyOn(prototype, "read").mockImplementation(async function (
this: typeof handle,
buffer,
offset,
length,
position,
) {
reads++;
const observed = await original.call(
this,
buffer,
offset,
Math.min(length, 3),
position,
);
if (reads === 2 && mode === "cancelled") controller.abort();
return observed;
});
try {
const result = readFileHandlePrefix(handle, 16, () =>
abortIfNeeded(controller.signal),
);
if (mode === "eof") {
expect((await result).equals(bytes)).toBe(true);
expect(reads).toBe(3);
} else {
await expect(result).rejects.toMatchObject({ reason: "cancelled" });
expect(reads).toBe(2);
}
} finally {
read.mockRestore();
await handle.close();
}
},
);
@@ -23,7 +23,7 @@ import {
ArtifactFileCleanupFailure,
withArtifactFileHandle,
} from "../../../src/resources/ArtifactFileOperation.js";
import { readFileHandlePrefix } from "../../../src/filesystem/readFileHandlePrefix.js";
import { readFileHandleRange } from "../../../src/filesystem/readFileHandleRange.js";
import { abortIfNeeded } from "../../../src/resources/StreamDigest.js";
import * as regularFile from "../../../src/filesystem/RegularFile.js";
@@ -583,7 +583,7 @@ it.each([
resources,
controller.signal,
(file) =>
readFileHandlePrefix(file, 16, () =>
readFileHandleRange(file, 0, 16, () =>
abortIfNeeded(controller.signal),
),
).catch((cause: unknown) => cause);
@@ -11,21 +11,21 @@ const source = async () => {
const handle = await open(path, "r");
onTestFinished(() => handle.close());
const read = handle.read.bind(handle);
const spy = vi.spyOn(handle, "read").mockImplementation((async (
...args: unknown[]
) => {
args[2] = Math.min(args[2] as number, 2);
return Reflect.apply(read, handle, args);
}) as typeof handle.read);
const cappedRead = (
buffer: Buffer,
offset: number,
length: number,
position: number,
) => read(buffer, offset, Math.min(length, 2), position);
const spy = vi
.spyOn(handle, "read")
.mockImplementation(cappedRead as typeof handle.read);
return { handle, spy };
};
it("fills positional windows across positive short reads and stops only at EOF", async () => {
const { handle, spy } = await source();
const { handle } = await source();
expect((await readFileHandleRange(handle, 3, 5)).toString()).toBe("34567");
expect(spy.mock.calls.map((call) => (call as unknown[])[3])).toEqual([
3, 5, 7,
]);
expect((await readFileHandleRange(handle, 8, 5)).toString()).toBe("89");
expect(await readFileHandleRange(handle, 12, 2)).toHaveLength(0);
// The helper borrows the descriptor; it remains usable after EOF.
@@ -35,16 +35,16 @@ it("fills positional windows across positive short reads and stops only at EOF",
it("validates ranges and checks cancellation even for empty windows", async () => {
const { handle, spy } = await source();
expect(await readFileHandleRange(handle, 2, 0)).toHaveLength(0);
expect(spy).not.toHaveBeenCalled();
for (const [offset, length] of [
[-1, 2],
[0, -1],
[0.5, 2],
[Number.MAX_SAFE_INTEGER, 1],
])
await expect(readFileHandleRange(handle, offset!, length!)).rejects.toThrow(
] as const)
await expect(readFileHandleRange(handle, offset, length)).rejects.toThrow(
RangeError,
);
expect(spy).not.toHaveBeenCalled();
const cancelled = new Error("cancelled");
await expect(
readFileHandleRange(handle, 0, 0, () => {
@@ -63,8 +63,14 @@ it("checks cancellation after each fulfilled read and retains native failures",
).rejects.toBe(cancelled);
expect(spy).toHaveBeenCalledTimes(1);
const native = new Error("native I/O failure");
spy.mockRejectedValueOnce(native);
await expect(readFileHandleRange(handle, 0, 4)).rejects.toBe(native);
const controller = new AbortController();
spy.mockImplementationOnce(async () => {
controller.abort(cancelled);
throw native;
});
await expect(
readFileHandleRange(handle, 0, 4, () => controller.signal.throwIfAborted()),
).rejects.toBe(native);
});
it("returns explicit EOF for the caller to interpret before late cancellation", async () => {