fix(providers): preserve observations and primary cleanup failures

This commit is contained in:
morluto
2026-10-09 21:01:52 +08:00
parent 88640f60fe
commit 0696bde266
18 changed files with 629 additions and 232 deletions
+9 -2
View File
@@ -221,7 +221,7 @@ class ArtifactClient implements AnalysisClient {
}),
);
} catch (cause: unknown) {
return err(translateFailure(operation, cause));
return err(translateArtifactFailure(operation, cause));
}
}
@@ -378,7 +378,8 @@ const isArtifactOperation = (
operation as (typeof ARTIFACT_ANALYSIS_OPERATIONS)[number],
);
const translateFailure = (
/** Translate one artifact boundary failure while retaining cleanup evidence. */
export const translateArtifactFailure = (
operation: ArtifactAnalysisOperation,
cause: unknown,
): AnalysisError => {
@@ -388,6 +389,12 @@ const translateFailure = (
cause.reason,
cause.details,
cause.message,
{
...(cause.cleanup === undefined ? {} : { cleanup: cause.cleanup }),
...(cause.partialObservation === undefined
? {}
: { partialObservation: cause.partialObservation }),
},
);
// Caller-selection and unsupported-target failures are already typed; keep
// their correction details instead of reducing them to an I/O failure.
+64 -1
View File
@@ -1,6 +1,15 @@
import type { Readable } from "node:stream";
import type { ArtifactCommand } from "../domain/artifactGraph.js";
import type { ZipPackageFormat } from "../domain/zipPackageFormat.js";
import type {
AnalysisCleanupObservation,
AnalysisPartialObservation,
} from "../domain/analysisErrorBase.js";
export interface ArtifactReaderFailureOptions extends ErrorOptions {
readonly cleanup?: AnalysisCleanupObservation;
readonly partialObservation?: AnalysisPartialObservation;
}
/** Archive-neutral entry metadata. Reader adapters never choose output paths. */
export interface ArtifactEntry {
@@ -33,6 +42,9 @@ export interface ArtifactReader {
/** Typed adapter failure translated at provider boundary. */
export class ArtifactReaderFailure extends Error {
readonly cleanup: AnalysisCleanupObservation | undefined;
readonly partialObservation: AnalysisPartialObservation | undefined;
constructor(
readonly reason:
| "cancelled"
@@ -43,7 +55,7 @@ export class ArtifactReaderFailure extends Error {
| "path"
| "unavailable",
message: string,
options?: ErrorOptions,
options?: ArtifactReaderFailureOptions,
readonly details?: Readonly<{
logicalPath: string;
declaredSha256: string | null;
@@ -53,5 +65,56 @@ export class ArtifactReaderFailure extends Error {
) {
super(message, options);
this.name = "ArtifactReaderFailure";
this.cleanup = options?.cleanup;
this.partialObservation = options?.partialObservation;
}
/** Preserve the primary failure while attaching cleanup and any complete observation. */
static withCleanup(
cause: unknown,
cleanup: AnalysisCleanupObservation,
partialObservation?: AnalysisPartialObservation,
): ArtifactReaderFailure {
const primary =
cause instanceof ArtifactReaderFailure
? cause
: new ArtifactReaderFailure("io", errorMessage(cause), { cause });
const mergedObservation = partialObservation ?? primary.partialObservation;
return new ArtifactReaderFailure(
primary.reason,
primary.message,
{
cause: primary,
cleanup: combineCleanup(primary.cleanup, cleanup),
...(mergedObservation === undefined
? {}
: { partialObservation: mergedObservation }),
},
primary.details,
);
}
/** Give otherwise opaque cleanup failures a concrete owned resource. */
static cleanupObservation(
cause: unknown,
resource: string,
): AnalysisCleanupObservation {
if (cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined)
return cause.cleanup;
return { reason: errorMessage(cause), resources: [resource] };
}
}
const combineCleanup = (
primary: AnalysisCleanupObservation | undefined,
cleanup: AnalysisCleanupObservation,
): AnalysisCleanupObservation =>
primary === undefined || primary === cleanup
? cleanup
: {
reason: `${primary.reason}; ${cleanup.reason}`,
resources: [...new Set([...primary.resources, ...cleanup.resources])],
};
const errorMessage = (cause: unknown): string =>
cause instanceof Error ? cause.message : String(cause);
+18 -5
View File
@@ -188,7 +188,18 @@ export class NativeDmgArtifactReader implements ArtifactReader {
throw new ArtifactReaderFailure(
"unavailable",
`DMG detach or mount-root cleanup failed for ${JSON.stringify(this.path)}: ${failureMessage(detachFailure)}`,
{ cause: detachFailure },
{
cause: detachFailure,
cleanup: {
reason: failureMessage(detachFailure),
resources: [
...this.#devices.map((device) => `DMG device ${device}`),
...(this.#mountRoot === undefined
? []
: [`DMG mount root ${this.#mountRoot}`]),
],
},
},
);
}
@@ -298,10 +309,12 @@ export class NativeDmgArtifactReader implements ArtifactReader {
cleanupFailure = cleanupCause;
}
if (cleanupFailure !== undefined)
throw new ArtifactReaderFailure(
"unavailable",
`DMG attach failed and cleanup could not detach every device: ${failureMessage(cause)}; cleanup: ${failureMessage(cleanupFailure)}`,
{ cause: new AggregateError([cause, cleanupFailure]) },
throw ArtifactReaderFailure.withCleanup(
cause,
ArtifactReaderFailure.cleanupObservation(
cleanupFailure,
`DMG mount root ${this.#mountRoot ?? this.path}`,
),
);
throw cause;
}
+17 -2
View File
@@ -208,7 +208,12 @@ export class SafeOutputTree {
/** Remove only this operation's unsealed tree and verify absence. */
async rollback(): Promise<SafeOutputCleanup> {
if (this.#published) return structuredClone(this.#cleanup);
await rm(this.#outputRoot, { recursive: true, force: true });
let removalFailure: unknown;
try {
await rm(this.#outputRoot, { recursive: true, force: true });
} catch (cause: unknown) {
removalFailure = cause;
}
const absent = await isAbsent(this.#outputRoot);
this.#cleanup = absent
? { status: "complete", residualPaths: [] }
@@ -219,7 +224,17 @@ export class SafeOutputTree {
if (!absent)
throw new ArtifactReaderFailure(
"integrity",
"Extraction output cleanup could not be verified",
`Extraction output cleanup could not be verified${removalFailure === undefined ? "" : `: ${removalFailure instanceof Error ? removalFailure.message : String(removalFailure)}`}`,
{
cause: removalFailure,
cleanup: {
reason:
removalFailure instanceof Error
? removalFailure.message
: "Extraction output root remains after rollback",
resources: [this.#outputRoot],
},
},
);
return structuredClone(this.#cleanup);
}
+48 -8
View File
@@ -1,5 +1,6 @@
import { lstat, realpath } from "node:fs/promises";
import { compareCodePoints } from "../../domain/canonicalOrdering.js";
import { canonicalDigest } from "../../domain/comparisonSemantics.js";
import { AsarArtifactReader } from "../AsarArtifactReader.js";
import {
@@ -136,10 +137,12 @@ const materializeSelection = async ({
selected.map((item) => [item.occurrence.logical_path, item]),
);
const reader = await createReader(sourcePath, input);
const output = await SafeOutputTree.create(input.outputRoot);
let output: SafeOutputTree | undefined;
let readerCloseAttempted = false;
let readerClosed = false;
const extracted: ExtractedOccurrence[] = [];
try {
output = await SafeOutputTree.create(input.outputRoot);
const materialized: SelectedOccurrence[] = [];
const registry = new ArtifactPathRegistry();
for await (const entry of reader.entries(signal)) {
@@ -171,10 +174,11 @@ const materializeSelection = async ({
});
materialized.push(selectedItem);
}
readerCloseAttempted = true;
await reader.close();
readerClosed = true;
extracted.sort((left, right) =>
left.relative_path.localeCompare(right.relative_path, "en"),
compareCodePoints(left.relative_path, right.relative_path),
);
const result = createExtractionResult(
input,
@@ -185,12 +189,48 @@ const materializeSelection = async ({
await output.commit();
return result;
} catch (cause: unknown) {
if (!readerClosed)
await reader.close().catch((cause: unknown) => {
// best-effort cleanup: reader close must not mask the extraction failure.
void cause;
const cleanupFailures: {
readonly cause: unknown;
readonly resource: string;
}[] = [];
if (readerCloseAttempted && !readerClosed)
cleanupFailures.push({
cause,
resource: `artifact reader for ${sourcePath}`,
});
await output.rollback();
if (!readerCloseAttempted) {
try {
readerCloseAttempted = true;
await reader.close();
} catch (cleanupCause: unknown) {
cleanupFailures.push({
cause: cleanupCause,
resource: `artifact reader for ${sourcePath}`,
});
}
}
if (output !== undefined) {
try {
await output.rollback();
} catch (cleanupCause: unknown) {
cleanupFailures.push({
cause: cleanupCause,
resource: input.outputRoot,
});
}
}
if (cleanupFailures.length > 0) {
const observations = cleanupFailures.map(
({ cause: cleanupCause, resource }) =>
ArtifactReaderFailure.cleanupObservation(cleanupCause, resource),
);
throw ArtifactReaderFailure.withCleanup(cause, {
reason: observations.map(({ reason }) => reason).join("; "),
resources: [
...new Set(observations.flatMap(({ resources }) => resources)),
],
});
}
throw cause;
}
};
@@ -205,7 +245,7 @@ const createExtractionResult = (
source_manifest_id: inventory.manifest.manifest_id,
selected_occurrence_ids: selected
.map(({ occurrence }) => occurrence.occurrence_id)
.sort((left, right) => left.localeCompare(right)),
.sort(compareCodePoints),
files_sha256: canonicalDigest(extracted, "Artifact"),
output_root_alias: "$OUTPUT_ROOT" as const,
};
+42 -15
View File
@@ -45,6 +45,7 @@ import {
export const scanCanonicalArtifactInventory = async (
path: string,
options: ArtifactInventoryOptions = {},
readerFactory: typeof createReader = createReader,
): Promise<ArtifactInventorySnapshot> => {
const integrity = options.integrity ?? STRICT_INTEGRITY_POLICY;
const metadata = await lstat(path);
@@ -52,33 +53,59 @@ export const scanCanonicalArtifactInventory = async (
const rootDigest = metadata.isDirectory()
? null
: await hashReadable(createReadStream(path), options.signal);
const reader = await createReader(
const reader = await readerFactory(
path,
rootFormat,
options.environment ?? {},
options.signal,
);
let outcome:
| {
readonly kind: "completed";
readonly snapshot: ArtifactInventorySnapshot;
}
| { readonly kind: "failed"; readonly cause: unknown };
try {
const { nodes, occurrences, pendingContradictions } = await scanReader(
reader,
options.signal,
integrity,
);
return await buildInventorySnapshot({
path,
metadata,
rootFormat,
rootDigest,
reader,
signal: options.signal,
nodes,
occurrences,
pendingContradictions,
});
} finally {
await reader?.close();
outcome = {
kind: "completed",
snapshot: await buildInventorySnapshot({
path,
metadata,
rootFormat,
rootDigest,
reader,
signal: options.signal,
nodes,
occurrences,
pendingContradictions,
}),
};
} catch (cause: unknown) {
outcome = { kind: "failed", cause };
}
try {
await reader?.close();
} catch (cleanupCause: unknown) {
const cleanup = ArtifactReaderFailure.cleanupObservation(
cleanupCause,
`artifact reader for ${path}`,
);
const primary = outcome.kind === "failed" ? outcome.cause : cleanupCause;
throw ArtifactReaderFailure.withCleanup(
primary,
cleanup,
outcome.kind === "completed"
? { kind: "artifact-inventory", inventory: outcome.snapshot }
: undefined,
);
}
if (outcome.kind === "failed") throw outcome.cause;
return outcome.snapshot;
};
interface SnapshotBuildInput {
+5 -1
View File
@@ -87,10 +87,14 @@ import type {
import type { FileOffsetPartialObservation } from "./native/fileOffsetPartialObservation.js";
import type { NativeCallPartialObservation } from "./native/nativeCallPartialObservation.js";
import type { ElectronActivePartialObservation } from "./javascript/electronActiveObservation.js";
import type { JavaScriptRuntimeObservation } from "./javascript/javascriptRuntimeObservation.js";
import type { ArtifactInventoryPartialObservation } from "./artifactPartialObservation.js";
/** Provider-neutral evidence collected before a typed analysis failure. */
export type AnalysisPartialObservation =
| PartialProcessCaptureObservation
| NativeCallPartialObservation
| FileOffsetPartialObservation
| ElectronActivePartialObservation;
| ElectronActivePartialObservation
| JavaScriptRuntimeObservation
| ArtifactInventoryPartialObservation;
+6 -1
View File
@@ -1,4 +1,7 @@
import { AnalysisError } from "./analysisErrorBase.js";
import {
AnalysisError,
type AnalysisErrorOptions,
} from "./analysisErrorBase.js";
/** Artifact inventory or extraction failed a typed safety boundary. */
export class ArtifactOperationError extends AnalysisError {
@@ -33,11 +36,13 @@ export class ArtifactOperationError extends AnalysisError {
}>,
/** The specific constraint that failed, such as the colliding path. */
readonly detail?: string,
options?: AnalysisErrorOptions,
) {
super(
artifactDetails === undefined
? `Artifact ${operation} failed: ${reason}`
: `Artifact ${operation} failed: ${reason} at ${artifactDetails.logicalPath} (declared_sha256=${artifactDetails.declaredSha256 ?? "unavailable"}, calculated_sha256=${artifactDetails.calculatedSha256 ?? "unavailable"}, unpacked=${String(artifactDetails.unpacked)})`,
options,
);
}
}
+7
View File
@@ -0,0 +1,7 @@
import type { ArtifactInventorySnapshot } from "./artifactInventorySnapshot.js";
/** A complete inventory retained when releasing its provider resources fails. */
export interface ArtifactInventoryPartialObservation {
readonly kind: "artifact-inventory";
readonly inventory: ArtifactInventorySnapshot;
}
@@ -4,6 +4,9 @@ import {
closeInspectorConnection,
inspectorCleanupError,
} from "./V8InspectorProvider.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { analysisErrorProjectionSchema } from "../contracts/errorSchemas.js";
import { javascriptRuntimeObservationSchema } from "../domain/javascript/javascriptRuntimeObservation.js";
it("returns promptly on cancellation while a V8 socket close is hung", async () => {
const controller = new AbortController();
@@ -32,6 +35,59 @@ it("maps a rejected close to incomplete cleanup and preserves the primary failur
expect(error.cleanupIncomplete).toBe(true);
expect(error.cleanupResources).toEqual(["browser_transport"]);
expect(error.cause).toBeInstanceOf(AggregateError);
if (!(error.cause instanceof AggregateError)) return;
expect(error.cause.errors).toEqual([primary, cleanup]);
expect(error.cause).toMatchObject({ errors: [primary, cleanup] });
});
it("projects a completed runtime observation with the cleanup failure", () => {
const observation = javascriptRuntimeObservationSchema.parse({
runtime: {
product: "Node.js",
protocol_version: "1.3",
v8_version: "12.0",
},
target: {
target_id: "target-1",
protocol_type: "node",
attached: false,
location: { kind: "file", file_path: "/fixture.js" },
runtime_kind: "node",
runtime_kind_authority: "caller-declared-unverified",
},
capture: {
observation_ms: 0,
events_observed: 0,
events_retained: 0,
events_dropped: 0,
metadata_bytes_retained: 0,
truncated: false,
truncation_reasons: [],
},
scripts: {
items: [],
observed_total: 0,
excluded: { unsupported_location: 0, invalid_protocol_value: 0 },
},
execution_contexts: [],
directly_observed: ["Inspector target attached and queried."],
unavailable_without_instrumentation: [],
unknowns: [],
limitations: [],
});
const primary = new Error("observation failed");
const cleanup = new Error("socket close failed");
const error = inspectorCleanupError(primary, cleanup, true, observation);
const cause = error.cause;
expect(cause).toBeInstanceOf(AggregateError);
expect(cause).toMatchObject({ errors: [primary, cleanup] });
const projected = projectAnalysisError(error);
expect(analysisErrorProjectionSchema.safeParse(projected).success).toBe(true);
expect(projected).toMatchObject({
code: "cleanup_incomplete",
details: {
cleanup_reason: "socket close failed",
resources: ["browser_transport"],
partial_observation: observation,
},
});
});
+26 -2
View File
@@ -13,6 +13,7 @@ import {
} from "../domain/javascript/javascriptRuntimeObservation.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { BrowserObservationError } from "../domain/browserObservationError.js";
import type { AnalysisPartialObservation } from "../domain/analysisErrorBase.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { type BrowserObservationOperation } from "../domain/browserObservationErrors.js";
import { err, ok, type Result } from "../domain/result.js";
@@ -190,7 +191,18 @@ export class V8InspectorProvider implements JavaScriptRuntimeObservationPort {
}
}
if (cleanupFailed) {
return err(inspectorCleanupError(primaryFailure, cleanupFailure, failed));
return err(
inspectorCleanupError(
primaryFailure,
cleanupFailure,
failed,
outcome?.ok === true
? outcome.value
: outcome?.ok === false
? outcome.error.partialObservation
: undefined,
),
);
}
return (
outcome ??
@@ -232,6 +244,7 @@ export const inspectorCleanupError = (
primaryFailure: unknown,
cleanupFailure: unknown,
hasPrimaryFailure: boolean,
partialObservation?: AnalysisPartialObservation,
): BrowserObservationError => {
const cause = hasPrimaryFailure
? new AggregateError(
@@ -239,10 +252,21 @@ export const inspectorCleanupError = (
"Inspector observation and cleanup both failed",
)
: cleanupFailure;
const cleanupReason =
cleanupFailure instanceof Error
? cleanupFailure.message
: String(cleanupFailure);
return new BrowserObservationError(
"observe_javascript_runtime",
"cleanup_failed",
{ cause },
{
cause,
cleanup: {
reason: cleanupReason,
resources: ["browser_transport"],
},
...(partialObservation === undefined ? {} : { partialObservation }),
},
);
};