From b655645608aeb68cf17a8632927e646b2e52a221 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:28:05 +0800 Subject: [PATCH] refactor(errors): give caller aborts a typed reason at the adapters (#10633) * refactor(errors): give caller aborts a typed reason at the adapters Squashes 908813551f, 87858de4dc (fix(mcp): preserve cancellation reasons in handlers) and fa151dc3f6 (test(server): race handler-entry gates against the triggering tool call) onto main without #10566's pre-squash commits. * refactor(errors): give owner-initiated aborts a typed reason outside the browser adapters (#10692) * refactor(errors): give owner-initiated aborts a typed reason outside the browser adapters * refactor(verify): keep the abort-reason scan receiver-independent Playwright's route.abort takes a network error code; the one call site now names its default code instead of the guard exempting a variable name. * refactor(browser): give owner-initiated CDP aborts typed reasons (#10706) * refactor(browser): give owner-initiated CDP aborts typed reasons * fix(browser): give the page-side request fetch page-native abort reasons The request callback runs in the page through page.evaluate and cannot reach REA's modules. Define its deadline and cleanup reasons as DOMExceptions inside the callback, and make the test fake evaluate the callback from its source so module imports are unavailable, as in a page. * test(process): expect the reader close's typed owner reason Closing the Darwin run-token reader aborts its compilation with OwnerCancellation.ownerClosed since the owner-abort change in this PR; the boundary test still expected the default DOMException. * fix(server): report HTTP session replacement and shutdown to pending tools as an owner close --- .../verify/architecture-guard-baselines.json | 5 +- scripts/verify/architecture-guards.mjs | 13 ++ src/application/DirectAnalysis.ts | 14 +- src/application/Doctor.ts | 8 +- src/application/HopperDownload.ts | 3 +- src/application/binary/BinarySession.ts | 3 +- src/application/desktop/DesktopBuildTurns.ts | 10 +- .../desktop/DesktopRemoteTaskReaders.ts | 7 +- .../reverse/ReverseEngineeringService.ts | 4 +- src/artifacts/ZipArtifactReader.ts | 3 +- .../apple/AppleAssetCatalogAnalysis.ts | 3 +- src/browser/CdpObservationSession.ts | 7 +- src/browser/CdpPageCapture.ts | 7 +- src/browser/CdpTargetSession.ts | 12 +- src/browser/PlaywrightScenarioRequest.test.ts | 30 ++- src/browser/PlaywrightScenarioRequest.ts | 17 +- .../PlaywrightScenarioServiceWorkers.ts | 7 +- src/browser/execution/CdpRuntimeSession.ts | 14 +- src/browser/modules/NativeModuleResolver.ts | 4 +- src/cli/commandCancellation.ts | 6 +- .../analysisErrorCore.cancellation.test.ts | 18 ++ src/domain/analysisErrorCore.ts | 81 +++++++- src/gdb/GdbSessionManager.ts | 9 +- src/ghidra/GhidraClient.ts | 18 +- src/ghidra/GhidraNativeAotSnapshotOwner.ts | 16 +- src/ghidra/GhidraProvider.ts | 8 +- src/hopper/HopperClient.ts | 20 +- src/ida/IdaSessionClient.ts | 6 +- src/inspector/V8InspectorProvider.ts | 7 +- src/kuna/KunaJsonStream.ts | 3 +- src/kuna/KunaProjectCache.ts | 4 +- src/kuna/KunaProjectReader.ts | 5 +- src/kuna/KunaSessionClient.ts | 8 +- src/main/eagerRuntime.ts | 5 +- src/process/AbortablePromise.test.ts | 26 +++ src/process/AbortablePromise.ts | 20 +- src/process/DarwinProcessRunTokenReader.ts | 5 +- src/process/OwnedCommand.ts | 9 +- src/process/SharedStartupAttempt.test.ts | 12 +- src/process/SharedStartupAttempt.ts | 21 +- src/process/WindowsExecutable.ts | 4 +- src/process/WorkerFrameSignal.ts | 3 +- .../capture/ProcessCaptureLifecycle.ts | 5 +- src/rizin/RizinDebugSessionManager.ts | 4 +- src/server/EvidenceMcpServer.test.ts | 193 +++++++++++++++++- src/server/EvidenceMcpServerCore.ts | 56 ++++- src/server/McpToolRequest.ts | 8 +- src/server/http/nodeHttpBridge.test.ts | 8 +- src/server/http/nodeHttpBridge.ts | 4 +- src/server/http/serveStreamableHttp.test.ts | 80 ++++++++ src/server/http/serveStreamableHttp.ts | 23 ++- src/server/transportOwnerClose.ts | 18 ++ .../cli/androidCliCancellation.test.ts | 12 +- .../ghidraProfileArtifactOwnership.test.ts | 6 +- .../darwinProcessRunTokenReader.test.ts | 7 +- .../providers/kuna/kunaDoctor.test.ts | 8 +- 56 files changed, 758 insertions(+), 159 deletions(-) create mode 100644 src/process/AbortablePromise.test.ts create mode 100644 src/server/transportOwnerClose.ts diff --git a/scripts/verify/architecture-guard-baselines.json b/scripts/verify/architecture-guard-baselines.json index 15e52621a3..6482fc12fb 100644 --- a/scripts/verify/architecture-guard-baselines.json +++ b/scripts/verify/architecture-guard-baselines.json @@ -111,7 +111,7 @@ "src/browser/modules/NativeModuleResolver.ts": 3, "src/captures/TsharkCaptureProvider.ts": 2, "src/electron/ElectronFuseFailures.ts": 3, - "src/gdb/GdbSessionManager.ts": 14, + "src/gdb/GdbSessionManager.ts": 13, "src/inspector/JavaScriptRuntimeScope.ts": 1, "src/inspector/V8InspectorProvider.ts": 2, "src/javascript/analysis/JavaScriptAnalysisWorker.ts": 5, @@ -502,5 +502,6 @@ "src/domain/apkSignature/apkV1SignatureBlock.ts": 1, "src/native/MachoArchitectureSelection.ts": 2, "src/native/NativeMachoInspection.ts": 1 - } + }, + "abort-without-reason": {} } diff --git a/scripts/verify/architecture-guards.mjs b/scripts/verify/architecture-guards.mjs index c7adfff99e..de42aef00c 100644 --- a/scripts/verify/architecture-guards.mjs +++ b/scripts/verify/architecture-guards.mjs @@ -330,6 +330,19 @@ checkCounted( ["src/pcap/TsharkJsonPackets.ts"], ); +// An abort reason names who ended the work: a typed `CallerAbort` at the CLI, +// MCP and HTTP adapters, or an `OwnerCancellation` when REA closes an owner. +// A bare `.abort()` leaves an anonymous platform AbortError as the cause. +// Playwright's `route.abort(errorCode)` takes a network error code instead; +// its call sites pass that code explicitly so the scan stays receiver-independent. +checkCounted( + "AbortController.abort() without a reason (pass a CallerAbort or OwnerCancellation from src/domain/analysisErrorCore)", + "abort-without-reason", + files, + /\.abort\(\s*\)/gu, + [], +); + // GDB MI result records have one parser, src/gdb/GdbMiRecord.ts, which // returns typed records and typed failures. A regex over `\^done` accepts a // malformed record by its prefix. diff --git a/src/application/DirectAnalysis.ts b/src/application/DirectAnalysis.ts index 08ccf5126b..b80a6a2cd1 100644 --- a/src/application/DirectAnalysis.ts +++ b/src/application/DirectAnalysis.ts @@ -84,6 +84,7 @@ import { resolveXrefsAddress } from "./XrefsAddressResolution.js"; import { AnalysisCancelledError, AnalysisInputError, + CallerAbort, } from "../domain/analysisErrorCore.js"; import { deliverAnalysisEvidence } from "./EvidenceBundleCommands.js"; import type { BinaryTargetError } from "../domain/configurationErrors.js"; @@ -853,16 +854,19 @@ const withProcessCancellation = async ( ): Promise => { if (suppliedSignal !== undefined) return operation(suppliedSignal); const controller = new AbortController(); - const cancel = (): void => controller.abort(); + const interrupt = (): void => + controller.abort(CallerAbort.forProcessSignal("SIGINT")); + const terminate = (): void => + controller.abort(CallerAbort.forProcessSignal("SIGTERM")); // Package runners can forward a terminal interrupt after REA already received // it directly. Keep both guards installed until provider cleanup has settled. - process.on("SIGINT", cancel); - process.on("SIGTERM", cancel); + process.on("SIGINT", interrupt); + process.on("SIGTERM", terminate); try { return await operation(controller.signal); } finally { - process.off("SIGINT", cancel); - process.off("SIGTERM", cancel); + process.off("SIGINT", interrupt); + process.off("SIGTERM", terminate); } }; diff --git a/src/application/Doctor.ts b/src/application/Doctor.ts index f4c4b7bde7..ae9ee5bfc0 100644 --- a/src/application/Doctor.ts +++ b/src/application/Doctor.ts @@ -1,12 +1,14 @@ import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; -import { AnalysisCancelledError } from "../domain/analysisErrorCore.js"; +import { + AnalysisCancelledError, + OwnerCancellation, +} from "../domain/analysisErrorCore.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; import { bindArtifactFileCleanup } from "../artifacts/ArtifactFileOperation.js"; import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js"; import { AnalysisCleanupLease } from "../artifacts/AnalysisCleanupLease.js"; -import { STARTUP_OWNER_CLOSED } from "../process/SharedStartupAttempt.js"; import { constants } from "node:fs"; import { access, realpath, stat } from "node:fs/promises"; import { posix, win32 } from "node:path"; @@ -933,7 +935,7 @@ export const systemDoctorHost = ( resources, ), close: async () => { - controller.abort(STARTUP_OWNER_CLOSED); + controller.abort(OwnerCancellation.startupOwnerClosed); try { await resources.close(); return undefined; diff --git a/src/application/HopperDownload.ts b/src/application/HopperDownload.ts index f7094c80ba..b7e5f5d280 100644 --- a/src/application/HopperDownload.ts +++ b/src/application/HopperDownload.ts @@ -1,3 +1,4 @@ +import { OwnerCancellation } from "../domain/analysisErrorCore.js"; import { sanitizeBrowserUrl } from "../domain/browserObservation.js"; import { err, ok, type Result } from "../domain/result.js"; @@ -114,7 +115,7 @@ export const downloadHopperPackage = async ( const deadline = new AbortController(); const expire = (limit: "stalled" | "deadline", limitMs: number) => { expired ??= { limit, timeoutMs: limitMs, receivedBytes }; - deadline.abort(); + deadline.abort(OwnerCancellation.deadlineElapsed); }; const overall = setTimeout(() => { expire("deadline", timeoutMs); diff --git a/src/application/binary/BinarySession.ts b/src/application/binary/BinarySession.ts index 2c50ef3ec4..8d8c951cc2 100644 --- a/src/application/binary/BinarySession.ts +++ b/src/application/binary/BinarySession.ts @@ -21,6 +21,7 @@ import { AnalysisCancelledError, AnalysisCapabilityUnavailableError, AnalysisOutputError, + OwnerCancellation, } from "../../domain/analysisErrorCore.js"; import { AnalysisError, @@ -1752,7 +1753,7 @@ export class BinarySession ): Promise { if (options.abortPrompts !== false) for (const controller of this.#promptCompletionControllers) - controller.abort(); + controller.abort(OwnerCancellation.noLongerNeeded); this.#transitionPending += 1; // Later calls wait for this transition and must not be included in its drain. const admittedThrough = this.#transitionGeneration++; diff --git a/src/application/desktop/DesktopBuildTurns.ts b/src/application/desktop/DesktopBuildTurns.ts index ea4f29820f..4f3002a3bc 100644 --- a/src/application/desktop/DesktopBuildTurns.ts +++ b/src/application/desktop/DesktopBuildTurns.ts @@ -1,7 +1,10 @@ import type { AnalysisError } from "../../domain/analysisErrorBase.js"; import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js"; import { err, type Result } from "../../domain/result.js"; -import { ABORTED, waitForAbortable } from "../../process/AbortablePromise.js"; +import { + AbortedWait, + waitForAbortable, +} from "../../process/AbortablePromise.js"; /** * One build computer's calls, each run alone in the order it arrived, so a @@ -25,7 +28,10 @@ export class DesktopBuildTurns { ): Promise> { const turn = AbortSignal.any([signal, this.#closing.signal]); const { previous, release } = this.#enqueue(); - if ((await waitForAbortable(previous, turn)) === ABORTED || turn.aborted) { + if ( + (await waitForAbortable(previous, turn)) instanceof AbortedWait || + turn.aborted + ) { // A call that never ran keeps its place until the one before it ends, so the next still waits for that one. void previous.then(release); return err(new AnalysisCancelledError(operation, { cause: turn.reason })); diff --git a/src/application/desktop/DesktopRemoteTaskReaders.ts b/src/application/desktop/DesktopRemoteTaskReaders.ts index feed67922d..3133faaada 100644 --- a/src/application/desktop/DesktopRemoteTaskReaders.ts +++ b/src/application/desktop/DesktopRemoteTaskReaders.ts @@ -19,7 +19,10 @@ import { AGENTENV_PROVIDER, type ComputerRelease, } from "../../desktop/AgentEnvComputerHelper.js"; -import { ABORTED, waitForAbortable } from "../../process/AbortablePromise.js"; +import { + AbortedWait, + waitForAbortable, +} from "../../process/AbortablePromise.js"; type Exec = ( argv: readonly string[], @@ -95,7 +98,7 @@ export class DesktopRemoteTaskReaders { pending.requestId, ); const observed = await waitForAbortable(pending.command, signal); - if (observed === ABORTED) throw signal.reason; + if (observed instanceof AbortedWait) throw observed.carried; result = observed; if (result.timed_out) { pending.uncertain = new Error( diff --git a/src/application/reverse/ReverseEngineeringService.ts b/src/application/reverse/ReverseEngineeringService.ts index 34c44c65d7..daa0ed2184 100644 --- a/src/application/reverse/ReverseEngineeringService.ts +++ b/src/application/reverse/ReverseEngineeringService.ts @@ -28,6 +28,7 @@ import { AnalysisResourceConstraintError, AnalysisTimeoutError, AnalysisOutputError, + OwnerCancellation, } from "../../domain/analysisErrorCore.js"; import { AnalysisError, @@ -322,7 +323,8 @@ export class ReverseEngineeringService { async #closeActiveOperationsAndCleanup(): Promise { const active = [...this.#activeOperations.entries()]; - for (const [controller] of active) controller.abort(); + for (const [controller] of active) + controller.abort(OwnerCancellation.ownerClosed); await Promise.allSettled(active.map(([, operation]) => operation)); const cleanup = await this.retryCleanup(); diff --git a/src/artifacts/ZipArtifactReader.ts b/src/artifacts/ZipArtifactReader.ts index 8af8f9daf6..21355d7ab8 100644 --- a/src/artifacts/ZipArtifactReader.ts +++ b/src/artifacts/ZipArtifactReader.ts @@ -1,3 +1,4 @@ +import { OwnerCancellation } from "../domain/analysisErrorCore.js"; import { assertArtifactReadActive } from "./ArtifactFileOperation.js"; import type { FileHandle } from "node:fs/promises"; import { Duplex, PassThrough, type Readable } from "node:stream"; @@ -555,7 +556,7 @@ const extractStream = ( // settlement before releasing the source descriptor. output.once("close", () => { signal?.removeEventListener("abort", onAbort); - controller.abort(); + controller.abort(OwnerCancellation.noLongerNeeded); }); const writable = new WritableStream({ write: async (chunk) => { diff --git a/src/artifacts/apple/AppleAssetCatalogAnalysis.ts b/src/artifacts/apple/AppleAssetCatalogAnalysis.ts index e486df4378..29eb957429 100644 --- a/src/artifacts/apple/AppleAssetCatalogAnalysis.ts +++ b/src/artifacts/apple/AppleAssetCatalogAnalysis.ts @@ -7,6 +7,7 @@ import { AnalysisTimeoutError, AnalysisCapabilityUnavailableError, AnalysisResourceConstraintError, + OwnerCancellation, } from "../../domain/analysisErrorCore.js"; import { fixedAllowanceOptions } from "../../domain/fixedAllowanceRemediation.js"; import { createHash } from "node:crypto"; @@ -103,7 +104,7 @@ export const analyzeAppleAssetCatalogs = async (input: { collectAssetCatalogs({ ...input, resources }), )); } catch (cause: unknown) { - interfaceBuilderCancel.abort(); + interfaceBuilderCancel.abort(OwnerCancellation.noLongerNeeded); const joined = await interfaceBuilderAnalysis; if ( !joined.ok && diff --git a/src/browser/CdpObservationSession.ts b/src/browser/CdpObservationSession.ts index 226d46f6a1..7fadc994dc 100644 --- a/src/browser/CdpObservationSession.ts +++ b/src/browser/CdpObservationSession.ts @@ -3,7 +3,10 @@ import type { ObserveWebSessionInput, WebObservationSession, } from "../domain/browserSession.js"; -import { AnalysisCancelledError } from "../domain/analysisErrorCore.js"; +import { + AnalysisCancelledError, + OwnerCancellation, +} from "../domain/analysisErrorCore.js"; import { BrowserObservationError } from "../domain/browserObservationError.js"; import { WEB_RUNTIME_LIMITS } from "../domain/webRuntime.js"; import type { CdpEndpointDiscovery, CdpEndpointTarget } from "./CdpEndpoint.js"; @@ -766,7 +769,7 @@ const waitForWindow = async ( const settle = (complete: () => void): void => { if (settled) return; settled = true; - timerController.abort(); + timerController.abort(OwnerCancellation.noLongerNeeded); signal?.removeEventListener("abort", onAbort); removeEnd(); removeProtocolFailure(); diff --git a/src/browser/CdpPageCapture.ts b/src/browser/CdpPageCapture.ts index 5c13c49b63..a5db166a96 100644 --- a/src/browser/CdpPageCapture.ts +++ b/src/browser/CdpPageCapture.ts @@ -3,7 +3,10 @@ import type { WebPageInspection } from "../domain/browserObservationSchemas.js"; import type { ProgressReporter } from "../application/ProgressReporter.js"; import { BrowserObservationError } from "../domain/browserObservationError.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; -import { AnalysisCancelledError } from "../domain/analysisErrorCore.js"; +import { + AnalysisCancelledError, + OwnerCancellation, +} from "../domain/analysisErrorCore.js"; import type { BrowserObservationOperation } from "../domain/browserObservationErrors.js"; import { stableWebResources } from "../domain/webInventory.js"; import type { CdpEndpointDiscovery, CdpEndpointTarget } from "./CdpEndpoint.js"; @@ -437,7 +440,7 @@ const capturePageDom = async (state: CaptureState): Promise => { step = capture.next(await Promise.all(pending)); } catch (cause: unknown) { // Stop and settle this bounded batch before the session can be detached. - pendingController.abort(); + pendingController.abort(OwnerCancellation.noLongerNeeded); await Promise.allSettled(pending); throw cause; } diff --git a/src/browser/CdpTargetSession.ts b/src/browser/CdpTargetSession.ts index e956d3c650..39bd327ea7 100644 --- a/src/browser/CdpTargetSession.ts +++ b/src/browser/CdpTargetSession.ts @@ -6,7 +6,10 @@ import { import type { BrowserObservationEndpoint } from "../domain/browserObservation.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; -import { AnalysisCancelledError } from "../domain/analysisErrorCore.js"; +import { + AnalysisCancelledError, + OwnerCancellation, +} from "../domain/analysisErrorCore.js"; import type { BrowserObservationOperation } from "../domain/browserObservationErrors.js"; import { CdpCommandRejection } from "./CdpCommandRejection.js"; import { CdpConnection } from "./CdpConnection.js"; @@ -398,7 +401,10 @@ const cleanupCdpTargetCommands = async ( signal === undefined ? cleanup.signal : AbortSignal.any([cleanup.signal, signal]); - const timeout = setTimeout(() => cleanup.abort(), 1_000); + const timeout = setTimeout( + () => cleanup.abort(OwnerCancellation.deadlineElapsed), + 1_000, + ); timeout.unref(); try { if (signal?.aborted !== true) { @@ -435,7 +441,7 @@ const cleanupCdpTargetCommands = async ( } } finally { clearTimeout(timeout); - cleanup.abort(); + cleanup.abort(OwnerCancellation.noLongerNeeded); } }; diff --git a/src/browser/PlaywrightScenarioRequest.test.ts b/src/browser/PlaywrightScenarioRequest.test.ts index 2ac2450a30..6c78384235 100644 --- a/src/browser/PlaywrightScenarioRequest.test.ts +++ b/src/browser/PlaywrightScenarioRequest.test.ts @@ -180,7 +180,13 @@ const fakePage = (options: { await new Promise((resolve) => setTimeout(resolve, options.evaluateDelayMs), ); - return fn(arg); + // Like Playwright, run the callback from its source text with a cloned + // argument, so it cannot reach this module's imports or closures. + const pageFunction = new Function( + "arg", + `return (${fn.toString()})(arg);`, + ) as (arg: Arg) => Result | Promise; + return await pageFunction(structuredClone(arg)); }, } as unknown as Page; }; @@ -284,6 +290,28 @@ describe("request dispatch boundary", () => { expect(calls).toEqual([]); }); + it("aborts the page fetch when its deadline elapses", async () => { + const signals: AbortSignal[] = []; + vi.stubGlobal( + "fetch", + async (_url: string, init: RequestInit) => + await new Promise((_resolve, reject) => { + const signal = init.signal!; + signals.push(signal); + signal.addEventListener("abort", () => reject(signal.reason), { + once: true, + }); + }), + ); + const parsed = scenario([requestStep({ timeout_ms: 20 })]); + await expect( + perform(fakePage({}), parsed.actions[0]!, resolved(parsed)), + ).rejects.toThrow(); + expect(signals).toHaveLength(1); + await waitFor(() => expect(signals[0]!.aborted).toBe(true)); + expect(signals[0]!.reason).toMatchObject({ name: "TimeoutError" }); + }); + it("guards dispatch after cancellation while evaluation was queued, and removes its route", async () => { const parsed = scenario([requestStep({})]); const controller = new AbortController(); diff --git a/src/browser/PlaywrightScenarioRequest.ts b/src/browser/PlaywrightScenarioRequest.ts index a71c2aa633..39809136a6 100644 --- a/src/browser/PlaywrightScenarioRequest.ts +++ b/src/browser/PlaywrightScenarioRequest.ts @@ -235,11 +235,22 @@ const sendFromPage = ( : request.deadlineEpochMs - Date.now(); if (remaining !== undefined && remaining <= 0) return { error: "The request ran out of time before it was sent." }; + // This callback runs in the page, which cannot reach REA's modules, so + // its abort reasons are page-native DOMExceptions defined here. const controller = new AbortController(); const timer = remaining === undefined ? undefined - : setTimeout(() => controller.abort(), remaining); + : setTimeout( + () => + controller.abort( + new DOMException( + "The request ran out of time.", + "TimeoutError", + ), + ), + remaining, + ); try { const answer = await fetch(request.url, { method: request.method, @@ -285,7 +296,9 @@ const sendFromPage = ( } return { status: answer.status }; } catch (cause: unknown) { - controller.abort(); + controller.abort( + new DOMException("The request is no longer needed.", "AbortError"), + ); return { error: cause instanceof Error ? cause.message : String(cause), }; diff --git a/src/browser/PlaywrightScenarioServiceWorkers.ts b/src/browser/PlaywrightScenarioServiceWorkers.ts index bca935deba..e23ad3c629 100644 --- a/src/browser/PlaywrightScenarioServiceWorkers.ts +++ b/src/browser/PlaywrightScenarioServiceWorkers.ts @@ -8,7 +8,10 @@ import { CDP_DISCOVERY_RESPONSE_TIMEOUT_MS, selectedCdpCommandTimeoutMs, } from "../domain/browserDeadline.js"; -import { AnalysisTimeoutError } from "../domain/analysisErrorCore.js"; +import { + AnalysisTimeoutError, + OwnerCancellation, +} from "../domain/analysisErrorCore.js"; import { browserObservationEndpointSchema } from "../domain/browserObservation.js"; import { BrowserObservationError } from "../domain/browserObservationError.js"; import { CdpTargetSessionOwner } from "./CdpTargetSessionOwner.js"; @@ -392,7 +395,7 @@ export class PlaywrightScenarioServiceWorkers { POLICY_CLEANUP_CONFIRMATION_TIMEOUT_MS, ); // Abort discovery/handshakes and reads, never an already-sent page mutation. - this.#setup.abort(); + this.#setup.abort(OwnerCancellation.ownerClosed); const restoration = (this.#restoration ??= this.restore()); const clearRestoration = (): void => { if (this.#restoration === restoration) this.#restoration = undefined; diff --git a/src/browser/execution/CdpRuntimeSession.ts b/src/browser/execution/CdpRuntimeSession.ts index 3b2d5095bd..eae0b5d447 100644 --- a/src/browser/execution/CdpRuntimeSession.ts +++ b/src/browser/execution/CdpRuntimeSession.ts @@ -1,6 +1,9 @@ import type { ExecutionOptions } from "../../application/AnalysisProvider.js"; import { AnalysisError } from "../../domain/analysisErrorBase.js"; -import { AnalysisTimeoutError } from "../../domain/analysisErrorCore.js"; +import { + AnalysisTimeoutError, + OwnerCancellation, +} from "../../domain/analysisErrorCore.js"; import { BrowserObservationError } from "../../domain/browserObservationError.js"; import type { BrowserObservationOperation } from "../../domain/browserObservationErrors.js"; import { ProviderCleanupError } from "../../domain/providerCleanupError.js"; @@ -205,7 +208,7 @@ export class CdpRuntimeSession { if (this.#completion !== undefined) return; this.#completion = new AbortController(); this.#completionTimer = setTimeout( - () => this.#completion?.abort(), + () => this.#completion?.abort(OwnerCancellation.deadlineElapsed), this.commandTimeoutMs, ); } @@ -259,7 +262,7 @@ export class CdpRuntimeSession { clearTimeout(this.#completionTimer); const controller = new AbortController(); const timer = setTimeout( - () => controller.abort(), + () => controller.abort(OwnerCancellation.deadlineElapsed), WEB_RUNTIME_LIMITS.cleanupTimeoutMs, ); // Switch before the first restoration send. A short command_timeout_ms @@ -396,7 +399,10 @@ export const runtimeDeadline = async ( method?: string, ): Promise => { const controller = new AbortController(); - const timer = setTimeout(() => controller.abort(), timeoutMs); + const timer = setTimeout( + () => controller.abort(OwnerCancellation.deadlineElapsed), + timeoutMs, + ); try { return await run( signal === undefined diff --git a/src/browser/modules/NativeModuleResolver.ts b/src/browser/modules/NativeModuleResolver.ts index 58e2935370..3570ae1c0f 100644 --- a/src/browser/modules/NativeModuleResolver.ts +++ b/src/browser/modules/NativeModuleResolver.ts @@ -423,7 +423,9 @@ const resolveInBrowser = async ( resource_type: request.resourceType(), effect: "blocked", }); - await route.abort(); + // Playwright's default network error code, named so the abort-reason + // guard sees an argument rather than a bare AbortController abort. + await route.abort("failed"); } }), ); diff --git a/src/cli/commandCancellation.ts b/src/cli/commandCancellation.ts index 328a744cb0..e9a3214551 100644 --- a/src/cli/commandCancellation.ts +++ b/src/cli/commandCancellation.ts @@ -1,3 +1,5 @@ +import { CallerAbort } from "../domain/analysisErrorCore.js"; + /** Process signal boundary injectable without emitting signals into a test runner. */ export interface CommandCancellationHost { on(signal: "SIGINT" | "SIGTERM", listener: () => void): unknown; @@ -14,11 +16,11 @@ export const withCommandCancellation = async ( let exitCode: number | undefined; const interrupt = () => { exitCode ??= 130; - controller.abort(); + controller.abort(CallerAbort.forProcessSignal("SIGINT")); }; const terminate = () => { exitCode ??= 143; - controller.abort(); + controller.abort(CallerAbort.forProcessSignal("SIGTERM")); }; host.on("SIGINT", interrupt); host.on("SIGTERM", terminate); diff --git a/src/domain/analysisErrorCore.cancellation.test.ts b/src/domain/analysisErrorCore.cancellation.test.ts index faad202567..943499e01c 100644 --- a/src/domain/analysisErrorCore.cancellation.test.ts +++ b/src/domain/analysisErrorCore.cancellation.test.ts @@ -1,6 +1,7 @@ import { expect, it } from "vitest"; import { AnalysisCancelledError, + CallerAbort, cancelledBy, carriedReason, isAborted, @@ -72,3 +73,20 @@ it("does not accept a cause beside the required reason", () => { const error = cancelledBy("probe", controller.signal, { cause: "other" }); expect(error.cause).toBe("caller"); }); + +it("keeps a caller abort the platform AbortError shape that names its adapter", () => { + const interrupt = CallerAbort.forProcessSignal("SIGINT"); + const cancelled = new CallerAbort("request-cancelled", "user stopped"); + + for (const reason of [interrupt, cancelled]) { + expect(reason).toBeInstanceOf(DOMException); + expect(reason).toBeInstanceOf(Error); + expect(reason.name).toBe("AbortError"); + } + expect(interrupt.kind).toBe("interrupt"); + expect(CallerAbort.forProcessSignal("SIGTERM").kind).toBe("terminate"); + expect(cancelled.clientReason).toBe("user stopped"); + expect(OwnerCancellation.startupOwnerClosed).not.toBe( + OwnerCancellation.ownerClosed, + ); +}); diff --git a/src/domain/analysisErrorCore.ts b/src/domain/analysisErrorCore.ts index 0800b1a4c2..67a5f6998f 100644 --- a/src/domain/analysisErrorCore.ts +++ b/src/domain/analysisErrorCore.ts @@ -333,7 +333,33 @@ export class AnalysisCancelledError extends AnalysisError { /** Why REA ended work on its own authority when no caller abort exists. */ export type OwnerCancellationKind = /** The provider, session, or service owning the work was closed or disposed. */ - "owner-closed"; + | "owner-closed" + /** + * The owner of a shared provider startup closed it. Startup consumers compare + * a startup signal's reason with this one to tell owner closure from a + * caller's cancellation, so only that startup's owner may abort with it. + */ + | "startup-owner-closed" + /** + * A bound REA set on its own work elapsed. The owner that set it reports the + * timeout; this reason only ends the bounded wait or request. + */ + | "deadline-elapsed" + /** + * REA stopped work whose result nobody will consume: its wait settled, its + * consumer closed, the last waiter left, or a sibling already failed. + */ + | "no-longer-needed"; + +const OWNER_CANCELLATION_MESSAGES: Readonly< + Record +> = { + "owner-closed": "REA closed the owner of this operation before it completed", + "startup-owner-closed": + "REA closed the owner of this operation before it completed", + "deadline-elapsed": "An internal REA bound on this operation elapsed", + "no-longer-needed": "REA stopped work whose result is no longer needed", +}; /** * A cancellation REA initiated itself, such as a provider closing. It stands @@ -342,7 +368,7 @@ export type OwnerCancellationKind = export class OwnerCancellation extends Error { override readonly name = "OwnerCancellation"; private constructor(readonly kind: OwnerCancellationKind) { - super("REA closed the owner of this operation before it completed"); + super(OWNER_CANCELLATION_MESSAGES[kind]); } /** @@ -350,6 +376,57 @@ export class OwnerCancellation extends Error { * the way repeated observations of one caller abort do. */ static readonly ownerClosed = new OwnerCancellation("owner-closed"); + + /** Reserved for the owner of a `SharedStartupAttempt`; see its kind. */ + static readonly startupOwnerClosed = new OwnerCancellation( + "startup-owner-closed", + ); + + /** An internal bound elapsed; see its kind. */ + static readonly deadlineElapsed = new OwnerCancellation("deadline-elapsed"); + + /** Work nobody will consume was stopped; see its kind. */ + static readonly noLongerNeeded = new OwnerCancellation("no-longer-needed"); +} + +/** How the caller ended work, as the CLI, MCP or HTTP adapter observed it. */ +export type CallerAbortKind = + /** The CLI or direct-analysis process received SIGINT. */ + | "interrupt" + /** The CLI or direct-analysis process received SIGTERM. */ + | "terminate" + /** The MCP client sent `notifications/cancelled` for the request. */ + | "request-cancelled" + /** The MCP or HTTP client left before its request settled. */ + | "client-disconnected"; + +const CALLER_ABORT_MESSAGES: Readonly> = { + interrupt: "The caller interrupted this operation (SIGINT)", + terminate: "The caller terminated this operation (SIGTERM)", + "request-cancelled": "The MCP client cancelled this request", + "client-disconnected": "The client disconnected before this request settled", +}; + +/** + * The abort reason an adapter gives when its caller ends work. It is the + * platform's `AbortError` shape, so consumers that recognize a platform abort + * keep recognizing it, and it records which adapter observed the abort and any + * reason the client supplied. Like any caller reason it is opaque: its kind + * never establishes failure origin or cleanup authority. + */ +export class CallerAbort extends DOMException { + constructor( + readonly kind: CallerAbortKind, + /** The client's own stated reason, such as an MCP cancellation's `reason`. */ + readonly clientReason?: unknown, + ) { + super(CALLER_ABORT_MESSAGES[kind], "AbortError"); + } + + /** The reason for a process signal delivered to a one-shot command. */ + static forProcessSignal(signal: "SIGINT" | "SIGTERM"): CallerAbort { + return new CallerAbort(signal === "SIGINT" ? "interrupt" : "terminate"); + } } /** A caller abort reason recovered from an earlier observation of that abort. */ diff --git a/src/gdb/GdbSessionManager.ts b/src/gdb/GdbSessionManager.ts index 22ba819847..ddf9d49882 100644 --- a/src/gdb/GdbSessionManager.ts +++ b/src/gdb/GdbSessionManager.ts @@ -12,7 +12,7 @@ import { type GdbProviderIdentity, } from "./GdbProviderIdentity.js"; import { persistentDebuggerHostSupported } from "../process/PersistentDebuggerHost.js"; -import { ABORTED, waitForAbortable } from "../process/AbortablePromise.js"; +import { AbortedWait, waitForAbortable } from "../process/AbortablePromise.js"; import { classifyLaunchFailure } from "../process/launchFailure.js"; import { snapshotGdbCommandRecords } from "./GdbCommandRecords.js"; import { randomUUID } from "node:crypto"; @@ -1426,7 +1426,8 @@ export class GdbSessionManager { async #drainStartsAndCloseSessions(): Promise { const active = [...this.#activeStarts.entries()]; - for (const [controller] of active) controller.abort(); + for (const [controller] of active) + controller.abort(OwnerCancellation.ownerClosed); await Promise.allSettled(active.map(([, start]) => start)); await Promise.all( [...this.#sessions.values()].map((session) => session.commandTail), @@ -2218,7 +2219,7 @@ const waitForGdbCommandTurn = ( ): Promise => { if (signal === undefined) return previous; return waitForAbortable(previous, signal).then((outcome) => { - if (outcome === ABORTED) - throw new AnalysisCancelledError("gdb_console", { cause: signal.reason }); + if (outcome instanceof AbortedWait) + throw cancelledBy("gdb_console", outcome); }); }; diff --git a/src/ghidra/GhidraClient.ts b/src/ghidra/GhidraClient.ts index 7f5176526e..30604e1db8 100644 --- a/src/ghidra/GhidraClient.ts +++ b/src/ghidra/GhidraClient.ts @@ -12,7 +12,10 @@ import type { FileHandle } from "node:fs/promises"; import type { Socket } from "node:net"; import type { ProgressReporter } from "../application/ProgressReporter.js"; -import { AnalysisCancelledError } from "../domain/analysisErrorCore.js"; +import { + AnalysisCancelledError, + OwnerCancellation, +} from "../domain/analysisErrorCore.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; import type { JsonValue } from "../domain/jsonValue.js"; import type { NativeValueFlowLimits } from "../domain/native/nativeValueFlow.js"; @@ -34,11 +37,8 @@ import { Utf8NdjsonLineBuffer, Utf8NdjsonDecodingError, } from "../process/Utf8NdjsonLineBuffer.js"; -import { ABORTED, waitForAbortable } from "../process/AbortablePromise.js"; -import { - SharedStartupAttempt, - STARTUP_OWNER_CLOSED, -} from "../process/SharedStartupAttempt.js"; +import { AbortedWait, waitForAbortable } from "../process/AbortablePromise.js"; +import { SharedStartupAttempt } from "../process/SharedStartupAttempt.js"; import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js"; import { ProviderStartupDeadline } from "../process/ProviderDeadline.js"; import { ProviderRunLineage } from "../process/ProviderRunLineage.js"; @@ -300,7 +300,7 @@ export class GhidraClient { if (this.#closePromise !== undefined) return waitForAbortable(this.#closePromise, signal).then( (closed) => - closed === ABORTED + closed instanceof AbortedWait ? err(this.#startupWaitCancellation(signal)) : this.start(signal), (cause: unknown) => @@ -361,7 +361,7 @@ export class GhidraClient { const signalAborted = (): boolean => signal?.aborted === true; if (signalAborted()) return err(this.#startupWaitCancellation(signal)); const waited = await waitForAbortable(attempt.promise, signal); - if (waited === ABORTED || (waited.ok && signalAborted())) + if (waited instanceof AbortedWait || (waited.ok && signalAborted())) return err(this.#startupWaitCancellation(signal)); if (waited.ok || waited.error.cleanupFailure !== undefined) return waited; return this.start(signal); @@ -1561,7 +1561,7 @@ export class GhidraClient { return this.#failure("cancelled", "Ghidra startup was cancelled", cause, { cancellation, }); - if (deadline.signal.reason === STARTUP_OWNER_CLOSED) + if (deadline.signal.reason === OwnerCancellation.startupOwnerClosed) return this.#failure( "process", "Ghidra session closed during startup", diff --git a/src/ghidra/GhidraNativeAotSnapshotOwner.ts b/src/ghidra/GhidraNativeAotSnapshotOwner.ts index 3b62e0a360..74f941ee08 100644 --- a/src/ghidra/GhidraNativeAotSnapshotOwner.ts +++ b/src/ghidra/GhidraNativeAotSnapshotOwner.ts @@ -8,6 +8,7 @@ import { AnalysisArtifactChangedError, cancelledBy, carriedReason, + OwnerCancellation, } from "../domain/analysisErrorCore.js"; import type { JsonValue } from "../domain/jsonValue.js"; import { @@ -24,10 +25,7 @@ import { } from "../domain/native/nativeAotSnapshotObservation.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { err, ok, type Result } from "../domain/result.js"; -import { - SharedStartupAttempt, - STARTUP_OWNER_CLOSED, -} from "../process/SharedStartupAttempt.js"; +import { SharedStartupAttempt } from "../process/SharedStartupAttempt.js"; import type { GhidraClient, GhidraTargetSnapshot } from "./GhidraClient.js"; import { GhidraSessionError } from "./GhidraSessionError.js"; @@ -70,7 +68,11 @@ export class GhidraNativeAotSnapshotOwner { return err(this.#cancelled(operation, callerSignal.reason, observations)); if (this.#closed) return err( - this.#cancelled(operation, STARTUP_OWNER_CLOSED, observations), + this.#cancelled( + operation, + OwnerCancellation.startupOwnerClosed, + observations, + ), ); if (this.#conflict !== undefined) return err(this.#identityError(operation, imageBase, observations)); @@ -115,7 +117,7 @@ export class GhidraNativeAotSnapshotOwner { operation, callerSignal?.aborted ? callerSignal.reason - : STARTUP_OWNER_CLOSED, + : OwnerCancellation.startupOwnerClosed, observations, this.#observation(cached), ), @@ -179,7 +181,7 @@ export class GhidraNativeAotSnapshotOwner { callerSignal?.aborted ? callerSignal.reason : this.#closed - ? STARTUP_OWNER_CLOSED + ? OwnerCancellation.startupOwnerClosed : attempt.signal.reason, observations, this.#observation(settled.value), diff --git a/src/ghidra/GhidraProvider.ts b/src/ghidra/GhidraProvider.ts index 1e2289787d..abaf3e3c13 100644 --- a/src/ghidra/GhidraProvider.ts +++ b/src/ghidra/GhidraProvider.ts @@ -19,10 +19,7 @@ import { DeferredAnalysisClient } from "../providers/DeferredAnalysisClient.js"; import type { ProviderInspectionScope } from "../application/ProviderInspectionScope.js"; import { analysisClientFailureForOperation } from "../providers/AnalysisClientFailure.js"; import { AnalysisCleanupLease } from "../artifacts/AnalysisCleanupLease.js"; -import { - SharedStartupAttempt, - STARTUP_OWNER_CLOSED, -} from "../process/SharedStartupAttempt.js"; +import { SharedStartupAttempt } from "../process/SharedStartupAttempt.js"; import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js"; import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js"; import { bindArtifactFileCleanup } from "../artifacts/ArtifactFileOperation.js"; @@ -72,6 +69,7 @@ import { AnalysisCancelledError, cancelledBy, carriedReason, + OwnerCancellation, } from "../domain/analysisErrorCore.js"; import { resolveGhidraAnalysisSeeds } from "./GhidraAnalysisSeeds.js"; import { @@ -339,7 +337,7 @@ export class GhidraProvider implements AnalysisProviderCandidate { closeOwnedResources() { this.#closing ??= Promise.resolve() .then(async () => { - this.#lifetime.abort(STARTUP_OWNER_CLOSED); + this.#lifetime.abort(OwnerCancellation.startupOwnerClosed); this.#inspectionAttempt?.close(); await Promise.allSettled([ ...this.#inspectionWork, diff --git a/src/hopper/HopperClient.ts b/src/hopper/HopperClient.ts index 99ffb593b0..5e7f5b92e2 100644 --- a/src/hopper/HopperClient.ts +++ b/src/hopper/HopperClient.ts @@ -9,7 +9,10 @@ import writeFileAtomic from "write-file-atomic"; import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; import { analysisClientFailureContext } from "../providers/AnalysisClientFailure.js"; -import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js"; +import { + AnalysisCapabilityUnavailableError, + OwnerCancellation, +} from "../domain/analysisErrorCore.js"; import { hopperCancelledBySignal, type HopperCancelledError, @@ -47,11 +50,8 @@ import { } from "../process/ProviderDeadline.js"; import { redactCapturedTransportCredential } from "../process/ProviderDiagnosticRedaction.js"; import { ProviderRunLineage } from "../process/ProviderRunLineage.js"; -import { ABORTED, waitForAbortable } from "../process/AbortablePromise.js"; -import { - SharedStartupAttempt, - STARTUP_OWNER_CLOSED, -} from "../process/SharedStartupAttempt.js"; +import { AbortedWait, waitForAbortable } from "../process/AbortablePromise.js"; +import { SharedStartupAttempt } from "../process/SharedStartupAttempt.js"; import { type ProviderProcessDiagnostic, ProviderProcessSupervisor, @@ -389,7 +389,7 @@ export class HopperClient { return Promise.resolve(err(hopperCancelledBySignal(signal))); if (this.#closePromise !== undefined) return waitForAbortable(this.#closePromise, signal).then((closed) => - closed === ABORTED + closed instanceof AbortedWait ? err(hopperCancelledBySignal(signal)) : closed.ok ? this.start(signal) @@ -437,7 +437,7 @@ export class HopperClient { signal?: AbortSignal, ): Promise { const waited = await waitForAbortable(attempt.promise, signal); - if (waited === ABORTED || (waited.ok && isAborted(signal))) + if (waited instanceof AbortedWait || (waited.ok && isAborted(signal))) return err(hopperCancelledBySignal(signal)); if (waited.ok || waited.error.cleanupIncomplete) return waited; return this.start(signal); @@ -779,7 +779,7 @@ export class HopperClient { return; const controller = new AbortController(); const timer = setTimeout( - () => controller.abort(), + () => controller.abort(OwnerCancellation.deadlineElapsed), HOPPER_SHUTDOWN_TIMEOUT_MS, ); this.#closing = true; @@ -975,7 +975,7 @@ export class HopperClient { async #startupInterruption( deadline: ProviderStartupDeadline, ): Promise { - if (deadline.signal.reason === STARTUP_OWNER_CLOSED) + if (deadline.signal.reason === OwnerCancellation.startupOwnerClosed) return new HopperProtocolError("Hopper session closed during startup"); if (deadline.interruption === "cancelled") return hopperCancelledBySignal(deadline.signal); diff --git a/src/ida/IdaSessionClient.ts b/src/ida/IdaSessionClient.ts index 237e3399c4..70d971df02 100644 --- a/src/ida/IdaSessionClient.ts +++ b/src/ida/IdaSessionClient.ts @@ -1,6 +1,6 @@ import type { AppConfig } from "../config/types.js"; import { z } from "zod"; -import { ABORTED, waitForAbortable } from "../process/AbortablePromise.js"; +import { AbortedWait, waitForAbortable } from "../process/AbortablePromise.js"; import { createAnalysisExecution, type AnalysisClient, @@ -270,8 +270,8 @@ export class IdaSessionClient implements AnalysisClient { () => undefined, ); const result = await waitForAbortable(call, options?.signal); - return result === ABORTED - ? err(cancelledBy(operation, carriedReason(options?.signal?.reason))) + return result instanceof AbortedWait + ? err(cancelledBy(operation, result)) : result; } diff --git a/src/inspector/V8InspectorProvider.ts b/src/inspector/V8InspectorProvider.ts index faa1c19a7a..51c4459645 100644 --- a/src/inspector/V8InspectorProvider.ts +++ b/src/inspector/V8InspectorProvider.ts @@ -17,7 +17,10 @@ import { type ObserveJavaScriptRuntimeInput, } from "../domain/javascript/javascriptRuntimeObservation.js"; import { AnalysisError } from "../domain/analysisErrorBase.js"; -import { AnalysisCancelledError } from "../domain/analysisErrorCore.js"; +import { + AnalysisCancelledError, + OwnerCancellation, +} from "../domain/analysisErrorCore.js"; import { BrowserObservationError } from "../domain/browserObservationError.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; @@ -789,7 +792,7 @@ const waitForCapture = async ( ]); } finally { // Cancel only this wait's timer. The caller owns and retains its signal. - timerOwner.abort(); + timerOwner.abort(OwnerCancellation.noLongerNeeded); removeDisconnect(); removeProtocolFailure(); } diff --git a/src/kuna/KunaJsonStream.ts b/src/kuna/KunaJsonStream.ts index 10085311be..64c26e3546 100644 --- a/src/kuna/KunaJsonStream.ts +++ b/src/kuna/KunaJsonStream.ts @@ -11,6 +11,7 @@ import type { AnalysisError } from "../domain/analysisErrorBase.js"; import { AnalysisOutputError, AnalysisResourceConstraintError, + OwnerCancellation, } from "../domain/analysisErrorCore.js"; import { err, ok, type Result } from "../domain/result.js"; import { KunaDocumentError } from "./KunaDocumentError.js"; @@ -213,7 +214,7 @@ export abstract class KunaJsonDocumentReader extends Writable { this.#feed(this.#decoder.decode(chunk, { stream: true })); } catch (cause: unknown) { this.#reject(cause); - this.#rejection.abort(); + this.#rejection.abort(OwnerCancellation.noLongerNeeded); } callback(); } diff --git a/src/kuna/KunaProjectCache.ts b/src/kuna/KunaProjectCache.ts index 4f870ebe24..bb35f44f7f 100644 --- a/src/kuna/KunaProjectCache.ts +++ b/src/kuna/KunaProjectCache.ts @@ -36,6 +36,7 @@ import { AnalysisResourceConstraintError, cancelledBy, carriedReason, + OwnerCancellation, } from "../domain/analysisErrorCore.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; @@ -948,7 +949,8 @@ export class KunaProjectCache { if (settled) return; settled = true; leave(); - if (entry.waiters === 0) entry.controller.abort(); + if (entry.waiters === 0) + entry.controller.abort(OwnerCancellation.noLongerNeeded); resolve( err( cancelledBy( diff --git a/src/kuna/KunaProjectReader.ts b/src/kuna/KunaProjectReader.ts index ec03cc8d06..3359c2fdb7 100644 --- a/src/kuna/KunaProjectReader.ts +++ b/src/kuna/KunaProjectReader.ts @@ -30,7 +30,7 @@ import { OwnedRegularFileOperationFailure, withOwnedFileHandle, } from "../filesystem/OwnedRegularFile.js"; -import { ABORTED, waitForAbortable } from "../process/AbortablePromise.js"; +import { AbortedWait, waitForAbortable } from "../process/AbortablePromise.js"; import type { KunaProject } from "./KunaProjectCache.js"; import { scanKunaAssembly, @@ -448,8 +448,7 @@ export class KunaProjectReader { }), ); const index = await waitForAbortable(this.#assembly, signal); - if (index === ABORTED) - return err(cancelledBy(operation, carriedReason(signal?.reason))); + if (index instanceof AbortedWait) return err(cancelledBy(operation, index)); return index.ok ? index : err( diff --git a/src/kuna/KunaSessionClient.ts b/src/kuna/KunaSessionClient.ts index 1c2b07805d..91004b12b6 100644 --- a/src/kuna/KunaSessionClient.ts +++ b/src/kuna/KunaSessionClient.ts @@ -54,7 +54,7 @@ import type { RelationshipCoverage } from "../domain/relationshipCoverage.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { ProviderCleanupError } from "../domain/providerCleanupError.js"; import { err, ok, type Result } from "../domain/result.js"; -import { ABORTED, waitForAbortable } from "../process/AbortablePromise.js"; +import { AbortedWait, waitForAbortable } from "../process/AbortablePromise.js"; import { SharedStartupAttempt } from "../process/SharedStartupAttempt.js"; import { KUNA_INVENTORY_OUTPUT_BYTES, @@ -220,8 +220,8 @@ const waitFor = async ( operation: string, ): Promise> => { const result = await waitForAbortable(work, signal); - return result === ABORTED - ? err(cancelledBy(operation, carriedReason(signal?.reason))) + return result instanceof AbortedWait + ? err(cancelledBy(operation, result)) : result; }; @@ -1694,7 +1694,7 @@ export class KunaSessionClient implements AnalysisClient { ? slot : Promise.race([slot, exported])); if (admitted !== EXPORT_READY) return admitted; - yielded.abort(); + yielded.abort(OwnerCancellation.noLongerNeeded); // A slot granted in the same turn is returned rather than leaked. void slot.then((release) => release?.()); return EXPORT_READY; diff --git a/src/main/eagerRuntime.ts b/src/main/eagerRuntime.ts index 9fadceed79..09bc7de781 100644 --- a/src/main/eagerRuntime.ts +++ b/src/main/eagerRuntime.ts @@ -18,6 +18,7 @@ import { createToolResultDelivery } from "../server/toolResult.js"; import { createShutdown, reportMcpShutdownFailure } from "./shutdown.js"; import { ownStdioStartupInput } from "./StdioStartupInput.js"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; +import { OwnerCancellation } from "../domain/analysisErrorCore.js"; /** * Start the long-lived MCP adapter and install idempotent shutdown handlers. @@ -76,7 +77,7 @@ export const runEager = async ( ...dependencies, registerShutdown: (handler) => dependencies.registerShutdown(() => { - startup.abort(); + startup.abort(OwnerCancellation.ownerClosed); handler(); }), }, @@ -93,7 +94,7 @@ export const runEager = async ( }) : undefined; dependencies.captureShutdown?.(async () => { - startup.abort(); + startup.abort(OwnerCancellation.ownerClosed); await shutdown.shutdown(); }); let ready = false; diff --git a/src/process/AbortablePromise.test.ts b/src/process/AbortablePromise.test.ts new file mode 100644 index 0000000000..4d5dbc8de5 --- /dev/null +++ b/src/process/AbortablePromise.test.ts @@ -0,0 +1,26 @@ +import { expect, it } from "vitest"; + +import { CallerAbort, cancelledBy } from "../domain/analysisErrorCore.js"; +import { AbortedWait, waitForAbortable } from "./AbortablePromise.js"; + +it("carries the reason an abortable wait observed into its cancellation", async () => { + const controller = new AbortController(); + const reason = new CallerAbort("client-disconnected"); + const waiting = waitForAbortable( + new Promise(() => undefined), + controller.signal, + ); + controller.abort(reason); + + const waited = await waiting; + expect(waited).toBeInstanceOf(AbortedWait); + if (!(waited instanceof AbortedWait)) return; + expect(cancelledBy("wait", waited).cause).toBe(reason); +}); + +it("carries the reason of a signal that aborted before the wait began", async () => { + const controller = new AbortController(); + controller.abort("already"); + const waited = await waitForAbortable(Promise.resolve(1), controller.signal); + expect(waited).toEqual(new AbortedWait("already")); +}); diff --git a/src/process/AbortablePromise.ts b/src/process/AbortablePromise.ts index 5069efda03..960e2d034a 100644 --- a/src/process/AbortablePromise.ts +++ b/src/process/AbortablePromise.ts @@ -1,5 +1,13 @@ -/** Sentinel returned when an abort signal wins an asynchronous race. */ -export const ABORTED = Symbol("aborted"); +import type { CarriedCancellationReason } from "../domain/analysisErrorCore.js"; + +/** + * An abortable wait that the signal won. It carries the signal's reason as + * observed when the abort won, so `cancelledBy(operation, waited)` keeps that + * reason without the consumer reading the signal again. + */ +export class AbortedWait implements CarriedCancellationReason { + constructor(readonly carried: unknown) {} +} /** * Await a promise without depending on the producer to observe cancellation. @@ -9,15 +17,15 @@ export const ABORTED = Symbol("aborted"); export const waitForAbortable = async ( pending: Promise, signal: AbortSignal | undefined, -): Promise => { +): Promise => { if (signal === undefined) return pending; let onAbort: (() => void) | undefined; - const cancelled = new Promise((resolve) => { + const cancelled = new Promise((resolve) => { if (signal.aborted) { - resolve(ABORTED); + resolve(new AbortedWait(signal.reason)); return; } - onAbort = () => resolve(ABORTED); + onAbort = () => resolve(new AbortedWait(signal.reason)); signal.addEventListener("abort", onAbort, { once: true }); }); try { diff --git a/src/process/DarwinProcessRunTokenReader.ts b/src/process/DarwinProcessRunTokenReader.ts index 5d35774bae..c1d55f4851 100644 --- a/src/process/DarwinProcessRunTokenReader.ts +++ b/src/process/DarwinProcessRunTokenReader.ts @@ -1,3 +1,4 @@ +import { OwnerCancellation } from "../domain/analysisErrorCore.js"; import { assertProcessOwnershipInspectionActive, ProcessOwnershipInspectionCancelled, @@ -698,7 +699,7 @@ export const createDarwinProcessRunTokenReader = ( !operation.aborting ) { operation.aborting = true; - operation.controller.abort(); + operation.controller.abort(OwnerCancellation.noLongerNeeded); const finalized = await operation.promise; if ( waited.kind === "cancelled" && @@ -874,7 +875,7 @@ export const createDarwinProcessRunTokenReader = ( const operation = compilation; if (operation !== undefined && !operation.settled) { operation.aborting = true; - operation.controller.abort(); + operation.controller.abort(OwnerCancellation.ownerClosed); await operation.promise; } await Promise.allSettled(activeCommands); diff --git a/src/process/OwnedCommand.ts b/src/process/OwnedCommand.ts index 515638421c..86c696a32a 100644 --- a/src/process/OwnedCommand.ts +++ b/src/process/OwnedCommand.ts @@ -1,3 +1,4 @@ +import { OwnerCancellation } from "../domain/analysisErrorCore.js"; import type { ProcessInspectionFailure } from "./ProcessInspectionCleanup.js"; import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js"; import { @@ -31,7 +32,7 @@ import { type OwnedProcessGroup, type ProcessCleanupFailure, } from "./ProcessOwnership.js"; -import { ABORTED, waitForAbortable } from "./AbortablePromise.js"; +import { AbortedWait, waitForAbortable } from "./AbortablePromise.js"; import type { ManagedRuntime } from "./RuntimeExhaustion.js"; import { ProviderStartupDeadline, @@ -371,7 +372,7 @@ const collectOwnedCommand = async ( processError, collectionFailure: true, }; - abandoned.abort(); + abandoned.abort(OwnerCancellation.noLongerNeeded); }) : Promise.resolve(); let failure: OwnedCommandFailure | undefined; @@ -431,7 +432,7 @@ const collectOwnedCommand = async ( } // Output has closed, but the sink may still be parsing what it buffered. const sinkFailure = await waitForAbortable(consumed, collectionSignal); - if (sinkFailure !== ABORTED) processFailure ??= sinkFailure; + if (!(sinkFailure instanceof AbortedWait)) processFailure ??= sinkFailure; await waitForAbortable(inputCompleted, collectionSignal); const snapshot = supervisor.snapshot(); const interrupted = interruptionOrObservedFailure( @@ -482,7 +483,7 @@ const collectOwnedCommand = async ( ); } // A finished sink ignores this; an unfinished one is destroyed. - abandoned.abort(); + abandoned.abort(OwnerCancellation.noLongerNeeded); const stopped = await supervisor.stop(); const snapshot = supervisor.snapshot(); // An input error can arrive after finish while process cleanup is still pending. diff --git a/src/process/SharedStartupAttempt.test.ts b/src/process/SharedStartupAttempt.test.ts index c6deca0482..3b91d3a34e 100644 --- a/src/process/SharedStartupAttempt.test.ts +++ b/src/process/SharedStartupAttempt.test.ts @@ -1,10 +1,8 @@ import { expect, it } from "vitest"; import { createDeferred } from "../../tests/fixtures/binarySession.js"; -import { - SharedStartupAttempt, - STARTUP_OWNER_CLOSED, -} from "./SharedStartupAttempt.js"; +import { OwnerCancellation } from "../domain/analysisErrorCore.js"; +import { SharedStartupAttempt } from "./SharedStartupAttempt.js"; it("keeps shared startup running for an interested peer and returns the departing caller's reason", async () => { const completed = createDeferred(); @@ -57,7 +55,7 @@ it("distinguishes provider closure from a caller's cancellation", async () => { const controller = new AbortController(); const waiting = attempt.wait(controller.signal); attempt.close(); - expect(attempt.signal.reason).toBe(STARTUP_OWNER_CLOSED); + expect(attempt.signal.reason).toBe(OwnerCancellation.startupOwnerClosed); expect(controller.signal.aborted).toBe(false); cleanup.resolve("provider stopped"); await expect(waiting).resolves.toEqual({ @@ -97,11 +95,11 @@ it.each(["caller", "owner"])( } else { attempt.close(); expect(attempt.signal.aborted).toBe(true); - expect(attempt.signal.reason).toBe(STARTUP_OWNER_CLOSED); + expect(attempt.signal.reason).toBe(OwnerCancellation.startupOwnerClosed); controller.abort(reason); } expect(attempt.signal.reason).toBe( - first === "caller" ? reason : STARTUP_OWNER_CLOSED, + first === "caller" ? reason : OwnerCancellation.startupOwnerClosed, ); expect(attempt.settled).toBe(false); completed.resolve("finalized"); diff --git a/src/process/SharedStartupAttempt.ts b/src/process/SharedStartupAttempt.ts index 5c683b8837..f0d5f011e8 100644 --- a/src/process/SharedStartupAttempt.ts +++ b/src/process/SharedStartupAttempt.ts @@ -1,7 +1,5 @@ -import { ABORTED, waitForAbortable } from "./AbortablePromise.js"; - -/** An owner closing a provider is distinct from a caller cancelling its wait. */ -export const STARTUP_OWNER_CLOSED = Symbol("provider startup owner closed"); +import { OwnerCancellation } from "../domain/analysisErrorCore.js"; +import { AbortedWait, waitForAbortable } from "./AbortablePromise.js"; /** The final departing caller retains the producer's complete cleanup result. */ export type SharedStartupWait = @@ -57,9 +55,13 @@ export class SharedStartupAttempt { return this.#settlement; } - /** Stop startup when its owning provider closes, regardless of active waits. */ + /** + * Stop startup when its owning provider closes, regardless of active waits. + * The reason is distinct from a caller's cancelling its wait. + */ close(): void { - if (!this.settled) this.#controller.abort(STARTUP_OWNER_CLOSED); + if (!this.settled) + this.#controller.abort(OwnerCancellation.startupOwnerClosed); } /** A peer's departure leaves the producer running; final departure joins cleanup. */ @@ -67,10 +69,11 @@ export class SharedStartupAttempt { this.#waiters += 1; try { const waited = await waitForAbortable(this.promise, signal); - if (waited !== ABORTED) return { status: "completed", value: waited }; + if (!(waited instanceof AbortedWait)) + return { status: "completed", value: waited }; if (this.#waiters > 1) - return { status: "cancelled", reason: signal?.reason }; - if (!this.settled) this.#controller.abort(signal?.reason); + return { status: "cancelled", reason: waited.carried }; + if (!this.settled) this.#controller.abort(waited.carried); return { status: "stopped", value: await this.promise }; } finally { this.#waiters -= 1; diff --git a/src/process/WindowsExecutable.ts b/src/process/WindowsExecutable.ts index f0e0836fba..b74f6e6174 100644 --- a/src/process/WindowsExecutable.ts +++ b/src/process/WindowsExecutable.ts @@ -2,7 +2,7 @@ import { stat } from "node:fs/promises"; import { win32 } from "node:path"; import { err, ok, type Result } from "../domain/result.js"; -import { ABORTED, waitForAbortable } from "./AbortablePromise.js"; +import { AbortedWait, waitForAbortable } from "./AbortablePromise.js"; import { snapshotEnvironment } from "./snapshotEnvironment.js"; /** Parse PATH once, preserving quoted semicolons and explicit relative entries. */ @@ -85,7 +85,7 @@ export const findWindowsExecutable = async ( stat(candidate), options.signal, ); - if (metadata === ABORTED || options.signal.aborted) + if (metadata instanceof AbortedWait || options.signal.aborted) return err({ kind: "interrupted" }); if (metadata.isFile()) return ok(candidate); } catch (cause: unknown) { diff --git a/src/process/WorkerFrameSignal.ts b/src/process/WorkerFrameSignal.ts index dae2a2ee01..ef234ebb36 100644 --- a/src/process/WorkerFrameSignal.ts +++ b/src/process/WorkerFrameSignal.ts @@ -1,3 +1,4 @@ +import { OwnerCancellation } from "../domain/analysisErrorCore.js"; import type { ProviderProcessSupervisor } from "./ProviderProcess.js"; type FrameOutcome = "frame" | "failure"; @@ -37,7 +38,7 @@ export class WorkerFrameSignal { ); return await Promise.race([frameAvailable, outputClose]); } finally { - outputCloseController.abort(); + outputCloseController.abort(OwnerCancellation.noLongerNeeded); signal.removeEventListener("abort", interruptOutputClose); this.#waiters.delete(wakeFrame); } diff --git a/src/process/capture/ProcessCaptureLifecycle.ts b/src/process/capture/ProcessCaptureLifecycle.ts index d45047fba3..3a861e0767 100644 --- a/src/process/capture/ProcessCaptureLifecycle.ts +++ b/src/process/capture/ProcessCaptureLifecycle.ts @@ -1,3 +1,4 @@ +import { OwnerCancellation } from "../../domain/analysisErrorCore.js"; import { createHash, randomUUID } from "node:crypto"; import { constants, statSync, type BigIntStats } from "node:fs"; import { open, mkdtemp, rm, stat } from "node:fs/promises"; @@ -933,7 +934,7 @@ export const awaitTerminalExit = async ({ })), ]) .finally(() => { - deliveryBound.abort(); + deliveryBound.abort(OwnerCancellation.noLongerNeeded); }) .then( ({ delivery, reason: deliveryReason }) => { @@ -1044,7 +1045,7 @@ export const awaitTerminalExit = async ({ }).catch(() => undefined), ]) .finally(() => { - grace.abort(); + grace.abort(OwnerCancellation.noLongerNeeded); }) .then(finish); }); diff --git a/src/rizin/RizinDebugSessionManager.ts b/src/rizin/RizinDebugSessionManager.ts index 944271c089..2621354205 100644 --- a/src/rizin/RizinDebugSessionManager.ts +++ b/src/rizin/RizinDebugSessionManager.ts @@ -62,7 +62,7 @@ import { } from "../process/ownedDebuggerSession.js"; import { OwnedDebuggerSessionRegistry } from "../process/OwnedDebuggerSessionRegistry.js"; import { absoluteCallerPath } from "../filesystem/callerPath.js"; -import { ABORTED, waitForAbortable } from "../process/AbortablePromise.js"; +import { AbortedWait, waitForAbortable } from "../process/AbortablePromise.js"; import { utf8HeadExcerpt } from "../domain/utf8HeadExcerpt.js"; const CLEANUP_COMMAND_TIMEOUT_MS = 1_000; @@ -2002,7 +2002,7 @@ const waitForTurn = ( ): Promise => { if (signal === undefined) return previous; return waitForAbortable(previous, signal).then((outcome) => { - if (outcome === ABORTED) + if (outcome instanceof AbortedWait) throw rizinCancellation("rizin_debug_command", signal); }); }; diff --git a/src/server/EvidenceMcpServer.test.ts b/src/server/EvidenceMcpServer.test.ts index 7381c97f2f..89f64d68e8 100644 --- a/src/server/EvidenceMcpServer.test.ts +++ b/src/server/EvidenceMcpServer.test.ts @@ -12,10 +12,13 @@ import { import { serveStdio } from "@modelcontextprotocol/server/stdio"; import { z } from "zod"; +import { CallerAbort, OwnerCancellation } from "../domain/analysisErrorCore.js"; import { InvestigationRecords } from "../application/investigation/InvestigationRecords.js"; import { OFFICIAL_TOOL_CONTRACTS } from "../contracts/officialToolContracts.js"; import { EvidenceMcpServer } from "./EvidenceMcpServer.js"; import { forgetPendingMcpRequest } from "./EvidenceMcpServerCore.js"; +import { createDeferred } from "../../tests/fixtures/binarySession.js"; +import { awaitAcknowledgement } from "../../tests/fixtures/lifecycleAcknowledgement.js"; import { createToolResultDelivery } from "./toolResult.js"; const firstText = (result: { @@ -102,20 +105,208 @@ describe("MCP request bookkeeping", () => { const pendingToolLists = new Set([7]); const pendingCompletions = new Map([[7, completion]]); + const cancellation = new CallerAbort("request-cancelled", "user stopped"); + forgetPendingMcpRequest( pendingTools, pendingToolLists, pendingCompletions, 7, + cancellation, ); expect(pendingTools.has(7)).toBe(false); expect(pendingToolLists.has(7)).toBe(false); - expect(completion.signal.aborted).toBe(true); + expect(completion.signal.reason).toBe(cancellation); expect(pendingCompletions.has(7)).toBe(false); }); }); +it("passes the owned cancellation signal to a tool without an input schema", async () => { + const records = new InvestigationRecords(); + const server = new EvidenceMcpServer( + { name: "no-input-abort-test", version: "1" }, + { capabilities: {} }, + (evidence) => records.recordEvidence(evidence), + createToolResultDelivery(4096), + ); + const entered = createDeferred(); + const observed = createDeferred(); + const release = createDeferred(); + const finished = createDeferred(); + let started = false; + server.registerTool("held", {}, async (context) => { + const signal = context.mcpReq.signal; + signal.addEventListener("abort", () => observed.resolve(signal.reason), { + once: true, + }); + started = true; + entered.resolve(); + try { + await release.promise; + return { content: [{ type: "text", text: "finished" }] }; + } finally { + finished.resolve(); + } + }); + const client = new Client( + { name: "no-input-abort-client", version: "1" }, + { versionNegotiation: { mode: { pin: "2026-07-28" } } }, + ); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + const serving = serveStdio(() => server, { transport: serverTransport }); + try { + await client.connect(clientTransport); + const controller = new AbortController(); + const pending = client + .callTool({ name: "held" }, { signal: controller.signal }) + .catch(() => undefined); + await awaitAcknowledgement( + entered.promise, + pending, + "held tool handler entry", + ); + controller.abort("stop no-input tool"); + await pending; + expect(await observed.promise).toMatchObject({ + kind: "request-cancelled", + clientReason: "stop no-input tool", + }); + } finally { + release.resolve(); + if (started) await finished.promise; + await Promise.all([client.close(), serving.close()]); + } +}); + +it("aborts a running tool with a caller abort that keeps the client's reason", async () => { + const records = new InvestigationRecords(); + const server = new EvidenceMcpServer( + { name: "caller-abort-test", version: "1" }, + { capabilities: {} }, + (evidence) => records.recordEvidence(evidence), + createToolResultDelivery(4096), + ); + const entered = createDeferred(); + const observed = createDeferred(); + const release = createDeferred(); + const finished = createDeferred(); + let started = false; + server.registerTool( + "held", + { inputSchema: z.strictObject({}) }, + async (_input, context) => { + const signal = context.mcpReq.signal; + signal.addEventListener("abort", () => observed.resolve(signal.reason), { + once: true, + }); + started = true; + entered.resolve(undefined); + try { + await release.promise; + return { content: [{ type: "text", text: "finished" }] }; + } finally { + finished.resolve(); + } + }, + ); + const client = new Client( + { name: "caller-abort-client", version: "1" }, + { versionNegotiation: { mode: { pin: "2026-07-28" } } }, + ); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + const serving = serveStdio(() => server, { transport: serverTransport }); + try { + await client.connect(clientTransport); + const controller = new AbortController(); + const pending = client.callTool( + { name: "held", arguments: {} }, + { signal: controller.signal }, + ); + const rejected = expect(pending).rejects.toBeDefined(); + await awaitAcknowledgement( + entered.promise, + pending, + "held tool handler entry", + ); + controller.abort("user stopped"); + await rejected; + + const reason = await observed.promise; + expect(reason).toBeInstanceOf(CallerAbort); + expect(reason).toMatchObject({ + kind: "request-cancelled", + clientReason: "user stopped", + name: "AbortError", + }); + } finally { + release.resolve(); + if (started) await finished.promise; + await Promise.all([client.close(), serving.close()]); + } +}); + +it("reports owner shutdown to the handler when transport close invokes onclose", async () => { + const records = new InvestigationRecords(); + const server = new EvidenceMcpServer( + { name: "owner-close-test", version: "1" }, + { capabilities: {} }, + (evidence) => records.recordEvidence(evidence), + createToolResultDelivery(4096), + ); + const entered = createDeferred(); + const observed = createDeferred(); + const release = createDeferred(); + const finished = createDeferred(); + let started = false; + server.registerTool( + "held", + { inputSchema: z.strictObject({}) }, + async (_input, context) => { + context.mcpReq.signal.addEventListener( + "abort", + () => observed.resolve(context.mcpReq.signal.reason), + { once: true }, + ); + started = true; + entered.resolve(); + try { + await release.promise; + return { content: [{ type: "text", text: "finished" }] }; + } finally { + finished.resolve(); + } + }, + ); + const client = new Client( + { name: "owner-close-client", version: "1" }, + { versionNegotiation: { mode: { pin: "2026-07-28" } } }, + ); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + const serving = serveStdio(() => server, { transport: serverTransport }); + try { + await client.connect(clientTransport); + const pending = client + .callTool({ name: "held", arguments: {} }) + .catch(() => undefined); + await awaitAcknowledgement( + entered.promise, + pending, + "held tool handler entry", + ); + await server.close(); + expect(await observed.promise).toBe(OwnerCancellation.ownerClosed); + await pending; + } finally { + release.resolve(); + if (started) await finished.promise; + await Promise.all([client.close(), serving.close()]); + } +}); + describe("Modern protocol error delivery", () => { it("preserves the modern wire envelope when replacing an oversized error", async () => { const records = new InvestigationRecords(); diff --git a/src/server/EvidenceMcpServerCore.ts b/src/server/EvidenceMcpServerCore.ts index e8faff245f..91549e1fac 100644 --- a/src/server/EvidenceMcpServerCore.ts +++ b/src/server/EvidenceMcpServerCore.ts @@ -16,6 +16,7 @@ import { type McpServerOptions, type RegisteredTool, type RegisteredPrompt, + type ServerContext, type PromptCallback, type RequestId, type ScopeChallengeHandler, @@ -27,6 +28,7 @@ import { } from "@modelcontextprotocol/server"; import { analysisErrorProjectionSchema } from "../contracts/errorSchemas.js"; +import { transportClosedByOwner } from "./transportOwnerClose.js"; import { presentAdvertisedInputSchema, type CompactInputSchemaPresentation, @@ -42,6 +44,8 @@ import type { EvidenceWriter } from "../application/investigation/InvestigationR import { AnalysisInputError, AnalysisResourceConstraintError, + CallerAbort, + OwnerCancellation, type AnalysisInputIssue, } from "../domain/analysisErrorCore.js"; import { projectAnalysisErrorWithoutPartialObservation } from "../domain/analysisErrorProjection.js"; @@ -279,10 +283,11 @@ export const forgetPendingMcpRequest = ( pendingToolLists: Set, pendingCompletions: Map, id: RequestId, + reason: CallerAbort | OwnerCancellation, ): void => { pendingTools.delete(id); pendingToolLists.delete(id); - pendingCompletions.get(id)?.abort(); + pendingCompletions.get(id)?.abort(reason); pendingCompletions.delete(id); }; import type { PromptCompletionSource } from "./promptCompletion.js"; @@ -471,9 +476,31 @@ export class EvidenceMcpServerCore extends RequestTrackingMcpServer { const request = currentMcpToolRequest(); request?.beginHandler(); try { + const normalized = (original: ServerContext): ServerContext => + request === undefined + ? original + : { + ...original, + mcpReq: { + ...original.mcpReq, + signal: AbortSignal.any([ + request.cancellation.signal, + original.mcpReq.signal, + ]), + }, + }; + const invoke = () => + config.inputSchema === undefined + ? (callback as ToolCallback)( + normalized(input as ServerContext), + ) + : (callback as ToolCallback)( + input, + normalized(context as ServerContext), + ); return await (this.analysisSettings === undefined - ? callback(input, context) - : this.analysisSettings.run(() => callback(input, context))); + ? invoke() + : this.analysisSettings.run(invoke)); } finally { request?.finishHandler(); } @@ -542,6 +569,7 @@ class ErrorEvidenceTransport implements Transport { private readonly pendingValidation = new Map(); private readonly pendingToolLists = new Set(); private readonly pendingCompletions = new Map(); + private closing = false; private get recordEvidence(): EvidenceWriter["recordEvidence"] | undefined { return this.currentEvidenceWriter(); @@ -615,13 +643,18 @@ class ErrorEvidenceTransport implements Transport { ) { const id = message.params?.["requestId"]; if (typeof id === "string" || typeof id === "number") { - this.pendingValidation.get(id)?.cancel(message.params?.["reason"]); + const cancellation = new CallerAbort( + "request-cancelled", + message.params?.["reason"], + ); + this.pendingValidation.get(id)?.cancel(cancellation); this.pendingValidation.delete(id); forgetPendingMcpRequest( this.pendingTools, this.pendingToolLists, this.pendingCompletions, id, + cancellation, ); } } @@ -639,13 +672,17 @@ class ErrorEvidenceTransport implements Transport { }; transport.onerror = (error) => this.onerror?.(error); transport.onclose = () => { + const disconnected = + this.closing || transportClosedByOwner(this.transport) + ? OwnerCancellation.ownerClosed + : new CallerAbort("client-disconnected"); this.pendingTools.clear(); for (const validation of this.pendingValidation.values()) - validation.cancel(); + validation.cancel(disconnected); this.pendingValidation.clear(); this.pendingToolLists.clear(); for (const completion of this.pendingCompletions.values()) - completion.abort(); + completion.abort(disconnected); this.pendingCompletions.clear(); this.onclose?.(); }; @@ -663,16 +700,17 @@ class ErrorEvidenceTransport implements Transport { } async close(): Promise { + this.closing = true; try { await this.transport.close(); } finally { this.pendingTools.clear(); for (const validation of this.pendingValidation.values()) - validation.cancel(); + validation.cancel(OwnerCancellation.ownerClosed); this.pendingValidation.clear(); this.pendingToolLists.clear(); for (const completion of this.pendingCompletions.values()) - completion.abort(); + completion.abort(OwnerCancellation.ownerClosed); this.pendingCompletions.clear(); } } @@ -756,11 +794,13 @@ class ErrorEvidenceTransport implements Transport { request?.finishPublication(); if (!isJSONRPCRequest(message) && id !== undefined) { this.pendingValidation.delete(id); + // The reply settled the request, so REA ends any work it left behind. forgetPendingMcpRequest( this.pendingTools, this.pendingToolLists, this.pendingCompletions, id, + OwnerCancellation.ownerClosed, ); } } diff --git a/src/server/McpToolRequest.ts b/src/server/McpToolRequest.ts index db740999e4..479b97073f 100644 --- a/src/server/McpToolRequest.ts +++ b/src/server/McpToolRequest.ts @@ -5,7 +5,11 @@ import type { z } from "zod"; import type { AnalysisOperationPort } from "../application/AnalysisProvider.js"; import type { BinarySessionPort } from "../application/binary/BinarySessionPort.js"; import type { AnalysisError } from "../domain/analysisErrorBase.js"; -import { cancelledBy } from "../domain/analysisErrorCore.js"; +import { + cancelledBy, + type CallerAbort, + type OwnerCancellation, +} from "../domain/analysisErrorCore.js"; import { err, ok, type Result } from "../domain/result.js"; const currentRequest = new AsyncLocalStorage(); @@ -54,7 +58,7 @@ export class McpToolRequest { } /** A suppressed SDK reply releases admission after the handler's cleanup. */ - cancel(reason?: unknown): void { + cancel(reason: CallerAbort | OwnerCancellation): void { this.cancellation.abort(reason); if (!this.#publicationStarted) this.#finishPublication(); } diff --git a/src/server/http/nodeHttpBridge.test.ts b/src/server/http/nodeHttpBridge.test.ts index 68bdfa7c02..562d368e20 100644 --- a/src/server/http/nodeHttpBridge.test.ts +++ b/src/server/http/nodeHttpBridge.test.ts @@ -10,6 +10,7 @@ import { type WebResponseOptions, } from "./nodeHttpBridge.js"; import { waitFor } from "../../../tests/support/testWait.js"; +import { CallerAbort } from "../../domain/analysisErrorCore.js"; const servers: Server[] = []; const encoder = new TextEncoder(); @@ -241,11 +242,11 @@ it("streams response chunks as the handler produces them", async () => { }); it("aborts the web Request and cancels its response body when the client leaves", async () => { - let aborted = false; + let aborted: unknown; let cancelled = false; const origin = await serve((request) => { request.signal.addEventListener("abort", () => { - aborted = true; + aborted = request.signal.reason; }); return new Response( new ReadableStream({ @@ -268,7 +269,8 @@ it("aborts the web Request and cancels its response body when the client leaves" await reader.read(); controller.abort(); await waitFor(() => { - expect(aborted).toBe(true); + expect(aborted).toBeInstanceOf(CallerAbort); + expect(aborted).toMatchObject({ kind: "client-disconnected" }); expect(cancelled).toBe(true); }); }); diff --git a/src/server/http/nodeHttpBridge.ts b/src/server/http/nodeHttpBridge.ts index cb44b9094d..6cab2227b0 100644 --- a/src/server/http/nodeHttpBridge.ts +++ b/src/server/http/nodeHttpBridge.ts @@ -1,5 +1,6 @@ import type { IncomingMessage, ServerResponse } from "node:http"; import { finished } from "node:stream"; +import { CallerAbort } from "../../domain/analysisErrorCore.js"; /** Fetch rejects a body on these methods, so their request streams are not forwarded. */ const BODYLESS_METHODS: ReadonlySet = new Set(["GET", "HEAD"]); @@ -93,7 +94,8 @@ export const toWebRequest = ( ): Request => { const controller = new AbortController(); response.once("close", () => { - if (!response.writableFinished) controller.abort(); + if (!response.writableFinished) + controller.abort(new CallerAbort("client-disconnected")); }); const method = request.method ?? "GET"; return new Request(requestUrl(request.url ?? "/", origin), { diff --git a/src/server/http/serveStreamableHttp.test.ts b/src/server/http/serveStreamableHttp.test.ts index 2cb16c3bb8..ea7a308855 100644 --- a/src/server/http/serveStreamableHttp.test.ts +++ b/src/server/http/serveStreamableHttp.test.ts @@ -27,6 +27,13 @@ import { parseMcpHttpArguments } from "../../main/mcpHttpArguments.js"; import { RequestTrackingMcpServer } from "../RequestTrackingMcpServer.js"; import { waitFor } from "../../../tests/support/testWait.js"; import { ProviderCleanupError } from "../../domain/providerCleanupError.js"; +import { + CallerAbort, + OwnerCancellation, +} from "../../domain/analysisErrorCore.js"; +import { EvidenceMcpServer } from "../EvidenceMcpServer.js"; +import { createToolResultDelivery } from "../toolResult.js"; +import { ok } from "../../domain/result.js"; const servers: StreamableHttpServer[] = []; @@ -2122,3 +2129,76 @@ it.each(["after timeout", "during drain"])( } }, ); + +it.each(["replacement", "shutdown", "DELETE"] as const)( + "tells a pending Evidence tool who ended its session after %s", + async (ending) => { + let release!: () => void; + let entered!: () => void; + let observed!: (reason: unknown) => void; + const gate = new Promise((resolve) => { + release = resolve; + }); + const started = new Promise((resolve) => { + entered = resolve; + }); + const aborted = new Promise((resolve) => { + observed = resolve; + }); + const { served } = await start({ + createMcpServer: () => { + const server = new EvidenceMcpServer( + { name: "owner-close-http", version: "1" }, + { capabilities: {} }, + () => ok("added"), + createToolResultDelivery(4096), + ); + server.registerTool( + "held", + { inputSchema: z.strictObject({}) }, + async (_args, context) => { + context.mcpReq.signal.addEventListener( + "abort", + () => observed(context.mcpReq.signal.reason), + { once: true }, + ); + entered(); + await gate; + return { content: [] }; + }, + ); + return server; + }, + }); + const first = await connect(served.url); + const request = first.client + .callTool({ name: "held", arguments: {} }) + .catch(() => undefined); + let ended: Promise | undefined; + try { + await awaitAcknowledgement(started, request, "tool start"); + ended = + ending === "DELETE" + ? first.transport.terminateSession() + : ending === "shutdown" + ? served.prepareShutdown() + : connect(served.url).then((next) => next.client.close()); + await awaitAcknowledgement( + aborted.then(() => undefined), + ended, + "tool abort", + ); + const reason = await aborted; + if (ending === "DELETE") expect(reason).toBeInstanceOf(CallerAbort); + else expect(reason).toBe(OwnerCancellation.ownerClosed); + } finally { + release(); + await closeVerifierResources([ + () => first.client.close(), + async () => { + await Promise.allSettled([request, ended]); + }, + ]); + } + }, +); diff --git a/src/server/http/serveStreamableHttp.ts b/src/server/http/serveStreamableHttp.ts index 2f5547f370..80bdff3622 100644 --- a/src/server/http/serveStreamableHttp.ts +++ b/src/server/http/serveStreamableHttp.ts @@ -29,6 +29,7 @@ import { writeWebResponse, } from "./nodeHttpBridge.js"; import { listenHttpServer } from "./listenHttpServer.js"; +import { markTransportOwnerClose } from "../transportOwnerClose.js"; import { StreamableHttpHostAllowlistError, StreamableHttpListenError, @@ -39,7 +40,10 @@ import { type NodeHttpExchangeContext, } from "./NodeHttpRequestOwner.js"; import { RequestTrackingMcpServer } from "../RequestTrackingMcpServer.js"; -import { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js"; +import { + AnalysisResourceConstraintError, + OwnerCancellation, +} from "../../domain/analysisErrorCore.js"; /** MCP endpoint path shared by `rea mcp --http` and agent environment servers. */ export const MCP_HTTP_PATH = "/mcp"; @@ -281,7 +285,7 @@ class LiveSession { } finally { // Header/size refusals can leave the SDK body unread. Its forwarding // stream belongs to this dispatch, not the remaining session lifetime. - bodyAbort.abort(); + bodyAbort.abort(OwnerCancellation.ownerClosed); } }), ); @@ -289,11 +293,20 @@ class LiveSession { shutdown(): Promise { this.#closed = true; - this.#bodyAbort.abort(); + this.#bodyAbort.abort(OwnerCancellation.ownerClosed); return this.#shutdown(); } } +/** + * End a session REA chose to end (replacement or shutdown). A DELETE closes + * the same transport through the SDK; only that close is the client's. + */ +const closeAsOwner = (session: LiveSession): Promise => { + markTransportOwnerClose(session.transport); + return session.transport.close(); +}; + /** Owns the single connected server and the transport of its current session. */ export class McpSessionSlot { #live: LiveSession | undefined; @@ -358,7 +371,7 @@ export class McpSessionSlot { ) { if (this.#closed) return SHUTTING_DOWN(); this.logger?.info("MCP HTTP session replaced by a new client"); - await open.transport.close(); + await closeAsOwner(open); } if (this.#closed) return SHUTTING_DOWN(); const session = await this.#current(); @@ -374,7 +387,7 @@ export class McpSessionSlot { const open = this.#live; // The session stays owned until its shutdown succeeds, so a retry can finish it. try { - await open?.transport.close(); + if (open !== undefined) await closeAsOwner(open); } catch (cause: unknown) { // Shutdown may have joined a handover that already started its bounded // drain. Retry that timeout with shutdown's completion-based wait. diff --git a/src/server/transportOwnerClose.ts b/src/server/transportOwnerClose.ts new file mode 100644 index 0000000000..0dc6c95473 --- /dev/null +++ b/src/server/transportOwnerClose.ts @@ -0,0 +1,18 @@ +import type { Transport } from "@modelcontextprotocol/server"; + +/** + * Transports their owner closed. An owner that closes the underlying transport + * itself, rather than through the server's `close()`, marks it first, so the + * Evidence transport reports pending work as ended by an owner close and not + * by a client disconnect. + */ +const ownerClosedTransports = new WeakSet(); + +/** Record that the owner, not the client, is closing this transport. */ +export const markTransportOwnerClose = (transport: Transport): void => { + ownerClosedTransports.add(transport); +}; + +/** Whether the owner closed this transport. */ +export const transportClosedByOwner = (transport: Transport): boolean => + ownerClosedTransports.has(transport); diff --git a/tests/boundary/cli/androidCliCancellation.test.ts b/tests/boundary/cli/androidCliCancellation.test.ts index 603091822d..3d18406c0b 100644 --- a/tests/boundary/cli/androidCliCancellation.test.ts +++ b/tests/boundary/cli/androidCliCancellation.test.ts @@ -4,23 +4,26 @@ import { withCommandCancellation, type CommandCancellationHost, } from "../../../src/cli/commandCancellation.js"; +import { CallerAbort } from "../../../src/domain/analysisErrorCore.js"; it.each([ - ["SIGINT", 130], - ["SIGTERM", 143], + ["SIGINT", 130, "interrupt"], + ["SIGTERM", 143, "terminate"], ] as const)( "awaits cleanup after %s and removes its listeners", - async (event, expectedExit) => { + async (event, expectedExit, expectedKind) => { const events = new EventEmitter(); const host: CommandCancellationHost = { on: events.on.bind(events), off: events.off.bind(events), }; let cleaned = false; + let reason: unknown; const operation = withCommandCancellation(async (signal) => { await new Promise((resolve) => signal.addEventListener("abort", () => resolve(), { once: true }), ); + reason = signal.reason; cleaned = true; return "cancelled after cleanup"; }, host); @@ -28,6 +31,9 @@ it.each([ events.emit(event); expect(await operation).toBe("cancelled after cleanup"); expect(cleaned).toBe(true); + // The adapter names its caller; a platform AbortError shape is kept. + expect(reason).toBeInstanceOf(CallerAbort); + expect(reason).toMatchObject({ kind: expectedKind, name: "AbortError" }); expect(host.exitCode).toBe(expectedExit); expect(events.listenerCount("SIGINT")).toBe(0); expect(events.listenerCount("SIGTERM")).toBe(0); diff --git a/tests/boundary/filesystem/ghidraProfileArtifactOwnership.test.ts b/tests/boundary/filesystem/ghidraProfileArtifactOwnership.test.ts index 8b0ec0e5ad..d37bd80bd3 100644 --- a/tests/boundary/filesystem/ghidraProfileArtifactOwnership.test.ts +++ b/tests/boundary/filesystem/ghidraProfileArtifactOwnership.test.ts @@ -6,9 +6,9 @@ import { GhidraHeadlessLauncher } from "../../../src/ghidra/GhidraLauncher.js"; import { GhidraProvider } from "../../../src/ghidra/GhidraProvider.js"; import { ghidraProfileInstallationHost } from "../../../src/ghidra/GhidraInstallation.fixture.js"; import { silentLogger } from "../../../src/logger.js"; +import { OwnerCancellation } from "../../../src/domain/analysisErrorCore.js"; import { createDeferred } from "../../fixtures/binarySession.js"; import { awaitAcknowledgement } from "../../fixtures/lifecycleAcknowledgement.js"; -import { STARTUP_OWNER_CLOSED } from "../../../src/process/SharedStartupAttempt.js"; import { readFile, rename, @@ -414,13 +414,13 @@ it("joins whole provider resolution before shutdown and gates the next admission release.resolve(); const stopped = await resolving; if (stopped.ok) throw new Error("Expected owned resolution cancellation"); - expect(stopped.error.cause).toBe(STARTUP_OWNER_CLOSED); + expect(stopped.error.cause).toBe(OwnerCancellation.startupOwnerClosed); expect(stopped).toMatchObject({ ok: false, error: { _tag: "AnalysisCancelledError", operation: "open_binary", - cause: STARTUP_OWNER_CLOSED, + cause: OwnerCancellation.startupOwnerClosed, }, }); expect(await closing).toEqual({ ok: true, value: null }); diff --git a/tests/boundary/process/darwinProcessRunTokenReader.test.ts b/tests/boundary/process/darwinProcessRunTokenReader.test.ts index 3292c71154..8cfae8cf0b 100644 --- a/tests/boundary/process/darwinProcessRunTokenReader.test.ts +++ b/tests/boundary/process/darwinProcessRunTokenReader.test.ts @@ -3,6 +3,7 @@ import { rethrowProcessOwnershipInspectionFailure, } from "../../../src/process/ProcessInspectionCancellation.js"; import { primaryAnalysisError } from "../../../src/domain/analysisErrorBase.js"; +import { OwnerCancellation } from "../../../src/domain/analysisErrorCore.js"; import { execFile, spawn, type ChildProcess } from "node:child_process"; import { once } from "node:events"; import { @@ -1066,10 +1067,8 @@ it.skipIf(process.platform === "win32")( ); if (!isProcessOwnershipInspectionCancellation(outcome.cause)) throw new Error("Expected producer-owned inspection cancellation"); - expect(outcome.cause.reason).toBeInstanceOf(DOMException); - if (!(outcome.cause.reason instanceof DOMException)) - throw new Error("Expected the reader's default abort reason"); - expect(outcome.cause.reason.name).toBe("AbortError"); + // Closing the reader is owner-initiated, so it carries the typed reason. + expect(outcome.cause.reason).toBe(OwnerCancellation.ownerClosed); await expect(access(state.root)).rejects.toThrow(); await expect(reader.prepare()).rejects.toMatchObject({ _tag: "ProcessAdmissionError", diff --git a/tests/boundary/providers/kuna/kunaDoctor.test.ts b/tests/boundary/providers/kuna/kunaDoctor.test.ts index 55e185737e..dc7ebc7cb0 100644 --- a/tests/boundary/providers/kuna/kunaDoctor.test.ts +++ b/tests/boundary/providers/kuna/kunaDoctor.test.ts @@ -8,8 +8,10 @@ import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js import { fakeKunaCalls, writeFakeKuna } from "./fakeKuna.js"; import { createSystemDoctorHost } from "../../../../src/doctorRuntime.js"; import { runDoctorOwned } from "../../../../src/application/Doctor.js"; -import { AnalysisCancelledError } from "../../../../src/domain/analysisErrorCore.js"; -import { STARTUP_OWNER_CLOSED } from "../../../../src/process/SharedStartupAttempt.js"; +import { + AnalysisCancelledError, + OwnerCancellation, +} from "../../../../src/domain/analysisErrorCore.js"; const it = test.skipIf(process.platform === "win32"); @@ -303,7 +305,7 @@ it.each(["caller", "host"] as const)( throw new Error("Expected Kuna inspection cancellation"); expect(failure.operation).toBe("doctor"); expect(failure.cause).toBe( - source === "caller" ? reason : STARTUP_OWNER_CLOSED, + source === "caller" ? reason : OwnerCancellation.startupOwnerClosed, ); // Cancellation only settles once execFile has reaped its direct child. expect(() => process.kill(probe.pid, 0)).toThrowError(