diff --git a/scripts/verify/architecture-guard-baselines.json b/scripts/verify/architecture-guard-baselines.json index 3174a697f6f..a93cafd8f89 100644 --- a/scripts/verify/architecture-guard-baselines.json +++ b/scripts/verify/architecture-guard-baselines.json @@ -168,55 +168,24 @@ "wall-clock-deadline": { "src/browser/PlaywrightScenarioRequest.ts": 1 }, - "cleanup-resolve-push": { - "src/application/desktop/DesktopBuildComputers.ts": 1, - "src/application/desktop/DesktopRemoteTaskReaders.ts": 1, - "src/application/desktop/DesktopTaskReaderCleanup.ts": 1, - "src/browser/WebSourceMapFetcher.ts": 2, - "src/desktop/AgentEnvSolveHelper.ts": 2, - "src/desktop/BuildComputerLongRuns.ts": 1, - "src/kuna/KunaProjectCache.ts": 1, - "src/native/CommandRunner.ts": 1, - "src/native/LldbCallTracer.ts": 1, - "src/providers/AnalysisClientFailure.ts": 1 - }, "cleanup-dependency-binding": { - "src/android/JadxConfiguration.ts": 1, - "src/android/JadxJavaProbe.ts": 1, - "src/android/JadxProvider.ts": 2, - "src/apktool/ApktoolCommandCleanup.ts": 1, - "src/apktool/ApktoolProvider.ts": 2, - "src/application/AnalysisContextQueries.ts": 1, "src/application/DirectAnalysisCleanup.ts": 2, - "src/application/Doctor.ts": 1, "src/application/EvidenceBundleCommands.ts": 1, - "src/application/EvidenceBundleFiles.ts": 1, "src/application/JsonFiles.ts": 1, - "src/application/Setup.ts": 2, "src/application/SetupCleanupOwner.ts": 2, "src/application/Uninstall.ts": 1, - "src/application/WebNetworkCaptureService.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/CompositeProvider.ts": 1, - "src/application/binaryDiagnostics/ByteEntropyService.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/DesktopApplicationState.ts": 1, - "src/application/desktop/DesktopCaptureFailure.ts": 1, "src/application/desktop/DesktopRetainedContent.ts": 1, - "src/application/environment/environmentExport.ts": 1, - "src/application/frida/FridaInstrumentationService.ts": 3, - "src/application/il2cpp/Il2cppMetadataService.ts": 1, - "src/application/javascript/JavaScriptArtifactReconstruction.ts": 1, - "src/application/managed/ManagedMemberComparisonService.ts": 1, - "src/application/native/NativeUiActionTrace.ts": 1, - "src/application/process/ProcessCli.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, diff --git a/scripts/verify/architecture-guards.mjs b/scripts/verify/architecture-guards.mjs index 0a48e32802a..ca3f3c878c6 100644 --- a/scripts/verify/architecture-guards.mjs +++ b/scripts/verify/architecture-guards.mjs @@ -515,23 +515,17 @@ checkCounted( ["src/domain/parseFailure.ts"], ); -// Cleanup completion is recorded by the owning lease and read by errors when -// asked. Pushing it with resolveCleanup() and composing dependency sets with -// bindCleanupDependencies() are being replaced, so neither may spread. +// Cleanup completion is recorded by the owner and read by errors when asked; +// AnalysisError has no push API. Composing dependency sets with +// bindCleanupDependencies() is being replaced, so it may not spread. checkCounted( - "resolveCleanup() push outside the error base (release the owning AnalysisCleanupLease instead)", - "cleanup-resolve-push", - files, - /\.resolveCleanup\(/gu, - ["src/domain/analysisErrorBase.ts"], -); -checkCounted( - "bindCleanupDependencies() composition outside the error base (compose through runOwned or copy lease claims)", + "bindCleanupDependencies() composition outside the error base (compose through analysisErrorWithCleanupDependencies or runOwned, or copy lease claims)", "cleanup-dependency-binding", files, /\.bindCleanupDependencies\(/gu, - ["src/domain/analysisErrorBase.ts", "src/providers/runOwned.ts"], + ["src/domain/analysisErrorBase.ts", "src/domain/analysisErrorCleanup.ts"], ); + // A launcher's PATH search order (POSIX empty and relative entries and `..`; // Windows quoted entries and PATHEXT) belongs to src/process/executableSearch; // callers choose only how they probe each candidate. diff --git a/src/android/JadxConfiguration.ts b/src/android/JadxConfiguration.ts index 89817e8b0d1..a636b59b744 100644 --- a/src/android/JadxConfiguration.ts +++ b/src/android/JadxConfiguration.ts @@ -38,7 +38,7 @@ import { err, ok, type Result } from "../domain/result.js"; import type { ProviderAvailability } from "../application/AnalysisProvider.js"; import { ownedProcessPrerequisiteAvailability } from "../application/ownedProcessAvailability.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 { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js"; import { @@ -422,11 +422,7 @@ const requireEngineArchive = async ( }, ); if (primary === undefined) throw cleanup; - throw analysisErrorWithCleanupFailure( - primary, - cleanup, - operation, - ).bindCleanupDependencies([primary, cleanup]); + throw analysisErrorWithCleanupDependencies(primary, cleanup, operation); } if (cause instanceof ArtifactFileCancelled) { throw archiveCancellation(cause.fileCancellation.reason, options, { diff --git a/src/android/JadxJavaProbe.ts b/src/android/JadxJavaProbe.ts index 8431cd6b46f..3926baa9a67 100644 --- a/src/android/JadxJavaProbe.ts +++ b/src/android/JadxJavaProbe.ts @@ -13,11 +13,11 @@ import { carriedReason, } from "../domain/analysisErrorCore.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { InternalInvariantError, invariantViolation, } from "../domain/internalInvariant.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js"; import { err, ok, type Result } from "../domain/result.js"; import { @@ -270,11 +270,11 @@ export const inspectJadxJava = async ( primary = projectRefusal(failure, operation, cause, output); } for (const cleanup of cleanups) - primary = analysisErrorWithCleanupFailure( + primary = analysisErrorWithCleanupDependencies( primary, cleanup, operation, - ).bindCleanupDependencies([primary, cleanup]); + ); throw bindProcessInspectionCancellations(cause, primary, operation); } }); diff --git a/src/android/JadxProvider.ts b/src/android/JadxProvider.ts index c8eddfccf17..10f5cad18b7 100644 --- a/src/android/JadxProvider.ts +++ b/src/android/JadxProvider.ts @@ -23,7 +23,10 @@ import { OwnerCancellation, } from "../domain/analysisErrorCore.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { + analysisErrorWithCleanupDependencies, + analysisErrorWithCleanupFailure, +} from "../domain/analysisErrorCleanup.js"; import type { AndroidRequest } from "../domain/android/androidAnalysis.js"; import type { AndroidMappingSource } from "../domain/android/androidMapping.js"; import { @@ -371,11 +374,11 @@ export class JadxProvider implements AndroidAnalysisPort { const outcome: Outcome = !retired.ok && !cleanup.ok ? err( - analysisErrorWithCleanupFailure( + analysisErrorWithCleanupDependencies( retired.error, cleanup.error, request.operation, - ).bindCleanupDependencies([retired.error, cleanup.error]), + ), ) : !retired.ok ? retired @@ -417,11 +420,11 @@ export class JadxProvider implements AndroidAnalysisPort { "close_binary", ); if (!retired.ok) - throw analysisErrorWithCleanupFailure( + throw analysisErrorWithCleanupDependencies( retired.error, cleanup, "close_binary", - ).bindCleanupDependencies([retired.error, cleanup]); + ); throw cleanup; } if (!retired.ok) throw retired.error; diff --git a/src/apktool/ApktoolCommandCleanup.ts b/src/apktool/ApktoolCommandCleanup.ts index f7e379da6a1..3bff4986cc8 100644 --- a/src/apktool/ApktoolCommandCleanup.ts +++ b/src/apktool/ApktoolCommandCleanup.ts @@ -12,7 +12,7 @@ import { } from "../artifacts/ArtifactResourceScope.js"; import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.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 { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js"; import { processInspectionCleanupFailures } from "../process/ProcessInspectionCleanup.js"; @@ -142,11 +142,7 @@ export class ApktoolCommandCleanup { this.#bind(cleanup, retained); return bindProcessInspectionCancellations( cause, - analysisErrorWithCleanupFailure( - primary, - cleanup, - operation, - ).bindCleanupDependencies([primary, cleanup]), + analysisErrorWithCleanupDependencies(primary, cleanup, operation), operation, ); } diff --git a/src/apktool/ApktoolCommandRecovery.test.ts b/src/apktool/ApktoolCommandRecovery.test.ts index 6707b1657ed..eae9a15da32 100644 --- a/src/apktool/ApktoolCommandRecovery.test.ts +++ b/src/apktool/ApktoolCommandRecovery.test.ts @@ -15,6 +15,7 @@ import { } from "../process/OwnedCommand.js"; import type { ProviderProcessSupervisor } from "../process/ProviderProcess.js"; import { ApktoolProvider } from "./ApktoolProvider.js"; +import { releaseOwnedCleanup } from "../../tests/support/cleanupRelease.js"; vi.mock("../process/OwnedCommand.js", async (original) => ({ ...(await original()), @@ -61,7 +62,7 @@ it.each(["process", "helper"] as const)( ); const helperClose = vi.fn(async () => { if (denied) throw helperCleanup; - helperCleanup.resolveCleanup(); + releaseOwnedCleanup(helperCleanup); }); const compilerOutput = { stdout: "authored compiler stdout", @@ -276,7 +277,7 @@ it("retries failed command peers without repeating successful helper cleanup", a const commands = new ApktoolCommandCleanup(); const helper = new ProviderCleanupError("process-ownership", ["helper"], {}); const close = vi.fn(async () => { - helper.resolveCleanup(); + releaseOwnedCleanup(helper); }); let denied = true; const stop = vi.fn(async () => @@ -329,7 +330,7 @@ it("joins preparation during close and retains a late helper handoff", async () {}, ); const close = vi.fn(async () => { - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); }); vi.mocked(prepareOwnedCommand).mockImplementationOnce(async () => { entered.resolve(); diff --git a/src/apktool/ApktoolProvider.ts b/src/apktool/ApktoolProvider.ts index f1d2e1f09cd..d95705407ed 100644 --- a/src/apktool/ApktoolProvider.ts +++ b/src/apktool/ApktoolProvider.ts @@ -56,7 +56,7 @@ import { OwnerCancellation, carriedReason, } from "../domain/analysisErrorCore.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { fixedAllowanceOptions } from "../domain/fixedAllowanceRemediation.js"; import { err, ok, type Result } from "../domain/result.js"; import { finalizedResult, runOwned } from "../providers/runOwned.js"; @@ -528,11 +528,7 @@ export class ApktoolProvider { if (first === undefined) return; throw failures.reduce( (primary, cleanup) => - analysisErrorWithCleanupFailure( - primary, - cleanup, - "close", - ).bindCleanupDependencies([primary, cleanup]), + analysisErrorWithCleanupDependencies(primary, cleanup, "close"), first, ); } @@ -740,11 +736,7 @@ export class ApktoolProvider { physical === cause && cause instanceof AnalysisError ? cause : failure.cleanupIncomplete - ? analysisErrorWithCleanupFailure( - primary, - failure, - operation, - ).bindCleanupDependencies([primary, failure]) + ? analysisErrorWithCleanupDependencies(primary, failure, operation) : primary; if ( completedDecode !== undefined && diff --git a/src/application/AnalysisContextQueries.ts b/src/application/AnalysisContextQueries.ts index db07c2311b0..183a759e7e9 100644 --- a/src/application/AnalysisContextQueries.ts +++ b/src/application/AnalysisContextQueries.ts @@ -19,7 +19,7 @@ import { unretainedEvidenceCandidates, type AnalysisErrorProjection, } from "../domain/analysisErrorProjection.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { analysisErrorWithCancellation } from "../domain/analysisErrorCancellation.js"; import { EvidenceIntegrityError } from "../domain/evidenceErrors.js"; import type { JsonValue } from "../domain/jsonValue.js"; @@ -372,11 +372,11 @@ const contextFailure = ( combined = analysisErrorWithCancellation(combined, failure); if (failure.cleanupIncomplete) { const previous = combined; - combined = analysisErrorWithCleanupFailure( + combined = analysisErrorWithCleanupDependencies( previous, failure, "inspect_address_context", - ).bindCleanupDependencies([previous, failure]); + ); } else if ( !(failure instanceof AnalysisCancelledError) && (isRequestLevelFailure(failure) || diff --git a/src/application/BrowserObservationService.test.ts b/src/application/BrowserObservationService.test.ts index ad801c782f3..794451d65f7 100644 --- a/src/application/BrowserObservationService.test.ts +++ b/src/application/BrowserObservationService.test.ts @@ -25,6 +25,7 @@ import { passiveNetworkCapture } from "../../tests/fixtures/passiveNetworkCaptur import { analyzeWebBundleFixture } from "../../tests/support/browser/analyzeWebBundleFixture.js"; import { analyzeWebBundleInputSchema } from "../domain/webBundleAnalysis.js"; import { inspectWebPageInputSchema } from "../domain/browserObservation.js"; +import { releaseOwnedCleanup } from "../../tests/support/cleanupRelease.js"; const input = { cdp_endpoint: { @@ -182,7 +183,7 @@ it.each([true, false])( }); if (wrapperRetainsFacts) expect(failure.partialObservation).toBe(primary.partialObservation); - failure.resolveCleanup(); + releaseOwnedCleanup(failure); expect(resolvedAnalysisError(failure)).toBe(primary); expect( parseEvidence( diff --git a/src/application/BrowserScenarioCaptureService.test.ts b/src/application/BrowserScenarioCaptureService.test.ts index cca3b8e405d..c8ad09a1006 100644 --- a/src/application/BrowserScenarioCaptureService.test.ts +++ b/src/application/BrowserScenarioCaptureService.test.ts @@ -23,6 +23,7 @@ import { expectKeptPartial, expectOwnerError, } from "../../tests/fixtures/ownerObservationExpectation.js"; +import { releaseOwnedCleanup } from "../../tests/support/cleanupRelease.js"; const scenario = browserScenarioInputSchema.parse({ browser: { mode: "launch", executable_path: "/fixture/chrome" }, @@ -110,7 +111,7 @@ it.each([false, true])( const result = await runScenario(failure, scenarioIdentity); if (result.ok) throw new Error("Expected cleanup failure"); expect(result.error).toBe(failure); - failure.resolveCleanup(); + releaseOwnedCleanup(failure); expect(resolvedAnalysisError(failure)).toBe(primary); expect(parseEvidence(primary.partialObservation)).toMatchObject({ operation: "capture_browser_scenario", @@ -327,7 +328,7 @@ it.each([false, true])( : parseEvidence(primary.partialObservation); if (cleanup) { expect(result).toMatchObject({ ok: false }); - failure.resolveCleanup(); + releaseOwnedCleanup(failure); expect(resolvedAnalysisError(failure)).toBe(primary); } else expect(result.ok).toBe(true); expect(evidence.raw_result).toEqual(source); diff --git a/src/application/Doctor.ts b/src/application/Doctor.ts index e77dbc5ea32..3064c42080a 100644 --- a/src/application/Doctor.ts +++ b/src/application/Doctor.ts @@ -7,7 +7,7 @@ import { OwnerCancellation, } from "../domain/analysisErrorCore.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { bindArtifactFileCleanup } from "../artifacts/ArtifactFileOperation.js"; import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js"; import { AnalysisCleanupLease } from "../artifacts/AnalysisCleanupLease.js"; @@ -266,11 +266,7 @@ export const runDoctorOwned = async ( { operation: "doctor" }, ) : cleanup; - throw analysisErrorWithCleanupFailure( - cause, - cleanupError, - "doctor", - ).bindCleanupDependencies([cause, cleanupError]); + throw analysisErrorWithCleanupDependencies(cause, cleanupError, "doctor"); } if (cleanup !== undefined) throw new AggregateError( diff --git a/src/application/EvidenceBundleFiles.ts b/src/application/EvidenceBundleFiles.ts index 995c4688851..b6116d55659 100644 --- a/src/application/EvidenceBundleFiles.ts +++ b/src/application/EvidenceBundleFiles.ts @@ -1,7 +1,7 @@ import type { AnalysisError } from "../domain/analysisErrorBase.js"; import type { EvidenceBundleExportReceipt } from "../domain/investigationLifecycle.js"; import { jsonValueValidationIssue } from "../domain/jsonValue.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { requireAuthenticationHeadroom } from "./JsonAuthenticationHeadroom.js"; import { absoluteCallerPath } from "../filesystem/callerPath.js"; import { resemblesAnalysisSnapshot } from "../domain/analysisSnapshot.js"; @@ -87,11 +87,11 @@ export const readComparisonEvidenceBundles = async ( if (!left.ok) { if (!right.ok && right.error.cleanupIncomplete) return err( - analysisErrorWithCleanupFailure( + analysisErrorWithCleanupDependencies( left.error, right.error, operation, - ).bindCleanupDependencies([left.error, right.error]), + ), ); return left; } diff --git a/src/application/ProviderOperationExecution.test.ts b/src/application/ProviderOperationExecution.test.ts index f3a36e1b5ac..d0b8fd47370 100644 --- a/src/application/ProviderOperationExecution.test.ts +++ b/src/application/ProviderOperationExecution.test.ts @@ -13,6 +13,7 @@ import { executeProviderOperation, keepIncompleteObservation, } from "./ProviderOperationExecution.js"; +import { releaseOwnedCleanup } from "../../tests/support/cleanupRelease.js"; it("projects request-schema issues without exposing the request envelope", async () => { const execute = vi.fn(); @@ -133,7 +134,7 @@ it("clears a non-JSON partial from the cleanup primary projection returns after expect(primary.secondaryFailures[0]).toBeInstanceOf(AnalysisOutputError); expect(projectAnalysisError(composed).code).toBe("cleanup_incomplete"); - composed.resolveCleanup(); + releaseOwnedCleanup(composed); expect(projectAnalysisError(composed)).toMatchObject({ code: "cancelled", category: "cancelled", diff --git a/src/application/Setup.ts b/src/application/Setup.ts index 830d7a5ff5b..94ab6abcb6e 100644 --- a/src/application/Setup.ts +++ b/src/application/Setup.ts @@ -32,7 +32,7 @@ import { type AnalysisCleanupObservation, } from "../domain/analysisErrorBase.js"; import { setupCleanupError, setupCleanupReason } from "./SetupCleanupOwner.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { AnalysisCancelledError, cancelledBy, @@ -128,11 +128,11 @@ export const runSetup = async ( if (threw) { if (cleanup === undefined) throw primaryFailure; if (primaryFailure instanceof AnalysisError) - throw analysisErrorWithCleanupFailure( + throw analysisErrorWithCleanupDependencies( primaryFailure, cleanup, "setup", - ).bindCleanupDependencies([primaryFailure, cleanup]); + ); throw new AggregateError( [primaryFailure, cleanup], "Setup and resource cleanup failed.", @@ -166,11 +166,7 @@ export const runSetup = async ( diagnostics: { setup_result: jsonValueSchema.parse(result) }, }); if (cleanup !== undefined) - throw analysisErrorWithCleanupFailure( - cancelled, - cleanup, - "setup", - ).bindCleanupDependencies([cancelled, cleanup]); + throw analysisErrorWithCleanupDependencies(cancelled, cleanup, "setup"); throw cancelled; } if (cleanup === undefined) return result; diff --git a/src/application/WebNetworkCaptureService.ts b/src/application/WebNetworkCaptureService.ts index 1b4745d7ce3..b772c8eb25f 100644 --- a/src/application/WebNetworkCaptureService.ts +++ b/src/application/WebNetworkCaptureService.ts @@ -26,7 +26,7 @@ import { type WebNetworkCapture, } from "../domain/webNetworkCapture.js"; import { completeProviderEvidence } from "./ProviderOperationExecution.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; const OPERATION = "inspect_web_network_capture"; @@ -115,11 +115,11 @@ export class WebNetworkCaptureService { partialFailure.retainSecondaryFailure(loaded.error); return failure( loaded.error.cleanupIncomplete - ? analysisErrorWithCleanupFailure( + ? analysisErrorWithCleanupDependencies( partialFailure, loaded.error, OPERATION, - ).bindCleanupDependencies([partialFailure, loaded.error]) + ) : partialFailure, ); } diff --git a/src/application/binary/AnalysisProviderRegistry.test.ts b/src/application/binary/AnalysisProviderRegistry.test.ts index 16ea27941d9..23022c0bead 100644 --- a/src/application/binary/AnalysisProviderRegistry.test.ts +++ b/src/application/binary/AnalysisProviderRegistry.test.ts @@ -26,6 +26,7 @@ import { ProviderSelectionError } from "../../domain/providerSelectionError.js"; import { LinuxOwnedProcessPrerequisiteError } from "../../process/ProcessOwnershipObservation.js"; import { projectAnalysisError } from "../../domain/analysisErrorProjection.js"; import { err, ok } from "../../domain/result.js"; +import { releaseOwnedCleanup } from "../../../tests/support/cleanupRelease.js"; const DATABASE_TARGET: BinaryTarget = { path: "/tmp/fixture.hop", @@ -1266,7 +1267,7 @@ describe("profile resolution terminal facts", () => { }, closeOwnedResources: async () => { if (!allowClose) return err(primary); - primary.resolveCleanup(); + releaseOwnedCleanup(primary); return ok(null); }, }, @@ -1327,7 +1328,7 @@ describe("automatic profile cleanup ownership", () => { }, closeOwnedResources: async () => { if (!released.has(id)) return err(failures[id]); - failures[id].resolveCleanup(); + releaseOwnedCleanup(failures[id]); return ok(null); }, }; @@ -1544,7 +1545,7 @@ it.each(["alpha", "beta"])( ...candidate(id).provider, closeOwnedResources: async () => { if (!released) return err(id === unknownOwner ? unknown : tracked); - if (id !== unknownOwner) tracked.resolveCleanup(); + if (id !== unknownOwner) releaseOwnedCleanup(tracked); return ok(null); }, })), @@ -1664,7 +1665,7 @@ it("joins every candidate and retains physical failure with exact mixed cleanup }, closeOwnedResources: async () => { releases++; - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); return ok(null); }, }, diff --git a/src/application/binary/BinarySessionBundleResources.test.ts b/src/application/binary/BinarySessionBundleResources.test.ts index 9e21bb8c803..da7c4e05dc8 100644 --- a/src/application/binary/BinarySessionBundleResources.test.ts +++ b/src/application/binary/BinarySessionBundleResources.test.ts @@ -26,6 +26,7 @@ import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js"; import { createEvidence } from "../../domain/evidence.js"; import { createAnalysisProfile } from "../../domain/analysisProfile.js"; import { createTestProviderRouter } from "../../../tests/fixtures/binarySession.js"; +import { releaseOwnedCleanup } from "../../../tests/support/cleanupRelease.js"; const identity: ProviderIdentity = { id: "bundle-resource-fixture", @@ -368,7 +369,7 @@ it.each([false, true])( await closeGate; } if (oldCloseAttempts < 3) return err(cleanupFailure); - if (liveCleanup) cleanupFailure.resolveCleanup(); + if (liveCleanup) releaseOwnedCleanup(cleanupFailure); return { ok: true, value: null }; }, }, @@ -903,7 +904,7 @@ it("tracks independent pending resource owners after a failed session replacemen execute: async () => ok(createAnalysisExecution(null, identity)), close: async () => { if (!released[index]) return err(failure); - failure.resolveCleanup(); + releaseOwnedCleanup(failure); return ok(null); }, }, @@ -968,7 +969,7 @@ it.each([false, true])( close: async () => { attempts += 1; if (attempts === 1) return err(cleanup); - if (liveCleanup) cleanup.resolveCleanup(); + if (liveCleanup) releaseOwnedCleanup(cleanup); return ok(null); }, })), @@ -1027,7 +1028,7 @@ it.each([0, 1])( return err( owner === unknownOwner ? unknownFailure : ownedFailure, ); - if (owner !== unknownOwner) ownedFailure.resolveCleanup(); + if (owner !== unknownOwner) releaseOwnedCleanup(ownedFailure); return ok(null); }, }, @@ -1066,7 +1067,7 @@ it.each([ const closeOwner = async (owner: "client" | "files") => { if (!failCleanup) return ok(null); if (!released) return err(owner === unknownOwner ? unknown : tracked); - if (owner !== unknownOwner) tracked.resolveCleanup(); + if (owner !== unknownOwner) releaseOwnedCleanup(tracked); return ok(null); }; const client: AnalysisClient = { @@ -1138,7 +1139,7 @@ it.each(["health", "cancellation"] as const)( }, close: async () => { if (++closeAttempts === 1) return err(cleanup); - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); return ok(null); }, }, diff --git a/src/application/binary/BinarySessionRestoration.test.ts b/src/application/binary/BinarySessionRestoration.test.ts index a9030a91cf9..4e6074fb7e4 100644 --- a/src/application/binary/BinarySessionRestoration.test.ts +++ b/src/application/binary/BinarySessionRestoration.test.ts @@ -20,6 +20,7 @@ import { SessionProviderRouter, type SessionProviderRoute, } from "./SessionProviderRouter.js"; +import { releaseOwnedCleanup } from "../../../tests/support/cleanupRelease.js"; it.each([false, true])( "refreshes state published by close on alias switch (incoming fails: %s)", @@ -225,7 +226,7 @@ it.each([ restorationCloseCalls += 1; if (cleanupFails && restorationCloseCalls === 1) return err(cleanupFailure); - cleanupFailure.resolveCleanup(); + releaseOwnedCleanup(cleanupFailure); return ok(null); }, }; diff --git a/src/application/binary/BundleResourceSession.test.ts b/src/application/binary/BundleResourceSession.test.ts index 70f2b338a5b..aaa356a8fad 100644 --- a/src/application/binary/BundleResourceSession.test.ts +++ b/src/application/binary/BundleResourceSession.test.ts @@ -9,6 +9,7 @@ import { import { AnalysisInputError } from "../../domain/analysisErrorCore.js"; import { ProviderCleanupError } from "../../domain/providerCleanupError.js"; import { err, ok } from "../../domain/result.js"; +import { releaseOwnedCleanup } from "../../../tests/support/cleanupRelease.js"; const identity: ProviderIdentity = { id: "bundle-resource-close-fixture", @@ -133,7 +134,7 @@ it("updates retained cleanup facts as the two child owners release independently execute: async () => ok(createAnalysisExecution(null, identity)), close: async () => { if (!released()) return err(failure); - failure.resolveCleanup(); + releaseOwnedCleanup(failure); return ok(null); }, }); @@ -173,6 +174,6 @@ it("keeps cleanup unknown when a child close failure has no cleanup lifecycle", client(new AnalysisInputError("close_binary")), ).close(); if (closed.ok) throw new Error("Expected child close failures"); - owned.resolveCleanup(); + releaseOwnedCleanup(owned); expect(closed.error.cleanupIncomplete).toBe(true); }); diff --git a/src/application/binary/DeferredAnalysisClient.test.ts b/src/application/binary/DeferredAnalysisClient.test.ts index 2a94e8445ea..b4d911f836b 100644 --- a/src/application/binary/DeferredAnalysisClient.test.ts +++ b/src/application/binary/DeferredAnalysisClient.test.ts @@ -17,6 +17,7 @@ import { ProviderCleanupError } from "../../domain/providerCleanupError.js"; import { projectAnalysisError } from "../../domain/analysisErrorProjection.js"; import { resolvedAnalysisError } from "../../domain/analysisErrorBase.js"; import { err, ok } from "../../domain/result.js"; +import { releaseOwnedCleanup } from "../../../tests/support/cleanupRelease.js"; const identity = { id: "controlled", name: "Controlled client", version: "1" }; @@ -521,7 +522,7 @@ it("retains a failed prerequisite owner without creating a native client", async close: async () => { releases++; if (denied) throw cleanup; - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); }, }, "controlled prerequisite", @@ -567,7 +568,7 @@ it("retries only unresolved prerequisite and native owners across mixed cleanup close: async () => { prerequisites++; if (denyPrerequisite) throw prerequisiteFailure; - prerequisiteFailure.resolveCleanup(); + releaseOwnedCleanup(prerequisiteFailure); }, }, "mixed prerequisite", diff --git a/src/application/binaryDiagnostics/ByteEntropyService.ts b/src/application/binaryDiagnostics/ByteEntropyService.ts index 4db145c6c81..359f1daf31e 100644 --- a/src/application/binaryDiagnostics/ByteEntropyService.ts +++ b/src/application/binaryDiagnostics/ByteEntropyService.ts @@ -38,7 +38,7 @@ import { artifactFileCancellationCause, artifactSelectedPathErrno, } from "../../artifacts/ArtifactFileOperation.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js"; import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js"; import { sameRegularFileState } from "../../filesystem/RegularFile.js"; import { completeProviderEvidence } from "../ProviderOperationExecution.js"; @@ -374,11 +374,7 @@ export class ByteEntropyService { if (outcome.kind === "failed") { const primary = readFailure(outcome.cause); return err( - analysisErrorWithCleanupFailure( - primary, - cleanup, - OPERATION, - ).bindCleanupDependencies([primary, cleanup]), + analysisErrorWithCleanupDependencies(primary, cleanup, OPERATION), ); } return err(cleanup); diff --git a/src/application/desktop/DesktopApplicationState.ts b/src/application/desktop/DesktopApplicationState.ts index fa7c00abb08..5eca62043c1 100644 --- a/src/application/desktop/DesktopApplicationState.ts +++ b/src/application/desktop/DesktopApplicationState.ts @@ -16,7 +16,7 @@ import { isAborted, } from "../../domain/analysisErrorCore.js"; import { analysisErrorWithCancellation } from "../../domain/analysisErrorCancellation.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js"; import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js"; import { desktopApplicationCaptureSchema, @@ -164,11 +164,7 @@ export const readDesktopCapture = async ( ); if (!outcome.ok && signal?.aborted) analysisErrorWithCancellation(primary, cancelledBy(OPERATION, signal)); - throw analysisErrorWithCleanupFailure( - primary, - cleanup, - OPERATION, - ).bindCleanupDependencies([primary, cleanup]); + throw analysisErrorWithCleanupDependencies(primary, cleanup, OPERATION); } if (!outcome.ok) { if (!signal?.aborted) throw outcome.error; diff --git a/src/application/desktop/DesktopBuildComputers.ts b/src/application/desktop/DesktopBuildComputers.ts index 4fa33da7a6c..9091a8dc80e 100644 --- a/src/application/desktop/DesktopBuildComputers.ts +++ b/src/application/desktop/DesktopBuildComputers.ts @@ -23,6 +23,7 @@ import { import type { JsonValue } from "../../domain/jsonValue.js"; import { ProviderAdapterError } from "../../domain/providerAdapterError.js"; import { ProviderCleanupError } from "../../domain/providerCleanupError.js"; +import { AnalysisCleanupRelease } from "../../domain/analysisCleanupRelease.js"; import { err, ok, type Result } from "../../domain/result.js"; import { AgentEnvComputer, @@ -108,7 +109,8 @@ interface HeldComputer { readonly turns: DesktopBuildTurns; readonly cleanup: { resources: readonly string[]; - errors: Set>; + /** Confirmed by a verified teardown; every bound teardown failure reads it. */ + readonly release: AnalysisCleanupRelease; }; closing: boolean; } @@ -120,9 +122,7 @@ const bindCleanupFailure = (held: HeldComputer, error: AnalysisError): void => { return held.cleanup.resources; }, }); - for (const reference of held.cleanup.errors) - if (reference.deref() === undefined) held.cleanup.errors.delete(reference); - held.cleanup.errors.add(new WeakRef(error)); + held.cleanup.release.bind(error); }; /** What the build step tools work on: a live computer, its capture, its witness and the turns they take. */ @@ -317,7 +317,7 @@ const liveComputer = ( turns, }, turns, - cleanup: { resources: [], errors: new Set() }, + cleanup: { resources: [], release: new AnalysisCleanupRelease() }, closing: false, }; }; @@ -562,7 +562,7 @@ export class DesktopBuildComputers { actions: new BuildComputerActionLog(this.#secrets.redact), steps: undefined, turns: new DesktopBuildTurns(), - cleanup: { resources: [], errors: new Set() }, + cleanup: { resources: [], release: new AnalysisCleanupRelease() }, closing: true, }); const release = await this.#retire(id); @@ -719,9 +719,7 @@ export class DesktopBuildComputers { const release = await held.turns.close(() => this.#retire(id)); held.cleanup.resources = release.verified ? [] : release.resources; if (release.verified) { - for (const reference of held.cleanup.errors) - reference.deref()?.resolveCleanup(); - held.cleanup.errors.clear(); + held.cleanup.release.confirm(); return ok({ computer_id: id, teardown: release.teardown }); } const failure = new ProviderCleanupError( diff --git a/src/application/desktop/DesktopCaptureFailure.ts b/src/application/desktop/DesktopCaptureFailure.ts index e2482193735..0c46fbbfaa6 100644 --- a/src/application/desktop/DesktopCaptureFailure.ts +++ b/src/application/desktop/DesktopCaptureFailure.ts @@ -8,7 +8,7 @@ import { ArtifactResourceScope, } from "../../artifacts/ArtifactResourceScope.js"; import { AnalysisError } from "../../domain/analysisErrorBase.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js"; import { ProviderAdapterError, type ProviderAdapterErrorOptions, @@ -230,11 +230,7 @@ export const failedCaptureError = ( diagnostics: { phase: "desktop_capture" }, })); return primary instanceof AnalysisError && primary.cleanupIncomplete - ? analysisErrorWithCleanupFailure( - primary, - failure, - DESKTOP_OPERATION, - ).bindCleanupDependencies([primary, failure]) + ? analysisErrorWithCleanupDependencies(primary, failure, DESKTOP_OPERATION) : failure; }; diff --git a/src/application/desktop/DesktopRemoteTaskReaders.ts b/src/application/desktop/DesktopRemoteTaskReaders.ts index 7c1e63dc0dd..15745adf812 100644 --- a/src/application/desktop/DesktopRemoteTaskReaders.ts +++ b/src/application/desktop/DesktopRemoteTaskReaders.ts @@ -17,6 +17,7 @@ import { type ReaderLease, } from "../../domain/desktop/appTaskReaders.js"; import { ProviderCleanupError } from "../../domain/providerCleanupError.js"; +import { AnalysisCleanupRelease } from "../../domain/analysisCleanupRelease.js"; import { ProviderAdapterError } from "../../domain/providerAdapterError.js"; import { AGENTENV_PROVIDER, @@ -52,7 +53,10 @@ interface PendingReader { /** Owns remote reader folders and joins interrupted commands before removing them. */ export class DesktopRemoteTaskReaders { readonly #pending = new Set(); + /** Failures reported for the current pending readers, kept to retain late reader facts. */ readonly #failures = new Set>(); + /** Confirmed once the readers pending when it was taken are all removed. */ + #release = new AnalysisCleanupRelease(); constructor(private readonly exec: Exec) {} @@ -243,7 +247,8 @@ export class DesktopRemoteTaskReaders { reason: errors.join("; "), resources: this.cleanupResources, }; - for (const failure of this.#failures) failure.deref()?.resolveCleanup(); + this.#release.confirm(); + this.#release = new AnalysisCleanupRelease(); this.#failures.clear(); return { verified: true, teardown: "agentenv" }; } @@ -305,7 +310,7 @@ export class DesktopRemoteTaskReaders { "Retry the check or close the build computer to retry cleanup. If the command outcome is unknown, inspect the reported computer and confirm the reader has stopped before removing its folder.", }, ); - failure.bindCleanupResourceOwner(this); + this.#release.bind(failure.bindCleanupResourceOwner(this)); this.#failures.add(new WeakRef(failure)); return failure; } diff --git a/src/application/desktop/DesktopTaskReaderCleanup.ts b/src/application/desktop/DesktopTaskReaderCleanup.ts index 7ad58c9d858..189a9a8d24f 100644 --- a/src/application/desktop/DesktopTaskReaderCleanup.ts +++ b/src/application/desktop/DesktopTaskReaderCleanup.ts @@ -2,6 +2,7 @@ import { cancelledBy, carriedReason } from "../../domain/analysisErrorCore.js"; import { AnalysisError } from "../../domain/analysisErrorBase.js"; import { ProviderAdapterError } from "../../domain/providerAdapterError.js"; import { ProviderCleanupError } from "../../domain/providerCleanupError.js"; +import { AnalysisCleanupRelease } from "../../domain/analysisCleanupRelease.js"; import type { TaskFileView } from "../../domain/desktop/appTaskChecks.js"; import { OwnedCommandFailure } from "../../process/OwnedCommand.js"; import { RetainedCommandCleanup } from "../../process/RetainedCommandCleanup.js"; @@ -63,11 +64,12 @@ export const readerFailure = ( /** Own an unconfirmed reader process and its working folder across requests. */ class ReaderCleanup implements RetainedWorkerCleanup { #retry: Promise | undefined; + readonly #released = new AnalysisCleanupRelease(); constructor( readonly owner: RetainedCommandCleanup, readonly failure: ProviderCleanupError, ) { - failure.bindCleanupResourceOwner(owner); + this.#released.bind(failure.bindCleanupResourceOwner(owner)); } retryRetainedCleanup(): Promise { @@ -86,7 +88,7 @@ class ReaderCleanup implements RetainedWorkerCleanup { try { await this.owner.close(); processWorkerCleanup.delete(this); - this.failure.resolveCleanup(); + this.#released.confirm(); } catch (cause: unknown) { this.failure.retainDiagnostics({ retry_failure: cause instanceof Error ? cause.message : String(cause), diff --git a/src/application/environment/environmentExport.ts b/src/application/environment/environmentExport.ts index 91504108a28..3df8b0cd470 100644 --- a/src/application/environment/environmentExport.ts +++ b/src/application/environment/environmentExport.ts @@ -2,7 +2,7 @@ import { isAbsolute } from "node:path"; import { getHeapStatistics } from "node:v8"; import { AnalysisError } from "../../domain/analysisErrorBase.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js"; import { AnalysisAccessDeniedError, AnalysisInputError, @@ -331,11 +331,7 @@ export const readEnvironmentExportFile = async ( cause.outcome.kind === "failed" ? cause.outcome.cause : undefined; return err( primary instanceof AnalysisError - ? analysisErrorWithCleanupFailure( - primary, - cleanup, - operation, - ).bindCleanupDependencies([primary, cleanup]) + ? analysisErrorWithCleanupDependencies(primary, cleanup, operation) : cleanup, ); } diff --git a/src/application/frida/FridaInstrumentationService.test.ts b/src/application/frida/FridaInstrumentationService.test.ts index f8b53d213f7..ac77c4ec385 100644 --- a/src/application/frida/FridaInstrumentationService.test.ts +++ b/src/application/frida/FridaInstrumentationService.test.ts @@ -15,6 +15,7 @@ import { import { ProviderAdapterError } from "../../domain/providerAdapterError.js"; import type { Evidence } from "../../domain/evidence.js"; import { ok } from "../../domain/result.js"; +import { releaseOwnedCleanup } from "../../../tests/support/cleanupRelease.js"; const createSession = () => ({ sessionId: "00000000-0000-4000-8000-000000000001", @@ -993,7 +994,7 @@ it.each([false, true])( // The parent provider owns the script and confirms its release. if (released) { scriptOwner.cleanupResources = []; - failure.resolveCleanup(); + releaseOwnedCleanup(failure); } return { ok: true, value: { targetResumeObserved: false } }; }, diff --git a/src/application/frida/FridaInstrumentationService.ts b/src/application/frida/FridaInstrumentationService.ts index 24ac972d3b7..52ec207943a 100644 --- a/src/application/frida/FridaInstrumentationService.ts +++ b/src/application/frida/FridaInstrumentationService.ts @@ -7,7 +7,7 @@ import { resolvedAnalysisError, 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 { AnalysisAccessDeniedError, @@ -423,11 +423,11 @@ export class FridaInstrumentationService { const closed = await this.#provider.closeSession(sessionId); const failure = closed.ok ? resolvedAnalysisError(primary) - : analysisErrorWithCleanupFailure( + : analysisErrorWithCleanupDependencies( primary, closed.error, "instrument_with_frida", - ).bindCleanupDependencies([primary, closed.error]); + ); return err( signal?.aborted ? analysisErrorWithCancellation( diff --git a/src/application/il2cpp/Il2cppMetadataService.test.ts b/src/application/il2cpp/Il2cppMetadataService.test.ts index 83dcffcd86c..444a8b3d0f7 100644 --- a/src/application/il2cpp/Il2cppMetadataService.test.ts +++ b/src/application/il2cpp/Il2cppMetadataService.test.ts @@ -16,6 +16,7 @@ import type { Il2cppSeedWriterPort } from "./Il2cppSeedWriterPort.js"; import { toolContract } from "../../contracts/toolContracts.js"; import { z } from "zod"; import { Ajv2020 } from "ajv/dist/2020.js"; +import { releaseOwnedCleanup } from "../../../tests/support/cleanupRelease.js"; const identity = { id: "fixture-il2cpp", @@ -290,9 +291,9 @@ it("closes both ports and keeps combined cleanup incomplete until both owners re "metadata-reader", "seed-output", ]); - output.resolveCleanup(); + releaseOwnedCleanup(output); expect(failure.cleanupIncomplete).toBe(true); - metadata.resolveCleanup(); + releaseOwnedCleanup(metadata); expect(failure.cleanupIncomplete).toBe(false); }); it.each([ diff --git a/src/application/il2cpp/Il2cppMetadataService.ts b/src/application/il2cpp/Il2cppMetadataService.ts index d1683cad9e4..00e745a1552 100644 --- a/src/application/il2cpp/Il2cppMetadataService.ts +++ b/src/application/il2cpp/Il2cppMetadataService.ts @@ -1,5 +1,5 @@ import { parseAnalysisInput } from "../AnalysisInput.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js"; import { ProviderCleanupError } from "../../domain/providerCleanupError.js"; import type { Il2cppSeedOutput, @@ -66,11 +66,7 @@ export class Il2cppMetadataService { failure = failure === undefined ? next - : analysisErrorWithCleanupFailure( - failure, - next, - OPERATION, - ).bindCleanupDependencies([failure, next]); + : analysisErrorWithCleanupDependencies(failure, next, OPERATION); } } if (failure !== undefined) throw failure; diff --git a/src/application/javascript/JavaScriptArtifactReconstruction.ts b/src/application/javascript/JavaScriptArtifactReconstruction.ts index ba833987be2..b084db4f44f 100644 --- a/src/application/javascript/JavaScriptArtifactReconstruction.ts +++ b/src/application/javascript/JavaScriptArtifactReconstruction.ts @@ -31,7 +31,7 @@ import { type ElectronBoundarySummary, } from "../../domain/javascript/javascriptApplicationAnalysis.js"; import { AnalysisError } from "../../domain/analysisErrorBase.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js"; import { ArtifactOperationError } from "../../domain/artifactOperationError.js"; import type { ArtifactInventorySnapshot } from "../../domain/artifactInventorySnapshot.js"; import type { ArtifactInventoryPartialObservation } from "../../domain/artifactPartialObservation.js"; @@ -424,11 +424,11 @@ export const reconstructJavaScriptArtifact = async ( ? interruption : interruption === null ? cleanupFailure - : analysisErrorWithCleanupFailure( + : analysisErrorWithCleanupDependencies( interruption, cleanupFailure, OPERATION, - ).bindCleanupDependencies([interruption, cleanupFailure]); + ); if (failure !== null) { const { electron_summary: summary, ...application } = completed; const partial = await completeJavaScriptAnalysisSteps( diff --git a/src/application/managed/ManagedMemberComparisonService.ts b/src/application/managed/ManagedMemberComparisonService.ts index 48c7651332a..f621af74bc2 100644 --- a/src/application/managed/ManagedMemberComparisonService.ts +++ b/src/application/managed/ManagedMemberComparisonService.ts @@ -17,7 +17,7 @@ import { AnalysisOutputError, } from "../../domain/analysisErrorCore.js"; import { AnalysisError } from "../../domain/analysisErrorBase.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js"; import { createEvidence, type Evidence } from "../../domain/evidence.js"; import { classifyBinaryTargetFilesystemFailure, @@ -132,11 +132,11 @@ export const compareManagedMemberPaths = async ( if (!leftTarget.ok) { if (!rightTarget.ok && rightTarget.error.cleanupIncomplete) return err( - analysisErrorWithCleanupFailure( + analysisErrorWithCleanupDependencies( leftTarget.error, rightTarget.error, operation, - ).bindCleanupDependencies([leftTarget.error, rightTarget.error]), + ), ); return leftTarget; } diff --git a/src/application/native/NativeUiActionTrace.ts b/src/application/native/NativeUiActionTrace.ts index 905686c0b89..e0c1174a1a5 100644 --- a/src/application/native/NativeUiActionTrace.ts +++ b/src/application/native/NativeUiActionTrace.ts @@ -1,4 +1,4 @@ -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js"; import { permitsCapabilityFallback } from "../CapabilityFallback.js"; import { stopsTraversal } from "../CallRelationshipTraversal.js"; import { z } from "zod"; @@ -63,11 +63,11 @@ export const traceNativeUiAction = async ( : uiExecution.error; if (secondary.cleanupIncomplete) return err( - analysisErrorWithCleanupFailure( + analysisErrorWithCleanupDependencies( primary, secondary, "trace_native_ui_action", - ).bindCleanupDependencies([primary, secondary]), + ), ); if (primary.cleanupIncomplete) primary.retainSecondaryFailure(secondary); return err(primary); diff --git a/src/application/process/ProcessCli.ts b/src/application/process/ProcessCli.ts index 4eaf875af07..5eecd16da19 100644 --- a/src/application/process/ProcessCli.ts +++ b/src/application/process/ProcessCli.ts @@ -1,6 +1,6 @@ import { AnalysisError } from "../../domain/analysisErrorBase.js"; import { err, ok, type Result } from "../../domain/result.js"; -import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../../domain/analysisErrorCleanup.js"; import { analysisErrorWithCancellation } from "../../domain/analysisErrorCancellation.js"; import { AnalysisCancelledError, @@ -175,11 +175,11 @@ export const captureProcessScenarioFile = async ( : original instanceof AnalysisError && cause instanceof AnalysisError ? original instanceof ProcessCaptureError ? original.withFinalization({ cleanupFailure: cause }) - : analysisErrorWithCleanupFailure( + : analysisErrorWithCleanupDependencies( original, cause, "capture_process_scenario", - ).bindCleanupDependencies([original, cause]) + ) : new AggregateError( [original, cause], "Process capture and cleanup failed", diff --git a/src/application/releaseExposure/ReleaseExposureService.test.ts b/src/application/releaseExposure/ReleaseExposureService.test.ts index 4a7b073e1b9..9df8ec3a2ea 100644 --- a/src/application/releaseExposure/ReleaseExposureService.test.ts +++ b/src/application/releaseExposure/ReleaseExposureService.test.ts @@ -28,6 +28,7 @@ import { err, ok, type Result } from "../../domain/result.js"; import type { ExecutionOptions } from "../AnalysisProvider.js"; import type { ReleaseExposurePort } from "./ReleaseExposurePort.js"; import { ReleaseExposureService } from "./ReleaseExposureService.js"; +import { releaseOwnedCleanup } from "../../../tests/support/cleanupRelease.js"; const SHA = "ab".repeat(32); @@ -2126,9 +2127,9 @@ describe("ReleaseExposureService cleanup", () => { "/work/app/desktop", "/work/app/go", ]); - first.resolveCleanup(); + releaseOwnedCleanup(first); expect(failure.cleanupIncomplete).toBe(true); - second.resolveCleanup(); + releaseOwnedCleanup(second); expect(failure.cleanupIncomplete).toBe(false); }); }); diff --git a/src/artifacts/AnalysisCleanupLease.test.ts b/src/artifacts/AnalysisCleanupLease.test.ts index 6bf04f690b0..5c83f17a813 100644 --- a/src/artifacts/AnalysisCleanupLease.test.ts +++ b/src/artifacts/AnalysisCleanupLease.test.ts @@ -1,4 +1,4 @@ -import { expect, it, vi } from "vitest"; +import { expect, it } from "vitest"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { @@ -72,7 +72,6 @@ it("resolves an aggregate only after every bound owner releases", async () => { it("lets errors read a group's release instead of having it pushed to them", async () => { const error = new ProviderCleanupError("fixture", ["owned resource"], {}); - const resolveCleanup = vi.spyOn(error, "resolveCleanup"); const lease = new AnalysisCleanupLease( async () => undefined, ["owned resource"], @@ -81,7 +80,6 @@ it("lets errors read a group's release instead of having it pushed to them", asy expect(group.cleanupReleased).toBe(false); await lease.release(); expect(group.cleanupReleased).toBe(true); - expect(resolveCleanup).not.toHaveBeenCalled(); // A dependency bound after the release, before any read, cannot reopen it. error.bindCleanupDependencies([ new ProviderCleanupError("fixture", ["later"], {}), diff --git a/src/browser/IsolatedWebBundleAnalyzer.test.ts b/src/browser/IsolatedWebBundleAnalyzer.test.ts index df2eef95aa6..3e344bf86de 100644 --- a/src/browser/IsolatedWebBundleAnalyzer.test.ts +++ b/src/browser/IsolatedWebBundleAnalyzer.test.ts @@ -24,6 +24,7 @@ import { WebBundleAnalysisAdmission, type WebBundleAnalysisWorkerPort, } from "./IsolatedWebBundleAnalyzer.js"; +import { releaseOwnedCleanup } from "../../tests/support/cleanupRelease.js"; const origin = "https://app.example.test"; const noSourceMaps: WebBundleAnalysis["observations"]["source_maps"] = { @@ -340,8 +341,8 @@ it("retains cleanup ownership after mixed worker/close failure and resolves it o close: async () => { closeAttempts += 1; if (closeAttempts <= 2) throw closeFailure; - closeFailure.resolveCleanup(); - primary.resolveCleanup(); + releaseOwnedCleanup(closeFailure); + releaseOwnedCleanup(primary); }, }), admission, diff --git a/src/browser/PlaywrightElectronActiveProvider.test.ts b/src/browser/PlaywrightElectronActiveProvider.test.ts index 2805d548a27..09640187646 100644 --- a/src/browser/PlaywrightElectronActiveProvider.test.ts +++ b/src/browser/PlaywrightElectronActiveProvider.test.ts @@ -33,6 +33,7 @@ import { safeElectronEnvironment, } from "./PlaywrightElectronActiveProvider.js"; import { waitFor } from "../../tests/support/testWait.js"; +import { releaseOwnedCleanup } from "../../tests/support/cleanupRelease.js"; afterEach(() => { vi.restoreAllMocks(); @@ -236,7 +237,7 @@ it("retains failed ownership-helper cleanup until provider close retries it", as ); const owner = { close: vi.fn(async () => { - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); }), }; const prepare = vi diff --git a/src/browser/WebBundleAnalysisWorker.test.ts b/src/browser/WebBundleAnalysisWorker.test.ts index a4567276237..2a6626eb360 100644 --- a/src/browser/WebBundleAnalysisWorker.test.ts +++ b/src/browser/WebBundleAnalysisWorker.test.ts @@ -37,6 +37,7 @@ import { WebBundleWorkerCleanup, } from "./WebBundleAnalysisWorker.js"; import { WEB_BUNDLE_WORKER_LIMITS } from "./WebBundleAnalysisWorkerProtocol.js"; +import { releaseOwnedCleanup } from "../../tests/support/cleanupRelease.js"; const makeScript = (text: string): IncludedScript => ({ script_key: `scr_${createHash("sha256").update(text).digest("hex")}`, @@ -378,7 +379,7 @@ it("retains ownership-helper cleanup until worker close retries it", async () => ); const owner = { close: vi.fn(async () => { - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); }), }; const prepare = vi @@ -419,7 +420,7 @@ it("retains failed helper cleanup without caller cancellation", async () => { ); const owner = { close: vi.fn(async () => { - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); }), }; const physical = new DarwinProcessOwnershipInspectionError( diff --git a/src/browser/WebSourceMapFetcher.ts b/src/browser/WebSourceMapFetcher.ts index eef18c5a6d3..a236152124a 100644 --- a/src/browser/WebSourceMapFetcher.ts +++ b/src/browser/WebSourceMapFetcher.ts @@ -56,6 +56,7 @@ import { import { selectedBrowserDeadlineMs } from "../domain/browserDeadline.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; +import { AnalysisCleanupRelease } from "../domain/analysisCleanupRelease.js"; import { selectedSourceMapLimits, sourceMapLimitRecovery, @@ -341,6 +342,8 @@ class SourceMapResponseCleanup extends Error { readonly failure: AnalysisError; readonly completion: Promise; #resource: { url: string; body: ReadableStream } | undefined; + /** Confirmed once the reader's cancellation completes and its lock is released. */ + readonly #released = new AnalysisCleanupRelease(); get cleanupResources(): readonly string[] { return this.#resource === undefined ? [] : [this.#resource.url]; @@ -374,7 +377,7 @@ class SourceMapResponseCleanup extends Error { cleanup, userMessage: cause instanceof Error ? cause.message : String(cause), }); - this.failure.bindCleanupResourceOwner(this); + this.#released.bind(this.failure.bindCleanupResourceOwner(this)); const failed = (cause: unknown): void => { reason = `Source-map response cancellation failed: ${cause instanceof Error ? cause.message : String(cause)}`; this.failure.retainSecondaryFailure( @@ -410,7 +413,7 @@ class SourceMapResponseCleanup extends Error { reader.releaseLock(); reason = "Source-map response cancellation completed."; this.#resource = undefined; - this.failure.resolveCleanup(); + this.#released.confirm(); } catch (cause: unknown) { failed(cause); } @@ -432,6 +435,8 @@ class SourceMapPendingFetch extends Error { readonly failure: AnalysisError; readonly settled: Promise; #resource: { url: string; response?: Response } | undefined; + /** Confirmed once the late response and any body it carries are released. */ + readonly #released = new AnalysisCleanupRelease(); get cleanupResources(): readonly string[] { return this.#resource === undefined ? [] : [this.#resource.url]; @@ -460,10 +465,10 @@ class SourceMapPendingFetch extends Error { carriedReason(sourceMapCallerReason(reason)), { cleanup }, ); - this.failure.bindCleanupResourceOwner(this); + this.#released.bind(this.failure.bindCleanupResourceOwner(this)); const finished = (): void => { this.#resource = undefined; - this.failure.resolveCleanup(); + this.#released.confirm(); }; this.settled = promise.then( async (response) => { diff --git a/src/desktop/AgentEnvSolveHelper.ts b/src/desktop/AgentEnvSolveHelper.ts index 40866c2f8d1..f885d533c05 100644 --- a/src/desktop/AgentEnvSolveHelper.ts +++ b/src/desktop/AgentEnvSolveHelper.ts @@ -6,6 +6,7 @@ import { z } from "zod"; import { AnalysisCancelledError } from "../domain/analysisErrorCore.js"; import { jsonValueSchema } from "../domain/jsonValue.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; +import { AnalysisCleanupRelease } from "../domain/analysisCleanupRelease.js"; import { readBoundedControlLines } from "../process/BoundedControlLines.js"; import { cleanupOwnedProcessGroup } from "../process/ProcessOwnership.js"; import { @@ -182,6 +183,7 @@ export const runSolveHelper = async (options: { } catch (cause: unknown) { const cleanup = await sandboxRoot.stop(); if (cleanup.status === "incomplete") { + const release = new AnalysisCleanupRelease(); const failure = new SolveCleanupError( undefined, [`sandbox root ${sandboxRoot.path}`], @@ -191,17 +193,19 @@ export const runSolveHelper = async (options: { }, options.operation, ); - failure.bindCleanupResourceOwner({ - get cleanupResources() { - return sandboxRoot.removed - ? [] - : [`sandbox root ${sandboxRoot.path}`]; - }, - }); + release.bind( + failure.bindCleanupResourceOwner({ + get cleanupResources() { + return sandboxRoot.removed + ? [] + : [`sandbox root ${sandboxRoot.path}`]; + }, + }), + ); options.retainCleanup({ async stop() { const result = await sandboxRoot.stop(); - if (result.status === "verified-cleanup") failure.resolveCleanup(); + if (result.status === "verified-cleanup") release.confirm(); return result; }, dispose: () => sandboxRoot.dispose(), @@ -269,7 +273,8 @@ export const runSolveHelper = async (options: { ...(!sandboxRoot.removed ? [`sandbox root ${sandboxRoot.path}`] : []), ...(unknown ? ["agentenv sandbox identity unknown"] : []), ]; - let cleanupError: SolveCleanupError | undefined; + // Confirmed once a stop removes everything and identifies every sandbox. + const release = new AnalysisCleanupRelease(); const cleanupOwner: SolveCleanupOwner = { async stop() { if (processPending) { @@ -294,7 +299,7 @@ export const runSolveHelper = async (options: { return { status: "incomplete", reason: failures.join(" ") }; // The solve's sandboxes are all local under its private root, and agentenv keeps a sandbox's folder until its teardown is confirmed, so an emptied root leaves none up. if (sandboxRoot.removed) unknown = false; - if (!unknown) cleanupError?.resolveCleanup(); + if (!unknown) release.confirm(); return { status: "verified-cleanup" }; }, dispose: () => { @@ -309,7 +314,7 @@ export const runSolveHelper = async (options: { cleanup.status === "incomplete" ? cleanup.reason : "The helper ended before identifying every sandbox, and REA could not empty its sandbox root."; - cleanupError = new SolveCleanupError( + const cleanupError = new SolveCleanupError( report, resources(), { @@ -326,7 +331,7 @@ export const runSolveHelper = async (options: { return resources(); }, }); - throw cleanupError; + throw release.bind(cleanupError); } if (signal.aborted && report !== undefined) throw new SolveCancelledError(report, options.operation, signal.reason); diff --git a/src/desktop/BuildComputerLongRuns.test.ts b/src/desktop/BuildComputerLongRuns.test.ts index ce52f27c3b6..9803f025ea9 100644 --- a/src/desktop/BuildComputerLongRuns.test.ts +++ b/src/desktop/BuildComputerLongRuns.test.ts @@ -324,3 +324,51 @@ it("preserves a new cancellation while retrying a previous job's cleanup", async expect(starts).toBe(1); expect(await owner.release()).toMatchObject({ verified: true }); }); + +it("keeps a failure naming several jobs incomplete until each job stops", async () => { + const stopped = new Set(); + const jobs: string[] = []; + const computer = { + exec: async (argv: readonly string[]) => { + const { job } = JSON.parse(argv.slice(5).join("")) as { job: string }; + if (argv[4] === "run-begin") { + jobs.push(job); + return response({ started: true }); + } + if (argv[4] === "run-poll") throw new Error("connection failed"); + if (argv[4] === "run-cancel") + return response( + stopped.has(job) + ? { finished: true, exit_code: 130, stdout_bytes: 0 } + : { pending: true }, + ); + throw new Error("unexpected command"); + }, + homeFiles: async () => new Map(), + redacted: (text: string) => text, + } as ControlledComputer; + const owner = new BuildComputerLongRuns(computer); + const run = () => + owner + .run( + ["export-desktop-application"], + options(new AbortController().signal), + ) + .catch((error: unknown) => error); + const [first, second] = await Promise.all([run(), run()]); + expect(first).toBeInstanceOf(ProviderCleanupError); + expect(second).toBeInstanceOf(ProviderCleanupError); + const both = await run(); + if (!(both instanceof ProviderCleanupError)) + throw new Error("expected retained cleanup"); + expect(jobs).toHaveLength(2); + expect(both.cleanupResources).toHaveLength(2); + stopped.add(jobs[0] ?? ""); + expect(await owner.release()).toMatchObject({ verified: false }); + expect(first).toMatchObject({ cleanupIncomplete: false }); + expect(both.cleanupIncomplete).toBe(true); + expect(both.cleanupResources).toHaveLength(1); + stopped.add(jobs[1] ?? ""); + expect(await owner.release()).toMatchObject({ verified: true }); + expect(both.cleanupIncomplete).toBe(false); +}); diff --git a/src/desktop/BuildComputerLongRuns.ts b/src/desktop/BuildComputerLongRuns.ts index 91fb3c6b34c..42fa24c95de 100644 --- a/src/desktop/BuildComputerLongRuns.ts +++ b/src/desktop/BuildComputerLongRuns.ts @@ -27,6 +27,7 @@ interface Job { readonly path: string; readonly token: string; readonly stdout: string; + /** Failures naming this job, kept to retain its completion receipt. */ readonly failures: Set>; } @@ -232,7 +233,6 @@ export class BuildComputerLongRuns { const failure = reference.deref(); if (completed !== undefined) failure?.retainDiagnostics({ completed_command: completed }); - failure?.resolveCleanup(); } return { verified: true, @@ -283,8 +283,15 @@ export class BuildComputerLongRuns { }, ); failure.bindCleanupResourceOwner(this); - for (const pending of job === undefined ? this.#jobs : [job]) - pending.failures.add(new WeakRef(failure)); - return failure; + const jobs = job === undefined ? [...this.#jobs] : [job]; + for (const pending of jobs) pending.failures.add(new WeakRef(failure)); + // Released once every job it names has confirmed its stop. Jobs leave + // only after that, and never return, so the release cannot reopen. + const owned = this.#jobs; + return failure.bindCleanupReleaseClaim({ + get cleanupReleased() { + return jobs.every((pending) => !owned.has(pending)); + }, + }); } } diff --git a/src/domain/analysisCleanupRelease.test.ts b/src/domain/analysisCleanupRelease.test.ts index d7c58604f83..988a11c8252 100644 --- a/src/domain/analysisCleanupRelease.test.ts +++ b/src/domain/analysisCleanupRelease.test.ts @@ -1,6 +1,10 @@ import { expect, it } from "vitest"; import { AnalysisCleanupRelease } from "./analysisCleanupRelease.js"; +import { + analysisErrorWithCleanupDependencies, + analysisErrorWithCleanupFailure, +} from "./analysisErrorCleanup.js"; import { ProviderCleanupError } from "./providerCleanupError.js"; const failure = () => @@ -44,3 +48,89 @@ it("reads a claim bound repeatedly to one error only once", () => { expect(error.cleanupIncomplete).toBe(true); expect(reads).toBe(1); }); + +const resource = (name: string) => + new ProviderCleanupError("fixture", [name], { reason: `${name} pending` }); + +it.each(["owner first", "dependency first"] as const)( + "completes an owned error only after its owner and every dependency release (%s)", + (order) => { + const ownerRelease = new AnalysisCleanupRelease(); + const dependencyRelease = new AnalysisCleanupRelease(); + const dependency = dependencyRelease.bind(resource("descriptor")); + const error = ownerRelease + .bind(resource("session")) + .bindCleanupDependencies([dependency]); + // Pending dependencies attribute the live resources. + expect(error.cleanupResources).toEqual(["descriptor"]); + + (order === "owner first" ? ownerRelease : dependencyRelease).confirm(); + expect(error.cleanupIncomplete).toBe(true); + expect(error.cleanupResources).toEqual([ + order === "owner first" ? "descriptor" : "session", + ]); + + (order === "owner first" ? dependencyRelease : ownerRelease).confirm(); + expect(error.cleanupIncomplete).toBe(false); + expect(error.cleanupResources).toEqual([]); + }, +); + +it("keeps an owner's pending record when every bound dependency is already complete", () => { + const release = new AnalysisCleanupRelease(); + const completedRelease = new AnalysisCleanupRelease(); + const completed = completedRelease.bind(resource("completed")); + completedRelease.confirm(); + const error = release + .bind(resource("session")) + .bindCleanupDependencies([completed]); + expect(error.cleanupIncomplete).toBe(true); + expect(error.cleanupResources).toEqual(["session"]); + release.confirm(); + expect(error.cleanupIncomplete).toBe(false); +}); + +// JADX's retained cleanup: the admission failure reads its descriptors' +// release, the retained cleanup error reads the whole cleanup's release, and +// close composes both with the prerequisite cleanup failure. +it("completes JADX-style owner records composed through the shared helper", () => { + const descriptorRelease = new AnalysisCleanupRelease(); + const release = new AnalysisCleanupRelease(); + const admission = descriptorRelease.bind(resource("descriptor")); + const retained = release.bind( + analysisErrorWithCleanupFailure(admission, resource("workspace")), + ); + const prerequisiteRelease = new AnalysisCleanupRelease(); + const prerequisite = prerequisiteRelease.bind(resource("java-probe")); + const closed = analysisErrorWithCleanupDependencies(retained, prerequisite); + + descriptorRelease.confirm(); + expect(admission.cleanupIncomplete).toBe(false); + expect(retained.cleanupIncomplete).toBe(true); + expect(closed.cleanupIncomplete).toBe(true); + + release.confirm(); + expect(retained.cleanupIncomplete).toBe(false); + expect(closed.cleanupIncomplete).toBe(true); + expect(closed.cleanupResources).toEqual(["java-probe"]); + + prerequisiteRelease.confirm(); + expect(closed.cleanupIncomplete).toBe(false); +}); + +it("keeps an owner's record bound to a composition of owned parts", () => { + const primaryRelease = new AnalysisCleanupRelease(); + const cleanupRelease = new AnalysisCleanupRelease(); + const ownerRelease = new AnalysisCleanupRelease(); + const composed = ownerRelease.bind( + analysisErrorWithCleanupDependencies( + primaryRelease.bind(resource("worker")), + cleanupRelease.bind(resource("root")), + ), + ); + primaryRelease.confirm(); + cleanupRelease.confirm(); + expect(composed.cleanupIncomplete).toBe(true); + ownerRelease.confirm(); + expect(composed.cleanupIncomplete).toBe(false); +}); diff --git a/src/domain/analysisErrorBase.ts b/src/domain/analysisErrorBase.ts index 0c37db6e2ea..ea57dac26fc 100644 --- a/src/domain/analysisErrorBase.ts +++ b/src/domain/analysisErrorBase.ts @@ -190,8 +190,8 @@ export abstract class AnalysisError extends Error { } readonly cleanup: AnalysisCleanupObservation | undefined; /** - * This error's own unresolved cleanup. With bound dependencies, completion - * is read from them when asked instead of being pushed to each dependent. + * Whether cleanup is still unsettled. Once settled it stays settled; until + * then completion is read from the owners when asked, never pushed here. */ #cleanupIncomplete: boolean; /** Whether this error ever owned cleanup, apart from whether it finished. */ @@ -251,29 +251,32 @@ export abstract class AnalysisError extends Error { } /** - * Whether owned resources remain unreleased, read from the owners when - * asked. Bound dependencies decide it once bound; otherwise a released - * lease claim completes it. Completion is monotonic, so a later binding - * cannot reopen it. + * Whether owned resources remain unreleased: this error's own record AND + * every bound dependency's record, each read from its owner when asked. + * Completion is monotonic, so a later binding cannot reopen it. */ get cleanupIncomplete(): boolean { if (!this.#cleanupIncomplete) return false; - const dependencies = this.#cleanupDependencies; - if (dependencies === undefined) { - if (!this.#anyClaimReleased()) return true; - } else - for (const dependency of dependencies) - if (dependency.cleanupIncomplete) return true; + if (this.#ownCleanupPending()) return true; + for (const dependency of this.#cleanupDependencies ?? []) + if (dependency.cleanupIncomplete) return true; this.#cleanupIncomplete = false; - dependencies?.clear(); + this.#cleanupDependencies?.clear(); this.#cleanupReleaseClaims.clear(); return false; } - #anyClaimReleased(): boolean { + /** + * This error's own completion record. A bound release claim is its owner's + * record; without one, an error composed only of dependencies has no + * resources of its own, and any other error waits for its owner. + */ + #ownCleanupPending(): boolean { + if (this.#cleanupReleaseClaims.size === 0) + return this.#cleanupDependencies === undefined; for (const claim of this.#cleanupReleaseClaims) - if (claim.cleanupReleased) return true; - return false; + if (claim.cleanupReleased) return false; + return true; } /** @@ -297,22 +300,29 @@ export abstract class AnalysisError extends Error { } readonly cleanupReport: ProcessCaptureCleanupReport | undefined = undefined; - /** Live dependencies own current resource attribution; cleanup keeps history. */ + /** + * Live owners own current resource attribution; cleanup keeps history. A + * composed error's own resources usually summarize its dependencies, so + * pending dependencies attribute; once only the owner's record is pending, + * its own resources do. + */ get cleanupResources(): readonly string[] { - if (this.#cleanupDependencies === undefined) - return ( - this.#cleanupResourceOwner?.cleanupResources ?? - this.#ownedCleanupResources - ); + const own = + this.#cleanupResourceOwner?.cleanupResources ?? + this.#ownedCleanupResources; + if (this.#cleanupDependencies === undefined) return own; const pending = [...this.#cleanupDependencies].filter( (dependency) => dependency.cleanupIncomplete, ); - if (pending.length === 0) return []; - if (this.#cleanupResourceProjection !== undefined) - return this.#cleanupResourceProjection.cleanupResources; - return [ - ...new Set(pending.flatMap((dependency) => dependency.cleanupResources)), - ]; + if (pending.length > 0) + return ( + this.#cleanupResourceProjection?.cleanupResources ?? [ + ...new Set( + pending.flatMap((dependency) => dependency.cleanupResources), + ), + ] + ); + return this.#cleanupIncomplete && this.#ownCleanupPending() ? own : []; } /** Whether cleanup follows an explicit owner or dependent errors. */ @@ -424,23 +434,6 @@ export abstract class AnalysisError extends Error { this.#cleanupResourceProjection = resourceProjection; for (const dependency of dependencies) if (dependency.cleanupIncomplete) pending.add(dependency); - if (pending.size === 0) this.resolveCleanup(); - return this; - } - - /** - * Clear live cleanup status only after its owning resource confirms retry - * success. Errors composed from this one read the change on their next check. - */ - resolveCleanup(): this { - if ( - [...(this.#cleanupDependencies ?? [])].some( - (dependency) => dependency.cleanupIncomplete, - ) - ) - return this; - this.#cleanupDependencies?.clear(); - this.#cleanupIncomplete = false; return this; } diff --git a/src/domain/analysisErrorCleanup.test.ts b/src/domain/analysisErrorCleanup.test.ts index 9e86f682261..ffbc20ad717 100644 --- a/src/domain/analysisErrorCleanup.test.ts +++ b/src/domain/analysisErrorCleanup.test.ts @@ -20,6 +20,7 @@ import { import { ProviderCleanupError } from "./providerCleanupError.js"; import { createEvidence } from "./evidence.js"; import { ArtifactOperationError } from "./artifactOperationError.js"; +import { releaseOwnedCleanup } from "../../tests/support/cleanupRelease.js"; it.each([false, true])( "keeps each owner's capture without text-based deduplication (matching: %s)", @@ -85,9 +86,9 @@ it("keeps dependency-owned resources empty after the final owner releases", () = expect(new Set(composed.cleanupResources)).toEqual( new Set(["file-owner", "trace-owner"]), ); - file.resolveCleanup(); + releaseOwnedCleanup(file); expect(composed.cleanupResources).toEqual(["trace-owner"]); - trace.resolveCleanup(); + releaseOwnedCleanup(trace); expect(composed.cleanupIncomplete).toBe(false); expect(composed.cleanupResources).toEqual([]); expect(new Set(composed.cleanup?.resources)).toEqual( @@ -110,7 +111,7 @@ it("reads completion through nested compositions from the releasing owner only", // Cleanup state is not writable state of an error value. expect(Reflect.set(outer, "cleanupIncomplete", false)).toBe(false); expect(outer.cleanupIncomplete).toBe(true); - owner.resolveCleanup(); + releaseOwnedCleanup(owner); expect(outer.cleanupIncomplete).toBe(false); expect(inner.cleanupIncomplete).toBe(false); // Completion is monotonic: a later binding cannot reopen it. @@ -127,7 +128,7 @@ it("keeps completion when a dependency is bound after release without an interme ["owned-worker"], {}, ).bindCleanupDependencies([owner]); - owner.resolveCleanup(); + releaseOwnedCleanup(owner); outer.bindCleanupDependencies([ new ProviderCleanupError("fixture", ["later"], {}), ]); @@ -146,7 +147,7 @@ it("keeps primary diagnostics separate from historical cleanup diagnostics with primary, cleanup, ).bindCleanupDependencies([primary, cleanup]); - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); const projected = projectAnalysisError(composed); expect(projected.details?.diagnostics).toEqual(primary.diagnostics); expect(projected.details?.cleanup_history).toMatchObject({ @@ -231,7 +232,7 @@ it.each([ execution_failure: original.code, resources: ["owned-input"], }); - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); const projected = projectAnalysisError(composed); expect(projected).toMatchObject(original); expect(projected.details?.cleanup_history).toMatchObject({ @@ -282,11 +283,11 @@ it.each(["inner", "outer"] as const)( execution_failure: "invalid_request", }, }); - released.resolveCleanup(); + releaseOwnedCleanup(released); expect(outer.cleanupIncomplete).toBe(true); expect(projectAnalysisError(outer).code).toBe("cleanup_incomplete"); expect(projectAnalysisError(outer).category).toBe("invalid_input"); - pending.resolveCleanup(); + releaseOwnedCleanup(pending); expect(outer.cleanupIncomplete).toBe(false); expect(projectAnalysisError(outer)).toMatchObject( projectAnalysisError(primary), @@ -355,7 +356,7 @@ it("does not infer cleanup success when a composition has no live owner binding" const primary = new AnalysisInputError("inspect"); const cleanup = new ProviderCleanupError("fixture", ["input"], {}); const composed = analysisErrorWithCleanupFailure(primary, cleanup); - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); expect(projectAnalysisError(composed).code).toBe("cleanup_incomplete"); expect(projectAnalysisError(composed).category).toBe("invalid_input"); expect(composed.cleanupIncomplete).toBe(true); @@ -397,7 +398,7 @@ it("keeps the physical failure primary when later cleanup observes cancellation" }, }); expect(composed.cleanupPrimary?.cause).toBe(physical); - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); expect(projectAnalysisError(composed)).toMatchObject( projectAnalysisError(primary), ); @@ -423,9 +424,9 @@ it("retains an observation attached to the composite after the primary failed", }, ); composed.retainPartialObservation(observation); - composed.resolveCleanup(); + releaseOwnedCleanup(composed); expect(projectAnalysisError(composed).code).toBe("cleanup_incomplete"); - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); expect(projectAnalysisError(composed)).toMatchObject({ code: "invalid_request", details: { partial_observation: observation }, @@ -470,10 +471,10 @@ it("retains an owner's finalization report independently of pending primary sema assertReport(finalized); assertReport(outer); expect(outer.cleanupIncomplete).toBe(true); - later.resolveCleanup(); + releaseOwnedCleanup(later); assertReport(outer); expect(outer.cleanupIncomplete).toBe(true); - finalized.resolveCleanup(); + releaseOwnedCleanup(finalized); assertReport(outer); expect(outer.cleanupIncomplete).toBe(false); }); diff --git a/src/domain/analysisErrorCleanup.ts b/src/domain/analysisErrorCleanup.ts index 14cb142bca7..2521f3d40fa 100644 --- a/src/domain/analysisErrorCleanup.ts +++ b/src/domain/analysisErrorCleanup.ts @@ -6,7 +6,11 @@ import { composedCallerGuidance, } from "./analysisErrorPresentation.js"; -/** Preserve the original lifecycle failure alongside incomplete cleanup. */ +/** + * Preserve the original lifecycle failure alongside incomplete cleanup. The + * composite waits for an owner to bind its completion; compose with + * `analysisErrorWithCleanupDependencies` when the parts own it. + */ export const analysisErrorWithCleanupFailure = ( primary: AnalysisError, cleanup: AnalysisError, @@ -53,3 +57,19 @@ export const analysisErrorWithCleanupFailure = ( }), }, ); + +/** + * Compose a failure with the cleanup failure that followed it. The composite + * has no cleanup record of its own: it completes once the primary's and the + * cleanup's records both report release, each read from its owner. + */ +export const analysisErrorWithCleanupDependencies = ( + primary: AnalysisError, + cleanup: AnalysisError, + operation = "close_binary", +): AnalysisError => + analysisErrorWithCleanupFailure( + primary, + cleanup, + operation, + ).bindCleanupDependencies([primary, cleanup]); diff --git a/src/domain/analysisErrorProjection.test.ts b/src/domain/analysisErrorProjection.test.ts index cc862d803f3..4eed513ce6c 100644 --- a/src/domain/analysisErrorProjection.test.ts +++ b/src/domain/analysisErrorProjection.test.ts @@ -49,6 +49,7 @@ import { redactExplicitText } from "./explicitSensitiveValues.js"; import { analysisErrorWithCleanupFailure } from "./analysisErrorCleanup.js"; import type { AnalysisCallerLifetime } from "./analysisErrorBase.js"; import { ProviderCleanupError } from "./providerCleanupError.js"; +import { releaseOwnedCleanup } from "../../tests/support/cleanupRelease.js"; it("projects nested workflow-publication recovery for the actual caller lifetime", () => { const child = new UnknownRegistryError( @@ -1759,7 +1760,7 @@ describe("analysis error projection: Hopper caller lifetime", () => { diagnostics: { primary_error: continuingPrimary }, }); - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); expect( projectAnalysisError(composed, "invocation").details?.cleanup_history, ).toMatchObject({ primary_error: invocationPrimary }); @@ -1812,7 +1813,7 @@ describe("analysis error projection: composed failures for a caller lifetime", ( `Only this request stopped. ${continuingOnly.userMessage}`, ); // After cleanup resolves, history keeps the composition-time snapshot. - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); for (const lifetime of ["continuing", "invocation"] as const) expect(child(lifetime)?.cleanup_history).toMatchObject({ primary_error: projectAnalysisError(primary, lifetime), diff --git a/src/domain/explicitSensitiveFailure.test.ts b/src/domain/explicitSensitiveFailure.test.ts index eb923f5102d..6826b59c880 100644 --- a/src/domain/explicitSensitiveFailure.test.ts +++ b/src/domain/explicitSensitiveFailure.test.ts @@ -17,6 +17,7 @@ import { analysisErrorWithCleanupFailure } from "./analysisErrorCleanup.js"; import { resolvedAnalysisError } from "./analysisErrorBase.js"; import { createEvidence } from "./evidence.js"; import { redactExplicitFailure } from "./explicitSensitiveFailure.js"; +import { releaseOwnedCleanup } from "../../tests/support/cleanupRelease.js"; const context = { diagnostics: { @@ -182,7 +183,7 @@ it("redacts cleanup primaries and mirrors the source error's live status", () => "private-marker", ); - original.resolveCleanup(); + releaseOwnedCleanup(original); expect(redacted.cleanupIncomplete).toBe(false); const resolved = resolvedAnalysisError(redacted); expect(JSON.stringify(projectAnalysisError(resolved))).not.toContain( @@ -236,7 +237,7 @@ it("retains sanitized finalization failures and their independent cleanup status }, ]); expect(JSON.stringify(projected)).not.toContain("declared-marker"); - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); expect(retainedCleanup?.cleanupIncomplete).toBe(false); expect(redacted.cleanupIncomplete).toBe(false); }); @@ -414,6 +415,6 @@ it("preserves completed publication and live cleanup while excluding marked file expect(projected.details).not.toHaveProperty("path"); expect(projected.details).not.toHaveProperty("published_path"); expect(JSON.stringify(projected)).not.toContain("private-marker"); - original.resolveCleanup(); + releaseOwnedCleanup(original); expect(redacted.cleanupIncomplete).toBe(false); }); diff --git a/src/domain/providerCleanupError.test.ts b/src/domain/providerCleanupError.test.ts index 1edfbcb7ecd..daae141bc55 100644 --- a/src/domain/providerCleanupError.test.ts +++ b/src/domain/providerCleanupError.test.ts @@ -6,6 +6,7 @@ import { AnalysisCancelledError } from "./analysisErrorCore.js"; import { cleanupRetryRemediation } from "./analysisErrorRecovery.js"; import { analysisErrorRemediationAction } from "./analysisErrorPresentation.js"; import { analysisErrorProjectionSchema } from "../contracts/errorSchemas.js"; +import { releaseOwnedCleanup } from "../../tests/support/cleanupRelease.js"; const CLOSE_RETRY = { operation: "close_binary" } as const; // Guidance comes from its owning formatters; tests check composition, not prose. @@ -36,7 +37,7 @@ it.each([false, true])( { reason: "first descriptor close failed" }, { operation: "capture_adb_screen" }, ); - if (resolved) primary.resolveCleanup(); + if (resolved) releaseOwnedCleanup(primary); const cleanup = new ProviderCleanupError("adb", ["runtime-root"], { reason: "workspace removal failed", }); @@ -86,7 +87,7 @@ it.each(["alpha", "beta"])( ).bindCleanupDependencies([children, third]); const released = first === "alpha" ? alpha : beta; const remaining = first === "alpha" ? beta : alpha; - released.resolveCleanup(); + releaseOwnedCleanup(released); expect(outer.cleanupIncomplete).toBe(true); expect(outer.cleanupResources).toEqual([ ...remaining.cleanupResources, @@ -96,10 +97,10 @@ it.each(["alpha", "beta"])( code: "cleanup_incomplete", details: { resources: [...remaining.cleanupResources, "third-file"] }, }); - remaining.resolveCleanup(); + releaseOwnedCleanup(remaining); expect(outer.cleanupIncomplete).toBe(true); expect(outer.cleanupResources).toEqual(["third-file"]); - third.resolveCleanup(); + releaseOwnedCleanup(third); expect(outer.cleanupIncomplete).toBe(false); expect(projectAnalysisError(outer).code).not.toBe("cleanup_incomplete"); }, @@ -131,7 +132,7 @@ it("offers a bound cleanup retry only while that cleanup remains incomplete", () ); expect(analysisErrorProjectionSchema.parse(offered)).toEqual(offered); - retained.resolveCleanup(); + releaseOwnedCleanup(retained); expect(retained.cleanupRetry).toBeUndefined(); const released = projectAnalysisError(retained); expect(released.code).toBe("execution_failure"); @@ -169,7 +170,7 @@ it("keeps a retry offer with the owner of the composed resources", () => { ); expect(offered.remediation.action.split(RETRY_ACTION)).toHaveLength(2); - retained.resolveCleanup(); + releaseOwnedCleanup(retained); expect(composed.cleanupIncomplete).toBe(false); expect(projectAnalysisError(composed)).toMatchObject({ code: "cancelled" }); expect(projectAnalysisError(composed)).not.toHaveProperty("recovery"); diff --git a/src/ghidra/GhidraProvider.behavior.test.ts b/src/ghidra/GhidraProvider.behavior.test.ts index f1a9562ea0c..941adc05a6e 100644 --- a/src/ghidra/GhidraProvider.behavior.test.ts +++ b/src/ghidra/GhidraProvider.behavior.test.ts @@ -123,6 +123,7 @@ import { import { AnalysisSnapshotCache } from "../application/binary/AnalysisSnapshotCache.js"; import { createEvidence } from "../domain/evidence.js"; import { createEvidenceBundle } from "../domain/evidenceBundle.js"; +import { releaseOwnedCleanup } from "../../tests/support/cleanupRelease.js"; const GHIDRA_SESSION_RETAINED = "The Ghidra session remains usable."; const GHIDRA_ANNOTATIONS_RETAINED = @@ -6870,7 +6871,7 @@ it("session-observation failure clears only its resolved cleanup dependency afte close: async () => { closes++; if (closes === 1) return err(retained); - retained.resolveCleanup(); + releaseOwnedCleanup(retained); return ok(null); }, }), diff --git a/src/ghidra/GhidraRequestQueue.test.ts b/src/ghidra/GhidraRequestQueue.test.ts index 585dc3f08e2..9248c636097 100644 --- a/src/ghidra/GhidraRequestQueue.test.ts +++ b/src/ghidra/GhidraRequestQueue.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest"; import { err, ok, type Result } from "../domain/result.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { GhidraRequestQueue } from "./GhidraRequestQueue.js"; +import { releaseOwnedCleanup } from "../../tests/support/cleanupRelease.js"; import { bindGhidraSessionFailure, GhidraSessionError, @@ -491,13 +492,13 @@ it.each([ throw new Error("Expected both cleanup owners"); const aggregate = result.error.cleanupFailure; expect(aggregate.cleanupIncomplete).toBe(true); - const owners = + const [first, second] = order === "execution-first" ? [executionCleanup, cancellationCleanup] : [cancellationCleanup, executionCleanup]; - owners[0]?.resolveCleanup(); + releaseOwnedCleanup(first); expect(aggregate.cleanupIncomplete).toBe(true); - owners[1]?.resolveCleanup(); + releaseOwnedCleanup(second); expect(aggregate.cleanupIncomplete).toBe(false); }, ); diff --git a/src/ghidra/GhidraSessionError.test.ts b/src/ghidra/GhidraSessionError.test.ts index 776bb84e1f5..1c22d3194a3 100644 --- a/src/ghidra/GhidraSessionError.test.ts +++ b/src/ghidra/GhidraSessionError.test.ts @@ -8,6 +8,7 @@ import { } from "./GhidraSessionError.js"; import { GhidraLaunchError } from "./GhidraLauncher.js"; import { createGhidraDiagnostics } from "./GhidraDiagnostics.js"; +import { releaseOwnedCleanup } from "../../tests/support/cleanupRelease.js"; it.each(["decompile_failed", "future_remote_failure"])( "retains complete session diagnostics for non-input remote code %s", @@ -232,7 +233,7 @@ it.each([null, undefined, new Error("original cause")])( }, }); expect(refreshed.cleanupFailure).toBe(cleanup); - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); expect(refreshed.cleanupFailure?.cleanupIncomplete).toBe(false); expect( Object.hasOwn( @@ -260,7 +261,7 @@ it("preserves the compiler root cleanup dependency through launch and session pr launch, ); expect(session.cleanupFailure).toBe(cleanup); - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); expect(session.cleanupFailure?.cleanupIncomplete).toBe(false); }); diff --git a/src/hopper/HopperRegexSearch.test.ts b/src/hopper/HopperRegexSearch.test.ts index 2dc4a23fc50..5ba64678364 100644 --- a/src/hopper/HopperRegexSearch.test.ts +++ b/src/hopper/HopperRegexSearch.test.ts @@ -15,6 +15,7 @@ import { parseConfig } from "../config/parseConfig.js"; import { silentLogger } from "../logger.js"; import { HopperClient } from "./HopperClient.js"; import { HopperProvider } from "./HopperProvider.js"; +import { releaseOwnedCleanup } from "../../tests/support/cleanupRelease.js"; const regexMatch = vi.hoisted(() => ({ afterSettle: undefined as (() => void) | undefined, @@ -242,7 +243,7 @@ it.each( stage: "analysis", }); expect(original.operation).toBe(inventory); - original.resolveCleanup(); + releaseOwnedCleanup(original); expect(result.error.cleanupIncomplete).toBe(false); } finally { await search.close(); diff --git a/src/javascript/analysis/JavaScriptAnalysisWorker.inspection.test.ts b/src/javascript/analysis/JavaScriptAnalysisWorker.inspection.test.ts index 65ccde5c85f..8236c19c929 100644 --- a/src/javascript/analysis/JavaScriptAnalysisWorker.inspection.test.ts +++ b/src/javascript/analysis/JavaScriptAnalysisWorker.inspection.test.ts @@ -13,6 +13,7 @@ import { ProcessOwnershipIdentityBatchFailure, } from "../../process/ProcessInspectionCancellation.js"; import * as ownership from "../../process/ProcessOwnershipObservation.js"; +import { releaseOwnedCleanup } from "../../../tests/support/cleanupRelease.js"; const text = "export const observed = 1;"; const file: JavaScriptArtifactFile = { @@ -101,7 +102,7 @@ it("retries the exact failed inspection owner before releasing its error", async const owner = { close: vi.fn(async () => { if (denied) throw cleanup; - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); }), }; const prepare = vi @@ -283,7 +284,7 @@ it("joins a late inspection cleanup handoff before worker close completes", asyn close: vi.fn(async () => { acknowledgeRetry(); await release; - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); }), }; const prepare = vi diff --git a/src/javascript/sourceMaps/SourceMapDecoder.test.ts b/src/javascript/sourceMaps/SourceMapDecoder.test.ts index 5b974be6029..cf2468c22c5 100644 --- a/src/javascript/sourceMaps/SourceMapDecoder.test.ts +++ b/src/javascript/sourceMaps/SourceMapDecoder.test.ts @@ -16,6 +16,7 @@ import { webSourceLocationArgs, webSourceLocationFixture, } from "../../../tests/fixtures/webSourceLocation.js"; +import { releaseOwnedCleanup } from "../../../tests/support/cleanupRelease.js"; const fixture = webSourceLocationFixture(); const input = { @@ -342,7 +343,7 @@ it("retains Darwin preparation cleanup ownership and cancellation through retry" close: async () => { if (!release) throw new Error("still held"); await root.close(); - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); }, }, }, diff --git a/src/kuna/KunaProjectCache.ts b/src/kuna/KunaProjectCache.ts index 5625d1ae831..20b34392818 100644 --- a/src/kuna/KunaProjectCache.ts +++ b/src/kuna/KunaProjectCache.ts @@ -267,9 +267,25 @@ interface RetainedHashFile { lastCloseFailure?: ProviderCleanupError; } -interface CleanupErrorReport { - readonly error: WeakRef; - readonly pendingOwners: Set; +/** + * Release of one retained resource owner. When retirement moves the owner's + * resources to another owner, it reads that successor's release instead. + */ +class KunaOwnerRelease { + #released = false; + #successor: KunaOwnerRelease | undefined; + + get released(): boolean { + return this.#released || (this.#successor?.released ?? false); + } + + confirm(): void { + this.#released = true; + } + + transferTo(successor: KunaOwnerRelease): void { + this.#successor = successor; + } } interface CleanupFailureOwner { @@ -390,8 +406,13 @@ export class KunaProjectCache { readonly #hashRecords = new WeakMap(); /** Serialize owner release and staging retirement across concurrent lookups. */ #hashRetry: Promise = Promise.resolve(); - /** Weakly track caller errors against every resource owner they report. */ - readonly #cleanupErrorReports: CleanupErrorReport[] = []; + /** Each resource owner's release, read by the errors reporting it. */ + readonly #ownerReleases = new WeakMap(); + /** Owner releases each reported error reads; it completes once all confirm. */ + readonly #errorOwnerReleases = new WeakMap< + AnalysisError, + KunaOwnerRelease[] + >(); readonly #stagingCleanupOwners = new Map(); constructor( @@ -660,7 +681,7 @@ export class KunaProjectCache { async #retryProcess(retained: RetainedProcess): Promise { const stopped = await retained.owner?.stop(); if (stopped === undefined || stopped.status === "incomplete") return; - this.#resolveCleanupOwner(retained); + this.#confirmOwnerRelease(retained); await this.#retireStaging(retained.staging, retained.key); this.#retainedProcesses.delete(retained); } @@ -695,7 +716,7 @@ export class KunaProjectCache { try { await retained.lease.release(); this.#retainedHashFiles.delete(owner); - this.#resolveCleanupOwner(owner); + this.#confirmOwnerRelease(owner); if (retained.staging !== null) staging.set(retained.staging, retained.key); } catch (cause: unknown) { @@ -797,18 +818,33 @@ export class KunaProjectCache { return result; } + /** Let `error` read the release of every owner it reports. */ #bindCleanupError(error: AnalysisError, owners: readonly object[]): void { - this.#pruneCleanupErrorReports(); - const report = this.#cleanupErrorReports.find( - (candidate) => candidate.error.deref() === error, - ); - const pending = report?.pendingOwners ?? new Set(); - for (const owner of owners) pending.add(owner); - if (report === undefined && pending.size > 0) - this.#cleanupErrorReports.push({ - error: new WeakRef(error), - pendingOwners: pending, + if (owners.length === 0) return; + let releases = this.#errorOwnerReleases.get(error); + if (releases === undefined) { + const bound: KunaOwnerRelease[] = []; + releases = bound; + this.#errorOwnerReleases.set(error, bound); + error.bindCleanupReleaseClaim({ + get cleanupReleased() { + return bound.every((release) => release.released); + }, }); + } + for (const owner of owners) { + const release = this.#ownerRelease(owner); + if (!releases.includes(release)) releases.push(release); + } + } + + #ownerRelease(owner: object): KunaOwnerRelease { + let release = this.#ownerReleases.get(owner); + if (release === undefined) { + release = new KunaOwnerRelease(); + this.#ownerReleases.set(owner, release); + } + return release; } #fileCleanupOwner(path: string): object { @@ -824,41 +860,12 @@ export class KunaProjectCache { return owner; } - #resolveCleanupOwner(owner: object): void { - for (const report of [...this.#cleanupErrorReports]) { - const error = report.error.deref(); - if (error === undefined) { - this.#cleanupErrorReports.splice( - this.#cleanupErrorReports.indexOf(report), - 1, - ); - continue; - } - report.pendingOwners.delete(owner); - if (report.pendingOwners.size === 0) { - error.resolveCleanup(); - this.#cleanupErrorReports.splice( - this.#cleanupErrorReports.indexOf(report), - 1, - ); - } - } + #confirmOwnerRelease(owner: object): void { + this.#ownerRelease(owner).confirm(); } #transferCleanupOwner(from: object, to: object): void { - this.#pruneCleanupErrorReports(); - for (const report of this.#cleanupErrorReports) - if (report.pendingOwners.delete(from)) report.pendingOwners.add(to); - } - - #pruneCleanupErrorReports(): void { - for ( - let index = this.#cleanupErrorReports.length - 1; - index >= 0; - index -= 1 - ) - if (this.#cleanupErrorReports[index]?.error.deref() === undefined) - this.#cleanupErrorReports.splice(index, 1); + this.#ownerRelease(from).transferTo(this.#ownerRelease(to)); } /** @@ -910,7 +917,7 @@ export class KunaProjectCache { await rename(staging, retired); cleanupPath = retired; await this.#removeRetired(retired, key); - if (stagingOwner !== undefined) this.#resolveCleanupOwner(stagingOwner); + if (stagingOwner !== undefined) this.#confirmOwnerRelease(stagingOwner); return undefined; } catch (cause: unknown) { const failure = @@ -1294,7 +1301,7 @@ export class KunaProjectCache { const retained = this.#retainedFiles.get(path); this.#retainedFiles.delete(path); if (retained !== undefined) - this.#resolveCleanupOwner(retained.cleanupOwner); + this.#confirmOwnerRelease(retained.cleanupOwner); } catch (cause: unknown) { throw this.#retainFileCleanup(path, cause, key); } diff --git a/src/native/CommandRunner.ts b/src/native/CommandRunner.ts index 52d8efaacd0..cbe67ea30ab 100644 --- a/src/native/CommandRunner.ts +++ b/src/native/CommandRunner.ts @@ -246,7 +246,7 @@ export class XcrunCommandRunner implements NativeCommandRunner { if (stopped.status === "not-owned") { reason = "native command ownership remains unresolved"; } else if (stopped.status !== "incomplete") { - marker.resolveCleanup(); + // The marker reads the supervisor's release of this stop. this.#cleanupMarkers.delete(owner); continue; } else @@ -284,6 +284,7 @@ export class XcrunCommandRunner implements NativeCommandRunner { { operation: "native_command", cause: failure }, ); } + marker.bindCleanupReleaseClaim(owner.cleanupRelease); this.#cleanupMarkers.set(owner, marker); if (failure.cleanupMarker === marker) return failure; return new NativeCommandFailure( diff --git a/src/native/LldbCallTracer.ts b/src/native/LldbCallTracer.ts index 8853fe7b03e..a9849316ab5 100644 --- a/src/native/LldbCallTracer.ts +++ b/src/native/LldbCallTracer.ts @@ -514,6 +514,7 @@ export class LldbCallTracer implements NativeCallTracer { { reason: entry.reason }, { operation: OPERATION, cause: failure }, ); + marker.bindCleanupReleaseClaim(entry.owner.cleanupRelease); this.#resolverCleanup.set(entry.owner, marker); } } @@ -580,7 +581,7 @@ export class LldbCallTracer implements NativeCallTracer { unresolved.push(marker); continue; } - marker.resolveCleanup(); + // The marker reads the supervisor's release of this stop. this.#resolverCleanup.delete(owner); } if (unresolved.length === 0) return undefined; diff --git a/src/process/OwnedCommandPreparation.test.ts b/src/process/OwnedCommandPreparation.test.ts index b2c0b040409..e13ebc219f3 100644 --- a/src/process/OwnedCommandPreparation.test.ts +++ b/src/process/OwnedCommandPreparation.test.ts @@ -13,6 +13,7 @@ import { prepareProcessOwnershipInspection, systemProcessOwnershipHost, } from "./ProcessOwnershipObservation.js"; +import { releaseOwnedCleanup } from "../../tests/support/cleanupRelease.js"; const platform = Object.getOwnPropertyDescriptor( systemProcessOwnershipHost, @@ -132,7 +133,7 @@ it("preserves exact cancelled preparation cleanup capabilities", async () => { ); const owner = { close: vi.fn(async () => { - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); }), }; const failure = new DarwinProcessOwnershipInspectionError( diff --git a/src/process/ProviderProcess.ts b/src/process/ProviderProcess.ts index d0819a4f481..6f4094f12ed 100644 --- a/src/process/ProviderProcess.ts +++ b/src/process/ProviderProcess.ts @@ -1,4 +1,6 @@ import { err, ok, type Result } from "../domain/result.js"; +import { AnalysisCleanupRelease } from "../domain/analysisCleanupRelease.js"; +import type { AnalysisCleanupReleaseClaim } from "../domain/analysisErrorBase.js"; import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { DarwinProcessOwnershipInspectionError } from "./DarwinProcessRunTokenReader.js"; import { @@ -464,6 +466,7 @@ export class ProviderProcessSupervisor { #exitObservation: ProviderProcessExitObservation | undefined; #stopPromise: Promise | undefined; #stopRequested = false; + readonly #release = new AnalysisCleanupRelease(); #disposed = false; #maxAggregateDiagnosticBytes: number | undefined; readonly #maxStreamDiagnosticBytes: @@ -793,6 +796,14 @@ export class ProviderProcessSupervisor { }; } + /** + * Confirmed once a stop proves this process ended; errors reporting the + * process read it instead of being told. + */ + get cleanupRelease(): AnalysisCleanupReleaseClaim { + return this.#release; + } + /** Share each stop attempt; incomplete cleanup retains ownership and permits retry. */ stop( options: ProviderProcessStopOptions = {}, @@ -801,6 +812,7 @@ export class ProviderProcessSupervisor { this.#stopRequested = true; this.#stopPromise ??= this.#stop(options).then((result) => { if (result.status === "incomplete") this.#stopPromise = undefined; + else if (result.status !== "not-owned") this.#release.confirm(); return result; }); return this.#stopPromise; diff --git a/src/process/capture/ProcessCaptureError.test.ts b/src/process/capture/ProcessCaptureError.test.ts index 164e9ea9b30..7d0f8f334a7 100644 --- a/src/process/capture/ProcessCaptureError.test.ts +++ b/src/process/capture/ProcessCaptureError.test.ts @@ -13,6 +13,7 @@ import { type ProcessCaptureCleanupOutcome, } from "./ProcessCaptureLifecycle.js"; import type { ProcessCaptureCleanupReport } from "../../domain/process/processCapture.js"; +import { releaseOwnedCleanup } from "../../../tests/support/cleanupRelease.js"; const cleanupReport = { owned_process_group: { state: "not_required" as const, reason: null }, @@ -71,7 +72,7 @@ it("preserves the compiler output and live cleanup owner at capture normalizatio expect(projectAnalysisError(error)).toMatchObject({ code: "cleanup_incomplete", }); - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); expect(error.cleanupIncomplete).toBe(false); expect(error.capturedOutput?.exit_code).toBe(7); }); @@ -121,13 +122,13 @@ it("retains compiler facts and cleanup dependency through capture finalization", capturedOutput: { stderr: "controlled compiler diagnostic", exit_code: 7 }, cleanupReport, }); - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); expect(finalized).toMatchObject({ cleanupIncomplete: false }); }); it("does not recreate unresolved cleanup after the exact owner already confirmed retry", () => { const { cleanup, compiler } = fixture(); - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); const normalized = normalizeCaptureFailure(compiler); expect(normalized).toMatchObject({ cleanupIncomplete: false, @@ -161,7 +162,7 @@ it("keeps later capture cleanup unresolved after compiler cleanup succeeds", () "temporary_root", ]), }); - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); expect(finalized).toMatchObject({ cleanupIncomplete: true }); }); @@ -180,9 +181,9 @@ it.each(["compiler first", "capture first"] as const)( }); const first = order === "compiler first" ? cleanup : captureCleanup; const second = order === "compiler first" ? captureCleanup : cleanup; - first.resolveCleanup(); + releaseOwnedCleanup(first); expect(finalized.cleanupIncomplete).toBe(true); - second.resolveCleanup(); + releaseOwnedCleanup(second); expect(finalized.cleanupIncomplete).toBe(false); expect(finalized.capturedOutput?.exit_code).toBe(7); }, diff --git a/src/providers/AnalysisClientFailure.test.ts b/src/providers/AnalysisClientFailure.test.ts index da9e7353888..bb6f5f33d62 100644 --- a/src/providers/AnalysisClientFailure.test.ts +++ b/src/providers/AnalysisClientFailure.test.ts @@ -14,6 +14,7 @@ import type { FileOffsetPartialObservation } from "../domain/native/fileOffsetPa import { analysisClientFailureForOperation } from "./AnalysisClientFailure.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import { regexMatchingDeadlineError } from "../process/RegexMatcher.js"; +import { releaseOwnedCleanup } from "../../tests/support/cleanupRelease.js"; const observation: FileOffsetPartialObservation = { operation: "address_to_file_offset", @@ -33,7 +34,7 @@ it.each([false, true])( { reason: "descriptor close failed" }, { operation: "provider_mapping", completedObservation: observation }, ); - if (resolved) source.resolveCleanup(); + if (resolved) releaseOwnedCleanup(source); const attributed = analysisClientFailureForOperation( source, @@ -49,7 +50,7 @@ it.each([false, true])( expect(attributed.cleanupResources).toEqual(["snapshot descriptor"]); // Attribution must keep the source owner's later cleanup confirmation live. - source.resolveCleanup(); + releaseOwnedCleanup(source); expect(attributed.cleanupIncomplete).toBe(false); if (!resolved) expect(attributed.cleanupResources).toEqual([]); expect(attributed.completedObservation).toBe(observation); diff --git a/src/providers/AnalysisClientFailure.ts b/src/providers/AnalysisClientFailure.ts index 5bff2eca8b1..5e1036cf08e 100644 --- a/src/providers/AnalysisClientFailure.ts +++ b/src/providers/AnalysisClientFailure.ts @@ -275,7 +275,14 @@ export const analysisClientFailureForOperation = ( result = analysisErrorWithCancellation(result, secondary); else result.retainSecondaryFailure(secondary); } + // The attributed error reads its source's cleanup: live resources while it + // is pending, otherwise the source's completed release with the resources + // kept as history. return cause.cleanupIncomplete ? result.bindCleanupDependencies([cause]) - : result.resolveCleanup(); + : result.bindCleanupReleaseClaim({ + get cleanupReleased() { + return !cause.cleanupIncomplete; + }, + }); }; diff --git a/src/providers/runOwned.deadline.test.ts b/src/providers/runOwned.deadline.test.ts index ef1d876dc59..26835cdb6e7 100644 --- a/src/providers/runOwned.deadline.test.ts +++ b/src/providers/runOwned.deadline.test.ts @@ -16,6 +16,7 @@ import { Deadline } from "../domain/deadline.js"; import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { ok, err, type Result } from "../domain/result.js"; +import { releaseOwnedCleanup } from "../../tests/support/cleanupRelease.js"; import { finalizedResult, runOwned, type Finalized } from "./runOwned.js"; const operation = "fixture_operation"; @@ -286,7 +287,7 @@ it("follows a late close rejection's own retry owner when no leases were supplie // The late owner names the resources still held. expect(finalized.error.cleanupResources).toEqual(["/owned/root"]); // The producer's own retry confirms release; the late failure follows it. - producerCleanup.resolveCleanup(); + releaseOwnedCleanup(producerCleanup); expect(finalized.error.cleanupIncomplete).toBe(false); }); @@ -499,7 +500,7 @@ it("follows a late close rejection whose owner already released before it arrive throw new Error(`expected retained cleanup, got ${finalized.kind}`); // A concurrent retry released the producer's resources before the original // close rejected with that producer's error. - producerCleanup.resolveCleanup(); + releaseOwnedCleanup(producerCleanup); rejectClose(producerCleanup); await new Promise((resolve) => setTimeout(resolve, 0)); expect(finalized.error.cleanupIncomplete).toBe(false); diff --git a/src/providers/runOwned.lifecycle.test.ts b/src/providers/runOwned.lifecycle.test.ts index e64db54bdc9..15c0ea34371 100644 --- a/src/providers/runOwned.lifecycle.test.ts +++ b/src/providers/runOwned.lifecycle.test.ts @@ -11,6 +11,7 @@ import { } from "../domain/analysisErrorCore.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; +import { releaseOwnedCleanup } from "../../tests/support/cleanupRelease.js"; import { err, ok, type Result } from "../domain/result.js"; import { finalizedResult, @@ -186,7 +187,7 @@ const run = async ( primary, recoverCleanup: async () => { if (adopter.lease) await lease.release(); - else typedCleanup.resolveCleanup(); + else releaseOwnedCleanup(typedCleanup); }, }; }; diff --git a/src/providers/runOwned.test.ts b/src/providers/runOwned.test.ts index 9abae9a9fe8..185a2a7f806 100644 --- a/src/providers/runOwned.test.ts +++ b/src/providers/runOwned.test.ts @@ -15,6 +15,7 @@ import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup. import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { err, ok, type Result } from "../domain/result.js"; import { finalizedResult, runOwned } from "./runOwned.js"; +import { releaseOwnedCleanup } from "../../tests/support/cleanupRelease.js"; const value: AnalysisPartialObservation = { kind: "retained-evidence", @@ -125,7 +126,7 @@ it("classifies a producer composite whose primary is a cancellation as cancelled const finalized = await runOwned( async () => err(composite), options(controller, async () => { - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); }), ); expect(finalized).toMatchObject({ @@ -159,7 +160,7 @@ it("publishes recovered completion after cleanup resolves", async () => { const published: AnalysisPartialObservation[] = []; const finalized = await runOwned(async () => err(failure), { ...options(controller, async () => { - failure.resolveCleanup(); + releaseOwnedCleanup(failure); }), recoverCompleted: (_error, observed) => observed.cleanupResolvedByClose ? { value } : undefined, @@ -178,7 +179,7 @@ it("keeps a recovered value when cancellation arrives during its publication", a }); const finalized = await runOwned(async () => err(failure), { ...options(controller, async () => { - failure.resolveCleanup(); + releaseOwnedCleanup(failure); }), recoverCompleted: () => ({ value }), commit: async () => { @@ -200,7 +201,7 @@ it("keeps a cancellation that arrives while a recovered publication fails", asyn const publication = new AnalysisProtocolError("publication failed"); const finalized = await runOwned(async () => err(failure), { ...options(controller, async () => { - failure.resolveCleanup(); + releaseOwnedCleanup(failure); }), recoverCompleted: () => ({ value }), commit: async () => { @@ -223,7 +224,7 @@ it("retains a recovered value when its publication fails", async () => { }); const finalized = await runOwned(async () => err(failure), { ...options(new AbortController(), async () => { - failure.resolveCleanup(); + releaseOwnedCleanup(failure); }), recoverCompleted: () => ({ value }), commit: async () => { diff --git a/src/providers/runOwned.ts b/src/providers/runOwned.ts index 2cb3b61016e..9405db08b5c 100644 --- a/src/providers/runOwned.ts +++ b/src/providers/runOwned.ts @@ -8,7 +8,7 @@ import { primaryAnalysisError, type AnalysisPartialObservation, } from "../domain/analysisErrorBase.js"; -import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { analysisErrorWithCancellation } from "../domain/analysisErrorCancellation.js"; import { AnalysisCancelledError, @@ -458,11 +458,11 @@ export const runOwned = async ( ])) replacement.retainSecondaryFailure(secondary); return replaced.cleanupIncomplete - ? analysisErrorWithCleanupFailure( + ? analysisErrorWithCleanupDependencies( replacement, replaced, options.operation, - ).bindCleanupDependencies([replaced]) + ) : replacement; }; if (budgetElapsed && isAborted(signal)) { @@ -583,11 +583,11 @@ export const runOwned = async ( error: cleanup.failure === outcome.error ? outcome.error - : analysisErrorWithCleanupFailure( + : analysisErrorWithCleanupDependencies( outcome.error, cleanup.failure, options.operation, - ).bindCleanupDependencies([outcome.error, cleanup.failure]), + ), cleanup, }; } diff --git a/tests/boundary/cli/finishAnalysisCommand.test.ts b/tests/boundary/cli/finishAnalysisCommand.test.ts index 1c3aa793d2b..81ec7cc1f65 100644 --- a/tests/boundary/cli/finishAnalysisCommand.test.ts +++ b/tests/boundary/cli/finishAnalysisCommand.test.ts @@ -10,6 +10,7 @@ import { import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js"; import { err, ok } from "../../../src/domain/result.js"; import { scriptCaptureEvidenceFixture } from "../../fixtures/webScriptCapture.js"; +import { releaseOwnedCleanup } from "../../support/cleanupRelease.js"; it("preserves producer-owned cleanup failure when service close does not resolve it", async () => { const evidence = scriptCaptureEvidenceFixture(); @@ -162,7 +163,7 @@ it("keeps the initial failure snapshot when close resolves its cleanup but fails async () => err(primary), { close: async () => { - primary.resolveCleanup(); + releaseOwnedCleanup(primary); controller.abort("cancelled during cleanup retry"); throw new ProviderCleanupError( "fixture-provider", @@ -219,7 +220,7 @@ it.each([false, true])( async () => err(failure), { close: async () => { - failure.resolveCleanup(); + releaseOwnedCleanup(failure); if (cancel) controller.abort("cancelled during successful retry"); }, }, @@ -266,7 +267,7 @@ it.each(["unresolved", "ordinary-partial", "initial-projection"] as const)( async () => err(failure), { close: async () => { - if (kind !== "unresolved") failure.resolveCleanup(); + if (kind !== "unresolved") releaseOwnedCleanup(failure); }, }, "fixture-provider", diff --git a/tests/boundary/cli/reverseEngineeringCommands.test.ts b/tests/boundary/cli/reverseEngineeringCommands.test.ts index 653803ec30a..c2e49e4fe69 100644 --- a/tests/boundary/cli/reverseEngineeringCommands.test.ts +++ b/tests/boundary/cli/reverseEngineeringCommands.test.ts @@ -28,6 +28,7 @@ import { } from "../../support/reverseEngineeringCompositionFixtures.js"; import type { CliInstance } from "../../../src/cli/types.js"; import type { ReverseEngineeringService } from "../../../src/application/reverse/ReverseEngineeringService.js"; +import { releaseOwnedCleanup } from "../../support/cleanupRelease.js"; const originalExitCode = process.exitCode; @@ -342,7 +343,7 @@ it("preserves an independent timeout after cleanup succeeds", async () => { const service = { inspectWithObjdump: vi.fn(async () => err(error)), close: vi.fn(async () => { - error.resolveCleanup(); + releaseOwnedCleanup(error); }), }; @@ -370,7 +371,7 @@ it("does not project cancellation cleanup as incomplete after a successful retry const service = { inspectWithObjdump: vi.fn(async () => err(error)), close: vi.fn(async () => { - error.resolveCleanup(); + releaseOwnedCleanup(error); }), }; diff --git a/tests/boundary/filesystem/binaryTargetCleanup.test.ts b/tests/boundary/filesystem/binaryTargetCleanup.test.ts index ab0684e57f9..feb2af429f8 100644 --- a/tests/boundary/filesystem/binaryTargetCleanup.test.ts +++ b/tests/boundary/filesystem/binaryTargetCleanup.test.ts @@ -19,6 +19,7 @@ import { import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { observed } from "../../fixtures/analysisExecution.js"; +import { releaseOwnedCleanup } from "../../support/cleanupRelease.js"; it.each( [true, false].flatMap((supported) => @@ -163,7 +164,7 @@ it("retries target and provider owners independently through the same MCP connec execute, close: async () => { if (!providerAllowed) return err(providerFailure); - providerFailure.resolveCleanup(); + releaseOwnedCleanup(providerFailure); return ok(null); }, })); diff --git a/tests/boundary/mcp/applicationMcpHarnessLifecycle.test.ts b/tests/boundary/mcp/applicationMcpHarnessLifecycle.test.ts index 27422118c43..288d14519b2 100644 --- a/tests/boundary/mcp/applicationMcpHarnessLifecycle.test.ts +++ b/tests/boundary/mcp/applicationMcpHarnessLifecycle.test.ts @@ -17,6 +17,7 @@ import { } from "../../fixtures/binarySession.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { awaitAcknowledgement } from "../../fixtures/lifecycleAcknowledgement.js"; +import { releaseOwnedCleanup } from "../../support/cleanupRelease.js"; const failureLeaves = (reason: unknown): unknown[] => reason instanceof AggregateError @@ -72,7 +73,7 @@ it("reports a failed session close, joins concurrent attempts and retries the re entered.resolve(); await release.promise; if (!allowClose) return err(failure); - failure.resolveCleanup(); + releaseOwnedCleanup(failure); return ok(null); }); let harness: ApplicationMcpHarness | undefined; @@ -123,7 +124,7 @@ it("preserves independent MCP provider and session close failures and releases e let allowAdbClose = false; const closeBinary = vi.fn(async () => { if (!allowBinaryClose) return err(binaryFailure); - binaryFailure.resolveCleanup(); + releaseOwnedCleanup(binaryFailure); return ok(null); }); const closeAdb = vi.fn(async () => { diff --git a/tests/boundary/mcp/batchSourcePublicationCleanup.test.ts b/tests/boundary/mcp/batchSourcePublicationCleanup.test.ts index ef5208f35d4..5dee3f82833 100644 --- a/tests/boundary/mcp/batchSourcePublicationCleanup.test.ts +++ b/tests/boundary/mcp/batchSourcePublicationCleanup.test.ts @@ -14,6 +14,7 @@ import { createTestProviderRouter } from "../../fixtures/binarySession.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; import { awaitAcknowledgement } from "../../fixtures/lifecycleAcknowledgement.js"; +import { releaseOwnedCleanup } from "../../support/cleanupRelease.js"; const expectRecoveredBatch = (response: CallToolResult, owned: string) => { expect(parseMcpToolError(response).error).toMatchObject({ @@ -97,7 +98,7 @@ it("keeps a batch cleanup owner and its completed prefix after source retention if (!allow) return err(failure); await rm(owned, { recursive: true }); pending = false; - failure.resolveCleanup(); + releaseOwnedCleanup(failure); return ok(null); }, })), diff --git a/tests/boundary/mcp/gdbCancellationMcp.test.ts b/tests/boundary/mcp/gdbCancellationMcp.test.ts index ebe5195eac8..7df48f8c5d5 100644 --- a/tests/boundary/mcp/gdbCancellationMcp.test.ts +++ b/tests/boundary/mcp/gdbCancellationMcp.test.ts @@ -34,6 +34,7 @@ import { validateDebuggerStatusResponse, waitForStartedFile, } from "../../support/reverseDebuggerMcpTestHelpers.js"; +import { releaseOwnedCleanup } from "../../support/cleanupRelease.js"; import { expectNoUnmodeledGdbCommands, FAKE_GDB_SESSION_REPLIES, @@ -579,7 +580,7 @@ it("recovers only the owning debugger cleanup and reopens admitted analysis", as status: () => undefined, close: async (sessionId: string) => { closeCalls.push(sessionId); - if (sessionId === ownerId) retainedFailure.resolveCleanup(); + if (sessionId === ownerId) releaseOwnedCleanup(retainedFailure); return ok({ target_state: "unknown" as const }); }, retryCleanupFailures: async () => ok(null), diff --git a/tests/boundary/mcp/gdbRetirementCancellation.test.ts b/tests/boundary/mcp/gdbRetirementCancellation.test.ts index d8aabbd45a2..849b53c754a 100644 --- a/tests/boundary/mcp/gdbRetirementCancellation.test.ts +++ b/tests/boundary/mcp/gdbRetirementCancellation.test.ts @@ -24,6 +24,7 @@ import { createDeferred, createTestBinarySession, } from "../../fixtures/binarySession.js"; +import { releaseOwnedCleanup } from "../../support/cleanupRelease.js"; it("compares cancellation before dispatch, during retirement, and an uncancelled control", async () => { for (const mode of ["pre-aborted", "during-retirement", "control"] as const) { @@ -277,7 +278,7 @@ it("follows the original owner of a completed mutation's retirement failure", as execute: async () => ok({ operation: "health", value: null }), close: async () => { if (!closed) return err(cleanup); - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); return ok(null); }, }) as never, diff --git a/tests/boundary/mcp/ghidraMcpHarnessLifecycle.test.ts b/tests/boundary/mcp/ghidraMcpHarnessLifecycle.test.ts index d16a8b36720..09d6501649b 100644 --- a/tests/boundary/mcp/ghidraMcpHarnessLifecycle.test.ts +++ b/tests/boundary/mcp/ghidraMcpHarnessLifecycle.test.ts @@ -4,6 +4,7 @@ import { expect, it, vi } from "vitest"; import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js"; import { err, ok } from "../../../src/domain/result.js"; import { connectGhidraMcp } from "./ghidraMcpHarness.js"; +import { releaseOwnedCleanup } from "../../support/cleanupRelease.js"; const failureLeaves = (reason: unknown): unknown[] => reason instanceof AggregateError @@ -18,7 +19,7 @@ it("reports independent cleanup failures and retries only retained owners", asyn let allowProviderClose = false; const closeProvider = vi.fn(async () => { if (!allowProviderClose) return err(providerFailure); - providerFailure.resolveCleanup(); + releaseOwnedCleanup(providerFailure); return ok(null); }); const harness = await connectGhidraMcp("ghidra-harness-close", undefined, { diff --git a/tests/boundary/mcp/providerSelectionMcp.test.ts b/tests/boundary/mcp/providerSelectionMcp.test.ts index a8851c1a3b6..028db7dc37c 100644 --- a/tests/boundary/mcp/providerSelectionMcp.test.ts +++ b/tests/boundary/mcp/providerSelectionMcp.test.ts @@ -46,6 +46,7 @@ import { toolAvailabilityInventory, toolAvailabilitySummaryInventory, } from "../../../src/contracts/toolOutputSchemaPrimitives.js"; +import { releaseOwnedCleanup } from "../../support/cleanupRelease.js"; const resources: Array<{ close(): Promise }> = []; afterEach(async () => { @@ -1715,7 +1716,7 @@ it("retains failed candidate-refresh cleanup while preserving the selected bindi closeOwnedResources: async () => { if (!fail) return ok(null); if (!release) return err(failure); - failure.resolveCleanup(); + releaseOwnedCleanup(failure); return ok(null); }, }, @@ -1791,7 +1792,7 @@ it("retains attributed mixed profile cleanup through registered MCP calls and pa resolveAnalysisProfile: async () => err(failures[id]), closeOwnedResources: async () => { if (!released.has(id)) return err(failures[id]); - failures[id].resolveCleanup(); + releaseOwnedCleanup(failures[id]); return ok(null); }, })); diff --git a/tests/boundary/mcp/webModuleTraceMcp.test.ts b/tests/boundary/mcp/webModuleTraceMcp.test.ts index 8f8c30f2603..11d5f50e3f7 100644 --- a/tests/boundary/mcp/webModuleTraceMcp.test.ts +++ b/tests/boundary/mcp/webModuleTraceMcp.test.ts @@ -21,6 +21,7 @@ import { completedModuleResolverLauncher, webModuleResolverFixture, } from "../../fixtures/webModuleTrace.js"; +import { releaseOwnedCleanup } from "../../support/cleanupRelease.js"; it("publishes valid SDK schemas and records the named module trace without a binary target", async () => { const artifacts = webModuleArtifactsFixture(); @@ -137,12 +138,14 @@ it.each(["opaque", "resolved-typed"] as const)( const unowned = kind === "opaque" ? new Error("unattributed resolver close rejection") - : new ProviderCleanupError( - "fixture-resolver", - [], - { reason: "resolver rejected an already-resolved cleanup error" }, - { operation: "trace_web_module_imports" }, - ).resolveCleanup(); + : releaseOwnedCleanup( + new ProviderCleanupError( + "fixture-resolver", + [], + { reason: "resolver rejected an already-resolved cleanup error" }, + { operation: "trace_web_module_imports" }, + ), + ); const service = new WebModuleTraceService( { load: async () => ok(webModuleArtifactsFixture()), diff --git a/tests/boundary/process/agentEvaluationCommands.test.ts b/tests/boundary/process/agentEvaluationCommands.test.ts index c40fe01de91..b7019197f49 100644 --- a/tests/boundary/process/agentEvaluationCommands.test.ts +++ b/tests/boundary/process/agentEvaluationCommands.test.ts @@ -224,14 +224,16 @@ processTest.for([ import { setTimeout as delay } from "node:timers/promises"; import { DarwinProcessOwnershipInspectionError } from ${JSON.stringify(new URL("../../../dist/process/DarwinProcessRunTokenReader.js", import.meta.url).href)}; import { ProviderCleanupError } from ${JSON.stringify(new URL("../../../dist/domain/providerCleanupError.js", import.meta.url).href)}; + import { AnalysisCleanupRelease } from ${JSON.stringify(new URL("../../../dist/domain/analysisCleanupRelease.js", import.meta.url).href)}; let prepared = false; - const cleanup = new ProviderCleanupError("fixture", ["darwin-fixture-reader"], { reason: "fixture preparation cleanup denied" }); + const release = new AnalysisCleanupRelease(); + const cleanup = release.bind(new ProviderCleanupError("fixture", ["darwin-fixture-reader"], { reason: "fixture preparation cleanup denied" })); const preparation = new DarwinProcessOwnershipInspectionError("fixture preparation failure", { cleanupFailure: cleanup, cleanupOwner: { close: async () => { await writeFile(${JSON.stringify(retried)}, "exact preparation owner retried"); if (${String(incomplete)}) throw new Error("fixture preparation cleanup denied"); - cleanup.resolveCleanup(); + release.confirm(); } }, }); export class OwnedCommandFailure extends Error { diff --git a/tests/boundary/process/artifactSelectedCommand.test.ts b/tests/boundary/process/artifactSelectedCommand.test.ts index 9e9f4da671a..9963ddb40d8 100644 --- a/tests/boundary/process/artifactSelectedCommand.test.ts +++ b/tests/boundary/process/artifactSelectedCommand.test.ts @@ -34,6 +34,7 @@ import { readStableArtifact } from "../../../src/artifacts/readStableArtifact.js import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js"; import type { LinuxResourceLimits } from "../../../src/process/LinuxResourceLimits.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { releaseOwnedCleanup } from "../../support/cleanupRelease.js"; // Real children and filesystem, with simulated Linux admission/limits. These // scripts do not establish native TShark, sigrok or prlimit behavior. @@ -550,6 +551,6 @@ it.skipIf(process.platform === "win32")( await expect(retained?.stop()).resolves.toMatchObject({ status: "verified-cleanup", }); - expect(failed.resolveCleanup().cleanupIncomplete).toBe(false); + expect(releaseOwnedCleanup(failed).cleanupIncomplete).toBe(false); }, ); diff --git a/tests/boundary/process/ghidraJavaLifecycle.test.ts b/tests/boundary/process/ghidraJavaLifecycle.test.ts index d2527d8433e..173c831b2b6 100644 --- a/tests/boundary/process/ghidraJavaLifecycle.test.ts +++ b/tests/boundary/process/ghidraJavaLifecycle.test.ts @@ -13,6 +13,7 @@ import { } from "../../../src/process/ProcessOwnershipObservation.js"; import { createInspectionResources } from "../../fixtures/inspectionResources.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { releaseOwnedCleanup } from "../../support/cleanupRelease.js"; // Real, idle Node processes stand in for Java. These controls exercise POSIX // process ownership and complete-output semantics, not a JVM or Ghidra. @@ -298,7 +299,7 @@ it("retains only the preparation owner's exact failed root through cancellation close: async () => { closes++; if (denied) throw cleanup; - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); }, }, }, diff --git a/tests/boundary/process/ghidraJavaProbePreparation.test.ts b/tests/boundary/process/ghidraJavaProbePreparation.test.ts index f7f44573ff8..9d40e3d02b2 100644 --- a/tests/boundary/process/ghidraJavaProbePreparation.test.ts +++ b/tests/boundary/process/ghidraJavaProbePreparation.test.ts @@ -17,6 +17,7 @@ import { import { createInspectionResources } from "../../fixtures/inspectionResources.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { waitForProcessOwnershipInspection } from "../../../src/process/ProcessInspectionCancellation.js"; +import { releaseOwnedCleanup } from "../../support/cleanupRelease.js"; // Long enough for an ordinary owned launch, short enough to keep the cold case quick. const PROBE_TIMEOUT_MS = 2_000; @@ -186,7 +187,7 @@ it.runIf(process.platform === "darwin")( let denied = true; const close = vi.fn(async () => { if (denied) throw cleanup; - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); }); vi.spyOn(systemProcessOwnershipHost, "prepare").mockImplementation( async () => { diff --git a/tests/boundary/providers/CutterBridgeService.test.ts b/tests/boundary/providers/CutterBridgeService.test.ts index 24a3920e29f..19f04c4e41f 100644 --- a/tests/boundary/providers/CutterBridgeService.test.ts +++ b/tests/boundary/providers/CutterBridgeService.test.ts @@ -6,6 +6,7 @@ import { AnalysisCancelledError, } from "../../../src/domain/analysisErrorCore.js"; import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js"; +import { releaseOwnedCleanup } from "../../support/cleanupRelease.js"; const cutterInput = { session_id: "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a", @@ -72,7 +73,7 @@ it.each(["descriptor-first", "command-first"] as const)( }, }); if (order === "descriptor-first") { - descriptor.resolveCleanup(); + releaseOwnedCleanup(descriptor); expect(retried.error.cleanupResources).toEqual([ `cutter-session:${cutterInput.session_id}`, ]); @@ -91,7 +92,7 @@ it.each(["descriptor-first", "command-first"] as const)( expect(dispatched.error.cleanupIncomplete).toBe(false); expect(retried.error.cleanupIncomplete).toBe(true); expect(retried.error.cleanupResources).toEqual(["descriptor-fixture"]); - descriptor.resolveCleanup(); + releaseOwnedCleanup(descriptor); } expect(retried.error.cleanupIncomplete).toBe(false); expect(retried.error.cleanupResources).toEqual([]); @@ -587,11 +588,11 @@ it.each(["descriptor-first", "command-first"])( throw new Error("Expected typed mixed cleanup"); expect(mixed.cleanupIncomplete).toBe(true); expect(close).not.toHaveBeenCalled(); - if (order === "descriptor-first") descriptorFailure.resolveCleanup(); + if (order === "descriptor-first") releaseOwnedCleanup(descriptorFailure); else terminal = true; await expect(service.close()).rejects.toBeInstanceOf(AnalysisError); expect(mixed.cleanupIncomplete).toBe(true); - descriptorFailure.resolveCleanup(); + releaseOwnedCleanup(descriptorFailure); terminal = true; await service.close(); expect(dispatched.error.cleanupIncomplete).toBe(false); diff --git a/tests/boundary/providers/ghidra/ghidraLaunchOutcome.test.ts b/tests/boundary/providers/ghidra/ghidraLaunchOutcome.test.ts index 5543f56081a..7fe758a76ae 100644 --- a/tests/boundary/providers/ghidra/ghidraLaunchOutcome.test.ts +++ b/tests/boundary/providers/ghidra/ghidraLaunchOutcome.test.ts @@ -23,6 +23,7 @@ import { import { GhidraLaunchSupportError } from "../../../../src/ghidra/GhidraJavaLaunch.js"; import { ExecFileOutputCancelledError } from "../../../../src/process/ExecFileOutput.js"; import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js"; +import { releaseOwnedCleanup } from "../../../support/cleanupRelease.js"; const launch = async ( javaLaunch: NonNullable< @@ -352,7 +353,7 @@ it("keeps the cancellation primary through retained Darwin preparation cleanup a cleanupOwner: { close: async () => { if (denied) throw cleanup; - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); }, }, }); diff --git a/tests/boundary/providers/hopper/hopperFileOffsetClose.test.ts b/tests/boundary/providers/hopper/hopperFileOffsetClose.test.ts index 49e6d5783dc..be51702182b 100644 --- a/tests/boundary/providers/hopper/hopperFileOffsetClose.test.ts +++ b/tests/boundary/providers/hopper/hopperFileOffsetClose.test.ts @@ -25,6 +25,7 @@ import { silentLogger } from "../../../../src/logger.js"; import { err, ok } from "../../../../src/domain/result.js"; import { HopperClient } from "../../../../src/hopper/HopperClient.js"; import { HopperProvider } from "../../../../src/hopper/HopperProvider.js"; +import { releaseOwnedCleanup } from "../../../support/cleanupRelease.js"; const state = vi.hoisted(() => ({ path: "", @@ -288,7 +289,7 @@ it("clears a combined Hopper close only after the descriptor and session release ]); expect(call).toHaveBeenCalledTimes(1); - session.resolveCleanup(); + releaseOwnedCleanup(session); expect(session.cleanupIncomplete).toBe(false); expect(combined.error.cleanupIncomplete).toBe(true); expect(combined.error.cleanupResources).toEqual([state.path]); diff --git a/tests/boundary/providers/kuna/kunaQueryCancellation.test.ts b/tests/boundary/providers/kuna/kunaQueryCancellation.test.ts index e5b5832394f..7e600c20b92 100644 --- a/tests/boundary/providers/kuna/kunaQueryCancellation.test.ts +++ b/tests/boundary/providers/kuna/kunaQueryCancellation.test.ts @@ -9,6 +9,7 @@ import { import { ProviderCleanupError } from "../../../../src/domain/providerCleanupError.js"; import { err, ok, type Result } from "../../../../src/domain/result.js"; import type { AnalysisError } from "../../../../src/domain/analysisErrorBase.js"; +import { releaseOwnedCleanup } from "../../../support/cleanupRelease.js"; // These controls exercise shared wait semantics without executing commands or opening files. const fixture = () => { @@ -121,7 +122,7 @@ it.each(["physical", "cancel-with-cleanup"] as const)( expect(result.error.capturedOutput).toEqual(output); if (kind === "cancel-with-cleanup") { expect(result.error.cleanupIncomplete).toBe(true); - primary.resolveCleanup(); + releaseOwnedCleanup(primary); expect(result.error.cleanupIncomplete).toBe(false); } }, diff --git a/tests/boundary/providers/kuna/kunaQueryErrors.test.ts b/tests/boundary/providers/kuna/kunaQueryErrors.test.ts index de8bde40a95..57615a9f74b 100644 --- a/tests/boundary/providers/kuna/kunaQueryErrors.test.ts +++ b/tests/boundary/providers/kuna/kunaQueryErrors.test.ts @@ -11,6 +11,7 @@ import { ProviderCleanupError } from "../../../../src/domain/providerCleanupErro import { analysisErrorWithCleanupFailure } from "../../../../src/domain/analysisErrorCleanup.js"; import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js"; import { createEvidence } from "../../../../src/domain/evidence.js"; +import { releaseOwnedCleanup } from "../../../support/cleanupRelease.js"; const capturedOutput = { stdout: "selected output", @@ -94,7 +95,7 @@ it.each([ resources = ["two"]; for (const caller of callers) expect(caller.cleanupResources).toEqual(["two"]); - source.resolveCleanup(); + releaseOwnedCleanup(source); for (const caller of callers) expect(caller.cleanupIncomplete).toBe(false); }, ); @@ -106,7 +107,7 @@ it("does not resurrect an already resolved cleanup failure", () => { {}, { operation: "kuna:strings" }, ); - source.resolveCleanup(); + releaseOwnedCleanup(source); const caller = kunaQueryFailureForCaller(source, "search_strings"); expect(caller.cleanupIncomplete).toBe(false); }); @@ -143,7 +144,7 @@ it("restores a caller-attributed typed primary after its exact cleanup owner res operation: "search_procedures", timeoutMs: 23, }); - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); expect(projectAnalysisError(caller)).toMatchObject({ code: "provider_timeout", details: { diff --git a/tests/boundary/providers/kuna/kunaWorkspaceRollback.test.ts b/tests/boundary/providers/kuna/kunaWorkspaceRollback.test.ts index 4bd33629812..56287394a9c 100644 --- a/tests/boundary/providers/kuna/kunaWorkspaceRollback.test.ts +++ b/tests/boundary/providers/kuna/kunaWorkspaceRollback.test.ts @@ -20,6 +20,7 @@ import { ProviderCleanupError } from "../../../../src/domain/providerCleanupErro import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js"; import { awaitAcknowledgement } from "../../../fixtures/lifecycleAcknowledgement.js"; import { session } from "./kunaSessionFixture.js"; +import { releaseOwnedCleanup } from "../../../support/cleanupRelease.js"; const it = test.skipIf(process.platform === "win32"); @@ -230,7 +231,7 @@ it.each([ roots.mockRestore(); if (reason instanceof ProviderCleanupError) { expect((await commands.prepare()).ok).toBe(false); - reason.resolveCleanup(); + releaseOwnedCleanup(reason); // Observe the settled cached failure before admitting a fresh allocation. const settled = await commands.prepare(); expect(settled).toEqual({ ok: false, error: reason }); diff --git a/tests/boundary/providers/native/lldbPrelaunchCleanup.test.ts b/tests/boundary/providers/native/lldbPrelaunchCleanup.test.ts index 56f2db9e7aa..fb01f23ac9e 100644 --- a/tests/boundary/providers/native/lldbPrelaunchCleanup.test.ts +++ b/tests/boundary/providers/native/lldbPrelaunchCleanup.test.ts @@ -12,6 +12,7 @@ import { NativeCommandFailure } from "../../../../src/native/CommandRunner.js"; import { LldbCallTracer } from "../../../../src/native/LldbCallTracer.js"; import { DarwinProcessOwnershipInspectionError } from "../../../../src/process/DarwinProcessRunTokenReader.js"; import * as processBoundary from "../../../../src/process/ProviderProcess.js"; +import { releaseOwnedCleanup } from "../../../support/cleanupRelease.js"; const tool = { invocationPath: "/usr/bin/true", @@ -34,7 +35,7 @@ const preparation = (cancellation?: { readonly reason: unknown }) => { { reason: "controlled root deletion failure" }, ); const close = vi.fn(async () => { - marker.resolveCleanup(); + releaseOwnedCleanup(marker); }); const failure = new DarwinProcessOwnershipInspectionError( "controlled compiler failure", @@ -168,6 +169,11 @@ it("retries the tracer-owned resolver supervisor before another trace", async () expect(stop).toHaveBeenCalledTimes(2); failStop = false; + // The supervisor's own stop completes the marker and the returned error + // before the tracer retries anything. + expect((await supervisor.stop()).status).not.toBe("incomplete"); + expect(marker.cleanupIncomplete).toBe(false); + expect(result.error.cleanupIncomplete).toBe(false); const released = await tracer.close(); expect(released.ok).toBe(true); expect(marker.cleanupIncomplete).toBe(false); diff --git a/tests/boundary/providers/native/nativeCommandTermination.test.ts b/tests/boundary/providers/native/nativeCommandTermination.test.ts index 8fdbeba7e36..93a4def7f55 100644 --- a/tests/boundary/providers/native/nativeCommandTermination.test.ts +++ b/tests/boundary/providers/native/nativeCommandTermination.test.ts @@ -186,6 +186,14 @@ it.skipIf(process.platform === "win32")( ); expect(launches).toBe(2); + // Stopping one retained supervisor directly completes only its own marker, + // before the runner retries anything. + const firstOwner = first.error.cleanupOwner; + expect(first.error.cleanupMarker?.cleanupIncomplete).toBe(true); + expect((await firstOwner?.stop())?.status).not.toBe("incomplete"); + expect(first.error.cleanupMarker?.cleanupIncomplete).toBe(false); + expect(second.error.cleanupMarker?.cleanupIncomplete).toBe(true); + const cleared = await runner.retryCleanup?.(); expect(cleared).toEqual([]); expect(cleanupCalls).toEqual( diff --git a/tests/boundary/providers/native/nativeProvider.test.ts b/tests/boundary/providers/native/nativeProvider.test.ts index 85cb1423034..b187db55011 100644 --- a/tests/boundary/providers/native/nativeProvider.test.ts +++ b/tests/boundary/providers/native/nativeProvider.test.ts @@ -55,6 +55,7 @@ import { nativeMachoTargetForFile, nativeResolvedToolFixture, } from "../../../fixtures/nativeCommands.js"; +import { releaseOwnedCleanup } from "../../../support/cleanupRelease.js"; /** The file runner identifies selected .plist inputs as XML. */ const writeFixturePlist = async (path: string): Promise => { @@ -1243,7 +1244,7 @@ describe("native command failure projection", () => { const result = await client.execute("list_architectures", {}); if (result.ok) throw new Error("Expected native command failure"); expect(result.error.cleanupIncomplete).toBe(true); - marker.resolveCleanup(); + releaseOwnedCleanup(marker); expect(result.error.cleanupIncomplete).toBe(true); expect(result.error.cleanupResources).toEqual([ "run:known", @@ -1976,7 +1977,7 @@ it("does not reopen a resolved preparation cleanup marker or invent absent compi "controlled preparation failure", { capturedOutput, cleanupFailure: marker }, ); - marker.resolveCleanup(); + releaseOwnedCleanup(marker); const failure = new NativeCommandFailure("swift-demangle", "io", null, { cause: inspection, }); @@ -2033,7 +2034,7 @@ it("retains an owned preparation cleanup marker when the command deadline expire _tag: "AnalysisTimeoutError", cause: failure, }); - marker.resolveCleanup(); + releaseOwnedCleanup(marker); expect(result.error.cleanupIncomplete).toBe(false); } finally { await client.close(); @@ -2084,7 +2085,7 @@ it("reports the selected command deadline when preparation times out", async () expect(projected.remediation.action).toContain( `${String(NATIVE_COMMAND_OUTPUT_BUDGET_BYTES)}-byte command output allowance`, ); - marker.resolveCleanup(); + releaseOwnedCleanup(marker); expect(result.error.cleanupIncomplete).toBe(false); } finally { await client.close(); diff --git a/tests/boundary/providers/ownedCommandCleanup.test.ts b/tests/boundary/providers/ownedCommandCleanup.test.ts index c2a96256747..1a1072882d9 100644 --- a/tests/boundary/providers/ownedCommandCleanup.test.ts +++ b/tests/boundary/providers/ownedCommandCleanup.test.ts @@ -5,6 +5,7 @@ import { OwnedCommandFailure } from "../../../src/process/OwnedCommand.js"; import { retainOwnedCommandCleanup } from "../../../src/providers/OwnedCommandCleanup.js"; import { createInspectionResources } from "../../fixtures/inspectionResources.js"; import { ArtifactResourceRetryFailure } from "../../../src/artifacts/ArtifactResourceScope.js"; +import { releaseOwnedCleanup } from "../../support/cleanupRelease.js"; it("retains every owned label without inventing a missing cleanup capability", async () => { // Model unavailable capabilities only; these labels name no real resources. @@ -52,7 +53,7 @@ it("reports only live helper peers across partial cleanup and retry", async () = throw cleanup; } labels = []; - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); }, }, }, @@ -75,7 +76,7 @@ it("reports only live helper peers across partial cleanup and retry", async () = expect(cleanup.cleanupIncomplete).toBe(false); } finally { labels = []; - cleanup.resolveCleanup(); + releaseOwnedCleanup(cleanup); await resources.close(); } }); diff --git a/tests/boundary/sqlite/sqliteDatabaseFailures.test.ts b/tests/boundary/sqlite/sqliteDatabaseFailures.test.ts index 837075aa94e..c7ff5ab4ee0 100644 --- a/tests/boundary/sqlite/sqliteDatabaseFailures.test.ts +++ b/tests/boundary/sqlite/sqliteDatabaseFailures.test.ts @@ -4,6 +4,7 @@ import { OwnedCommandFailure } from "../../../src/process/OwnedCommand.js"; import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js"; import { sqliteDatabaseFailure } from "../../../src/sqlite/SqliteDatabaseFailures.js"; import { SQLITE_DATABASE_LIMITS } from "../../../src/sqlite/SqliteDatabaseLimits.js"; +import { releaseOwnedCleanup } from "../../support/cleanupRelease.js"; it.each([null, "owned stop unconfirmed"])( "preserves a selected worker deadline with cleanup=%s", @@ -61,7 +62,7 @@ it.each([null, "owned stop unconfirmed"])( _tag: "AnalysisTimeoutError", timeoutMs: 1234, }); - failure.resolveCleanup(); + releaseOwnedCleanup(failure); const resolved = projectAnalysisError(failure); expect(resolved).toMatchObject({ code: "provider_timeout", diff --git a/tests/composition/analysis-sessions/binarySession.test.ts b/tests/composition/analysis-sessions/binarySession.test.ts index de05296e045..a187d18b810 100644 --- a/tests/composition/analysis-sessions/binarySession.test.ts +++ b/tests/composition/analysis-sessions/binarySession.test.ts @@ -37,6 +37,7 @@ import { } from "node:fs/promises"; import { dirname, extname, join } from "node:path"; import { describe, expect, it, onTestFinished, vi } from "vitest"; +import { releaseOwnedCleanup } from "../../support/cleanupRelease.js"; const client = (fail = false): AnalysisClient => ({ execute: () => Promise.resolve(fail ? err(new HopperStartError()) : ok(null)), @@ -1959,7 +1960,7 @@ it("blocks analysis rebinding until the external writer cleanup settles", async ).toEqual(err(failure)); expect(anotherMutation).not.toHaveBeenCalled(); // Only the resource owner may acknowledge completed cleanup. - failure.resolveCleanup(); + releaseOwnedCleanup(failure); expect((await session.open(target)).ok).toBe(true); await session.close(); }); diff --git a/tests/process-global/binaryDiagnosticsCliCleanup.test.ts b/tests/process-global/binaryDiagnosticsCliCleanup.test.ts index 29a5c1d23d0..52ed00155f7 100644 --- a/tests/process-global/binaryDiagnosticsCliCleanup.test.ts +++ b/tests/process-global/binaryDiagnosticsCliCleanup.test.ts @@ -9,6 +9,7 @@ import { AnalysisOutputError } from "../../src/domain/analysisErrorCore.js"; import { ProviderCleanupError } from "../../src/domain/providerCleanupError.js"; import { err } from "../../src/domain/result.js"; import { analysisErrorWithCleanupFailure } from "../../src/domain/analysisErrorCleanup.js"; +import { releaseOwnedCleanup } from "../support/cleanupRelease.js"; const exitCode = process.exitCode; afterEach(() => { @@ -45,7 +46,7 @@ it.each( cleanup, "inspect_binary_layout", ).bindCleanupDependencies([primary, cleanup]); - if (recovered) cleanup.resolveCleanup(); + if (recovered) releaseOwnedCleanup(cleanup); const inspectAndClose = vi.fn(async () => err(composed)); const identity = { id: "fixture-decoder", diff --git a/tests/process-global/historicalCaptureSnapshotRedaction.test.ts b/tests/process-global/historicalCaptureSnapshotRedaction.test.ts index 8421d2cf43c..fab8140ac0c 100644 --- a/tests/process-global/historicalCaptureSnapshotRedaction.test.ts +++ b/tests/process-global/historicalCaptureSnapshotRedaction.test.ts @@ -46,6 +46,7 @@ import { ProviderCleanupError } from "../../src/domain/providerCleanupError.js"; import { analysisErrorWithCleanupFailure } from "../../src/domain/analysisErrorCleanup.js"; import { err } from "../../src/domain/result.js"; import { deliverCliAnalysisEvidence } from "../../src/cli/analysisEvidenceDelivery.js"; +import { releaseOwnedCleanup } from "../support/cleanupRelease.js"; const services: WebNetworkCaptureService[] = []; afterEach(async () => { @@ -256,7 +257,7 @@ it.each(["captured", "over-capacity"] as const)( ); expect(JSON.stringify(projected)).not.toContain("private-read-marker"); expect(JSON.stringify(projected)).not.toContain(snapshot.sha256); - composed.resolveCleanup(); + releaseOwnedCleanup(composed); const finalized = projectAnalysisError(nestedResult.error); expect(finalized.details?.partial_observation).toEqual(expected); }, diff --git a/tests/support/cleanupRelease.ts b/tests/support/cleanupRelease.ts new file mode 100644 index 00000000000..631b93a4f35 --- /dev/null +++ b/tests/support/cleanupRelease.ts @@ -0,0 +1,14 @@ +import { AnalysisCleanupRelease } from "../../src/domain/analysisCleanupRelease.js"; +import type { AnalysisError } from "../../src/domain/analysisErrorBase.js"; + +/** + * Act as the owner of `error`'s own resources and record their confirmed + * release. Errors composed from it read the release when asked; dependencies + * bound to `error` keep their own records. + */ +export const releaseOwnedCleanup = (error: T): T => { + const release = new AnalysisCleanupRelease(); + release.bind(error); + release.confirm(); + return error; +};