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
+47 -14
View File
@@ -1,5 +1,7 @@
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js";
import type { PeResourcesPort } from "../../application/binaryDiagnostics/PeResourcesPort.js";
import type { ExecutionOptions } from "../../application/AnalysisProvider.js";
import { ArtifactOperationError } from "../../domain/artifactOperationError.js";
@@ -12,19 +14,29 @@ import {
} from "../../domain/analysisErrorCore.js";
import type { InspectPeResourcesInput } from "../../domain/native/peResources.js";
import { err, ok } from "../../domain/result.js";
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
import { PE_RESOURCES_PROVIDER } from "../../application/InvestigationProviders.js";
import { parsePeResources } from "./PeResourceParser.js";
/** Portable parser over one bounded, identity-checked regular file. */
export class PeResourcesProvider implements PeResourcesPort {
readonly identity = PE_RESOURCES_PROVIDER;
readonly #resources = new ArtifactResourceScope();
close(): Promise<void> {
return this.#resources.close();
}
async inspect(input: InspectPeResourcesInput, options?: ExecutionOptions) {
try {
const snapshot = await readStableArtifact(
input.path,
input.max_file_bytes,
options?.signal,
const snapshot = await this.#resources.run(() =>
readStableArtifact(
input.path,
input.max_file_bytes,
options?.signal,
undefined,
this.#resources,
),
);
return ok(
await parsePeResources(
@@ -44,12 +56,21 @@ export class PeResourcesProvider implements PeResourcesPort {
}
}
const peResourcesFailure = (
const peResourcesFailurePrimary = (
cause: unknown,
input: InspectPeResourcesInput,
signal: AbortSignal | undefined,
) => {
const operation = "inspect_pe_resources";
if (cause instanceof ArtifactReaderFailure && cause.reason === "integrity")
return new AnalysisArtifactChangedError(
operation,
input.path,
cause.message,
{ cause },
);
if (cause instanceof ArtifactReaderFailure && cause.reason === "cancelled")
return new AnalysisCancelledError(operation, { cause });
if (signal?.aborted) return new AnalysisCancelledError(operation, { cause });
if (cause instanceof ArtifactReaderFailure) {
@@ -64,13 +85,6 @@ const peResourcesFailure = (
},
{ cause },
);
if (cause.reason === "integrity")
return new AnalysisArtifactChangedError(
operation,
input.path,
cause.message,
{ cause },
);
if (cause.reason === "path" || cause.reason === "format")
return new AnalysisInputError(operation, { cause }, [
{
@@ -79,8 +93,6 @@ const peResourcesFailure = (
message: cause.message,
},
]);
if (cause.reason === "cancelled")
return new AnalysisCancelledError(operation, { cause });
}
if (cause instanceof Error && "code" in cause) {
@@ -106,3 +118,24 @@ const peResourcesFailure = (
{ cause },
);
};
const peResourcesFailure = (
cause: unknown,
input: InspectPeResourcesInput,
signal: AbortSignal | undefined,
) => {
const primary = peResourcesFailurePrimary(cause, input, signal);
if (!(cause instanceof ArtifactReaderFailure) || cause.cleanup === undefined)
return primary;
const cleanup = new ProviderCleanupError(
PE_RESOURCES_PROVIDER.id,
cause.cleanup.resources,
{ reason: cause.cleanup.reason },
{ operation: "inspect_pe_resources", cause },
);
return analysisErrorWithCleanupFailure(
primary,
cleanup,
"inspect_pe_resources",
);
};
+19 -13
View File
@@ -17,6 +17,7 @@ import {
type RecordedCrash,
} from "../../domain/native/recordedCrash.js";
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
import type { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
capturedPwntoolsOutput,
@@ -46,6 +47,7 @@ const replySchema = z.discriminatedUnion("ok", [
export const inspectPwndbgCore = async ({
environment,
rootPath,
resources,
diagnostics,
options,
runCommand,
@@ -53,6 +55,7 @@ export const inspectPwndbgCore = async ({
}: {
readonly environment: Readonly<NodeJS.ProcessEnv>;
readonly rootPath: string;
readonly resources: ArtifactResourceScope;
readonly diagnostics: AnalysisCapturedOutput;
readonly options: ExecutionOptions | undefined;
readonly runCommand: PwntoolsCommand;
@@ -178,11 +181,14 @@ export const inspectPwndbgCore = async ({
replyPath,
PWNTOOLS_LIMITS.outputBytes,
options?.signal,
undefined,
resources,
);
reply = replySchema.parse(JSON.parse(raw.bytes.toString("utf8")));
} catch (cause: unknown) {
if (options?.signal?.aborted)
throw new AnalysisCancelledError(OPERATION, {
cause,
capturedOutput: recordedCrashStageOutput(diagnostics, output),
});
throw new AnalysisOutputError(
@@ -226,22 +232,22 @@ export const inspectPwndbgCore = async ({
return { ...reply.value, diagnostics: output };
} catch (cause: unknown) {
if (cause instanceof AnalysisError && cause.cleanupIncomplete) throw cause;
if (
const primary =
options?.signal?.aborted &&
(cause === options.signal.reason ||
(cause instanceof Error && cause.name === "AbortError"))
)
throw new AnalysisCancelledError(OPERATION, {
capturedOutput: recordedCrashStageOutput(diagnostics, output),
});
throw pwntoolsDecoderFailure(
cause,
"debugger",
gdb,
environment.REA_PWNTOOLS_PYTHON ?? "",
await readPwntoolsFailureEvidence(cause, stage),
failureContext,
);
? new AnalysisCancelledError(OPERATION, {
capturedOutput: recordedCrashStageOutput(diagnostics, output),
})
: pwntoolsDecoderFailure(
cause,
"debugger",
gdb,
environment.REA_PWNTOOLS_PYTHON ?? "",
await readPwntoolsFailureEvidence(cause, stage, resources),
failureContext,
);
throw primary;
}
};
+106 -19
View File
@@ -16,6 +16,8 @@ import type {
AnalysisPartialObservation,
} from "../../domain/analysisErrorBase.js";
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
@@ -78,6 +80,7 @@ export interface PwntoolsDecoderProfile<
readonly payload: Payload;
readonly snapshot: { readonly bytes: Buffer; readonly sha256: string };
readonly rootPath: string;
readonly resources: ArtifactResourceScope;
readonly diagnostics: AnalysisCapturedOutput;
readonly options: ExecutionOptions | undefined;
readonly runCommand: PwntoolsCommand;
@@ -96,6 +99,7 @@ export class PwntoolsDecoder<
symbol,
"admitted" | "cancelled"
>();
readonly #resources = new ArtifactResourceScope();
#closing = false;
#closePromise: Promise<void> | undefined;
#pendingCleanup:
@@ -244,6 +248,8 @@ export class PwntoolsDecoder<
input.path,
PWNTOOLS_LIMITS.inputBytes,
options?.signal,
undefined,
this.#resources,
);
phase = "decoder";
root = await this.createRuntime();
@@ -298,11 +304,16 @@ export class PwntoolsDecoder<
replyPath,
PWNTOOLS_LIMITS.outputBytes,
options?.signal,
undefined,
this.#resources,
);
reply = replySchema.parse(JSON.parse(file.bytes.toString("utf8")));
} catch (cause: unknown) {
if (options?.signal?.aborted)
throw new AnalysisCancelledError(OPERATION, { capturedOutput });
throw new AnalysisCancelledError(OPERATION, {
cause,
capturedOutput,
});
throw new AnalysisOutputError(
OPERATION,
`Owned pwntools decoder reply failed for ${input.path}: ${cause instanceof z.ZodError ? cause.issues[0]?.message + " at " + (cause.issues[0]?.path.map(String).join(".") ?? "root") : cause instanceof Error ? cause.message : String(cause)}`,
@@ -369,6 +380,7 @@ export class PwntoolsDecoder<
payload: reply.value,
snapshot,
rootPath: root.path,
resources: this.#resources,
diagnostics: capturedOutput,
options,
runCommand: (spawn, classifyFailure) =>
@@ -385,12 +397,18 @@ export class PwntoolsDecoder<
}
return err(cause);
}
const evidence = await readPwntoolsFailureEvidence(cause, root?.path);
result = err(
const evidence = await readPwntoolsFailureEvidence(
cause,
root?.path,
this.#resources,
);
const primary =
options?.signal?.aborted &&
(cause === options.signal.reason ||
(cause instanceof Error && cause.name === "AbortError"))
? new AnalysisCancelledError(OPERATION)
(cause === options.signal.reason ||
(cause instanceof Error && cause.name === "AbortError") ||
(cause instanceof ArtifactReaderFailure &&
cause.cleanup !== undefined))
? new AnalysisCancelledError(OPERATION, { cause })
: pwntoolsDecoderFailure(
cause,
phase,
@@ -398,8 +416,8 @@ export class PwntoolsDecoder<
executablePath,
evidence,
context,
),
);
);
result = err(primary);
}
if (this.#pendingCleanup !== undefined) {
this.#pendingCleanup.failure = result.ok ? undefined : result.error;
@@ -483,7 +501,39 @@ export class PwntoolsDecoder<
this.#closing = true;
this.#closePromise ??= this.#tail
.then(async () => {
const failure = await this.#retire();
let failure: AnalysisError | undefined;
try {
failure = await this.#retire();
} catch (cause: unknown) {
failure = new ProviderCleanupError(
this.identity.id,
[this.#pendingCleanup?.root?.path ?? "pwntools decoder"],
{ reason: cause instanceof Error ? cause.message : String(cause) },
{ operation: this.profile.operation, cause },
);
}
try {
await this.#resources.close();
} catch (cause: unknown) {
const observation = ArtifactReaderFailure.cleanupObservation(
cause,
"pwntools artifact read",
);
const resourceFailure = new ProviderCleanupError(
this.identity.id,
observation.resources,
{ reason: observation.reason },
{ operation: this.profile.operation, cause },
);
failure =
failure === undefined
? resourceFailure
: analysisErrorWithCleanupFailure(
failure,
resourceFailure,
this.profile.operation,
);
}
if (failure !== undefined) throw failure;
})
.catch((cause: unknown) => {
@@ -502,8 +552,8 @@ export class PwntoolsDecoder<
}
async #completeCleanup(
retire: () => Promise<ProviderCleanupError | undefined>,
): Promise<ProviderCleanupError | undefined> {
retire: () => Promise<AnalysisError | undefined>,
): Promise<AnalysisError | undefined> {
const failure = await retire();
return failure !== undefined && this.#closing ? retire() : failure;
}
@@ -548,18 +598,46 @@ export class PwntoolsDecoder<
return undefined;
}
async #retire(): Promise<ProviderCleanupError | undefined> {
const failure = await this.#retireProcess();
if (failure !== undefined) return failure;
async #retire(): Promise<AnalysisError | undefined> {
let failure: AnalysisError | undefined;
try {
await this.#resources.retryCleanup();
} catch (cause: unknown) {
const observation = ArtifactReaderFailure.cleanupObservation(
cause,
"pwntools artifact read",
);
failure = new ProviderCleanupError(
this.identity.id,
observation.resources,
{ reason: observation.reason },
{
operation: this.profile.operation,
cause,
...(this.#pendingCleanup?.observation === undefined
? {}
: { partialObservation: this.#pendingCleanup.observation }),
},
);
}
const processFailure = await this.#retireProcess();
if (processFailure !== undefined) {
return failure === undefined
? processFailure
: analysisErrorWithCleanupFailure(
failure,
processFailure,
this.profile.operation,
);
}
const pending = this.#pendingCleanup;
if (pending === undefined) return undefined;
if (pending.root !== undefined) {
if (pending?.root !== undefined) {
const root = pending.root;
try {
await root.close();
pending.root = undefined;
} catch (cause: unknown) {
return new ProviderCleanupError(
const rootFailure = new ProviderCleanupError(
this.identity.id,
[root.path],
{
@@ -580,9 +658,18 @@ export class PwntoolsDecoder<
: { partialObservation: pending.observation }),
},
);
failure =
failure === undefined
? rootFailure
: analysisErrorWithCleanupFailure(
failure,
rootFailure,
this.profile.operation,
);
}
}
this.#pendingCleanup = undefined;
return undefined;
if (!this.#resources.hasPending && pending?.root === undefined)
this.#pendingCleanup = undefined;
return failure;
}
}
@@ -48,6 +48,7 @@ export class PwntoolsRecordedCrashProvider
payload,
snapshot,
rootPath,
resources,
diagnostics,
options,
runCommand,
@@ -120,6 +121,7 @@ export class PwntoolsRecordedCrashProvider
const context = await inspectPwndbgCore({
environment,
rootPath,
resources,
diagnostics,
options,
runCommand,
@@ -7,6 +7,7 @@ import {
} from "./PwntoolsRelease.js";
import { z } from "zod";
import { PWNTOOLS_LIMITS } from "./PwntoolsRelease.js";
import type { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
/** Actual limits reported by the owned bridge after lowering inherited soft limits. */
export const pwntoolsResourceLimitsSchema = z.strictObject({
@@ -42,6 +43,7 @@ export interface PwntoolsFailureEvidence {
export const readPwntoolsFailureEvidence = async (
cause: unknown,
rootPath?: string,
resources?: ArtifactResourceScope,
): Promise<PwntoolsFailureEvidence> => {
let limitReport: PwntoolsLimitReport | undefined;
let marker: PwntoolsFailureEvidence["marker"];
@@ -56,6 +58,9 @@ export const readPwntoolsFailureEvidence = async (
const reported = await readStableArtifact(
join(rootPath, "resource.failure"),
1,
undefined,
undefined,
resources,
);
const expected =
cause.snapshot.exitCode === PWNTOOLS_MEMORY_FAILURE_EXIT ? "M" : "F";
@@ -90,6 +95,9 @@ export const readPwntoolsFailureEvidence = async (
const reported = await readStableArtifact(
join(rootPath, "limits.json"),
4096,
undefined,
undefined,
resources,
);
limitReport = {
limits: pwntoolsResourceLimitsSchema.parse(