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:
morluto
2026-10-13 16:08:41 +08:00
parent c923fb0dc9
commit b955b825fc
44 changed files with 1758 additions and 330 deletions
+196 -45
View File
@@ -1,6 +1,6 @@
import { access, chmod, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it } from "vitest";
import { expect, it, vi } from "vitest";
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
import { WabtArtifactProvider } from "./WabtArtifactProvider.js";
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
@@ -9,6 +9,33 @@ import { spawnOwnedProviderProcess } from "../process/ProviderProcess.js";
import { OwnedCommandFailure } from "../process/OwnedCommand.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
const fileCloseFailure = vi.hoisted(() => ({
selectedPath: "",
attempts: 0,
failFirst: false,
}));
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);
if (String(args[0]) !== fileCloseFailure.selectedPath) return handle;
const close = handle.close.bind(handle);
handle.close = async () => {
fileCloseFailure.attempts += 1;
if (fileCloseFailure.failFirst) {
fileCloseFailure.failFirst = false;
throw new Error("injected WABT input close failure");
}
return close();
};
return handle;
},
};
});
const failureTags: Readonly<Record<string, string>> = {
invalid: "AnalysisInputError",
timeout: "AnalysisTimeoutError",
@@ -20,6 +47,82 @@ const failureTags: Readonly<Record<string, string>> = {
"wat-warning": "AnalysisOutputError",
};
const assertCleanupRecovery = async (options: {
readonly provider: WabtArtifactProvider;
readonly result: Awaited<ReturnType<WabtArtifactProvider["inspect"]>>;
readonly path: string;
readonly runtimePath: string;
readonly cleanupAttempts: () => number;
readonly runtimeCreations: () => number;
}): Promise<void> => {
expect(options.result).toMatchObject({
error: {
cleanupIncomplete: true,
cleanupResources: [options.runtimePath],
partialObservation: { normalized_result: { validation: "valid" } },
},
});
await expect(access(options.runtimePath)).resolves.toBeUndefined();
const blocked = await options.provider.inspect({
path: options.path,
glue_paths: [],
candidate_paths: [],
});
expect(blocked).toMatchObject({
ok: false,
error: {
cleanupIncomplete: true,
cleanupResources: [options.runtimePath],
},
});
expect(options.cleanupAttempts()).toBe(2);
expect(options.runtimeCreations()).toBe(1);
await options.provider.close();
expect(options.cleanupAttempts()).toBe(3);
await expect(access(options.runtimePath)).rejects.toMatchObject({
code: "ENOENT",
});
};
const assertModeOutcome = (
mode: string,
result: Awaited<ReturnType<WabtArtifactProvider["inspect"]>>,
path: string,
): void => {
if (mode === "success")
expect(result).toMatchObject({
ok: true,
value: {
result: {
artifact: { path, bytes: 76 },
validation: "valid",
runtime_execution: "not-performed",
},
},
});
else
expect(result).toMatchObject({
ok: false,
error: { _tag: failureTags[mode] },
});
if (mode === "invalid")
expect(result).toMatchObject({
error: { capturedOutput: { stderr: "module.wasm: invalid bytes\n" } },
});
if (mode === "malformed-wat" || mode === "wat-warning")
expect(result).toMatchObject({
error: {
capturedOutput: {
stdout:
mode === "malformed-wat"
? "unexpected decoder output\n"
: '(module (@custom "test" "payload"))\n',
stderr: mode === "wat-warning" ? "decoder warning\n" : "",
},
},
});
};
it("returns actionable unavailable without creating a workspace when tools are absent", async () => {
const provider = new WabtArtifactProvider({}, undefined, () => {
throw new Error("Must not allocate");
@@ -39,6 +142,88 @@ it("returns actionable unavailable without creating a workspace when tools are a
});
});
it("retries a retained input descriptor before admitting the next WABT operation", async () => {
const root = await createTestTempDirectory("rea-wabt-read-cleanup-");
const path = join(root, "selected.wasm");
await writeFile(path, Buffer.alloc(76, 1));
for (const tool of ["wasm-validate", "wasm-objdump", "wasm2wat"])
await writeFile(join(root, tool), "source-owned executable seam", {
mode: 0o700,
});
const dump = await readFile(
new URL("../../tests/fixtures/wasm/objdump.txt", import.meta.url),
"utf8",
);
const provider = new WabtArtifactProvider(
{ REA_WABT_BIN_DIRECTORY: root },
async (input) => {
const version = input.arguments[0] === "--version";
const stdout = version
? "1.0.42\n"
: input.command.includes("wasm-objdump")
? dump
: input.command.includes("wasm2wat")
? '(module (@custom "test" "payload"))\n'
: "";
const launched = await spawnOwnedProviderProcess({
...input,
command: process.execPath,
arguments: [
"-e",
`process.stdout.write(${JSON.stringify(stdout)}); process.exit(0);`,
],
expectedCommand: null,
});
return launched;
},
);
fileCloseFailure.selectedPath = path;
fileCloseFailure.attempts = 0;
fileCloseFailure.failFirst = true;
try {
const first = await provider.inspect({
path,
candidate_paths: [],
glue_paths: [],
});
expect(first).toMatchObject({
ok: false,
error: {
cleanupIncomplete: true,
cleanupResources: [path],
cause: { message: "injected WABT input close failure" },
},
});
expect(fileCloseFailure.attempts).toBe(1);
const retried = await provider.inspect({
path,
candidate_paths: [],
glue_paths: [],
});
expect(retried.ok).toBe(true);
expect(fileCloseFailure.attempts).toBeGreaterThan(1);
fileCloseFailure.failFirst = true;
const closeRetry = await provider.inspect({
path,
candidate_paths: [],
glue_paths: [],
});
expect(closeRetry).toMatchObject({
ok: false,
error: { cleanupIncomplete: true, cleanupResources: [path] },
});
const beforeClose = fileCloseFailure.attempts;
await provider.close();
expect(fileCloseFailure.attempts).toBeGreaterThan(beforeClose);
} finally {
fileCloseFailure.selectedPath = "";
fileCloseFailure.failFirst = false;
await provider.close();
}
});
it.each([false, true])(
"reports an unavailable private runtime root with retryable=%s without a misleading WABT remediation",
async (retryable) => {
@@ -110,6 +295,7 @@ it.each([
"utf8",
);
let runtimePath = "";
let runtimeCreations = 0;
let acquiredPid: number | undefined;
let cleanupAttempts = 0;
const controller = new AbortController();
@@ -168,6 +354,7 @@ it.each([
return launched;
},
async () => {
runtimeCreations += 1;
const root = await PrivateRuntimeRoot.create({
prefix: "rea-wabt-owned-test-",
});
@@ -186,53 +373,17 @@ it.each([
{ path, glue_paths: [], candidate_paths: [] },
{ signal: controller.signal },
);
if (mode === "success")
expect(result).toMatchObject({
ok: true,
value: {
result: {
artifact: { path, bytes: 76 },
validation: "valid",
runtime_execution: "not-performed",
},
},
});
else
expect(result).toMatchObject({
ok: false,
error: { _tag: failureTags[mode] },
});
if (mode === "invalid")
expect(result).toMatchObject({
error: { capturedOutput: { stderr: "module.wasm: invalid bytes\n" } },
});
assertModeOutcome(mode, result, path);
if (mode === "cleanup") {
expect(result).toMatchObject({
error: {
cleanupIncomplete: true,
cleanupResources: [runtimePath],
partialObservation: { normalized_result: { validation: "valid" } },
},
await assertCleanupRecovery({
provider,
result,
path,
runtimePath,
cleanupAttempts: () => cleanupAttempts,
runtimeCreations: () => runtimeCreations,
});
await expect(access(runtimePath)).resolves.toBeUndefined();
await expect(provider.close()).rejects.toMatchObject({
cleanupIncomplete: true,
});
await expect(access(runtimePath)).resolves.toBeUndefined();
await provider.close();
}
if (mode === "malformed-wat" || mode === "wat-warning")
expect(result).toMatchObject({
error: {
capturedOutput: {
stdout:
mode === "malformed-wat"
? "unexpected decoder output\n"
: '(module (@custom "test" "payload"))\n',
stderr: mode === "wat-warning" ? "decoder warning\n" : "",
},
},
});
await expect(access(runtimePath)).rejects.toMatchObject({ code: "ENOENT" });
expect(await readFile(path)).toEqual(bytes);
if (acquiredPid !== undefined) {