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
@@ -17,6 +17,7 @@ import { z } from "zod";
import type { ExecutionOptions } from "../../application/AnalysisProvider.js";
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisCapabilityUnavailableError,
@@ -26,6 +27,7 @@ import {
} from "../../domain/analysisErrorCore.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js";
import { err, ok, type Result } from "../../domain/result.js";
import {
WEB_NETWORK_CAPTURE_LIMITS,
@@ -60,18 +62,52 @@ const replySchema = z.discriminatedUnion("ok", [
/** One owned snapshot/process/root lifecycle for replaceable historical format decoders. */
export class HistoricalCaptureDecoder {
readonly #resources: ArtifactResourceScope;
constructor(
readonly adapters: readonly HistoricalCaptureFormatAdapter[],
readonly environment: Readonly<NodeJS.ProcessEnv>,
readonly createRuntime: () => Promise<
Pick<PrivateRuntimeRoot, "path" | "close">
> = () => PrivateRuntimeRoot.create({ prefix: "rea-web-capture-" }),
) {}
resources = new ArtifactResourceScope(),
) {
this.#resources = resources;
}
/** Retry retained readers and private roots at service shutdown. */
close(): Promise<void> {
return this.#resources.close();
}
/** Snapshot the selected artifact, decode it offline, and release private credentials and processes. */
async inspect(
input: InspectWebNetworkCaptureInput,
options?: ExecutionOptions,
): Promise<Result<WebNetworkCapture, AnalysisError>> {
try {
return await this.#resources.run(() =>
this.inspectAdmitted(input, options),
);
} catch (cause: unknown) {
const error = historicalCaptureFailure(
input,
cause,
"capture-read",
options,
);
return err(
redactExplicitFailure(
this.withReaderCleanup(error, cause),
input.sensitive_values,
),
);
}
}
private async inspectAdmitted(
input: InspectWebNetworkCaptureInput,
options?: ExecutionOptions,
): Promise<Result<WebNetworkCapture, AnalysisError>> {
let runtime: Pick<PrivateRuntimeRoot, "path" | "close"> | undefined;
let result: Result<WebNetworkCapture, AnalysisError>;
@@ -90,6 +126,8 @@ export class HistoricalCaptureDecoder {
input.capture_path,
WEB_NETWORK_CAPTURE_LIMITS.inputBytes,
options?.signal,
undefined,
this.#resources,
);
phase = "decoder";
runtime = await this.createRuntime();
@@ -139,9 +177,16 @@ export class HistoricalCaptureDecoder {
replyPath,
WEB_NETWORK_CAPTURE_LIMITS.outputBytes,
options?.signal,
undefined,
this.#resources,
);
reply = replySchema.parse(JSON.parse(replyFile.bytes.toString("utf8")));
} catch (cause: unknown) {
if (
cause instanceof ArtifactReaderFailure &&
cause.cleanup !== undefined
)
throw cause;
if (options?.signal?.aborted)
throw new AnalysisCancelledError(OPERATION);
throw new AnalysisOutputError(
@@ -230,17 +275,21 @@ export class HistoricalCaptureDecoder {
result = ok({ ...reply.value, ...common, format: input.format });
}
} catch (cause: unknown) {
const error = historicalCaptureFailure(input, cause, phase, options);
result = err(
redactExplicitFailure(
historicalCaptureFailure(input, cause, phase, options),
this.withReaderCleanup(error, cause),
input.sensitive_values,
),
);
}
if (runtime !== undefined) {
try {
await runtime.close();
} catch (cause: unknown) {
const cleanup = await this.#resources.release({
kind: "private-runtime-root",
resource: runtime.path,
root: runtime,
});
if (cleanup.kind === "failed") {
return err(
redactExplicitFailure(
new ProviderCleanupError(
@@ -251,9 +300,12 @@ export class HistoricalCaptureDecoder {
previous_error: result.ok
? null
: projectAnalysisError(result.error),
reason: cause instanceof Error ? cause.message : String(cause),
reason:
cleanup.cause instanceof Error
? cleanup.cause.message
: String(cleanup.cause),
},
{ operation: OPERATION },
{ operation: OPERATION, cause: cleanup.cause },
),
input.sensitive_values,
),
@@ -264,6 +316,34 @@ export class HistoricalCaptureDecoder {
? err(new AnalysisCancelledError(OPERATION))
: result;
}
private withReaderCleanup(
primary: AnalysisError,
cause: unknown,
): AnalysisError {
if (
!(cause instanceof ArtifactReaderFailure) ||
cause.cleanup === undefined
)
return primary;
if (cause.reason === "unavailable")
return new ProviderCleanupError(
"web-network-capture",
cause.cleanup.resources,
{ reason: cause.cleanup.reason },
{ operation: OPERATION, cause },
);
const cleanup = new ProviderCleanupError(
"web-network-capture",
cause.cleanup.resources,
{
reason: cause.cleanup.reason,
previous_error: projectAnalysisError(primary),
},
{ operation: OPERATION, cause },
);
return analysisErrorWithCleanupFailure(primary, cleanup, OPERATION);
}
}
/** The Node capture decoder runs on this executable; only Node.js enforces its V8 heap flags. */