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(lifecycle): retain Android and Kuna descriptors when close fails (#6363)
morluto746a41937d0c
diff --git a/src/android/AndroidTargetSnapshot.ts b/src/android/AndroidTargetSnapshot.tsindex 1801768c6..42e7785e0 100644--- a/src/android/AndroidTargetSnapshot.ts+++ b/src/android/AndroidTargetSnapshot.ts@@ -8,13 +8,60 @@ import {AnalysisInputError,AnalysisCapabilityUnavailableError,} from "../domain/analysisErrorCore.js";+import type { AnalysisError } from "../domain/analysisErrorBase.js";+import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";+import {+ RegularFileCleanupFailure,+ withOwnedFileHandle,+} from "../filesystem/OwnedRegularFile.js";import {openRegularFile,+ RegularFileAdmissionFailure,assertRegularFileActive,sameRegularFileState,} from "../filesystem/RegularFile.js";import type { AndroidOperation } from "../domain/android/androidAnalysis.js";+/** Completed snapshot bytes retained when descriptor close fails after the copy. */+export interface AndroidSnapshotCopy {+ readonly kind: "android-snapshot-copy";+ readonly sha256: string;+ readonly sourcePath: string;+ readonly snapshotPath: string;+ readonly bytes: number;+}++/** Recognize the copy record carried by a rejected snapshot close. */+export const androidSnapshotCopy = (+ value: unknown,+): AndroidSnapshotCopy | undefined =>+ typeof value === "object" &&+ value !== null &&+ "kind" in value &&+ value.kind === "android-snapshot-copy" &&+ "sha256" in value &&+ typeof value.sha256 === "string" &&+ "sourcePath" in value &&+ typeof value.sourcePath === "string" &&+ "snapshotPath" in value &&+ typeof value.snapshotPath === "string" &&+ "bytes" in value &&+ typeof value.bytes === "number"+ ? {+ kind: "android-snapshot-copy",+ sha256: value.sha256,+ sourcePath: value.sourcePath,+ snapshotPath: value.snapshotPath,+ bytes: value.bytes,+ }+ : undefined;++/** Adopt a snapshot descriptor whose close rejected, keyed by its exact path. */+export type AndroidSnapshotCloseRetention = (+ path: string,+ owner: OwnedFileHandle,+) => void;+/** Bind decompiler input to the admitted artifact, even if the original changes. */export const snapshotAndroidTarget = async (path: string,@@ -22,22 +69,32 @@ export const snapshotAndroidTarget = async (root: string,operation: AndroidOperation,signal?: AbortSignal,+ retainFailedClose?: AndroidSnapshotCloseRetention,): Promise<string> => {const snapshot = join(root, "target.apk");try {- await copyAndroidSnapshot(path, snapshot, sha256, signal);+ await copyAndroidSnapshot(+ path,+ snapshot,+ sha256,+ signal,+ retainFailedClose,+ );assertRegularFileActive(signal);await chmod(snapshot, 0o400);return snapshot;} catch (cause: unknown) {- if (!(cause instanceof AndroidSnapshotChangedError)) throw cause;- throw new AnalysisInputError(operation, { cause }, [- {- path: ["path"],- reason: "invalid_value",- message: `APK bytes changed after admission at ${path}; retry against a stable file.`,- },- ]);+ throw projectSnapshotFailure(+ cause,+ (changed) =>+ new AnalysisInputError(operation, { cause: changed }, [+ {+ path: ["path"],+ reason: "invalid_value",+ message: `APK bytes changed after admission at ${path}; retry against a stable file.`,+ },+ ]),+ );}};@@ -48,102 +105,242 @@ export const snapshotAndroidEngine = async (root: string,operation: AndroidOperation,signal?: AbortSignal,+ retainFailedClose?: AndroidSnapshotCloseRetention,): Promise<{ path: string; sha256: string }> => {const path = join(root, "engine.jar");try {- const observed = await copyAndroidSnapshot(source, path, sha256, signal);+ const observed = await copyAndroidSnapshot(+ source,+ path,+ sha256,+ signal,+ retainFailedClose,+ );assertRegularFileActive(signal);await chmod(path, 0o400);- return { path, sha256: observed };+ return { path, sha256: observed.sha256 };} catch (cause: unknown) {- if (!(cause instanceof AndroidSnapshotChangedError)) throw cause;- throw new AnalysisCapabilityUnavailableError(- "jadx",- operation,- `REA_JADX_MCP_JAR bytes changed during admission at ${source}; retry with a stable engine file.`,- { cause },+ throw projectSnapshotFailure(+ cause,+ (changed) =>+ new AnalysisCapabilityUnavailableError(+ "jadx",+ operation,+ `REA_JADX_MCP_JAR bytes changed during admission at ${source}; retry with a stable engine file.`,+ { cause: changed },+ ),);}};+/**+ * Streams close their FileHandle on destroy. Route that close through the+ * owner so a stream shutdown and the explicit close confirm the same attempt.+ */+const adoptSnapshotHandle = (+ handle: FileHandle,+): { readonly handle: FileHandle; readonly owner: OwnedFileHandle } => {+ const close = handle.close.bind(handle);+ const owner = new OwnedFileHandle({+ get fd() {+ return handle.fd;+ },+ close,+ });+ handle.close = () => owner.close();+ // Callers read through `handle`. The owner only needs fd and close, which+ // is the whole contract withOwnedFileHandle and provider retry use.+ return { handle, owner: owner as OwnedFileHandle };+};+const copyAndroidSnapshot = async (sourcePath: string,snapshotPath: string,expectedSha256: string,- signal?: AbortSignal,-): Promise<string> => {+ signal: AbortSignal | undefined,+ retainFailedClose: AndroidSnapshotCloseRetention | undefined,+): Promise<AndroidSnapshotCopy> => {assertRegularFileActive(signal);- const source = await openRegularFile(sourcePath, {- symlinks: "follow",- signal,- });- let destination: FileHandle | undefined;- let inputStream: ReadStream | undefined;- let outputStream: WriteStream | undefined;let removeSnapshot = false;- let copiedBytes = 0;- const hash = createHash("sha256");+ const retain = (path: string) =>+ retainFailedClose === undefined+ ? {}+ : {+ retainFailedClose: (owner: OwnedFileHandle) =>+ retainFailedClose(path, owner),+ };try {- const initial = await source.stat();- assertRegularFileActive(signal);- const digest = new Transform({- transform(- chunk: Buffer,- _encoding: BufferEncoding,- callback: TransformCallback,- ) {- copiedBytes += chunk.length;- if (copiedBytes > initial.size) {- callback(- new AndroidSnapshotChangedError(- `Android input grew while being copied: ${sourcePath}`,- ),+ // Close each descriptor through its owner. A rejected close keeps the+ // copy outcome and stays retained until that owner is retried; the+ // partial file is removed only after those close attempts.+ const source = adoptSnapshotHandle(+ await openSnapshotSource(sourcePath, signal, retain(sourcePath)),+ );+ return await withOwnedFileHandle(+ sourcePath,+ source.owner,+ {+ ...(signal === undefined ? {} : { signal }),+ ...retain(sourcePath),+ },+ async () => {+ const initial = await source.handle.stat();+ assertRegularFileActive(signal);+ let copiedBytes = 0;+ const hash = createHash("sha256");+ const digest = new Transform({+ transform(+ chunk: Buffer,+ _encoding: BufferEncoding,+ callback: TransformCallback,+ ) {+ copiedBytes += chunk.length;+ if (copiedBytes > initial.size) {+ callback(+ new AndroidSnapshotChangedError(+ `Android input grew while being copied: ${sourcePath}`,+ ),+ );+ return;+ }+ hash.update(chunk);+ callback(null, chunk);+ },+ });+ assertRegularFileActive(signal);+ const destination = adoptSnapshotHandle(+ await open(snapshotPath, "wx", 0o600),+ );+ let copyCompleted = false;+ try {+ return await withOwnedFileHandle(+ snapshotPath,+ destination.owner,+ {+ ...(signal === undefined ? {} : { signal }),+ ...retain(snapshotPath),+ },+ async () => {+ let inputStream: ReadStream | undefined;+ let outputStream: WriteStream | undefined;+ try {+ assertRegularFileActive(signal);+ inputStream = source.handle.createReadStream({+ start: 0,+ end: initial.size,+ autoClose: false,+ });+ outputStream = destination.handle.createWriteStream({+ autoClose: false,+ });+ await pipeline(inputStream, digest, outputStream, { signal });+ assertRegularFileActive(signal);+ await verifySourceState(+ source.handle,+ sourcePath,+ initial,+ copiedBytes,+ );+ const observedSha256 = hash.digest("hex");+ if (observedSha256 !== expectedSha256)+ throw new AndroidSnapshotChangedError(+ `Android snapshot digest mismatch for ${sourcePath}`,+ );+ copyCompleted = true;+ return {+ kind: "android-snapshot-copy" as const,+ sha256: observedSha256,+ sourcePath,+ snapshotPath,+ bytes: copiedBytes,+ };+ } finally {+ // Destroy drops the stream's FileHandle reference and closes+ // through the owner installed above. A later owner close joins+ // that attempt. The stream may surface the same close error.+ for (const stream of [inputStream, outputStream]) {+ stream?.on("error", () => undefined);+ stream?.destroy();+ }+ }+ },);- return;+ } finally {+ if (!copyCompleted) removeSnapshot = true;}- hash.update(chunk);- callback(null, chunk);},- });- try {- destination = await open(snapshotPath, "wx", 0o600);- assertRegularFileActive(signal);- inputStream = source.createReadStream({- start: 0,- end: initial.size,- autoClose: false,- });- outputStream = destination.createWriteStream({ autoClose: false });- await pipeline(inputStream, digest, outputStream, { signal });- assertRegularFileActive(signal);- await verifySourceState(source, sourcePath, initial, copiedBytes);- const observedSha256 = hash.digest("hex");- if (observedSha256 !== expectedSha256)- throw new AndroidSnapshotChangedError(- `Android snapshot digest mismatch for ${sourcePath}`,- );- return observedSha256;- } catch (cause: unknown) {- removeSnapshot = destination !== undefined;- throw cause;- }+ );} finally {- // Non-auto-closing streams retain a reference to their FileHandle even- // after pipeline completion. Release those references before awaiting- // descriptor closure, after the admitted source state has been verified.- inputStream?.destroy();- outputStream?.destroy();- try {- await Promise.all([source.close(), destination?.close()]);- } finally {- if (removeSnapshot)- await rm(snapshotPath, { force: true }).catch(() => undefined);- }+ if (removeSnapshot)+ await rm(snapshotPath, { force: true }).catch(() => undefined);+ }+};++/**+ * Admission can reject after the descriptor opens. Keep that owner when its+ * own close also rejects; the success path still adopts one close owner.+ */+const openSnapshotSource = async (+ path: string,+ signal: AbortSignal | undefined,+ retention: {+ readonly retainFailedClose?: (owner: OwnedFileHandle) => void;+ },+): Promise<FileHandle> => {+ try {+ return await openRegularFile(path, { symlinks: "follow", signal });+ } catch (cause: unknown) {+ if (!(cause instanceof RegularFileAdmissionFailure)) throw cause;+ throw new RegularFileCleanupFailure(+ path,+ cause.owner,+ { kind: "failed", cause: cause.cause },+ cause.cleanupCause,+ retainAdmissionOwner(retention.retainFailedClose, cause.owner),+ );+ }+};++const retainAdmissionOwner = (+ retain: ((owner: OwnedFileHandle) => void) | undefined,+ owner: OwnedFileHandle,+): RegularFileCleanupFailure["retention"] => {+ if (retain === undefined) return { kind: "not_requested" };+ try {+ retain(owner);+ return { kind: "callback_returned" };+ } catch (cause: unknown) {+ return { kind: "callback_threw", cause };}};+/** Keep a stable-file diagnosis when descriptor cleanup fails around it. */+const projectSnapshotFailure = (+ cause: unknown,+ projectChanged: (changed: AndroidSnapshotChangedError) => AnalysisError,+): unknown => {+ if (cause instanceof AndroidSnapshotChangedError)+ return projectChanged(cause);+ if (+ !(cause instanceof RegularFileCleanupFailure) ||+ cause.outcome.kind !== "failed"+ )+ return cause;+ const projected = projectSnapshotFailure(cause.outcome.cause, projectChanged);+ if (projected === cause.outcome.cause) return cause;+ return new RegularFileCleanupFailure(+ cause.path,+ cause.owner,+ { kind: "failed", cause: projected },+ cause.cleanupCause,+ cause.retention,+ cause.completionCancellation,+ cause.operationFailure,+ );+};+const verifySourceState = async (- handle: Awaited<ReturnType<typeof openRegularFile>>,+ handle: FileHandle,path: string,initial: Stats,observedBytes: number,diff --git a/src/android/JadxFailure.ts b/src/android/JadxFailure.tsindex 2e934e15c..0b779a8a7 100644--- a/src/android/JadxFailure.ts+++ b/src/android/JadxFailure.ts@@ -17,9 +17,11 @@ import {StableFileHashFailure,} from "../filesystem/StableFileHash.js";import {+ RegularFileCancelled,RegularFileCleanupFailure,regularFileCancellation,} from "../filesystem/OwnedRegularFile.js";+import { androidSnapshotCopy } from "./AndroidTargetSnapshot.js";import type { JadxSession } from "./JadxSession.js";import type { JadxMcpTransport } from "./JadxMcpTransport.js";@@ -115,12 +117,61 @@ const observeJadxFailure = (cause: cancellation.reason,});if (cause instanceof RegularFileCleanupFailure) {- const primaryCause =- cause.outcome.kind === "failed"- ? stableFileHashCause(cause.outcome.cause)- : cause;+ const reason =+ cause.cleanupCause instanceof Error+ ? cause.cleanupCause.message+ : String(cause.cleanupCause);+ // A finished copy or its cancellation can sit on this close or inside a+ // nested one when another descriptor also rejected close. Name every+ // descriptor that failed; the copied output path stays on the observation.+ const closeFailures = snapshotCloseFailures(cause);+ const descriptorPaths = [+ ...new Set(closeFailures.map((failure) => failure.path)),+ ];+ const completed = completedSnapshotCopy(cause);+ const nestedCancellation = nestedFileCancellation(cause);+ const nestedCancellationError =+ nestedCancellation === undefined+ ? undefined+ : timeout.aborted && nestedCancellation.reason === timeout.reason+ ? new AnalysisTimeoutError(request.operation, timeoutMs, {+ cause: nestedCancellation.reason,+ ...jadxOperationTimeoutGuidance(timeoutMs),+ })+ : new AnalysisCancelledError(request.operation, {+ cause: nestedCancellation.reason,+ });+ const snapshotObservation =+ completed === undefined+ ? undefined+ : {+ kind: "file-snapshot-hash" as const,+ path: completed.snapshotPath,+ sha256: completed.sha256,+ bytes: completed.bytes,+ };+ if (completed !== undefined && nestedCancellationError === undefined)+ return new ProviderCleanupError(+ "jadx",+ descriptorPaths,+ {+ reason,+ snapshot_copy: "completed",+ source_path: completed.sourcePath,+ snapshot_sha256: completed.sha256,+ snapshot_bytes: completed.bytes,+ },+ {+ operation: request.operation,+ cause,+ ...(snapshotObservation === undefined+ ? {}+ : { partialObservation: snapshotObservation }),+ },+ );+ const primaryCause = nestedOperationCause(cause);const primary =- cancellationError ??+ nestedCancellationError ??(primaryCause instanceof AnalysisError? primaryCause: new ProviderAdapterError("jadx", request.operation, {@@ -132,18 +183,47 @@ const observeJadxFailure = (}));const cleanup = new ProviderCleanupError("jadx",- [cause.path],+ descriptorPaths,{- reason:- cause.cleanupCause instanceof Error- ? cause.cleanupCause.message- : String(cause.cleanupCause),+ reason,+ ...(completed === undefined+ ? {}+ : {+ snapshot_copy: "completed" as const,+ source_path: completed.sourcePath,+ snapshot_sha256: completed.sha256,+ snapshot_bytes: completed.bytes,+ }),},{ operation: request.operation, cause },);- return analysisErrorWithCleanupFailure(primary, cleanup, request.operation);+ const composed = analysisErrorWithCleanupFailure(+ primary,+ cleanup,+ request.operation,+ );+ if (snapshotObservation !== undefined)+ composed.retainPartialObservation(snapshotObservation);+ return composed;+ }+ if (cancellationError !== undefined) {+ const completed = completedSnapshotCopy(cause);+ if (completed !== undefined) {+ cancellationError.retainPartialObservation({+ kind: "file-snapshot-hash",+ path: completed.snapshotPath,+ sha256: completed.sha256,+ bytes: completed.bytes,+ });+ cancellationError.retainDiagnostics({+ snapshot_copy: "completed",+ source_path: completed.sourcePath,+ snapshot_sha256: completed.sha256,+ snapshot_bytes: completed.bytes,+ });+ }+ return cancellationError;}- if (cancellationError !== undefined) return cancellationError;if (cause instanceof StableFileHashFailure)return new ProviderAdapterError("jadx", request.operation, {cause: cause.cause,@@ -176,6 +256,58 @@ const observeJadxFailure = ();};+/**+ * A finished copy can be the close outcome or the value inside a nested+ * cancellation thrown after the destination close succeeded.+ */+const completedSnapshotCopy = (+ cause: unknown,+): ReturnType<typeof androidSnapshotCopy> => {+ if (cause instanceof RegularFileCancelled)+ return androidSnapshotCopy(cause.outcome.value);+ if (!(cause instanceof RegularFileCleanupFailure)) return undefined;+ if (cause.outcome.kind === "completed")+ return androidSnapshotCopy(cause.outcome.value);+ return completedSnapshotCopy(cause.outcome.cause);+};++/** This close and any nested close whose failure is its operation outcome. */+const snapshotCloseFailures = (+ cause: RegularFileCleanupFailure,+): readonly RegularFileCleanupFailure[] => {+ const failures = [cause];+ if (+ cause.outcome.kind === "failed" &&+ cause.outcome.cause instanceof RegularFileCleanupFailure+ )+ failures.push(...snapshotCloseFailures(cause.outcome.cause));+ return failures;+};++/** Cancellation recorded on this close or on a nested descriptor close. */+const nestedFileCancellation = (+ cause: unknown,+): { readonly reason: unknown } | undefined => {+ const direct = regularFileCancellation(cause);+ if (direct !== undefined) return direct;+ if (+ cause instanceof RegularFileCleanupFailure &&+ cause.outcome.kind === "failed"+ )+ return nestedFileCancellation(cause.outcome.cause);+ return undefined;+};++/** The operation error under nested close failures, not the close wrapper. */+const nestedOperationCause = (cause: unknown): unknown => {+ if (+ cause instanceof RegularFileCleanupFailure &&+ cause.outcome.kind === "failed"+ )+ return nestedOperationCause(stableFileHashCause(cause.outcome.cause));+ return stableFileHashCause(cause);+};+const presentDiagnosticFailure = (failure: DiagnosticFailure,): AnalysisError => {diff --git a/src/android/JadxProvider.ts b/src/android/JadxProvider.tsindex 289c79528..7cf78055a 100644--- a/src/android/JadxProvider.ts+++ b/src/android/JadxProvider.ts@@ -125,6 +125,22 @@ interface PendingCleanup {reportedErrors: WeakRef<AnalysisError>[];}+/** Every descriptor owner nested in one rejected close, without treating a later owner as the first. */+const retainedCleanupOwners = (+ cause: unknown,+): ReadonlySet<OwnedFileHandle> => {+ const owners = new Set<OwnedFileHandle>();+ const visit = (value: unknown, seen: Set<unknown>): void => {+ if (typeof value !== "object" || value === null || seen.has(value)) return;+ seen.add(value);+ if (!(value instanceof RegularFileCleanupFailure)) return;+ owners.add(value.owner);+ if (value.outcome.kind === "failed") visit(value.outcome.cause, seen);+ };+ visit(cause, new Set());+ return owners;+};+const cleanupResources = (resources: PendingCleanup): readonly string[] => [...(resources.session === undefined? []@@ -166,16 +182,22 @@ const cleanup = async (sessionCloseFailed = true;sessionCloseCause = cause;}+ const tracked = retainedCleanupOwners(resources.operationCause);+ const trackedInMap = [...tracked].filter((owner) =>+ resources.fileHandles.has(owner),+ );const fileCloseCauses: unknown[] = [];for (const owner of resources.fileHandles.keys()) {try {await owner.close();+ resources.fileHandles.delete(owner);+ // One descriptor's release clears only that owner. The admission error+ // stays incomplete until every owner from the same close failure is gone.if (- resources.operationCause instanceof RegularFileCleanupFailure &&- resources.operationCause.owner === owner+ trackedInMap.length > 0 &&+ trackedInMap.every((candidate) => !resources.fileHandles.has(candidate)))resources.previousError?.resolveCleanup();- resources.fileHandles.delete(owner);} catch (cause: unknown) {fileCloseCauses.push(cause);}@@ -214,6 +236,8 @@ const cleanup = async (return err(cleanupFailure(resources, cleanupError));}try {+ // Child descriptors are released above. The workspace root follows only+ // after those owners confirm close.await root?.close();resources.root = undefined;} catch (cause) {@@ -510,12 +534,16 @@ export class JadxProvider implements AndroidAnalysisPort {root.failureSignal === undefined? signal: AbortSignal.any([signal, root.failureSignal]);+ const retainSnapshot = (path: string, owner: OwnedFileHandle): void => {+ fileHandles.set(owner, path);+ };const engine = await snapshotAndroidEngine(configuration.jar,jarHash,root.path,request.operation,workspaceSignal,+ retainSnapshot,);const snapshot = await snapshotAndroidTarget(target.path,@@ -523,6 +551,7 @@ export class JadxProvider implements AndroidAnalysisPort {root.path,request.operation,workspaceSignal,+ retainSnapshot,);const bridge = join(root.path, "ReaJadxBridge.java");await copyFile(BRIDGE_SOURCE, bridge);diff --git a/src/kuna/KunaProjectReader.ts b/src/kuna/KunaProjectReader.tsindex 605461ec1..c8e7b76f1 100644--- a/src/kuna/KunaProjectReader.ts+++ b/src/kuna/KunaProjectReader.ts@@ -2,13 +2,22 @@ import { createReadStream } from "node:fs";import { open } from "node:fs/promises";import { join } from "node:path";-import type { AnalysisError } from "../domain/analysisErrorBase.js";+import { AnalysisError } from "../domain/analysisErrorBase.js";+import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";import {AnalysisCancelledError,AnalysisResourceConstraintError,} from "../domain/analysisErrorCore.js";import { ProviderAdapterError } from "../domain/providerAdapterError.js";+import { ProviderCleanupError } from "../domain/providerCleanupError.js";import { err, ok, type Result } from "../domain/result.js";+import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";+import {+ RegularFileCancelled,+ RegularFileCleanupFailure,+ withOwnedFileHandle,+} from "../filesystem/OwnedRegularFile.js";+import { RegularFileOperationCancelled } from "../filesystem/RegularFile.js";import { ABORTED, waitForAbortable } from "../process/AbortablePromise.js";import type { KunaProject } from "./KunaProjectCache.js";import {@@ -34,11 +43,33 @@ export interface KunaProjectText {readonly limitations: readonly string[];}+/** Session scope that adopts a span descriptor before the read opens it. */+export interface KunaSpanOwnership {+ readonly retainFailedClose?: (path: string, owner: OwnedFileHandle) => void;+ readonly bindSpanCleanup?: (+ owner: OwnedFileHandle,+ marker: ProviderCleanupError,+ ) => void;+ /**+ * Check retained cleanup and open one descriptor. The session holds this+ * together with finishSpan so a failed close is retained before the next open.+ */+ readonly admitSpan?: <T>(+ operation: string,+ signal: AbortSignal | undefined,+ open: () => Promise<T>,+ ) => Promise<Result<T, AnalysisError>>;+ /** Close one admitted descriptor before another span may open. */+ readonly finishSpan?: <T>(finish: () => Promise<T>) => Promise<T>;+}+const readSpan = async (operation: string,path: string,offset: number,length: number,+ ownership: KunaSpanOwnership,+ signal?: AbortSignal,): Promise<Result<string, AnalysisError>> => {if (length > KUNA_FUNCTION_TEXT_BYTES)return err(@@ -54,16 +85,168 @@ const readSpan = async (},),);- const handle = await open(path, "r");+ const callerAborted = (): AbortSignal | undefined =>+ signal?.aborted === true ? signal : undefined;+ const cancelled = callerAborted();+ if (cancelled !== undefined)+ return err(+ new AnalysisCancelledError(operation, { cause: cancelled.reason }),+ );+ const opened =+ ownership.admitSpan === undefined+ ? ok(await open(path, "r"))+ : await ownership.admitSpan(operation, signal, () => open(path, "r"));+ if (!opened.ok) return opened;+ const owner = new OwnedFileHandle(opened.value);+ let text: string | undefined;+ let readFailure: unknown;try {const buffer = Buffer.alloc(length);- const { bytesRead } = await handle.read(buffer, 0, length, offset);+ const { bytesRead } = await owner.handle.read(buffer, 0, length, offset);if (bytesRead !== length)throw new Error(`${path} is shorter than its recorded span`);- return ok(buffer.toString("utf8"));- } finally {- await handle.close();+ text = buffer.toString("utf8");+ } catch (cause: unknown) {+ readFailure = cause;}+ const finish = () =>+ withOwnedFileHandle(+ path,+ owner,+ {+ // A failed read keeps its own diagnostic. A completed read records+ // cancellation when the caller aborts before the queued close settles.+ ...(readFailure === undefined && signal !== undefined+ ? { signal }+ : {}),+ ...(ownership.retainFailedClose === undefined+ ? {}+ : {+ retainFailedClose: (failed) =>+ ownership.retainFailedClose?.(path, failed),+ }),+ },+ async () => {+ if (readFailure !== undefined) throw readFailure;+ return text ?? "";+ },+ );+ try {+ const value =+ ownership.finishSpan === undefined+ ? await finish()+ : await ownership.finishSpan(finish);+ return ok(value);+ } catch (cause: unknown) {+ if (cause instanceof RegularFileCleanupFailure)+ return err(+ spanCloseFailure(+ operation,+ path,+ offset,+ length,+ spanCloseAfterRead(cause, text, readFailure, signal),+ ownership,+ ),+ );+ // Close succeeded. The caller's abort reason is the cancellation cause,+ // not the wrapper thrown after that close.+ const aborted = callerAborted();+ if (+ aborted !== undefined &&+ (cause instanceof RegularFileOperationCancelled ||+ cause instanceof RegularFileCancelled)+ )+ return err(+ new AnalysisCancelledError(operation, { cause: aborted.reason }),+ );+ throw cause;+ }+};++/**+ * Finalization checks the signal before replaying a read that already+ * finished. Put that text back on the close failure so cancellation stays+ * the primary error and the descriptor stays retained.+ */+const spanCloseAfterRead = (+ failure: RegularFileCleanupFailure<string>,+ text: string | undefined,+ readFailure: unknown,+ signal: AbortSignal | undefined,+): RegularFileCleanupFailure<string> => {+ if (+ failure.completionCancellation !== undefined ||+ text === undefined ||+ readFailure !== undefined ||+ signal?.aborted !== true ||+ failure.outcome.kind !== "failed" ||+ !(failure.outcome.cause instanceof RegularFileOperationCancelled)+ )+ return failure;+ return new RegularFileCleanupFailure(+ failure.path,+ failure.owner,+ { kind: "completed", value: text },+ failure.cleanupCause,+ failure.retention,+ { reason: signal.reason },+ );+};++/** Keep the span text or the short-read diagnostic with the exact handle. */+const spanCloseFailure = (+ operation: string,+ path: string,+ offset: number,+ length: number,+ failure: RegularFileCleanupFailure<string>,+ ownership: KunaSpanOwnership,+): AnalysisError => {+ const reason =+ failure.cleanupCause instanceof Error+ ? failure.cleanupCause.message+ : String(failure.cleanupCause);+ const completed = failure.outcome.kind === "completed";+ const marker = new ProviderCleanupError(+ KUNA_PROVIDER_ID,+ [failure.path],+ {+ reason,+ path,+ byte_offset: offset,+ byte_length: length,+ span_read: completed ? "completed" : "failed",+ ...(completed ? { span_text: failure.outcome.value } : {}),+ },+ { operation, cause: failure },+ );+ ownership.bindSpanCleanup?.(failure.owner, marker);+ if (failure.completionCancellation !== undefined)+ return analysisErrorWithCleanupFailure(+ new AnalysisCancelledError(operation, {+ cause: failure.completionCancellation.reason,+ }),+ marker,+ operation,+ ).bindCleanupDependencies([marker]);+ if (failure.outcome.kind !== "failed") return marker;+ const primaryCause = failure.outcome.cause;+ const primary =+ primaryCause instanceof AnalysisError+ ? primaryCause+ : new ProviderAdapterError(KUNA_PROVIDER_ID, operation, {+ cause: primaryCause,+ userMessage:+ primaryCause instanceof Error+ ? primaryCause.message+ : String(primaryCause),+ });+ return analysisErrorWithCleanupFailure(+ primary,+ marker,+ operation,+ ).bindCleanupDependencies([marker]);};/** One immutable export owns both its text ranges and its parsed label indexes. */@@ -76,12 +259,13 @@ export class KunaProjectReader {readonly lifetime: {readonly signal: AbortSignal;readonly own: <T>(work: Promise<T>) => Promise<T>;- },+ } & KunaSpanOwnership,) {}async pseudocode(address: string,operation: string,+ signal?: AbortSignal,): Promise<Result<KunaProjectText, AnalysisError>> {this.#blocks ??= new Map(this.project.functions.map((block) => [block.address, block]),@@ -113,6 +297,8 @@ export class KunaProjectReader {join(this.project.directory, this.project.manifest.files.c.path),block.cOffset,block.cLength,+ this.lifetime,+ signal ?? this.lifetime.signal,);if (!text.ok) return text;return ok({@@ -144,6 +330,8 @@ export class KunaProjectReader {join(this.project.directory, this.project.manifest.files.asm.path),span.offset,span.length,+ this.lifetime,+ signal ?? this.lifetime.signal,);if (!text.ok) return text;return ok({diff --git a/src/kuna/KunaSessionClient.ts b/src/kuna/KunaSessionClient.tsindex 85c8fa681..4be16c916 100644--- a/src/kuna/KunaSessionClient.ts+++ b/src/kuna/KunaSessionClient.ts@@ -1,4 +1,8 @@-import { AnalysisCleanupLease } from "../artifacts/AnalysisCleanupLease.js";+import {+ AnalysisCleanupLease,+ AnalysisCleanupLeaseGroup,+} from "../artifacts/AnalysisCleanupLease.js";+import type { ArtifactResourceOwner } from "../artifacts/ArtifactResourceScope.js";import { z } from "zod";import {@@ -80,8 +84,12 @@ import {} from "./KunaProjectReader.js";import { kunaUnavailable } from "./KunaUnavailable.js";import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js";-import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";+import {+ ArtifactResourceRetryFailure,+ ArtifactResourceScope,+} from "../artifacts/ArtifactResourceScope.js";import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";+import type { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";import { kunaQueryFailureForCaller } from "./KunaQueryErrors.js";/** How often a request waiting on the project export reports that it still waits. */@@ -174,6 +182,29 @@ const failure = (operation: string, cause: unknown): AnalysisError =>userMessage: `Kuna ${operation} failed: ${message(cause)}`,});+/** Bind a refused descriptor retry to the leases that still own those handles. */+const descriptorCleanupError = (+ cause: ArtifactReaderFailure,+ operation: string,+): ProviderCleanupError => {+ const observation = ArtifactReaderFailure.cleanupObservation(+ cause,+ "Kuna provider file descriptor",+ );+ const error = new ProviderCleanupError(+ KUNA_PROVIDER_ID,+ observation.resources,+ { reason: observation.reason },+ { cause, operation },+ );+ if (+ cause instanceof ArtifactResourceRetryFailure &&+ cause.cleanupLeases.length > 0+ )+ new AnalysisCleanupLeaseGroup(error, cause.cleanupLeases);+ return error;+};+/*** How a request that needs the export reports the export's failure. A session* never rebuilds a failed export, so repeating the request cannot succeed; the@@ -240,6 +271,18 @@ export class KunaSessionClient implements AnalysisClient {readonly #runSlots: KunaRunSlots;readonly #launcher: KunaProcessLauncher | undefined;readonly #resourceScope = new ArtifactResourceScope();+ readonly #spanLeases = new Map<+ OwnedFileHandle,+ {+ readonly lease: AnalysisCleanupLease;+ readonly scopeOwner: ArtifactResourceOwner;+ }+ >();+ /**+ * Serializes span admission and finalization. The byte read stays outside+ * this queue so one held read does not block another span's open.+ */+ #spanAdmission: Promise<void> = Promise.resolve();/** Single-function runs in flight, by entry address. */readonly #singleFunctionRuns = new Map<string, SingleFunctionRun>();/** Completed single-function texts by address, least recently used first. */@@ -349,6 +392,10 @@ export class KunaSessionClient implements AnalysisClient {parameters: Readonly<Record<string, JsonValue>>,options: ExecutionOptions,): Promise<Result<AnalysisExecution, AnalysisError>> {+ // A peer can retain a descriptor after this check. Each span open rechecks+ // under #admitSpan, which shares its queue with that descriptor's close.+ const pendingDescriptors = await this.#pendingDescriptorCleanup(operation);+ if (pendingDescriptors !== undefined) return err(pendingDescriptors);if (cancelled(options.signal))return err(new AnalysisCancelledError(operation, {@@ -467,18 +514,8 @@ export class KunaSessionClient implements AnalysisClient {try {await this.#resourceScope.close();} catch (cause: unknown) {- const observation = ArtifactReaderFailure.cleanupObservation(- cause,- "Kuna provider file descriptor",- );- failures.push(- new ProviderCleanupError(- KUNA_PROVIDER_ID,- observation.resources,- { reason: observation.reason },- { cause, operation: "close_binary" },- ),- );+ if (!(cause instanceof ArtifactReaderFailure)) throw cause;+ failures.push(descriptorCleanupError(cause, "close_binary"));}if (failures.length > 0)return err(@@ -973,7 +1010,11 @@ export class KunaSessionClient implements AnalysisClient {const reader = this.#reader;if (reader !== undefined) {try {- const text = await reader.pseudocode(entry.address, operation);+ const text = await reader.pseudocode(+ entry.address,+ operation,+ options.signal,+ );if (!text.ok) return text;return ok({...text.value,@@ -1205,7 +1246,11 @@ export class KunaSessionClient implements AnalysisClient {): Promise<Result<Answer, AnalysisError>> {const assembly = await reader.assembly(entry.address, operation, signal);if (!assembly.ok) return assembly;- const pseudocode = await reader.pseudocode(entry.address, operation);+ const pseudocode = await reader.pseudocode(+ entry.address,+ operation,+ signal,+ );if (!pseudocode.ok) return pseudocode;const text =typeof pseudocode.value.result === "string"@@ -1555,7 +1600,126 @@ export class KunaSessionClient implements AnalysisClient {: new KunaProjectReader(project, {signal: this.#session.signal,own: (work) => this.#own(work),+ retainFailedClose: (path, owner) => {+ const lease = AnalysisCleanupLease.forCloseOwner(owner, path);+ const scopeOwner: ArtifactResourceOwner = {+ kind: "lease",+ resource: path,+ lease,+ };+ this.#spanLeases.set(owner, { lease, scopeOwner });+ this.#resourceScope.retain(scopeOwner);+ },+ bindSpanCleanup: (owner, marker) => {+ this.#spanLeases.get(owner)?.lease.bindCleanupError(marker);+ },+ admitSpan: (operation, signal, open) =>+ this.#admitSpan(operation, signal, open),+ finishSpan: (finish) => this.#finishSpan(finish),+ });+ }++ #enqueueSpan<T>(work: () => Promise<T>): Promise<T> {+ const admitted = this.#spanAdmission.then(work, work);+ this.#spanAdmission = admitted.then(+ () => undefined,+ () => undefined,+ );+ return admitted;+ }++ /**+ * Recheck retained closes and the caller signal immediately before open.+ * Finalization uses the same queue, so this cannot pass between a rejected+ * close and the lease that records it.+ */+ #admitSpan<T>(+ operation: string,+ signal: AbortSignal | undefined,+ open: () => Promise<T>,+ ): Promise<Result<T, AnalysisError>> {+ const callerAborted = (): AbortSignal | undefined =>+ signal?.aborted === true ? signal : undefined;+ return this.#enqueueSpan(async () => {+ const cancelledBefore = callerAborted();+ if (cancelledBefore !== undefined)+ return err(+ new AnalysisCancelledError(operation, {+ cause: cancelledBefore.reason,+ }),+ );+ const pending = await this.#pendingDescriptorCleanup(operation);+ if (pending !== undefined) return err(pending);+ const cancelledAfter = callerAborted();+ if (cancelledAfter !== undefined)+ return err(+ new AnalysisCancelledError(operation, {+ cause: cancelledAfter.reason,+ }),+ );+ return ok(await open());+ });+ }++ /** Release or retain this descriptor before the next span is admitted. */+ #finishSpan<T>(finish: () => Promise<T>): Promise<T> {+ return this.#enqueueSpan(finish);+ }++ /**+ * Retry span descriptors before another read. Installation cleanup stays on+ * the shared scope and is not re-adjudicated here.+ */+ async #pendingDescriptorCleanup(+ operation: string,+ ): Promise<AnalysisError | undefined> {+ const pending = [...this.#spanLeases.entries()].filter(+ ([, retained]) => !retained.lease.released,+ );+ if (pending.length === 0) return undefined;+ const failures: {+ readonly lease: AnalysisCleanupLease;+ readonly cause: unknown;+ readonly path: string;+ }[] = [];+ for (const [owner, retained] of pending) {+ const attempt = await this.#resourceScope.release(retained.scopeOwner);+ if (attempt.kind === "failed") {+ failures.push({+ lease: retained.lease,+ cause: attempt.cause,+ path:+ retained.lease.cleanupResources?.[0] ??+ retained.scopeOwner.resource,});+ continue;+ }+ this.#spanLeases.delete(owner);+ }+ if (failures.length === 0) return undefined;+ const error = new ProviderCleanupError(+ KUNA_PROVIDER_ID,+ failures.map(({ path }) => path),+ {+ reason: failures+ .map(({ cause }) =>+ cause instanceof Error ? cause.message : String(cause),+ )+ .join("; "),+ },+ {+ operation,+ cause: new AggregateError(+ failures.map(({ cause }) => cause),+ "Kuna span descriptor cleanup remains incomplete",+ ),+ },+ );+ new AnalysisCleanupLeaseGroup(+ error,+ failures.map(({ lease }) => lease),+ );+ return error;}/** The export's failure once it has settled; undefined while it builds or after success. */diff --git a/tests/boundary/process/androidSnapshotClose.test.ts b/tests/boundary/process/androidSnapshotClose.test.tsnew file mode 100644index 000000000..4b94506c6--- /dev/null+++ b/tests/boundary/process/androidSnapshotClose.test.ts@@ -0,0 +1,630 @@+import { createHash } from "node:crypto";+import { type FileHandle, readFile, stat } from "node:fs/promises";+import { sep } from "node:path";++import { expect, test, vi } from "vitest";++import { captureJadxFailure } from "../../../src/android/JadxFailure.js";+import type { AndroidRequest } from "../../../src/domain/android/androidAnalysis.js";+import {+ AnalysisCancelledError,+ AnalysisInputError,+} from "../../../src/domain/analysisErrorCore.js";+import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";+import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";+import { OwnedFileHandle } from "../../../src/filesystem/OwnedFileHandle.js";+import {+ RegularFileCancelled,+ RegularFileCleanupFailure,+} from "../../../src/filesystem/OwnedRegularFile.js";+import {+ createJadxProtocolFixture,+ verifyJadxFixtureCleanup,+} from "../../fixtures/android/jadx.js";++const state = vi.hoisted(() => ({+ enabled: false,+ change: false,+ fail: false,+ failSource: false,+ failAdmission: false,+ source: "",+ closeCalls: 0,+ sourceCloseCalls: 0,+ opens: 0,+ sourceOpens: 0,+ handles: [] as { handle: FileHandle; close: () => Promise<void> }[],+ sourceHandles: [] as { handle: FileHandle; close: () => Promise<void> }[],+ latestSource: undefined as+ | {+ handle: FileHandle;+ close: () => Promise<void>;+ snapshot: boolean;+ }+ | undefined,+}));++vi.mock("node:fs/promises", async (importOriginal) => {+ const actual = await importOriginal<typeof import("node:fs/promises")>();+ return {+ ...actual,+ open: async (...args: Parameters<typeof actual.open>) => {+ const handle = await actual.open(...args);+ const path = String(args[0]);+ if (+ state.enabled &&+ path === state.source &&+ typeof args[1] === "number"+ ) {+ state.sourceOpens += 1;+ const close = handle.close.bind(handle);+ const record = {+ handle,+ close,+ snapshot: false,+ admit: state.failAdmission && state.sourceOpens > 1,+ };+ state.latestSource = record;+ state.sourceHandles.push(record);+ if (record.admit) {+ handle.stat = async () => {+ throw Object.assign(new Error("controlled admission stat EIO"), {+ code: "EIO",+ });+ };+ }+ handle.close = async () => {+ state.sourceCloseCalls += 1;+ // Only the descriptor still open when the snapshot destination is+ // created belongs to the copy. Later admission reads must close.+ if (record.admit && state.failAdmission)+ throw Object.assign(new Error("controlled admission close EIO"), {+ code: "EIO",+ });+ if (record.snapshot && state.failSource)+ throw Object.assign(new Error("controlled source close EIO"), {+ code: "EIO",+ });+ return close();+ };+ }+ if (+ state.enabled &&+ path.endsWith(`${sep}target.apk`) &&+ args[1] === "wx"+ ) {+ state.opens += 1;+ if (+ state.latestSource !== undefined &&+ state.latestSource.handle.fd >= 0+ )+ state.latestSource.snapshot = true;+ if (state.change) await actual.appendFile(state.source, "changed");+ const close = handle.close.bind(handle);+ state.handles.push({ handle, close });+ handle.close = async () => {+ state.closeCalls += 1;+ if (state.fail)+ throw Object.assign(new Error("controlled snapshot close EIO"), {+ code: "EIO",+ });+ return close();+ };+ }+ return handle;+ },+ };+});++const snapshotResource = (resources: readonly string[]): string | undefined =>+ resources.find((resource) => resource.endsWith(`${sep}target.apk`));++test("keeps the stable-file diagnosis when snapshot close succeeds", async () => {+ const fixture = await createJadxProtocolFixture();+ state.source = fixture.apk;+ state.change = true;+ state.fail = false;+ state.failSource = false;+ state.enabled = true;+ state.closeCalls = 0;+ state.sourceCloseCalls = 0;+ state.opens = 0;+ state.sourceOpens = 0;+ state.handles = [];+ state.sourceHandles = [];+ state.latestSource = undefined;+ try {+ const result = await fixture.service.execute("inspect_android_package", {+ path: fixture.apk,+ });+ expect(result.ok).toBe(false);+ if (result.ok) return;+ expect(projectAnalysisError(result.error).code).toBe("invalid_request");+ expect(result.error).toBeInstanceOf(AnalysisInputError);+ expect(result.error.cause?.constructor.name).toBe(+ "AndroidSnapshotChangedError",+ );+ expect(result.error.cleanupIncomplete).toBe(false);+ expect(state.handles[0]?.handle.fd).toBe(-1);+ expect(fixture.launches).toHaveLength(0);+ await fixture.provider.close();+ } finally {+ state.enabled = false;+ state.fail = false;+ await fixture.provider.close().catch(() => undefined);+ await verifyJadxFixtureCleanup(fixture.launches);+ }+});++for (const mode of [+ "changed-close-failure",+ "completed-close-failure",+] as const)+ test(`retains the destination descriptor when snapshot close fails (${mode})`, async () => {+ const fixture = await createJadxProtocolFixture();+ const sourceBytes = await readFile(fixture.apk);+ const sha256 = createHash("sha256").update(sourceBytes).digest("hex");+ state.source = fixture.apk;+ state.change = mode === "changed-close-failure";+ state.fail = true;+ state.failSource = false;+ state.enabled = true;+ state.closeCalls = 0;+ state.sourceCloseCalls = 0;+ state.opens = 0;+ state.sourceOpens = 0;+ state.handles = [];+ state.sourceHandles = [];+ state.latestSource = undefined;+ try {+ const result = await fixture.service.execute("inspect_android_package", {+ path: fixture.apk,+ });+ expect(result.ok).toBe(false);+ if (result.ok) return;+ expect(projectAnalysisError(result.error).code).toBe(+ "cleanup_incomplete",+ );+ expect(result.error.cleanupIncomplete).toBe(true);+ expect(JSON.stringify(projectAnalysisError(result.error))).toContain(+ "controlled snapshot close EIO",+ );+ const owned = state.handles[0];+ if (owned === undefined)+ throw new Error("missing destination descriptor");+ expect(owned.handle.fd).toBeGreaterThanOrEqual(0);+ expect(state.opens).toBe(1);+ expect(fixture.launches).toHaveLength(0);+ const snapshot = snapshotResource(result.error.cleanupResources);+ expect(snapshot).toBeDefined();+ const workspace = snapshot?.slice(0, -`${sep}target.apk`.length);+ if (workspace === undefined)+ throw new Error("missing snapshot workspace");+ await expect(stat(workspace)).resolves.toMatchObject({+ isDirectory: expect.any(Function),+ });+ if (mode === "changed-close-failure") {+ expect(result.error.cleanupPrimary?.cleanupPrimary).toBeInstanceOf(+ AnalysisInputError,+ );+ expect(+ result.error.cleanupPrimary?.cleanupPrimary?.cause?.constructor.name,+ ).toBe("AndroidSnapshotChangedError");+ expect(+ projectAnalysisError(+ result.error.cleanupPrimary?.cleanupPrimary ?? result.error,+ ).code,+ ).toBe("invalid_request");+ } else {+ expect(result.error.cleanupPrimary).toBeInstanceOf(+ ProviderCleanupError,+ );+ expect(result.error.cleanupPrimary?.diagnostics).toMatchObject({+ snapshot_copy: "completed",+ snapshot_sha256: sha256,+ snapshot_bytes: sourceBytes.length,+ reason: "controlled snapshot close EIO",+ });+ expect(result.error.partialObservation).toMatchObject({+ kind: "file-snapshot-hash",+ sha256,+ bytes: sourceBytes.length,+ });+ }++ const opens = state.opens;+ const closeCalls = state.closeCalls;+ const blocked = await fixture.service.execute("inspect_android_package", {+ path: fixture.apk,+ });+ expect(blocked.ok).toBe(false);+ if (blocked.ok) return;+ expect(blocked.error.cleanupIncomplete).toBe(true);+ expect(state.opens).toBe(opens);+ expect(state.closeCalls).toBeGreaterThan(closeCalls);+ expect(owned.handle.fd).toBeGreaterThanOrEqual(0);+ await expect(stat(workspace)).resolves.toBeTruthy();++ const closeCallsBeforeShutdown = state.closeCalls;+ await expect(fixture.provider.close()).rejects.toMatchObject({+ cleanupIncomplete: true,+ });+ expect(state.closeCalls).toBeGreaterThan(closeCallsBeforeShutdown);+ expect(owned.handle.fd).toBeGreaterThanOrEqual(0);+ expect(result.error.cleanupIncomplete).toBe(true);+ await expect(stat(workspace)).resolves.toBeTruthy();++ state.fail = false;+ await fixture.provider.close();+ expect(owned.handle.fd).toBe(-1);+ expect(result.error.cleanupIncomplete).toBe(false);+ expect(blocked.error.cleanupIncomplete).toBe(false);+ await expect(stat(workspace)).rejects.toMatchObject({ code: "ENOENT" });+ } finally {+ state.enabled = false;+ state.fail = false;+ await fixture.provider.close().catch(() => undefined);+ for (const owned of [...state.handles, ...state.sourceHandles])+ if (owned.handle.fd >= 0) await owned.close().catch(() => undefined);+ await verifyJadxFixtureCleanup(fixture.launches);+ }+ });++for (const mode of ["source-close-failure", "both-close-failure"] as const)+ test(`attributes a finished copy to the descriptor that rejected close (${mode})`, async () => {+ const fixture = await createJadxProtocolFixture();+ const sourceBytes = await readFile(fixture.apk);+ const sha256 = createHash("sha256").update(sourceBytes).digest("hex");+ state.source = fixture.apk;+ state.change = false;+ state.fail = mode === "both-close-failure";+ state.failSource = true;+ state.enabled = true;+ state.closeCalls = 0;+ state.sourceCloseCalls = 0;+ state.opens = 0;+ state.sourceOpens = 0;+ state.handles = [];+ state.sourceHandles = [];+ state.latestSource = undefined;+ try {+ const result = await fixture.service.execute("inspect_android_package", {+ path: fixture.apk,+ });+ expect(result.ok).toBe(false);+ if (result.ok) return;+ expect(projectAnalysisError(result.error).code).toBe(+ "cleanup_incomplete",+ );+ expect(result.error.cleanupIncomplete).toBe(true);+ expect(result.error.cleanupPrimary).toBeInstanceOf(ProviderCleanupError);+ expect(result.error.cleanupPrimary?.diagnostics).toMatchObject({+ snapshot_copy: "completed",+ source_path: fixture.apk,+ snapshot_sha256: sha256,+ snapshot_bytes: sourceBytes.length,+ });+ expect(result.error.partialObservation).toMatchObject({+ kind: "file-snapshot-hash",+ sha256,+ bytes: sourceBytes.length,+ });+ const observation = result.error.partialObservation;+ if (+ observation === undefined ||+ !("path" in observation) ||+ typeof observation.path !== "string"+ )+ throw new Error("missing snapshot observation");+ const snapshotPath = observation.path;+ expect(snapshotPath).toContain(`${sep}target.apk`);+ const ownedPaths = [fixture.apk];+ if (mode === "both-close-failure" && snapshotPath !== undefined)+ ownedPaths.push(snapshotPath);+ expect(result.error.cleanupPrimary?.cleanupResources).toEqual(ownedPaths);+ expect(result.error.diagnostics).toMatchObject({+ primary_error: {+ details: {+ resources: ownedPaths,+ diagnostics: {+ snapshot_copy: "completed",+ snapshot_sha256: sha256,+ snapshot_bytes: sourceBytes.length,+ },+ },+ },+ });+ const source = state.sourceHandles.find(+ (candidate) => candidate.handle.fd >= 0,+ );+ if (source === undefined) throw new Error("missing source descriptor");+ expect(source.handle.fd).toBeGreaterThanOrEqual(0);+ expect(state.opens).toBe(1);+ const destination = state.handles[0];+ if (destination === undefined)+ throw new Error("missing destination descriptor");+ if (mode === "both-close-failure")+ expect(destination.handle.fd).toBeGreaterThanOrEqual(0);+ else expect(destination.handle.fd).toBe(-1);+ const workspace = snapshotPath?.slice(0, -`${sep}target.apk`.length);+ if (workspace === undefined)+ throw new Error("missing snapshot workspace");+ await expect(stat(workspace)).resolves.toBeTruthy();++ const opens = state.opens;+ const blocked = await fixture.service.execute("inspect_android_package", {+ path: fixture.apk,+ });+ expect(blocked.ok).toBe(false);+ if (blocked.ok) return;+ expect(blocked.error.cleanupIncomplete).toBe(true);+ expect(state.opens).toBe(opens);+ expect(source.handle.fd).toBeGreaterThanOrEqual(0);++ await expect(fixture.provider.close()).rejects.toMatchObject({+ cleanupIncomplete: true,+ });+ expect(source.handle.fd).toBeGreaterThanOrEqual(0);+ expect(result.error.cleanupIncomplete).toBe(true);++ state.fail = false;+ state.failSource = false;+ await fixture.provider.close();+ expect(source.handle.fd).toBe(-1);+ if (mode === "both-close-failure") expect(destination.handle.fd).toBe(-1);+ expect(result.error.cleanupIncomplete).toBe(false);+ expect(blocked.error.cleanupIncomplete).toBe(false);+ await expect(stat(workspace)).rejects.toMatchObject({ code: "ENOENT" });+ } finally {+ state.enabled = false;+ state.fail = false;+ state.failSource = false;+ await fixture.provider.close().catch(() => undefined);+ for (const owned of [...state.handles, ...state.sourceHandles])+ if (owned.handle.fd >= 0) await owned.close().catch(() => undefined);+ await verifyJadxFixtureCleanup(fixture.launches);+ }+ });++test("keeps the changed-file diagnosis when both snapshot closes fail", async () => {+ const fixture = await createJadxProtocolFixture();+ state.source = fixture.apk;+ state.change = true;+ state.fail = true;+ state.failSource = true;+ state.enabled = true;+ state.closeCalls = 0;+ state.sourceCloseCalls = 0;+ state.opens = 0;+ state.sourceOpens = 0;+ state.handles = [];+ state.sourceHandles = [];+ state.latestSource = undefined;+ try {+ const result = await fixture.service.execute("inspect_android_package", {+ path: fixture.apk,+ });+ expect(result.ok).toBe(false);+ if (result.ok) return;+ expect(projectAnalysisError(result.error).code).toBe("cleanup_incomplete");+ expect(result.error.cleanupPrimary?.cleanupPrimary).toBeInstanceOf(+ AnalysisInputError,+ );+ expect(+ result.error.cleanupPrimary?.cleanupPrimary?.cause?.constructor.name,+ ).toBe("AndroidSnapshotChangedError");+ const source = state.sourceHandles.find(+ (candidate) => candidate.handle.fd >= 0,+ );+ const destination = state.handles[0];+ if (source === undefined || destination === undefined)+ throw new Error("missing snapshot descriptors");+ expect(source.handle.fd).toBeGreaterThanOrEqual(0);+ expect(destination.handle.fd).toBeGreaterThanOrEqual(0);+ const resources = result.error.cleanupPrimary?.cleanupResources ?? [];+ expect(resources).toContain(fixture.apk);+ expect(snapshotResource(resources)).toBeDefined();+ } finally {+ state.enabled = false;+ state.fail = false;+ state.failSource = false;+ await fixture.provider.close().catch(() => undefined);+ for (const owned of [...state.handles, ...state.sourceHandles])+ if (owned.handle.fd >= 0) await owned.close().catch(() => undefined);+ await verifyJadxFixtureCleanup(fixture.launches);+ }+});++test("retains the source descriptor when snapshot admission cleanup fails", async () => {+ const fixture = await createJadxProtocolFixture();+ state.source = fixture.apk;+ state.change = false;+ state.fail = false;+ state.failSource = false;+ state.failAdmission = true;+ state.enabled = true;+ state.closeCalls = 0;+ state.sourceCloseCalls = 0;+ state.opens = 0;+ state.sourceOpens = 0;+ state.handles = [];+ state.sourceHandles = [];+ state.latestSource = undefined;+ try {+ const result = await fixture.service.execute("inspect_android_package", {+ path: fixture.apk,+ });+ expect(result.ok).toBe(false);+ if (result.ok) return;+ expect(projectAnalysisError(result.error).code).toBe("cleanup_incomplete");+ expect(result.error.cleanupIncomplete).toBe(true);+ expect(result.error.cleanupResources).toContain(fixture.apk);+ expect(state.opens).toBe(0);+ const source = state.sourceHandles.find(+ (candidate) => candidate.handle.fd >= 0,+ );+ if (source === undefined) throw new Error("missing source descriptor");+ expect(source.handle.fd).toBeGreaterThanOrEqual(0);+ await expect(fixture.provider.close()).rejects.toMatchObject({+ cleanupIncomplete: true,+ });+ expect(source.handle.fd).toBeGreaterThanOrEqual(0);++ state.failAdmission = false;+ await fixture.provider.close();+ expect(source.handle.fd).toBe(-1);+ expect(result.error.cleanupIncomplete).toBe(false);+ } finally {+ state.enabled = false;+ state.failAdmission = false;+ await fixture.provider.close().catch(() => undefined);+ for (const owned of [...state.handles, ...state.sourceHandles])+ if (owned.handle.fd >= 0) await owned.close().catch(() => undefined);+ await verifyJadxFixtureCleanup(fixture.launches);+ }+});++test("keeps the snapshot hash when a successful close is cancelled", () => {+ const reason = { requested: "snapshot-close" };+ const copy = {+ kind: "android-snapshot-copy" as const,+ sha256: "c".repeat(64),+ sourcePath: "/workspace/sample.apk",+ snapshotPath: "/workspace/snap/target.apk",+ bytes: 36,+ };+ const cancelled = new RegularFileCancelled(+ copy.snapshotPath,+ new OwnedFileHandle({+ fd: 7,+ close: async () => undefined,+ } as FileHandle),+ { outcome: { kind: "completed", value: copy }, reason },+ );+ const error = captureJadxFailure({+ cause: cancelled,+ request: {+ operation: "inspect_android_package",+ input: { path: copy.sourcePath },+ } as AndroidRequest,+ timeout: new AbortController().signal,+ timeoutMs: 1000,+ signal: AbortSignal.abort(reason),+ session: undefined,+ })();+ expect(error).toBeInstanceOf(AnalysisCancelledError);+ expect(error.cause).toBe(reason);+ expect(error.cleanupIncomplete).toBe(false);+ expect(error.partialObservation).toMatchObject({+ kind: "file-snapshot-hash",+ path: copy.snapshotPath,+ sha256: copy.sha256,+ bytes: copy.bytes,+ });+ expect(error.diagnostics).toMatchObject({+ snapshot_copy: "completed",+ source_path: copy.sourcePath,+ snapshot_sha256: copy.sha256,+ snapshot_bytes: copy.bytes,+ });+});++test("keeps the snapshot hash when cancellation wraps the finished copy", () => {+ const reason = { requested: "snapshot-close" };+ const copy = {+ kind: "android-snapshot-copy" as const,+ sha256: "b".repeat(64),+ sourcePath: "/workspace/sample.apk",+ snapshotPath: "/workspace/snap/target.apk",+ bytes: 24,+ };+ const destination = new RegularFileCancelled(+ copy.snapshotPath,+ new OwnedFileHandle({+ fd: 7,+ close: async () => undefined,+ } as FileHandle),+ { outcome: { kind: "completed", value: copy }, reason },+ );+ const source = new RegularFileCleanupFailure(+ copy.sourcePath,+ new OwnedFileHandle({+ fd: 8,+ close: async () => undefined,+ } as FileHandle),+ { kind: "failed", cause: destination },+ new Error("source EIO"),+ );+ const error = captureJadxFailure({+ cause: source,+ request: {+ operation: "inspect_android_package",+ input: { path: copy.sourcePath },+ } as AndroidRequest,+ timeout: new AbortController().signal,+ timeoutMs: 1000,+ signal: AbortSignal.abort(reason),+ session: undefined,+ })();+ expect(error.cleanupPrimary).toBeInstanceOf(AnalysisCancelledError);+ expect(error.cleanupPrimary?.cause).toBe(reason);+ expect(error.cleanupIncomplete).toBe(true);+ expect(error.cleanupResources).toEqual([copy.sourcePath]);+ expect(error.partialObservation).toMatchObject({+ kind: "file-snapshot-hash",+ path: copy.snapshotPath,+ sha256: copy.sha256,+ bytes: copy.bytes,+ });+});++test("classifies a nested snapshot close as cancellation", () => {+ const reason = { requested: "snapshot-close" };+ const copy = {+ kind: "android-snapshot-copy" as const,+ sha256: "a".repeat(64),+ sourcePath: "/workspace/sample.apk",+ snapshotPath: "/workspace/snap/target.apk",+ bytes: 12,+ };+ const destination = new RegularFileCleanupFailure(+ copy.snapshotPath,+ new OwnedFileHandle({+ fd: 7,+ close: async () => undefined,+ } as FileHandle),+ { kind: "completed", value: copy },+ new Error("dest EIO"),+ { kind: "not_requested" },+ { reason },+ );+ const source = new RegularFileCleanupFailure(+ copy.sourcePath,+ new OwnedFileHandle({+ fd: 8,+ close: async () => undefined,+ } as FileHandle),+ { kind: "failed", cause: destination },+ new Error("source EIO"),+ );+ const error = captureJadxFailure({+ cause: source,+ request: {+ operation: "inspect_android_package",+ input: { path: copy.sourcePath },+ } as AndroidRequest,+ timeout: new AbortController().signal,+ timeoutMs: 1000,+ signal: AbortSignal.abort(reason),+ session: undefined,+ })();+ expect(error.cleanupPrimary).toBeInstanceOf(AnalysisCancelledError);+ expect(error.cleanupIncomplete).toBe(true);+ expect(error.cleanupResources).toEqual([copy.sourcePath, copy.snapshotPath]);+ expect(error.partialObservation).toMatchObject({+ kind: "file-snapshot-hash",+ path: copy.snapshotPath,+ sha256: copy.sha256,+ bytes: copy.bytes,+ });+});diff --git a/tests/boundary/providers/kuna/kunaSpanCloseOwnership.test.ts b/tests/boundary/providers/kuna/kunaSpanCloseOwnership.test.tsnew file mode 100644index 000000000..6565c83db--- /dev/null+++ b/tests/boundary/providers/kuna/kunaSpanCloseOwnership.test.ts@@ -0,0 +1,454 @@+import { readdir, type FileHandle } from "node:fs/promises";+import { join } from "node:path";++import { afterEach, expect, it, vi } from "vitest";++import { ArtifactResourceScope } from "../../../../src/artifacts/ArtifactResourceScope.js";+import { AnalysisCancelledError } from "../../../../src/domain/analysisErrorCore.js";+import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";+import { ProviderCleanupError } from "../../../../src/domain/providerCleanupError.js";+import { run, session } from "./kunaSessionFixture.js";++const fault = vi.hoisted(() => ({+ fail: false,+ span: "",+ short: false,+ reads: 0,+ entered: 0,+ closeEntered: 0,+ closes: 0,+ opens: 0,+ hold: undefined as Promise<void> | undefined,+ releaseHold: (): void => undefined,+ afterRead: (): void => undefined,+ handles: [] as FileHandle[],+ cause: Object.assign(new Error("controlled close refusal"), { code: "EIO" }),+}));++vi.mock("node:fs/promises", async (importOriginal) => {+ const actual = await importOriginal<typeof import("node:fs/promises")>();+ return {+ ...actual,+ open: async (...args: Parameters<typeof actual.open>) => {+ const handle = await actual.open(...args);+ if (String(args[0]) !== fault.span) return handle;+ fault.opens += 1;+ fault.handles.push(handle);+ return new Proxy(handle, {+ get(target, key) {+ if (key === "read")+ return async (...readArgs: unknown[]) => {+ fault.entered += 1;+ const read = await Reflect.apply(target.read, target, readArgs);+ fault.reads += 1;+ fault.afterRead();+ return fault.short ? { ...read, bytesRead: 0 } : read;+ };+ if (key === "close")+ return async () => {+ fault.closeEntered += 1;+ if (fault.hold !== undefined) await fault.hold;+ fault.closes += 1;+ if (fault.fail) throw fault.cause;+ return target.close();+ };+ const value = Reflect.get(target, key, target);+ return typeof value === "function" ? value.bind(target) : value;+ },+ });+ },+ };+});++afterEach(() => {+ fault.releaseHold();+ fault.fail = false;+ fault.span = "";+ fault.short = false;+ fault.reads = 0;+ fault.entered = 0;+ fault.closeEntered = 0;+ fault.closes = 0;+ fault.opens = 0;+ fault.hold = undefined;+ fault.releaseHold = () => undefined;+ fault.afterRead = () => undefined;+ fault.handles = [];+});++it.each([false, true])(+ "preserves the span outcome and retries the exact handle when close fails (short=%s)",+ async (short) => {+ const { cacheRoot, open: createClient } = await session(+ "rea-kuna-span-close-",+ );+ const client = createClient();+ try {+ const warm = await run(client, "procedure_assembly", {+ procedure: "main",+ });+ const text = String(warm.result);+ const [key] = await readdir(join(cacheRoot, "projects"));+ fault.span = join(+ cacheRoot,+ "projects",+ key ?? "",+ "project",+ "program.asm",+ );+ fault.short = short;+ fault.fail = true;+ const result = await client.execute(+ "procedure_assembly",+ { procedure: "main" },+ {},+ );+ expect(result.ok).toBe(false);+ if (result.ok) return;+ expect(projectAnalysisError(result.error).code).toBe(+ "cleanup_incomplete",+ );+ expect(result.error.cleanupIncomplete).toBe(true);+ expect(result.error.cleanupResources).toContain(fault.span);+ expect(fault.reads).toBe(1);+ expect(fault.closes).toBe(1);+ expect(fault.opens).toBe(1);+ const handle = fault.handles[0];+ if (handle === undefined) throw new Error("missing span descriptor");+ if (short) {+ expect(result.error.cleanupPrimary?.userMessage).toContain(+ "shorter than its recorded span",+ );+ expect(result.error.diagnostics?.span_read).toBeUndefined();+ } else {+ expect(result.error).toBeInstanceOf(ProviderCleanupError);+ expect(result.error.diagnostics).toMatchObject({+ span_read: "completed",+ span_text: expect.stringContaining(text),+ path: fault.span,+ });+ }+ const live = await handle.read(Buffer.alloc(4), 0, 4, 0);+ expect(live.bytesRead).toBe(4);++ const blocked = await client.execute(+ "procedure_assembly",+ { procedure: "main" },+ {},+ );+ expect(blocked.ok).toBe(false);+ if (blocked.ok) return;+ expect(blocked.error.cleanupIncomplete).toBe(true);+ expect(fault.reads).toBe(1);+ expect(fault.opens).toBe(1);+ expect(fault.closes).toBeGreaterThan(1);+ expect(handle.fd).toBeGreaterThanOrEqual(0);++ const closesBeforeShutdown = fault.closes;+ const closed = await client.close();+ expect(closed.ok).toBe(false);+ if (closed.ok) return;+ expect(closed.error.cleanupIncomplete).toBe(true);+ expect(fault.closes).toBeGreaterThan(closesBeforeShutdown);+ expect(handle.fd).toBeGreaterThanOrEqual(0);+ expect(result.error.cleanupIncomplete).toBe(true);+ const stillLive = await handle.read(Buffer.alloc(4), 0, 4, 0);+ expect(stillLive.bytesRead).toBe(4);++ fault.fail = false;+ const released = await client.close();+ expect(released).toEqual({ ok: true, value: null });+ expect(handle.fd).toBe(-1);+ expect(result.error.cleanupIncomplete).toBe(false);+ expect(blocked.error.cleanupIncomplete).toBe(false);+ expect(closed.error.cleanupIncomplete).toBe(false);+ } finally {+ fault.fail = false;+ fault.span = "";+ await client.close();+ for (const handle of fault.handles)+ if (handle.fd >= 0) await handle.close().catch(() => undefined);+ }+ },+);++it("does not open a second span while a peer still holds a failed close", async () => {+ const { cacheRoot, open: createClient } = await session(+ "rea-kuna-span-close-gate-",+ );+ const client = createClient();+ try {+ await run(client, "procedure_assembly", { procedure: "main" });+ const [key] = await readdir(join(cacheRoot, "projects"));+ fault.span = join(+ cacheRoot,+ "projects",+ key ?? "",+ "project",+ "program.asm",+ );+ fault.fail = true;+ fault.hold = new Promise<void>((resolve) => {+ fault.releaseHold = resolve;+ });+ const first = client.execute(+ "procedure_assembly",+ { procedure: "main" },+ {},+ );+ await vi.waitFor(() => {+ expect(fault.closeEntered).toBe(1);+ });+ const second = client.execute(+ "procedure_assembly",+ { procedure: "parse" },+ {},+ );+ await new Promise((resolve) => {+ setImmediate(resolve);+ });+ expect(fault.opens).toBe(1);+ expect(fault.reads).toBe(1);+ fault.releaseHold();+ const [firstResult, secondResult] = await Promise.all([first, second]);+ expect(firstResult.ok).toBe(false);+ if (firstResult.ok) return;+ expect(secondResult.ok).toBe(false);+ if (secondResult.ok) return;+ expect(firstResult.error.cleanupIncomplete).toBe(true);+ expect(secondResult.error.cleanupIncomplete).toBe(true);+ expect(secondResult.error.cleanupResources).toContain(fault.span);+ expect(fault.opens).toBe(1);+ expect(fault.reads).toBe(1);+ expect(fault.closes).toBeGreaterThanOrEqual(2);+ const handle = fault.handles[0];+ if (handle === undefined) throw new Error("missing span descriptor");+ expect(handle.fd).toBeGreaterThanOrEqual(0);+ const live = await handle.read(Buffer.alloc(4), 0, 4, 0);+ expect(live.bytesRead).toBe(4);+ } finally {+ fault.releaseHold();+ fault.fail = false;+ fault.hold = undefined;+ fault.span = "";+ await client.close();+ for (const handle of fault.handles)+ if (handle.fd >= 0) await handle.close().catch(() => undefined);+ }+});++it("does not open a queued span after its caller aborts", async () => {+ const { cacheRoot, open: createClient } = await session(+ "rea-kuna-span-close-cancel-",+ );+ const client = createClient();+ try {+ await run(client, "procedure_assembly", { procedure: "main" });+ const [key] = await readdir(join(cacheRoot, "projects"));+ fault.span = join(+ cacheRoot,+ "projects",+ key ?? "",+ "project",+ "program.asm",+ );+ fault.fail = true;+ fault.hold = new Promise<void>((resolve) => {+ fault.releaseHold = resolve;+ });+ const first = client.execute(+ "procedure_assembly",+ { procedure: "main" },+ {},+ );+ await vi.waitFor(() => {+ expect(fault.closeEntered).toBe(1);+ });+ const abort = new AbortController();+ const second = client.execute(+ "procedure_assembly",+ { procedure: "parse" },+ { signal: abort.signal },+ );+ await new Promise((resolve) => {+ setImmediate(resolve);+ });+ abort.abort();+ fault.releaseHold();+ const [firstResult, secondResult] = await Promise.all([first, second]);+ expect(firstResult.ok).toBe(false);+ expect(secondResult.ok).toBe(false);+ if (secondResult.ok) return;+ expect(secondResult.error).toBeInstanceOf(AnalysisCancelledError);+ expect(fault.opens).toBe(1);+ } finally {+ fault.releaseHold();+ fault.fail = false;+ fault.hold = undefined;+ fault.span = "";+ await client.close();+ for (const handle of fault.handles)+ if (handle.fd >= 0) await handle.close().catch(() => undefined);+ }+});++it.each(["before close", "during close"] as const)(+ "keeps the caller abort reason when span close succeeds (%s)",+ async (when) => {+ const reason = { requested: "span-close" };+ const { cacheRoot, open: createClient } = await session(+ `rea-kuna-span-close-reason-${when.replace(" ", "-")}-`,+ );+ const client = createClient();+ try {+ await run(client, "procedure_assembly", { procedure: "main" });+ const [key] = await readdir(join(cacheRoot, "projects"));+ fault.span = join(+ cacheRoot,+ "projects",+ key ?? "",+ "project",+ "program.asm",+ );+ const abort = new AbortController();+ if (when === "before close") fault.afterRead = () => abort.abort(reason);+ else {+ fault.hold = new Promise<void>((resolve) => {+ fault.releaseHold = resolve;+ });+ }+ const pending = client.execute(+ "procedure_assembly",+ { procedure: "main" },+ { signal: abort.signal },+ );+ if (when === "during close") {+ await vi.waitFor(() => {+ expect(fault.closeEntered).toBe(1);+ });+ abort.abort(reason);+ fault.releaseHold();+ }+ const result = await pending;+ expect(result.ok).toBe(false);+ if (result.ok) return;+ expect(result.error).toBeInstanceOf(AnalysisCancelledError);+ expect(result.error.cause).toBe(reason);+ expect(result.error.cleanupIncomplete).toBe(false);+ expect(fault.handles[0]?.fd).toBe(-1);+ expect(fault.opens).toBe(1);+ } finally {+ fault.releaseHold();+ fault.fail = false;+ fault.hold = undefined;+ fault.span = "";+ fault.afterRead = () => undefined;+ await client.close();+ for (const handle of fault.handles)+ if (handle.fd >= 0) await handle.close().catch(() => undefined);+ }+ },+);++it("keeps cancellation when a completed span close fails after abort", async () => {+ const reason = { requested: "span-close" };+ const { cacheRoot, open: createClient } = await session(+ "rea-kuna-span-close-cancel-read-",+ );+ const client = createClient();+ try {+ const warm = await run(client, "procedure_assembly", {+ procedure: "main",+ });+ const text = String(warm.result);+ const [key] = await readdir(join(cacheRoot, "projects"));+ fault.span = join(+ cacheRoot,+ "projects",+ key ?? "",+ "project",+ "program.asm",+ );+ fault.fail = true;+ const abort = new AbortController();+ fault.afterRead = () => abort.abort(reason);+ const result = await client.execute(+ "procedure_assembly",+ { procedure: "main" },+ { signal: abort.signal },+ );+ expect(result.ok).toBe(false);+ if (result.ok) return;+ expect(result.error.cleanupIncomplete).toBe(true);+ expect(result.error.cleanupResources).toContain(fault.span);+ expect(result.error.cleanupPrimary).toBeInstanceOf(AnalysisCancelledError);+ expect(result.error.cleanupPrimary?.cause).toBe(reason);+ expect(result.error.diagnostics).toMatchObject({+ cleanup_error: {+ details: {+ diagnostics: {+ span_read: "completed",+ span_text: expect.stringContaining(text),+ },+ },+ },+ });+ const handle = fault.handles[0];+ if (handle === undefined) throw new Error("missing span descriptor");+ expect(handle.fd).toBeGreaterThanOrEqual(0);+ expect(fault.opens).toBe(1);+ } finally {+ fault.fail = false;+ fault.span = "";+ fault.afterRead = () => undefined;+ await client.close();+ for (const handle of fault.handles)+ if (handle.fd >= 0) await handle.close().catch(() => undefined);+ }+});++it("removes a span lease from the resource scope after close succeeds", async () => {+ const release = vi.spyOn(ArtifactResourceScope.prototype, "release");+ const { cacheRoot, open: createClient } = await session(+ "rea-kuna-span-scope-release-",+ );+ const client = createClient();+ try {+ await run(client, "procedure_assembly", { procedure: "main" });+ const [key] = await readdir(join(cacheRoot, "projects"));+ fault.span = join(+ cacheRoot,+ "projects",+ key ?? "",+ "project",+ "program.asm",+ );+ fault.fail = true;+ const failed = await client.execute(+ "procedure_assembly",+ { procedure: "main" },+ {},+ );+ expect(failed.ok).toBe(false);+ fault.fail = false;+ const recovered = await client.execute(+ "procedure_assembly",+ { procedure: "main" },+ {},+ );+ expect(recovered.ok).toBe(true);+ expect(+ release.mock.calls.some(+ ([owner]) => owner.kind === "lease" && owner.resource === fault.span,+ ),+ ).toBe(true);+ expect(fault.handles[0]?.fd).toBe(-1);+ } finally {+ release.mockRestore();+ fault.fail = false;+ fault.span = "";+ await client.close();+ for (const handle of fault.handles)+ if (handle.fd >= 0) await handle.close().catch(() => undefined);+ }+});