fix(firmware): recover after workspace removal failures (#1616)

This commit is contained in:
Ysopwnable
2026-10-11 03:16:34 +08:00
committed by GitHub
parent a761981897
commit 043fd2579d
7 changed files with 356 additions and 183 deletions
+2
View File
@@ -99,6 +99,8 @@ const chunk = z.strictObject({
export interface FirmwarePartialObservation {
readonly kind: "firmware";
readonly result: JsonValue;
/** Completed producer data, artifact identity and analysis metadata. */
readonly provenance?: JsonValue;
}
/** Portable results retain reported boundaries, unknowns and extraction lineage. */
-98
View File
@@ -1,98 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { err, ok } from "../domain/result.js";
import { firmwareRequestSchema } from "../domain/firmware/firmwareAnalysis.js";
import { finishFirmwareWorkspace } from "./FirmwareProvider.js";
const request = firmwareRequestSchema.parse({
operation: "extract_firmware",
input: {
path: "/tmp/firmware.bin",
output_directory: "/tmp/extracted",
},
});
const execution = ok({
result: { files: ["kept"] },
rawResult: null,
provider: { id: "unblob", name: "unblob", version: "1" },
limitations: [],
locations: [],
subject: null,
});
describe("firmware workspace cleanup", () => {
it("returns the completed extraction beside a cleanup failure and does not delete the leaked root", async () => {
const close = vi.fn(async () => {
throw new Error("cleanup failed");
});
const finished = await finishFirmwareWorkspace(
{ path: "/tmp/runtime", close },
execution,
"unblob",
request,
);
expect(close).toHaveBeenCalledOnce();
if (finished.ok || !(finished.error instanceof ProviderAdapterError))
throw new Error("Expected cleanup failure");
expect(finished.error.cleanupResources).toEqual([
"/tmp/runtime",
"/tmp/extracted",
]);
expect(finished.error.partialObservation).toEqual({
kind: "firmware",
result: { files: ["kept"] },
});
expect(finished.error.diagnostics).toEqual({ reason: "cleanup failed" });
expect(projectAnalysisError(finished.error).details).toMatchObject({
partial_observation: {
kind: "firmware",
result: { files: ["kept"] },
},
});
});
it("does not replay a cleanup failure for a later workspace", async () => {
const failed = await finishFirmwareWorkspace(
{
path: "/tmp/runtime",
close: async () => {
throw new Error("cleanup failed");
},
},
execution,
"unblob",
request,
);
expect(failed.ok).toBe(false);
const next = await finishFirmwareWorkspace(
{ path: "/tmp/next", close: async () => undefined },
execution,
"unblob",
request,
);
expect(next).toBe(execution);
});
it("leaves an uncertain workspace recorded and does not remove it", async () => {
const close = vi.fn(async () => undefined);
const cleanup = new ProviderCleanupError(
"unblob",
["/tmp/runtime"],
{ reason: "ownership uncertain" },
{ operation: "extract_firmware" },
);
const outcome = err(cleanup);
const finished = await finishFirmwareWorkspace(
{ path: "/tmp/runtime", close },
outcome,
"unblob",
request,
);
expect(close).not.toHaveBeenCalled();
expect(finished).toBe(outcome);
});
});
+144 -72
View File
@@ -3,13 +3,16 @@ import { z } from "zod";
import type { FirmwareAnalysisPort } from "../application/firmware/FirmwareAnalysisPort.js";
import {
createAnalysisExecution,
type AnalysisExecution,
type ExecutionOptions,
} from "../application/AnalysisProvider.js";
import {
firmwareResultSchemas,
type FirmwareRequest,
type FirmwarePartialObservation,
} from "../domain/firmware/firmwareAnalysis.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
import {
AnalysisCancelledError,
AnalysisInputError,
@@ -18,6 +21,7 @@ import {
} from "../domain/analysisErrorCore.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { err, ok } from "../domain/result.js";
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
import type { ProviderProcessSupervisor } from "../process/ProviderProcess.js";
@@ -42,6 +46,37 @@ import {
} from "./FirmwareReports.js";
type Outcome = Awaited<ReturnType<FirmwareAnalysisPort["execute"]>>;
interface PendingFirmwareCleanup {
supervisor?: ProviderProcessSupervisor;
readonly root: PrivateRuntimeRoot;
readonly engine: string;
readonly operation: string;
}
interface FirmwareCleanupAttempt {
readonly failure: ProviderCleanupError | undefined;
readonly processUnverified: boolean;
}
const combineCleanupFailures = (
failures: readonly ProviderCleanupError[],
): ProviderCleanupError | undefined => {
if (failures.length < 2) return failures[0];
return new ProviderCleanupError(
"firmware",
failures.flatMap((failure) => [...failure.cleanupResources]),
{
reason: "Multiple owned firmware resources could not be cleaned",
failures: failures.map((failure) => ({
engine: failure.providerId,
operation: failure.operation,
resources: [...failure.cleanupResources],
reason: failure.diagnostics?.reason ?? failure.message,
})),
},
{ operation: "close_firmware", cause: new AggregateError(failures) },
);
};
const waitForPredecessor = (
predecessor: Promise<void>,
operation: string,
@@ -67,14 +102,7 @@ const limitations = [
export class FirmwareProvider implements FirmwareAnalysisPort {
#tail: Promise<void> = Promise.resolve();
#closed = false;
#pendingCleanup:
| {
supervisor?: ProviderProcessSupervisor;
root: PrivateRuntimeRoot;
engine: string;
operation: string;
}
| undefined;
readonly #pendingCleanup = new Map<string, PendingFirmwareCleanup>();
constructor(
readonly environment: Readonly<
Record<string, string | undefined>
@@ -107,53 +135,71 @@ export class FirmwareProvider implements FirmwareAnalysisPort {
try {
if (this.#closed)
return err(new AnalysisCancelledError(request.operation));
try {
await this.#retryCleanup();
} catch (cause: unknown) {
return err(
cause instanceof AnalysisError
? cause
: new ProviderCleanupError("firmware", [], {
reason: cause instanceof Error ? cause.message : String(cause),
}),
);
}
const cleanup = await this.#retryCleanup();
if (cleanup.processUnverified && cleanup.failure !== undefined)
return err(cleanup.failure);
return await this.#execute(request, options);
} finally {
release();
}
}
/** Retry identity-bound cleanup before relinquishing private workspaces. */
/** Retry every retained owner, reporting failures without discarding other roots. */
async close(): Promise<void> {
this.#closed = true;
await this.#tail;
await this.#retryCleanup();
const cleanup = await this.#retryCleanup();
if (cleanup.failure !== undefined) throw cleanup.failure;
}
async #retryCleanup(): Promise<void> {
const pending = this.#pendingCleanup;
if (pending === undefined) return;
const stopped = await pending.supervisor?.stop();
if (stopped?.status === "incomplete")
throw new ProviderCleanupError(
pending.engine,
[pending.root.path],
{ reason: stopped.reason },
{ operation: pending.operation },
);
delete pending.supervisor;
try {
await pending.root.close();
} catch (cause: unknown) {
throw new ProviderCleanupError(
pending.engine,
[pending.root.path],
{ reason: cause instanceof Error ? cause.message : String(cause) },
{ operation: pending.operation, cause },
);
async #retryCleanup(): Promise<FirmwareCleanupAttempt> {
const failures: ProviderCleanupError[] = [];
let processUnverified = false;
for (const [path, pending] of this.#pendingCleanup) {
try {
const stopped = await pending.supervisor?.stop();
if (stopped?.status === "incomplete") {
processUnverified = true;
failures.push(
new ProviderCleanupError(
pending.engine,
[path],
{ reason: stopped.reason },
{ operation: pending.operation },
),
);
continue;
}
delete pending.supervisor;
} catch (cause: unknown) {
processUnverified = true;
failures.push(
new ProviderCleanupError(
pending.engine,
[path],
{ reason: cause instanceof Error ? cause.message : String(cause) },
{ operation: pending.operation, cause },
),
);
continue;
}
try {
await pending.root.close();
this.#pendingCleanup.delete(path);
} catch (cause: unknown) {
// A verified stopped process cannot use this root. Keep ownership for
// later removal without blocking a new operation's disjoint workspace.
failures.push(
new ProviderCleanupError(
pending.engine,
[path],
{ reason: cause instanceof Error ? cause.message : String(cause) },
{ operation: pending.operation, cause },
),
);
}
}
this.#pendingCleanup = undefined;
return { failure: combineCleanupFailures(failures), processUnverified };
}
async #execute(
@@ -192,12 +238,12 @@ export class FirmwareProvider implements FirmwareAnalysisPort {
environment: this.environment,
signal,
retainCleanup: (supervisor) => {
this.#pendingCleanup = {
this.#pendingCleanup.set(ownedRoot.path, {
supervisor,
root: ownedRoot,
engine: engineName,
operation: request.operation,
};
});
},
...(this.launcher === undefined ? {} : { launcher: this.launcher }),
...(outputBudget === undefined
@@ -386,12 +432,17 @@ export class FirmwareProvider implements FirmwareAnalysisPort {
engineName,
request,
);
if (!finished.ok && finished.error.cleanupIncomplete && root !== undefined)
this.#pendingCleanup ??= {
if (
!finished.ok &&
finished.error.cleanupIncomplete &&
root !== undefined &&
!this.#pendingCleanup.has(root.path)
)
this.#pendingCleanup.set(root.path, {
root,
engine: engineName,
operation: request.operation,
};
});
return finished;
}
}
@@ -429,32 +480,53 @@ export const finishFirmwareWorkspace = async (
try {
await root?.close();
} catch (cause: unknown) {
const cleanup = new ProviderCleanupError(
engineName,
[
root?.path ?? "unknown",
...(outcome.ok && request.operation === "extract_firmware"
? [request.input.output_directory]
: []),
],
{ reason: cause instanceof Error ? cause.message : String(cause) },
{
cause,
operation: request.operation,
...(outcome.ok
? {
partialObservation: completedFirmwareObservation(outcome.value),
}
: outcome.error.partialObservation === undefined
? {}
: { partialObservation: outcome.error.partialObservation }),
},
);
return err(
new ProviderCleanupError(
engineName,
[
root?.path ?? "unknown",
...(outcome.ok && request.operation === "extract_firmware"
? [request.input.output_directory]
: []),
],
{ reason: cause instanceof Error ? cause.message : String(cause) },
{
cause,
operation: request.operation,
...(outcome.ok
? {
partialObservation: {
kind: "firmware",
result: outcome.value.result,
},
}
: outcome.error.partialObservation === undefined
? {}
: { partialObservation: outcome.error.partialObservation }),
},
),
outcome.ok
? cleanup
: analysisErrorWithCleanupFailure(
outcome.error,
cleanup,
request.operation,
),
);
}
return outcome;
};
const completedFirmwareObservation = (
execution: AnalysisExecution,
): FirmwarePartialObservation => ({
kind: "firmware",
result: execution.result,
provenance: jsonValueSchema.parse({
raw_result: execution.rawResult,
provider: execution.provider,
subject: execution.subject,
locations: execution.locations,
limitations: execution.limitations,
...(execution.analysisProfile === undefined
? {}
: { analysis_profile: execution.analysisProfile }),
}),
});