Reverse engineer anything with agents, from app behavior down to native binaries.
TypeScript agent-skillsai-agentsbinary-analysisclaude-codeclicodexcordisdecompilerdeveloper-toolsdshdsh-pluginghidrahopperllmmcpmodel-context-protocolreareverse-engineeringstatic-analysistouhou
fix(pcap): preserve cancellation and endpoint evidence through cleanup
morluto419502c8d069
diff --git a/src/pcap/PcapCommand.ts b/src/pcap/PcapCommand.tsindex c5d61fef1..be4ea4564 100644--- a/src/pcap/PcapCommand.ts+++ b/src/pcap/PcapCommand.ts@@ -10,10 +10,10 @@ import {import {OwnedCommandFailure,ownedCommandResources,+ prepareOwnedCommand,runOwnedCommand,} from "../process/OwnedCommand.js";import type { ProviderProcessSupervisor } from "../process/ProviderProcess.js";-import { prepareProcessOwnershipInspection } from "../process/ProcessOwnershipObservation.js";import {isWindowsBatchFile,windowsBatchCommand,@@ -99,7 +99,7 @@ export const runPcapCommand = async (options: {};// Native ownership preparation has its own bounded compiler lifecycle;// do not spend the tool's execution deadline rebuilding a cold SDK cache.- await prepareProcessOwnershipInspection(signal);+ await prepareOwnedCommand(signal);const output = await runOwnedCommand({...boundedInvocation,@@ -184,11 +184,11 @@ export const runPcapCommand = async (options: {}: {}),};- if (- signal?.aborted ||- (cause instanceof OwnedCommandFailure && cause.reason === "cancelled")- )- throw new AnalysisCancelledError(operation, details);+ if (cause instanceof OwnedCommandFailure && cause.reason === "cancelled")+ throw new AnalysisCancelledError(operation, {+ ...details,+ cause: cause.cancellation?.reason,+ });if (cause instanceof OwnedCommandFailure &&cause.snapshot?.memoryLimitReached === truediff --git a/src/pcap/PcapOutput.test.ts b/src/pcap/PcapOutput.test.tsindex c0e158438..12569151f 100644--- a/src/pcap/PcapOutput.test.ts+++ b/src/pcap/PcapOutput.test.ts@@ -1,4 +1,6 @@import { expect, it } from "vitest";+import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";+import { ProviderCleanupError } from "../domain/providerCleanupError.js";import { parseCapinfosOutput, parseTsharkJsonOutput } from "./PcapOutput.js";const capture = (layers: ReadonlyArray<Record<string, string[]>>) =>@@ -156,12 +158,26 @@ it("refuses dense JSON before its expanded graph exceeds the decoding budget", a});});-it("permits cancellation while validating and aggregating producer output", async () => {- const controller = new AbortController();- const result = parseTsharkJsonOutput(- capture([{ "ip.src": ["192.0.2.1"] }]),- controller.signal,- );- controller.abort(new Error("stopped"));- await expect(result).rejects.toThrow("stopped");-});+it.each([+ null,+ "stopped",+ new ProviderCleanupError("caller", ["foreign-resource"], {}),+])(+ "preserves opaque cancellation while validating producer output: %s",+ async (reason) => {+ const controller = new AbortController();+ const result = parseTsharkJsonOutput(+ capture([{ "ip.src": ["192.0.2.1"] }]),+ controller.signal,+ );+ controller.abort(reason);+ const failure = await result.catch((cause: unknown) => cause);+ expect(failure).toBeInstanceOf(AnalysisCancelledError);+ if (!(failure instanceof AnalysisCancelledError)) throw failure;+ expect(failure.cause).toBe(reason);+ expect(failure.cleanupIncomplete).toBe(false);+ expect(failure.cleanupResources).toEqual([]);+ if (reason instanceof ProviderCleanupError)+ expect(reason.cleanupIncomplete).toBe(true);+ },+);diff --git a/src/pcap/PcapOutput.ts b/src/pcap/PcapOutput.tsindex 9a9838f58..3944d3871 100644--- a/src/pcap/PcapOutput.ts+++ b/src/pcap/PcapOutput.ts@@ -1,5 +1,6 @@import { setImmediate as yieldToEventLoop } from "node:timers/promises";import {+ AnalysisCancelledError,AnalysisProtocolError,AnalysisResourceConstraintError,} from "../domain/analysisErrorCore.js";@@ -12,6 +13,11 @@ export const TSHARK_JSON_MAX_BYTES = 8 * 1024 * 1024;const MAX_RETAINED_BYTES = 16 * 1024 * 1024;const MAX_DECODED_BYTES = 128 * 1024 * 1024;+const assertOutputReadActive = (signal: AbortSignal | undefined): void => {+ if (signal?.aborted)+ throw new AnalysisCancelledError(OPERATION, { cause: signal.reason });+};+const protocolFailure = (reason: string): never => {throw new AnalysisProtocolError(`Invalid packet-capture output: ${reason}`);};@@ -148,7 +154,7 @@ export const parseTsharkJsonOutput = async (stdout: string,signal?: AbortSignal,): Promise<TsharkFields> => {- signal?.throwIfAborted();+ assertOutputReadActive(signal);if (Buffer.byteLength(stdout) > TSHARK_JSON_MAX_BYTES)throw new AnalysisResourceConstraintError(OPERATION,@@ -165,7 +171,7 @@ export const parseTsharkJsonOutput = async (for (let index = 0; index < stdout.length; index += 1) {if (index % 65536 === 0) {await yieldToEventLoop();- signal?.throwIfAborted();+ assertOutputReadActive(signal);}const char = stdout[index];if (quoted) {@@ -225,7 +231,7 @@ export const parseTsharkJsonOutput = async (for (let index = 0; index < packets.length; index += 1) {if (index % 256 === 0) {await yieldToEventLoop();- signal?.throwIfAborted();+ assertOutputReadActive(signal);}const packet: unknown = packets[index];if (@@ -320,7 +326,7 @@ export const parseTsharkJsonOutput = async ();}}- signal?.throwIfAborted();+ assertOutputReadActive(signal);return {endpoints: [...endpoints].sort((a, b) => b[1] - a[1] || compareUnicodeCodePoints(a[0], b[0]))diff --git a/src/pcap/PcapProvider.ts b/src/pcap/PcapProvider.tsindex 420557584..304f99b77 100644--- a/src/pcap/PcapProvider.ts+++ b/src/pcap/PcapProvider.ts@@ -92,6 +92,9 @@ const pcapPartialEvidence = (locations: [{ kind: "artifact-path", path }],});+/** Completed Pcap output whose only failure is its retained command cleanup. */+class PcapCommandCleanupError extends ProviderCleanupError {}+const pcapCommandCleanupError = (operation: PcapOperation,snapshotPath: string | undefined,@@ -99,7 +102,7 @@ const pcapCommandCleanupError = (capturedOutput: { readonly stdout: string; readonly stderr: string },partialObservation?: ReturnType<typeof pcapPartialEvidence>,) =>- new ProviderCleanupError(+ new PcapCommandCleanupError("pcap",[...new Set([@@ -133,7 +136,14 @@ interface RetainedPcapCommand {readonly reason: string;readonly capturedOutput: PcapCommandCleanup["capturedOutput"];ownerReleased: boolean;- failure: ProviderCleanupError | undefined;+ failure: AnalysisError | undefined;+}++interface RetainedSnapshotFailure {+ /** Exact error returned to the caller for the originating analysis. */+ readonly returned: AnalysisError;+ /** Snapshot-owned failure resolved only by a successful snapshot close. */+ readonly snapshot: AnalysisError;}/** Inspect saved captures through bounded, owned tool processes and one stable input copy. */@@ -151,7 +161,10 @@ export class PcapProvider {private readonly environment: Readonly<Record<string, string | undefined>>;private readonly launcher: PcapCommandLauncher | undefined;private readonly snapshots = new Set<PcapSnapshot>();- private readonly snapshotFailures = new Map<PcapSnapshot, AnalysisError>();+ private readonly snapshotFailures = new Map<+ PcapSnapshot,+ RetainedSnapshotFailure+ >();private readonly commands = new Map<ProviderProcessSupervisor,RetainedPcapCommand@@ -173,37 +186,48 @@ export class PcapProvider {) {let cleanup: PcapCommandCleanup | undefined;let retainedCommand: RetainedPcapCommand | undefined;- const output = await runPcapCommand({- operation,- command,- arguments: args,- limits,- signal,- environment:- snapshot === undefined- ? this.environment- : {- ...this.environment,- WIRESHARK_CONFIG_DIR: snapshot.configurationPath,- },- ...(inputPath === undefined ? {} : { inputPath }),- ...(inputPath === undefined || this.nativeBound === undefined- ? {}- : { nativeBound: this.nativeBound }),- ...(this.launcher === undefined ? {} : { launcher: this.launcher }),- retain: (owner, resources, reason, capturedOutput) => {- retainedCommand = {- snapshot,- resources,- reason,- capturedOutput,- ownerReleased: false,- failure: undefined,- };- this.commands.set(owner, retainedCommand);- cleanup = { reason, resources, capturedOutput };- },- });+ let output: Awaited<ReturnType<typeof runPcapCommand>>;+ try {+ output = await runPcapCommand({+ operation,+ command,+ arguments: args,+ limits,+ signal,+ environment:+ snapshot === undefined+ ? this.environment+ : {+ ...this.environment,+ WIRESHARK_CONFIG_DIR: snapshot.configurationPath,+ },+ ...(inputPath === undefined ? {} : { inputPath }),+ ...(inputPath === undefined || this.nativeBound === undefined+ ? {}+ : { nativeBound: this.nativeBound }),+ ...(this.launcher === undefined ? {} : { launcher: this.launcher }),+ retain: (owner, resources, reason, capturedOutput) => {+ retainedCommand = {+ snapshot,+ resources,+ reason,+ capturedOutput,+ ownerReleased: false,+ failure: undefined,+ };+ this.commands.set(owner, retainedCommand);+ cleanup = { reason, resources, capturedOutput };+ },+ });+ } catch (cause) {+ if (+ retainedCommand !== undefined &&+ cause instanceof AnalysisError &&+ cause.cleanupIncomplete+ )+ retainedCommand.failure = cause;+ throw cause;+ }if (inputPath === undefined && cleanup !== undefined) {const failure = new ProviderCleanupError("pcap",@@ -278,10 +302,11 @@ export class PcapProvider {async inspectAvailability(signal?: AbortSignal,): Promise<ProviderAvailability> {- const result = await this.#resources.run(- async () => ok(await this.inspectAvailabilityAdmitted(signal)),- signal,- );+ const result = await this.#resources.run(async () => {+ const cleanup = this.pendingCleanupFailure("inspect_pcap_client");+ if (cleanup !== undefined) throw cleanup;+ return ok(await this.inspectAvailabilityAdmitted(signal));+ }, signal);if (!result.ok) throw result.error;return result.value;}@@ -307,9 +332,11 @@ export class PcapProvider {diagnostics: client,};} catch (cause) {- if (cause instanceof ProviderCleanupError) throw cause;- if (signal?.aborted || cause instanceof AnalysisCancelledError)- throw new AnalysisCancelledError("inspect_pcap_client", { cause });+ if (+ cause instanceof ProviderCleanupError ||+ cause instanceof AnalysisCancelledError+ )+ throw cause;if (cause instanceof PcapConfigurationFailure)return pcapConfigurationAvailability(cause);return {@@ -338,7 +365,9 @@ export class PcapProvider {);await snapshot.close();this.snapshots.delete(snapshot);- this.snapshotFailures.get(snapshot)?.resolveCleanup();+ const retainedFailure = this.snapshotFailures.get(snapshot);+ retainedFailure?.snapshot.resolveCleanup();+ retainedFailure?.returned.resolveCleanup();this.snapshotFailures.delete(snapshot);return undefined;} catch (cause) {@@ -351,15 +380,50 @@ export class PcapProvider {}}+ /** Refuse new work while a prior command or snapshot still has a cleanup owner. */+ private pendingCleanupFailure(+ operation: string,+ ): ProviderCleanupError | undefined {+ const retainedCommands = [...this.commands.values()].filter(+ (command) => !command.ownerReleased,+ );+ if (retainedCommands.length === 0 && this.snapshots.size === 0)+ return undefined;+ const dependencies = [+ ...retainedCommands.flatMap((command) =>+ command.failure === undefined ? [] : [command.failure],+ ),+ ...[...this.snapshotFailures.values()].map(({ snapshot }) => snapshot),+ ];+ return new ProviderCleanupError(+ "pcap",+ [+ ...[...this.snapshots].map((snapshot) => snapshot.path),+ ...retainedCommands.flatMap((command) => command.resources),+ ],+ { reason: "Previous packet-capture resources remain owned." },+ { operation },+ ).bindCleanupDependencies(dependencies);+ }+async close(): Promise<void> {const failures: unknown[] = [];+ let artifactCleanupFailure: AnalysisError | undefined;try {await this.#resources.close();} catch (cause) {failures.push(cause);+ if (cause instanceof AnalysisError && cause.cleanupIncomplete)+ artifactCleanupFailure = cause;}for (const [owner, command] of this.commands) {if (command.ownerReleased) continue;+ command.failure ??= new ProviderCleanupError(+ "pcap",+ command.resources,+ { reason: command.reason },+ { operation: "pcap.close" },+ );try {const result = await owner.stop();if (result.status === "incomplete") failures.push(result.reason);@@ -367,8 +431,8 @@ export class PcapProvider {failures.push("Command ownership remains unresolved");else {command.ownerReleased = true;+ command.failure?.resolveCleanup();if (command.snapshot === undefined) {- command.failure?.resolveCleanup();this.commands.delete(owner);}}@@ -376,6 +440,19 @@ export class PcapProvider {failures.push(cause);}}+ for (const snapshot of this.snapshots) {+ if (this.snapshotFailures.has(snapshot)) continue;+ const failure = new ProviderCleanupError(+ "pcap",+ [snapshot.path],+ { reason: "Capture snapshot cleanup remains unresolved." },+ { operation: "pcap.close" },+ );+ this.snapshotFailures.set(snapshot, {+ returned: failure,+ snapshot: failure,+ });+ }for (const snapshot of this.snapshots) {const failure = await this.discard(snapshot);if (failure !== undefined) {@@ -387,27 +464,49 @@ export class PcapProvider {}}}- if (failures.length > 0)- throw new ProviderCleanupError(+ if (failures.length > 0) {+ const cleanup = new ProviderCleanupError("pcap",- [...this.snapshots]- .map((snapshot) => snapshot.path)- .concat(- [...this.commands.values()].flatMap((command) => command.resources),- ),+ [+ ...(artifactCleanupFailure?.cleanupResources ?? []),+ ...[...this.snapshots]+ .map((snapshot) => snapshot.path)+ .concat(+ [...this.commands.values()]+ .filter((command) => !command.ownerReleased)+ .flatMap((command) => command.resources),+ ),+ ],{ reason: "Owned process or snapshot cleanup failed" },{ operation: "pcap.close", cause: new AggregateError(failures) },);+ const dependencies = [+ ...(artifactCleanupFailure === undefined+ ? []+ : [artifactCleanupFailure]),+ ...[...this.commands.values()]+ .filter((command) => !command.ownerReleased)+ .flatMap((command) =>+ command.failure === undefined ? [] : [command.failure],+ ),+ ...[...this.snapshotFailures.values()].map(({ snapshot }) => snapshot),+ ];+ if (dependencies.length > 0)+ cleanup.bindCleanupDependencies([...new Set(dependencies)]);+ throw cleanup;+ }}async execute(request: PcapRequest,options?: ExecutionOptions,): Promise<Result<AnalysisExecution, AnalysisError>> {- return this.#resources.run(- () => this.executeAdmitted(request, options),- options?.signal,- );+ return this.#resources.run(() => {+ const cleanup = this.pendingCleanupFailure(request.operation);+ return cleanup === undefined+ ? this.executeAdmitted(request, options)+ : Promise.resolve(err(cleanup));+ }, options?.signal);}private async executeAdmitted(@@ -418,7 +517,10 @@ export class PcapProvider {let snapshot: PcapSnapshot | undefined;let result: Result<AnalysisExecution, AnalysisError>;try {- signal?.throwIfAborted();+ if (signal?.aborted)+ throw new AnalysisCancelledError(request.operation, {+ cause: signal.reason,+ });const { selection, client } = await this.client(request.operation,signal,@@ -468,16 +570,14 @@ export class PcapProvider {result = err(cause instanceof AnalysisError? cause- : signal?.aborted- ? new AnalysisCancelledError(request.operation, { cause })- : cause instanceof PcapConfigurationFailure- ? pcapToolUnavailable(request.operation, cause.message, {- cause,- })- : new AnalysisProtocolError(- `Packet-capture analysis failed: ${cause instanceof Error ? cause.message : String(cause)}`,- { cause },- ),+ : cause instanceof PcapConfigurationFailure+ ? pcapToolUnavailable(request.operation, cause.message, {+ cause,+ })+ : new AnalysisProtocolError(+ `Packet-capture analysis failed: ${cause instanceof Error ? cause.message : String(cause)}`,+ { cause },+ ),);}if (signal?.aborted && result.ok)@@ -502,32 +602,59 @@ export class PcapProvider {partialObservation: createPcapEvidence(request, result.value),}),);- if (cleanup !== undefined)- result = result.ok- ? err(- cleanup.retainPartialObservation(- createPcapEvidence(request, result.value),- ),- )- : err(- analysisErrorWithCleanupFailure(- result.error,- cleanup,- request.operation,- ),- );+ if (cleanup !== undefined) {+ if (result.ok) {+ const failure = cleanup.retainPartialObservation(+ createPcapEvidence(request, result.value),+ );+ result = err(failure);+ this.snapshotFailures.set(snapshot, {+ returned: failure,+ snapshot: failure,+ });+ } else {+ const returned = analysisErrorWithCleanupFailure(+ result.error,+ cleanup,+ request.operation,+ ).bindCleanupDependencies([cleanup]);+ result = err(returned);+ this.snapshotFailures.set(snapshot, {+ returned,+ snapshot: cleanup,+ });+ }+ }}- if (- snapshot !== undefined &&- pendingCommand !== undefined &&- (result.ok || !(result.error instanceof ProviderCleanupError))- ) {+ if (snapshot !== undefined && pendingCommand !== undefined) {const partialObservation = result.ok? createPcapEvidence(request, result.value): result.error.partialObservation;const capturedOutput = result.ok? undefined: result.error.capturedOutput;+ let commandFailure = pendingCommand.failure;+ if (commandFailure === undefined) {+ commandFailure = new ProviderCleanupError(+ "pcap",+ pendingCommand.resources,+ {+ reason: pendingCommand.reason,+ captured_output: pendingCommand.capturedOutput,+ },+ { operation: request.operation },+ );+ pendingCommand.failure = commandFailure;+ }+ const snapshotFailure = new ProviderCleanupError(+ "pcap",+ [snapshot.path],+ {+ reason:+ "Capture snapshot remains owned until command cleanup completes.",+ },+ { operation: request.operation },+ );const cleanupFailure = new ProviderCleanupError("pcap",[...new Set([snapshot.path, ...pendingCommand.resources])],@@ -549,15 +676,37 @@ export class PcapProvider {...(partialObservation === undefined ? {} : { partialObservation }),},);- result = err(cleanupFailure);+ const returned = result.ok+ ? cleanupFailure+ .retainPartialObservation(partialObservation!)+ .bindCleanupDependencies([commandFailure, snapshotFailure])+ : result.error instanceof PcapCommandCleanupError+ ? result.error.bindCleanupDependencies([+ commandFailure,+ snapshotFailure,+ ])+ : analysisErrorWithCleanupFailure(+ result.error,+ cleanupFailure,+ request.operation,+ ).bindCleanupDependencies([commandFailure, snapshotFailure]);+ result = err(returned);+ this.snapshotFailures.set(snapshot, {+ returned,+ snapshot: snapshotFailure,+ });}if (snapshot !== undefined &&this.snapshots.has(snapshot) &&!result.ok &&- result.error.cleanupIncomplete+ result.error.cleanupIncomplete &&+ !this.snapshotFailures.has(snapshot))- this.snapshotFailures.set(snapshot, result.error);+ this.snapshotFailures.set(snapshot, {+ returned: result.error,+ snapshot: result.error,+ });return result;}diff --git a/src/pcap/PcapSnapshot.ts b/src/pcap/PcapSnapshot.tsindex 416198ccf..fb1620d86 100644--- a/src/pcap/PcapSnapshot.ts+++ b/src/pcap/PcapSnapshot.ts@@ -11,8 +11,10 @@ import {AnalysisInputError,AnalysisResourceConstraintError,} from "../domain/analysisErrorCore.js";+import { ProviderCleanupError } from "../domain/providerCleanupError.js";import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";import {+ assertRegularFileActive,openRegularFile,RegularFileAdmissionFailure,sameRegularFileState,@@ -26,6 +28,10 @@ const MAX_CAPTURE_BYTES = 2 * 1024 ** 3;/** An owned capture copy and every descriptor needed to release it safely. */export class PcapSnapshot {private readonly handles = new Set<OwnedFileHandle>();+ private readonly completionCleanup = new Map<+ OwnedFileHandle,+ AnalysisError+ >();readonly path: string;readonly configurationPath: string;private constructor(private readonly root: PrivateRuntimeRoot) {@@ -63,6 +69,36 @@ export class PcapSnapshot {private async release(handle: OwnedFileHandle): Promise<void> {await handle.close();this.handles.delete(handle);+ this.completionCleanup.get(handle)?.resolveCleanup();+ this.completionCleanup.delete(handle);+ }+ private async releaseCompleted(+ handle: OwnedFileHandle,+ signal?: AbortSignal,+ ): Promise<void> {+ try {+ await this.release(handle);+ } catch (cleanupCause) {+ const cleanup = new ProviderCleanupError(+ "pcap",+ [this.path],+ { reason: "Owned snapshot descriptor close failed" },+ { operation: OPERATION, cause: cleanupCause },+ );+ this.completionCleanup.set(handle, cleanup);+ if (signal?.aborted !== true) throw cleanup;+ const cancelled = new AnalysisCancelledError(OPERATION, {+ cause: signal.reason,+ cleanup: {+ reason: "Owned snapshot descriptor close could not be confirmed",+ resources: [this.path],+ },+ });+ cancelled+ .retainSecondaryFailure(cleanup)+ .bindCleanupDependencies([cleanup]);+ throw cancelled;+ }}async capture(@@ -74,12 +110,7 @@ export class PcapSnapshot {return await read();} catch (cause) {const cancellation = regularFileCancellation(cause);- if (cancellation !== undefined)- throw new AnalysisCancelledError(OPERATION, {- cause: cancellation.reason,- });- if (signal?.aborted)- throw new AnalysisCancelledError(OPERATION, { cause });+ if (cancellation !== undefined) throw cause;if (cause instanceof AnalysisError) throw cause;if (cause instanceof Error &&@@ -99,7 +130,7 @@ export class PcapSnapshot {}};try {- signal?.throwIfAborted();+ assertRegularFileActive(signal);await mkdir(this.configurationPath, { mode: 0o700 });const source = await sourceRead(async () => {try {@@ -133,7 +164,7 @@ export class PcapSnapshot {const hash = createHash("sha256");let copied = 0;while (copied <= Number(before.size)) {- signal?.throwIfAborted();+ assertRegularFileActive(signal);const { bytesRead } = await sourceRead(() =>source.handle.read(buffer,@@ -142,7 +173,7 @@ export class PcapSnapshot {copied,),);- signal?.throwIfAborted();+ assertRegularFileActive(signal);if (bytesRead === 0) break;copied += bytesRead;if (BigInt(copied) > before.size)@@ -186,10 +217,10 @@ export class PcapSnapshot {path,"Capture identity or contents changed during acquisition",);- await this.release(source);- await this.release(destination);+ await this.releaseCompleted(source, signal);+ await this.releaseCompleted(destination, signal);await chmod(this.path, 0o400);- signal?.throwIfAborted();+ assertRegularFileActive(signal);return { bytes: copied, sha256: hash.digest("hex") };} catch (cause) {if (cause instanceof RegularFileAdmissionFailure) this.own(cause.owner);@@ -201,8 +232,6 @@ export class PcapSnapshot {cause: cancellation.reason,});if (cause instanceof AnalysisError) throw cause;- if (signal?.aborted)- throw new AnalysisCancelledError(OPERATION, { cause: signal.reason });throw new AnalysisResourceConstraintError(OPERATION,"file-size",@@ -230,7 +259,7 @@ export class PcapSnapshot {const hash = createHash("sha256");let bytes = 0;while (bytes <= expected.bytes) {- signal?.throwIfAborted();+ assertRegularFileActive(signal);const read = await file.handle.read(buffer,0,@@ -254,7 +283,8 @@ export class PcapSnapshot {selectedPath,"Owned packet snapshot changed during tool analysis.",);- await this.release(file);+ await this.releaseCompleted(file, signal);+ assertRegularFileActive(signal);} catch (cause) {if (cause instanceof RegularFileAdmissionFailure) this.own(cause.owner);const primary =@@ -265,8 +295,6 @@ export class PcapSnapshot {cause: cancellation.reason,});if (cause instanceof AnalysisError) throw cause;- if (signal?.aborted)- throw new AnalysisCancelledError(OPERATION, { cause: signal.reason });throw new AnalysisArtifactChangedError(OPERATION,selectedPath,diff --git a/tests/boundary/pcap/pcapCommand.test.ts b/tests/boundary/pcap/pcapCommand.test.tsindex d8d52b6bb..30aeaf9bc 100644--- a/tests/boundary/pcap/pcapCommand.test.ts+++ b/tests/boundary/pcap/pcapCommand.test.ts@@ -5,56 +5,186 @@ import * as ownership from "../../../src/process/ProcessOwnershipObservation.js"import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";import type { ProviderProcessSupervisor } from "../../../src/process/ProviderProcess.js";+import {+ AnalysisCancelledError,+ AnalysisProtocolError,+} from "../../../src/domain/analysisErrorCore.js";+import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";+import { OwnedCommandFailure } from "../../../src/process/OwnedCommand.js";-it("does not spend the tool execution deadline preparing native ownership", async () => {- const original = ownership.prepareProcessOwnershipInspection;- let entered!: () => void;- let release!: () => void;- const preparing = new Promise<void>((resolve) => {- entered = resolve;- });- const gate = new Promise<void>((resolve) => {- release = resolve;- });- let first = true;- const prepare = vi- .spyOn(ownership, "prepareProcessOwnershipInspection")- .mockImplementation(async (signal) => {- await original(signal);- if (first) {- first = false;- entered();- await gate;- }+it.skipIf(process.platform !== "darwin")(+ "preserves opaque cancellation during native ownership preparation without acquiring caller resources",+ async () => {+ const controller = new AbortController();+ const reason = new ProviderCleanupError("caller", ["foreign-resource"], {});+ const prepare = vi+ .spyOn(ownership, "prepareProcessOwnershipInspection")+ .mockImplementationOnce(async (signal) => {+ controller.abort(reason);+ signal?.throwIfAborted();+ });+ onTestFinished(() => prepare.mockRestore());+ const launcher = vi.fn(async () => {+ throw new Error("Cancelled preparation must not launch the tool");});- onTestFinished(() => {- prepare.mockRestore();- release();- });- const pending = runPcapCommand({- operation: "inspect_pcap_client",+ const failure = await runPcapCommand({+ operation: "inspect_pcap_client",+ command: process.execPath,+ arguments: ["--version"],+ limits: { timeoutMs: 5000, maxOutputBytes: 1024 },+ environment: {},+ signal: controller.signal,+ launcher,+ retain: () => {+ throw new Error("No provider resources were acquired");+ },+ }).catch((cause: unknown) => cause);+ expect(failure).toBeInstanceOf(AnalysisCancelledError);+ if (!(failure instanceof AnalysisCancelledError)) throw failure;+ expect(failure.cause).toBe(reason);+ expect(failure.cleanupIncomplete).toBe(false);+ expect(failure.cleanupResources).toEqual([]);+ expect(reason.cleanupIncomplete).toBe(true);+ expect(launcher).not.toHaveBeenCalled();+ },+);++it("preserves a failed producer when cancellation arrives during its final cleanup", async () => {+ const controller = new AbortController();+ const reason = { request: "cancel during cleanup" };+ const failure = await runPcapCommand({+ operation: "inspect_pcap_capture",command: process.execPath,- arguments: ["--version"],- limits: { timeoutMs: 1000, maxOutputBytes: 1024 },+ arguments: [+ "-e",+ 'process.stderr.write("authored producer failure"); process.exitCode = 7',+ ],+ inputPath: "/authored-capture.pcap",+ limits: { timeoutMs: 5000, maxOutputBytes: 1024 },environment: {},- signal: undefined,- retain: (owner) => {+ signal: controller.signal,+ launcher: async (spawn) => {+ const launched = await spawnOwnedProviderProcess(spawn);+ const cleanup =+ launched.cleanup ??+ (() => cleanupOwnedProcessGroup(launched.ownership));+ return {+ ...launched,+ cleanup: async () => {+ const result = await cleanup();+ controller.abort(reason);+ return result;+ },+ };+ },+ retain: (owner) =>onTestFinished(async () => {expect((await owner.stop()).status).not.toBe("incomplete");- });- },- }).then(- (value) => ({ ok: true as const, value }),- (error: unknown) => ({ ok: false as const, error }),- );- await preparing;- await delay(1100);- release();- const result = await pending;- if (!result.ok) throw result.error;- expect(result.value.stdout.trim()).toBe(process.version);+ }),+ }).catch((cause: unknown) => cause);+ expect(controller.signal.aborted).toBe(true);+ expect(failure).toBeInstanceOf(AnalysisProtocolError);+ if (!(failure instanceof AnalysisProtocolError)) throw failure;+ expect(failure.cause).toBeInstanceOf(OwnedCommandFailure);+ expect((failure.cause as OwnedCommandFailure).reason).toBe("process");+ expect(failure.capturedOutput).toMatchObject({+ stderr: "authored producer failure",+ exit_code: 7,+ });});+it.each([+ null,+ "opaque caller cancellation",+ new ProviderCleanupError("caller", ["caller-owned-resource"], {+ reason: "unrelated cleanup",+ }),+])(+ "preserves the exact active command cancellation reason %s",+ async (reason) => {+ const controller = new AbortController();+ const failure = await runPcapCommand({+ operation: "inspect_pcap_client",+ command: process.execPath,+ arguments: [+ "-e",+ 'process.stdout.write("ready"); setInterval(() => {}, 1000)',+ ],+ limits: { timeoutMs: 5000, maxOutputBytes: 1024 },+ environment: {},+ signal: controller.signal,+ launcher: async (spawn) => {+ const launched = await spawnOwnedProviderProcess(spawn);+ launched.process.stdout?.once("data", () => controller.abort(reason));+ return launched;+ },+ retain: (owner) =>+ onTestFinished(async () => {+ expect((await owner.stop()).status).not.toBe("incomplete");+ }),+ }).catch((cause: unknown) => cause);+ expect(failure).toBeInstanceOf(AnalysisCancelledError);+ if (!(failure instanceof AnalysisCancelledError)) throw failure;+ expect(failure.cause).toBe(reason);+ expect(failure.cleanupIncomplete).toBe(false);+ expect(failure.cleanupResources).toEqual([]);+ if (reason instanceof ProviderCleanupError)+ expect(reason.cleanupIncomplete).toBe(true);+ },+);++it.skipIf(process.platform !== "darwin")(+ "does not spend the tool execution deadline preparing native ownership",+ async () => {+ const original = ownership.prepareProcessOwnershipInspection;+ let entered!: () => void;+ let release!: () => void;+ const preparing = new Promise<void>((resolve) => {+ entered = resolve;+ });+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ let first = true;+ const prepare = vi+ .spyOn(ownership, "prepareProcessOwnershipInspection")+ .mockImplementation(async (signal) => {+ await original(signal);+ if (first) {+ first = false;+ entered();+ await gate;+ }+ });+ onTestFinished(() => {+ prepare.mockRestore();+ release();+ });+ const pending = runPcapCommand({+ operation: "inspect_pcap_client",+ command: process.execPath,+ arguments: ["--version"],+ limits: { timeoutMs: 1000, maxOutputBytes: 1024 },+ environment: {},+ signal: undefined,+ retain: (owner) => {+ onTestFinished(async () => {+ expect((await owner.stop()).status).not.toBe("incomplete");+ });+ },+ }).then(+ (value) => ({ ok: true as const, value }),+ (error: unknown) => ({ ok: false as const, error }),+ );+ await preparing;+ await delay(1100);+ release();+ const result = await pending;+ if (!result.ok) throw result.error;+ expect(result.value.stdout.trim()).toBe(process.version);+ },+);+it("returns complete stdout while retaining unresolved process cleanup", async () => {let retained:| {diff --git a/tests/boundary/pcap/pcapProviderCancellation.test.ts b/tests/boundary/pcap/pcapProviderCancellation.test.tsnew file mode 100644index 000000000..95b331220--- /dev/null+++ b/tests/boundary/pcap/pcapProviderCancellation.test.ts@@ -0,0 +1,269 @@+import { writeFile } from "node:fs/promises";+import { dirname, join } from "node:path";+import { expect, onTestFinished, test, vi } from "vitest";++import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js";+import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";+import { resolvedAnalysisError } from "../../../src/domain/analysisErrorBase.js";+import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";+import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";+import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";+import { PcapProvider } from "../../../src/pcap/PcapProvider.js";+import type { PcapCommandLauncher } from "../../../src/pcap/PcapCommand.js";+import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";++const it = test.skipIf(process.platform === "win32");++vi.mock("../../../src/pcap/PcapNativeBound.js", async (importOriginal) => ({+ ...(await importOriginal<+ typeof import("../../../src/pcap/PcapNativeBound.js")+ >()),+ // Exercise the provider's capture consumer with real owned children on hosts+ // where its production native bound is unavailable (including macOS).+ preparePcapNativeBound: async () => ({ nativeBound: {}, limitations: [] }),+}));++const writeTool = async (+ root: string,+ name: string,+ body: string,+): Promise<string> => {+ const path = join(root, name);+ await writeFile(path, `#!/usr/bin/env -S ${process.execPath}\n${body}\n`, {+ mode: 0o755,+ });+ return path;+};++const writeTools = async (+ root: string,+ capinfosMode: "active" | "physical" | "complete",+ activeVersion = false,+): Promise<{ readonly tshark: string; readonly capinfos: string }> => {+ const tshark = await writeTool(+ root,+ "tshark.cjs",+ `if (process.argv[2] === "--version") { ${activeVersion ? 'process.stdout.write("ready\\n"); setInterval(() => {}, 1000);' : 'console.log("TShark (Wireshark) 4.6.6-test"); process.exit(0);'} }\nconsole.log("[]");`,+ );+ const capinfosBody =+ capinfosMode === "active"+ ? `if (process.argv[2] === "--version") { console.log("Capinfos (Wireshark) 4.6.6-test"); process.exit(0); }\nprocess.stdout.write("ready\\n"); setInterval(() => {}, 1000);`+ : capinfosMode === "physical"+ ? `if (process.argv[2] === "--version") { console.log("Capinfos (Wireshark) 4.6.6-test"); process.exit(0); }\nprocess.stderr.write("authored producer failure\\n"); process.exitCode = 7;`+ : `if (process.argv[2] === "--version") { console.log("Capinfos (Wireshark) 4.6.6-test"); process.exit(0); }\nprocess.stdout.write(${JSON.stringify("File name: /work/capture.pcap\nFile type: Wireshark/tcpdump/... - pcap\nFile encapsulation: Ethernet\nPacket size limit: file hdr: 262144 bytes\nNumber of packets: 0\nCapture duration: 0.000 seconds\nEarliest packet time: 1791728020.608505\nLatest packet time: 1791728020.608505\n")});`;+ const capinfos = await writeTool(root, "capinfos.cjs", capinfosBody);+ return { tshark, capinfos };+};++const fixture = async (+ mode: "active" | "physical" | "complete",+ controller: AbortController,+ reason: unknown,+ failedCleanupAttempts: number,+ activeVersion = false,+) => {+ const root = await createTestTempDirectory("rea-pcap-provider-cancel-");+ const tools = await writeTools(root, mode, activeVersion);+ const capture = join(root, "capture.pcap");+ await writeFile(capture, "controlled capture bytes");+ let cleanupAttempts = 0;+ const launcher: PcapCommandLauncher = async (spawn) => {+ const launched = await spawnOwnedProviderProcess(spawn);+ const captureCommand = spawn.arguments.includes("-M");+ const activeVersionCommand =+ activeVersion && spawn.arguments.includes("--version");+ if (!captureCommand && !activeVersionCommand) return launched;+ if (activeVersionCommand) controller.abort(reason);+ if (mode === "active" && captureCommand)+ launched.process.stdout?.on("data", (chunk: Buffer) => {+ if (chunk.toString().includes("ready")) controller.abort(reason);+ });+ if (!captureCommand) return launched;+ const cleanup =+ launched.cleanup ?? (() => cleanupOwnedProcessGroup(launched.ownership));+ return {+ ...launched,+ cleanup: async () => {+ cleanupAttempts += 1;+ if (mode === "physical") controller.abort(reason);+ if (cleanupAttempts <= failedCleanupAttempts)+ throw new Error("injected retained cleanup failure");+ const result = await cleanup();+ return result;+ },+ };+ };+ const provider = new PcapProvider({+ environment: {+ REA_TSHARK_COMMAND: tools.tshark,+ REA_CAPINFOS_COMMAND: tools.capinfos,+ },+ launcher,+ });+ onTestFinished(async () => provider.close());+ return { provider, root, capture, cleanupAttempts: () => cleanupAttempts };+};++it("availability preserves the producer's exact cancellation reason", async () => {+ const controller = new AbortController();+ const reason = new ProviderCleanupError(+ "caller-owned",+ ["foreign resource"],+ { reason: "opaque caller reason" },+ );+ const { provider } = await fixture("active", controller, reason, 0, true);+ let failure: unknown;+ try {+ await provider.inspectAvailability(controller.signal);+ } catch (cause) {+ failure = cause;+ }+ expect(failure).toBeInstanceOf(AnalysisCancelledError);+ expect(failure).toMatchObject({ cause: reason });+});++it("active cancellation stays primary through retained command and snapshot cleanup retry", async () => {+ const controller = new AbortController();+ const reason = "caller cancellation token";+ const { provider, capture, cleanupAttempts } = await fixture(+ "active",+ controller,+ reason,+ 2,+ );+ const result = await provider.execute(+ {+ operation: "inspect_pcap_capture",+ input: { path: capture },+ },+ { signal: controller.signal },+ );+ expect(result.ok).toBe(false);+ if (result.ok) return;+ const returned = result.error;+ const primary = returned.cleanupPrimary;+ expect(primary).toBeInstanceOf(AnalysisCancelledError);+ expect(primary?.cause).toBe(reason);+ expect(projectAnalysisError(returned).code).toBe("cleanup_incomplete");+ expect(+ returned.cleanupResources.some((path) => path.startsWith("process-group:")),+ ).toBe(true);+ expect(+ returned.cleanupResources.some((path) => path.endsWith("/capture.pcap")),+ ).toBe(true);++ const blocked = await provider.execute({+ operation: "inspect_pcap_capture",+ input: { path: capture },+ });+ expect(blocked.ok).toBe(false);+ if (!blocked.ok) {+ expect(blocked.error).toBeInstanceOf(ProviderCleanupError);+ expect(blocked.error.cleanupResources).toEqual(returned.cleanupResources);+ }++ const snapshotPath = returned.cleanupResources.find((path) =>+ path.endsWith("/capture.pcap"),+ );+ if (snapshotPath === undefined) throw new Error("Missing retained snapshot");+ const close = PrivateRuntimeRoot.prototype.close;+ const denied = vi+ .spyOn(PrivateRuntimeRoot.prototype, "close")+ .mockImplementation(function (this: PrivateRuntimeRoot) {+ if (this.path === dirname(snapshotPath))+ return Promise.reject(new Error("injected snapshot close failure"));+ return close.call(this);+ });+ try {+ let firstCloseFailure: unknown;+ try {+ await provider.close();+ } catch (cause) {+ firstCloseFailure = cause;+ }+ expect(firstCloseFailure).toBeInstanceOf(ProviderCleanupError);+ expect(firstCloseFailure).toMatchObject({ cleanupIncomplete: true });+ const closeFailure = firstCloseFailure as ProviderCleanupError;+ expect(closeFailure.cleanupResources).toContain(snapshotPath);+ expect(+ closeFailure.cleanupResources.some((path) =>+ path.startsWith("process-group:"),+ ),+ ).toBe(true);+ expect(cleanupAttempts()).toBe(2);+ // The next close releases the command but the deliberately denied snapshot+ // close leaves only that exact owner in the first close error.+ await expect(provider.close()).rejects.toMatchObject({+ cleanupIncomplete: true,+ });+ expect(closeFailure.cleanupResources).toEqual([snapshotPath]);+ expect(closeFailure.cleanupIncomplete).toBe(true);+ expect(returned.cleanupIncomplete).toBe(true);+ expect(returned.cleanupResources).toEqual([snapshotPath]);+ denied.mockRestore();+ await provider.close();+ expect(closeFailure.cleanupIncomplete).toBe(false);+ expect(closeFailure.cleanupResources).toEqual([]);+ } finally {+ denied.mockRestore();+ }+ expect(returned.cleanupIncomplete).toBe(false);+ expect(resolvedAnalysisError(returned)).toBe(primary);+});++it("a physical command failure survives a late cancellation and cleanup retry", async () => {+ const controller = new AbortController();+ const reason = { caller: "late abort" };+ const { provider, capture } = await fixture(+ "physical",+ controller,+ reason,+ 1,+ );+ const result = await provider.execute(+ {+ operation: "inspect_pcap_capture",+ input: { path: capture },+ },+ { signal: controller.signal },+ );+ expect(result.ok).toBe(false);+ if (result.ok) return;+ const returned = result.error;+ const primary = returned.cleanupPrimary;+ expect(primary?._tag).toBe("AnalysisProtocolError");+ expect(primary?.cause).not.toBe(reason);+ expect(projectAnalysisError(returned).code).toBe("cleanup_incomplete");+ expect(returned.capturedOutput?.stderr).toContain(+ "authored producer failure",+ );+ await provider.close();+ expect(returned.cleanupIncomplete).toBe(false);+ expect(resolvedAnalysisError(returned)).toBe(primary);+});++it("resolves the original completed-output cleanup error after retry", async () => {+ const controller = new AbortController();+ const { provider, capture, cleanupAttempts } = await fixture(+ "complete",+ controller,+ undefined,+ 1,+ );+ const result = await provider.execute({+ operation: "inspect_pcap_capture",+ input: { path: capture },+ });+ expect(result.ok).toBe(false);+ if (result.ok) return;+ const returned = result.error;+ expect(returned).toBeInstanceOf(ProviderCleanupError);+ expect(returned.diagnostics).toMatchObject({ previous_error: null });+ expect(returned.partialObservation).toBeDefined();+ expect(returned.cleanupIncomplete).toBe(true);+ await provider.close();+ expect(cleanupAttempts()).toBe(2);+ expect(returned.cleanupIncomplete).toBe(false);+ expect(resolvedAnalysisError(returned)).toBe(returned);+});diff --git a/tests/boundary/pcap/pcapSnapshotCancellation.test.ts b/tests/boundary/pcap/pcapSnapshotCancellation.test.tsnew file mode 100644index 000000000..e96f975a9--- /dev/null+++ b/tests/boundary/pcap/pcapSnapshotCancellation.test.ts@@ -0,0 +1,201 @@+import { createHash } from "node:crypto";+import { open, stat, writeFile, type FileHandle } from "node:fs/promises";+import { join } from "node:path";+import { expect, onTestFinished, test, vi } from "vitest";++import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";+import { OwnedFileHandle } from "../../../src/filesystem/OwnedFileHandle.js";+import { PcapSnapshot } from "../../../src/pcap/PcapSnapshot.js";+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";++const opaqueCleanupReason = () =>+ new ProviderCleanupError(+ "caller-owned",+ ["caller-owned-resource"],+ { reason: "opaque abort reason" },+ { operation: "caller_operation" },+ );++const makeCapture = async () => {+ const parent = await createTestTempDirectory("rea-pcap-snapshot-cancel-");+ const path = join(parent, "capture.pcap");+ const contents = Buffer.from("capture bytes for snapshot cancellation");+ await writeFile(path, contents);+ return { parent, path, contents };+};++test.each([+ ["null", null],+ ["string", "caller stopped"],+ ["foreign typed error", opaqueCleanupReason()],+] as const)(+ "preserves the exact opaque %s reason at snapshot admission",+ async (_label, reason) => {+ const { path } = await makeCapture();+ const snapshot = await PcapSnapshot.create();+ onTestFinished(() => snapshot.close());+ const controller = new AbortController();+ controller.abort(reason);++ const error = await snapshot+ .capture(path, controller.signal)+ .catch((e) => e);+ expect(error).toMatchObject({ _tag: "AnalysisCancelledError" });+ expect(error.cause).toBe(reason);+ if (reason instanceof ProviderCleanupError) {+ expect(reason.cleanupIncomplete).toBe(true);+ expect(reason.cleanupResources).toEqual(["caller-owned-resource"]);+ expect(error.cleanupResources).not.toContain("caller-owned-resource");+ }+ },+);++test("keeps a physical read failure primary when abort arrives with it", async () => {+ const { path } = await makeCapture();+ const snapshot = await PcapSnapshot.create();+ onTestFinished(() => snapshot.close());+ const controller = new AbortController();+ const probe = await open(path, "r");+ const prototype = Object.getPrototypeOf(probe) as {+ read: FileHandle["read"];+ };+ await probe.close();+ const physicalFailure = new Error("injected source read failure");+ const read = vi.spyOn(prototype, "read").mockImplementationOnce(async () => {+ controller.abort("late caller cancellation");+ throw physicalFailure;+ });+ onTestFinished(() => read.mockRestore());++ const error = await snapshot.capture(path, controller.signal).catch((e) => e);+ expect(error).toMatchObject({ _tag: "AnalysisInputError" });+ expect(error.cause).toBe(physicalFailure);+});++test("maps cancellation observed after owned handle close exactly once", async () => {+ const { path } = await makeCapture();+ const snapshot = await PcapSnapshot.create();+ onTestFinished(() => snapshot.close());+ const controller = new AbortController();+ const reason = opaqueCleanupReason();+ const close = OwnedFileHandle.prototype.close;+ const closeSpy = vi+ .spyOn(OwnedFileHandle.prototype, "close")+ .mockImplementation(async function (this: OwnedFileHandle) {+ await close.call(this);+ if (!controller.signal.aborted) controller.abort(reason);+ });+ onTestFinished(() => closeSpy.mockRestore());++ const error = await snapshot.capture(path, controller.signal).catch((e) => e);+ expect(error).toMatchObject({ _tag: "AnalysisCancelledError" });+ expect(error.cause).toBe(reason);+});++test("verify maps cancellation after final descriptor close exactly once", async () => {+ const { path, contents } = await makeCapture();+ const snapshot = await PcapSnapshot.create();+ onTestFinished(() => snapshot.close());+ const identity = {+ bytes: contents.length,+ sha256: createHash("sha256").update(contents).digest("hex"),+ };+ await snapshot.capture(path);+ const controller = new AbortController();+ const reason = opaqueCleanupReason();+ const close = OwnedFileHandle.prototype.close;+ const closeSpy = vi+ .spyOn(OwnedFileHandle.prototype, "close")+ .mockImplementation(async function (this: OwnedFileHandle) {+ await close.call(this);+ if (!controller.signal.aborted) controller.abort(reason);+ });+ onTestFinished(() => closeSpy.mockRestore());++ const error = await snapshot+ .verify(identity, path, controller.signal)+ .catch((e) => e);+ expect(error).toMatchObject({ _tag: "AnalysisCancelledError" });+ expect(error.cause).toBe(reason);+ expect(reason.cleanupIncomplete).toBe(true);+ expect(reason.cleanupResources).toEqual(["caller-owned-resource"]);+});++test("close failure during final cancellation retains owner and resolves its marker on retry", async () => {+ const { path, contents } = await makeCapture();+ const snapshot = await PcapSnapshot.create();+ const identity = {+ bytes: contents.length,+ sha256: createHash("sha256").update(contents).digest("hex"),+ };+ await snapshot.capture(path);+ const controller = new AbortController();+ const reason = opaqueCleanupReason();+ const closeFailure = new Error("injected final descriptor close failure");+ let retained: FileHandle | undefined;+ const closeSpy = vi+ .spyOn(OwnedFileHandle.prototype, "close")+ .mockImplementationOnce(async function (this: OwnedFileHandle) {+ retained = this.handle;+ controller.abort(reason);+ throw closeFailure;+ });++ const error = await snapshot+ .verify(identity, path, controller.signal)+ .catch((e) => e);+ expect(error).toMatchObject({+ _tag: "AnalysisCancelledError",+ cleanupIncomplete: true,+ });+ expect(error.cause).toBe(reason);+ expect(error.cleanupResources).toContain(snapshot.path);+ expect(error.secondaryFailures).toHaveLength(1);+ expect(error.secondaryFailures[0]).toMatchObject({+ _tag: "ProviderAdapterError",+ });+ expect(error.secondaryFailures[0].cause).toBe(closeFailure);+ expect(retained?.fd).toBeGreaterThanOrEqual(0);+ expect(reason.cleanupIncomplete).toBe(true);+ expect(reason.cleanupResources).toEqual(["caller-owned-resource"]);++ closeSpy.mockRestore();+ await snapshot.close();+ expect(retained?.fd).toBe(-1);+ expect(error.cleanupIncomplete).toBe(false);+ expect(error.cleanupResources).toEqual([]);+ expect(reason.cleanupIncomplete).toBe(true);+ await expect(stat(snapshot.path)).rejects.toMatchObject({ code: "ENOENT" });+});++test("retains an open descriptor after failed close and releases it on retry", async () => {+ const { path, contents } = await makeCapture();+ const snapshot = await PcapSnapshot.create();+ onTestFinished(() => snapshot.close());+ const identity = {+ bytes: contents.length,+ sha256: createHash("sha256").update(contents).digest("hex"),+ };+ await snapshot.capture(path);+ const closeFailure = new Error("injected descriptor close failure");+ let retained: FileHandle | undefined;+ const closeSpy = vi+ .spyOn(OwnedFileHandle.prototype, "close")+ .mockImplementationOnce(async function (this: OwnedFileHandle) {+ retained = this.handle;+ throw closeFailure;+ });++ const error = await snapshot.verify(identity, path).catch((e) => e);+ expect(error).toBeInstanceOf(ProviderCleanupError);+ expect(error.cause).toBe(closeFailure);+ expect(error.cleanupIncomplete).toBe(true);+ expect(error.cleanupResources).toContain(snapshot.path);+ expect(retained?.fd).toBeGreaterThanOrEqual(0);++ closeSpy.mockRestore();+ await snapshot.close();+ expect(retained?.fd).toBe(-1);+ expect(error.cleanupIncomplete).toBe(false);+ await expect(stat(snapshot.path)).rejects.toMatchObject({ code: "ENOENT" });+});