Skip to content

armgit / rea

Public Imported from GitHub
0

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

fix(filesystem): observe cancellation after file finalization

Ysopwnablec884864876c2
diff --git a/src/adb/AdbProvider.ts b/src/adb/AdbProvider.ts
index ff705ad3a..e8ddd666c 100644
--- a/src/adb/AdbProvider.ts
+++ b/src/adb/AdbProvider.ts
@@ -57,7 +57,10 @@ import { err, ok, type Result } from "../domain/result.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { jsonObjectSchema } from "../domain/jsonValue.js";
import { hashStableFile } from "../filesystem/StableFileHash.js";
-import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js";
+import {
+ RegularFileCancelled,
+ RegularFileCleanupFailure,
+} from "../filesystem/OwnedRegularFile.js";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
import { createEvidence } from "../domain/evidence.js";
import {
@@ -145,9 +148,11 @@ const STDERR_EXCERPT_BYTES = 512;
const UNPARSED_LINES_REPORTED = 10;
/** Carry the exact digest owner through caller-specific partial-result mapping. */
-class AdbDigestCleanupFailure extends Error {
+class AdbDigestFailure extends Error {
constructor(
- readonly fileFailure: RegularFileCleanupFailure<AdbFileDigest>,
+ readonly fileFailure:
+ | RegularFileCleanupFailure<AdbFileDigest>
+ | RegularFileCancelled<AdbFileDigest>,
readonly bindCleanupError: (error: AnalysisError) => void,
) {
super(fileFailure.message, { cause: fileFailure });
@@ -174,9 +179,15 @@ const hashAdbFile = async (
},
});
} catch (cause: unknown) {
- if (cause instanceof RegularFileCleanupFailure)
- throw new AdbDigestCleanupFailure(
- cause as RegularFileCleanupFailure<AdbFileDigest>,
+ if (
+ cause !== signal?.reason &&
+ (cause instanceof RegularFileCleanupFailure ||
+ cause instanceof RegularFileCancelled)
+ )
+ throw new AdbDigestFailure(
+ cause as
+ | RegularFileCleanupFailure<AdbFileDigest>
+ | RegularFileCancelled<AdbFileDigest>,
(error) => {
closeLease?.bindCleanupError(error);
},
@@ -187,7 +198,7 @@ const hashAdbFile = async (
}
};
-const adbDigestCleanupError = (
+const adbDigestError = (
cause: unknown,
operation: string,
signal: AbortSignal | undefined,
@@ -195,7 +206,7 @@ const adbDigestCleanupError = (
| AdbAcquiredFilePartialObservation
| AdbPackagePullPartialObservation,
): AnalysisError | undefined => {
- if (!(cause instanceof AdbDigestCleanupFailure)) return undefined;
+ if (!(cause instanceof AdbDigestFailure)) return undefined;
const digestFailure = cause.fileFailure;
const digestOutcome = digestFailure.outcome;
if (digestOutcome.kind === "completed")
@@ -203,6 +214,11 @@ const adbDigestCleanupError = (
partialObservation,
digestOutcome.value,
);
+ if (digestFailure instanceof RegularFileCancelled)
+ return new AnalysisCancelledError(operation, {
+ cause: digestFailure.reason,
+ partialObservation,
+ });
const resource = `${digestFailure.path} (ADB digest handle)`;
const reason =
digestFailure.cleanupCause instanceof Error
@@ -2290,9 +2306,7 @@ export class AdbProvider {
});
} catch (cause: unknown) {
const digestFailure =
- cause instanceof AdbDigestCleanupFailure
- ? cause.fileFailure
- : undefined;
+ cause instanceof AdbDigestFailure ? cause.fileFailure : undefined;
const completedDigest =
digestFailure?.outcome.kind === "completed"
? digestFailure.outcome.value
@@ -2328,13 +2342,15 @@ export class AdbProvider {
message:
completedDigest === undefined
? `The pulled file remains at ${localPath}, but its digest and descriptor cleanup are unconfirmed.`
- : `The pulled file digest is known, but its descriptor cleanup is unconfirmed: ${localPath}`,
+ : digestFailure instanceof RegularFileCancelled
+ ? `The pulled file digest and descriptor cleanup are confirmed; the request was cancelled: ${localPath}`
+ : `The pulled file digest is known, but its descriptor cleanup is unconfirmed: ${localPath}`,
},
],
coverage: "partial",
},
};
- const cleanupError = adbDigestCleanupError(
+ const cleanupError = adbDigestError(
cause,
operation,
signal,
@@ -2460,7 +2476,7 @@ export class AdbProvider {
digest_status: "unknown",
},
};
- const cleanupError = adbDigestCleanupError(
+ const cleanupError = adbDigestError(
cause,
operation,
signal,
@@ -3287,12 +3303,7 @@ export class AdbProvider {
const cleanupError =
retainedObservation === undefined
? undefined
- : adbDigestCleanupError(
- cause,
- operation,
- signal,
- retainedObservation,
- );
+ : adbDigestError(cause, operation, signal, retainedObservation);
if (cleanupError !== undefined) return err(cleanupError);
if (cause instanceof AnalysisCancelledError) {
if (retainedObservation !== undefined)
diff --git a/src/application/RegularFileRead.ts b/src/application/RegularFileRead.ts
index 85588aed1..4d26e2ca5 100644
--- a/src/application/RegularFileRead.ts
+++ b/src/application/RegularFileRead.ts
@@ -7,6 +7,7 @@ import {
} from "../filesystem/RegularFile.js";
import {
RegularFileCleanupFailure,
+ RegularFileCancelled,
withOwnedRegularFile,
type RegularFileOperationOutcome,
} from "../filesystem/OwnedRegularFile.js";
@@ -67,14 +68,9 @@ export const withRegularFile = async <Value>(
path: string,
read: (handle: FileHandle, stats: Stats) => Promise<Value>,
options: RegularFileReadOptions = {},
-): Promise<Value> => withRegularFileOwned(path, read, options);
-
-const withRegularFileOwned = async <Value>(
- path: string,
- read: (handle: FileHandle, stats: Stats) => Promise<Value>,
- options: RegularFileReadOptions,
): Promise<Value> => {
const { signal, resources } = options;
+ let admitted: FileHandle | undefined;
const operation = async () => {
try {
return await withOwnedRegularFile(
@@ -84,6 +80,7 @@ const withRegularFileOwned = async <Value>(
symlinks: options.symlinks ?? "follow",
},
async (handle) => {
+ admitted = handle;
const stats = await handle.stat();
signal?.throwIfAborted();
const value = await read(handle, stats);
@@ -101,6 +98,12 @@ const withRegularFileOwned = async <Value>(
},
);
} catch (cause: unknown) {
+ if (signal?.aborted === true && cause === signal.reason) throw cause;
+ if (
+ cause instanceof RegularFileCancelled &&
+ cause.owner.handle === admitted
+ )
+ throw cause.reason;
if (
!(cause instanceof RegularFileCleanupFailure) ||
resources === undefined
@@ -112,7 +115,13 @@ const withRegularFileOwned = async <Value>(
return retry.outcome.value;
}
};
- return resources === undefined ? operation() : resources.run(operation);
+ const value = await (resources === undefined
+ ? operation()
+ : resources.run(operation));
+ // A retained close may have recovered after the descriptor owner's outcome
+ // was captured. Include that retry and the scope's finalization in cancellation.
+ signal?.throwIfAborted();
+ return value;
};
/** Admit a regular file without waiting for a pipe, then read its verified handle. */
diff --git a/src/filesystem/OwnedRegularFile.ts b/src/filesystem/OwnedRegularFile.ts
index dc100c6ef..d5e1893ff 100644
--- a/src/filesystem/OwnedRegularFile.ts
+++ b/src/filesystem/OwnedRegularFile.ts
@@ -7,6 +7,34 @@ export type RegularFileOperationOutcome<Value> =
| { readonly kind: "completed"; readonly value: Value }
| { readonly kind: "failed"; readonly cause: unknown };
+type CompletedRegularFileOutcome<Value> = Extract<
+ RegularFileOperationOutcome<Value>,
+ { readonly kind: "completed" }
+>;
+
+/** Cancellation after confirmed close, retaining the completed physical read. */
+export class RegularFileCancelled<Value = unknown> extends Error {
+ readonly _tag = "RegularFileCancelled";
+ readonly outcome: CompletedRegularFileOutcome<Value>;
+ readonly reason: unknown;
+
+ constructor(
+ readonly path: string,
+ readonly owner: OwnedFileHandle,
+ completion: {
+ readonly outcome: CompletedRegularFileOutcome<Value>;
+ readonly reason: unknown;
+ },
+ ) {
+ super(`Regular file operation cancelled after closing ${path}`, {
+ cause: completion.reason,
+ });
+ this.name = this._tag;
+ this.outcome = completion.outcome;
+ this.reason = completion.reason;
+ }
+}
+
/** A failed close transfers its exact descriptor owner and operation outcome. */
export class RegularFileCleanupFailure<Value = unknown> extends Error {
constructor(
@@ -71,6 +99,8 @@ export const withOwnedRegularFile = async <Value>(
try {
await owner.close();
} catch (cleanupCause: unknown) {
+ // Retain the physical read outcome even if the caller cancelled during
+ // close: consumers may need completed observations such as a file digest.
throw new RegularFileCleanupFailure(
path,
owner,
@@ -80,6 +110,11 @@ export const withOwnedRegularFile = async <Value>(
);
}
if (outcome.kind === "failed") throw outcome.cause;
+ if (options.signal?.aborted === true)
+ throw new RegularFileCancelled(path, owner, {
+ outcome,
+ reason: options.signal.reason,
+ });
return outcome.value;
};
diff --git a/tests/boundary/filesystem/regularFileCancellation.test.ts b/tests/boundary/filesystem/regularFileCancellation.test.ts
new file mode 100644
index 000000000..9a36a581e
--- /dev/null
+++ b/tests/boundary/filesystem/regularFileCancellation.test.ts
@@ -0,0 +1,233 @@
+import type { FileHandle } from "node:fs/promises";
+import { open, readFile, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { expect, it, vi } from "vitest";
+
+import { withRegularFile } from "../../../src/application/RegularFileRead.js";
+import { ArtifactResourceScope } from "../../../src/artifacts/ArtifactResourceScope.js";
+import { OwnedFileHandle } from "../../../src/filesystem/OwnedFileHandle.js";
+import {
+ RegularFileCleanupFailure,
+ RegularFileCancelled,
+ withOwnedRegularFile,
+} from "../../../src/filesystem/OwnedRegularFile.js";
+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+
+it("keeps a caller-selected cancellation reason opaque", async () => {
+ const root = await createTestTempDirectory("rea-file-caller-reason-");
+ const path = join(root, "input.txt");
+ await writeFile(path, "fixture bytes");
+ const callerOwner = new OwnedFileHandle(await open(path, "r"));
+ await callerOwner.close();
+ const reason = new RegularFileCancelled(
+ "/caller-selected-path",
+ callerOwner,
+ {
+ outcome: { kind: "completed", value: "caller-owned value" },
+ reason: new Error("nested reason"),
+ },
+ );
+ const controller = new AbortController();
+ controller.abort(reason);
+ const resources = new ArtifactResourceScope();
+ const read = vi.fn(async () => "unexpected");
+ try {
+ await expect(
+ withRegularFile(path, read, { signal: controller.signal, resources }),
+ ).rejects.toBe(reason);
+ expect(read).not.toHaveBeenCalled();
+ expect(resources.hasPending).toBe(false);
+ } finally {
+ await resources.close();
+ }
+});
+
+it.each([false, true])(
+ "preserves a nested read cancellation with the same signal=%s",
+ async (sameSignal) => {
+ const root = await createTestTempDirectory("rea-nested-file-cancel-");
+ const path = join(root, "input.txt");
+ const bytes = Buffer.from("nested read bytes");
+ await writeFile(path, bytes);
+ const outer = new AbortController();
+ const inner = sameSignal ? outer : new AbortController();
+ const reason = new Error("nested caller cancellation");
+ let outerHandle: FileHandle | undefined;
+ let innerHandle: FileHandle | undefined;
+ try {
+ const failure: unknown = await withRegularFile(
+ path,
+ async (handle) => {
+ outerHandle = handle;
+ return withOwnedRegularFile(
+ path,
+ { signal: inner.signal },
+ async (nested) => {
+ innerHandle = nested;
+ const value = await nested.readFile();
+ const close = nested.close.bind(nested);
+ vi.spyOn(nested, "close").mockImplementation(async () => {
+ await close();
+ inner.abort(reason);
+ });
+ return value;
+ },
+ );
+ },
+ { signal: outer.signal },
+ ).catch((cause: unknown) => cause);
+ expect(failure).toBeInstanceOf(RegularFileCancelled);
+ if (!(failure instanceof RegularFileCancelled))
+ throw new Error(
+ "Expected the nested operation's completed observations",
+ );
+ expect(failure.path).toBe(path);
+ expect(failure.reason).toBe(reason);
+ expect(failure.outcome).toEqual({ kind: "completed", value: bytes });
+ expect(failure.owner.handle).toBe(innerHandle);
+ expect(outerHandle?.fd).toBe(-1);
+ expect(innerHandle?.fd).toBe(-1);
+ } finally {
+ vi.restoreAllMocks();
+ }
+ },
+);
+
+it.each(
+ (["metadata", "close"] as const).flatMap((stage) =>
+ [false, true].map((scoped) => ({ stage, scoped })),
+ ),
+)(
+ "observes cancellation after $stage with scope=$scoped",
+ async ({ stage, scoped }) => {
+ const root = await createTestTempDirectory("rea-file-finalization-");
+ const path = join(root, "input.txt");
+ const bytes = Buffer.from("unchanged fixture bytes");
+ await writeFile(path, bytes);
+ const controller = new AbortController();
+ const reason = new Error("cancel during file finalization");
+ const resources = scoped ? new ArtifactResourceScope() : undefined;
+ let admitted: FileHandle | undefined;
+ try {
+ await expect(
+ withRegularFile(
+ path,
+ async (handle) => {
+ admitted = handle;
+ const value = await handle.readFile();
+ if (stage === "metadata") {
+ const stat = handle.stat.bind(handle);
+ vi.spyOn(handle, "stat").mockImplementation(async () => {
+ const metadata = await stat();
+ controller.abort(reason);
+ return metadata;
+ });
+ } else {
+ const close = handle.close.bind(handle);
+ vi.spyOn(handle, "close").mockImplementation(async () => {
+ await close();
+ controller.abort(reason);
+ });
+ }
+ return value;
+ },
+ { signal: controller.signal, ...(resources ? { resources } : {}) },
+ ),
+ ).rejects.toBe(reason);
+ expect(admitted?.fd).toBe(-1);
+ expect(resources?.hasPending ?? false).toBe(false);
+ await resources?.retryCleanup();
+ expect(await readFile(path)).toEqual(bytes);
+ } finally {
+ vi.restoreAllMocks();
+ await resources?.close();
+ }
+ },
+);
+
+it("observes cancellation during a recovered descriptor close", async () => {
+ const root = await createTestTempDirectory("rea-file-retry-cancel-");
+ const path = join(root, "input.txt");
+ await writeFile(path, "fixture bytes");
+ const controller = new AbortController();
+ const reason = new Error("cancel during close retry");
+ const resources = new ArtifactResourceScope();
+ const nativeClose = OwnedFileHandle.prototype.close;
+ let attempts = 0;
+ const close = vi
+ .spyOn(OwnedFileHandle.prototype, "close")
+ .mockImplementation(async function (this: OwnedFileHandle) {
+ if (++attempts === 1) throw new Error("transient close failure");
+ await nativeClose.call(this);
+ controller.abort(reason);
+ });
+ try {
+ await expect(
+ withRegularFile(path, (handle) => handle.readFile(), {
+ signal: controller.signal,
+ resources,
+ }),
+ ).rejects.toBe(reason);
+ expect(attempts).toBe(2);
+ expect(resources.hasPending).toBe(false);
+ await resources.retryCleanup();
+ } finally {
+ close.mockRestore();
+ await resources.close();
+ }
+});
+
+it.each(["completed", "failed"] as const)(
+ "retains the physical read outcome when close fails after cancellation: %s",
+ async (outcome) => {
+ const root = await createTestTempDirectory("rea-file-close-cancel-");
+ const path = join(root, "input.txt");
+ await writeFile(path, "fixture bytes");
+ const controller = new AbortController();
+ const reason = new Error("cancel during failed close");
+ const primary = new Error("existing read failure");
+ const cleanupCause = new Error("injected close failure");
+ const retained: OwnedFileHandle[] = [];
+ const close = vi
+ .spyOn(OwnedFileHandle.prototype, "close")
+ .mockImplementationOnce(async () => {
+ controller.abort(reason);
+ throw cleanupCause;
+ });
+ try {
+ let failure: unknown;
+ try {
+ await withOwnedRegularFile(
+ path,
+ {
+ signal: controller.signal,
+ retainFailedClose: (owner) => retained.push(owner),
+ },
+ async (handle) => {
+ const bytes = await handle.readFile();
+ if (outcome === "failed") throw primary;
+ return bytes;
+ },
+ );
+ } catch (cause: unknown) {
+ failure = cause;
+ }
+ expect(failure).toBeInstanceOf(RegularFileCleanupFailure);
+ if (!(failure instanceof RegularFileCleanupFailure))
+ throw new Error("Expected the retained close owner");
+ expect(failure.outcome).toEqual(
+ outcome === "failed"
+ ? { kind: "failed", cause: primary }
+ : { kind: "completed", value: Buffer.from("fixture bytes") },
+ );
+ expect(controller.signal.reason).toBe(reason);
+ expect(failure.cleanupCause).toBe(cleanupCause);
+ expect(retained).toEqual([failure.owner]);
+ expect(failure.owner.handle.fd).toBeGreaterThanOrEqual(0);
+ } finally {
+ close.mockRestore();
+ await retained[0]?.close();
+ }
+ expect(retained[0]?.handle.fd).toBe(-1);
+ },
+);
diff --git a/tests/boundary/filesystem/stableFileHashOwnership.test.ts b/tests/boundary/filesystem/stableFileHashOwnership.test.ts
index c58f3aeef..e19faaae9 100644
--- a/tests/boundary/filesystem/stableFileHashOwnership.test.ts
+++ b/tests/boundary/filesystem/stableFileHashOwnership.test.ts
@@ -10,7 +10,10 @@ import * as regularFile from "../../../src/filesystem/RegularFile.js";
import { RegularFileAdmissionFailure } from "../../../src/filesystem/RegularFile.js";
import { hashStableFile } from "../../../src/filesystem/StableFileHash.js";
import { LinuxHopperPublisher } from "../../../src/application/LinuxHopperPublisher.js";
-import { RegularFileCleanupFailure } from "../../../src/filesystem/OwnedRegularFile.js";
+import {
+ RegularFileCancelled,
+ RegularFileCleanupFailure,
+} from "../../../src/filesystem/OwnedRegularFile.js";
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
import type { VerifiedLinuxHopperPackage } from "../../../src/application/LinuxHopperPublisher.js";
@@ -125,6 +128,51 @@ it("closes a normally hashed file without adopting an owner", async () => {
expect(retainFailedClose).not.toHaveBeenCalled();
});
+it("retains a completed digest when cancellation follows successful close", async () => {
+ const root = await createTestTempDirectory("rea-stable-hash-cancel-");
+ const path = join(root, "input.bin");
+ const bytes = Buffer.from("owned bytes");
+ await writeFile(path, bytes);
+ const controller = new AbortController();
+ const reason = new Error("caller cancelled during close");
+ const retainFailedClose = vi.fn();
+ const nativeClose = OwnedFileHandle.prototype.close;
+ let observed: OwnedFileHandle | undefined;
+ const close = vi
+ .spyOn(OwnedFileHandle.prototype, "close")
+ .mockImplementationOnce(async function (this: OwnedFileHandle) {
+ observed = this;
+ await nativeClose.call(this);
+ controller.abort(reason);
+ });
+ try {
+ const failure: unknown = await hashStableFile(path, {
+ signal: controller.signal,
+ retainFailedClose,
+ }).catch((cause: unknown) => cause);
+ expect(failure).toBeInstanceOf(RegularFileCancelled);
+ if (!(failure instanceof RegularFileCancelled))
+ throw new Error(
+ "Expected completed file observations under cancellation",
+ );
+ expect(failure.path).toBe(path);
+ expect(failure.reason).toBe(reason);
+ expect(failure.owner).toBe(observed);
+ expect(failure.outcome).toEqual({
+ kind: "completed",
+ value: {
+ bytes: bytes.length,
+ sha256: createHash("sha256").update(bytes).digest("hex"),
+ },
+ });
+ expect(observed?.handle.fd).toBe(-1);
+ expect(retainFailedClose).not.toHaveBeenCalled();
+ } finally {
+ close.mockRestore();
+ await observed?.close();
+ }
+});
+
it("adopts a descriptor from an admission failure and preserves both causes", async () => {
const root = await createTestTempDirectory("rea-stable-hash-admission-");
const path = join(root, "input.bin");
diff --git a/tests/boundary/providers/adb/adbInputSnapshotOwnership.test.ts b/tests/boundary/providers/adb/adbInputSnapshotOwnership.test.ts
index 69aaa4cb2..d3050a1de 100644
--- a/tests/boundary/providers/adb/adbInputSnapshotOwnership.test.ts
+++ b/tests/boundary/providers/adb/adbInputSnapshotOwnership.test.ts
@@ -360,14 +360,16 @@ test.each([
);
test.each([
- { cancelDuringClose: false, failRead: false },
- { cancelDuringClose: true, failRead: false },
- { cancelDuringClose: false, failRead: true },
+ { cancelDuringClose: false, failRead: false, failClose: true },
+ { cancelDuringClose: true, failRead: false, failClose: true },
+ { cancelDuringClose: false, failRead: true, failClose: true },
+ { cancelDuringClose: true, failRead: false, failClose: false },
])(
- "pull preserves the digest outcome when descriptor cleanup fails (%#)",
- async ({ cancelDuringClose, failRead }) => {
+ "pull preserves the digest outcome through descriptor finalization (%#)",
+ async ({ cancelDuringClose, failRead, failClose }) => {
const f = await fixture();
const controller = new AbortController();
+ const reason = new Error("caller cancelled during digest close");
const actualFs =
await vi.importActual<typeof import("node:fs/promises")>(
"node:fs/promises",
@@ -392,11 +394,13 @@ test.each([
const close = handle.close.bind(handle);
handle.close = async () => {
closeAttempts += 1;
- if (closeAttempts === 1) {
- if (cancelDuringClose) controller.abort();
+ if (closeAttempts === 1 && failClose) {
+ if (cancelDuringClose) controller.abort(reason);
throw new Error("controlled descriptor close");
}
await close();
+ if (closeAttempts === 1 && cancelDuringClose)
+ controller.abort(reason);
};
}
return handle;
@@ -418,10 +422,15 @@ test.each([
expect(result.error._tag).toBe(
cancelDuringClose ? "AnalysisCancelledError" : "ProviderAdapterError",
);
- expect(result.error.cleanupIncomplete).toBe(true);
- expect(result.error.cleanupResources).toContain(
- `${localPath} (ADB digest handle)`,
- );
+ expect(result.error.cleanupIncomplete).toBe(failClose);
+ if (failClose)
+ expect(result.error.cleanupResources).toContain(
+ `${localPath} (ADB digest handle)`,
+ );
+ else {
+ expect(result.error.cleanupResources).toEqual([]);
+ expect(result.error.cause).toBe(reason);
+ }
expect(result.error.partialObservation).toMatchObject({
provider_id: "adb",
operation: "pull_adb_file",
@@ -439,102 +448,118 @@ test.each([
await expect(readFile(localPath)).resolves.toEqual(pulledBytes);
const originatingError = result.error;
await f.provider.close();
- expect(closeAttempts).toBe(2);
+ expect(closeAttempts).toBe(failClose ? 2 : 1);
expect(originatingError.cleanupIncomplete).toBe(false);
},
);
-test("package pull keeps earlier and completed artifacts when the digest handle cannot close", async () => {
- const f = await fixture();
- const actualFs =
- await vi.importActual<typeof import("node:fs/promises")>(
- "node:fs/promises",
- );
- const outputDirectory = join(f.root, "package-output");
- const packageDirectory = join(outputDirectory, "com.example.app");
- const splitPath = join(packageDirectory, "split.apk");
- const baseBytes = Buffer.from("base apk");
- const splitBytes = Buffer.from("split apk");
- let closeAttempts = 0;
- const version = `Android Debug Bridge version 1.0.41\nVersion 34.0.5-stub\nInstalled as ${f.root}/adb\n`;
- vi.mocked(execFileOutput).mockImplementation(async (_binary, args) => {
- if (args[0] === "version")
- return {
- stdout: version,
- stderr: "",
- stdoutBytes: Buffer.byteLength(version),
- stderrBytes: 0,
- };
- return { stdout: "", stderr: "", stdoutBytes: 0, stderrBytes: 0 };
- });
- vi.mocked(execFileBytes).mockImplementation(async (_binary, args) => {
- if (args.includes("path"))
- return {
- stdout: Buffer.from(
- "package:/data/app/com.example.app/base.apk\npackage:/data/app/com.example.app/split.apk\n",
- ),
- stderr: Buffer.alloc(0),
- };
- if (args[2] === "pull")
- await actualFs.writeFile(
- args[4]!,
- args[3]!.endsWith("base.apk") ? baseBytes : splitBytes,
+test.each([false, true])(
+ "package pull retains digests through close or cancellation (%s)",
+ async (cancelDuringClose) => {
+ const f = await fixture();
+ const actualFs =
+ await vi.importActual<typeof import("node:fs/promises")>(
+ "node:fs/promises",
);
- return { stdout: Buffer.alloc(0), stderr: Buffer.alloc(0) };
- });
- vi.mocked(open).mockImplementation(async (path, ...args) => {
- const handle = await actualFs.open(path, ...args);
- if (String(path) === splitPath) {
- const close = handle.close.bind(handle);
- handle.close = async () => {
- closeAttempts += 1;
- if (closeAttempts === 1) throw new Error("controlled descriptor close");
- await close();
- };
- }
- return handle;
- });
+ const outputDirectory = join(f.root, "package-output");
+ const packageDirectory = join(outputDirectory, "com.example.app");
+ const splitPath = join(packageDirectory, "split.apk");
+ const baseBytes = Buffer.from("base apk");
+ const splitBytes = Buffer.from("split apk");
+ const controller = new AbortController();
+ const reason = new Error("caller cancelled after split digest close");
+ let closeAttempts = 0;
+ const version = `Android Debug Bridge version 1.0.41\nVersion 34.0.5-stub\nInstalled as ${f.root}/adb\n`;
+ vi.mocked(execFileOutput).mockImplementation(async (_binary, args) => {
+ if (args[0] === "version")
+ return {
+ stdout: version,
+ stderr: "",
+ stdoutBytes: Buffer.byteLength(version),
+ stderrBytes: 0,
+ };
+ return { stdout: "", stderr: "", stdoutBytes: 0, stderrBytes: 0 };
+ });
+ vi.mocked(execFileBytes).mockImplementation(async (_binary, args) => {
+ if (args.includes("path"))
+ return {
+ stdout: Buffer.from(
+ "package:/data/app/com.example.app/base.apk\npackage:/data/app/com.example.app/split.apk\n",
+ ),
+ stderr: Buffer.alloc(0),
+ };
+ if (args[2] === "pull")
+ await actualFs.writeFile(
+ args[4]!,
+ args[3]!.endsWith("base.apk") ? baseBytes : splitBytes,
+ );
+ return { stdout: Buffer.alloc(0), stderr: Buffer.alloc(0) };
+ });
+ vi.mocked(open).mockImplementation(async (path, ...args) => {
+ const handle = await actualFs.open(path, ...args);
+ if (String(path) === splitPath) {
+ const close = handle.close.bind(handle);
+ handle.close = async () => {
+ closeAttempts += 1;
+ if (closeAttempts === 1 && !cancelDuringClose)
+ throw new Error("controlled descriptor close");
+ await close();
+ if (closeAttempts === 1 && cancelDuringClose)
+ controller.abort(reason);
+ };
+ }
+ return handle;
+ });
- const result = await f.provider.execute({
- operation: "pull_adb_package",
- input: {
- serial: "device",
- package: "com.example.app",
- output_directory: outputDirectory,
- },
- });
- expect(result.ok).toBe(false);
- if (result.ok)
- throw new Error("expected retained package digest cleanup failure");
- expect(result.error.cleanupIncomplete).toBe(true);
- expect(result.error.partialObservation).toMatchObject({
- provider_id: "adb",
- operation: "pull_adb_package",
- result: {
- coverage: "partial",
- artifacts: [
- {
- local_path: join(packageDirectory, "base.apk"),
- bytes: baseBytes.byteLength,
- sha256: createHash("sha256").update(baseBytes).digest("hex"),
- },
- {
- local_path: splitPath,
- bytes: splitBytes.byteLength,
- sha256: createHash("sha256").update(splitBytes).digest("hex"),
- },
- ],
- failures: [
- {
- stage: "digest",
- device_path: "/data/app/com.example.app/split.apk",
+ const result = await f.provider.execute(
+ {
+ operation: "pull_adb_package",
+ input: {
+ serial: "device",
+ package: "com.example.app",
+ output_directory: outputDirectory,
},
- ],
- },
- });
- await f.provider.close();
- expect(closeAttempts).toBe(2);
-});
+ },
+ cancelDuringClose ? { signal: controller.signal } : undefined,
+ );
+ expect(result.ok).toBe(false);
+ if (result.ok)
+ throw new Error("expected retained package digest cleanup failure");
+ expect(result.error.cleanupIncomplete).toBe(!cancelDuringClose);
+ if (cancelDuringClose) {
+ expect(result.error._tag).toBe("AnalysisCancelledError");
+ expect(result.error.cause).toBe(reason);
+ expect(result.error.cleanupResources).toEqual([]);
+ }
+ expect(result.error.partialObservation).toMatchObject({
+ provider_id: "adb",
+ operation: "pull_adb_package",
+ result: {
+ coverage: "partial",
+ artifacts: [
+ {
+ local_path: join(packageDirectory, "base.apk"),
+ bytes: baseBytes.byteLength,
+ sha256: createHash("sha256").update(baseBytes).digest("hex"),
+ },
+ {
+ local_path: splitPath,
+ bytes: splitBytes.byteLength,
+ sha256: createHash("sha256").update(splitBytes).digest("hex"),
+ },
+ ],
+ failures: [
+ {
+ stage: "digest",
+ device_path: "/data/app/com.example.app/split.apk",
+ },
+ ],
+ },
+ });
+ await f.provider.close();
+ expect(closeAttempts).toBe(cancelDuringClose ? 1 : 2);
+ },
+);
test("resolves package-directory cleanup on the originating pull error", async () => {
const f = await fixture();
diff --git a/tests/boundary/providers/kuna/kunaInstallationLifetime.test.ts b/tests/boundary/providers/kuna/kunaInstallationLifetime.test.ts
index d8c987e5a..764a12a32 100644
--- a/tests/boundary/providers/kuna/kunaInstallationLifetime.test.ts
+++ b/tests/boundary/providers/kuna/kunaInstallationLifetime.test.ts
@@ -1,31 +1,21 @@
-import { afterEach, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
const gates = vi.hoisted(() => {
- let releaseHashClose!: () => void;
- let releaseShebangRead!: () => void;
- let hashCloseEntered!: () => void;
- let shebangReadEntered!: () => void;
- const hashClose = new Promise<void>((resolve) => {
- releaseHashClose = resolve;
- });
- const shebangRead = new Promise<void>((resolve) => {
- releaseShebangRead = resolve;
- });
- const hashCloseStarted = new Promise<void>((resolve) => {
- hashCloseEntered = resolve;
- });
- const shebangReadStarted = new Promise<void>((resolve) => {
- shebangReadEntered = resolve;
- });
+ const createGate = () => {
+ let enter!: () => void;
+ let release!: () => void;
+ const started = new Promise<void>((resolve) => {
+ enter = resolve;
+ });
+ const hold = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ return { started, hold, enter, release };
+ };
return {
- hashClose,
- hashCloseStarted,
- shebangRead,
- shebangReadStarted,
- releaseHashClose,
- releaseShebangRead,
- hashCloseEntered,
- shebangReadEntered,
+ createGate,
+ hashClose: createGate(),
+ shebangRead: createGate(),
opens: 0,
};
});
@@ -49,15 +39,15 @@ vi.mock("../../../../src/filesystem/RegularFile.js", async (importOriginal) => {
handle.stat(...statArgs),
read: async (...readArgs: Parameters<typeof handle.read>) => {
if (index === 1) {
- gates.shebangReadEntered();
- await gates.shebangRead;
+ gates.shebangRead.enter();
+ await gates.shebangRead.hold;
}
return handle.read(...readArgs);
},
close: async () => {
if (index === 0) {
- gates.hashCloseEntered();
- await gates.hashClose;
+ gates.hashClose.enter();
+ await gates.hashClose.hold;
}
await handle.close();
},
@@ -73,14 +63,22 @@ import { inspectKunaInstallation } from "../../../../src/kuna/KunaInstallation.j
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { writeFakeKuna } from "./fakeKuna.js";
+beforeEach(() => {
+ gates.opens = 0;
+ gates.hashClose = gates.createGate();
+ gates.shebangRead = gates.createGate();
+});
+
afterEach(() => {
- gates.releaseHashClose();
- gates.releaseShebangRead();
+ gates.hashClose.release();
+ gates.shebangRead.release();
});
-it.skipIf(process.platform === "win32")(
- "keeps installation inspection inside the resource owner's lifetime through shebang reading",
- async () => {
+it
+ .skipIf(process.platform === "win32")
+ .each(["hash-close", "shebang-read"] as const)(
+ "keeps installation cleanup waiting for its active phase when cancelled during %s",
+ async (phase) => {
const root = await createTestTempDirectory("rea-kuna-inspection-lifetime-");
const executable = await writeFakeKuna(root);
const scope = new ArtifactResourceScope();
@@ -105,32 +103,38 @@ it.skipIf(process.platform === "win32")(
);
let cleanup: Promise<void> | undefined;
try {
- await gates.hashCloseStarted;
+ await gates.hashClose.started;
cleanup = scope.retryCleanup();
- controller.abort();
- gates.releaseHashClose();
- const reachedShebang = await Promise.race([
- gates.shebangReadStarted.then(() => true),
- inspection.then(
- () => false,
- () => false,
- ),
- ]);
- expect(reachedShebang).toBe(true);
-
let cleanupFinished = false;
void cleanup.then(() => {
cleanupFinished = true;
});
await Promise.resolve();
expect(cleanupFinished).toBe(false);
+ if (phase === "hash-close") controller.abort();
+ gates.hashClose.release();
+ const reachedShebang = await Promise.race([
+ gates.shebangRead.started.then(() => true),
+ inspection.then(
+ () => false,
+ () => false,
+ ),
+ ]);
+ expect(reachedShebang).toBe(phase === "shebang-read");
+ if (phase === "shebang-read") {
+ controller.abort();
+ await Promise.resolve();
+ expect(cleanupFinished).toBe(false);
+ }
- gates.releaseShebangRead();
- await expect(inspection).rejects.toMatchObject({ name: "AbortError" });
+ gates.shebangRead.release();
+ await expect(inspection).rejects.toBe(controller.signal.reason);
await expect(cleanup).resolves.toBeUndefined();
+ expect(gates.opens).toBe(phase === "hash-close" ? 1 : 2);
+ expect(scope.hasPending).toBe(false);
} finally {
- gates.releaseHashClose();
- gates.releaseShebangRead();
+ gates.hashClose.release();
+ gates.shebangRead.release();
await inspectionOutcome;
await cleanup;
await scope.close();