perf(wasm): parallelize WABT tool admission, stat-verify unchanged binaries, and halve snapshot re-hashing (#13470)

* perf(wasm): parallelize WABT tool admission, stat-verify unchanged binaries, and halve snapshot re-hashing (#13284)

* fix(wabt): retain every failed tool admission cleanup
This commit is contained in:
morluto authored and GitHub committed 2026-11-22 11:40:12 -05:00
1 parent 90ca43e052
commit 99c42ddc46
2 files changed
+135 -58

No files matched your search

+48
View File
@@ -58,6 +58,7 @@ const fileCloseFailure = vi.hoisted(() => ({
selectedPath: "",
attempts: 0,
failFirst: false,
toolCloseFailures: new Set<string>(),
failRead: undefined as (() => Error) | undefined,
abortSnapshotWrite: undefined as AbortController | undefined,
}));
@@ -82,6 +83,18 @@ vi.mock("node:fs/promises", async (importOriginal) => {
},
open: async (...args: Parameters<typeof fs.open>) => {
const handle = await fs.open(...args);
const toolPath = [...fileCloseFailure.toolCloseFailures].find((path) =>
samePath(String(args[0]), path),
);
if (toolPath !== undefined) {
const close = handle.close.bind(handle);
handle.close = async () => {
if (fileCloseFailure.toolCloseFailures.delete(toolPath))
throw new Error("injected WABT tool close failure");
return close();
};
return handle;
}
if (!samePath(String(args[0]), fileCloseFailure.selectedPath))
return handle;
const close = handle.close.bind(handle);
@@ -1242,6 +1255,41 @@ it("retries a retained input descriptor before admitting the next WABT operation
}
});
it("reports the first tool admission failure and tracks every sibling descriptor until release", async () => {
const root = await realpath(
await createTestTempDirectory("rea-wabt-tool-cleanup-"),
);
const suffix = process.platform === "win32" ? ".exe" : "";
const siblingTools = ["wasm-objdump", "wasm2wat"].map((tool) =>
join(root, tool + suffix),
);
for (const path of siblingTools) {
await writeFile(path, "fixture tool", { mode: 0o755 });
fileCloseFailure.toolCloseFailures.add(path);
}
const provider = new WabtArtifactProvider({ REA_WABT_BIN_DIRECTORY: root });
try {
const result = await provider.inspect({
path: join(root, "selected.wasm"),
candidate_paths: [],
glue_paths: [],
});
if (result.ok) throw new Error("Expected rejected tool admission");
const primary = projectAnalysisError(primaryAnalysisError(result.error));
expect(primary.code).toBe("capability_unavailable");
expect(primary.message).toContain("wasm-validate");
expect(result.error.cleanupIncomplete).toBe(true);
expect(result.error.cleanupResources).toEqual(siblingTools);
await provider.close();
expect(result.error.cleanupIncomplete).toBe(false);
expect(result.error.cleanupResources).toEqual([]);
} finally {
fileCloseFailure.toolCloseFailures.clear();
await provider.close();
}
});
it.each([false, true])(
"reports an unavailable private runtime root with retryable=%s without a misleading WABT remediation",
async (retryable) => {
+87 -58
View File
@@ -4,10 +4,11 @@ import { decodeStrictUtf8 } from "../domain/strictUtf8.js";
import { WabtAdmissionError } from "./WabtAdmissionError.js";
import { HOST_PLATFORM } from "../platform/HostPlatform.js";
import { randomUUID } from "node:crypto";
import { access, writeFile } from "node:fs/promises";
import { constants } from "node:fs";
import { access, stat, writeFile } from "node:fs/promises";
import { constants, type BigIntStats } from "node:fs";
import { isAbsolute, join } from "node:path";
import { appendCallerPath } from "../filesystem/callerPath.js";
import { sameRegularFileState } from "../filesystem/RegularFile.js";
import type {
WasmArtifactExecutionOptions,
WasmArtifactExecution,
@@ -261,6 +262,24 @@ export class WabtArtifactProvider implements WasmArtifactPort {
input.command_timeout_ms !== undefined
? "request"
: options?.commandTimeoutSource;
const classifyFailure = (cause: unknown) =>
classifyProviderFailure(
cause,
wabtFailureDialect(
phase,
phase === "artifact" ? artifactInput.path : input.path,
{
commandTimeoutMs,
...(commandTimeoutSource === undefined
? {}
: { commandTimeoutSource }),
limits,
inputField: artifactInput.field,
observedOutput: capturedOutput,
...(versionProbe === undefined ? {} : { versionProbe }),
},
),
);
try {
if (isAborted(options?.signal))
throw cancelledBy(OPERATION, options.signal);
@@ -271,6 +290,38 @@ export class WabtArtifactProvider implements WasmArtifactPort {
// Keep the caller's rejected selection; unset stays distinct.
...(directory === undefined ? {} : { configured: directory }),
});
const toolNames = ["wasm-validate", "wasm-objdump", "wasm2wat"] as const;
const settledTools = await Promise.allSettled(
toolNames.map(async (tool) => {
const selection = await selectArtifactCommandPath(
appendCallerPath(
directory,
`${tool}${HOST_PLATFORM.platform === "win32" ? ".exe" : ""}`,
),
options?.signal,
);
const path = selection.resolvedPath;
await access(path, constants.X_OK);
const initialStat = await stat(path, { bigint: true });
const binary = await readIdentity(path, limits.toolBytes);
return {
tool,
path,
selection,
initialStat,
sha256: binary.sha256,
version_banner: "",
arguments:
tool === "wasm-objdump"
? ["-h", "-x", "module.wasm"]
: [
"--enable-all",
"--ignore-custom-section-errors",
"module.wasm",
],
};
}),
);
const commands: {
tool: "wasm-validate" | "wasm-objdump" | "wasm2wat";
path: string;
@@ -278,38 +329,24 @@ export class WabtArtifactProvider implements WasmArtifactPort {
version_banner: string;
arguments: string[];
selection: ArtifactCommandPath;
initialStat: BigIntStats;
}[] = [];
for (const tool of [
"wasm-validate",
"wasm-objdump",
"wasm2wat",
] as const) {
const selection = await selectArtifactCommandPath(
appendCallerPath(
directory,
`${tool}${HOST_PLATFORM.platform === "win32" ? ".exe" : ""}`,
),
options?.signal,
);
const path = selection.resolvedPath;
await access(path, constants.X_OK);
const binary = await readIdentity(path, limits.toolBytes);
commands.push({
tool,
path,
selection,
sha256: binary.sha256,
version_banner: "",
arguments:
tool === "wasm-objdump"
? ["-h", "-x", "module.wasm"]
: [
"--enable-all",
"--ignore-custom-section-errors",
"module.wasm",
],
});
let admissionFailure: AnalysisError | undefined;
for (const settled of settledTools) {
if (settled.status === "fulfilled") {
commands.push(settled.value);
continue;
}
const failure = classifyFailure(settled.reason);
if (admissionFailure === undefined) admissionFailure = failure;
else if (failure.cleanupIncomplete)
admissionFailure = analysisErrorWithCleanupDependencies(
admissionFailure,
failure,
OPERATION,
);
}
if (admissionFailure !== undefined) throw admissionFailure;
const root = await this.createRuntime();
runtime = new WabtRuntime(root);
const snapshotPath = join(root.path, "module.wasm");
@@ -332,7 +369,6 @@ export class WabtArtifactProvider implements WasmArtifactPort {
) => {
capturedOutput = undefined;
await assertArtifactCommandPath(command.selection, OPERATION, options);
await verifySnapshot();
const snapshot = await runOwnedCommand(
{
command: command.selection.invocationPath,
@@ -378,13 +414,21 @@ export class WabtArtifactProvider implements WasmArtifactPort {
...(options?.signal === undefined ? {} : { signal: options.signal }),
capturedOutput,
});
const current = await readIdentity(command.path, limits.toolBytes);
if (current.sha256 !== command.sha256)
throw new AnalysisOutputError(
OPERATION,
"Configured WABT executable changed during inspection.",
{ capturedOutput },
);
const currentStat = await stat(command.path, { bigint: true }).catch(
() => undefined,
);
if (
currentStat === undefined ||
!sameRegularFileState(command.initialStat, currentStat)
) {
const current = await readIdentity(command.path, limits.toolBytes);
if (current.sha256 !== command.sha256)
throw new AnalysisOutputError(
OPERATION,
"Configured WABT executable changed during inspection.",
{ capturedOutput },
);
}
await verifySnapshot();
return snapshot;
};
@@ -437,7 +481,8 @@ export class WabtArtifactProvider implements WasmArtifactPort {
source_commit:
admittedVersion === WABT_VERSION ? WABT_SOURCE_COMMIT : null,
commands: commands.map(
({ selection: _selection, ...command }) => command,
({ selection: _selection, initialStat: _initialStat, ...command }) =>
command,
),
timeout_ms: commandTimeoutMs,
output_budget_bytes: limits.outputBytes,
@@ -706,23 +751,7 @@ export class WabtArtifactProvider implements WasmArtifactPort {
}),
);
} catch (cause: unknown) {
const failure = classifyProviderFailure(
cause,
wabtFailureDialect(
phase,
phase === "artifact" ? artifactInput.path : input.path,
{
commandTimeoutMs,
...(commandTimeoutSource === undefined
? {}
: { commandTimeoutSource }),
limits,
inputField: artifactInput.field,
observedOutput: capturedOutput,
...(versionProbe === undefined ? {} : { versionProbe }),
},
),
);
const failure = classifyFailure(cause);
if (failure.partialObservation === undefined) {
const partial = acquiredEvidence();
if (partial !== undefined) failure.retainPartialObservation(partial);