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) {
+68 -26
View File
@@ -9,6 +9,8 @@ import type {
WasmArtifactPort,
} from "../application/wasm/WasmArtifactPort.js";
import { readStableArtifact } from "../artifacts/readStableArtifact.js";
import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import type {
AnalysisError,
AnalysisCapturedOutput,
@@ -16,6 +18,7 @@ import type {
import {
AnalysisCancelledError,
AnalysisArtifactChangedError,
AnalysisCapabilityUnavailableError,
AnalysisInputError,
AnalysisOutputError,
} from "../domain/analysisErrorCore.js";
@@ -41,9 +44,7 @@ const digest = (text: string) =>
createHash("sha256").update(text).digest("hex");
/** Run caller-supplied WABT against private copies of exactly selected bytes. */
export class WabtArtifactProvider implements WasmArtifactPort {
readonly #pendingRoots = new Set<
Pick<PrivateRuntimeRoot, "path" | "close">
>();
readonly #resources = new ArtifactResourceScope();
constructor(
readonly environment: Readonly<NodeJS.ProcessEnv> = process.env,
readonly launcher?: Launcher,
@@ -53,29 +54,51 @@ export class WabtArtifactProvider implements WasmArtifactPort {
) {}
/** Retry retained cleanup without discarding roots that still cannot be removed. */
async close(): Promise<void> {
const failures: { path: string; reason: string }[] = [];
for (const root of this.#pendingRoots) {
try {
await root.close();
this.#pendingRoots.delete(root);
} catch (cause: unknown) {
failures.push({
path: root.path,
reason: cause instanceof Error ? cause.message : String(cause),
});
}
}
if (failures.length > 0)
try {
await this.#resources.close();
} catch (cause: unknown) {
const cleanup =
cause instanceof ArtifactReaderFailure ? cause.cleanup : undefined;
throw new ProviderCleanupError(
WABT_PROVIDER_IDENTITY.id,
failures.map(({ path }) => path),
{ failures },
{ operation: OPERATION },
cleanup?.resources ?? ["artifact-resources"],
{
reason:
cleanup?.reason ??
(cause instanceof Error ? cause.message : String(cause)),
},
{ operation: OPERATION, cause },
);
}
}
async inspect(
input: InspectWasmArtifactInput,
options?: ExecutionOptions,
): Promise<Result<WasmArtifactExecution, AnalysisError>> {
try {
return await this.#resources.run(() => this.#inspect(input, options));
} catch (cause: unknown) {
if (
cause instanceof ArtifactReaderFailure &&
cause.reason === "unavailable" &&
cause.cleanup === undefined
)
return err(this.#closedError());
return err(wabtFailure(cause, "artifact", input.path));
}
}
#closedError(): AnalysisCapabilityUnavailableError {
return new AnalysisCapabilityUnavailableError(
WABT_PROVIDER_IDENTITY.id,
OPERATION,
"Provider is closing",
);
}
async #inspect(
input: InspectWasmArtifactInput,
options?: ExecutionOptions,
): Promise<Result<WasmArtifactExecution, AnalysisError>> {
let root: Pick<PrivateRuntimeRoot, "path" | "close"> | undefined;
let phase: "configuration" | "artifact" | "producer" = "configuration";
@@ -83,7 +106,6 @@ export class WabtArtifactProvider implements WasmArtifactPort {
let capturedOutput: AnalysisCapturedOutput | undefined;
try {
if (options?.signal?.aborted) throw new AnalysisCancelledError(OPERATION);
await this.close();
const directory = this.environment.REA_WABT_BIN_DIRECTORY ?? "";
if (!isAbsolute(directory))
throw new Error(
@@ -108,6 +130,8 @@ export class WabtArtifactProvider implements WasmArtifactPort {
path,
WABT_LIMITS.toolBytes,
options?.signal,
undefined,
this.#resources,
);
commands.push({
tool,
@@ -130,17 +154,24 @@ export class WabtArtifactProvider implements WasmArtifactPort {
snapshotPath,
WABT_LIMITS.inputBytes,
options?.signal,
undefined,
this.#resources,
);
if (bytes.sha256 !== snapshotHash)
throw new Error("Private WASM snapshot bytes changed.");
} catch (cause: unknown) {
const cleanup =
cause instanceof ArtifactReaderFailure ? cause.cleanup : undefined;
if (options?.signal?.aborted)
throw new AnalysisCancelledError(OPERATION);
throw new AnalysisCancelledError(OPERATION, {
cause,
...(cleanup === undefined ? {} : { cleanup }),
});
throw new AnalysisArtifactChangedError(
OPERATION,
input.path,
"Private WASM snapshot no longer matches selected byte identity.",
{ cause },
{ cause, ...(cleanup === undefined ? {} : { cleanup }) },
);
}
};
@@ -175,6 +206,8 @@ export class WabtArtifactProvider implements WasmArtifactPort {
command.path,
WABT_LIMITS.toolBytes,
options?.signal,
undefined,
this.#resources,
);
if (current.sha256 !== command.sha256)
throw new AnalysisOutputError(
@@ -200,6 +233,8 @@ export class WabtArtifactProvider implements WasmArtifactPort {
input.path,
WABT_LIMITS.inputBytes,
options?.signal,
undefined,
this.#resources,
);
const artifact = {
path: input.path,
@@ -215,6 +250,8 @@ export class WabtArtifactProvider implements WasmArtifactPort {
path,
WABT_LIMITS.inputBytes,
options?.signal,
undefined,
this.#resources,
);
candidates.push({
path,
@@ -228,6 +265,8 @@ export class WabtArtifactProvider implements WasmArtifactPort {
path,
WABT_LIMITS.inputBytes,
options?.signal,
undefined,
this.#resources,
);
const source = new TextDecoder("utf-8", { fatal: true }).decode(
bytes.bytes,
@@ -395,10 +434,13 @@ export class WabtArtifactProvider implements WasmArtifactPort {
);
}
if (root !== undefined) {
try {
await root.close();
} catch (cause: unknown) {
this.#pendingRoots.add(root);
const cleanup = await this.#resources.release({
kind: "private-runtime-root",
resource: root.path,
root,
});
if (cleanup.kind === "failed") {
const cause = cleanup.cause;
const partialObservation = result.ok
? createEvidence(
result.value.subject ?? undefined,
+20 -7
View File
@@ -20,12 +20,19 @@ export const wabtFailure = (
path: string,
): AnalysisError => {
if (cause instanceof AnalysisError) return cause;
const artifactCleanup =
cause instanceof ArtifactReaderFailure ? cause.cleanup : undefined;
const cleanupOptions =
artifactCleanup === undefined ? {} : { cleanup: artifactCleanup };
const reason = cause instanceof Error ? cause.message : String(cause);
if (
(cause instanceof ArtifactReaderFailure && cause.reason === "cancelled") ||
(cause instanceof Error && cause.name === "AbortError")
)
return new AnalysisCancelledError("inspect_wasm_artifact", { cause });
return new AnalysisCancelledError("inspect_wasm_artifact", {
cause,
...cleanupOptions,
});
if (cause instanceof OwnedCommandFailure) {
const capturedOutput =
cause.snapshot === null
@@ -85,6 +92,7 @@ export const wabtFailure = (
reason,
{
cause,
...cleanupOptions,
userMessage: `${reason} Supply WABT 1.0.42 via absolute REA_WABT_BIN_DIRECTORY; REA does not install tools.`,
},
);
@@ -97,7 +105,7 @@ export const wabtFailure = (
"inspect_wasm_artifact",
path,
reason,
{ cause },
{ cause, ...cleanupOptions },
);
if (
phase === "artifact" &&
@@ -109,11 +117,16 @@ export const wabtFailure = (
"inspect_wasm_artifact",
path,
cause.code,
{ cause },
{ cause, ...cleanupOptions },
);
if (phase === "artifact")
return new AnalysisInputError("inspect_wasm_artifact", { cause }, [
{ path: ["path"], reason: "invalid_value", message: reason },
]);
return new AnalysisOutputError("inspect_wasm_artifact", reason, { cause });
return new AnalysisInputError(
"inspect_wasm_artifact",
{ cause, ...cleanupOptions },
[{ path: ["path"], reason: "invalid_value", message: reason }],
);
return new AnalysisOutputError("inspect_wasm_artifact", reason, {
cause,
...cleanupOptions,
});
};