Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

fix(native): own call preflight hashing through client close

morluto69e670d268cb
diff --git a/src/native/NativeCallObservation.test.ts b/src/native/NativeCallObservation.test.ts
index 15b9b2604..b7f71e1a9 100644
--- a/src/native/NativeCallObservation.test.ts
+++ b/src/native/NativeCallObservation.test.ts
@@ -1,61 +1,104 @@
-import { createHash } from "node:crypto";
-import { writeFile } from "node:fs/promises";
+import { open, writeFile, type FileHandle } from "node:fs/promises";
import { join } from "node:path";
-
-import { describe, expect, it } from "vitest";
-
+import { expect, it, vi, onTestFinished } from "vitest";
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
-import type { JsonValue } from "../domain/jsonValue.js";
+import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { ok, type Result } from "../domain/result.js";
+import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import type { NativeCallTrace, NativeCallTracer } from "./LldbCallTracer.js";
import { observeNativeCalls } from "./NativeCallObservation.js";
-import { nativeMachoTarget } from "../../tests/fixtures/nativeCommands.js";
+import { nativeMachoTargetForFile } from "../../tests/fixtures/nativeCommands.js";
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
class NeverStartedTracer implements NativeCallTracer {
calls = 0;
-
trace(): Promise<Result<NativeCallTrace, AnalysisError>> {
this.calls += 1;
- throw new Error("tracer must not run after hash cancellation");
+ throw new Error("tracer must not run after hash refusal");
}
-
close(): Promise<Result<null, AnalysisError>> {
return Promise.resolve(ok(null));
}
}
-describe("native call target digest cancellation", () => {
- it("returns tagged cancellation when hashing aborts after a chunk", async () => {
- const directory = await createTestTempDirectory("rea-native-digest-");
- const path = join(directory, "fixture");
- const bytes = "selected executable";
- await writeFile(path, bytes);
- const target = {
- ...nativeMachoTarget(path),
- sha256: createHash("sha256").update(bytes).digest("hex"),
- };
- const signal = new AbortController();
- const tracer = new NeverStartedTracer();
+const fixture = async () => {
+ const root = await createTestTempDirectory("rea-native-digest-");
+ const path = join(root, "fixture");
+ await writeFile(path, "selected executable");
+ const target = await nativeMachoTargetForFile(path);
+ const probe = await open(path, "r");
+ const prototype = Object.getPrototypeOf(probe) as FileHandle;
+ await probe.close();
+ const resources = new ArtifactResourceScope();
+ onTestFinished(() => resources.close());
+ return { target, prototype, resources, tracer: new NeverStartedTracer() };
+};
+const parameters = { breakpoints: [{ kind: "function", name: "main" }] };
- const observed = await observeNativeCalls(
+it.each([null, 0, new ProviderCleanupError("foreign", ["unowned"], {})])(
+ "preserves exact hash cancellation reason %s without borrowing authority",
+ async (reason) => {
+ const { target, prototype, resources, tracer } = await fixture();
+ const controller = new AbortController();
+ const original = prototype.read;
+ const read = vi
+ .spyOn(prototype, "read")
+ .mockImplementationOnce(async function (
+ this: FileHandle,
+ ...args: Parameters<FileHandle["read"]>
+ ) {
+ const result = await Reflect.apply(original, this, args);
+ controller.abort(reason);
+ return result;
+ });
+ onTestFinished(() => read.mockRestore());
+ const result = await observeNativeCalls(
target,
- { breakpoints: [{ kind: "function", name: "main" }] } satisfies Record<
- string,
- JsonValue
- >,
+ parameters,
tracer,
- signal.signal,
- async () => {
- signal.abort();
- throw new DOMException("read aborted", "AbortError");
- },
+ resources,
+ controller.signal,
);
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error("Expected owned hash cancellation");
+ expect(result.error).toBeInstanceOf(AnalysisCancelledError);
+ expect(result.error.cause).toBe(reason);
+ expect(result.error.cleanupIncomplete).toBe(false);
+ expect(result.error.cleanupResources).toEqual([]);
+ expect(tracer.calls).toBe(0);
+ },
+);
- expect(!observed.ok && observed.error).toBeInstanceOf(
- AnalysisCancelledError,
+it.each([false, true])(
+ "preserves a physical read failure despite AbortError naming or signal state (aborts: %s)",
+ async (aborts) => {
+ const { target, prototype, resources, tracer } = await fixture();
+ const controller = new AbortController();
+ const failure = aborts
+ ? new Error("physical I/O failure")
+ : new DOMException("unrelated physical AbortError", "AbortError");
+ const read = vi
+ .spyOn(prototype, "read")
+ .mockImplementationOnce(async () => {
+ if (aborts) controller.abort(null);
+ throw failure;
+ });
+ onTestFinished(() => read.mockRestore());
+ const result = await observeNativeCalls(
+ target,
+ parameters,
+ tracer,
+ resources,
+ controller.signal,
);
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error("Expected physical read failure");
+ expect(result.error).toMatchObject({
+ _tag: "ProviderAdapterError",
+ cause: failure,
+ cleanupIncomplete: false,
+ });
expect(tracer.calls).toBe(0);
- });
-});
+ },
+);
diff --git a/src/native/NativeCallObservation.ts b/src/native/NativeCallObservation.ts
index bb3960b56..6b7ec7586 100644
--- a/src/native/NativeCallObservation.ts
+++ b/src/native/NativeCallObservation.ts
@@ -1,9 +1,6 @@
-import { createHash } from "node:crypto";
-import { open } from "node:fs/promises";
-
import {
- AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
+ AnalysisCancelledError,
AnalysisInputError,
} from "../domain/analysisErrorCore.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
@@ -11,7 +8,6 @@ import {
isMachOFormat,
type BinaryTarget,
} from "../domain/binaryTargetTypes.js";
-import { EvidenceIntegrityError } from "../domain/evidenceErrors.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import type { JsonValue } from "../domain/jsonValue.js";
import {
@@ -20,6 +16,11 @@ import {
type NativeCallObservationInput,
type NativeCallObservationResult,
} from "../domain/native/nativeCallObservation.js";
+import {
+ nativeCallTargetFailure,
+ verifyNativeCallTarget,
+} from "./NativeCallTarget.js";
+import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { err, ok, type Result } from "../domain/result.js";
import type { NativeCallTrace, NativeCallTracer } from "./LldbCallTracer.js";
@@ -40,8 +41,8 @@ export const observeNativeCalls = async (
target: BinaryTarget,
parameters: Readonly<Record<string, JsonValue>>,
tracer: NativeCallTracer,
+ resources: ArtifactResourceScope,
signal?: AbortSignal,
- readTargetDigest: typeof fileSha256 = fileSha256,
): Promise<Result<NativeCallObservationResult, AnalysisError>> => {
if (target.kind !== "executable" || !isMachOFormat(target.format))
return err(
@@ -54,46 +55,62 @@ export const observeNativeCalls = async (
const parsed = nativeCallObservationInputSchema.safeParse(parameters);
if (!parsed.success)
return err(new AnalysisInputError(OPERATION, { cause: parsed.error }));
- // Observe the bytes the session's other Evidence describes.
- let digest: string;
try {
- digest = await readTargetDigest(target.path, signal);
+ return await resources.run(async () => {
+ const selected = await verifyNativeCallTarget(target, resources, signal);
+ if (!selected.ok) return selected;
+ if (signal?.aborted)
+ return err(
+ new AnalysisCancelledError(OPERATION, { cause: signal.reason }),
+ );
+ try {
+ const traced = await tracer.trace(
+ {
+ executable: target.path,
+ architecture: target.architecture,
+ expectedSha256: target.sha256,
+ input: parsed.data,
+ },
+ signal,
+ );
+ if (!traced.ok) return traced;
+ const observation = projectNativeCalls(
+ target,
+ parsed.data,
+ traced.value,
+ );
+ return signal?.aborted
+ ? err(
+ new AnalysisCancelledError(OPERATION, {
+ cause: signal.reason,
+ partialObservation: {
+ ...observation,
+ kind: "native-call-observation",
+ coverage: {
+ ...observation.coverage,
+ status: "partial",
+ reason: "cancelled",
+ },
+ },
+ }),
+ )
+ : ok(observation);
+ } catch (cause: unknown) {
+ // Unknown tracer/parser failures carry no file cleanup authority.
+ return err(
+ new ProviderAdapterError("native-macos", OPERATION, {
+ cause,
+ diagnostics: { phase: "trace-result" },
+ }),
+ );
+ }
+ });
} catch (cause: unknown) {
- if (signal?.aborted === true || isAbortError(cause))
- return err(new AnalysisCancelledError(OPERATION));
- return err(
- new ProviderAdapterError("native-macos", OPERATION, {
- diagnostics: {
- reason: "Unable to verify the selected target digest",
- detail: cause instanceof Error ? cause.message : String(cause),
- },
- }),
- );
+ // Only resource admission/retry can reject outside the owned operation.
+ return err(nativeCallTargetFailure(cause, target.path));
}
- if (digest !== target.sha256)
- return err(
- new EvidenceIntegrityError(
- "Native call observation target digest changed after session binding",
- ),
- );
- if (signal?.aborted === true)
- return err(new AnalysisCancelledError(OPERATION));
- const traced = await tracer.trace(
- {
- executable: target.path,
- architecture: target.architecture,
- expectedSha256: target.sha256,
- input: parsed.data,
- },
- signal,
- );
- if (!traced.ok) return traced;
- return ok(projectNativeCalls(target, parsed.data, traced.value));
};
-const isAbortError = (cause: unknown): boolean =>
- cause instanceof Error && cause.name === "AbortError";
-
/** Join the request, the tracer's run and REA's own checks into the result contract. */
export const projectNativeCalls = (
target: Pick<BinaryTarget, "path" | "sha256"> & {
@@ -226,23 +243,3 @@ export const projectNativeCalls = (
],
});
};
-
-const fileSha256 = async (
- path: string,
- signal?: AbortSignal,
-): Promise<string> => {
- const handle = await open(path, "r");
- try {
- const hash = createHash("sha256");
- const buffer = new Uint8Array(1024 * 1024);
- for (;;) {
- signal?.throwIfAborted();
- const { bytesRead } = await handle.read(buffer, 0, buffer.length, null);
- if (bytesRead === 0) break;
- hash.update(buffer.subarray(0, bytesRead));
- }
- return hash.digest("hex");
- } finally {
- await handle.close();
- }
-};
diff --git a/src/native/NativeCallTarget.ts b/src/native/NativeCallTarget.ts
new file mode 100644
index 000000000..e55fd669f
--- /dev/null
+++ b/src/native/NativeCallTarget.ts
@@ -0,0 +1,151 @@
+import { NATIVE_MACOS_PROVIDER_IDENTITY as IDENTITY } from "./NativeMacOSProviderMetadata.js";
+import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
+import type { AnalysisError } from "../domain/analysisErrorBase.js";
+import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
+import { EvidenceIntegrityError } from "../domain/evidenceErrors.js";
+import { ProviderAdapterError } from "../domain/providerAdapterError.js";
+import { ProviderCleanupError } from "../domain/providerCleanupError.js";
+import { jsonValueSchema } from "../domain/jsonValue.js";
+import { err, ok, type Result } from "../domain/result.js";
+import {
+ hashStableFile,
+ stableFileHashCause,
+} from "../filesystem/StableFileHash.js";
+import {
+ RegularFileOperationCancelled,
+ RegularFileChangedError,
+} from "../filesystem/RegularFile.js";
+import {
+ RegularFileCancelled,
+ RegularFileCleanupFailure,
+ regularFileCancellation,
+} from "../filesystem/OwnedRegularFile.js";
+import { AnalysisCleanupLease } from "../artifacts/AnalysisCleanupLease.js";
+import {
+ ArtifactResourceRetryFailure,
+ type ArtifactResourceScope,
+} from "../artifacts/ArtifactResourceScope.js";
+import {
+ ArtifactFileCleanupFailure,
+ bindArtifactFileCleanup,
+} from "../artifacts/ArtifactFileOperation.js";
+
+const OPERATION = "observe_native_calls";
+
+/** Translate this file owner's outcome without inferring cancellation from signal state. */
+export const nativeCallTargetFailure = (
+ cause: unknown,
+ path: string,
+): AnalysisError => {
+ if (
+ cause instanceof ArtifactResourceRetryFailure &&
+ cause.cleanup !== undefined
+ ) {
+ const failure = new ProviderCleanupError(
+ IDENTITY.id,
+ cause.cleanup.resources,
+ { reason: cause.cleanup.reason, phase: "target-digest-retry" },
+ { operation: OPERATION, cause },
+ );
+ bindArtifactFileCleanup(cause, failure);
+ return failure;
+ }
+ if (
+ cause instanceof RegularFileOperationCancelled ||
+ cause instanceof RegularFileCancelled
+ )
+ return new AnalysisCancelledError(OPERATION, {
+ cause: cause.reason,
+ ...(cause instanceof RegularFileCancelled
+ ? {
+ diagnostics: {
+ completed_hash: jsonValueSchema.parse(cause.outcome.value),
+ },
+ }
+ : {}),
+ });
+ const physical = stableFileHashCause(cause);
+ if (physical instanceof RegularFileChangedError)
+ return new EvidenceIntegrityError(
+ "Native call observation target changed during digest verification",
+ { cause: physical },
+ );
+ return new ProviderAdapterError(IDENTITY.id, OPERATION, {
+ cause: physical,
+ diagnostics: {
+ path,
+ phase: "target-digest",
+ reason: "Unable to verify the selected target digest",
+ detail: physical instanceof Error ? physical.message : String(physical),
+ },
+ });
+};
+
+/** Verify one stable regular descriptor, retaining its exact owner if close fails. */
+export const verifyNativeCallTarget = async (
+ target: BinaryTarget,
+ resources: ArtifactResourceScope,
+ signal?: AbortSignal,
+): Promise<Result<void, AnalysisError>> => {
+ let cleanupLease: AnalysisCleanupLease | undefined;
+ try {
+ const digest = await hashStableFile(target.path, {
+ ...(signal === undefined ? {} : { signal }),
+ retainFailedClose: (owner) => {
+ cleanupLease = new AnalysisCleanupLease(
+ () => owner.close(),
+ [target.path],
+ );
+ resources.retain({
+ kind: "lease",
+ resource: target.path,
+ lease: cleanupLease,
+ });
+ },
+ });
+ return digest.sha256 === target.sha256
+ ? ok(undefined)
+ : err(
+ new EvidenceIntegrityError(
+ "Native call observation target digest changed after session binding",
+ ),
+ );
+ } catch (cause: unknown) {
+ if (
+ cause instanceof RegularFileCleanupFailure &&
+ cleanupLease !== undefined
+ ) {
+ const cancellation = regularFileCancellation(cause);
+ const completed =
+ cause.outcome.kind === "completed"
+ ? { completed_hash: jsonValueSchema.parse(cause.outcome.value) }
+ : undefined;
+ const primary =
+ cause.outcome.kind === "failed"
+ ? nativeCallTargetFailure(cause.outcome.cause, target.path)
+ : cancellation === undefined
+ ? undefined
+ : new AnalysisCancelledError(OPERATION, {
+ cause: cancellation.reason,
+ diagnostics: completed,
+ });
+ const framed = new ArtifactFileCleanupFailure(cause, cleanupLease);
+ const failure = new ProviderCleanupError(
+ IDENTITY.id,
+ [target.path],
+ {
+ phase: "target-digest-close",
+ reason:
+ cause.cleanupCause instanceof Error
+ ? cause.cleanupCause.message
+ : String(cause.cleanupCause),
+ ...completed,
+ },
+ { operation: OPERATION, cause: framed, cleanupPrimary: primary },
+ );
+ bindArtifactFileCleanup(framed, failure);
+ return err(failure);
+ }
+ return err(nativeCallTargetFailure(cause, target.path));
+ }
+};
diff --git a/src/native/NativeMacOSProvider.ts b/src/native/NativeMacOSProvider.ts
index 63346df15..16d0ee5ae 100644
--- a/src/native/NativeMacOSProvider.ts
+++ b/src/native/NativeMacOSProvider.ts
@@ -156,6 +156,7 @@ class NativeMacOSClient implements AnalysisClient {
readonly #pendingCommands = new Set<Promise<unknown>>();
readonly #signatureResources = new ArtifactResourceScope();
readonly #plistResources = new ArtifactResourceScope();
+ readonly #callResources = new ArtifactResourceScope();
#nativeUiTail: Promise<void> = Promise.resolve();
#closed = false;
@@ -259,6 +260,7 @@ class NativeMacOSClient implements AnalysisClient {
this.target,
parameters,
this.tracer,
+ this.#callResources,
options?.signal,
);
return result.ok
@@ -309,6 +311,10 @@ class NativeMacOSClient implements AnalysisClient {
this.#plistResources,
"plist-file",
);
+ const callCleanup = await closeNativeFileScope(
+ this.#callResources,
+ "native-call-target",
+ );
const commandCleanup = await this.#retryNativeCommandCleanup();
let result = await this.tracer.close();
const cleanupErrors = [
@@ -318,6 +324,7 @@ class NativeMacOSClient implements AnalysisClient {
...(commandCleanup === undefined ? [] : [commandCleanup]),
...(signatureCleanup === undefined ? [] : [signatureCleanup]),
...(plistCleanup === undefined ? [] : [plistCleanup]),
+ ...(callCleanup === undefined ? [] : [callCleanup]),
];
for (const cleanupError of cleanupErrors)
result = result.ok
diff --git a/tests/boundary/providers/native/nativeCallObservation.test.ts b/tests/boundary/providers/native/nativeCallObservation.test.ts
index c915da0d9..1aea890fc 100644
--- a/tests/boundary/providers/native/nativeCallObservation.test.ts
+++ b/tests/boundary/providers/native/nativeCallObservation.test.ts
@@ -11,6 +11,7 @@ import {
} from "../../../../src/domain/analysisErrorCore.js";
import type { AnalysisError } from "../../../../src/domain/analysisErrorBase.js";
import { EvidenceIntegrityError } from "../../../../src/domain/evidenceErrors.js";
+import { nativeCallPartialObservationSchema } from "../../../../src/domain/native/nativeCallPartialObservation.js";
import { nativeCallObservationResultSchema } from "../../../../src/domain/native/nativeCallObservation.js";
import { err, ok, type Result } from "../../../../src/domain/result.js";
import type {
@@ -463,3 +464,38 @@ describe("observe_native_calls failures", () => {
);
});
});
+
+it("retains completed call facts when cancellation arrives with the tracer result", async () => {
+ const controller = new AbortController();
+ const reason = { caller: "completed-trace-consumption" };
+ const recorded = new FixtureTracer();
+ const result = await observe(
+ {
+ trace: async (request) => {
+ const result = await recorded.trace(request);
+ controller.abort(reason);
+ return result;
+ },
+ close: () => recorded.close(),
+ },
+ { breakpoints: BREAKPOINTS },
+ undefined,
+ controller.signal,
+ );
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error("Expected completion cancellation");
+ expect(result.error).toMatchObject({
+ _tag: "AnalysisCancelledError",
+ cause: reason,
+ });
+ const partial = nativeCallPartialObservationSchema.parse(
+ result.error.partialObservation,
+ );
+ expect(partial.events).toHaveLength(1);
+ expect(partial.process.stdout?.text).toBe("hello\n");
+ expect(partial.process.terminated).toBe(true);
+ expect(partial.coverage).toMatchObject({
+ status: "partial",
+ reason: "cancelled",
+ });
+});
diff --git a/tests/boundary/providers/native/nativeCallTargetCleanup.test.ts b/tests/boundary/providers/native/nativeCallTargetCleanup.test.ts
new file mode 100644
index 000000000..74781d143
--- /dev/null
+++ b/tests/boundary/providers/native/nativeCallTargetCleanup.test.ts
@@ -0,0 +1,282 @@
+import { open, writeFile, type FileHandle } from "node:fs/promises";
+import { join } from "node:path";
+import { expect, it, vi, onTestFinished } from "vitest";
+import { NativeMacOSProvider } from "../../../../src/native/NativeMacOSProvider.js";
+import {
+ NativeFixtureRunner,
+ nativeMachoTargetForFile,
+} from "../../../fixtures/nativeCommands.js";
+import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
+import { AnalysisOutputError } from "../../../../src/domain/analysisErrorCore.js";
+import { resolvedAnalysisError } from "../../../../src/domain/analysisErrorBase.js";
+import { err, ok } from "../../../../src/domain/result.js";
+import { ProviderCleanupError } from "../../../../src/domain/providerCleanupError.js";
+import { ArtifactFileCleanupFailure } from "../../../../src/artifacts/ArtifactFileOperation.js";
+
+const parameters = { breakpoints: [{ kind: "function", name: "main" }] };
+const fixture = async () => {
+ const directory = await createTestTempDirectory("rea-native-call-file-");
+ const path = join(directory, "inert.bin");
+ await writeFile(path, "inert native call preflight bytes");
+ const target = await nativeMachoTargetForFile(path);
+ const probe = await open(path, "r");
+ const prototype = Object.getPrototypeOf(probe) as FileHandle;
+ await probe.close();
+ return { path, target, prototype };
+};
+
+it("retains preflight read failure and exact descriptor across failed client cleanup retries", async () => {
+ const { path, target, prototype } = await fixture();
+ const readFailure = new Error("controlled preflight read failure");
+ const closeFailure = new Error("controlled preflight close failure");
+ let release: (() => Promise<void>) | undefined;
+ let attempts = 0;
+ const read = vi
+ .spyOn(prototype, "read")
+ .mockImplementationOnce(async function (this: FileHandle) {
+ release = this.close.bind(this);
+ this.close = async () => {
+ if (++attempts <= 3) throw closeFailure;
+ await release!();
+ };
+ throw readFailure;
+ });
+ const trace = vi.fn(async () =>
+ err(new AnalysisOutputError("observe_native_calls", "must not trace")),
+ );
+ const client = new NativeMacOSProvider(
+ {},
+ new NativeFixtureRunner(),
+ "darwin",
+ () => ({ trace, close: async () => ok(null) }),
+ ).createClient(target);
+ onTestFinished(async () => {
+ read.mockRestore();
+ await release?.();
+ await client.close();
+ });
+ const result = await client.execute("observe_native_calls", parameters);
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error("Expected retained descriptor cleanup");
+ expect(result.error.cleanupIncomplete).toBe(true);
+ expect(result.error.cleanupResources).toEqual([path]);
+ expect(result.error.cause).toBeInstanceOf(ArtifactFileCleanupFailure);
+ const failure = result.error.cause as ArtifactFileCleanupFailure;
+ expect(failure.fileCleanupFailure.outcome).toEqual({
+ kind: "failed",
+ cause: readFailure,
+ });
+ expect(failure.fileCleanupFailure.cleanupCause).toBe(closeFailure);
+ const retry = await client.execute("observe_native_calls", parameters);
+ expect(retry.ok).toBe(false);
+ if (retry.ok)
+ throw new Error(
+ "Expected retained descriptor to block replacement admission",
+ );
+ expect(retry.error.cleanupIncomplete).toBe(true);
+ expect(read).toHaveBeenCalledTimes(1);
+ const first = await client.close();
+ expect(first.ok).toBe(false);
+ expect(attempts).toBe(3);
+ expect((await client.close()).ok).toBe(true);
+ expect(attempts).toBe(4);
+ expect(retry.error.cleanupIncomplete).toBe(false);
+ expect(retry.error.cleanupResources).toEqual([]);
+ expect(result.error.cleanupIncomplete).toBe(false);
+ expect(result.error.cleanupResources).toEqual([]);
+ expect(resolvedAnalysisError(result.error).cause).toBe(readFailure);
+ if (!first.ok) expect(first.error.cleanupIncomplete).toBe(false);
+ expect(trace).not.toHaveBeenCalled();
+});
+
+it("joins admitted preflight before closing the tracer", async () => {
+ const { target, prototype } = await fixture();
+ let enter!: () => void, resume!: () => void;
+ const entered = new Promise<void>((resolve) => {
+ enter = resolve;
+ });
+ const gate = new Promise<void>((resolve) => {
+ resume = resolve;
+ });
+ const original = prototype.read;
+ const read = vi
+ .spyOn(prototype, "read")
+ .mockImplementationOnce(async function (
+ this: FileHandle,
+ ...args: Parameters<FileHandle["read"]>
+ ) {
+ enter();
+ await gate;
+ return Reflect.apply(original, this, args);
+ });
+ const calls: string[] = [];
+ const client = new NativeMacOSProvider(
+ {},
+ new NativeFixtureRunner(),
+ "darwin",
+ () => ({
+ trace: async () => {
+ calls.push("trace");
+ return err(
+ new AnalysisOutputError(
+ "observe_native_calls",
+ "controlled tracer refusal",
+ ),
+ );
+ },
+ close: async () => {
+ calls.push("close");
+ return ok(null);
+ },
+ }),
+ ).createClient(target);
+ onTestFinished(async () => {
+ resume();
+ await observing;
+ read.mockRestore();
+ await client.close();
+ });
+ const observing = client.execute("observe_native_calls", parameters);
+ await entered;
+ let closed = false;
+ const closing = client.close().then((result) => {
+ closed = true;
+ return result;
+ });
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ expect(closed).toBe(false);
+ resume();
+ expect((await observing).ok).toBe(false);
+ expect((await closing).ok).toBe(true);
+ expect(calls).toEqual(["trace", "close"]);
+});
+
+for (const readFails of [false, true])
+ it(`preserves physical hash outcome when close cancellation also fails (read fails: ${readFails})`, async () => {
+ const { path, target, prototype } = await fixture();
+ const controller = new AbortController();
+ const reason = new ProviderCleanupError("foreign", ["unowned"], {});
+ const primary = new Error("controlled hash read failure");
+ const original = prototype.read;
+ let release: (() => Promise<void>) | undefined;
+ let attempts = 0;
+ const read = vi
+ .spyOn(prototype, "read")
+ .mockImplementationOnce(async function (
+ this: FileHandle,
+ ...args: Parameters<FileHandle["read"]>
+ ) {
+ release = this.close.bind(this);
+ this.close = async () => {
+ if (++attempts === 1) {
+ controller.abort(reason);
+ throw new Error("controlled hash close failure");
+ }
+ await release!();
+ };
+ if (readFails) throw primary;
+ return Reflect.apply(original, this, args);
+ });
+ const trace = vi.fn(async () =>
+ err(new AnalysisOutputError("observe_native_calls", "must not trace")),
+ );
+ const client = new NativeMacOSProvider(
+ {},
+ new NativeFixtureRunner(),
+ "darwin",
+ () => ({ trace, close: async () => ok(null) }),
+ ).createClient(target);
+ onTestFinished(async () => {
+ read.mockRestore();
+ await client.close();
+ await release?.();
+ });
+ const result = await client.execute("observe_native_calls", parameters, {
+ signal: controller.signal,
+ });
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error("Expected retained hash close failure");
+ expect(result.error.cleanupIncomplete).toBe(true);
+ expect(result.error.cleanupResources).toEqual([path]);
+ expect((await client.close()).ok).toBe(true);
+ const resolved = resolvedAnalysisError(result.error);
+ expect(resolved.cause).toBe(readFails ? primary : reason);
+ expect(resolved._tag).toBe(
+ readFails ? "ProviderAdapterError" : "AnalysisCancelledError",
+ );
+ expect(result.error.cleanupResources).toEqual([]);
+ expect(trace).not.toHaveBeenCalled();
+ });
+
+it("retains a completed hash when cancellation arrives after successful descriptor close", async () => {
+ const { target, prototype } = await fixture();
+ const controller = new AbortController();
+ const reason = { caller: "hash-final-close" };
+ const original = prototype.read;
+ const read = vi
+ .spyOn(prototype, "read")
+ .mockImplementationOnce(async function (
+ this: FileHandle,
+ ...args: Parameters<FileHandle["read"]>
+ ) {
+ const closed = this.close.bind(this);
+ this.close = async () => {
+ await closed();
+ controller.abort(reason);
+ };
+ return Reflect.apply(original, this, args);
+ });
+ const trace = vi.fn(async () =>
+ err(new AnalysisOutputError("observe_native_calls", "must not trace")),
+ );
+ const client = new NativeMacOSProvider(
+ {},
+ new NativeFixtureRunner(),
+ "darwin",
+ () => ({ trace, close: async () => ok(null) }),
+ ).createClient(target);
+ onTestFinished(async () => {
+ read.mockRestore();
+ await client.close();
+ });
+ const result = await client.execute("observe_native_calls", parameters, {
+ signal: controller.signal,
+ });
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error("Expected final hash cancellation");
+ expect(result.error).toMatchObject({
+ _tag: "AnalysisCancelledError",
+ cause: reason,
+ cleanupIncomplete: false,
+ diagnostics: { completed_hash: { sha256: target.sha256 } },
+ });
+ expect(trace).not.toHaveBeenCalled();
+});
+
+it("does not adopt an arbitrary thrown tracer cleanup marker", async () => {
+ const { target } = await fixture();
+ const marker = new ProviderCleanupError("foreign", ["unowned"], {});
+ const client = new NativeMacOSProvider(
+ {},
+ new NativeFixtureRunner(),
+ "darwin",
+ () => ({
+ trace: async () => {
+ throw marker;
+ },
+ close: async () => ok(null),
+ }),
+ ).createClient(target);
+ onTestFinished(async () => {
+ await client.close();
+ });
+ const result = await client.execute("observe_native_calls", parameters);
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error("Expected opaque tracer failure");
+ expect(result.error).toMatchObject({
+ _tag: "ProviderAdapterError",
+ cause: marker,
+ cleanupIncomplete: false,
+ });
+ expect(result.error.cleanupResources).toEqual([]);
+});