fix(artifacts)!: retain cleanup owners through client shutdown

Keep failed reader, root descriptor, and output-tree cleanup with the caller. Drain admitted work before close, retry the same retained owners, and block new resource work while cleanup is incomplete. Preserve primary failures and complete inventory observations.

Thread ownership through JavaScript reconstruction, the CLI's one-shot scope, MCP server shutdown, verifier scripts, and test fixtures. Remove redundant ownership flags and the unused validated test wrapper.

Validate with 850 passing focused tests across 90 suites (two skipped), targeted classification and cleanup retries, static and unused-code checks, and real macOS CLI/MCP directory, ZIP, and DMG workflows. Native Windows and deep-analysis providers were not verified.

BREAKING CHANGE: Direct artifact inventory/extraction and JavaScript analysis APIs require an explicit caller-owned ArtifactResourceScope. CLI and MCP input contracts are unchanged.
This commit is contained in:
morluto
2026-10-11 04:43:02 +08:00
parent 87d5ec93d5
commit ffe0574e17
76 changed files with 1361 additions and 374 deletions
+12 -4
View File
@@ -5,14 +5,14 @@ import {
type ArtifactInventoryResult,
} from "../../domain/artifactGraph.js";
import { abortIfNeeded } from "../ArtifactHash.js";
import { scanCanonicalArtifactInventory } from "./scanCanonical.js";
import { scanCanonicalArtifactInventoryInScope } from "./scanCanonical.js";
import type { ArtifactInventoryOptions } from "./types.js";
import type { ArtifactInventorySnapshot } from "../../domain/artifactInventorySnapshot.js";
/** Inventory one local artifact and return every graph collection inline. */
export const inventoryArtifact = async (
inputPath: string,
options: ArtifactInventoryOptions = {},
options: ArtifactInventoryOptions,
): Promise<ArtifactInventoryResult> => {
const snapshot = await scanArtifactInventory(inputPath, options);
return artifactInventoryResultSchema.parse(snapshot);
@@ -21,9 +21,17 @@ export const inventoryArtifact = async (
/** Scan an artifact once and retain the complete immutable graph for projection. */
export const scanArtifactInventory = async (
inputPath: string,
options: ArtifactInventoryOptions = {},
options: ArtifactInventoryOptions,
): Promise<ArtifactInventorySnapshot> =>
options.resourceScope.run(() =>
scanArtifactInventoryInScope(inputPath, options),
);
export const scanArtifactInventoryInScope = async (
inputPath: string,
options: ArtifactInventoryOptions,
): Promise<ArtifactInventorySnapshot> => {
abortIfNeeded(options.signal);
const path = await realpath(inputPath);
return scanCanonicalArtifactInventory(path, options);
return scanCanonicalArtifactInventoryInScope(path, options);
};
@@ -4,7 +4,7 @@ import { join } from "node:path";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { describe, expect, it } from "vitest";
import { inventoryArtifact } from "./ArtifactInventory.js";
import { inventoryArtifact } from "../../../tests/fixtures/artifactInventory.js";
import { compareArtifacts } from "../../domain/artifactComparison.js";
import { projectAppleApplication } from "../../domain/apple/appleApplication.js";
import { createEvidence } from "../../domain/evidence.js";
+64 -22
View File
@@ -15,8 +15,10 @@ import {
zipPackageFormatForPath,
} from "../../domain/zipPackageFormat.js";
import { ArtifactReaderFailure } from "../ArtifactReader.js";
import { type ArtifactResourceOwner } from "../ArtifactResourceScope.js";
import type { HashResult } from "../ArtifactHash.js";
import { hashStableRootArtifactHandle } from "./hashStableRootArtifact.js";
import type { ArtifactInventoryOptions } from "./types.js";
interface RootClassification {
readonly format: ArtifactOccurrence["artifact_format"];
@@ -32,19 +34,34 @@ export const classifyAndHashRoot = async (
path: string,
directory: boolean,
expectedMetadata: Stats,
signal?: AbortSignal,
options: Pick<ArtifactInventoryOptions, "resourceScope" | "signal">,
): Promise<RootClassification> => {
const result = await classifyAndHashRootForInventory(
path,
directory,
expectedMetadata,
signal,
);
try {
return options.resourceScope.run(async () => {
const result = await classifyAndHashRootForInventory(
path,
directory,
expectedMetadata,
options,
);
const rootSource = result.rootSource;
if (rootSource !== undefined) {
const owner: ArtifactResourceOwner = {
kind: "file-handle",
handle: rootSource.handle,
resource: `root artifact descriptor for ${path}`,
};
const cleanupAttempt = await options.resourceScope.release(owner);
if (cleanupAttempt.kind === "failed")
throw ArtifactReaderFailure.withCleanup(
cleanupAttempt.cause,
ArtifactReaderFailure.cleanupObservation(
cleanupAttempt.cause,
owner.resource,
),
);
}
return { format: result.format, digest: result.digest };
} finally {
await result.rootSource?.handle.close();
}
});
};
/** Classify a root and retain its admitted ZIP descriptor for child inventory. */
@@ -52,12 +69,22 @@ export const classifyAndHashRootForInventory = async (
path: string,
directory: boolean,
expectedMetadata: Stats,
signal?: AbortSignal,
options: Pick<ArtifactInventoryOptions, "resourceScope" | "signal">,
): Promise<RootInventoryClassification> => {
if (directory)
return { format: "directory", digest: null, rootSource: undefined };
const handle = await openRootFile(path, signal);
let transferHandle = false;
const handle = await openRootFile(path, options.signal);
const owner: ArtifactResourceOwner = {
kind: "file-handle",
handle,
resource: `root artifact descriptor for ${path}`,
};
let outcome:
| {
readonly kind: "completed";
readonly value: RootInventoryClassification;
}
| { readonly kind: "failed"; readonly cause: unknown };
try {
const initial = await handle.stat();
if (!sameRegularFileState(expectedMetadata, initial))
@@ -70,18 +97,33 @@ export const classifyAndHashRootForInventory = async (
path,
handle,
initial,
signal,
options.signal,
);
const retainSource = isZipFormat(format) || format === "mach-o-universal";
if (retainSource) transferHandle = true;
return {
format,
digest,
rootSource: retainSource ? { handle, initial } : undefined,
outcome = {
kind: "completed",
value: {
format,
digest,
rootSource: retainSource ? { handle, initial } : undefined,
},
};
} finally {
if (!transferHandle) await handle.close();
} catch (cause: unknown) {
outcome = { kind: "failed", cause };
}
if (outcome.kind === "failed" || outcome.value.rootSource === undefined) {
const cleanupAttempt = await options.resourceScope.release(owner);
if (cleanupAttempt.kind === "failed")
throw ArtifactReaderFailure.withCleanup(
outcome.kind === "failed" ? outcome.cause : cleanupAttempt.cause,
ArtifactReaderFailure.cleanupObservation(
cleanupAttempt.cause,
owner.resource,
),
);
}
if (outcome.kind === "failed") throw outcome.cause;
return outcome.value;
};
const isZipFormat = (format: ArtifactOccurrence["artifact_format"]): boolean =>
+71 -45
View File
@@ -11,6 +11,7 @@ import {
ArtifactReaderFailure,
type ArtifactReader,
} from "../ArtifactReader.js";
import type { ArtifactResourceOwner } from "../ArtifactResourceScope.js";
import {
artifactInventoryResultSchema,
type ArtifactInventoryResult,
@@ -50,7 +51,16 @@ import {
export const scanCanonicalArtifactInventory = async (
path: string,
options: ArtifactInventoryOptions = {},
options: ArtifactInventoryOptions,
readerFactory: typeof createReader = createReader,
): Promise<ArtifactInventorySnapshot> =>
options.resourceScope.run(() =>
scanCanonicalArtifactInventoryInScope(path, options, readerFactory),
);
export const scanCanonicalArtifactInventoryInScope = async (
path: string,
options: ArtifactInventoryOptions,
readerFactory: typeof createReader = createReader,
): Promise<ArtifactInventorySnapshot> => {
const integrity = options.integrity ?? STRICT_INTEGRITY_POLICY;
@@ -63,7 +73,7 @@ export const scanCanonicalArtifactInventory = async (
path,
metadata.isDirectory(),
metadata,
options.signal,
options,
);
let reader: ArtifactReader | undefined;
let readerCreationFailure: { readonly cause: unknown } | undefined;
@@ -78,12 +88,7 @@ export const scanCanonicalArtifactInventory = async (
readerCreationFailure = { cause };
}
const ownedReaders: ArtifactReader[] = reader === undefined ? [] : [reader];
let outcome:
| {
readonly kind: "completed";
readonly snapshot: ArtifactInventorySnapshot;
}
| { readonly kind: "failed"; readonly cause: unknown };
let outcome: InventoryScanOutcome;
try {
if (readerCreationFailure !== undefined) throw readerCreationFailure.cause;
if (reader instanceof AsarArtifactReader)
@@ -113,48 +118,69 @@ export const scanCanonicalArtifactInventory = async (
} catch (cause: unknown) {
outcome = { kind: "failed", cause };
}
let cleanupFailure: ArtifactReaderFailure | undefined;
for (const owned of ownedReaders.reverse()) {
try {
await owned.close();
} catch (cleanupCause: unknown) {
const cleanup = ArtifactReaderFailure.cleanupObservation(
cleanupCause,
`artifact reader for ${path}`,
);
cleanupFailure = ArtifactReaderFailure.withCleanup(
cleanupFailure ??
(outcome.kind === "failed" ? outcome.cause : cleanupCause),
cleanup,
outcome.kind === "completed"
? { kind: "artifact-inventory", inventory: outcome.snapshot }
: undefined,
);
}
}
if (rootSource !== undefined) {
try {
await rootSource.handle.close();
} catch (cleanupCause: unknown) {
const cleanup = ArtifactReaderFailure.cleanupObservation(
cleanupCause,
`root artifact descriptor for ${path}`,
);
cleanupFailure = ArtifactReaderFailure.withCleanup(
cleanupFailure ??
(outcome.kind === "failed" ? outcome.cause : cleanupCause),
cleanup,
outcome.kind === "completed"
? { kind: "artifact-inventory", inventory: outcome.snapshot }
: undefined,
);
}
}
const cleanupFailure = await cleanupInventoryOwners({
path,
options,
rootSource,
ownedReaders,
outcome,
});
if (cleanupFailure !== undefined) throw cleanupFailure;
if (outcome.kind === "failed") throw outcome.cause;
return outcome.snapshot;
};
type InventoryScanOutcome =
| {
readonly kind: "completed";
readonly snapshot: ArtifactInventorySnapshot;
}
| { readonly kind: "failed"; readonly cause: unknown };
const cleanupInventoryOwners = async ({
path,
options,
rootSource,
ownedReaders,
outcome,
}: {
readonly path: string;
readonly options: ArtifactInventoryOptions;
readonly rootSource: StableRegularFileDescriptor | undefined;
readonly ownedReaders: readonly ArtifactReader[];
readonly outcome: InventoryScanOutcome;
}): Promise<ArtifactReaderFailure | undefined> => {
let cleanupFailure: ArtifactReaderFailure | undefined;
const owners: ArtifactResourceOwner[] = [...ownedReaders]
.reverse()
.map((reader) => ({
kind: "reader" as const,
reader,
resource: `artifact reader for ${path}`,
}));
if (rootSource !== undefined)
owners.push({
kind: "file-handle",
handle: rootSource.handle,
resource: `root artifact descriptor for ${path}`,
});
for (const owner of owners) {
const attempt = await options.resourceScope.release(owner);
if (attempt.kind === "released") continue;
const primary =
cleanupFailure ??
(outcome.kind === "failed" ? outcome.cause : attempt.cause);
cleanupFailure = ArtifactReaderFailure.withCleanup(
primary,
ArtifactReaderFailure.cleanupObservation(attempt.cause, owner.resource),
outcome.kind === "completed"
? { kind: "artifact-inventory", inventory: outcome.snapshot }
: undefined,
);
}
return cleanupFailure;
};
interface SnapshotBuildInput {
readonly path: string;
readonly metadata: Stats;
+3
View File
@@ -1,3 +1,5 @@
import type { ArtifactResourceScope } from "../ArtifactResourceScope.js";
/** Resolved integrity behavior admitted to the artifact scanner. */
export type ArtifactIntegrityPolicy =
| { readonly mode: "fail" }
@@ -9,6 +11,7 @@ export const STRICT_INTEGRITY_POLICY: ArtifactIntegrityPolicy = {
/** Options shared by artifact inventory scans. */
export interface ArtifactInventoryOptions {
readonly resourceScope: ArtifactResourceScope;
readonly signal?: AbortSignal | undefined;
readonly integrity?: ArtifactIntegrityPolicy | undefined;
readonly environment?: Readonly<NodeJS.ProcessEnv> | undefined;