diff --git a/scripts/verify/architecture-guard-baselines.json b/scripts/verify/architecture-guard-baselines.json index a393baaf8b..4173336d9e 100644 --- a/scripts/verify/architecture-guard-baselines.json +++ b/scripts/verify/architecture-guard-baselines.json @@ -180,24 +180,16 @@ "src/browser/PlaywrightScenarioRequest.ts": 1 }, "cleanup-resolve-push": { - "src/android/JadxProvider.ts": 2, - "src/application/binary/AnalysisProviderRegistry.ts": 1, - "src/application/binary/BinarySession.ts": 1, "src/application/desktop/DesktopBuildComputers.ts": 1, "src/application/desktop/DesktopRemoteTaskReaders.ts": 1, "src/application/desktop/DesktopTaskReaderCleanup.ts": 1, - "src/application/reverse/ReverseEngineeringService.ts": 1, "src/browser/WebSourceMapFetcher.ts": 2, - "src/cutter/CutterBridgeService.ts": 1, "src/desktop/AgentEnvSolveHelper.ts": 2, "src/desktop/BuildComputerLongRuns.ts": 1, - "src/ida/IdaSessionClient.ts": 1, - "src/javascript/sourceMaps/SourceMapCommand.ts": 1, "src/kuna/KunaProjectCache.ts": 1, "src/native/CommandRunner.ts": 1, "src/native/LldbCallTracer.ts": 1, - "src/providers/AnalysisClientFailure.ts": 1, - "src/sqlite/SqliteDatabaseProvider.ts": 2 + "src/providers/AnalysisClientFailure.ts": 1 }, "cleanup-dependency-binding": { "src/android/JadxConfiguration.ts": 1, @@ -285,7 +277,7 @@ "src/ida/IdaSessionClient.ts": 2, "src/inspector/V8InspectorProvider.ts": 1, "src/javascript/analysis/JavaScriptAnalysisWorker.ts": 1, - "src/javascript/sourceMaps/SourceMapCommand.ts": 5, + "src/javascript/sourceMaps/SourceMapCommand.ts": 4, "src/jeb/JebMcpConnectionOwner.ts": 1, "src/jeb/JebProvider.ts": 2, "src/kuna/KunaProjectCache.ts": 2, diff --git a/src/android/JadxProvider.ts b/src/android/JadxProvider.ts index 873296d4bf..c8eddfccf1 100644 --- a/src/android/JadxProvider.ts +++ b/src/android/JadxProvider.ts @@ -14,6 +14,7 @@ import { join } from "node:path"; import { fileURLToPath } from "node:url"; import type { AndroidAnalysisPort } from "../application/android/AndroidAnalysisPort.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; +import { AnalysisCleanupRelease } from "../domain/analysisCleanupRelease.js"; import { AnalysisCapabilityUnavailableError, AnalysisInputError, @@ -131,9 +132,13 @@ interface PendingCleanup { session: JadxSession | undefined; root: JadxWorkspaceRoot | undefined; readonly fileHandles: Map; + /** Reports admission failure; bound to `descriptorRelease`. */ readonly previousError: AnalysisError | undefined; + /** Confirmed once every descriptor owner from the admission close failure closes. */ + readonly descriptorRelease: AnalysisCleanupRelease; + /** Confirmed once this whole retained cleanup completes; errors it reported read it. */ + readonly release: AnalysisCleanupRelease; readonly operationCause: unknown; - reportedErrors: WeakRef[]; } /** Every descriptor owner nested in one rejected close, without treating a later owner as the first. */ @@ -165,18 +170,20 @@ const cleanupFailure = ( resources: PendingCleanup, cleanup: ProviderCleanupError, ): AnalysisError => - (resources.previousError === undefined - ? cleanup - : analysisErrorWithCleanupFailure( - resources.previousError, - cleanup, - resources.operation, - ) - ).bindCleanupResourceOwner({ - get cleanupResources() { - return cleanupResources(resources); - }, - }); + resources.release.bind( + (resources.previousError === undefined + ? cleanup + : analysisErrorWithCleanupFailure( + resources.previousError, + cleanup, + resources.operation, + ) + ).bindCleanupResourceOwner({ + get cleanupResources() { + return cleanupResources(resources); + }, + }), + ); const cleanup = async ( resources: PendingCleanup, @@ -208,7 +215,7 @@ const cleanup = async ( trackedInMap.length > 0 && trackedInMap.every((candidate) => !resources.fileHandles.has(candidate)) ) - resources.previousError?.resolveCleanup(); + resources.descriptorRelease.confirm(); } catch (cause: unknown) { fileCloseCauses.push(cause); } @@ -434,8 +441,9 @@ export class JadxProvider implements AndroidAnalysisPort { root: this.#retained.root, fileHandles: new Map(), previousError: undefined, + descriptorRelease: new AnalysisCleanupRelease(), + release: new AnalysisCleanupRelease(), operationCause: undefined, - reportedErrors: [], }; this.#retained = undefined; } @@ -443,17 +451,8 @@ export class JadxProvider implements AndroidAnalysisPort { const pending = this.#pendingCleanup; const result = await cleanup(pending); if (result.ok) { - for (const reportedError of pending.reportedErrors) - reportedError.deref()?.resolveCleanup(); - pending.reportedErrors = []; + pending.release.confirm(); this.#pendingCleanup = undefined; - } else { - pending.reportedErrors = [ - ...pending.reportedErrors.filter( - (reportedError) => reportedError.deref() !== undefined, - ), - new WeakRef(result.error), - ]; } return result; } @@ -731,19 +730,25 @@ export class JadxProvider implements AndroidAnalysisPort { root ??= this.#retained?.root; session ??= this.#retained?.session; this.#retained = undefined; + // The admission failure reads its descriptors' release however it is + // first projected: by a cleanup failure or returned on its own. + const descriptorRelease = new AnalysisCleanupRelease(); + const admissionFailure = (): AnalysisError => + descriptorRelease.bind(failure()); this.#pendingCleanup = { operation: request.operation, session, root, fileHandles, get previousError() { - return failure(); + return admissionFailure(); }, + descriptorRelease, + release: new AnalysisCleanupRelease(), operationCause: cause, - reportedErrors: [], }; const retired = await this.#retire(); - return retired.ok ? err(failure()) : retired; + return retired.ok ? err(admissionFailure()) : retired; } } } diff --git a/src/application/binary/AnalysisProviderRegistry.ts b/src/application/binary/AnalysisProviderRegistry.ts index dccb4f16df..70a9707e61 100644 --- a/src/application/binary/AnalysisProviderRegistry.ts +++ b/src/application/binary/AnalysisProviderRegistry.ts @@ -23,6 +23,7 @@ import { carriedReason, } from "../../domain/analysisErrorCore.js"; import { AnalysisError } from "../../domain/analysisErrorBase.js"; +import { AnalysisCleanupRelease } from "../../domain/analysisCleanupRelease.js"; import { ProviderSelectionError, type ProviderSelectionErrorOptions, @@ -135,9 +136,10 @@ export class AnalysisProviderRegistry { > >(); readonly #selectionCleanup = new Set(); + /** Each candidate's unconfirmed resource close; its failures read it. */ readonly #candidateCleanup = new Map< AnalysisProviderCandidate, - Set + AnalysisCleanupRelease >(); readonly #profileResources = new ArtifactResourceScope(); readonly #profileOwner: RetainedResourceScope = { @@ -270,8 +272,7 @@ export class AnalysisProviderRegistry { result = err(cause); } if (result.ok) { - for (const failure of this.#candidateCleanup.get(provider) ?? []) - failure.resolveCleanup(); + this.#candidateCleanup.get(provider)?.confirm(); this.#candidateCleanup.delete(provider); } else { const failure = @@ -293,9 +294,10 @@ export class AnalysisProviderRegistry { }, ); failures.push(failure); - const retained = this.#candidateCleanup.get(provider) ?? new Set(); - retained.add(failure); - this.#candidateCleanup.set(provider, retained); + const release = + this.#candidateCleanup.get(provider) ?? new AnalysisCleanupRelease(); + release.bind(failure); + this.#candidateCleanup.set(provider, release); this.#selectionCleanup.add(failure); } } diff --git a/src/application/binary/BinarySession.ts b/src/application/binary/BinarySession.ts index f04a9d0913..c7f2bdd9d4 100644 --- a/src/application/binary/BinarySession.ts +++ b/src/application/binary/BinarySession.ts @@ -13,6 +13,7 @@ import { } from "../../domain/savedAnalysisSnapshot.js"; import type { BinaryTarget } from "../../domain/binaryTargetTypes.js"; +import { AnalysisCleanupRelease } from "../../domain/analysisCleanupRelease.js"; import { analysisProfilesEqual, type AnalysisProfileCommitment, @@ -131,6 +132,18 @@ const sessionCleanupFailure = ( : failure; }; +/** + * Let a cleanup failure the client's close reported read that close. A failure + * whose cleanup already follows its own owner keeps reading that owner. + */ +const bindClientRelease = ( + release: AnalysisCleanupRelease, + failure: AnalysisError, +): void => { + if (failure.cleanupIncomplete && !failure.hasCleanupOwner) + release.bind(failure); +}; + const trackCleanupFailures = ( signal: AbortSignal | undefined, operation: string, @@ -197,7 +210,8 @@ export class BinarySession | { readonly run: SessionRun; readonly retainDocument: boolean; - readonly failures: Set; + /** Confirmed by the client's close; failures it reported read it. */ + readonly release: AnalysisCleanupRelease; } | undefined; #transition: Promise = Promise.resolve(); @@ -1196,7 +1210,7 @@ export class BinarySession this.#pendingCleanup = { run, retainDocument: options.retainDocument === true, - failures: new Set(), + release: new AnalysisCleanupRelease(), }; return this.#retryPendingCleanup( options.progress, @@ -1223,18 +1237,15 @@ export class BinarySession ...(progress === undefined ? {} : { progress }), ...(pending.retainDocument ? { retainDocument: true } : {}), onCleanupFailure: (failure) => { - if (failure.cleanupIncomplete) pending.failures.add(failure); + bindClientRelease(pending.release, failure); onCleanupFailure?.(failure); }, }, ); if (closed.ok) { - for (const failure of pending.failures) - if (!failure.hasCleanupOwner) failure.resolveCleanup(); + pending.release.confirm(); this.#pendingCleanup = undefined; - } else if (closed.error.cleanupIncomplete) { - pending.failures.add(closed.error); - } + } else bindClientRelease(pending.release, closed.error); return closed; } diff --git a/src/application/reverse/ReverseEngineeringService.ts b/src/application/reverse/ReverseEngineeringService.ts index 257dcaa243..2914b524e0 100644 --- a/src/application/reverse/ReverseEngineeringService.ts +++ b/src/application/reverse/ReverseEngineeringService.ts @@ -36,6 +36,7 @@ import { AnalysisError, type AnalysisCleanupObservation, } from "../../domain/analysisErrorBase.js"; +import { AnalysisCleanupRelease } from "../../domain/analysisCleanupRelease.js"; import { ProviderAdapterError } from "../../domain/providerAdapterError.js"; import { createEvidence, type Evidence } from "../../domain/evidence.js"; import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js"; @@ -233,7 +234,8 @@ export class ReverseEngineeringService { ProviderProcessSupervisor, { readonly observation: AnalysisCleanupObservation; - readonly failures: Set; + /** Confirmed by a later verified stop; retry failures read it. */ + readonly release: AnalysisCleanupRelease; readonly retryFailure?: AnalysisError; } >(); @@ -260,7 +262,9 @@ export class ReverseEngineeringService { (owner, cleanup) => this.#pendingCleanup.set(owner, { observation: cleanup, - failures: this.#pendingCleanup.get(owner)?.failures ?? new Set(), + release: + this.#pendingCleanup.get(owner)?.release ?? + new AnalysisCleanupRelease(), }), ); this.#digest = options.digest ?? digestFile; @@ -305,21 +309,22 @@ export class ReverseEngineeringService { }; let retryFailure = retained.retryFailure; if (retryFailure === undefined) { - retryFailure = new AnalysisOutputError( - operation, - "A previous provider process still requires cleanup.", - { cleanup: observation }, + retryFailure = retained.release.bind( + new AnalysisOutputError( + operation, + "A previous provider process still requires cleanup.", + { cleanup: observation }, + ), ); - retained.failures.add(retryFailure); } this.#pendingCleanup.set(owner, { observation, - failures: retained.failures, + release: retained.release, retryFailure, }); if (failure === undefined) failure = retryFailure; } else { - for (const previous of retained.failures) previous.resolveCleanup(); + retained.release.confirm(); this.#pendingCleanup.delete(owner); } } @@ -1293,7 +1298,7 @@ export class ReverseEngineeringService { cleanupOwner: ProviderProcessSupervisor | undefined, ): AnalysisError { if (cleanupOwner !== undefined && failure.cleanupIncomplete) - this.#pendingCleanup.get(cleanupOwner)?.failures.add(failure); + this.#pendingCleanup.get(cleanupOwner)?.release.bind(failure); return failure; } } diff --git a/src/cutter/CutterBridgeService.ts b/src/cutter/CutterBridgeService.ts index 8988df11df..0b3d672beb 100644 --- a/src/cutter/CutterBridgeService.ts +++ b/src/cutter/CutterBridgeService.ts @@ -1,4 +1,5 @@ import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { AnalysisCleanupRelease } from "../domain/analysisCleanupRelease.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { jsonValueSchema } from "../domain/jsonValue.js"; import { @@ -48,6 +49,8 @@ export class CutterBridgeService { readonly sessionId: string; readonly completionToken?: string; readonly failure: AnalysisOutputError; + /** Confirmed by the producer's terminal receipt; the failure reads it. */ + readonly release: AnalysisCleanupRelease; } >(); @@ -82,8 +85,7 @@ export class CutterBridgeService { ).bindCleanupDependencies([pending.failure, receipt.error]), ); if (!receipt.value) return err(pending.failure); - const { failure } = pending; - failure.resolveCleanup(); + pending.release.confirm(); this.#pendingCleanup.delete(requestId); } return ok(null); @@ -230,12 +232,14 @@ export class CutterBridgeService { partialObservation: evidence, }, ); + const release = new AnalysisCleanupRelease(); this.#pendingCleanup.set(output.requestId, { sessionId: input.session_id, ...(output.completionToken === undefined ? {} : { completionToken: output.completionToken }), - failure, + failure: release.bind(failure), + release, }); return err(failure); } diff --git a/src/domain/analysisCleanupRelease.test.ts b/src/domain/analysisCleanupRelease.test.ts index 65c6cb325b..d7c58604f8 100644 --- a/src/domain/analysisCleanupRelease.test.ts +++ b/src/domain/analysisCleanupRelease.test.ts @@ -29,3 +29,18 @@ it("lets every bound error read one owner's confirmed release", () => { // An error bound after the release reads it immediately. expect(release.bind(failure()).cleanupIncomplete).toBe(false); }); + +it("reads a claim bound repeatedly to one error only once", () => { + let reads = 0; + const claim = { + get cleanupReleased() { + reads += 1; + return false; + }, + }; + const error = failure(); + for (let attempt = 0; attempt < 3; attempt += 1) + error.bindCleanupReleaseClaim(claim); + expect(error.cleanupIncomplete).toBe(true); + expect(reads).toBe(1); +}); diff --git a/src/domain/analysisErrorBase.ts b/src/domain/analysisErrorBase.ts index b8ebabf1b2..0c37db6e2e 100644 --- a/src/domain/analysisErrorBase.ts +++ b/src/domain/analysisErrorBase.ts @@ -199,7 +199,7 @@ export abstract class AnalysisError extends Error { #ownedCleanupResources: readonly string[]; #cleanupResourceOwner: AnalysisCleanupResourceOwner | undefined; #cleanupCompletionOwner: AnalysisCleanupResourceOwner | undefined; - readonly #cleanupReleaseClaims: AnalysisCleanupReleaseClaim[] = []; + readonly #cleanupReleaseClaims = new Set(); #cleanupRetry: AnalysisCleanupRetry | undefined; #secondaryFailures: AnalysisError[] = []; constructor(message: string, options?: AnalysisErrorOptions) { @@ -260,21 +260,29 @@ export abstract class AnalysisError extends Error { if (!this.#cleanupIncomplete) return false; const dependencies = this.#cleanupDependencies; if (dependencies === undefined) { - if (!this.#cleanupReleaseClaims.some((claim) => claim.cleanupReleased)) - return true; + if (!this.#anyClaimReleased()) return true; } else for (const dependency of dependencies) if (dependency.cleanupIncomplete) return true; this.#cleanupIncomplete = false; dependencies?.clear(); - this.#cleanupReleaseClaims.length = 0; + this.#cleanupReleaseClaims.clear(); return false; } - /** Read completion from a lease owner instead of having it pushed here. */ + #anyClaimReleased(): boolean { + for (const claim of this.#cleanupReleaseClaims) + if (claim.cleanupReleased) return true; + return false; + } + + /** + * Read completion from a lease owner instead of having it pushed here. + * Binding the same claim again is a no-op, so retries do not grow it. + */ bindCleanupReleaseClaim(claim: AnalysisCleanupReleaseClaim): this { this.#carriesCleanup = true; - this.#cleanupReleaseClaims.push(claim); + this.#cleanupReleaseClaims.add(claim); return this; } diff --git a/src/ida/IdaSessionClient.ts b/src/ida/IdaSessionClient.ts index 70d971df02..e473180940 100644 --- a/src/ida/IdaSessionClient.ts +++ b/src/ida/IdaSessionClient.ts @@ -211,7 +211,6 @@ export class IdaSessionClient implements AnalysisClient { #closed = false; #closing = false; #closePromise: Promise> | undefined; - #closeFailures: WeakRef[] = []; #workspace: IdaWorkspace | undefined; #database: string | undefined; #databaseCloseCompleted = false; @@ -1003,9 +1002,6 @@ export class IdaSessionClient implements AnalysisClient { await this.connection.close(); await this.#workspace?.remove(); this.#closed = true; - for (const failure of this.#closeFailures) - failure.deref()?.resolveCleanup(); - this.#closeFailures = []; return ok(null); } catch (cause: unknown) { this.connection.detach(); @@ -1016,18 +1012,18 @@ export class IdaSessionClient implements AnalysisClient { this.#unreleasedSessions(), ); const client = this; - failure.bindCleanupResourceOwner({ + // The failure reads this client's later successful close. + const owner = { get cleanupResources() { return client.#closed ? [] : [path]; }, - }); - this.#closeFailures = [ - ...this.#closeFailures.filter( - (reference) => reference.deref() !== undefined, - ), - new WeakRef(failure), - ]; - return err(failure); + get cleanupReleased() { + return client.#closed; + }, + }; + return err( + failure.bindCleanupResourceOwner(owner).bindCleanupReleaseClaim(owner), + ); } } } diff --git a/src/javascript/sourceMaps/SourceMapCommand.ts b/src/javascript/sourceMaps/SourceMapCommand.ts index 603f52cf66..bd001f56a2 100644 --- a/src/javascript/sourceMaps/SourceMapCommand.ts +++ b/src/javascript/sourceMaps/SourceMapCommand.ts @@ -10,6 +10,7 @@ import { join } from "node:path"; import { fileURLToPath } from "node:url"; import type { ExecutionOptions } from "../../application/AnalysisProvider.js"; import { AnalysisError } from "../../domain/analysisErrorBase.js"; +import { AnalysisCleanupRelease } from "../../domain/analysisCleanupRelease.js"; import { analysisErrorWithCleanupFailure } from "../../domain/analysisErrorCleanup.js"; import { analysisErrorWithCancellation } from "../../domain/analysisErrorCancellation.js"; import { @@ -253,7 +254,8 @@ class OwnedCodec implements SourceMapCleanupOwner { readonly #runId = `rea-source-map-${randomUUID()}`; #runtime: SourceMapCodecRuntime | undefined; #supervisor: ProviderProcessSupervisor | undefined; - #cleanupAnchor: SourceMapCleanupFailure | undefined; + /** Reported by every close failure until a later close releases the codec. */ + #cleanupRelease: AnalysisCleanupRelease | undefined; #outcome: CodecOutcome | undefined; #drainStop: CodecPhysicalObservation | undefined; readonly #onInterruption: () => void; @@ -604,8 +606,8 @@ class OwnedCodec implements SourceMapCleanupOwner { } } if (failures.length === 0) { - this.#cleanupAnchor?.resolveCleanup(); - this.#cleanupAnchor = undefined; + this.#cleanupRelease?.confirm(); + this.#cleanupRelease = undefined; return undefined; } const failure = new SourceMapCleanupFailure(this.cleanupResources, { @@ -613,9 +615,9 @@ class OwnedCodec implements SourceMapCleanupOwner { cleanup_failures: failures, codec_pid: this.#supervisor?.launch.process.pid ?? null, }).bindCleanupResourceOwner(this); - if (this.#cleanupAnchor === undefined) this.#cleanupAnchor = failure; - else failure.bindCleanupDependencies([this.#cleanupAnchor], this); - return failure; + return (this.#cleanupRelease ??= new AnalysisCleanupRelease()).bind( + failure, + ); } } const message = (cause: unknown): string => diff --git a/src/sqlite/SqliteDatabaseProvider.ts b/src/sqlite/SqliteDatabaseProvider.ts index 1797fba07b..1d99dc2d6f 100644 --- a/src/sqlite/SqliteDatabaseProvider.ts +++ b/src/sqlite/SqliteDatabaseProvider.ts @@ -11,6 +11,7 @@ import type { AnalysisCapturedOutput, AnalysisError, } from "../domain/analysisErrorBase.js"; +import { AnalysisCleanupRelease } from "../domain/analysisCleanupRelease.js"; import { AnalysisOutputError, AnalysisResourceConstraintError, @@ -60,10 +61,23 @@ interface PendingSnapshotCleanup { readonly input: InspectSqliteDatabaseInput; readonly result: SqliteOutcome; readonly output: AnalysisCapturedOutput | undefined; + /** Reports the runtime root until its removal confirms `rootRelease`. */ readonly rootFailure: AnalysisError; + readonly rootRelease: AnalysisCleanupRelease; + /** Reports the worker until a verified stop confirms `processRelease`. */ readonly processFailure: AnalysisError | undefined; + readonly processRelease: AnalysisCleanupRelease; process: ProviderProcessSupervisor | undefined; } +/** The runtime root a retained cleanup still owns. */ +const sqliteRootFailure = (root: SqliteRuntimeRoot): ProviderCleanupError => + new ProviderCleanupError( + SQLITE_PROVIDER_IDENTITY.id, + [root.path], + { reason: "SQLite runtime root cleanup remains unresolved." }, + { operation }, + ); + /** Inspect a provider-owned copy through a cancellable SQLite child, without source writes. */ export class SqliteDatabaseProvider implements SqliteDatabasePort { readonly #active = new Set>(); @@ -216,7 +230,7 @@ export class SqliteDatabaseProvider implements SqliteDatabasePort { continue; } pending.process = undefined; - pending.processFailure?.resolveCleanup(); + pending.processRelease.confirm(); } const cleaned = await cleanupSqliteRoot( root, @@ -225,7 +239,7 @@ export class SqliteDatabaseProvider implements SqliteDatabasePort { pending.output, ); if (cleaned.ok) { - pending.rootFailure.resolveCleanup(); + pending.rootRelease.confirm(); this.#pendingCleanup.delete(root); } else { cleaned.error.bindCleanupDependencies([pending.rootFailure]); @@ -347,28 +361,29 @@ export class SqliteDatabaseProvider implements SqliteDatabasePort { if (root !== undefined) { if (processOwner !== undefined) { const ownership = processOwner.launch.ownership; - const rootFailure = new ProviderCleanupError( - SQLITE_PROVIDER_IDENTITY.id, - [root.path], - { reason: "SQLite runtime root cleanup remains unresolved." }, - { operation }, - ); + const rootRelease = new AnalysisCleanupRelease(); + const rootFailure = rootRelease.bind(sqliteRootFailure(root)); const processReason = processCleanup?.reason ?? "SQLite worker cleanup remains unresolved."; - const processFailure = new ProviderCleanupError( - SQLITE_PROVIDER_IDENTITY.id, - ownership === undefined - ? ["owned-sqlite-worker"] - : ownedCommandResources(ownership), - { reason: processReason }, - { operation }, + const processRelease = new AnalysisCleanupRelease(); + const processFailure = processRelease.bind( + new ProviderCleanupError( + SQLITE_PROVIDER_IDENTITY.id, + ownership === undefined + ? ["owned-sqlite-worker"] + : ownedCommandResources(ownership), + { reason: processReason }, + { operation }, + ), ); this.#pendingCleanup.set(root, { input, result, output: retainedOutput, rootFailure, + rootRelease, processFailure, + processRelease, process: processOwner, }); if (processCleanup !== undefined) { @@ -428,19 +443,17 @@ export class SqliteDatabaseProvider implements SqliteDatabasePort { retainedOutput, ); if (!cleaned.ok) { - const rootFailure = new ProviderCleanupError( - SQLITE_PROVIDER_IDENTITY.id, - [root.path], - { reason: "SQLite runtime root cleanup remains unresolved." }, - { operation }, - ); + const rootRelease = new AnalysisCleanupRelease(); + const rootFailure = rootRelease.bind(sqliteRootFailure(root)); cleaned.error.bindCleanupDependencies([rootFailure]); this.#pendingCleanup.set(root, { input, result, output: retainedOutput, rootFailure, + rootRelease, processFailure: undefined, + processRelease: new AnalysisCleanupRelease(), process: undefined, }); return cleaned; diff --git a/tests/composition/analysis-sessions/binarySessionCleanupRetry.test.ts b/tests/composition/analysis-sessions/binarySessionCleanupRetry.test.ts index 5c8e315414..9238753d79 100644 --- a/tests/composition/analysis-sessions/binarySessionCleanupRetry.test.ts +++ b/tests/composition/analysis-sessions/binarySessionCleanupRetry.test.ts @@ -523,3 +523,33 @@ it("does not start a replacement cancelled while pending cleanup completes", asy expect(created).toBe(1); await expect(access(runtime)).rejects.toMatchObject({ code: "ENOENT" }); }); + +it("lets an unowned close failure read the later successful close", async () => { + const [first] = await createBinarySessionTargets(); + let allowed = false; + const session = createTestBinarySession(() => ({ + execute: () => Promise.resolve(ok(null)), + close: () => + Promise.resolve( + allowed + ? resultOk(null) + : err( + new ProviderCleanupError("fixture", ["owned-runtime"], { + reason: "cleanup denied", + }), + ), + ), + })); + onTestFinished(async () => { + allowed = true; + await session.close(); + }); + expect((await session.open(first)).ok).toBe(true); + const failed = await session.close(); + if (failed.ok) throw new Error("Expected retained close failure"); + expect(failed.error.hasCleanupOwner).toBe(false); + expect(failed.error.cleanupIncomplete).toBe(true); + allowed = true; + expect((await session.close()).ok).toBe(true); + expect(failed.error.cleanupIncomplete).toBe(false); +});