fix(artifacts): retain read cleanup ownership through CLI and MCP shutdown
Keep failed stable-read handles and WABT runtime roots under retryable resource scopes. Preserve cancellation causes and primary errors, close the same service instances bound to MCP tools, and consolidate CLI operation/cleanup projection. Validation: fast typecheck and lint, cached runtime build, docs checks, SDK schema validation, focused service and real-file cleanup tests, CLI cleanup regressions, and MCP lifecycle/shutdown workflows. Provider process fixtures simulate engine output; real WABT and Linux EVM execution are not established by this pass.
This commit is contained in:
@@ -11,7 +11,7 @@ import {
|
||||
} from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
import { expect, it, onTestFinished, vi } from "vitest";
|
||||
import { HistoricalCaptureDecoder } from "../../../src/browser/history/HistoricalCaptureDecoder.js";
|
||||
import { MitmproxyCaptureAdapter } from "../../../src/browser/history/MitmproxyCaptureAdapter.js";
|
||||
import { HAR_CAPTURE_PROVIDER_IDENTITY } from "../../../src/browser/history/CaptureRelease.js";
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
import { historicalHar } from "../../fixtures/historicalHar.js";
|
||||
import { decodeHarCapture } from "../../../src/browser/history/HarCapture.js";
|
||||
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
|
||||
import { OwnedFileHandle } from "../../../src/filesystem/OwnedFileHandle.js";
|
||||
|
||||
const linux = it.skipIf(process.platform !== "linux");
|
||||
|
||||
@@ -138,6 +139,66 @@ it("classifies an oversized selected capture before creating an owned decoder",
|
||||
});
|
||||
});
|
||||
|
||||
it("retains a failed capture reader and retries it before a fresh load", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-capture-reader-close-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
const path = join(root, "input.har");
|
||||
await writeFile(path, JSON.stringify(historicalHar()));
|
||||
const originalClose = OwnedFileHandle.prototype.close;
|
||||
const close = vi.spyOn(OwnedFileHandle.prototype, "close");
|
||||
let allowClose = false;
|
||||
let closeAttempts = 0;
|
||||
close.mockImplementation(async function (this: OwnedFileHandle) {
|
||||
closeAttempts += 1;
|
||||
if (!allowClose) throw new Error("injected capture reader close failure");
|
||||
await originalClose.call(this);
|
||||
});
|
||||
let decoderCalls = 0;
|
||||
const decoder = new HistoricalCaptureDecoder(
|
||||
[
|
||||
{
|
||||
format: "har",
|
||||
identity: HAR_CAPTURE_PROVIDER_IDENTITY,
|
||||
command: async () => {
|
||||
decoderCalls += 1;
|
||||
return {
|
||||
command: process.execPath,
|
||||
arguments: ["-e", "process.exit(0)"],
|
||||
};
|
||||
},
|
||||
},
|
||||
],
|
||||
process.env,
|
||||
);
|
||||
const input = inspectWebNetworkCaptureInputSchema.parse({
|
||||
capture_path: path,
|
||||
format: "har",
|
||||
});
|
||||
try {
|
||||
const first = await decoder.inspect(input);
|
||||
expect(first.ok).toBe(false);
|
||||
if (first.ok) throw new Error("Reader close failure must fail inspection");
|
||||
expect(first.error.cleanupResources).toContain(path);
|
||||
expect(decoderCalls).toBe(0);
|
||||
|
||||
const refused = await decoder.inspect(input);
|
||||
expect(refused.ok).toBe(false);
|
||||
if (refused.ok) throw new Error("Fresh read must wait for owner cleanup");
|
||||
expect(refused.error.cleanupIncomplete).toBe(true);
|
||||
expect(refused.error.cleanupResources).toContain(path);
|
||||
expect(decoderCalls).toBe(0);
|
||||
expect(closeAttempts).toBe(2);
|
||||
|
||||
allowClose = true;
|
||||
await decoder.close();
|
||||
expect(closeAttempts).toBe(3);
|
||||
} finally {
|
||||
allowClose = true;
|
||||
await decoder.close().catch(() => undefined);
|
||||
close.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not misclassify decoder filesystem failures as missing selected input", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-historical-command-"));
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||
|
||||
@@ -5,6 +5,7 @@ import { silentLogger } from "../../../src/logger.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";
|
||||
import { err } from "../../../src/domain/result.js";
|
||||
import { AnalysisInputError } from "../../../src/domain/analysisErrorCore.js";
|
||||
|
||||
it.each([false, true])(
|
||||
"awaits cleanup retry and preserves completed output when retry failure is %s",
|
||||
@@ -82,6 +83,111 @@ it.each([false, true])(
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps the primary CLI failure when close throws an untyped error", async () => {
|
||||
const cli = Cli.create("capture-cleanup-primary-test", { sync: false });
|
||||
registerCaptureCommands(
|
||||
cli,
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspectFields: async () => {
|
||||
throw new Error("Unexpected field discovery call");
|
||||
},
|
||||
inspect: async () =>
|
||||
err(
|
||||
new AnalysisInputError("inspect_packet_capture", {
|
||||
userMessage: "The selected capture input was rejected.",
|
||||
}),
|
||||
),
|
||||
close: async () => {
|
||||
throw new Error("raw close failure");
|
||||
},
|
||||
},
|
||||
);
|
||||
let stdout = "";
|
||||
await cli.serve(
|
||||
[
|
||||
"inspect-packet-capture",
|
||||
"recording.pcap",
|
||||
"--fields",
|
||||
"ip.addr",
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
{
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
exit: () => {},
|
||||
},
|
||||
);
|
||||
expect(JSON.parse(stdout)).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
message: "The selected capture input was rejected.",
|
||||
details: {
|
||||
diagnostics: {
|
||||
primary_error: { code: "invalid_request" },
|
||||
},
|
||||
resources: [],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("closes the service and retains an unexpected producer rejection", async () => {
|
||||
const cli = Cli.create("capture-producer-rejection-test", { sync: false });
|
||||
let closed = false;
|
||||
registerCaptureCommands(
|
||||
cli,
|
||||
silentLogger,
|
||||
{},
|
||||
{
|
||||
inspectFields: async () => {
|
||||
throw new Error("Unexpected field discovery call");
|
||||
},
|
||||
inspect: async () => {
|
||||
throw new Error("raw producer failure");
|
||||
},
|
||||
close: async () => {
|
||||
closed = true;
|
||||
throw new Error("raw close failure");
|
||||
},
|
||||
},
|
||||
);
|
||||
let stdout = "";
|
||||
await cli.serve(
|
||||
[
|
||||
"inspect-packet-capture",
|
||||
"recording.pcap",
|
||||
"--fields",
|
||||
"ip.addr",
|
||||
"--format",
|
||||
"json",
|
||||
],
|
||||
{
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
exit: () => {},
|
||||
},
|
||||
);
|
||||
expect(closed).toBe(true);
|
||||
expect(JSON.parse(stdout)).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
diagnostics: {
|
||||
primary_error: {
|
||||
code: "execution_failure",
|
||||
details: {
|
||||
operation: "inspect_packet_capture",
|
||||
provider_id: "tshark-capture",
|
||||
},
|
||||
},
|
||||
cleanup_error: { code: "cleanup_incomplete" },
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects an oversized selector budget before the CLI invokes its service", async () => {
|
||||
const cli = Cli.create("capture-selector-test", { sync: false });
|
||||
let called = false;
|
||||
|
||||
@@ -31,9 +31,12 @@ it("reads exact binary and empty bytes and rejects symlink/size/cancellation bou
|
||||
});
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
await expect(readStableArtifact(real, 3, controller.signal)).rejects.toBe(
|
||||
controller.signal.reason,
|
||||
);
|
||||
await expect(
|
||||
readStableArtifact(real, 3, controller.signal),
|
||||
).rejects.toMatchObject({
|
||||
reason: "cancelled",
|
||||
cause: controller.signal.reason,
|
||||
});
|
||||
});
|
||||
|
||||
const checkChange = async (
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect, it, onTestFinished, vi } from "vitest";
|
||||
|
||||
const injected = vi.hoisted(() => ({
|
||||
sourcePath: undefined as string | undefined,
|
||||
abortController: undefined as AbortController | undefined,
|
||||
failClose: false,
|
||||
closeAttempts: 0,
|
||||
}));
|
||||
|
||||
vi.mock("node:fs/promises", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("node:fs/promises")>();
|
||||
return {
|
||||
...actual,
|
||||
open: async (...args: Parameters<typeof actual.open>) => {
|
||||
const handle = await actual.open(...args);
|
||||
if (args[0] !== injected.sourcePath) return handle;
|
||||
const createReadStream = handle.createReadStream.bind(handle);
|
||||
handle.createReadStream = (options) => {
|
||||
injected.abortController?.abort();
|
||||
return createReadStream(options);
|
||||
};
|
||||
const close = handle.close.bind(handle);
|
||||
handle.close = async () => {
|
||||
injected.closeAttempts += 1;
|
||||
if (injected.failClose) throw new Error("fixture close refusal");
|
||||
await close();
|
||||
};
|
||||
return handle;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
import { WebModuleTraceService } from "../../../src/application/WebModuleTraceService.js";
|
||||
import { LocalWebModuleArtifacts } from "../../../src/browser/modules/WebModuleArtifacts.js";
|
||||
import { webModuleArtifactsFixture } from "../../fixtures/webModuleTrace.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
it("retains cancelled source read ownership until service close retries it", async () => {
|
||||
const root = await createTestTempDirectory("rea-web-artifact-read-owner-");
|
||||
onTestFinished(async () => {
|
||||
injected.sourcePath = undefined;
|
||||
injected.abortController = undefined;
|
||||
injected.failClose = false;
|
||||
injected.closeAttempts = 0;
|
||||
await rm(root, { recursive: true, force: true });
|
||||
});
|
||||
const source = 'import "./dep.js";';
|
||||
const fixture = webModuleArtifactsFixture(source);
|
||||
const manifestPath = join(root, "manifest.json");
|
||||
const sourcePath = join(root, "files", "modules", "main.js");
|
||||
await mkdir(join(root, "files", "modules"), { recursive: true });
|
||||
await writeFile(sourcePath, source);
|
||||
await writeFile(manifestPath, JSON.stringify(fixture.manifest));
|
||||
|
||||
injected.sourcePath = sourcePath;
|
||||
injected.failClose = true;
|
||||
const controller = new AbortController();
|
||||
injected.abortController = controller;
|
||||
const resolver = {
|
||||
resolve: vi.fn(),
|
||||
close: vi.fn(async () => undefined),
|
||||
};
|
||||
const service = new WebModuleTraceService(
|
||||
new LocalWebModuleArtifacts(),
|
||||
resolver,
|
||||
);
|
||||
const input = { manifest_path: manifestPath, script_index: 0 };
|
||||
|
||||
const cancelled = await service.trace(input, { signal: controller.signal });
|
||||
expect(cancelled.ok).toBe(false);
|
||||
if (cancelled.ok) throw new Error("Expected cancelled source read");
|
||||
expect(cancelled.error.cleanupIncomplete).toBe(true);
|
||||
expect(cancelled.error.cleanupResources).toContain(sourcePath);
|
||||
expect(resolver.resolve).not.toHaveBeenCalled();
|
||||
|
||||
injected.abortController = undefined;
|
||||
const blocked = await service.trace(input);
|
||||
expect(blocked.ok).toBe(false);
|
||||
if (blocked.ok) throw new Error("Expected retained cleanup to block load");
|
||||
expect(blocked.error.cleanupIncomplete).toBe(true);
|
||||
expect(injected.closeAttempts).toBe(2);
|
||||
|
||||
await expect(service.close()).rejects.toThrow(
|
||||
"Web module trace cleanup failed",
|
||||
);
|
||||
expect(resolver.close).toHaveBeenCalledTimes(1);
|
||||
expect(injected.closeAttempts).toBe(3);
|
||||
|
||||
injected.failClose = false;
|
||||
const attemptsBeforeRetry = injected.closeAttempts;
|
||||
await service.close();
|
||||
expect(injected.closeAttempts).toBeGreaterThan(attemptsBeforeRetry);
|
||||
expect(resolver.close).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
@@ -34,6 +34,9 @@ import {
|
||||
} from "../../support/workspace/workspaceFixture.js";
|
||||
import { z } from "zod";
|
||||
import { createDeferred } from "../../fixtures/binarySession.js";
|
||||
import { GoBinaryService } from "../../../src/application/go/GoBinaryService.js";
|
||||
import { WebNetworkCaptureService } from "../../../src/application/WebNetworkCaptureService.js";
|
||||
import { AnalysisUnsupportedTargetError } from "../../../src/domain/analysisErrorCore.js";
|
||||
|
||||
const resources: Array<{ close(): Promise<void> }> = [];
|
||||
|
||||
@@ -334,6 +337,68 @@ it("awaits SQLite cleanup and retries its retained owner after failed server shu
|
||||
expect(attempts).toBe(2);
|
||||
});
|
||||
|
||||
it("closes the bound Go and web-capture services and retries failed shutdown", async () => {
|
||||
let goCalls = 0;
|
||||
let goCloseAttempts = 0;
|
||||
let captureCloseAttempts = 0;
|
||||
let cleanupAllowed = false;
|
||||
const goBinary = new GoBinaryService({
|
||||
identity: { id: "go-fixture", name: "Go fixture", version: "1" },
|
||||
inspect: async ({ path }) => {
|
||||
goCalls += 1;
|
||||
return err(
|
||||
new AnalysisUnsupportedTargetError(
|
||||
"inspect_go_binary",
|
||||
path,
|
||||
"fixture rejection",
|
||||
),
|
||||
);
|
||||
},
|
||||
close: async () => {
|
||||
goCloseAttempts += 1;
|
||||
if (!cleanupAllowed) throw new Error("Go cleanup refused");
|
||||
},
|
||||
});
|
||||
const webNetworkCapture = new WebNetworkCaptureService({
|
||||
inspect: async () => {
|
||||
throw new Error("No capture inspection requested");
|
||||
},
|
||||
close: async () => {
|
||||
captureCloseAttempts += 1;
|
||||
if (!cleanupAllowed) throw new Error("Capture cleanup refused");
|
||||
},
|
||||
});
|
||||
const server = createServer(
|
||||
{ kind: "fixed", analysis: { execute: async () => ok(null) } },
|
||||
{ goBinary, webNetworkCapture },
|
||||
);
|
||||
const client = new Client({ name: "bound-service-lifecycle", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
resources.push(client, server);
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const result = await client.callTool({
|
||||
name: "inspect_go_binary",
|
||||
arguments: { path: "/tmp/go-fixture" },
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
expect(goCalls).toBe(1);
|
||||
|
||||
await expect(server.close()).rejects.toBeInstanceOf(AggregateError);
|
||||
expect(goCloseAttempts).toBe(1);
|
||||
expect(captureCloseAttempts).toBe(1);
|
||||
|
||||
cleanupAllowed = true;
|
||||
await server.close();
|
||||
expect(goCloseAttempts).toBe(2);
|
||||
expect(captureCloseAttempts).toBe(2);
|
||||
} finally {
|
||||
cleanupAllowed = true;
|
||||
}
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
resources.splice(0).map(async (resource) => resource.close()),
|
||||
|
||||
@@ -2,6 +2,7 @@ import { access } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect, it, onTestFinished } from "vitest";
|
||||
import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js";
|
||||
import { ArtifactResourceScope } from "../../../src/artifacts/ArtifactResourceScope.js";
|
||||
import {
|
||||
createTestWorkspace,
|
||||
removeTestWorkspace,
|
||||
@@ -40,6 +41,7 @@ it.each(["pre-aborted", "aborted-during-probe"] as const)(
|
||||
REA_PWNDBG_VENV_PATH: join(workspace.root, "missing-venv"),
|
||||
},
|
||||
rootPath: workspace.root,
|
||||
resources: new ArtifactResourceScope(),
|
||||
diagnostics,
|
||||
options: { signal: controller.signal },
|
||||
probePath,
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
const closeState = vi.hoisted(() => ({
|
||||
fail: false,
|
||||
failOnce: false,
|
||||
opened: 0,
|
||||
closes: 0,
|
||||
}));
|
||||
|
||||
vi.mock("node:fs/promises", async (importOriginal) => {
|
||||
const fs = await importOriginal<typeof import("node:fs/promises")>();
|
||||
return {
|
||||
...fs,
|
||||
open: async (...args: Parameters<typeof fs.open>) => {
|
||||
const handle = await fs.open(...args);
|
||||
closeState.opened++;
|
||||
const close = handle.close.bind(handle);
|
||||
handle.close = async () => {
|
||||
closeState.closes++;
|
||||
if (closeState.fail || closeState.failOnce) {
|
||||
closeState.failOnce = false;
|
||||
throw new Error("injected stable artifact close failure");
|
||||
}
|
||||
return close();
|
||||
};
|
||||
return handle;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
import { PwntoolsDecoder } from "../../../src/native/pwntools/PwntoolsDecoder.js";
|
||||
import { PWNTOOLS_PROVIDER_IDENTITY } from "../../../src/native/pwntools/PwntoolsRelease.js";
|
||||
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
|
||||
|
||||
const makeDecoder = () =>
|
||||
new PwntoolsDecoder(
|
||||
{
|
||||
identity: PWNTOOLS_PROVIDER_IDENTITY,
|
||||
operation: "test_pwntools_artifact_read",
|
||||
bridge: new URL("file:///unused-bridge.py"),
|
||||
payloadSchema: z.string(),
|
||||
project: () => {
|
||||
throw new Error("input read should fail before decoder launch");
|
||||
},
|
||||
},
|
||||
{ REA_PWNTOOLS_PYTHON: process.execPath },
|
||||
undefined,
|
||||
async () => {
|
||||
throw new Error("runtime should not be created for failed input read");
|
||||
},
|
||||
);
|
||||
|
||||
const emulateSupportedHost = async (
|
||||
run: () => Promise<void>,
|
||||
): Promise<void> => {
|
||||
const platform = Object.getOwnPropertyDescriptor(process, "platform");
|
||||
const arch = Object.getOwnPropertyDescriptor(process, "arch");
|
||||
Object.defineProperty(process, "platform", { ...platform, value: "linux" });
|
||||
Object.defineProperty(process, "arch", { ...arch, value: "x64" });
|
||||
try {
|
||||
await run();
|
||||
} finally {
|
||||
if (platform !== undefined)
|
||||
Object.defineProperty(process, "platform", platform);
|
||||
if (arch !== undefined) Object.defineProperty(process, "arch", arch);
|
||||
}
|
||||
};
|
||||
|
||||
it("reports the read failure without stale incomplete-cleanup state when close retry succeeds", async () =>
|
||||
emulateSupportedHost(async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-pwntools-close-retry-"));
|
||||
const path = join(root, "selected.bin");
|
||||
await writeFile(path, "selected evidence");
|
||||
closeState.fail = false;
|
||||
closeState.failOnce = true;
|
||||
closeState.opened = 0;
|
||||
closeState.closes = 0;
|
||||
const decoder = makeDecoder();
|
||||
try {
|
||||
const result = await decoder.inspect({ path });
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("Injected close failure was not returned");
|
||||
expect(result.error.cleanupIncomplete).toBe(false);
|
||||
expect(projectAnalysisError(result.error).code).not.toBe(
|
||||
"cleanup_incomplete",
|
||||
);
|
||||
expect(result.error.cause).toMatchObject({
|
||||
cleanup: {
|
||||
resources: [path],
|
||||
reason: expect.stringContaining(
|
||||
"injected stable artifact close failure",
|
||||
),
|
||||
},
|
||||
});
|
||||
expect(closeState.closes).toBeGreaterThanOrEqual(2);
|
||||
} finally {
|
||||
closeState.fail = false;
|
||||
closeState.failOnce = false;
|
||||
await decoder.close();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
}));
|
||||
|
||||
it("retains a persistent failed input descriptor and refuses the next acquisition", async () =>
|
||||
emulateSupportedHost(async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-pwntools-held-close-"));
|
||||
const path = join(root, "selected.bin");
|
||||
await writeFile(path, "selected evidence");
|
||||
closeState.fail = true;
|
||||
closeState.failOnce = false;
|
||||
closeState.opened = 0;
|
||||
closeState.closes = 0;
|
||||
const decoder = makeDecoder();
|
||||
try {
|
||||
const first = await decoder.inspect({ path });
|
||||
expect(first.ok).toBe(false);
|
||||
if (first.ok)
|
||||
throw new Error("Persistent close failure was not returned");
|
||||
expect(projectAnalysisError(first.error).code).toBe("cleanup_incomplete");
|
||||
const openedAfterFailure = closeState.opened;
|
||||
|
||||
const retry = await decoder.inspect({ path });
|
||||
expect(retry.ok).toBe(false);
|
||||
if (retry.ok) throw new Error("Retained descriptor was not retried");
|
||||
expect(projectAnalysisError(retry.error).code).toBe("cleanup_incomplete");
|
||||
expect(closeState.opened).toBe(openedAfterFailure);
|
||||
|
||||
await expect(decoder.close()).rejects.toMatchObject({
|
||||
cleanupIncomplete: true,
|
||||
});
|
||||
closeState.fail = false;
|
||||
await decoder.close();
|
||||
} finally {
|
||||
closeState.fail = false;
|
||||
closeState.failOnce = false;
|
||||
try {
|
||||
await decoder.close();
|
||||
} catch {
|
||||
// The test already asserts persistent cleanup failure before releasing it.
|
||||
}
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
}));
|
||||
@@ -0,0 +1,100 @@
|
||||
import type { FileHandle } from "node:fs/promises";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { expect, it, vi } from "vitest";
|
||||
|
||||
const cleanupState = vi.hoisted(() => ({
|
||||
failFirstClose: false,
|
||||
abortController: undefined as AbortController | undefined,
|
||||
firstHandle: undefined as FileHandle | undefined,
|
||||
firstHandleCloseAttempts: 0,
|
||||
}));
|
||||
|
||||
vi.mock("node:fs/promises", async (importOriginal) => {
|
||||
const fs = await importOriginal<typeof import("node:fs/promises")>();
|
||||
return {
|
||||
...fs,
|
||||
open: async (...args: Parameters<typeof fs.open>) => {
|
||||
const handle = await fs.open(...args);
|
||||
const close = handle.close.bind(handle);
|
||||
if (cleanupState.abortController !== undefined)
|
||||
setImmediate(() => {
|
||||
cleanupState.abortController?.abort();
|
||||
cleanupState.abortController = undefined;
|
||||
});
|
||||
handle.close = async () => {
|
||||
if (handle === cleanupState.firstHandle)
|
||||
cleanupState.firstHandleCloseAttempts += 1;
|
||||
else if (cleanupState.firstHandle === undefined)
|
||||
cleanupState.firstHandle = handle;
|
||||
if (
|
||||
cleanupState.failFirstClose &&
|
||||
handle === cleanupState.firstHandle
|
||||
) {
|
||||
cleanupState.failFirstClose = false;
|
||||
throw new Error("injected descriptor close failure");
|
||||
}
|
||||
return close();
|
||||
};
|
||||
return handle;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
|
||||
import { GoBinaryProvider } from "../../../src/go/GoBinaryProvider.js";
|
||||
import { PeResourcesProvider } from "../../../src/native/pe/PeResourcesProvider.js";
|
||||
import { createGoBinaryFixture } from "../../fixtures/go/image.js";
|
||||
import { peResourceFixture } from "../../../src/native/pe/PeResources.fixture.js";
|
||||
|
||||
it.each(["go", "pe"] as const)(
|
||||
"%s provider retains a failed descriptor close and retries that owner before the next read",
|
||||
async (kind) => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-read-cleanup-"));
|
||||
const path = join(root, kind === "go" ? "program.elf" : "program.exe");
|
||||
const bytes =
|
||||
kind === "go" ? createGoBinaryFixture().bytes : peResourceFixture().bytes;
|
||||
await writeFile(path, bytes);
|
||||
const provider =
|
||||
kind === "go" ? new GoBinaryProvider() : new PeResourcesProvider();
|
||||
cleanupState.failFirstClose = true;
|
||||
const controller = new AbortController();
|
||||
cleanupState.abortController = controller;
|
||||
cleanupState.firstHandle = undefined;
|
||||
cleanupState.firstHandleCloseAttempts = 0;
|
||||
try {
|
||||
const input = {
|
||||
path,
|
||||
max_file_bytes: 8 * 1024 * 1024,
|
||||
max_entries: 4096,
|
||||
};
|
||||
const first = await provider.inspect(input, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
expect(first.ok).toBe(false);
|
||||
if (first.ok) throw new Error("Injected close failure was not returned");
|
||||
expect(projectAnalysisError(first.error)).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: { diagnostics: { primary_error: { code: "cancelled" } } },
|
||||
});
|
||||
expect(first.error.cause).toBeInstanceOf(AggregateError);
|
||||
if (!(first.error.cause instanceof AggregateError))
|
||||
throw first.error.cause;
|
||||
expect(first.error.cause.errors[1]).toMatchObject({
|
||||
cleanupResources: [path],
|
||||
});
|
||||
|
||||
const retry = await provider.inspect(input);
|
||||
expect(retry.ok).toBe(true);
|
||||
expect(cleanupState.firstHandleCloseAttempts).toBe(2);
|
||||
} finally {
|
||||
await provider.close();
|
||||
cleanupState.failFirstClose = false;
|
||||
cleanupState.abortController = undefined;
|
||||
cleanupState.firstHandle = undefined;
|
||||
cleanupState.firstHandleCloseAttempts = 0;
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
Reference in New Issue
Block a user