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
+131 -75
View File
@@ -26,9 +26,13 @@ import {
type IntegrityContradiction,
} from "../../domain/artifactGraph.js";
import { AnalysisUnsupportedTargetError } from "../../domain/analysisErrorCore.js";
import {
type ArtifactResourceOwner,
type ArtifactResourceScope,
} from "../ArtifactResourceScope.js";
import type { BinaryTarget } from "../../domain/binaryTargetTypes.js";
import type { ArtifactInventorySnapshot } from "../../domain/artifactInventorySnapshot.js";
import { scanArtifactInventory } from "../inventory/ArtifactInventory.js";
import { scanArtifactInventoryInScope } from "../inventory/ArtifactInventory.js";
import type { ArtifactIntegrityPolicyName } from "../../domain/artifactIntegrityPolicy.js";
/** Local extraction input with the output root chosen by the adapter. */
@@ -38,23 +42,36 @@ export interface ArtifactExtractionInput {
readonly outputRoot: string;
readonly environment: Readonly<NodeJS.ProcessEnv>;
readonly integrityPolicy: ArtifactIntegrityPolicyName;
readonly resourceScope: ArtifactResourceScope;
}
/** Extract every regular inventory occurrence into an exclusively owned absent root. */
export const extractArtifact = async (
input: ArtifactExtractionInput,
signal?: AbortSignal,
): Promise<ArtifactExtractionResult> =>
input.resourceScope.run(() => extractArtifactInScope(input, signal));
const extractArtifactInScope = async (
input: ArtifactExtractionInput,
signal?: AbortSignal,
): Promise<ArtifactExtractionResult> => {
// Cancellation wins over every later refusal, including unsupported formats.
abortIfNeeded(signal);
const sourcePath = await realpath(input.inputPath);
await requireExtractableFormat(sourcePath, input);
const snapshot = await scanArtifactInventory(sourcePath, {
const snapshot = await scanArtifactInventoryInScope(sourcePath, {
resourceScope: input.resourceScope,
signal,
environment: input.environment,
integrity: { mode: input.integrityPolicy },
});
return materializeArtifactInventory(input, sourcePath, snapshot, signal);
return materializeArtifactInventoryInScope(
input,
sourcePath,
snapshot,
signal,
);
};
/** Materialize a scanned inventory, verifying every current occurrence against it. */
@@ -63,6 +80,17 @@ export const materializeArtifactInventory = async (
sourcePath: string,
snapshot: ArtifactInventorySnapshot,
signal?: AbortSignal,
): Promise<ArtifactExtractionResult> => {
return input.resourceScope.run(() =>
materializeArtifactInventoryInScope(input, sourcePath, snapshot, signal),
);
};
const materializeArtifactInventoryInScope = async (
input: ArtifactExtractionInput,
sourcePath: string,
snapshot: ArtifactInventorySnapshot,
signal?: AbortSignal,
): Promise<ArtifactExtractionResult> => {
abortIfNeeded(signal);
const selectedOccurrences = snapshot.occurrences.filter(
@@ -185,53 +213,27 @@ const materializeSelection = async ({
selected.map((item) => [item.occurrence.logical_path, item]),
);
const reader = await createReader(sourcePath, input);
const readerOwner: ArtifactResourceOwner = {
kind: "reader" as const,
reader,
resource: `artifact reader for ${sourcePath}`,
};
let localReaderOwner: ArtifactResourceOwner | undefined = readerOwner;
let output: SafeOutputTree | undefined;
let readerCloseAttempted = false;
let readerClosed = false;
const extracted: ExtractedOccurrence[] = [];
try {
output = await SafeOutputTree.create(input.outputRoot);
const registry = new ArtifactPathRegistry();
for await (const entry of reader.entries(signal)) {
const path = normalizeArtifactPath(entry.path);
registry.add(path, entry.kind);
const selectedItem = byPath.get(path);
if (selectedItem === undefined) {
if (entry.kind === "file" || entry.kind === "slice")
throw new ArtifactReaderFailure(
"integrity",
`Regular artifact entry is missing from inventory: ${path}`,
);
continue;
}
preflight(entry);
const stream = await reader.open(entry, signal);
const written = await output.write(
path,
stream,
{
sha256: selectedItem.node.sha256,
bytes: selectedItem.node.size,
},
signal,
await writeSelectedEntries({ reader, output, byPath, extracted, signal });
localReaderOwner = undefined;
const closeAttempt = await input.resourceScope.release(readerOwner);
if (closeAttempt.kind === "failed")
throw ArtifactReaderFailure.withCleanup(
closeAttempt.cause,
ArtifactReaderFailure.cleanupObservation(
closeAttempt.cause,
readerOwner.resource,
),
);
extracted.push({
artifact_id: selectedItem.node.artifact_id,
relative_path: written.relativePath,
sha256: written.sha256,
bytes_written: written.bytesWritten,
created: true,
});
byPath.delete(path);
}
if (byPath.size > 0)
throw new ArtifactReaderFailure(
"integrity",
`Inventoried regular artifact entries were not materialized: ${[...byPath.keys()].sort(compareUnicodeCodePoints).join(", ")}`,
);
readerCloseAttempted = true;
await reader.close();
readerClosed = true;
extracted.sort((left, right) =>
compareUnicodeCodePoints(left.relative_path, right.relative_path),
);
@@ -244,36 +246,12 @@ const materializeSelection = async ({
await output.commit();
return result;
} catch (cause: unknown) {
const cleanupFailures: {
readonly cause: unknown;
readonly resource: string;
}[] = [];
if (readerCloseAttempted && !readerClosed)
cleanupFailures.push({
cause,
resource: `artifact reader for ${sourcePath}`,
});
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,
});
}
}
const cleanupFailures = await releaseExtractionOwners(
input.resourceScope,
localReaderOwner,
output,
input.outputRoot,
);
if (cleanupFailures.length > 0) {
const observations = cleanupFailures.map(
({ cause: cleanupCause, resource }) =>
@@ -290,6 +268,84 @@ const materializeSelection = async ({
}
};
const writeSelectedEntries = async ({
reader,
output,
byPath,
extracted,
signal,
}: {
readonly reader: ArtifactReader;
readonly output: SafeOutputTree;
readonly byPath: Map<string, SelectedOccurrence>;
readonly extracted: ExtractedOccurrence[];
readonly signal: AbortSignal | undefined;
}): Promise<void> => {
const registry = new ArtifactPathRegistry();
for await (const entry of reader.entries(signal)) {
const path = normalizeArtifactPath(entry.path);
registry.add(path, entry.kind);
const selectedItem = byPath.get(path);
if (selectedItem === undefined) {
if (entry.kind === "file" || entry.kind === "slice")
throw new ArtifactReaderFailure(
"integrity",
`Regular artifact entry is missing from inventory: ${path}`,
);
continue;
}
preflight(entry);
const stream = await reader.open(entry, signal);
const written = await output.write(
path,
stream,
{
sha256: selectedItem.node.sha256,
bytes: selectedItem.node.size,
},
signal,
);
extracted.push({
artifact_id: selectedItem.node.artifact_id,
relative_path: written.relativePath,
sha256: written.sha256,
bytes_written: written.bytesWritten,
created: true,
});
byPath.delete(path);
}
if (byPath.size > 0)
throw new ArtifactReaderFailure(
"integrity",
`Inventoried regular artifact entries were not materialized: ${[...byPath.keys()].sort(compareUnicodeCodePoints).join(", ")}`,
);
};
const releaseExtractionOwners = async (
resourceScope: ArtifactResourceScope,
readerOwner: ArtifactResourceOwner | undefined,
output: SafeOutputTree | undefined,
outputRoot: string,
): Promise<{ readonly cause: unknown; readonly resource: string }[]> => {
const failures: { readonly cause: unknown; readonly resource: string }[] = [];
if (readerOwner !== undefined) {
const attempt = await resourceScope.release(readerOwner);
if (attempt.kind === "failed")
failures.push({ cause: attempt.cause, resource: readerOwner.resource });
}
if (output !== undefined) {
const owner: ArtifactResourceOwner = {
kind: "output-tree",
tree: output,
resource: outputRoot,
};
const attempt = await resourceScope.release(owner);
if (attempt.kind === "failed")
failures.push({ cause: attempt.cause, resource: owner.resource });
}
return failures;
};
const createExtractionResult = (
input: ArtifactExtractionInput,
inventory: ExtractionInventory,