Files
reverse-engineering-anything/src/domain/analysisErrorCleanup.test.ts
T
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

690 lines
23 KiB
TypeScript

import { unknownTarget } from "./targetIdentity.js";
import { expect, it } from "vitest";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
AnalysisInputError,
AnalysisOutputError,
AnalysisResourceConstraintError,
AnalysisTimeoutError,
} from "./analysisErrorCore.js";
import {
analysisErrorWithCleanupFailure,
providerCleanupErrorFromFailures,
withInheritedCleanupOwnership,
withSecondaryCleanupFailure,
} from "./analysisErrorCleanup.js";
import {
projectAnalysisError,
projectAnalysisErrorWithoutCapturedOutput,
} from "./analysisErrorProjection.js";
import {
analysisErrorCategory,
analysisErrorRemediationAction,
analysisErrorUserMessage,
} from "./analysisErrorPresentation.js";
import { ProviderCleanupError } from "./providerCleanupError.js";
import { createEvidence } from "./evidence.js";
import { ArtifactOperationError } from "./artifactOperationError.js";
import { releaseOwnedCleanup } from "../../tests/support/cleanupRelease.js";
it.each([false, true])(
"keeps each owner's capture without text-based deduplication (matching: %s)",
(matching) => {
const primary = new AnalysisTimeoutError("inspect", 1234, {
capturedOutput: {
stdout: "primary-capture-sentinel",
stderr: "",
truncated: false,
},
});
const cleanup = new ProviderCleanupError(
"fixture",
["owned-worker"],
{},
{
capturedOutput: {
stdout: matching
? "primary-capture-sentinel"
: "cleanup-capture-sentinel",
stderr: "",
truncated: true,
},
},
);
const composed = analysisErrorWithCleanupFailure(
primary,
cleanup,
"inspect",
);
const projected = projectAnalysisError(composed);
expect(projected.details?.captured_output).toEqual(primary.capturedOutput);
expect(projected.details?.diagnostics).toMatchObject({
primary_error: {
code: "provider_timeout",
details: { timeout_ms: 1234 },
},
cleanup_error: { details: { captured_output: cleanup.capturedOutput } },
});
expect(
JSON.stringify(projected).split("primary-capture-sentinel"),
).toHaveLength(matching ? 3 : 2);
if (!matching)
expect(
JSON.stringify(projected).split("cleanup-capture-sentinel"),
).toHaveLength(2);
expect(
projectAnalysisErrorWithoutCapturedOutput(primary).details,
).not.toHaveProperty("captured_output");
expect(projectAnalysisError(primary).details?.captured_output).toEqual(
primary.capturedOutput,
);
},
);
it("keeps dependency-owned resources empty after the final owner releases", () => {
const file = new ProviderCleanupError("fixture", ["file-owner"], {});
const trace = new ProviderCleanupError("fixture", ["trace-owner"], {});
const composed = analysisErrorWithCleanupFailure(
file,
trace,
).bindCleanupDependencies([file, trace]);
expect(new Set(composed.cleanupResources)).toEqual(
new Set(["file-owner", "trace-owner"]),
);
releaseOwnedCleanup(file);
expect(composed.cleanupResources).toEqual(["trace-owner"]);
releaseOwnedCleanup(trace);
expect(composed.cleanupIncomplete).toBe(false);
expect(composed.cleanupResources).toEqual([]);
expect(new Set(composed.cleanup?.resources)).toEqual(
new Set(["file-owner", "trace-owner"]),
);
});
it("reads completion through nested compositions from the releasing owner only", () => {
const owner = new ProviderCleanupError("fixture", ["owned-worker"], {});
const inner = new ProviderCleanupError(
"fixture",
["owned-worker"],
{},
).bindCleanupDependencies([owner]);
const outer = new ProviderCleanupError(
"fixture",
["owned-worker"],
{},
).bindCleanupDependencies([inner]);
// Cleanup state is not writable state of an error value.
expect(Reflect.set(outer, "cleanupIncomplete", false)).toBe(false);
expect(outer.cleanupIncomplete).toBe(true);
releaseOwnedCleanup(owner);
expect(outer.cleanupIncomplete).toBe(false);
expect(inner.cleanupIncomplete).toBe(false);
// Completion is monotonic: a later binding cannot reopen it.
outer.bindCleanupDependencies([
new ProviderCleanupError("fixture", ["later"], {}),
]);
expect(outer.cleanupIncomplete).toBe(false);
expect(outer.cleanupResources).toEqual([]);
});
it("keeps completion when a dependency is bound after release without an intermediate read", () => {
const owner = new ProviderCleanupError("fixture", ["owned-worker"], {});
const outer = new ProviderCleanupError(
"fixture",
["owned-worker"],
{},
).bindCleanupDependencies([owner]);
releaseOwnedCleanup(owner);
outer.bindCleanupDependencies([
new ProviderCleanupError("fixture", ["later"], {}),
]);
expect(outer.cleanupIncomplete).toBe(false);
});
it("keeps primary diagnostics separate from historical cleanup diagnostics with the same keys", () => {
const primary = new AnalysisInputError("inspect", {
diagnostics: {
primary_error: "source observation",
cleanup_error: "another source observation",
},
});
const cleanup = new ProviderCleanupError("fixture", ["owned-input"], {});
const composed = analysisErrorWithCleanupFailure(
primary,
cleanup,
).bindCleanupDependencies([primary, cleanup]);
releaseOwnedCleanup(cleanup);
const projected = projectAnalysisError(composed);
expect(projected.details?.diagnostics).toEqual(primary.diagnostics);
expect(projected.details?.cleanup_history).toMatchObject({
primary_error: projectAnalysisError(primary),
cleanup_error: { code: "cleanup_incomplete" },
});
expect(composed.cleanupPrimary).toBe(primary);
expect(Object.hasOwn(composed, "cleanupPrimary")).toBe(false);
});
it.each([
new ArtifactOperationError(
"inspect_asset_catalog",
"integrity",
undefined,
"Asset catalog changed during inspection: Contents/Resources/Assets.car",
),
new AnalysisInputError("inspect", { diagnostics: { input: "original" } }, [
{
path: ["path"],
reason: "out_of_range",
message: "fixed input allowance",
},
]),
new AnalysisCancelledError("inspect", { cause: "caller reason" }),
new AnalysisTimeoutError("inspect", 1234),
new AnalysisResourceConstraintError(
"inspect",
"file-size",
"fixed input allowance",
{ maximum_input_bytes: 123 },
{ retryable: false, remediationAction: "Select a smaller suitable input." },
),
new AnalysisOutputError("inspect", "invalid output", {
capturedOutput: {
stdout: "original output",
stderr: "original warning",
truncated: true,
},
partialObservation: createEvidence(
unknownTarget("not-observed"),
{ id: "fixture", name: "Fixture", version: null },
{
operation: "inspect",
parameters: {},
result: { original_fact: true },
confidence: "observed",
locations: [],
limitations: [],
},
),
}),
])("restores the typed $_tag primary after confirmed cleanup", (primary) => {
const original = projectAnalysisError(primary);
const cleanup = new ProviderCleanupError(
"fixture",
["owned-input"],
{ reason: "close denied" },
{
operation: "inspect",
cleanup: { reason: "close denied", resources: ["owned-input"] },
},
);
const composed = analysisErrorWithCleanupFailure(
primary,
cleanup,
"inspect",
).bindCleanupDependencies([primary, cleanup]);
expect(composed.cleanup?.reason).toBe("close denied");
expect(composed.cleanup?.reason).not.toBe(
projectAnalysisError(cleanup).message,
);
const pending = projectAnalysisError(composed);
expect(pending.code).toBe("cleanup_incomplete");
expect(pending.category).toBe(original.category);
expect(analysisErrorCategory(composed)).toBe(original.category);
const { diagnostics: _diagnostics, ...semanticDetails } =
original.details ?? {};
expect(pending.details).toMatchObject({
...semanticDetails,
cleanup: "incomplete",
execution_failure: original.code,
resources: ["owned-input"],
});
releaseOwnedCleanup(cleanup);
const projected = projectAnalysisError(composed);
expect(projected).toMatchObject(original);
expect(projected.details?.cleanup_history).toMatchObject({
primary_error: { code: original.code, message: original.message },
cleanup_error: { code: "cleanup_incomplete" },
});
expect(projected.details?.cleanup_history).not.toHaveProperty(
"primary_error.details.partial_observation",
);
expect(projected.details?.cleanup_history).not.toHaveProperty(
"primary_error.details.captured_output",
);
expect(projected.details).not.toHaveProperty("cleanup", "incomplete");
expect(projected.details).not.toHaveProperty("resources");
expect(analysisErrorCategory(composed)).toBe(original.category);
expect(analysisErrorUserMessage(composed)).toBe(original.message);
expect(analysisErrorRemediationAction(composed)).toBe(
original.remediation.action,
);
expect(composed.cause).toBeInstanceOf(AggregateError);
expect((composed.cause as AggregateError).errors[0]).toBe(primary);
});
it.each(["inner", "outer"] as const)(
"waits for both nested cleanup owners when %s resolves first",
(first) => {
const primary = new AnalysisInputError("inspect", undefined, [
{ path: ["path"], reason: "missing_argument" },
]);
const innerCleanup = new ProviderCleanupError("fixture", ["input"], {});
const outerCleanup = new ProviderCleanupError("fixture", ["workspace"], {});
const inner = analysisErrorWithCleanupFailure(
primary,
innerCleanup,
).bindCleanupDependencies([primary, innerCleanup]);
const outer = analysisErrorWithCleanupFailure(
inner,
outerCleanup,
).bindCleanupDependencies([inner, outerCleanup]);
const released = first === "inner" ? innerCleanup : outerCleanup;
const pending = first === "inner" ? outerCleanup : innerCleanup;
expect(projectAnalysisError(outer)).toMatchObject({
code: "cleanup_incomplete",
category: "invalid_input",
details: {
operation: "inspect",
issues: primary.issues,
execution_failure: "invalid_request",
},
});
releaseOwnedCleanup(released);
expect(outer.cleanupIncomplete).toBe(true);
expect(projectAnalysisError(outer).code).toBe("cleanup_incomplete");
expect(projectAnalysisError(outer).category).toBe("invalid_input");
releaseOwnedCleanup(pending);
expect(outer.cleanupIncomplete).toBe(false);
expect(projectAnalysisError(outer)).toMatchObject(
projectAnalysisError(primary),
);
},
);
it("preserves recovery and secondary failures owned by an intermediate cleanup", () => {
const primary = new AnalysisInputError("inspect");
const inner = analysisErrorWithCleanupFailure(
primary,
new ProviderCleanupError("fixture", ["input"], {}),
);
inner.retainSourcePublication({
kind: "omitted",
reason: "primary-authentication-failed",
source_closure: "not-established",
});
inner.retainSecondaryFailure(new AnalysisInputError("source"));
const outer = analysisErrorWithCleanupFailure(
inner,
new ProviderCleanupError("fixture", ["workspace"], {}),
);
expect(projectAnalysisError(outer)).toMatchObject({
details: {
completed_observation_omitted: {
reason: "primary-authentication-failed",
source_closure: "not-established",
},
secondary_failures: [{ code: "invalid_request" }],
},
});
});
it("prefers the outer publication source over the nested primary observation", () => {
const provider = { id: "fixture", name: "Fixture", version: null };
const source = createEvidence(unknownTarget("not-observed"), provider, {
operation: "source",
parameters: {},
result: "source",
});
const nested = createEvidence(unknownTarget("not-observed"), provider, {
operation: "nested",
parameters: {},
result: "nested",
});
const primary = new AnalysisCancelledError("inspect", {
partialObservation: nested,
});
const composed = analysisErrorWithCleanupFailure(
primary,
new ProviderCleanupError("fixture", ["input"], {}),
);
composed.partialObservation = source;
composed.retainSourcePublication({
kind: "omitted",
reason: "primary-authentication-failed",
source_closure: "not-established",
});
expect(projectAnalysisError(composed).details?.partial_observation).toEqual(
source,
);
});
it("does not infer cleanup success when a composition has no live owner binding", () => {
const primary = new AnalysisInputError("inspect");
const cleanup = new ProviderCleanupError("fixture", ["input"], {});
const composed = analysisErrorWithCleanupFailure(primary, cleanup);
releaseOwnedCleanup(cleanup);
expect(projectAnalysisError(composed).code).toBe("cleanup_incomplete");
expect(projectAnalysisError(composed).category).toBe("invalid_input");
expect(composed.cleanupIncomplete).toBe(true);
});
it("keeps the physical failure primary when later cleanup observes cancellation", () => {
const physical = Object.assign(new Error("selected file read EIO"), {
code: "EIO",
});
const primary = new ArtifactOperationError(
"inspect_asset_catalog",
"io",
undefined,
physical.message,
{ cause: physical },
);
const reason = { request: "cancel after read failure" };
const cleanup = new ProviderCleanupError(
"fixture",
["owned-input"],
{},
{
cause: new AnalysisCancelledError("inspect", { cause: reason }),
},
);
const composed = analysisErrorWithCleanupFailure(
primary,
cleanup,
"inspect",
).bindCleanupDependencies([primary, cleanup]);
expect(projectAnalysisError(composed)).toMatchObject({
code: "cleanup_incomplete",
category: "execution_failure",
details: {
operation: "inspect_asset_catalog",
reason: "io",
detail: physical.message,
execution_failure: "artifact_operation_failed",
},
});
expect(composed.cleanupPrimary?.cause).toBe(physical);
releaseOwnedCleanup(cleanup);
expect(projectAnalysisError(composed)).toMatchObject(
projectAnalysisError(primary),
);
});
it("retains an observation attached to the composite after the primary failed", () => {
const primary = new AnalysisInputError("inspect");
const cleanup = new ProviderCleanupError("fixture", ["input"], {});
const composed = analysisErrorWithCleanupFailure(
primary,
cleanup,
).bindCleanupDependencies([primary, cleanup]);
const observation = createEvidence(
unknownTarget("not-observed"),
{ id: "fixture", name: "Fixture", version: null },
{
operation: "inspect",
parameters: {},
result: { late_fact: true },
confidence: "observed",
locations: [],
limitations: [],
},
);
composed.retainPartialObservation(observation);
releaseOwnedCleanup(composed);
expect(projectAnalysisError(composed).code).toBe("cleanup_incomplete");
releaseOwnedCleanup(cleanup);
expect(projectAnalysisError(composed)).toMatchObject({
code: "invalid_request",
details: { partial_observation: observation },
});
});
it("retains an owner's finalization report independently of pending primary semantics", () => {
const report = {
owned_process_group: { state: "not_required" as const, reason: null },
terminal_renderer: { state: "not_required" as const, reason: null },
temporary_root: { state: "cleaned" as const, reason: null },
};
class ReportedCleanup extends ProviderCleanupError {
override readonly cleanupReport = report;
}
const primary = new AnalysisInputError("inspect", undefined, [
{ path: ["path"], reason: "missing_argument" },
]);
const finalized = new ReportedCleanup(
"fixture",
["input"],
{},
{
cleanupPrimary: primary,
},
);
const later = new ProviderCleanupError("fixture", ["workspace"], {});
const outer = analysisErrorWithCleanupFailure(
finalized,
later,
).bindCleanupDependencies([finalized, later]);
const assertReport = (error: typeof outer) => {
expect(projectAnalysisError(error)).toMatchObject({
category: "invalid_input",
details: {
operation: "inspect",
issues: primary.issues,
cleanup_report: report,
},
});
};
assertReport(finalized);
assertReport(outer);
expect(outer.cleanupIncomplete).toBe(true);
releaseOwnedCleanup(later);
assertReport(outer);
expect(outer.cleanupIncomplete).toBe(true);
releaseOwnedCleanup(finalized);
assertReport(outer);
expect(outer.cleanupIncomplete).toBe(false);
});
it.each(["primary", "cleanup", "default", "cleanup-continuing"] as const)(
"preserves the explicit %s remediation owner through cleanup projection",
(owner) => {
const primaryAction =
"Inspect the selected compiler before retrying this request.";
const cleanupAction =
"Release the recorded cleanup resource before retrying.";
const primary = new AnalysisTimeoutError(
"inspect",
123,
owner === "default" ? {} : { remediationAction: primaryAction },
);
const cleanup = new AnalysisCapabilityUnavailableError(
"process-ownership",
"close",
"retained cleanup",
{
cleanup: { reason: "close failed", resources: ["owned resource"] },
...(owner === "cleanup" ? { remediationAction: cleanupAction } : {}),
...(owner === "cleanup-continuing"
? { continuingCallerGuidance: { remediationAction: cleanupAction } }
: {}),
},
);
const composed = analysisErrorWithCleanupFailure(
primary,
cleanup,
"inspect",
);
const expected =
owner === "cleanup"
? cleanupAction
: owner === "default"
? "Review details.reason, which names why the provider cannot run this operation. In a binary-analysis session, binary_session lists the operations available for the open target and provider; select one of those, or open a target that supports this analysis. Otherwise resolve the condition the reason names."
: primaryAction;
expect(projectAnalysisError(composed).remediation.action).toBe(
owner === "cleanup-continuing" ? cleanupAction : expected,
);
expect(
projectAnalysisError(composed, "invocation").remediation.action,
).toBe(expected);
expect(composed.cleanupPrimary).toBe(primary);
expect(composed.cleanupResources).toEqual(["owned resource"]);
expect(projectAnalysisError(composed).code).toBe("cleanup_incomplete");
},
);
it("tracks a shared resource until both cleanup owners release", () => {
const first = new ProviderCleanupError(
"fixture",
["shared-handle", "first-handle"],
{ reason: "first" },
{ operation: "fixture_close" },
);
const second = new ProviderCleanupError(
"fixture",
["shared-handle", "second-handle"],
{ reason: "second" },
{ operation: "fixture_close" },
);
const untyped = new Error("untyped close failure");
const composite = providerCleanupErrorFromFailures(
"fixture-provider",
[first, second],
"Fixture cleanup remains incomplete",
{
operation: "fixture_close",
causes: [first, untyped, second],
message: "Fixture cleanup failed",
},
);
expect(composite).toBeInstanceOf(ProviderCleanupError);
expect(composite).toMatchObject({
providerId: "fixture-provider",
operation: "fixture_close",
cleanupIncomplete: true,
cleanupResources: ["shared-handle", "first-handle", "second-handle"],
diagnostics: { reason: "Fixture cleanup remains incomplete" },
});
expect(composite.cause).toBeInstanceOf(AggregateError);
expect((composite.cause as AggregateError).errors).toEqual([
first,
untyped,
second,
]);
expect((composite.cause as AggregateError).message).toBe(
"Fixture cleanup failed",
);
releaseOwnedCleanup(first);
expect(composite).toMatchObject({
cleanupIncomplete: true,
cleanupResources: ["shared-handle", "second-handle"],
});
releaseOwnedCleanup(second);
expect(composite).toMatchObject({
cleanupIncomplete: false,
cleanupResources: [],
});
});
it("defaults the aggregate cause to the owned failures", () => {
const only = new ProviderCleanupError(
"fixture",
["only-handle"],
{ reason: "only" },
{ operation: "fixture_close" },
);
const composite = providerCleanupErrorFromFailures(
"fixture-provider",
[only],
"Fixture cleanup remains incomplete",
{ operation: "fixture_close" },
);
expect((composite.cause as AggregateError).errors).toEqual([only]);
expect((composite.cause as AggregateError).message).toBe("");
});
it("follows an existing owner's release via withInheritedCleanupOwnership", () => {
const owner = new ProviderCleanupError("fixture", ["owned-handle"], {});
const cleanup = { reason: owner.message, resources: owner.cleanupResources };
const wrapper = withInheritedCleanupOwnership(
new AnalysisCapabilityUnavailableError("fixture", "open", "wrapped", {
cleanup,
}),
owner,
);
expect(wrapper.cleanupIncomplete).toBe(true);
expect(wrapper.cleanupResources).toEqual(["owned-handle"]);
releaseOwnedCleanup(owner);
expect(wrapper.cleanupIncomplete).toBe(false);
expect(wrapper.cleanupResources).toEqual([]);
const unownedCleanup = new AnalysisCapabilityUnavailableError(
"fixture",
"open",
"wrapped",
{
cleanup,
},
);
const retainedUnknown = withInheritedCleanupOwnership(unownedCleanup, owner);
expect(retainedUnknown.cleanupIncomplete).toBe(true);
const cleanOwner = new AnalysisInputError("open", undefined, []);
const cleanWrapper = withInheritedCleanupOwnership(
new AnalysisInputError("open", undefined, []),
cleanOwner,
);
expect(cleanWrapper.hasCleanupOwner).toBe(false);
expect(cleanWrapper.cleanupIncomplete).toBe(false);
});
it("reports a capability refusal as retryable once its cleanup settles", () => {
// The refusal is retryable only after the bound cleanup owner releases, so the
// flag has to follow the live cleanup state rather than the build-time one.
const error = new AnalysisCapabilityUnavailableError(
"ghidra",
"inspect",
"the selected provider is unavailable",
{
retry: "same_call",
cleanup: { reason: "close denied", resources: ["owned-worker"] },
},
);
expect(error.cleanupIncomplete).toBe(true);
expect(error.retryable).toBe(false);
releaseOwnedCleanup(error);
expect(error.cleanupIncomplete).toBe(false);
expect(error.retryable).toBe(true);
});
it("keeps a refusal the owner did not mark retryable non-retryable", () => {
const error = new AnalysisCapabilityUnavailableError(
"ghidra",
"inspect",
"the selected provider is unavailable",
);
expect(error.retryable).toBe(false);
});
it("keeps cleanupIncomplete and cleanupResources consistent when attaching secondary cleanup to a non-cleanup error", () => {
const primary = new AnalysisInputError("open", undefined, []);
const secondary = new ProviderCleanupError("fixture", ["leaked-fd"], {});
withSecondaryCleanupFailure(primary, secondary);
expect(primary.cleanupIncomplete).toBe(true);
expect(primary.cleanupResources).toEqual(["leaked-fd"]);
releaseOwnedCleanup(secondary);
expect(primary.cleanupIncomplete).toBe(false);
expect(primary.cleanupResources).toEqual([]);
primary.bindCleanupDependencies([
new ProviderCleanupError("fixture", ["after-settlement"], {}),
]);
expect(primary.cleanupIncomplete).toBe(false);
expect(primary.cleanupResources).toEqual([]);
});