Files
rea/tests/composition/directAnalysisCleanup.test.ts
morluto bd353e7e5c fix(errors)!: producers declare retry class, refusal recovery and real error codes (#15372)
* fix(errors)!: derive retryable from the producer's declared retry class

`retryable` means the unchanged request may succeed, but it was computed
downstream as an OR of a code table and five class rules. Every error
classification now declares a retry class (same_call, change_first, never,
unknown_outcome); `retryable` is `same_call` after one incomplete-cleanup
check, and the RETRYABLE_CODES table is deleted.

Producer corrections:
- update_unknown revision conflicts are change_first and report
  details.current_revision; duplicate record_unknown reports
  details.existing_unknown_id.
- close_gdb_session's explicit-disposition refusal is change_first.
- Per-call artifact reader limits are change_first (never when the limit
  cannot rise).
- An exited or unreachable Hopper bridge, and a Hopper start that another
  REA session owns, are change_first.
- File-descriptor exhaustion (EMFILE/ENFILE) outside process launch is
  occupied host capacity (same_call) for private workspaces, model and GPU
  readers and JavaScript application reads.
- apktool JVM native-thread exhaustion follows the shared capacity default.

BREAKING CHANGE: these refusals now report `retryable: false` (descriptor
pressure now reports `retryable: true` as `resource_constraint`). Callers
that repeated them unchanged should follow the remediation first: re-read
the unknown and retry with details.current_revision, dispose GDB inferiors,
raise the reported reader limit, or restart the Hopper provider.

* fix(errors): require producers to name recovery for conforming refusals

A refusal whose arguments match the input schema was presented as a schema
error whenever its producer left out remediation, and many producers did.
AnalysisInputError's options are now a union: a conforming refusal must
supply both its outcome (userMessage) and next step (remediationAction),
so the compiler lists every producer; only contract violations may fall
back to the schema guidance.

Producers fixed: unknown Frida session and script, decompile_all
output-directory state, the duplicate unknown build computer factory
(collapsed), stale Cutter sessions, Mach-O architecture selection, output
roots that already exist, selected files the host refuses, Ghidra lookups
the bridge could not resolve, YARA path refusals, unresolved native symbol
names, apt key files and withheld sign-in state. A missing selected APK is
now target_unavailable like every other selected-file reader.

The capability fallback "Choose another analysis or target" is deleted; a
capability refusal without its own recovery names details.reason and
binary_session.

Refs #15312

* fix(errors): classify caller selections and target bytes by their real failure

Several refusals reported a code that reads as corruption or a crash:
- a missing unknown_id and a missing Evidence reference now report
  invalid_request instead of execution_failure and
  evidence_integrity_mismatch;
- close_binary with snapshot_path in a resource-only session reports
  invalid_request instead of evidence_integrity_mismatch;
- ADB push onto an existing device path and pulls into an occupied output
  directory are conforming invalid_request refusals naming overwrite or
  output_directory, not unreadable_output;
- damaged APK ZIP, signing-block, signer and central-directory structures
  are malformed targets, not invalid input;
- NuGet and VSIX bytes without a ZIP signature are unrecognized, not
  malformed;
- a historical source graph file whose entries contradict its root
  commitment is an integrity failure, not invalid input;
- a CDP protocol failure states what happened instead of the unclassified
  fallback message.

Refs #15319

* feat(errors): expose the producer's retry class as retry_class

Every error projection now carries retry_class (same_call, change_first, never or unknown_outcome) beside retryable, which stays true exactly for same_call. The field is additive: the error schema accepts errors retained by earlier releases without it.

Refs #15323

* fix(errors): address review of the folded error-contract PRs

Keep a provider's own capability message as its remediation; the binary_session fallback applies only to a bare declared reason. Delete the unused conformingInputRefusal helper. Compose both retry fields for a refused publication whose cleanup is incomplete. Report descriptor exhaustion from a JavaScript directory opendir as occupied capacity. Let an exited Hopper startup attempt without a setup failure code retry unchanged. Declare retry for the Ghidra superseded checkpoint and unknown IDA readiness. Redact ambiguous selector candidates. Give a Ghidra document miss its own recovery. Drop an unchanged-files claim the journal repair cannot make. Name each withheld sign-in refusal's step. Hash the source graph commitment before the cancellation yield. Keep the browser protocol_error message neutral. Add tests for mutation-audit survivors C3, C5, P2, P4, P8, H1, H4 and H5.

* fix(errors): keep a missing Evidence reference an integrity failure and state only the observed commitment mismatch

* test(desktop): assert the unknown build computer refusal's remediation, not its message

The refusal now carries its next step in remediation.action instead of the message, so the closed-computer checks assert the exact code, message and remediation facts.

* fix(errors): keep producer retry choices apart from cleanup and fixed ceilings

A capture's retryable flag no longer folds in pending cleanup, so the projection applies the cleanup rule once and a transient capture with pending cleanup reports change_first instead of never. A release-fixed artifact allowance reports never, and a stale admitted session identity reports change_first (reopen, then retry); both have catalogue rows. The bare capability-unavailable remediation names binary_session only for a binary-analysis session, so standalone bridges such as Cutter are pointed at their own reason.

* test(vsix): expect a non-ZIP selection to be refused as unrecognized

This PR reports bytes without a ZIP signature as another format (unrecognized), not a damaged package; the exact-reason assertion added on main still expected malformed.

* test(delivery): expect the capacity refusal's retry class in delivered failure facts

The exact failure facts asserted on main predate the projection's retry_class; occupied capacity reports same_call.

* fix(errors): mark a sent Hopper cancellation unknown and missing Evidence recoverable

A cancellation Hopper already received may still apply, so its retry class is unknown_outcome instead of same_call; an unsent cancellation keeps same_call. A missing EvidenceReferenceError is change_first, since importing the referenced records lets the same request succeed; other reference failures stay never. Both have catalogue rows.

* fix(hopper): ask for changed launch arguments before retrying an unencodable launch

A launcher path or argument that cannot be encoded as an AppleScript literal meets the same pre-launch guard on every attempt, so the start refusal is change_first and its retry_action is unknown; a start failure without a declared reason stays same_call.

* fix(errors): keep a one-shot cleanup failure's retry class with its cleanup state

A one-shot reply that reports cleanup_incomplete spread the primary or cleanup projection and overrode only retryable, so a timed-out read whose close also failed carried retry_class same_call. The reply now reads its retry class from the typed composed failure, and never offers the same call before cleanup settles.

* test(evtx): expect an unreadable selected log to be refused with its own recovery

This PR treats a well-formed path the host refused as a regular file as conforming input with its own remediation; the evtx boundary test still expected a schema-recovery refusal.

* test(javascript): expect a broken source-graph commitment as an integrity failure

This PR reports a well-formed historical source graph whose entries disagree with its root_sha256 as evidence_integrity_mismatch, not an input issue; the exact refusal assertion added on main still expected invalid_request.
2026-12-01 05:32:33 +00:00

1058 lines
37 KiB
TypeScript

import { publishCliAnalysisEvidence } from "../../src/cli/analysisEvidenceDelivery.js";
import { projectCliAnalysisResult } from "../../src/cli/projectCliAnalysisResult.js";
import {
mkdir,
open,
readFile,
readdir,
stat,
writeFile,
} from "node:fs/promises";
import { basename, dirname, join } from "node:path";
import { describe, expect, it, vi } from "vitest";
import { createPackageWithOptions } from "@electron/asar";
import { createArtifactBinarySession } from "../../src/composition/artifactSession.js";
import {
runDirectAnalysis,
runManagedProviderExecution,
runProviderAnalysis,
} from "../../src/application/DirectAnalysis.js";
import type { DirectAnalysisDependencies } from "../../src/application/DirectAnalysisDependencies.js";
import { parseConfig } from "../../src/config/parseConfig.js";
import { analysisCliErrorEnvelopeSchema } from "../../src/contracts/errorSchemas.js";
import type { AnalysisError } from "../../src/domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisInputError,
AnalysisTimeoutError,
} from "../../src/domain/analysisErrorCore.js";
import {
projectAnalysisError,
projectAnalysisErrorWithoutCapturedOutput,
} from "../../src/domain/analysisErrorProjection.js";
import {
createEvidence,
parseEvidence,
type Evidence,
} from "../../src/domain/evidence.js";
import { jsonObjectSchema } from "../../src/domain/jsonValue.js";
import { artifactInspectionResultSchema } from "../../src/domain/artifactInspection.js";
import { ProviderCleanupError } from "../../src/domain/providerCleanupError.js";
import { ghidraFunctionDossier } from "../../src/domain/ghidraValues.fixture.js";
import {
createAnalysisProfile,
type AnalysisProfileCommitment,
} from "../../src/domain/analysisProfile.js";
import { OwnedStagedOutput } from "../../src/filesystem/OwnedStagedOutput.js";
import { readAnalysisSnapshot } from "../../src/application/binary/AnalysisSnapshotFiles.js";
import { EvidenceFileError } from "../../src/domain/evidenceErrors.js";
import { err, ok } from "../../src/domain/result.js";
import { isCliOperationFailure } from "../../src/cliLogging.js";
import {
createFixtureProviderIdentity,
observed,
} from "../fixtures/analysisExecution.js";
import {
createBinarySessionTargets,
createTestBinarySession,
createTestProviderRouter,
} from "../fixtures/binarySession.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
import { BinarySession } from "../../src/application/binary/BinarySession.js";
import { InvestigationRecords } from "../../src/application/investigation/InvestigationRecords.js";
import { AnalysisCleanupLease } from "../../src/resources/AnalysisCleanupLease.js";
const createCleanupError = () =>
new ProviderCleanupError(
"fixture",
["fixture-provider-process"],
{ reason: "process exit could not be confirmed" },
{
remediationAction: "Close the retained fixture process before retrying.",
},
);
const CAPTURED_OUTPUT = {
stdout: "retained observation",
stderr: "",
truncated: false,
};
const createPrimaryError = () =>
new AnalysisTimeoutError("read_bytes", 100, {
capturedOutput: CAPTURED_OUTPUT,
});
const factories = (
options: {
readonly profile?: AnalysisProfileCommitment;
readonly executionError?: AnalysisError;
readonly thrownExecution?: Error;
readonly cleanupError?: AnalysisError;
readonly thrownCleanup?: Error;
readonly onClose?: () => void;
} = {},
) => {
const profile = options.profile;
const session = createTestBinarySession(
() => ({
execute: async (operation) => {
if (operation === "health") return observed(null);
if (options.thrownExecution !== undefined)
throw options.thrownExecution;
return options.executionError === undefined
? observed(
operation === "analyze_function"
? ghidraFunctionDossier()
: { operation, observation: "retained result" },
)
: err(options.executionError);
},
close: async () => {
if (options.thrownCleanup !== undefined) throw options.thrownCleanup;
options.onClose?.();
return options.cleanupError === undefined
? ok(null)
: err(options.cleanupError);
},
}),
profile === undefined
? {}
: { resolveAnalysisProfile: async () => ok({ profile }) },
);
const dependencies: DirectAnalysisDependencies = {
readConfiguration: () => parseConfig({}),
createBinarySession: () => session,
createArtifactBinarySession: () => session,
createNativeDispatchBinarySession: () => session,
createNativeBinarySession: () => session,
createManagedBinarySession: () => session,
};
return { dependencies, session };
};
it("rejects malformed one-shot operation inputs before creating a session", async () => {
const { dependencies, session } = factories();
const create = vi.fn(() => session);
const guarded = {
...dependencies,
createBinarySession: create,
createNativeBinarySession: create,
createNativeDispatchBinarySession: create,
createArtifactBinarySession: create,
createManagedBinarySession: create,
};
for (const result of [
await runDirectAnalysis(guarded, "/missing", "inspect_native_instruction", {
address: "",
}),
await runDirectAnalysis(guarded, "/missing", "annotate_native_function", {
procedure: "main",
}),
await runDirectAnalysis(guarded, "/missing", "trace_feature", {
query: "",
}),
await runDirectAnalysis(guarded, "/missing", "analyze_function", {
procedure: "",
}),
await runDirectAnalysis(guarded, "/missing", "inspect_native_api", {
procedure: "",
}),
await runProviderAnalysis(guarded, "/missing", "observe_native_calls", {
breakpoints: [],
}),
await runProviderAnalysis(guarded, "/missing", "inspect_asset_catalog", {
limit: -1,
}),
]) {
expect(result.ok).toBe(false);
if (!result.ok)
expect(result.error).toMatchObject({ code: "invalid_request" });
}
const xrefs = await runDirectAnalysis(guarded, "/missing", "xrefs", {
address: "table_only",
extra: true,
});
const managed = await runManagedProviderExecution(
guarded,
"/missing",
"inspect_managed_members",
undefined,
{ type_names: ["Duplicate", "Duplicate"] },
);
expect(managed.ok).toBe(false);
if (!managed.ok)
expect(projectAnalysisError(managed.error)).toMatchObject({
code: "invalid_request",
});
expect(create).not.toHaveBeenCalled();
expect(xrefs).toMatchObject({
ok: false,
error: {
code: "invalid_request",
details: {
operation: "xrefs",
issues: [{ path: ["extra"], reason: "unknown_argument" }],
},
},
});
});
it.each([false, true])(
"retains actual artifact sources and caller path after final-close cancellation (cleanup fails: %s)",
async (closeFails) => {
const root = await createTestTempDirectory("rea-artifact-final-close-");
const source = join(root, "source");
const archive = join(root, "fixture.asar");
await mkdir(source);
await writeFile(join(source, "main.js"), "console.log('retained');\n");
await createPackageWithOptions(source, archive, {});
const session = await createArtifactBinarySession({});
const cleanupError = createCleanupError();
const nativeClose = session.close.bind(session);
const controller = new AbortController();
const reason = {
request: "cancel during actual artifact session final close",
};
let completed: Evidence | undefined;
const close = vi
.spyOn(session, "close")
.mockImplementationOnce(async () => {
completed = session
.exportEvidenceBundle()
.records.find(
({ operation, caller_input_path }) =>
operation === "inspect_artifact" && caller_input_path === archive,
);
controller.abort(reason);
// A controlled refusal retains the actual static session for finally
// cleanup; successful cleanup runs its native owner here.
return closeFails ? err(cleanupError) : nativeClose();
});
const unexpectedSession = () => {
throw new Error("Artifact one-shot must select its static session");
};
const dependencies: DirectAnalysisDependencies = {
readConfiguration: () => parseConfig({}),
createArtifactBinarySession: () => session,
createBinarySession: unexpectedSession,
createNativeDispatchBinarySession: unexpectedSession,
createNativeBinarySession: unexpectedSession,
createManagedBinarySession: unexpectedSession,
};
try {
const result = analysisCliErrorEnvelopeSchema.parse(
await runProviderAnalysis(
dependencies,
archive,
"inspect_artifact",
{},
undefined,
controller.signal,
).then(projectCliAnalysisResult),
);
expect(result.code).toBe(closeFails ? "cleanup_incomplete" : "cancelled");
expect(result.category).toBe("cancelled");
expect(completed).toBeDefined();
const details = jsonObjectSchema.parse(result.details);
const partial = parseEvidence(details.partial_observation);
expect(partial).toEqual(completed);
expect(partial.operation).toBe("inspect_artifact");
expect(partial.caller_input_path).toBe(archive);
expect(partial.subject?.local_path).toBe(archive);
const inspection = artifactInspectionResultSchema.parse(
partial.normalized_result,
);
expect(inspection.subject.root_format).toBe("asar");
expect(partial.evidence_links).toEqual(inspection.evidence_links);
expect(partial.evidence_links).toEqual(
inspection.substeps.map(({ evidence }) => evidence.evidence_id),
);
expect(inspection.substeps[0]?.evidence.normalized_result).toMatchObject({
occurrences: expect.arrayContaining([
expect.objectContaining({ logical_path: "main.js" }),
]),
});
if (closeFails)
expect(details.cleanup_error).toEqual(
projectAnalysisError(cleanupError),
);
else expect(result.details).not.toHaveProperty("cleanup_error");
expect((await readdir(root)).sort()).toEqual(["fixture.asar", "source"]);
} finally {
close.mockRestore();
const closed = await nativeClose();
if (!closed.ok) throw closed.error;
}
},
);
it.each([false, true])(
"binds the exact caller path to provider failure Evidence (session cleanup fails: %s)",
async (closeFails) => {
const [path] = await createBinarySessionTargets();
const callerPath = `${dirname(path)}/./${basename(path)}`;
const original = createEvidence(
{ path, sha256: "a".repeat(64), format: "mach-o", architecture: "arm64" },
{ id: "fixture", name: "Fixture", version: null },
{ operation: "read_bytes", parameters: {}, result: { byte: 42 } },
);
const failure = new AnalysisCancelledError("read_bytes", {
partialObservation: original,
});
const { dependencies } = factories({
executionError: failure,
...(closeFails ? { cleanupError: createCleanupError() } : {}),
});
const result = analysisCliErrorEnvelopeSchema.parse(
await runDirectAnalysis(dependencies, callerPath, "read_bytes", {
address: "0x1000",
}).then(projectCliAnalysisResult),
);
const observation = parseEvidence(
jsonObjectSchema.parse(result.details).partial_observation,
);
expect(observation.caller_input_path).toBe(callerPath);
expect(observation.subject?.local_path).toBe(path);
expect(observation.evidence_id).toBe(original.evidence_id);
expect(observation.normalized_result).toEqual({ byte: 42 });
expect(original.caller_input_path).toBeUndefined();
},
);
it("preserves the caller path on an authenticated record refused by the ledger", async () => {
const [path] = await createBinarySessionTargets();
const callerPath = `${dirname(path)}/./${basename(path)}`;
const records = new InvestigationRecords({ maximumRepresentationBytes: 0 });
const session = new BinarySession(
createTestProviderRouter(
() => ({
execute: async (operation) =>
observed(operation === "health" ? null : { byte: 42 }),
close: async () => ok(null),
}),
{
resolveAnalysisProfile: async () =>
ok({
profile: createAnalysisProfile(createFixtureProviderIdentity(), {
fixture: true,
}),
}),
},
),
records,
);
const createSession = () => session;
const result = analysisCliErrorEnvelopeSchema.parse(
await runDirectAnalysis(
{
readConfiguration: () => parseConfig({}),
createBinarySession: createSession,
createArtifactBinarySession: createSession,
createNativeDispatchBinarySession: createSession,
createNativeBinarySession: createSession,
createManagedBinarySession: createSession,
},
callerPath,
"read_bytes",
{ address: "0x100", document: "fixture" },
).then(projectCliAnalysisResult),
);
expect(result.code).toBe("resource_constraint");
const partial = jsonObjectSchema.parse(
jsonObjectSchema.parse(result.details).partial_observation,
);
expect(partial.kind).toBe("unretained-evidence");
const evidence = parseEvidence(partial.evidence);
expect(evidence.caller_input_path).toBe(callerPath);
expect(evidence.subject?.local_path).toBe(path);
expect(evidence.normalized_result).toEqual({ byte: 42 });
expect(records.statistics().evidenceRecords).toBe(0);
});
describe("one-shot finalization cancellation", () => {
it.each(["read_bytes", "analyze_function"] as const)(
"retains completed %s Evidence when cancellation arrives during final close",
async (tool) => {
const [path] = await createBinarySessionTargets();
const parameters =
tool === "analyze_function"
? { procedure: "fixture" }
: { address: "0x1000" };
const original = parseEvidence(
await runDirectAnalysis(
factories().dependencies,
path,
tool,
parameters,
).then(projectCliAnalysisResult),
);
const controller = new AbortController();
const reason = { request: "cancel during native close" };
const { dependencies, session } = factories({
onClose: () => controller.abort(reason),
});
const result = await runDirectAnalysis(
dependencies,
path,
tool,
parameters,
{ signal: controller.signal },
).then(projectCliAnalysisResult);
expect(result).toEqual({
error: "Analysis failed",
...projectAnalysisError(
new AnalysisCancelledError(tool, {
cause: reason,
partialObservation: original,
}),
),
});
expect(session.activeTarget()).toBeUndefined();
},
);
it.each([false, true])(
"preserves the execution failure during close cancellation (cleanup fails: %s)",
async (closeFails) => {
const [path] = await createBinarySessionTargets();
const controller = new AbortController();
const failure = createPrimaryError();
const cleanupError = createCleanupError();
const { dependencies } = factories({
executionError: failure,
onClose: () => controller.abort({ later: true }),
...(closeFails ? { cleanupError } : {}),
});
const result = await runDirectAnalysis(
dependencies,
path,
"read_bytes",
{ address: "0x1000" },
{ signal: controller.signal },
).then(projectCliAnalysisResult);
expect(result).toMatchObject({
code: closeFails ? "cleanup_incomplete" : "provider_timeout",
// A timeout may repeat unchanged; one whose close also failed may
// repeat only after cleanup settles.
retryable: !closeFails,
retry_class: closeFails ? "change_first" : "same_call",
message: projectAnalysisError(failure).message,
details: {
captured_output: failure.capturedOutput,
...(closeFails
? { cleanup_error: projectAnalysisError(cleanupError) }
: {}),
},
});
},
);
it("retains completed Evidence and cancellation alongside unsuccessful cleanup", async () => {
const [path] = await createBinarySessionTargets();
const controller = new AbortController();
const cleanupError = createCleanupError();
const { dependencies } = factories({
cleanupError,
onClose: () => controller.abort({ during: "close" }),
});
const result = await runDirectAnalysis(
dependencies,
path,
"read_bytes",
{ address: "0x1000" },
{ signal: controller.signal },
).then(projectCliAnalysisResult);
expect(result).toMatchObject({
code: "cleanup_incomplete",
category: "cancelled",
retryable: false,
retry_class: "change_first",
details: {
execution_failure: "cancelled",
resources: ["fixture-provider-process"],
partial_observation: {
operation: "read_bytes",
normalized_result: { observation: "retained result" },
},
cleanup_error: projectAnalysisError(cleanupError),
},
});
});
});
describe("snapshot publication finalization", () => {
it.each([
"success",
"cancel",
"recovered-write-cancel",
"close-failure",
"cancel-close-failure",
] as const)(
"retains the actual snapshot publication through finalization: %s",
async (mode) => {
const [path] = await createBinarySessionTargets();
const snapshotPath = join(dirname(path), "snapshot.json");
const controller = new AbortController();
const profile = createAnalysisProfile(createFixtureProviderIdentity(), {
fixture: true,
});
const cancelled = mode.includes("cancel");
const { dependencies, session } = factories({
profile,
onClose: () => {
if (cancelled) controller.abort({ during: "snapshot finalization" });
},
...(mode.includes("close-failure")
? { cleanupError: createCleanupError() }
: {}),
});
const stagingCleanup =
mode === "recovered-write-cancel"
? vi
.spyOn(OwnedStagedOutput.prototype, "close")
.mockRejectedValueOnce(
new Error("transient staging cleanup failure"),
)
: undefined;
try {
const result = await runDirectAnalysis(
dependencies,
path,
"read_bytes",
{ address: "0x1000" },
{ signal: controller.signal, snapshotPath },
).then(projectCliAnalysisResult);
const loaded = await readAnalysisSnapshot(snapshotPath);
if (!loaded.ok) throw loaded.error;
const evidence = loaded.value.evidence_bundle.records.find(
(record) => record.operation === "read_bytes",
);
expect(evidence).toBeDefined();
const receipt = {
path: snapshotPath,
bytes: (await stat(snapshotPath)).size,
};
expect((await readFile(snapshotPath)).byteLength).toBe(receipt.bytes);
if (mode === "success") expect(result).toEqual(evidence);
else {
const failure = analysisCliErrorEnvelopeSchema.parse(result);
expect(failure.code).toBe(
mode.includes("close-failure") ? "cleanup_incomplete" : "cancelled",
);
expect(failure.details).toMatchObject({
partial_observation: evidence,
diagnostics: { analysis_snapshot: receipt },
});
}
expect(session.activeTarget()).toBeUndefined();
expect((await readdir(dirname(path))).toSorted()).toEqual([
"first.hop",
"second.hop",
"snapshot.json",
]);
if (stagingCleanup !== undefined)
expect(stagingCleanup).toHaveBeenCalledTimes(2);
} finally {
stagingCleanup?.mockRestore();
}
},
);
it("preserves a snapshot write failure over later cancellation without a publication receipt", async () => {
const [path] = await createBinarySessionTargets();
const controller = new AbortController();
const profile = createAnalysisProfile(createFixtureProviderIdentity(), {
fixture: true,
});
const { dependencies, session } = factories({
profile,
onClose: () => controller.abort({ later: true }),
});
const failure = new EvidenceFileError("write", "io", {
path: join(dirname(path), "failed.json"),
});
const write = vi
.spyOn(session, "writeAnalysisSnapshot")
.mockResolvedValue(err(failure));
try {
const result = analysisCliErrorEnvelopeSchema.parse(
await runDirectAnalysis(
dependencies,
path,
"read_bytes",
{ address: "0x1000" },
{ signal: controller.signal, snapshotPath: failure.path },
).then(projectCliAnalysisResult),
);
expect(result.code).toBe(projectAnalysisError(failure).code);
expect(result.details).toMatchObject({
partial_observation: { operation: "read_bytes" },
});
expect(result.details).not.toHaveProperty(
"diagnostics.analysis_snapshot",
);
expect(await readdir(dirname(path))).not.toContain("failed.json");
} finally {
write.mockRestore();
}
});
});
it.each([false, true])(
"retains original cleanup diagnostics and distinct resources (final close fails: %s)",
async (closeFails) => {
const [path] = await createBinarySessionTargets();
const executionError = new AnalysisTimeoutError("read_bytes", 100, {
cleanup: {
reason: "snapshot removal failed during execution",
resources: ["primary-snapshot", "shared-owner"],
},
capturedOutput: CAPTURED_OUTPUT,
});
const closeError = new ProviderCleanupError(
"fixture",
["fixture-provider-process", "shared-owner"],
{ reason: "process exit could not be confirmed" },
);
const primary = projectAnalysisError(executionError);
const { dependencies } = factories({
executionError,
...(closeFails ? { cleanupError: closeError } : {}),
});
const result = analysisCliErrorEnvelopeSchema.parse(
await runDirectAnalysis(dependencies, path, "read_bytes", {
address: "0x1000",
}).then(projectCliAnalysisResult),
);
expect(result).toMatchObject({
code: "cleanup_incomplete",
details: {
...primary.details,
...(closeFails
? {
resources: [
"primary-snapshot",
"shared-owner",
"fixture-provider-process",
],
execution_failure: "provider_timeout",
cleanup_error: projectAnalysisError(closeError),
}
: {}),
},
});
expect(JSON.stringify(result).match(/retained observation/g)).toHaveLength(
1,
);
if (!closeFails) expect(result.details).not.toHaveProperty("cleanup_error");
},
);
describe("one-shot analysis cleanup outcomes", () => {
const readBytes = (dependencies: DirectAnalysisDependencies, path: string) =>
runDirectAnalysis(dependencies, path, "read_bytes", {
address: "0x1000",
}).then(projectCliAnalysisResult);
it.each([
["typed cleanup failure", "fixture-provider-process"],
["unexpected close rejection", "provider-client"],
] as const)(
"retains completed Evidence in the CLI response to %s",
async (kind, resource) => {
const [path] = await createBinarySessionTargets();
const { dependencies, session } = factories(
kind === "typed cleanup failure"
? { cleanupError: createCleanupError() }
: { thrownCleanup: new Error("unexpected close rejection") },
);
const result = await readBytes(dependencies, path);
expect(result).toMatchObject({
error: "Analysis failed",
code: "cleanup_incomplete",
details: {
resources: [resource],
...(kind === "unexpected close rejection" && {
diagnostics: {
reason: "provider client close rejected unexpectedly",
},
}),
partial_observation: {
operation: "read_bytes",
subject: { local_path: path },
normalized_result: { observation: "retained result" },
raw_result: null,
},
},
});
expect(isCliOperationFailure(result)).toBe(true);
expect(session.activeTarget()).toBeUndefined();
},
);
it("preserves primary failure diagnostics alongside an unsuccessful close", async () => {
const [path] = await createBinarySessionTargets();
const primaryError = createPrimaryError();
const cleanupError = createCleanupError();
const { dependencies } = factories({
executionError: primaryError,
cleanupError,
});
const primary = projectAnalysisError(primaryError);
const result = await readBytes(dependencies, path);
const callerError = analysisCliErrorEnvelopeSchema.parse(result);
expect(callerError).toMatchObject({
code: "cleanup_incomplete",
category: primary.category,
message: primary.message,
remediation: {
action: "Close the retained fixture process before retrying.",
},
details: {
execution_failure: primary.code,
captured_output: primary.details?.captured_output,
cleanup_error: projectAnalysisError(cleanupError),
},
});
expect(callerError.details).not.toHaveProperty("primary_error");
expect(
JSON.stringify(callerError).match(/retained observation/g),
).toHaveLength(1);
expect(isCliOperationFailure(result)).toBe(true);
});
it("retains both unexpected execution failure and cleanup failure", async () => {
const [path] = await createBinarySessionTargets();
const thrownExecution = new Error("unexpected execution rejection");
const cleanupError = createCleanupError();
const { dependencies } = factories({ thrownExecution, cleanupError });
await expect(readBytes(dependencies, path)).rejects.toMatchObject({
cause: thrownExecution,
errors: [thrownExecution, cleanupError],
});
});
it("keeps successful evidence unchanged after confirmed cleanup", async () => {
const [path] = await createBinarySessionTargets();
const { dependencies, session } = factories();
const result = await readBytes(dependencies, path);
expect(parseEvidence(result)).toMatchObject({
operation: "read_bytes",
normalized_result: { observation: "retained result" },
});
expect(isCliOperationFailure(result)).toBe(false);
expect(session.activeTarget()).toBeUndefined();
});
});
it("retains completed Evidence after managed close cancellation in inline and requested summary delivery", async () => {
const [path] = await createBinarySessionTargets();
const files = (await readdir(dirname(path))).sort();
const original = parseEvidence(
await runProviderAnalysis(
factories().dependencies,
path,
"inspect_managed_members",
{},
).then(projectCliAnalysisResult),
);
const controller = new AbortController();
const reason = new Error("cancel during managed close");
const { dependencies, session } = factories({
onClose: () => controller.abort(reason),
});
const analysis = await runProviderAnalysis(
dependencies,
path,
"inspect_managed_members",
{},
undefined,
controller.signal,
);
const expected = {
error: "Analysis failed",
...projectAnalysisError(
new AnalysisCancelledError("inspect_managed_members", {
cause: reason,
partialObservation: original,
}),
),
};
expect(projectCliAnalysisResult(analysis)).toEqual(expected);
expect(
await publishCliAnalysisEvidence(analysis, {
operation: "inspect_managed_members",
signal: controller.signal,
detail: "summary",
evidenceOutput: join(dirname(path), "bundle.json"),
}),
).toEqual(expected);
expect(session.activeTarget()).toBeUndefined();
expect((await readdir(dirname(path))).sort()).toEqual(files);
});
it("preserves a managed provider failure when cancellation arrives during close", async () => {
const [path] = await createBinarySessionTargets();
const controller = new AbortController();
const reason = new Error("later cancellation");
const failure = new AnalysisInputError("inspect_managed_members", undefined, [
{ path: ["path"], reason: "invalid_format" },
]);
const { dependencies, session } = factories({
executionError: failure,
onClose: () => controller.abort(reason),
});
const result = await runProviderAnalysis(
dependencies,
path,
"inspect_managed_members",
{},
undefined,
controller.signal,
).then(projectCliAnalysisResult);
expect(result).toEqual({
error: "Analysis failed",
...projectAnalysisError(failure),
});
expect(
failure.secondaryFailures.some(
(secondary) =>
secondary instanceof AnalysisCancelledError &&
secondary.cause === reason,
),
).toBe(true);
expect(session.activeTarget()).toBeUndefined();
});
describe("managed one-shot cleanup outcomes", () => {
it("returns a managed cleanup error retaining the complete successful execution", async () => {
const [path] = await createBinarySessionTargets();
const cleanupError = createCleanupError();
const { dependencies } = factories({ cleanupError });
const result = await runManagedProviderExecution(
dependencies,
path,
"inspect_managed_artifact",
);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(projectAnalysisError(result.error)).toMatchObject({
code: "cleanup_incomplete",
remediation: {
action: "Close the retained fixture process before retrying.",
},
details: {
resources: ["fixture-provider-process"],
diagnostics: {
cleanup_error: projectAnalysisError(cleanupError),
partial_observation: {
result: {
operation: "inspect_managed_artifact",
observation: "retained result",
},
rawResult: null,
provider: { id: "fixture" },
},
},
},
});
});
it("retains the typed managed primary error when close also fails", async () => {
const [path] = await createBinarySessionTargets();
const primaryError = createPrimaryError();
const cleanupError = createCleanupError();
const { dependencies } = factories({
executionError: primaryError,
cleanupError,
});
const result = await runManagedProviderExecution(
dependencies,
path,
"inspect_managed_artifact",
);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error.cause).toBeInstanceOf(AggregateError);
expect(result.error.cause).toMatchObject({
cause: primaryError,
errors: [primaryError, cleanupError],
});
const projected = projectAnalysisError(result.error);
expect(projected).toMatchObject({
code: "cleanup_incomplete",
details: {
captured_output: primaryError.capturedOutput,
diagnostics: {
primary_error:
projectAnalysisErrorWithoutCapturedOutput(primaryError),
cleanup_error: projectAnalysisError(cleanupError),
},
},
});
expect(projected).not.toHaveProperty(
"details.diagnostics.primary_error.details.captured_output",
);
expect(
JSON.stringify(projected).split("retained observation"),
).toHaveLength(2);
});
it("exposes managed cleanup failure to the CLI error classifier", async () => {
const [path] = await createBinarySessionTargets();
const { dependencies } = factories({ cleanupError: createCleanupError() });
const result = await runProviderAnalysis(
dependencies,
path,
"inspect_managed_artifact",
{},
).then(projectCliAnalysisResult);
expect(isCliOperationFailure(result)).toBe(true);
expect(result).toMatchObject({
error: "Analysis failed",
code: "cleanup_incomplete",
});
});
});
describe("managed one-shot cleanup retry ownership", () => {
it.each(["success", "timeout", "independent primary"] as const)(
"follows exact cleanup completion after a %s outcome",
async (mode) => {
const [path] = await createBinarySessionTargets();
const resource = join(dirname(path), "retained-descriptor");
const handle = await open(resource, "w+");
const cleanup = new ProviderCleanupError("fixture", [resource], {
reason: "controlled first close refusal",
});
let attempts = 0;
const lease = new AnalysisCleanupLease(async () => {
if (++attempts === 1) throw new Error("first close refused");
await handle.close();
}, [resource]);
lease.bindCleanupError(cleanup);
const primaryResource = join(dirname(path), "primary-descriptor");
const primaryHandle =
mode === "independent primary"
? await open(primaryResource, "w+")
: undefined;
const primary =
mode === "success"
? undefined
: new AnalysisTimeoutError("inspect_managed_members", 100, {
capturedOutput: {
stdout: "retained timeout observation",
stderr: "",
truncated: false,
},
...(primaryHandle === undefined
? {}
: {
cleanup: {
reason: "independent primary cleanup",
resources: [primaryResource],
},
}),
});
const primaryLease =
primaryHandle === undefined
? undefined
: new AnalysisCleanupLease(
() => primaryHandle.close(),
[primaryResource],
);
if (primary !== undefined) primaryLease?.bindCleanupError(primary);
const session = createTestBinarySession(() => ({
execute: async (operation) =>
operation === "health"
? observed(null)
: primary === undefined
? observed({ retained: true })
: err(primary),
close: async () => {
try {
await lease.release();
return ok(null);
} catch {
return err(cleanup);
}
},
}));
try {
const result = await runManagedProviderExecution(
{ createManagedBinarySession: () => session },
path,
"inspect_managed_members",
);
if (result.ok) throw new Error("Expected retained cleanup failure");
expect(projectAnalysisError(result.error).code).toBe(
"cleanup_incomplete",
);
expect(handle.fd).toBeGreaterThanOrEqual(0);
expect(await session.close()).toMatchObject({ ok: true });
expect(handle.fd).toBe(-1);
expect(cleanup.cleanupIncomplete).toBe(false);
if (primaryLease !== undefined) {
expect(result.error.cleanupIncomplete).toBe(true);
expect(result.error.cleanupResources).toEqual([primaryResource]);
expect(primaryHandle?.fd).toBeGreaterThanOrEqual(0);
await primaryLease.release();
}
expect(result.error.cleanupIncomplete).toBe(false);
const projected = projectAnalysisError(result.error);
if (primary === undefined)
expect(projected).toMatchObject({
details: {
diagnostics: {
partial_observation: { result: { retained: true } },
},
},
});
else
expect(projected).toMatchObject({
code: "provider_timeout",
details: {
captured_output: { stdout: "retained timeout observation" },
},
});
} finally {
await session.close();
await lease.release();
await primaryLease?.release();
await handle.close();
await primaryHandle?.close();
}
},
);
it.each([false, true])(
"keeps rejected cleanup without a live completion owner unknown (primary failure: %s)",
async (primaryFailure) => {
const [path] = await createBinarySessionTargets();
const unowned = new AnalysisInputError("close_binary");
const { dependencies } = factories({
...(primaryFailure
? {
executionError: new AnalysisTimeoutError(
"inspect_managed_members",
100,
),
}
: {}),
cleanupError: unowned,
});
const result = await runManagedProviderExecution(
dependencies,
path,
"inspect_managed_members",
);
if (result.ok) throw new Error("Expected cleanup rejection");
expect(unowned.cleanupIncomplete).toBe(false);
expect(result.error.cleanupIncomplete).toBe(true);
expect(projectAnalysisError(result.error).code).toBe(
"cleanup_incomplete",
);
},
);
});