From b98fbdc44212c860fbbd929393d74981ec946be8 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 15 Nov 2026 19:53:53 +0800 Subject: [PATCH] refactor(ida): let IDA close failures read the session's later close (#10811) * refactor(errors): read cleanup completion from dependencies instead of pushing it to dependents AnalysisError.cleanupIncomplete becomes a getter over the error's own unresolved state and its bound dependencies. The WeakRef dependents graph and resolveCleanup's push propagation are removed, and subclasses mark their initial state through markCleanupIncomplete instead of overriding a public mutable field. * fix(errors): settle bound dependencies before binding more A composite whose dependencies had released but whose status was never read stayed incomplete when a later dependency was bound. * refactor(errors): let errors read a lease group's release instead of resolving them (#10759) AnalysisCleanupLeaseGroup no longer calls resolveCleanup() on its error. The error holds the group as a release claim and reads cleanupReleased when asked, so completion follows the lease owner without a push. * chore(verify): count resolveCleanup and bindCleanupDependencies calls so they only shrink (#10763) * refactor(errors): let errors read a lease group's release instead of resolving them AnalysisCleanupLeaseGroup no longer calls resolveCleanup() on its error. The error holds the group as a release claim and reads cleanupReleased when asked, so completion follows the lease owner without a push. * chore(verify): count resolveCleanup and bindCleanupDependencies calls so they only shrink * refactor(process): let worker cleanup errors read their root epoch's release OwnedWorkerRuntime's root epoch is now an AnalysisCleanupReleaseClaim. Errors bound to it read its release when asked instead of the epoch pushing resolveCleanup() through weak references, and a runtime without a retained root binds an already-released owner. Removes the OwnedWorkerCleanupFailure structural type and four resolveCleanup() pushes; the counted baseline shrinks accordingly. * refactor(pcap): let pcap cleanup errors read command and snapshot release (#10792) Retained pcap commands, retained snapshot failures and snapshot completion descriptors now own their release and errors read it: commands and snapshot failures implement AnalysisCleanupReleaseClaim, and a failed completion-descriptor close is retried through an AnalysisCleanupLease bound to its error. Removes four resolveCleanup() pushes; the counted baseline shrinks accordingly. * refactor(process): let Darwin helper cleanup errors read their owner's release Darwin helper cache and run-token reader root cleanup now record an AnalysisCleanupRelease that every failure reports; a successful retry confirms it. Replaces the first-failure anchor that later failures depended on and the resolveCleanup() push. Removes two resolveCleanup() and two bindCleanupDependencies() calls; both counted baselines shrink. * refactor(ghidra): let Ghidra cleanup errors read the client's and checkpoint's release GhidraClient and GhidraCheckpoint bind each cleanup failure to an AnalysisCleanupRelease and confirm it when a later close or retry releases everything, instead of keeping a set of failures and pushing resolveCleanup() to each. Removes two resolveCleanup() calls; the counted baseline shrinks. * refactor(process): let debugger session cleanup errors read a confirmed stop OwnedDebuggerSessionRegistry binds each retained gdb or rizin cleanup failure to the session's AnalysisCleanupRelease and confirms it when a stop is confirmed, keeping the latest failure for retry reporting, instead of pushing resolveCleanup() to a set of failures. Removes one resolveCleanup() call; the counted baseline shrinks. * refactor(process): drop the debugger registry's unused closeOperation option Returning the latest retained failure removed the last reader of closeOperation; remove the option and the values gdb and rizin supplied. * refactor(server): let environment shutdown errors read a successful close serveEnvironment binds each shutdown failure to an AnalysisCleanupRelease that a later successful close confirms, instead of pushing resolveCleanup() to a set of failures. The state-file retry test now also requires the earlier report to read the release. Removes one resolveCleanup() call; the counted baseline shrinks. * refactor(desktop): release retained screen-judge cleanup through its lease Each retained judge or screenshot cleanup owner is wrapped in an AnalysisCleanupLease bound to its failure; close() releases the lease, which records the release the failure reads, instead of closing the owner and pushing resolveCleanup(). Removes one resolveCleanup() call; the counted baseline shrinks. * refactor(ida): let IDA close failures read the session's later close IdaSessionClient's close failure binds an owner that is both its resource owner and its release claim, read from the client's closed state, instead of keeping weak references and pushing resolveCleanup() after a successful retry. Removes one resolveCleanup() call; the counted baseline shrinks. * refactor(javascript): let source-map codec cleanup errors read a later close (#10814) * refactor(javascript): let source-map codec cleanup errors read a later close OwnedCodec binds each close failure to an AnalysisCleanupRelease that a later successful close confirms, replacing the first-failure anchor that later failures depended on and the resolveCleanup() push. Removes one resolveCleanup() and one bindCleanupDependencies() call; both counted baselines shrink. * refactor(cutter): let pending Cutter command errors read the completion receipt (#10815) * refactor(cutter): let pending Cutter command errors read the completion receipt Each pending Cutter command keeps an AnalysisCleanupRelease bound to its timeout failure; the producer's terminal completion receipt confirms it instead of pushing resolveCleanup(). Removes one resolveCleanup() call; the counted baseline shrinks. * refactor(application): let provider candidate cleanup errors read the candidate's close (#10817) * refactor(application): let provider candidate cleanup errors read the candidate's close AnalysisProviderRegistry keeps one AnalysisCleanupRelease per candidate whose resource close is unconfirmed; failures bind to it and a later confirmed close confirms it, instead of pushing resolveCleanup() to a set of failures. Removes one resolveCleanup() call; the counted baseline shrinks. * fix(errors): bind a cleanup release claim to an error at most once AnalysisError kept release claims in an array, so a provider whose retried close returned the same error bound the same claim again on every retry and each cleanupIncomplete read scanned the duplicates. Keep the claims in a set. * refactor(application): let reverse-tool cleanup errors read a verified stop (#10819) * refactor(application): let reverse-tool cleanup errors read a verified stop Each retained provider process group in ReverseEngineeringService keeps an AnalysisCleanupRelease; its command and retry failures bind to it and a later verified stop confirms it, instead of collecting failures and pushing resolveCleanup(). Removes one resolveCleanup() call; the counted baseline shrinks. * refactor(sqlite): let SQLite worker and root cleanup errors read their release (#10821) Each retained SQLite snapshot cleanup records an AnalysisCleanupRelease for its worker and for its runtime root; the resource failures bind to them and a verified stop or root removal confirms them, instead of pushing resolveCleanup(). Composite failures keep reading those resource failures. Removes two resolveCleanup() calls; the counted baseline shrinks. * refactor(application): let JADX and session close failures read their owner's release (#10854) * refactor(android): let JADX cleanup errors read their retained cleanup's release Each retained JADX cleanup records an AnalysisCleanupRelease for the admission failure's descriptor owners and one for the whole retained cleanup. The admission failure and every error the cleanup reports bind to them, and a confirmed close confirms them, instead of pushing resolveCleanup() through WeakRefs to reported errors. Removes two resolveCleanup() calls; the counted baseline shrinks. * refactor(application): let session close failures read the client's later close A retained session cleanup records an AnalysisCleanupRelease; unowned cleanup failures the client's close reported bind to it and the successful close confirms it, instead of the session collecting them and pushing resolveCleanup(). Failures that already follow their own owner keep reading it. Adds a regression for an unowned close failure. Removes one resolveCleanup() call; the counted baseline shrinks. --- .../verify/architecture-guard-baselines.json | 12 +--- src/android/JadxProvider.ts | 61 ++++++++++--------- .../binary/AnalysisProviderRegistry.ts | 14 +++-- src/application/binary/BinarySession.ts | 27 +++++--- .../reverse/ReverseEngineeringService.ts | 25 +++++--- src/cutter/CutterBridgeService.ts | 10 ++- src/domain/analysisCleanupRelease.test.ts | 15 +++++ src/domain/analysisErrorBase.ts | 20 ++++-- src/ida/IdaSessionClient.ts | 22 +++---- src/javascript/sourceMaps/SourceMapCommand.ts | 14 +++-- src/sqlite/SqliteDatabaseProvider.ts | 55 ++++++++++------- .../binarySessionCleanupRetry.test.ts | 30 +++++++++ 12 files changed, 194 insertions(+), 111 deletions(-) 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); +});