diff --git a/scripts/verify/architecture-guards.mjs b/scripts/verify/architecture-guards.mjs index cbf1129498..5d401b8e88 100644 --- a/scripts/verify/architecture-guards.mjs +++ b/scripts/verify/architecture-guards.mjs @@ -691,7 +691,7 @@ checkCounted( // AnalysisError has no push API. Composing dependency sets with // bindCleanupDependencies() is being replaced, so it may not spread. checkCounted( - "bindCleanupDependencies() composition outside the error base (compose through analysisErrorWithCleanupDependencies or runOwned, or copy lease claims)", + "bindCleanupDependencies() composition outside the error base (compose through analysisErrorWithCleanupDependencies, analysisErrorWithCloseRejection(s) for close rejections whose completion may be unknown, or runOwned, or copy lease claims)", "cleanup-dependency-binding", files, /\.bindCleanupDependencies\(/gu, diff --git a/scripts/verify/baselines/cleanup-dependency-binding.json b/scripts/verify/baselines/cleanup-dependency-binding.json index 3abb2379eb..2e3a86f4f5 100644 --- a/scripts/verify/baselines/cleanup-dependency-binding.json +++ b/scripts/verify/baselines/cleanup-dependency-binding.json @@ -1,101 +1,56 @@ { - "src/application/DirectAnalysisCleanup.ts": 2, + "src/application/DirectAnalysisCleanup.ts": 1, "src/application/EvidenceBundleCommands.ts": 1, "src/application/JsonFiles.ts": 1, "src/application/SetupCleanupOwner.ts": 2, - "src/application/Uninstall.ts": 1, - "src/application/analysisView/AnalysisViewService.ts": 1, "src/application/binary/AnalysisProviderRegistry.ts": 2, - "src/application/binary/BinarySession.ts": 6, - "src/application/binary/BundleResourceSession.ts": 1, + "src/application/binary/BinarySession.ts": 1, "src/application/binary/CompositeProvider.ts": 1, "src/application/closeOwnedWebResources.ts": 1, - "src/application/decompileDirectory/decompileAll.ts": 1, - "src/application/decompileDirectory/exportResources.ts": 1, - "src/application/decompileDirectory/exportTree.ts": 1, "src/application/desktop/DesktopApplicationExport.ts": 2, - "src/application/desktop/DesktopRetainedContent.ts": 1, "src/application/frida/FridaInstrumentationService.ts": 2, "src/application/releaseExposure/ReleaseExposureService.ts": 1, - "src/artifacts/apple/AppleAssetCatalogAnalysis.ts": 2, - "src/artifacts/apple/KeyedArchiveReader.ts": 1, - "src/browser/BrowserScenarioPartialObservation.ts": 1, "src/browser/CdpBrowserProvider.ts": 1, "src/browser/CdpElectronProvider.ts": 1, "src/browser/CdpTargetSessionOwner.ts": 2, - "src/browser/ElectronFileScope.ts": 1, - "src/browser/IsolatedWebBundleAnalyzer.ts": 3, - "src/browser/PlaywrightBrowserScenarioProvider.ts": 3, + "src/browser/PlaywrightBrowserScenarioProvider.ts": 2, "src/browser/PlaywrightElectronActiveActions.ts": 1, "src/browser/PlaywrightElectronActiveProvider.ts": 1, - "src/browser/PlaywrightScenarioBrowser.ts": 1, - "src/browser/WebBundleAnalysisWorker.ts": 1, "src/browser/WebSourceMapFetcher.ts": 2, - "src/browser/assets/WebArtifactReads.ts": 1, - "src/browser/history/CaptureFailures.ts": 1, "src/browser/history/HistoricalCaptureDecoder.ts": 1, - "src/browser/modules/NativeModuleResolver.ts": 1, "src/cli/desktopCaptureCommands.ts": 1, - "src/cli/environmentCommands.ts": 1, - "src/cutter/CutterBridgeClient.ts": 2, - "src/cutter/CutterBridgeService.ts": 2, - "src/desktop/DesktopBuildSetupHost.ts": 1, + "src/cutter/CutterBridgeClient.ts": 1, "src/desktop/ScreenJudgeProcess.ts": 1, "src/domain/explicitSensitiveFailure.ts": 1, - "src/dotnet/ManagedSnapshot.ts": 2, - "src/electron/ElectronFuseFailures.ts": 1, "src/evm/EvmoleInterfaceProvider.ts": 6, "src/firmware/FirmwareFailures.ts": 1, "src/firmware/FirmwareProvider.ts": 1, - "src/flutter/FlutterBuildProvider.ts": 2, + "src/flutter/FlutterBuildProvider.ts": 1, "src/frida/FridaInstrumentationManager.ts": 1, "src/gdb/GdbSessionManager.ts": 2, "src/ghidra/GhidraFileArtifacts.ts": 1, - "src/ghidra/GhidraJavaProbe.ts": 1, - "src/ghidra/GhidraNativeAotSnapshotOwner.ts": 2, - "src/ghidra/GhidraProviderClient.ts": 3, - "src/ghidra/GhidraSessionError.ts": 1, "src/hopper/BridgeLauncher.ts": 3, "src/hopper/HopperAnalysisProfile.ts": 1, "src/hopper/HopperClient.ts": 1, "src/hopper/HopperFileOffset.ts": 1, "src/hopper/HopperImageCopy.ts": 1, - "src/hopper/HopperProvider.ts": 1, - "src/ida/IdaSessionClient.ts": 2, + "src/ida/IdaSessionClient.ts": 1, "src/inspector/V8InspectorProvider.ts": 1, - "src/javascript/analysis/JavaScriptAnalysisWorker.ts": 1, "src/javascript/sourceMaps/SourceMapCommand.ts": 4, "src/jeb/JebMcpConnectionOwner.ts": 1, "src/jeb/JebProvider.ts": 2, - "src/kuna/KunaProjectCache.ts": 2, - "src/kuna/KunaProjectExport.ts": 1, - "src/kuna/KunaProjectReader.ts": 2, + "src/kuna/KunaProjectCache.ts": 1, "src/kuna/KunaSessionClient.ts": 1, - "src/kuna/KunaTargetCommands.ts": 2, - "src/native/LldbCallTracer.ts": 4, + "src/kuna/KunaTargetCommands.ts": 1, + "src/native/LldbCallTracer.ts": 3, "src/native/NativeCommandAnalysisError.ts": 1, - "src/native/NativeMacOSProvider.ts": 5, - "src/native/NativeUiObservation.ts": 1, - "src/native/SignatureTargetBinding.ts": 1, - "src/native/pwndbg/PwndbgCoreContext.ts": 1, - "src/native/pwntools/PwntoolsDecoder.ts": 6, + "src/native/NativeMacOSProvider.ts": 2, "src/pcap/PcapProvider.ts": 7, "src/pcap/PcapSnapshot.ts": 1, "src/process/ArtifactAnalysisResources.ts": 3, - "src/process/DarwinProcessRunTokenReader.ts": 2, "src/process/OwnedDebuggerSessionRegistry.ts": 1, - "src/process/capture/FilesystemSnapshot.ts": 1, "src/process/capture/ProcessCaptureError.ts": 3, - "src/process/capture/ProcessCaptureLifecycle.ts": 1, - "src/process/capture/ProcessHarness.ts": 2, - "src/providers/AnalysisClientCreation.ts": 3, "src/providers/AnalysisClientFailure.ts": 1, - "src/providers/OwnedCommandCleanup.ts": 1, - "src/rizin/RizinDebugSessionManager.ts": 1, - "src/server/registerCloseLifecycleTool.ts": 1, - "src/server/registerResetInvestigationTool.ts": 1, - "src/server/sessionStatusTool.ts": 1, "src/sqlite/SqliteDatabaseProvider.ts": 8, - "src/sqlite/SqliteDatabaseWorkerExecution.ts": 2, - "src/wasm/WabtArtifactProvider.ts": 1 + "src/sqlite/SqliteDatabaseWorkerExecution.ts": 2 } diff --git a/src/application/DirectAnalysisCleanup.ts b/src/application/DirectAnalysisCleanup.ts index 22c0f1a321..7f887a6593 100644 --- a/src/application/DirectAnalysisCleanup.ts +++ b/src/application/DirectAnalysisCleanup.ts @@ -15,7 +15,10 @@ import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { err, type Result } from "../domain/result.js"; import type { AnalysisExecution } from "../ports/AnalysisProvider.js"; import type { BinarySession } from "./binary/BinarySession.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { + analysisErrorWithCleanupFailure, + analysisErrorWithCloseRejection, +} from "../domain/analysisErrorCleanup.js"; import { tryParseEvidence, withEvidenceCallerInputPath, @@ -159,16 +162,8 @@ export const managedAnalysisCleanupFailure = ( result: Result, error: AnalysisError, ): Result => { - // A close rejection without a live cleanup state has unknown completion; - // an empty dependency set must not turn that rejection into confirmed cleanup. - if (!result.ok) { - const failure = analysisErrorWithCleanupFailure(result.error, error); - return err( - error.cleanupIncomplete - ? failure.bindCleanupDependencies([result.error, error]) - : failure, - ); - } + if (!result.ok) + return err(analysisErrorWithCloseRejection(result.error, error)); const failure = new ProviderAdapterError( error instanceof ProviderAdapterError ? error.providerId : "rea", "close_binary", diff --git a/src/application/Uninstall.ts b/src/application/Uninstall.ts index 7c91c941b3..d3559ba201 100644 --- a/src/application/Uninstall.ts +++ b/src/application/Uninstall.ts @@ -22,7 +22,7 @@ import { AnalysisError, type AnalysisCleanupObservation, } from "../domain/analysisErrorBase.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { copyFile, lstat, realpath, rm, rmdir } from "node:fs/promises"; import { constants as fsConstants } from "node:fs"; @@ -248,11 +248,11 @@ export const runUninstall = async ( if (failed) { if (cleanupFailure !== undefined) { if (primaryFailure instanceof AnalysisError) - throw analysisErrorWithCleanupFailure( + throw analysisErrorWithCleanupDependencies( primaryFailure, cleanupFailure, "uninstall", - ).bindCleanupDependencies([primaryFailure, cleanupFailure]); + ); throw new AggregateError( [primaryFailure, cleanupFailure], "Uninstall failed and its resource cleanup remains incomplete.", diff --git a/src/application/analysisView/AnalysisViewService.ts b/src/application/analysisView/AnalysisViewService.ts index 8890206c08..e4a43a0f22 100644 --- a/src/application/analysisView/AnalysisViewService.ts +++ b/src/application/analysisView/AnalysisViewService.ts @@ -1,5 +1,5 @@ import { projectAnalysisErrorWithoutCapturedOutput } from "../../domain/analysisErrorProjection.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js"; import { parseAnalysisInput } from "../AnalysisInput.js"; import { isNativeObservationOperation } from "../../domain/native/nativeObservation.js"; import { dispatchQueuedInterrupts } from "../../process/queuedInterrupts.js"; @@ -186,11 +186,11 @@ const cancelledFileViewResult = ( }); return err( !result.ok && result.error.cleanupIncomplete - ? analysisErrorWithCleanupFailure( + ? analysisErrorWithCleanupDependencies( cancellation, result.error, INSPECT_ANALYSIS_VIEW_OPERATION, - ).bindCleanupDependencies([result.error]) + ) : cancellation, ); }; diff --git a/src/application/binary/BinarySession.ts b/src/application/binary/BinarySession.ts index dd163ca2b7..7b48f3e7ce 100644 --- a/src/application/binary/BinarySession.ts +++ b/src/application/binary/BinarySession.ts @@ -80,7 +80,12 @@ import { prepareSessionExecution, } from "./BinarySessionExecution.js"; import { closeAnalysisClient } from "../../providers/AnalysisClientCleanup.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { + analysisErrorWithCleanupFailure, + analysisErrorWithCleanupDependencies, + analysisErrorWithCloseRejection, + analysisErrorWithCloseRejections, +} from "../../domain/analysisErrorCleanup.js"; import { ConfigurationError } from "../../domain/configurationErrors.js"; import type { AnalysisCleanupRetry } from "../../domain/analysisErrorRecovery.js"; import { analysisErrorWithCancellation } from "../../domain/analysisErrorCancellation.js"; @@ -118,30 +123,6 @@ interface CleanupFailureTracker { readonly onFailure: (failure: AnalysisError) => void; } -/** Compose live cleanup facts without treating an unowned rejection as completion. */ -const sessionCleanupFailure = ( - primary: AnalysisError, - cleanup: AnalysisError, - operation: string, -): AnalysisError => { - const failure = analysisErrorWithCleanupFailure(primary, cleanup, operation); - return cleanup.cleanupIncomplete - ? failure.bindCleanupDependencies([primary, cleanup]) - : failure; -}; - -/** - * Let a cleanup failure the client's close reported read that close. A failure - * whose cleanup already follows its own owner keeps reading that owner. - */ -const bindClientRelease = ( - release: AnalysisCleanupRelease, - failure: AnalysisError, -): void => { - if (failure.cleanupIncomplete && !failure.hasCleanupOwner) - release.bind(failure); -}; - const trackCleanupFailures = ( signal: AbortSignal | undefined, operation: string, @@ -168,14 +149,20 @@ const trackCleanupFailures = ( } else { // Both operands are cleanup observations here. An earlier rejection // without a live lifecycle must not disappear when a later owner resolves. - cleanupFailure = cleanupFailure.cleanupIncomplete - ? sessionCleanupFailure(cleanupFailure, failure, operation) - : analysisErrorWithCleanupFailure(cleanupFailure, failure, operation); + cleanupFailure = analysisErrorWithCloseRejections( + cleanupFailure, + failure, + operation, + ); } error = cancellation === undefined ? cleanupFailure - : sessionCleanupFailure(cancellation, cleanupFailure, operation); + : analysisErrorWithCloseRejection( + cancellation, + cleanupFailure, + operation, + ); }, }; }; @@ -303,7 +290,7 @@ export class BinarySession return err( closed.ok ? started.error - : sessionCleanupFailure( + : analysisErrorWithCloseRejection( started.error, closed.error, "open_bundle_resources", @@ -317,7 +304,7 @@ export class BinarySession return err( closed.ok ? cancelled - : sessionCleanupFailure( + : analysisErrorWithCloseRejection( cancelled, closed.error, "open_bundle_resources", @@ -340,7 +327,7 @@ export class BinarySession cleanupFailures.error ?? (candidateClosed.ok ? primary - : analysisErrorWithCleanupFailure( + : analysisErrorWithCloseRejections( primary, candidateClosed.error, "open_bundle_resources", @@ -358,7 +345,7 @@ export class BinarySession cleanupFailures.error ?? (candidateClosed.ok ? cancelled - : sessionCleanupFailure( + : analysisErrorWithCloseRejection( cancelled, candidateClosed.error, "open_bundle_resources", @@ -855,11 +842,11 @@ export class BinarySession const primary = completionFailure(value, retired.error); const failure = retired.error.cleanupIncomplete && primary !== retired.error - ? analysisErrorWithCleanupFailure( + ? analysisErrorWithCleanupDependencies( primary, retired.error, operationName, - ).bindCleanupDependencies([primary, retired.error]) + ) : primary; return err( isAborted(signal) @@ -1136,24 +1123,20 @@ export class BinarySession let resourceFailure = resourceFailures[0]; for (const next of resourceFailures.slice(1)) if (resourceFailure !== undefined) { - const previous = resourceFailure; - resourceFailure = analysisErrorWithCleanupFailure( - previous, + resourceFailure = analysisErrorWithCloseRejections( + resourceFailure, next, "close_binary", ); - if (previous.cleanupIncomplete && next.cleanupIncomplete) - resourceFailure.bindCleanupDependencies([previous, next]); } if (!closed.ok && resourceFailure !== undefined) { - const combined = analysisErrorWithCleanupFailure( - closed.error, - resourceFailure, - "close_binary", + return err( + analysisErrorWithCloseRejections( + closed.error, + resourceFailure, + "close_binary", + ), ); - if (closed.error.cleanupIncomplete && resourceFailure.cleanupIncomplete) - combined.bindCleanupDependencies([closed.error, resourceFailure]); - return err(combined); } if (!closed.ok) return closed; return resourceFailure === undefined ? ok(null) : err(resourceFailure); @@ -1178,20 +1161,14 @@ export class BinarySession ); if (!closed.ok) { retained.push(session); - const previous = failure; failure = - previous === undefined + failure === undefined ? closed.error - : analysisErrorWithCleanupFailure( - previous, + : analysisErrorWithCloseRejections( + failure, closed.error, "close_binary", ); - if ( - previous?.cleanupIncomplete === true && - closed.error.cleanupIncomplete - ) - failure.bindCleanupDependencies([previous, closed.error]); } } this.#pendingBundleResourceCleanup = retained; @@ -1235,7 +1212,7 @@ export class BinarySession ...(progress === undefined ? {} : { progress }), ...(pending.retainDocument ? { retainDocument: true } : {}), onCleanupFailure: (failure) => { - bindClientRelease(pending.release, failure); + pending.release.bindUnowned(failure); onCleanupFailure?.(failure); }, }, @@ -1243,7 +1220,7 @@ export class BinarySession if (closed.ok) { pending.release.confirm(); this.#pendingCleanup = undefined; - } else bindClientRelease(pending.release, closed.error); + } else pending.release.bindUnowned(closed.error); return closed; } @@ -1258,7 +1235,11 @@ export class BinarySession onCleanupFailure === undefined ? {} : { onCleanupFailure }, ); if (!closed.ok) - return sessionCleanupFailure(primary, closed.error, "open_binary"); + return analysisErrorWithCloseRejection( + primary, + closed.error, + "open_binary", + ); return this.#restoreAfterFailedOpen(previous, primary); } @@ -1274,7 +1255,7 @@ export class BinarySession ), }); return restored.error.cleanupIncomplete - ? sessionCleanupFailure(primary, restored.error, "open_binary") + ? analysisErrorWithCloseRejection(primary, restored.error, "open_binary") : primary; } @@ -1780,7 +1761,13 @@ export class BinarySession const closed = await this.#retireClient(run); return closed.ok ? err(started.error) - : err(sessionCleanupFailure(started.error, closed.error, "open_binary")); + : err( + analysisErrorWithCloseRejection( + started.error, + closed.error, + "open_binary", + ), + ); } async #waitForTransition( diff --git a/src/application/binary/BundleResourceSession.ts b/src/application/binary/BundleResourceSession.ts index 447a491fa7..6628acb4d8 100644 --- a/src/application/binary/BundleResourceSession.ts +++ b/src/application/binary/BundleResourceSession.ts @@ -4,7 +4,7 @@ import type { CapabilityDescriptor, } from "../../ports/AnalysisProvider.js"; import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCloseRejections } from "../../domain/analysisErrorCleanup.js"; import { err, ok } from "../../domain/result.js"; import type { ResolvedAppBundleResourceRoot } from "../../domain/apple/bundleResourceRoot.js"; import { closeAnalysisClient } from "../../providers/AnalysisClientCleanup.js"; @@ -78,14 +78,13 @@ export const combineBundleResourceClients = ( closeAnalysisClient(nativeClient, "bundle-resources", options), ]); if (!artifact.ok && !native.ok) { - const failure = analysisErrorWithCleanupFailure( - artifact.error, - native.error, - "close_binary", + return err( + analysisErrorWithCloseRejections( + artifact.error, + native.error, + "close_binary", + ), ); - if (artifact.error.cleanupIncomplete && native.error.cleanupIncomplete) - failure.bindCleanupDependencies([artifact.error, native.error]); - return err(failure); } if (!artifact.ok) return artifact; if (!native.ok) return native; diff --git a/src/application/decompileDirectory/decompileAll.ts b/src/application/decompileDirectory/decompileAll.ts index ce60711de1..2d36fe3413 100644 --- a/src/application/decompileDirectory/decompileAll.ts +++ b/src/application/decompileDirectory/decompileAll.ts @@ -29,7 +29,7 @@ import { cancelledBy, } from "../../domain/analysisErrorCore.js"; import type { AnalysisError } from "../../domain/analysisErrorBase.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js"; import { projectAnalysisError } from "../../domain/analysisErrorProjection.js"; import { procedureInfoSchema } from "../../domain/native/procedureInfo.js"; import { listProceduresFact } from "../../domain/native/nativeOperationFacts.js"; @@ -236,11 +236,11 @@ export const decompileAll = async ( primary !== closed.error && closed.error.cleanupIncomplete ) { - failure = analysisErrorWithCleanupFailure( + failure = analysisErrorWithCleanupDependencies( primary, closed.error, "decompile_all", - ).bindCleanupDependencies([primary, closed.error]); + ); } if (publishedOutput !== undefined) failure.retainPrimaryDiagnostics({ published_output: publishedOutput }); diff --git a/src/application/decompileDirectory/exportResources.ts b/src/application/decompileDirectory/exportResources.ts index fe429590d1..0c9f7947ab 100644 --- a/src/application/decompileDirectory/exportResources.ts +++ b/src/application/decompileDirectory/exportResources.ts @@ -20,7 +20,7 @@ import { RegularFileCleanupFailure } from "../../filesystem/OwnedRegularFile.js" import { DECOMPILE_DIRECTORY_JOURNAL_NAME } from "../../contracts/decompileDirectory.js"; import type { AnalysisError } from "../../domain/analysisErrorBase.js"; import { AnalysisOutputError } from "../../domain/analysisErrorCore.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js"; import { err, ok, type Result } from "../../domain/result.js"; import { OwnedFileHandle } from "../../filesystem/OwnedFileHandle.js"; import { OwnedStagedOutput } from "../../filesystem/OwnedStagedOutput.js"; @@ -202,11 +202,11 @@ export class ExportResources { return closed.ok ? err(error) : err( - analysisErrorWithCleanupFailure( + analysisErrorWithCleanupDependencies( error, closed.error, "decompile_all", - ).bindCleanupDependencies([closed.error]), + ), ); } diff --git a/src/application/decompileDirectory/exportTree.ts b/src/application/decompileDirectory/exportTree.ts index 17e940cd12..37c4d17582 100644 --- a/src/application/decompileDirectory/exportTree.ts +++ b/src/application/decompileDirectory/exportTree.ts @@ -35,7 +35,7 @@ import { AnalysisResourceConstraintError, } from "../../domain/analysisErrorCore.js"; import { AnalysisError } from "../../domain/analysisErrorBase.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js"; import { isPathWithinRoot } from "../../domain/localPath.js"; import { err, ok, type Result } from "../../domain/result.js"; import { @@ -356,11 +356,11 @@ export class DecompileExport { return closed.ok ? opened : err( - analysisErrorWithCleanupFailure( + analysisErrorWithCleanupDependencies( opened.error, closed.error, "decompile_all", - ).bindCleanupDependencies([closed.error]), + ), ); } return ok( diff --git a/src/application/desktop/DesktopRetainedContent.ts b/src/application/desktop/DesktopRetainedContent.ts index 66f3cf2d13..c5c6552945 100644 --- a/src/application/desktop/DesktopRetainedContent.ts +++ b/src/application/desktop/DesktopRetainedContent.ts @@ -9,7 +9,7 @@ import { type ArtifactCleanupAttempt, } from "../../resources/index.js"; import { err, ok, type Result } from "../../domain/result.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js"; import { ProviderCleanupError } from "../../domain/providerCleanupError.js"; import type { OwnedFileHandle } from "../../filesystem/OwnedFileHandle.js"; import { @@ -152,13 +152,11 @@ export const withRetainedContent = async ( { operation: outcome.cause.operation, cause: fileFailure }, ); bindArtifactFileCleanup(fileFailure, fileCleanup); - const combined = analysisErrorWithCleanupFailure( + throw analysisErrorWithCleanupDependencies( outcome.cause, fileCleanup, outcome.cause.operation, ); - combined.bindCleanupDependencies([outcome.cause, fileCleanup]); - throw combined; } throw resources.cleanupFailure(outcome, failures); } diff --git a/src/application/desktop/DesktopTaskExport.ts b/src/application/desktop/DesktopTaskExport.ts index eeba486b4e..9b87930da9 100644 --- a/src/application/desktop/DesktopTaskExport.ts +++ b/src/application/desktop/DesktopTaskExport.ts @@ -41,7 +41,7 @@ import { import type { AnalysisError } from "../../domain/analysisErrorBase.js"; import type { JsonValue } from "../../domain/jsonValue.js"; import { AnalysisInputError } from "../../domain/analysisErrorCore.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCloseRejection } from "../../domain/analysisErrorCleanup.js"; import { EvidenceFileError } from "../../domain/evidenceErrors.js"; import { err } from "../../domain/result.js"; import { describeValidationFailure } from "../../domain/validationFailure.js"; @@ -149,7 +149,7 @@ const readTaskFile = async ( if (closed !== undefined) throw primary === undefined ? closed - : analysisErrorWithCleanupFailure(primary, closed, OPERATION); + : analysisErrorWithCloseRejection(primary, closed, OPERATION); if (loaded.ok) return loaded.value; throw primary ?? typed(loaded.error); }; diff --git a/src/artifacts/ArtifactEmbeddedFormatProbes.ts b/src/artifacts/ArtifactEmbeddedFormatProbes.ts index 5e7d24fdd9..1a6c22b8ef 100644 --- a/src/artifacts/ArtifactEmbeddedFormatProbes.ts +++ b/src/artifacts/ArtifactEmbeddedFormatProbes.ts @@ -19,7 +19,7 @@ import { sameRegularFileState, } from "../filesystem/RegularFile.js"; import { findDotnetBundleHeader } from "./dotnet/DotnetBundle.js"; -import { ArtifactReaderFailure } from "../resources/index.js"; +import { ArtifactReaderFailure, abortIfNeeded } from "../resources/index.js"; import { locateGodotPck, type GodotPckLocation } from "./GodotPckLocation.js"; import { locateNodeSea, @@ -30,7 +30,6 @@ import { type PyInstallerCookie, type PyInstallerCookieObservation, } from "./pyinstaller/CArchiveLayout.js"; -import { abortIfNeeded } from "../resources/index.js"; /** Completed observations and explicit recognition limits; null alone is examined absence. */ export interface ArtifactEmbeddedFormatProbeFacts { diff --git a/src/artifacts/ArtifactProvider.ts b/src/artifacts/ArtifactProvider.ts index 95e564775b..6b46e6cfe4 100644 --- a/src/artifacts/ArtifactProvider.ts +++ b/src/artifacts/ArtifactProvider.ts @@ -11,6 +11,7 @@ import { bindArtifactFileCleanup, ArtifactReaderFailure, ArtifactResourceScope, + withArtifactTargetIdentity, } from "../resources/index.js"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; import { translateArtifactFailure } from "./ArtifactOperationFailure.js"; @@ -30,7 +31,6 @@ import { } from "./apple/KeyedArchiveReader.js"; import { traceDylibResolution } from "./apple/DylibResolutionReader.js"; import { dirname } from "node:path"; -import { withArtifactTargetIdentity } from "../resources/index.js"; import { inventoryArtifact } from "./inventory/ArtifactInventory.js"; import { extractArtifact } from "./extraction/ArtifactExtraction.js"; import { analyzeInterfaceBuilderBundle } from "./apple/InterfaceBuilderAnalysis.js"; diff --git a/src/artifacts/DesktopApplicationReader.ts b/src/artifacts/DesktopApplicationReader.ts index 77d5c1e43a..0804018891 100644 --- a/src/artifacts/DesktopApplicationReader.ts +++ b/src/artifacts/DesktopApplicationReader.ts @@ -11,6 +11,7 @@ import { artifactFileCompletion, ArtifactResourceScope, type ArtifactResourceOwner, + abortIfNeeded, } from "../resources/index.js"; import { declaredArtifactEntries } from "./ArtifactTraversalObservation.js"; import { translateArtifactFailure } from "./ArtifactOperationFailure.js"; @@ -44,7 +45,6 @@ import type { AnalysisPartialObservation, } from "../domain/analysisErrorBase.js"; import { BinaryTargetError } from "../domain/configurationErrors.js"; -import { abortIfNeeded } from "../resources/index.js"; const RETAINED_METADATA_BYTES = 32 * 1024 * 1024; /** diff --git a/src/artifacts/DesktopFileInspection.ts b/src/artifacts/DesktopFileInspection.ts index 347e49504d..e9ba95c5ec 100644 --- a/src/artifacts/DesktopFileInspection.ts +++ b/src/artifacts/DesktopFileInspection.ts @@ -21,13 +21,12 @@ import { readManagedMetadataLayout } from "../dotnet/ManagedMetadataLayout.js"; import { readManagedCliHeaderPrefix } from "../domain/managed/managedCliHeaderPrefix.js"; import { readAssemblyReferenceName } from "../dotnet/ManagedMetadataInventoryRows.js"; import { ManagedReaderFailure } from "../dotnet/ManagedReaderFailure.js"; -import { ArtifactReaderFailure } from "../resources/index.js"; +import { ArtifactReaderFailure, abortIfNeeded } from "../resources/index.js"; import { hasMachoMagic } from "../domain/apple/machoContainer.js"; import { hasUnityFsHeader, readUnityFsHeaderFacts, } from "../domain/unityfsFormat.js"; -import { abortIfNeeded } from "../resources/index.js"; export interface DesktopReadBudget { bytes: number; diff --git a/src/artifacts/InesArtifactReader.ts b/src/artifacts/InesArtifactReader.ts index e152a66cac..cffcc7702d 100644 --- a/src/artifacts/InesArtifactReader.ts +++ b/src/artifacts/InesArtifactReader.ts @@ -8,6 +8,7 @@ import { type ArtifactTraversalOptions, readArtifactFileChunks, streamChunkToBuffer, + abortIfNeeded, } from "../resources/index.js"; import { readFileHandlePrefix } from "../filesystem/readFileHandlePrefix.js"; import { Readable } from "node:stream"; @@ -23,7 +24,6 @@ import { type StableRegularFileDescriptor, } from "../filesystem/RegularFile.js"; import type { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js"; -import { abortIfNeeded } from "../resources/index.js"; export const INES_LIMITATION = "Classic iNES file regions are observed; mapper execution, CPU bank mappings, CHR-RAM contents, 6502 analysis and emulator behavior are not observed. Trailing bytes are retained without interpretation. NES 2.0 and UNIF are unsupported."; diff --git a/src/artifacts/ReleaseExposureReader.ts b/src/artifacts/ReleaseExposureReader.ts index 6a393ab6c3..6160045466 100644 --- a/src/artifacts/ReleaseExposureReader.ts +++ b/src/artifacts/ReleaseExposureReader.ts @@ -32,6 +32,9 @@ import { projectArtifactCloseFailure, projectStableArtifactFailure, readerIntegrityFailure, + hashStableRootArtifactHandle, + openRootArtifact, + releaseRootArtifact, } from "../resources/index.js"; import { decodeBinaryPlistText } from "../domain/apple/binaryPlistMaterializer.js"; import { @@ -51,11 +54,6 @@ import { analysisSettingLimit } from "../domain/analysisSettingDefinitions.js"; import { ArtifactTraversalObservation } from "./ArtifactTraversalObservation.js"; import { classifyEmbeddedExecutablePackage } from "./inventory/classify.js"; import { inventoryArtifactInScope } from "./inventory/ArtifactInventory.js"; -import { - hashStableRootArtifactHandle, - openRootArtifact, - releaseRootArtifact, -} from "../resources/index.js"; import { createArtifactReader } from "./createArtifactReader.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; import { diff --git a/src/artifacts/apple/AppleAssetCatalogAnalysis.ts b/src/artifacts/apple/AppleAssetCatalogAnalysis.ts index e58dc6975a..d0c2e4e4cc 100644 --- a/src/artifacts/apple/AppleAssetCatalogAnalysis.ts +++ b/src/artifacts/apple/AppleAssetCatalogAnalysis.ts @@ -26,7 +26,7 @@ import { translateArtifactFailure } from "../ArtifactOperationFailure.js"; import { InternalInvariantError } from "../../domain/internalInvariant.js"; import { ProviderAdapterError } from "../../domain/providerAdapterError.js"; import { ARTIFACT_GRAPH_PROVIDER } from "../../domain/investigationProviders.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js"; import { ArtifactTraversalObservation, declaredArtifactEntries, @@ -136,11 +136,11 @@ export const analyzeAppleAssetCatalogs = async (input: { "inspect_asset_catalog", joined.error, ); - throw analysisErrorWithCleanupFailure( + throw analysisErrorWithCleanupDependencies( primary, cleanup, "inspect_asset_catalog", - ).bindCleanupDependencies([primary, cleanup]); + ); } throw cause; } @@ -281,11 +281,11 @@ const collectAssetCatalogs = async (input: { "inspect_asset_catalog", input.resources.cleanupFailure({ kind: "completed" }, [released]), ); - throw analysisErrorWithCleanupFailure( + throw analysisErrorWithCleanupDependencies( outcome.cause, cleanup, "inspect_asset_catalog", - ).bindCleanupDependencies([outcome.cause, cleanup]); + ); } throw input.resources.cleanupFailure(outcome, [released]); } diff --git a/src/artifacts/apple/DylibResolutionReader.ts b/src/artifacts/apple/DylibResolutionReader.ts index 230a8abd7b..3acb53f6cd 100644 --- a/src/artifacts/apple/DylibResolutionReader.ts +++ b/src/artifacts/apple/DylibResolutionReader.ts @@ -22,10 +22,10 @@ import { type ArtifactReaderTraversal, ArtifactResourceScope, assertArtifactReadActive, + targetDigestChangedFailure, } from "../../resources/index.js"; import { ArtifactTraversalObservation } from "../ArtifactTraversalObservation.js"; import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js"; -import { targetDigestChangedFailure } from "../../resources/index.js"; import { consumeWithOrderedReads } from "../OrderedReads.js"; import { DylibFileAccess, diff --git a/src/artifacts/apple/KeyedArchiveReader.ts b/src/artifacts/apple/KeyedArchiveReader.ts index 8e050eb1a5..198f6b332f 100644 --- a/src/artifacts/apple/KeyedArchiveReader.ts +++ b/src/artifacts/apple/KeyedArchiveReader.ts @@ -1,15 +1,6 @@ import { HOST_PLATFORM } from "../../platform/HostPlatform.js"; -import { targetDigestChangedFailure } from "../../resources/index.js"; -import { createHash } from "node:crypto"; -import { - decodeLimit, - isHostLimitFailure, - ParseFailureError, -} from "../../domain/parseFailure.js"; -import { basename, join } from "node:path"; -import { realpath } from "node:fs/promises"; -import { InternalInvariantError } from "../../domain/internalInvariant.js"; import { + targetDigestChangedFailure, readStableArtifact, projectStableArtifactFailure, ArtifactReaderFailure, @@ -20,6 +11,15 @@ import { bindArtifactFileCleanup, ArtifactResourceScope, } from "../../resources/index.js"; +import { createHash } from "node:crypto"; +import { + decodeLimit, + isHostLimitFailure, + ParseFailureError, +} from "../../domain/parseFailure.js"; +import { basename, join } from "node:path"; +import { realpath } from "node:fs/promises"; +import { InternalInvariantError } from "../../domain/internalInvariant.js"; import { ARTIFACT_GRAPH_PROVIDER } from "../../domain/investigationProviders.js"; import { z } from "zod"; @@ -56,7 +56,7 @@ import { } from "../DirectoryArtifactReader.js"; import { AnalysisError } from "../../domain/analysisErrorBase.js"; import { translateArtifactFailure } from "../ArtifactOperationFailure.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js"; import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js"; import { decodeXmlPlistText } from "../../domain/propertyListXmlText.js"; @@ -227,11 +227,11 @@ export const inspectBundleKeyedArchive = (input: BundleKeyedArchiveInput) => { "inspect_keyed_archive", resources.cleanupFailure({ kind: "completed" }, [released]), ); - throw analysisErrorWithCleanupFailure( + throw analysisErrorWithCleanupDependencies( outcome.cause, cleanup, "inspect_keyed_archive", - ).bindCleanupDependencies([outcome.cause, cleanup]); + ); } throw resources.cleanupFailure(outcome, [released]); } diff --git a/src/artifacts/deno/DenoSectionLayout.ts b/src/artifacts/deno/DenoSectionLayout.ts index 7c0aad8255..310b834c10 100644 --- a/src/artifacts/deno/DenoSectionLayout.ts +++ b/src/artifacts/deno/DenoSectionLayout.ts @@ -1,9 +1,8 @@ import { fixedAllowanceRemediation } from "../../domain/fixedAllowanceRemediation.js"; import { jsonValueSchema, type JsonValue } from "../../domain/jsonValue.js"; -import { ArtifactReaderFailure } from "../../resources/index.js"; +import { ArtifactReaderFailure, abortIfNeeded } from "../../resources/index.js"; import { walkDenoVirtualFs, type DenoVfsWalk } from "./DenoVirtualFs.js"; import { strictUtf8Decoder } from "../../domain/strictUtf8.js"; -import { abortIfNeeded } from "../../resources/index.js"; /** Opening and closing marker of a Deno compile data section. */ export const DENO_SECTION_MAGIC = Buffer.from("d3n0l4nd", "latin1"); diff --git a/src/artifacts/deno/DenoVirtualFs.ts b/src/artifacts/deno/DenoVirtualFs.ts index 85ba4ee6c8..448f3994b4 100644 --- a/src/artifacts/deno/DenoVirtualFs.ts +++ b/src/artifacts/deno/DenoVirtualFs.ts @@ -1,7 +1,9 @@ import { fixedAllowanceRemediation } from "../../domain/fixedAllowanceRemediation.js"; -import { ArtifactReaderFailure } from "../../resources/index.js"; -import { normalizeArtifactPath } from "../../resources/index.js"; -import { abortIfNeeded } from "../../resources/index.js"; +import { + ArtifactReaderFailure, + normalizeArtifactPath, + abortIfNeeded, +} from "../../resources/index.js"; /** Directory, file, and symlink records admitted from one virtual filesystem. */ const MAX_DENO_VFS_ENTRIES = 100_000; diff --git a/src/artifacts/inventory/classify.ts b/src/artifacts/inventory/classify.ts index bab76752ce..4f161ca5ac 100644 --- a/src/artifacts/inventory/classify.ts +++ b/src/artifacts/inventory/classify.ts @@ -1,6 +1,9 @@ import { artifactOperationCause, ArtifactReaderFailure, + openRootArtifact, + releaseRootArtifact, + abortIfNeeded, } from "../../resources/index.js"; import { nesContainerFormat, @@ -54,11 +57,6 @@ import { classifyStableRootArtifactHandle, type HashResult, } from "../ArtifactHash.js"; -import { - openRootArtifact, - releaseRootArtifact, - abortIfNeeded, -} from "../../resources/index.js"; import type { ArtifactInventoryOptions } from "./types.js"; import { readMachoHeaderPrefixFacts } from "../../domain/apple/machoContainer.js"; import { hasDiskImageSignature } from "../../domain/apple/diskImageFormat.js"; diff --git a/src/artifacts/inventory/scanCanonical.ts b/src/artifacts/inventory/scanCanonical.ts index e5a5780a4f..ef3c22a12f 100644 --- a/src/artifacts/inventory/scanCanonical.ts +++ b/src/artifacts/inventory/scanCanonical.ts @@ -20,6 +20,8 @@ import { type ArtifactReader, type ArtifactReaderTraversal, type ArtifactResourceOwner, + hashStableRootArtifact, + hashStableRootArtifactHandle, } from "../../resources/index.js"; import { artifactInventoryResultSchema, @@ -45,10 +47,6 @@ import { import { classifyAndHashRootForInventory } from "./classify.js"; import { hostExecutableMarking } from "../hostExecutableMarking.js"; import type { HashResult } from "../ArtifactHash.js"; -import { - hashStableRootArtifact, - hashStableRootArtifactHandle, -} from "../../resources/index.js"; import { createReader, inventoryCoverage } from "./reader.js"; import { scanReader, diff --git a/src/artifacts/inventory/scanReader.ts b/src/artifacts/inventory/scanReader.ts index 476f68f4e3..dda17de618 100644 --- a/src/artifacts/inventory/scanReader.ts +++ b/src/artifacts/inventory/scanReader.ts @@ -18,6 +18,7 @@ import { type ArtifactEntry, type ArtifactReader, type ArtifactReaderTraversal, + abortIfNeeded, } from "../../resources/index.js"; import { ArtifactTraversalObservation, @@ -48,7 +49,6 @@ import { } from "./ArtifactGraphConstruction.js"; import type { ArtifactIntegrityPolicyName } from "../../domain/artifactIntegrityPolicy.js"; import { hashReadable } from "../ArtifactHash.js"; -import { abortIfNeeded } from "../../resources/index.js"; export interface PendingIntegrityContradiction { readonly occurrence: MutableOccurrence; diff --git a/src/artifacts/pyinstaller/PyInstallerBytes.ts b/src/artifacts/pyinstaller/PyInstallerBytes.ts index 28491bf6e4..ef6f9e42b6 100644 --- a/src/artifacts/pyinstaller/PyInstallerBytes.ts +++ b/src/artifacts/pyinstaller/PyInstallerBytes.ts @@ -1,11 +1,10 @@ import type { FileHandle } from "node:fs/promises"; import { err, ok, type Result } from "../../domain/result.js"; -import { ArtifactReaderFailure } from "../../resources/index.js"; +import { ArtifactReaderFailure, abortIfNeeded } from "../../resources/index.js"; import { pyInstallerFailure, type PyInstallerFailure, } from "./PyInstallerFailure.js"; -import { abortIfNeeded } from "../../resources/index.js"; /** Fill one already-budgeted format range; only zero bytes establish EOF. */ export const readPyInstallerBytes = async ( diff --git a/src/artifacts/pyinstaller/PyInstallerMemberStream.ts b/src/artifacts/pyinstaller/PyInstallerMemberStream.ts index 74bb14d542..dab142dcee 100644 --- a/src/artifacts/pyinstaller/PyInstallerMemberStream.ts +++ b/src/artifacts/pyinstaller/PyInstallerMemberStream.ts @@ -1,8 +1,7 @@ import { Readable, Transform } from "node:stream"; import { pipeline } from "node:stream/promises"; import { createInflate } from "node:zlib"; -import { ArtifactReaderFailure } from "../../resources/index.js"; -import { abortIfNeeded } from "../../resources/index.js"; +import { ArtifactReaderFailure, abortIfNeeded } from "../../resources/index.js"; interface MemberStreamOptions { readonly sourceBytes: number; diff --git a/src/browser/BrowserScenarioPartialObservation.ts b/src/browser/BrowserScenarioPartialObservation.ts index 74d01d1e11..4953158b9e 100644 --- a/src/browser/BrowserScenarioPartialObservation.ts +++ b/src/browser/BrowserScenarioPartialObservation.ts @@ -11,7 +11,7 @@ import type { import type { BrowserScenarioSessionPort } from "./BrowserScenarioSessionPort.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; import { browserCleanupObservation } from "../domain/browserObservationError.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY } from "./providerIdentities.js"; @@ -138,9 +138,5 @@ export const browserScenarioOperationFailure = ( { reason: observation.reason }, { operation: "close_browser_scenario", cause: cleanupFailure.cause }, ); - return analysisErrorWithCleanupFailure( - primary, - cleanup, - OPERATION, - ).bindCleanupDependencies([primary, cleanup]); + return analysisErrorWithCleanupDependencies(primary, cleanup, OPERATION); }; diff --git a/src/browser/ElectronFileScope.ts b/src/browser/ElectronFileScope.ts index dc56675f1d..9b51c86061 100644 --- a/src/browser/ElectronFileScope.ts +++ b/src/browser/ElectronFileScope.ts @@ -4,7 +4,7 @@ import { isAbsolute, join, sep } from "node:path"; import { fileURLToPath } from "node:url"; import { cancelledBy, carriedReason } from "../domain/analysisErrorCore.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import type { JsonValue } from "../domain/jsonValue.js"; @@ -141,11 +141,11 @@ export const mapElectronFileAuthorizationFailure = ( if (diagnostics !== undefined) (primary ?? cleanup).retainDiagnostics(diagnostics); if (primary === undefined) return cleanup; - const composed = analysisErrorWithCleanupFailure( + const composed = analysisErrorWithCleanupDependencies( primary, cleanup, operation, - ).bindCleanupDependencies([primary, cleanup]); + ); bindArtifactFileCleanup(cause, composed); return composed; }; diff --git a/src/browser/IsolatedWebBundleAnalyzer.ts b/src/browser/IsolatedWebBundleAnalyzer.ts index e1bce97fd0..7bbd2feced 100644 --- a/src/browser/IsolatedWebBundleAnalyzer.ts +++ b/src/browser/IsolatedWebBundleAnalyzer.ts @@ -23,7 +23,7 @@ import { cancelledBy, OwnerCancellation, } from "../domain/analysisErrorCore.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { analysisErrorWithCancellation } from "../domain/analysisErrorCancellation.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { err, ok, type Result } from "../domain/result.js"; @@ -306,11 +306,11 @@ export class IsolatedWebBundleAnalyzer { failure = failure === undefined ? cleanup - : analysisErrorWithCleanupFailure( + : analysisErrorWithCleanupDependencies( failure, cleanup, "analyze_web_bundle", - ).bindCleanupDependencies([failure, cleanup]); + ); } finally { deadline.dispose(); } @@ -321,11 +321,11 @@ export class IsolatedWebBundleAnalyzer { failure = hasPrimaryFailure ? analysisErrorWithCancellation(failure, cancelled) : failure?.cleanupIncomplete === true - ? analysisErrorWithCleanupFailure( + ? analysisErrorWithCleanupDependencies( cancelled, failure, "analyze_web_bundle", - ).bindCleanupDependencies([cancelled, failure]) + ) : cancelled; } else if (!hasPrimaryFailure && deadline.interruption === "timeout") { const totalTimeoutMs = @@ -341,11 +341,11 @@ export class IsolatedWebBundleAnalyzer { ); failure = failure?.cleanupIncomplete === true - ? analysisErrorWithCleanupFailure( + ? analysisErrorWithCleanupDependencies( timeout, failure, "analyze_web_bundle", - ).bindCleanupDependencies([timeout, failure]) + ) : timeout; } if (failure !== undefined) { diff --git a/src/browser/PlaywrightBrowserScenarioProvider.ts b/src/browser/PlaywrightBrowserScenarioProvider.ts index cf540a05f1..64fadcd160 100644 --- a/src/browser/PlaywrightBrowserScenarioProvider.ts +++ b/src/browser/PlaywrightBrowserScenarioProvider.ts @@ -2,7 +2,7 @@ import { withPlaywrightExecutionBoundary, PLAYWRIGHT_CLEANUP_CONFIRMATION_TIMEOUT_MS, } from "./PlaywrightExecutionBoundary.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { AnalysisCleanupLease, AnalysisCleanupLeaseGroup, @@ -475,11 +475,7 @@ export class PlaywrightBrowserScenarioProvider implements BrowserScenarioCapture ); this.#bindCleanup(cleanup, retained); return err( - analysisErrorWithCleanupFailure( - primary, - cleanup, - OPERATION, - ).bindCleanupDependencies([primary, cleanup]), + analysisErrorWithCleanupDependencies(primary, cleanup, OPERATION), ); } } diff --git a/src/browser/PlaywrightScenarioBrowser.ts b/src/browser/PlaywrightScenarioBrowser.ts index e58d6e2f9a..ec36401cef 100644 --- a/src/browser/PlaywrightScenarioBrowser.ts +++ b/src/browser/PlaywrightScenarioBrowser.ts @@ -4,7 +4,7 @@ import { chromiumLaunchRemediation, chromiumSandboxEnabled, } from "./ChromiumSandbox.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { AnalysisCleanupLeaseGroup, @@ -707,11 +707,7 @@ export const failBrowserScenarioOperation = async ( }, }); new AnalysisCleanupLeaseGroup(failure, [cleanup]); - throw analysisErrorWithCleanupFailure( - primary, - failure, - OPERATION, - ).bindCleanupDependencies([primary, failure]); + throw analysisErrorWithCleanupDependencies(primary, failure, OPERATION); } throw primaryFailure; }; diff --git a/src/browser/WebBundleAnalysisWorker.ts b/src/browser/WebBundleAnalysisWorker.ts index b7fc44f39d..6d9e596963 100644 --- a/src/browser/WebBundleAnalysisWorker.ts +++ b/src/browser/WebBundleAnalysisWorker.ts @@ -49,7 +49,7 @@ import { cancelledBy, carriedReason, } from "../domain/analysisErrorCore.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { jsonParts, bufferedJsonParts } from "../domain/jsonSerialization.js"; import { safeParseUtf8Json } from "../domain/safeJson.js"; @@ -1001,11 +1001,7 @@ export class WebBundleAnalysisWorker { new AnalysisCleanupLeaseGroup(cleanup, [this.#cleanup]); return primary === undefined ? cleanup - : analysisErrorWithCleanupFailure( - primary, - cleanup, - OPERATION, - ).bindCleanupDependencies([primary, cleanup]); + : analysisErrorWithCleanupDependencies(primary, cleanup, OPERATION); } async close(): Promise { diff --git a/src/browser/assets/WebArtifactReads.ts b/src/browser/assets/WebArtifactReads.ts index 32db5ab6b0..822b987f73 100644 --- a/src/browser/assets/WebArtifactReads.ts +++ b/src/browser/assets/WebArtifactReads.ts @@ -25,7 +25,7 @@ import { import { ArtifactOperationError } from "../../domain/artifactOperationError.js"; import { ProviderAdapterError } from "../../domain/providerAdapterError.js"; import { ProviderCleanupError } from "../../domain/providerCleanupError.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js"; import { safeParseJson } from "../../domain/safeJson.js"; import { malformedInput, @@ -156,11 +156,11 @@ export const webArtifactReadError = ( { cause, operation: context.operation }, ); bindArtifactFileCleanup(cause, cleanup); - return analysisErrorWithCleanupFailure( + return analysisErrorWithCleanupDependencies( primary, cleanup, context.operation, - ).bindCleanupDependencies([primary, cleanup]); + ); } return primary; }; diff --git a/src/browser/history/CaptureFailures.ts b/src/browser/history/CaptureFailures.ts index 9214065d42..49ba2e5b74 100644 --- a/src/browser/history/CaptureFailures.ts +++ b/src/browser/history/CaptureFailures.ts @@ -13,7 +13,10 @@ import { artifactFilePrimaryFacts, artifactSelectedPathErrno, } from "../../resources/index.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { + analysisErrorWithCleanupFailure, + analysisErrorWithCleanupDependencies, +} from "../../domain/analysisErrorCleanup.js"; import { AnalysisError } from "../../domain/analysisErrorBase.js"; import { AnalysisAccessDeniedError, @@ -439,11 +442,11 @@ export const withCaptureReaderCleanup = ( cleanup.retainPartialObservation(primary.partialObservation); return cleanup; } - const composed = analysisErrorWithCleanupFailure( + const composed = analysisErrorWithCleanupDependencies( primary, cleanup, OPERATION, - ).bindCleanupDependencies([primary, cleanup]); + ); bindArtifactFileCleanup(cause, composed); return composed; }; diff --git a/src/browser/modules/NativeModuleResolver.ts b/src/browser/modules/NativeModuleResolver.ts index b76a37b9ee..fcc7bb58b4 100644 --- a/src/browser/modules/NativeModuleResolver.ts +++ b/src/browser/modules/NativeModuleResolver.ts @@ -16,7 +16,7 @@ import type { import type { ExecutionOptions } from "../../ports/AnalysisProvider.js"; import type { WebModuleResolutionPort } from "../../ports/WebModulePorts.js"; import type { AnalysisError } from "../../domain/analysisErrorBase.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js"; import { analysisErrorWithCancellation } from "../../domain/analysisErrorCancellation.js"; import { AnalysisCapabilityUnavailableError, @@ -305,11 +305,11 @@ export class NativeModuleResolver implements WebModuleResolutionPort { return err( result.ok ? cleanupError - : analysisErrorWithCleanupFailure( + : analysisErrorWithCleanupDependencies( result.error, cleanupError, OPERATION, - ).bindCleanupDependencies([result.error, cleanupError]), + ), ); return result; diff --git a/src/cli/environmentCommands.ts b/src/cli/environmentCommands.ts index 5f04684e7e..8c83a35cf0 100644 --- a/src/cli/environmentCommands.ts +++ b/src/cli/environmentCommands.ts @@ -25,7 +25,7 @@ import { type McpHttpEndpoint, } from "../config/mcpHttpEndpoint.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import type { StreamableHttpListenError } from "../server/http/streamableHttpListenError.js"; import { AnalysisInputError, @@ -241,11 +241,11 @@ const serveEnvironmentCommand = async ( if (!(cause instanceof AnalysisError)) throw cause; if (listenerError !== undefined) return cliError( - analysisErrorWithCleanupFailure( + analysisErrorWithCleanupDependencies( listenerError, cause, CLI_COMMANDS.environmentServe, - ).bindCleanupDependencies([cause]), + ), ); cause.retainDiagnostics({ shutdown_observation: { status: "shutdown_requested", ...observation }, diff --git a/src/cutter/CutterBridgeClient.ts b/src/cutter/CutterBridgeClient.ts index ecf393dae9..4b853d1499 100644 --- a/src/cutter/CutterBridgeClient.ts +++ b/src/cutter/CutterBridgeClient.ts @@ -1,5 +1,5 @@ import { HOST_PLATFORM } from "../platform/HostPlatform.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { ArtifactResourceScope, @@ -1298,11 +1298,7 @@ const discoveryFailure = ( primary instanceof AnalysisError ? primary : new ProviderAdapterError("cutter", operation, { cause: primary }); - return analysisErrorWithCleanupFailure( - original, - cleanup, - operation, - ).bindCleanupDependencies([cleanup]); + return analysisErrorWithCleanupDependencies(original, cleanup, operation); } if (cause.reason === "cancelled") return cancelledBy( diff --git a/src/cutter/CutterBridgeService.ts b/src/cutter/CutterBridgeService.ts index 0b3d672beb..91b718c459 100644 --- a/src/cutter/CutterBridgeService.ts +++ b/src/cutter/CutterBridgeService.ts @@ -1,4 +1,4 @@ -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { AnalysisCleanupRelease } from "../domain/analysisCleanupRelease.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { jsonValueSchema } from "../domain/jsonValue.js"; @@ -78,11 +78,11 @@ export class CutterBridgeService { ); if (!receipt.ok) return err( - analysisErrorWithCleanupFailure( + analysisErrorWithCleanupDependencies( pending.failure, receipt.error, "cutter_command", - ).bindCleanupDependencies([pending.failure, receipt.error]), + ), ); if (!receipt.value) return err(pending.failure); pending.release.confirm(); @@ -134,11 +134,11 @@ export class CutterBridgeService { ); throw pending.ok ? failure - : analysisErrorWithCleanupFailure( + : analysisErrorWithCleanupDependencies( pending.error, failure, "close_cutter", - ).bindCleanupDependencies([pending.error, failure]); + ); } if (!pending.ok) throw pending.error; } diff --git a/src/desktop/DesktopBuildSetupHost.ts b/src/desktop/DesktopBuildSetupHost.ts index 38fdeafd4a..e702fb39e4 100644 --- a/src/desktop/DesktopBuildSetupHost.ts +++ b/src/desktop/DesktopBuildSetupHost.ts @@ -9,7 +9,7 @@ import { AnalysisCleanupLease, } from "../resources/index.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { assertSetupActive } from "../domain/setupCancellation.js"; import { absoluteCallerPath } from "../filesystem/callerPath.js"; @@ -161,11 +161,11 @@ export const systemDesktopBuildSetupHost = ( ); cleanupFailure.bindCleanupResourceOwner(lease); lease.bindCleanupError(cleanupFailure); - throw analysisErrorWithCleanupFailure( + throw analysisErrorWithCleanupDependencies( cause, cleanupFailure, "setup", - ).bindCleanupDependencies([cause, cleanupFailure]); + ); } return `${desktopBuildOwnedCommandReason(cause)}; partial archive cleanup failed: ${failureReason(cleanup)}`; } diff --git a/src/domain/analysisCleanupRelease.test.ts b/src/domain/analysisCleanupRelease.test.ts index 988a11c825..6af673e234 100644 --- a/src/domain/analysisCleanupRelease.test.ts +++ b/src/domain/analysisCleanupRelease.test.ts @@ -4,6 +4,8 @@ import { AnalysisCleanupRelease } from "./analysisCleanupRelease.js"; import { analysisErrorWithCleanupDependencies, analysisErrorWithCleanupFailure, + analysisErrorWithCloseRejection, + analysisErrorWithCloseRejections, } from "./analysisErrorCleanup.js"; import { ProviderCleanupError } from "./providerCleanupError.js"; @@ -134,3 +136,63 @@ it("keeps an owner's record bound to a composition of owned parts", () => { ownerRelease.confirm(); expect(composed.cleanupIncomplete).toBe(false); }); + +// A primary that still holds resources keeps the composite incomplete after +// the cleanup that followed it releases: binding only the cleanup would let +// the composite read as complete while the primary's resources remain owned. +it("keeps a composed failure incomplete until the primary's own owner releases", () => { + const primaryRelease = new AnalysisCleanupRelease(); + const cleanupRelease = new AnalysisCleanupRelease(); + const composed = analysisErrorWithCleanupDependencies( + primaryRelease.bind(resource("session")), + cleanupRelease.bind(resource("workspace")), + ); + cleanupRelease.confirm(); + expect(composed.cleanupIncomplete).toBe(true); + expect(composed.cleanupResources).toEqual(["session"]); + primaryRelease.confirm(); + expect(composed.cleanupIncomplete).toBe(false); + expect(composed.cleanupResources).toEqual([]); +}); + +// A close rejection whose cleanup record is not live has unknown completion: +// the composite must not read as complete because nothing was left to bind. +it("keeps a composition with an unknown-completion close rejection incomplete", () => { + const primaryRelease = new AnalysisCleanupRelease(); + const rejectionRelease = new AnalysisCleanupRelease(); + const rejection = rejectionRelease.bind(resource("socket")); + rejectionRelease.confirm(); + + const composed = analysisErrorWithCloseRejection( + primaryRelease.bind(resource("session")), + rejection, + ); + primaryRelease.confirm(); + expect(composed.cleanupIncomplete).toBe(true); + expect( + analysisErrorWithCloseRejections(rejection, resource("worker")) + .cleanupIncomplete, + ).toBe(true); + expect( + analysisErrorWithCloseRejections(resource("worker"), rejection) + .cleanupIncomplete, + ).toBe(true); +}); + +it.each(["rejection", "rejections"] as const)( + "binds live close rejections so the composite completes when they release (%s)", + (shape) => { + const firstRelease = new AnalysisCleanupRelease(); + const secondRelease = new AnalysisCleanupRelease(); + const first = firstRelease.bind(resource("session")); + const second = secondRelease.bind(resource("socket")); + const composed = + shape === "rejection" + ? analysisErrorWithCloseRejection(first, second) + : analysisErrorWithCloseRejections(first, second); + secondRelease.confirm(); + expect(composed.cleanupIncomplete).toBe(true); + firstRelease.confirm(); + expect(composed.cleanupIncomplete).toBe(false); + }, +); diff --git a/src/domain/analysisCleanupRelease.ts b/src/domain/analysisCleanupRelease.ts index ea5a0e2fd3..4cd3a90ad6 100644 --- a/src/domain/analysisCleanupRelease.ts +++ b/src/domain/analysisCleanupRelease.ts @@ -20,6 +20,17 @@ export class AnalysisCleanupRelease implements AnalysisCleanupReleaseClaim { return error.bindCleanupReleaseClaim(this); } + /** + * Let a failure reported by another producer read this release only when + * its cleanup has no owner of its own; an owned failure keeps reading that + * owner, so a later release of its resources is not hidden behind this one. + */ + bindUnowned(error: T): T { + return error.cleanupIncomplete && !error.hasCleanupOwner + ? this.bind(error) + : error; + } + confirm(): void { this.#released = true; } diff --git a/src/domain/analysisErrorCleanup.ts b/src/domain/analysisErrorCleanup.ts index 2521f3d40f..5963e558be 100644 --- a/src/domain/analysisErrorCleanup.ts +++ b/src/domain/analysisErrorCleanup.ts @@ -73,3 +73,32 @@ export const analysisErrorWithCleanupDependencies = ( cleanup, operation, ).bindCleanupDependencies([primary, cleanup]); + +/** + * Compose a failure with a close rejection whose completion may be unknown. A + * rejection without a live cleanup record has unknown completion, not + * confirmed release, so the composite binds its parts only while the rejection + * is live. Otherwise it keeps its own pending record and never reads as + * complete. + */ +export const analysisErrorWithCloseRejection = ( + primary: AnalysisError, + rejection: AnalysisError, + operation = "close_binary", +): AnalysisError => + rejection.cleanupIncomplete + ? analysisErrorWithCleanupDependencies(primary, rejection, operation) + : analysisErrorWithCleanupFailure(primary, rejection, operation); + +/** + * Compose two close rejections. Each may have unknown completion, so the + * composite binds them only while both are live. + */ +export const analysisErrorWithCloseRejections = ( + first: AnalysisError, + second: AnalysisError, + operation = "close_binary", +): AnalysisError => + first.cleanupIncomplete + ? analysisErrorWithCloseRejection(first, second, operation) + : analysisErrorWithCleanupFailure(first, second, operation); diff --git a/src/dotnet/ManagedSnapshot.ts b/src/dotnet/ManagedSnapshot.ts index 0256d4f535..91746da420 100644 --- a/src/dotnet/ManagedSnapshot.ts +++ b/src/dotnet/ManagedSnapshot.ts @@ -15,7 +15,7 @@ import { type RegularFileReadOptions, } from "../process/RegularFileRead.js"; import { ArtifactReaderFailure } from "../resources/index.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; import { AnalysisArtifactChangedError, @@ -280,11 +280,7 @@ export const managedCleanupError = ( failure.retainPartialObservation(observation); } return failure instanceof AnalysisError - ? analysisErrorWithCleanupFailure( - failure, - cleanup, - operation, - ).bindCleanupDependencies([failure, cleanup]) + ? analysisErrorWithCleanupDependencies(failure, cleanup, operation) : cleanup; } if (cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined) { @@ -307,11 +303,7 @@ export const managedCleanupError = ( ), { partialObservation: cause.partialObservation }, ); - return analysisErrorWithCleanupFailure( - cancelled, - error, - operation, - ).bindCleanupDependencies([cancelled, error]); + return analysisErrorWithCleanupDependencies(cancelled, error, operation); } return error; } diff --git a/src/electron/ElectronFuseFailures.ts b/src/electron/ElectronFuseFailures.ts index 1c5356306e..4651476d0b 100644 --- a/src/electron/ElectronFuseFailures.ts +++ b/src/electron/ElectronFuseFailures.ts @@ -8,7 +8,7 @@ import { bindArtifactFileCleanup, } from "../resources/index.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { regularFileCancellation } from "../filesystem/OwnedRegularFile.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; import { @@ -57,11 +57,11 @@ export const electronFuseFailure = ( ? undefined : cancelledBy(operation, carriedReason(cancellation.reason)); if (primary !== undefined) - return analysisErrorWithCleanupFailure( + return analysisErrorWithCleanupDependencies( primary, cleanup, operation, - ).bindCleanupDependencies([primary, cleanup]); + ); } return cleanup; } diff --git a/src/flutter/FlutterBuildProvider.ts b/src/flutter/FlutterBuildProvider.ts index 2dd3a4be9c..2c8ac69191 100644 --- a/src/flutter/FlutterBuildProvider.ts +++ b/src/flutter/FlutterBuildProvider.ts @@ -8,7 +8,7 @@ import { ArtifactReaderFailure, type ArtifactEntry, } from "../resources/index.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { analysisErrorWithCancellation } from "../domain/analysisErrorCancellation.js"; import { regularFileCancellation } from "../filesystem/OwnedRegularFile.js"; import { createHash } from "node:crypto"; @@ -628,11 +628,7 @@ export class FlutterBuildProvider { cleanup: AnalysisError, operation: string, ): AnalysisError { - return analysisErrorWithCleanupFailure( - primary, - cleanup, - operation, - ).bindCleanupDependencies([primary, cleanup]); + return analysisErrorWithCleanupDependencies(primary, cleanup, operation); } /** Stop admission and drain active snapshots before attempting retained cleanup. */ diff --git a/src/ghidra/GhidraJavaProbe.ts b/src/ghidra/GhidraJavaProbe.ts index b228fbb1bb..2c37fbc948 100644 --- a/src/ghidra/GhidraJavaProbe.ts +++ b/src/ghidra/GhidraJavaProbe.ts @@ -13,7 +13,7 @@ import { randomUUID } from "node:crypto"; import { AnalysisError } from "../domain/analysisErrorBase.js"; import { cancelledBy, carriedReason } from "../domain/analysisErrorCore.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { jsonValueSchema } from "../domain/jsonValue.js"; import type { RetainedResourceScope } from "../ports/AnalysisProvider.js"; import { DarwinProcessOwnershipInspectionError } from "../process/DarwinProcessRunTokenReader.js"; @@ -319,11 +319,11 @@ const observeGhidraJava = async ( primary = probeFailureError(failed, cause); } for (const cleanup of cleanups) - primary = analysisErrorWithCleanupFailure( + primary = analysisErrorWithCleanupDependencies( primary, cleanup, "ghidra:java", - ).bindCleanupDependencies([primary, cleanup]); + ); return err( bindProcessInspectionCancellations(cause, primary, "ghidra:java"), ); diff --git a/src/ghidra/GhidraNativeAotSnapshotOwner.ts b/src/ghidra/GhidraNativeAotSnapshotOwner.ts index 8d696af862..ea6fb59b28 100644 --- a/src/ghidra/GhidraNativeAotSnapshotOwner.ts +++ b/src/ghidra/GhidraNativeAotSnapshotOwner.ts @@ -3,7 +3,7 @@ import type { AnalysisError, AnalysisPartialObservation, } from "../domain/analysisErrorBase.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { AnalysisArtifactChangedError, type AnalysisCancelledError, @@ -219,11 +219,11 @@ export class GhidraNativeAotSnapshotOwner { }, ); return failure.cleanupFailure?.cleanupIncomplete - ? analysisErrorWithCleanupFailure( + ? analysisErrorWithCleanupDependencies( primary, failure.cleanupFailure, operation, - ).bindCleanupDependencies([primary, failure.cleanupFailure]) + ) : primary; } if (failure.kind !== "cancelled" || this.#conflict === undefined) @@ -391,11 +391,7 @@ export class GhidraNativeAotSnapshotOwner { }); const cleanup = source?.cleanupFailure ?? this.cleanupFailure; return cleanup?.cleanupIncomplete - ? analysisErrorWithCleanupFailure( - primary, - cleanup, - operation, - ).bindCleanupDependencies([primary, cleanup]) + ? analysisErrorWithCleanupDependencies(primary, cleanup, operation) : primary; } } diff --git a/src/ghidra/GhidraProviderClient.ts b/src/ghidra/GhidraProviderClient.ts index af95f47494..e89e96a852 100644 --- a/src/ghidra/GhidraProviderClient.ts +++ b/src/ghidra/GhidraProviderClient.ts @@ -20,7 +20,7 @@ import { } from "../domain/analysisResourceLimits.js"; import { z } from "zod"; import { analysisClientFailureForOperation } from "../providers/AnalysisClientFailure.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { artifactFilePrimaryFacts } from "../resources/index.js"; import { fileURLToPath } from "node:url"; import { GHIDRA_BRIDGE_SOURCES } from "./GhidraBridgeSources.js"; @@ -830,11 +830,11 @@ export const createGhidraProviderClient = (input: { const closed = await client.close(); return closed.ok ? extensionFailure - : analysisErrorWithCleanupFailure( + : analysisErrorWithCleanupDependencies( extensionFailure, closed.error, operation, - ).bindCleanupDependencies([extensionFailure, closed.error]); + ); }; const startSession = async ( operation: AnalysisOperation, @@ -1197,12 +1197,7 @@ export const createGhidraProviderClient = (input: { if (retained === undefined) return closed; return closed.ok ? err(retained) - : err( - analysisErrorWithCleanupFailure( - closed.error, - retained, - ).bindCleanupDependencies([closed.error, retained]), - ); + : err(analysisErrorWithCleanupDependencies(closed.error, retained)); }, }); }; @@ -1330,11 +1325,11 @@ const projectSessionError = ( ); return failure.cleanupFailure === undefined ? primary - : analysisErrorWithCleanupFailure( + : analysisErrorWithCleanupDependencies( primary, failure.cleanupFailure, operation, - ).bindCleanupDependencies([primary, failure.cleanupFailure]); + ); }; const projectPrimarySessionError = ( diff --git a/src/ghidra/GhidraSessionError.ts b/src/ghidra/GhidraSessionError.ts index c76184e22b..d09703eb60 100644 --- a/src/ghidra/GhidraSessionError.ts +++ b/src/ghidra/GhidraSessionError.ts @@ -1,4 +1,4 @@ -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { AnalysisError, type AnalysisPartialObservation, @@ -92,10 +92,7 @@ export class GhidraSessionError extends Error { const combined = this.cleanupFailure === undefined || this.cleanupFailure === cleanup ? cleanup - : analysisErrorWithCleanupFailure( - this.cleanupFailure, - cleanup, - ).bindCleanupDependencies([this.cleanupFailure, cleanup]); + : analysisErrorWithCleanupDependencies(this.cleanupFailure, cleanup); return this.#copy(diagnostics, combined); } diff --git a/src/hopper/HopperClient.ts b/src/hopper/HopperClient.ts index dbeabb341b..403d484b26 100644 --- a/src/hopper/HopperClient.ts +++ b/src/hopper/HopperClient.ts @@ -11,7 +11,11 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import writeFileAtomic from "write-file-atomic"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { AnalysisCleanupRelease } from "../domain/analysisCleanupRelease.js"; +import { + analysisErrorWithCloseRejection, + analysisErrorWithCloseRejections, +} from "../domain/analysisErrorCleanup.js"; import { analysisClientFailureContext } from "../providers/AnalysisClientFailure.js"; import { AnalysisCapabilityUnavailableError, @@ -210,6 +214,15 @@ export class HopperClient< #runId: string | undefined; #startupAttempt: HopperStartupAttempt | undefined; #closePromise: Promise> | undefined; + /** + * Confirm the failures a close of this client reported, one release per + * part: the next close retries the same retained session and launcher, and + * each part's success releases only the failures that part reported. + */ + readonly #closeRetries: { + session: AnalysisCleanupRelease | undefined; + launcher: AnalysisCleanupRelease | undefined; + } = { session: undefined, launcher: undefined }; readonly #onSocketData = (chunk: Buffer): void => { this.#responses.push(chunk); }; @@ -716,7 +729,7 @@ export class HopperClient< const closed = await this.#cleanup(); const failure = closed.ok ? primary - : analysisErrorWithCleanupFailure(primary, closed.error, "open_binary"); + : analysisErrorWithCloseRejection(primary, closed.error, "open_binary"); this.#startupFailureResult = failure; return err(failure); } @@ -970,11 +983,33 @@ export class HopperClient< ), ), ); - if (launcherClosed === undefined || launcherClosed.ok) return closed; + // Each part confirms its own earlier failures when it succeeds; an + // ownerless failed part binds to its part's retry before composing, so + // the composite reports only the parts still unreleased. A part that + // already follows its own owner keeps reading that owner. + const retries = this.#closeRetries; + if (closed.ok) { + retries.session?.confirm(); + retries.session = undefined; + } else + (retries.session ??= new AnalysisCleanupRelease()).bindUnowned( + closed.error, + ); + if (launcherClosed === undefined || launcherClosed.ok) { + retries.launcher?.confirm(); + retries.launcher = undefined; + return closed; + } + (retries.launcher ??= new AnalysisCleanupRelease()).bindUnowned( + launcherClosed.error, + ); return closed.ok ? launcherClosed : err( - analysisErrorWithCleanupFailure(closed.error, launcherClosed.error), + analysisErrorWithCloseRejections( + closed.error, + launcherClosed.error, + ), ); } finally { if (this.#socket?.destroyed === true) this.#socket = undefined; diff --git a/src/hopper/HopperProvider.ts b/src/hopper/HopperProvider.ts index 365820022b..3c39498362 100644 --- a/src/hopper/HopperProvider.ts +++ b/src/hopper/HopperProvider.ts @@ -32,7 +32,7 @@ import { selectedHopperLauncherPath } from "../hopperPaths/HopperLauncherDiscove import type { BinaryTarget } from "../domain/binaryTargetTypes.js"; import type { JsonValue } from "../domain/jsonValue.js"; import type { Logger } from "pino"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js"; import { err, ok, type Result } from "../domain/result.js"; @@ -614,11 +614,11 @@ export class HopperProvider implements AnalysisProviderCandidate { return closed.ok ? err(descriptors) : err( - analysisErrorWithCleanupFailure( + analysisErrorWithCleanupDependencies( closed.error, descriptors, "close_binary", - ).bindCleanupDependencies([closed.error, descriptors]), + ), ); }, }; diff --git a/src/ida/IdaSessionClient.ts b/src/ida/IdaSessionClient.ts index a57fc57b47..bbe85d5ad3 100644 --- a/src/ida/IdaSessionClient.ts +++ b/src/ida/IdaSessionClient.ts @@ -64,7 +64,7 @@ import { } from "../resources/index.js"; import { classifyProviderFailure } from "../providers/classifyProviderFailure.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { analysisClientFailureContext, analysisClientFailureForOperation, @@ -550,11 +550,11 @@ export class IdaSessionClient implements AnalysisClient { { operation, cause: read }, ); bindArtifactFileCleanup(read, cleanup); - return analysisErrorWithCleanupFailure( + return analysisErrorWithCleanupDependencies( primary ?? adapterFailure(read), cleanup, operation, - ).bindCleanupDependencies([cleanup]); + ); }, unclassified: adapterFailure, }); diff --git a/src/javascript/analysis/JavaScriptAnalysisWorker.ts b/src/javascript/analysis/JavaScriptAnalysisWorker.ts index 3b5a8cef35..5bd0f58981 100644 --- a/src/javascript/analysis/JavaScriptAnalysisWorker.ts +++ b/src/javascript/analysis/JavaScriptAnalysisWorker.ts @@ -10,7 +10,7 @@ import { ArtifactReaderFailure, bindArtifactFileCleanup, } from "../../resources/index.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js"; import { retainProcessInspectionCleanup, processInspectionCancellationError, @@ -706,11 +706,11 @@ export class JavaScriptAnalysisWorker { ? runtime.reason : this.#failure(runtime.reason, "worker close", undefined); if (inspectionError !== undefined) - throw analysisErrorWithCleanupFailure( + throw analysisErrorWithCleanupDependencies( runtimeError, inspectionError, OPERATION, - ).bindCleanupDependencies([runtimeError, inspectionError]); + ); throw runtimeError; } if (inspectionError !== undefined) throw inspectionError; diff --git a/src/kuna/KunaProjectCache.ts b/src/kuna/KunaProjectCache.ts index a28cff3cfa..fccc6c2d0d 100644 --- a/src/kuna/KunaProjectCache.ts +++ b/src/kuna/KunaProjectCache.ts @@ -33,7 +33,7 @@ import { bindArtifactFileCleanup, AnalysisCleanupLease, } from "../resources/index.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; import { AnalysisResourceConstraintError, @@ -1057,11 +1057,11 @@ export class KunaProjectCache { return err( built.result.ok ? new KunaPublishedProjectCleanupError(built.result.value, retired) - : analysisErrorWithCleanupFailure( + : analysisErrorWithCleanupDependencies( built.result.error, retired, KUNA_EXPORT_OPERATION, - ).bindCleanupDependencies([built.result.error, retired]), + ), ); if (built.result.ok) // The entry is published either way; a failed eviction retries on the next publish. diff --git a/src/kuna/KunaProjectExport.ts b/src/kuna/KunaProjectExport.ts index 41eeda961e..8c3e0a3566 100644 --- a/src/kuna/KunaProjectExport.ts +++ b/src/kuna/KunaProjectExport.ts @@ -4,7 +4,7 @@ import { artifactFileCancellationCause, bindArtifactFileCleanup, } from "../resources/index.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import type { RegularFileState } from "../filesystem/RegularFile.js"; import { createHash } from "node:crypto"; import { @@ -212,11 +212,11 @@ export const kunaExportFailureDialect = ( const { completion } = kunaCopyFailureFacts(read); if (completion !== undefined && completion.cancellation === undefined) return cleanup; - return analysisErrorWithCleanupFailure( + return analysisErrorWithCleanupDependencies( projectCacheReadFailure(read), cleanup, KUNA_EXPORT_OPERATION, - ).bindCleanupDependencies([cleanup]); + ); }, unclassified: (cause) => { if (cause instanceof ArtifactReaderFailure) diff --git a/src/kuna/KunaProjectReader.ts b/src/kuna/KunaProjectReader.ts index 3359c2fdb7..7d75472feb 100644 --- a/src/kuna/KunaProjectReader.ts +++ b/src/kuna/KunaProjectReader.ts @@ -11,7 +11,7 @@ import { open } from "node:fs/promises"; import { join } from "node:path"; import { AnalysisError } from "../domain/analysisErrorBase.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { AnalysisCancelledError, AnalysisResourceConstraintError, @@ -261,14 +261,14 @@ const spanCloseFailure = ( ); ownership.bindSpanCleanup(failure.owner, marker); if (failure.completionCancellation !== undefined) - return analysisErrorWithCleanupFailure( + return analysisErrorWithCleanupDependencies( cancelledBy( operation, carriedReason(failure.completionCancellation.reason), ), marker, operation, - ).bindCleanupDependencies([marker]); + ); if (failure.outcome.kind !== "failed") return marker; const primaryCause = failure.outcome.cause; const primary = @@ -282,11 +282,7 @@ const spanCloseFailure = ( ? primaryCause.message : String(primaryCause), }); - return analysisErrorWithCleanupFailure( - primary, - marker, - operation, - ).bindCleanupDependencies([marker]); + return analysisErrorWithCleanupDependencies(primary, marker, operation); }; /** One immutable export owns both its text ranges and its parsed label indexes. */ diff --git a/src/kuna/KunaTargetCommands.ts b/src/kuna/KunaTargetCommands.ts index 68b9b10e91..fa4e3a830f 100644 --- a/src/kuna/KunaTargetCommands.ts +++ b/src/kuna/KunaTargetCommands.ts @@ -26,7 +26,7 @@ import { import type { BinaryTarget } from "../domain/binaryTargetTypes.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { err, ok, type Result } from "../domain/result.js"; import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js"; import { prepareProcessOwnershipInspection } from "../process/ProcessOwnershipObservation.js"; @@ -474,11 +474,11 @@ export class KunaTargetCommands { { cause, operation: "kuna:workspace" }, ); owned.cleanup.bindCleanupError(cleanup); - failure = analysisErrorWithCleanupFailure( + failure = analysisErrorWithCleanupDependencies( primary, cleanup, "kuna:workspace", - ).bindCleanupDependencies([primary, cleanup]); + ); } } return err( diff --git a/src/native/LldbCallTracer.ts b/src/native/LldbCallTracer.ts index 8b78b068ac..578cfc71e2 100644 --- a/src/native/LldbCallTracer.ts +++ b/src/native/LldbCallTracer.ts @@ -69,7 +69,7 @@ import { } from "./CommandRunner.js"; import { projectPartialNativeCalls } from "./NativeCallObservation.js"; import { LldbReadbackFiles } from "./LldbReadbackFiles.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { resolvedAnalysisError } from "../domain/analysisErrorBase.js"; import { runOwned } from "../providers/runOwned.js"; import { @@ -390,11 +390,11 @@ export class LldbCallTracer implements NativeCallTracer { const failure = await this.#retryPendingCleanup(); if (resolverCleanup !== undefined && failure !== undefined) return err( - analysisErrorWithCleanupFailure( + analysisErrorWithCleanupDependencies( resolverCleanup, failure, OPERATION, - ).bindCleanupDependencies([resolverCleanup, failure]), + ), ); if (resolverCleanup !== undefined) return err(resolverCleanup); return failure === undefined ? ok(null) : err(failure); diff --git a/src/native/NativeMacOSProvider.ts b/src/native/NativeMacOSProvider.ts index ec026ef376..338a9a8458 100644 --- a/src/native/NativeMacOSProvider.ts +++ b/src/native/NativeMacOSProvider.ts @@ -149,7 +149,10 @@ import { architectureLocations, inspectNativeMacho, } from "./NativeMachoInspection.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { + analysisErrorWithCleanupDependencies, + analysisErrorWithCleanupFailure, +} from "../domain/analysisErrorCleanup.js"; import { analysisErrorWithCancellation } from "../domain/analysisErrorCancellation.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import { @@ -461,12 +464,7 @@ class NativeMacOSClient implements AnalysisClient { for (const cleanupError of cleanupErrors) result = result.ok ? err(cleanupError) - : err( - analysisErrorWithCleanupFailure( - result.error, - cleanupError, - ).bindCleanupDependencies([result.error, cleanupError]), - ); + : err(analysisErrorWithCleanupDependencies(result.error, cleanupError)); return result; } @@ -543,11 +541,11 @@ class NativeMacOSClient implements AnalysisClient { return err( result.ok ? cleanup - : analysisErrorWithCleanupFailure( + : analysisErrorWithCleanupDependencies( result.error, cleanup, operation, - ).bindCleanupDependencies([result.error, cleanup]), + ), ); } result = finishNativeUiObservation(result, operation, interruption); @@ -1566,11 +1564,11 @@ class NativeMacOSClient implements AnalysisClient { return err( primary === undefined ? cleanup - : analysisErrorWithCleanupFailure( + : analysisErrorWithCleanupDependencies( primary, cleanup, "inspect_macho", - ).bindCleanupDependencies([primary, cleanup]), + ), ); } if (signal?.aborted && result.ok) diff --git a/src/native/NativeMachoSource.ts b/src/native/NativeMachoSource.ts index a533b43011..90c3ba6144 100644 --- a/src/native/NativeMachoSource.ts +++ b/src/native/NativeMachoSource.ts @@ -6,8 +6,6 @@ import { artifactSelectedPathErrno, ArtifactReaderFailure, type ArtifactResourceScope, -} from "../resources/index.js"; -import { hashStableRootArtifactHandle, targetDigestChangedFailure, } from "../resources/index.js"; diff --git a/src/native/NativeUiObservation.ts b/src/native/NativeUiObservation.ts index 0924e63c07..7ed923052c 100644 --- a/src/native/NativeUiObservation.ts +++ b/src/native/NativeUiObservation.ts @@ -23,7 +23,7 @@ import { } from "../domain/analysisErrorCore.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { ExecFileOutputCancelledError } from "../process/ExecFileOutput.js"; import { NativeUiCleanupError } from "./NativeUiCleanupError.js"; import { err, ok, type Result } from "../domain/result.js"; @@ -127,11 +127,11 @@ export const observeNativeUi = async ( return result.ok ? err(cleanup) : err( - analysisErrorWithCleanupFailure( + analysisErrorWithCleanupDependencies( result.error, cleanup, operation, - ).bindCleanupDependencies([result.error, cleanup]), + ), ); } } diff --git a/src/native/SignatureTargetBinding.ts b/src/native/SignatureTargetBinding.ts index f8a7fabd22..ce23efe1ef 100644 --- a/src/native/SignatureTargetBinding.ts +++ b/src/native/SignatureTargetBinding.ts @@ -22,7 +22,7 @@ import { import { InternalInvariantError } from "../domain/internalInvariant.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { analysisErrorWithCancellation } from "../domain/analysisErrorCancellation.js"; import { err, ok, type Result } from "../domain/result.js"; import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js"; @@ -222,11 +222,11 @@ export const withSignatureTarget = async ( ); bindArtifactFileCleanup(cause, failure); return err( - analysisErrorWithCleanupFailure( + analysisErrorWithCleanupDependencies( outcome, failure, "inspect_signature", - ).bindCleanupDependencies([outcome, failure]), + ), ); } return err(outcome); diff --git a/src/native/pwndbg/PwndbgCoreContext.ts b/src/native/pwndbg/PwndbgCoreContext.ts index c7d1e815c2..7fe9744b02 100644 --- a/src/native/pwndbg/PwndbgCoreContext.ts +++ b/src/native/pwndbg/PwndbgCoreContext.ts @@ -33,7 +33,7 @@ import { type RecordedCrash, } from "../../domain/native/recordedCrash.js"; import { AnalysisError } from "../../domain/analysisErrorBase.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js"; import { ProviderCleanupError } from "../../domain/providerCleanupError.js"; import { pwntoolsFailureDialect, @@ -412,11 +412,7 @@ export const pwndbgContextFinalizationFailure = ( finalization === undefined ? primary : finalization.cleanupIncomplete - ? analysisErrorWithCleanupFailure( - primary, - finalization, - OPERATION, - ).bindCleanupDependencies([primary, finalization]) + ? analysisErrorWithCleanupDependencies(primary, finalization, OPERATION) : primary.retainSecondaryFailure(finalization); /** Preserve both stages' exact text and their independently observed truncation state. */ diff --git a/src/native/pwntools/PwntoolsDecoder.ts b/src/native/pwntools/PwntoolsDecoder.ts index a891305f98..ff3a4b675d 100644 --- a/src/native/pwntools/PwntoolsDecoder.ts +++ b/src/native/pwntools/PwntoolsDecoder.ts @@ -53,7 +53,7 @@ import { projectAnalysisError, projectAnalysisErrorWithoutCapturedOutput, } from "../../domain/analysisErrorProjection.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js"; import { ProviderAdapterError } from "../../domain/providerAdapterError.js"; import { ProviderCleanupError } from "../../domain/providerCleanupError.js"; import { err, ok, type Result } from "../../domain/result.js"; @@ -512,11 +512,11 @@ export class PwntoolsDecoder< })); replyFinalization = cleanup !== undefined && primary !== cleanup - ? analysisErrorWithCleanupFailure( + ? analysisErrorWithCleanupDependencies( primary, cleanup, OPERATION, - ).bindCleanupDependencies([primary, cleanup]) + ) : primary; } const decoded = safeParseUtf8Json(file.bytes); @@ -660,11 +660,11 @@ export class PwntoolsDecoder< if (replyFinalization !== undefined && cause !== replyFinalization) { const primary = failure(cause); cause = replyFinalization.cleanupIncomplete - ? analysisErrorWithCleanupFailure( + ? analysisErrorWithCleanupDependencies( primary, replyFinalization, OPERATION, - ).bindCleanupDependencies([primary, replyFinalization]) + ) : primary.retainSecondaryFailure(replyFinalization, { reply_finalization_error: projectAnalysisErrorWithoutCapturedOutput(replyFinalization), @@ -717,11 +717,11 @@ export class PwntoolsDecoder< if (cleanup !== undefined) { const failure = result.ok ? cleanup - : analysisErrorWithCleanupFailure( + : analysisErrorWithCleanupDependencies( result.error, cleanup, OPERATION, - ).bindCleanupDependencies([result.error, cleanup]); + ); if (this.#pendingCleanup !== undefined) this.#pendingCleanup.failure = failure; return err(failure); @@ -786,11 +786,11 @@ export class PwntoolsDecoder< if (outcome.ok) throw cleanup; // Until retirement succeeds, resource-limit markers remain unverified. const primary = failure(outcome.error); - throw analysisErrorWithCleanupFailure( + throw analysisErrorWithCleanupDependencies( primary, cleanup, this.profile.operation, - ).bindCleanupDependencies([primary, cleanup]); + ); } if (!outcome.ok) throw outcome.error; return outcome.value; @@ -829,11 +829,11 @@ export class PwntoolsDecoder< failure = failure === undefined ? resourceFailure - : analysisErrorWithCleanupFailure( + : analysisErrorWithCleanupDependencies( failure, resourceFailure, this.profile.operation, - ).bindCleanupDependencies([failure, resourceFailure]); + ); } if (failure !== undefined) throw failure; }) @@ -931,11 +931,11 @@ export class PwntoolsDecoder< if (processFailure !== undefined) { return failure === undefined ? processFailure - : analysisErrorWithCleanupFailure( + : analysisErrorWithCleanupDependencies( failure, processFailure, this.profile.operation, - ).bindCleanupDependencies([failure, processFailure]); + ); } // Retained descriptors still own local evidence under this root. if (failure !== undefined) return failure; diff --git a/src/process/DarwinProcessRunTokenReader.ts b/src/process/DarwinProcessRunTokenReader.ts index 880af6de8c..08c0b2d0d0 100644 --- a/src/process/DarwinProcessRunTokenReader.ts +++ b/src/process/DarwinProcessRunTokenReader.ts @@ -27,7 +27,7 @@ import type { AnalysisCapturedOutput, AnalysisError, } from "../domain/analysisErrorBase.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { safeParseJson } from "../domain/safeJson.js"; import { utf8HeadExcerpt } from "../domain/utf8HeadExcerpt.js"; import { createDarwinHelperCache } from "./DarwinHelperCache.js"; @@ -229,10 +229,7 @@ export class DarwinProcessOwnershipInspectionError extends Error { const combined = this.cleanupFailure === undefined || this.cleanupFailure === cleanup ? cleanup - : analysisErrorWithCleanupFailure( - this.cleanupFailure, - cleanup, - ).bindCleanupDependencies([this.cleanupFailure, cleanup]); + : analysisErrorWithCleanupDependencies(this.cleanupFailure, cleanup); return new DarwinProcessOwnershipInspectionError(this.message, { ...(Object.hasOwn(this, "cause") ? { cause: this.cause } : {}), ...(this.compilerOutcome === undefined @@ -907,10 +904,10 @@ export const createDarwinProcessRunTokenReader = ( rootCleanup.reason instanceof ProviderCleanupError && cacheCleanup.reason instanceof ProviderCleanupError ) - throw analysisErrorWithCleanupFailure( + throw analysisErrorWithCleanupDependencies( rootCleanup.reason, cacheCleanup.reason, - ).bindCleanupDependencies([rootCleanup.reason, cacheCleanup.reason]); + ); if (rootCleanup.status === "rejected") throw rootCleanup.reason; if (cacheCleanup.status === "rejected") throw cacheCleanup.reason; })().catch((cause: unknown) => { diff --git a/src/process/capture/FilesystemSnapshot.ts b/src/process/capture/FilesystemSnapshot.ts index a66e4d5e2e..45e2831f9c 100644 --- a/src/process/capture/FilesystemSnapshot.ts +++ b/src/process/capture/FilesystemSnapshot.ts @@ -33,7 +33,7 @@ import { type ProcessCaptureCleanupRetainer, } from "./ProcessCaptureRead.js"; import { AnalysisError } from "../../domain/analysisErrorBase.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js"; const hasSameIdentity = ( before: Stats, @@ -280,11 +280,7 @@ export class ProcessCaptureSnapshotFailure extends ProcessCaptureError { const primary = this.cleanupPrimary; if (!(primary instanceof AnalysisAccessDeniedError)) return this; return this.cleanupIncomplete - ? analysisErrorWithCleanupFailure( - primary, - this, - "capture_process", - ).bindCleanupDependencies([primary, this]) + ? analysisErrorWithCleanupDependencies(primary, this, "capture_process") : primary; } } diff --git a/src/process/capture/ProcessCaptureLifecycle.ts b/src/process/capture/ProcessCaptureLifecycle.ts index 13a6cd2824..9b74f179d9 100644 --- a/src/process/capture/ProcessCaptureLifecycle.ts +++ b/src/process/capture/ProcessCaptureLifecycle.ts @@ -64,7 +64,7 @@ import { PROCESS_PROVIDER } from "../../domain/process/processEvidenceProvider.j import { TerminalRenderer } from "./TerminalRenderer.js"; import type { ProcessSensitiveOutput } from "./ProcessSensitiveOutput.js"; import { AnalysisError } from "../../domain/analysisErrorBase.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js"; import { jsonValueSchema } from "../../domain/jsonValue.js"; import { hasCaptureTruncation, @@ -1871,11 +1871,11 @@ export const resolveProcessResult = ( if (executionFailure instanceof AnalysisError) { if (partialObservation !== undefined) executionFailure.retainPartialObservation(partialObservation); - throw analysisErrorWithCleanupFailure( + throw analysisErrorWithCleanupDependencies( executionFailure, cleanupError, "capture_process", - ).bindCleanupDependencies([executionFailure, cleanupError]); + ); } throw cleanupError; } diff --git a/src/process/capture/ProcessHarness.ts b/src/process/capture/ProcessHarness.ts index a9142c0b9a..28bf7f50e3 100644 --- a/src/process/capture/ProcessHarness.ts +++ b/src/process/capture/ProcessHarness.ts @@ -11,7 +11,7 @@ import { createProcessTerminalFinalizer, retainTerminalObservationFailure, } from "./ProcessTerminalObservation.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js"; import { captureInspectionFailures, describeProcessCaptureExecutionFailure, @@ -486,9 +486,11 @@ const retainSamplingFailure = ( retainCaptureInspectionCancellations(error, inspection); if (error.secondaryFailures.includes(secondary)) return error; if (secondary.cleanupIncomplete) - return analysisErrorWithCleanupFailure(error, secondary, "capture_process") - .bindCleanupDependencies([error, secondary]) - .retainSecondaryFailure(secondary); + return analysisErrorWithCleanupDependencies( + error, + secondary, + "capture_process", + ).retainSecondaryFailure(secondary); return error.retainSecondaryFailure(secondary); }; @@ -1076,11 +1078,11 @@ export const captureProcessScenario = async ( ? cause : capture.error instanceof ProcessCaptureError ? capture.error.withFinalization({ cleanupFailure: cause }) - : analysisErrorWithCleanupFailure( + : analysisErrorWithCleanupDependencies( capture.error, cause, "capture_process_scenario", - ).bindCleanupDependencies([capture.error, cause]), + ), ); } return capture; diff --git a/src/providers/AnalysisClientCreation.ts b/src/providers/AnalysisClientCreation.ts index b984919b3d..333c33e498 100644 --- a/src/providers/AnalysisClientCreation.ts +++ b/src/providers/AnalysisClientCreation.ts @@ -21,7 +21,7 @@ import { closedAnalysisClientError, ProviderAdapterError, } from "../domain/providerAdapterError.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { err, ok, type Result } from "../domain/result.js"; import { SharedStartupAttempt } from "../process/SharedStartupAttempt.js"; import { closeAnalysisClient } from "./AnalysisClientCleanup.js"; @@ -162,21 +162,21 @@ export class AnalysisClientCreation { primary = primary === undefined ? inspections.error - : analysisErrorWithCleanupFailure( + : analysisErrorWithCleanupDependencies( primary, inspections.error, "create_analysis_client", - ).bindCleanupDependencies([primary, inspections.error]); + ); if (primary !== undefined) { const closed = await this.#releaseClient(this.#closeOptions); return err( closed.ok ? primary - : analysisErrorWithCleanupFailure( + : analysisErrorWithCleanupDependencies( primary, closed.error, "create_analysis_client", - ).bindCleanupDependencies([primary, closed.error]), + ), ); } if (this.#client === undefined) @@ -224,11 +224,11 @@ export class AnalysisClientCreation { const closed = await this.#releaseClient(options); if (!closed.ok && inspectionFailure !== undefined) return err( - analysisErrorWithCleanupFailure( + analysisErrorWithCleanupDependencies( closed.error, inspectionFailure, "create_analysis_client", - ).bindCleanupDependencies([closed.error, inspectionFailure]), + ), ); if (!closed.ok) return closed; if (inspectionFailure !== undefined) return err(inspectionFailure); diff --git a/src/providers/OwnedCommandCleanup.ts b/src/providers/OwnedCommandCleanup.ts index 7ae8034f53..6a13ea06c8 100644 --- a/src/providers/OwnedCommandCleanup.ts +++ b/src/providers/OwnedCommandCleanup.ts @@ -14,7 +14,7 @@ import { type ArtifactResourceScope, AnalysisCleanupLease, } from "../resources/index.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { jsonValueSchema } from "../domain/jsonValue.js"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; import type { RetainedResourceScope } from "../ports/AnalysisProvider.js"; @@ -213,11 +213,7 @@ export const retainProcessInspectionCleanup = ( operation, ); for (const failure of failures) - primary = analysisErrorWithCleanupFailure( - primary, - failure, - operation, - ).bindCleanupDependencies([primary, failure]); + primary = analysisErrorWithCleanupDependencies(primary, failure, operation); return bindProcessInspectionCancellations(cause, primary, operation); }; diff --git a/src/rizin/RizinDebugSessionManager.ts b/src/rizin/RizinDebugSessionManager.ts index c9e58ee09d..c33dccc799 100644 --- a/src/rizin/RizinDebugSessionManager.ts +++ b/src/rizin/RizinDebugSessionManager.ts @@ -41,7 +41,10 @@ import type { AnalysisError, AnalysisErrorOptions, } from "../domain/analysisErrorBase.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { + analysisErrorWithCleanupDependencies, + analysisErrorWithCleanupFailure, +} from "../domain/analysisErrorCleanup.js"; import { createEvidence, type Evidence } from "../domain/evidence.js"; import { currentAnalysisOperationSnapshot } from "../domain/analysisOperationSnapshot.js"; import { err, ok, type Result } from "../domain/result.js"; @@ -1728,11 +1731,11 @@ export class RizinDebugSessionManager { operation, stopped.reason, ); - const composed = analysisErrorWithCleanupFailure( + const composed = analysisErrorWithCleanupDependencies( primary, cleanup, operation, - ).bindCleanupDependencies([cleanup]); + ); return this.#sessions.retain(session, composed); } diff --git a/src/server/registerCloseLifecycleTool.ts b/src/server/registerCloseLifecycleTool.ts index f31740e8eb..c766b7537b 100644 --- a/src/server/registerCloseLifecycleTool.ts +++ b/src/server/registerCloseLifecycleTool.ts @@ -8,7 +8,7 @@ import { } from "./operationProgress.js"; import { err, ok } from "../domain/result.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import type { AnalysisCleanupRetry } from "../domain/analysisErrorRecovery.js"; import type { Result } from "../domain/result.js"; import { mcpProgressReporter } from "./mcpProgress.js"; @@ -74,10 +74,10 @@ export const registerCloseLifecycleTool = ({ const resources = resourceClose.value; if (!closed.ok) { if (resources.ok) return closed; - const combined = analysisErrorWithCleanupFailure( + const combined = analysisErrorWithCleanupDependencies( closed.error, resources.error, - ).bindCleanupDependencies([closed.error, resources.error]); + ); // The session offers a retry only after retiring its target; a failed // save keeps that target open and needs its own recovery first. return err( diff --git a/src/server/registerResetInvestigationTool.ts b/src/server/registerResetInvestigationTool.ts index 347828b5b6..37ae4d6ab9 100644 --- a/src/server/registerResetInvestigationTool.ts +++ b/src/server/registerResetInvestigationTool.ts @@ -3,7 +3,7 @@ import { ArtifactReaderFailure, bindArtifactFileCleanup, } from "../resources/index.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { err, ok } from "../domain/result.js"; import { toolRegistrationOptions } from "./toolRegistrationOptions.js"; @@ -53,11 +53,11 @@ export const registerResetInvestigationTool = ({ ]); if (!process.ok && !artifacts.ok) return err( - analysisErrorWithCleanupFailure( + analysisErrorWithCleanupDependencies( process.error, artifacts.error, contract.name, - ).bindCleanupDependencies([process.error, artifacts.error]), + ), ); return process.ok ? artifacts : process; }, diff --git a/src/server/sessionStatusTool.ts b/src/server/sessionStatusTool.ts index f6101839d4..ea9e93ec6d 100644 --- a/src/server/sessionStatusTool.ts +++ b/src/server/sessionStatusTool.ts @@ -12,7 +12,7 @@ import type { BinarySessionPort } from "../application/binary/BinarySessionPort. import type { ProviderAvailability } from "../ports/AnalysisProvider.js"; import type { JebAnalysisAvailability } from "../ports/jeb/JebAnalysisPort.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { buildCapabilityInventory, @@ -90,11 +90,11 @@ const probeSessionAvailability = async ( : new ProviderAdapterError("rea", "binary_session", { cause: failure, }); - failure = analysisErrorWithCleanupFailure( + failure = analysisErrorWithCleanupDependencies( primary, result.reason, "binary_session", - ).bindCleanupDependencies([primary, result.reason]); + ); } throw failure; } diff --git a/src/wasm/WabtArtifactProvider.ts b/src/wasm/WabtArtifactProvider.ts index 0164c08042..4c2f3ac5cc 100644 --- a/src/wasm/WabtArtifactProvider.ts +++ b/src/wasm/WabtArtifactProvider.ts @@ -37,7 +37,7 @@ import { isAborted, } from "../domain/analysisErrorCore.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { analysisErrorWithCancellation } from "../domain/analysisErrorCancellation.js"; import { createEvidence } from "../domain/evidence.js"; import { createAnalysisExecutionEvidence } from "../domain/analysisObservation.js"; @@ -796,11 +796,11 @@ export class WabtArtifactProvider implements WasmArtifactPort { result = result.ok ? err(failure) : err( - analysisErrorWithCleanupFailure( + analysisErrorWithCleanupDependencies( result.error, failure, OPERATION, - ).bindCleanupDependencies([result.error, failure]), + ), ); } } diff --git a/tests/boundary/providers/hopper/hopperClient.cleanupRetry.test.ts b/tests/boundary/providers/hopper/hopperClient.cleanupRetry.test.ts index 897420af1c..b3030c775c 100644 --- a/tests/boundary/providers/hopper/hopperClient.cleanupRetry.test.ts +++ b/tests/boundary/providers/hopper/hopperClient.cleanupRetry.test.ts @@ -5,8 +5,10 @@ import { Socket } from "node:net"; import { expect, it, onTestFinished } from "vitest"; +import { AnalysisCleanupRelease } from "../../../../src/domain/analysisCleanupRelease.js"; import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js"; import { HopperStartError } from "../../../../src/domain/hopperErrors.js"; +import { ProviderCleanupError } from "../../../../src/domain/providerCleanupError.js"; import { err, ok } from "../../../../src/domain/result.js"; import type { BridgeLaunch, @@ -102,7 +104,8 @@ const createClient = (options: HopperClientOptions) => { const failedStartup = async (launcher: RetryCleanupLauncher) => { const client = createClient({ launcher }); - await expect(client.start()).resolves.toMatchObject({ + const started = await client.start(); + expect(started).toMatchObject({ ok: false, error: { _tag: "ProviderAdapterError", @@ -112,14 +115,15 @@ const failedStartup = async (launcher: RetryCleanupLauncher) => { }); const session = launcher.sessions[0]; const child = launcher.processes[0]; - if (session === undefined || child === undefined) + if (session === undefined || child === undefined || started.ok) throw new Error("Fixture launch was not observed"); - return { client, session, child }; + return { client, session, child, startupFailure: started.error }; }; it("retains failed startup cleanup until an owned process and its backing image are closed", async () => { const launcher = new RetryCleanupLauncher(); - const { client, session, child } = await failedStartup(launcher); + const { client, session, child, startupFailure } = + await failedStartup(launcher); const closed = await client.close(); expect(closed).toMatchObject({ ok: false, @@ -150,6 +154,9 @@ it("retains failed startup cleanup until an owned process and its backing image const second = client.close(); await expect(first).resolves.toEqual({ ok: true, value: null }); await expect(second).resolves.toEqual({ ok: true, value: null }); + // The successful retry confirms the cleanup the earlier failures reported. + expect(closed.error.cleanupIncomplete).toBe(false); + expect(startupFailure.cleanupIncomplete).toBe(false); expectStoppedFixture(child); await expect(access(session.directory)).rejects.toMatchObject({ code: "ENOENT", @@ -350,6 +357,110 @@ it("retries a failed lease release after document, process, and runtime cleanup expect(fixture.processes).toHaveLength(1); }); +it("reports a launcher aggregate released by its own owner while session cleanup still fails", async () => { + const fixture = new RetryCleanupLauncher(); + fixture.allowCleanup = true; + // The launcher's aggregate follows its child failure, whose release the + // launcher confirms on its own retry. + const imageRelease = new AnalysisCleanupRelease(); + const imageFailure = imageRelease.bind( + new ProviderCleanupError("hopper", ["hopper-prepared-image"], { + reason: "fixture image cleanup denial", + }), + ); + const launcherFailure = new ProviderCleanupError( + "hopper", + ["hopper-prepared-image"], + { reason: "fixture launcher cleanup denial" }, + ).bindCleanupDependencies([imageFailure]); + let launcherReleases = false; + const launcher: BridgeLauncher = { + launch: async (session) => { + const launched = await fixture.launch(session); + if (!launched.ok) return launched; + return ok({ + ...launched.value, + releaseLease: async () => { + throw new Error("fixture lease release denial"); + }, + }); + }, + cleanup: async () => { + if (!launcherReleases) return err(launcherFailure); + imageRelease.confirm(); + return ok(null); + }, + }; + const client = createClient({ launcher }); + await expect(client.start()).resolves.toMatchObject({ ok: false }); + const first = await client.close(); + expect(first).toMatchObject({ + ok: false, + error: { cleanupIncomplete: true }, + }); + expect(launcherFailure.cleanupIncomplete).toBe(true); + + launcherReleases = true; + const second = await client.close(); + expect(second).toMatchObject({ + ok: false, + error: { cleanupIncomplete: true, cleanupResources: ["hopper-lease"] }, + }); + // The launcher released its resources; only the session's lease remains. + expect(launcherFailure.cleanupIncomplete).toBe(false); + if (!first.ok) expect(first.error.cleanupResources).toEqual(["hopper-lease"]); +}); + +it("releases a session part on its own retry while the launcher part still fails", async () => { + const fixture = new RetryCleanupLauncher(); + fixture.allowCleanup = true; + let leaseReleases = false; + let launcherReleases = false; + const launcher: BridgeLauncher = { + launch: async (session) => { + const launched = await fixture.launch(session); + if (!launched.ok) return launched; + return ok({ + ...launched.value, + releaseLease: async () => { + if (!leaseReleases) throw new Error("fixture lease release denial"); + }, + }); + }, + // An ownerless failure: only this client's retry can confirm it. + cleanup: async () => + launcherReleases + ? ok(null) + : err( + new ProviderCleanupError("hopper", ["hopper-launcher"], { + reason: "fixture launcher cleanup denial", + }), + ), + }; + const client = createClient({ launcher }); + await expect(client.start()).resolves.toMatchObject({ ok: false }); + const first = await client.close(); + if (first.ok) throw new Error("expected both close parts to fail"); + expect([...first.error.cleanupResources].sort()).toEqual([ + "hopper-launcher", + "hopper-lease", + ]); + + leaseReleases = true; + const second = await client.close(); + expect(second).toMatchObject({ + ok: false, + error: { cleanupIncomplete: true, cleanupResources: ["hopper-launcher"] }, + }); + // The session part succeeded: the first failure reports only the launcher. + expect(first.error.cleanupIncomplete).toBe(true); + expect(first.error.cleanupResources).toEqual(["hopper-launcher"]); + + launcherReleases = true; + await expect(client.close()).resolves.toEqual({ ok: true, value: null }); + expect(first.error.cleanupIncomplete).toBe(false); +}); + it("preserves confirmed document shutdown while retrying owned process cleanup", async () => { const launcher = new RetryCleanupLauncher(); const runtimeRoot = await PrivateRuntimeRoot.create();