refactor(errors): give caller aborts a typed reason at the adapters

The CLI, direct-analysis, MCP and HTTP adapters abort with a CallerAbort that
names the observing adapter and keeps an MCP client's stated reason. REA's own
aborts pass an OwnerCancellation; the startup-owner symbol becomes
OwnerCancellation.startupOwnerClosed. waitForAbortable returns the observed
reason as an AbortedWait, and a counted-baseline guard rejects new bare
.abort() calls.
This commit is contained in:
morluto committed 2026-11-14 14:34:00 -05:00
1 parent 9a8aa2e9fd
commit 908813551f
34 files changed
+360 -113

No files matched your search

@@ -147,7 +147,7 @@
"src/firmware/FirmwareProvider.ts": 1,
"src/flutter/FlutterBuildProvider.ts": 8,
"src/frida/FridaInstrumentationManager.ts": 2,
"src/gdb/GdbSessionManager.ts": 13,
"src/gdb/GdbSessionManager.ts": 12,
"src/gpu/GpuCodeObjectsProvider.ts": 1,
"src/hopper/HopperAnalysisProfile.ts": 1,
"src/hopper/HopperCallerReconciliation.ts": 2,
@@ -203,5 +203,32 @@
"src/sqlite/SqliteDatabaseWorkerExecution.ts": 2,
"src/wasm/WabtArtifactProvider.ts": 2,
"src/wasm/WabtFailures.ts": 2
},
"abort-without-reason": {
"src/android/JadxProvider.ts": 1,
"src/apktool/ApktoolProvider.ts": 1,
"src/application/HopperDownload.ts": 1,
"src/application/binary/BinarySession.ts": 1,
"src/application/reverse/ReverseEngineeringService.ts": 1,
"src/artifacts/ZipArtifactReader.ts": 1,
"src/artifacts/apple/AppleAssetCatalogAnalysis.ts": 1,
"src/browser/CdpObservationSession.ts": 1,
"src/browser/CdpPageCapture.ts": 1,
"src/browser/CdpTargetSession.ts": 2,
"src/browser/PlaywrightScenarioRequest.ts": 2,
"src/browser/PlaywrightScenarioServiceWorkers.ts": 1,
"src/browser/execution/CdpRuntimeSession.ts": 3,
"src/browser/modules/NativeModuleResolver.ts": 1,
"src/gdb/GdbSessionManager.ts": 1,
"src/hopper/HopperClient.ts": 1,
"src/hopper/HopperRegexSearch.ts": 1,
"src/inspector/V8InspectorProvider.ts": 1,
"src/kuna/KunaJsonStream.ts": 1,
"src/kuna/KunaProjectCache.ts": 1,
"src/kuna/KunaSessionClient.ts": 1,
"src/process/DarwinProcessRunTokenReader.ts": 2,
"src/process/OwnedCommand.ts": 2,
"src/process/WorkerFrameSignal.ts": 1,
"src/process/capture/ProcessCaptureLifecycle.ts": 2
}
}
+11
View File
@@ -217,6 +217,17 @@ checkCounted(
["src/domain/analysisErrorCore.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.
checkCounted(
"AbortController.abort() without a reason (pass a CallerAbort or OwnerCancellation from src/domain/analysisErrorCore)",
"abort-without-reason",
files,
/\.abort\(\s*\)/gu,
[],
);
if (baselinesShrunk) {
const sorted = Object.fromEntries(
Object.entries(baselines).map(([key, counts]) => [
+9 -5
View File
@@ -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 <Value>(
): Promise<Value> => {
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);
}
};
+5 -3
View File
@@ -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;
+8 -2
View File
@@ -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<Result<Value, AnalysisError>> {
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 }));
@@ -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(
+4 -2
View File
@@ -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 <Value>(
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);
@@ -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,
);
});
+52 -1
View File
@@ -311,7 +311,13 @@ 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 cancellation REA initiated itself, such as a provider closing. It stands
@@ -328,6 +334,51 @@ 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",
);
}
/** 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<Record<CallerAbortKind, string>> = {
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. */
+3 -3
View File
@@ -1,6 +1,6 @@
import { GDB_PROVIDER_IDENTITY } from "./GdbProviderIdentity.js";
import { persistentDebuggerHostSupported } from "../process/PersistentDebuggerHost.js";
import { ABORTED, waitForAbortable } from "../process/AbortablePromise.js";
import { AbortedWait, waitForAbortable } from "../process/AbortablePromise.js";
import { snapshotGdbCommandRecords } from "./GdbCommandRecords.js";
import { randomUUID } from "node:crypto";
import { constants as fsConstants } from "node:fs";
@@ -2540,7 +2540,7 @@ const waitForGdbCommandTurn = (
): Promise<void> => {
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);
});
};
+9 -9
View File
@@ -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";
@@ -33,11 +36,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";
@@ -293,7 +293,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) =>
@@ -354,7 +354,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);
@@ -1550,7 +1550,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",
+9 -7
View File
@@ -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),
+3 -5
View File
@@ -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,
+9 -9
View File
@@ -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<HopperStartupResult> {
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);
@@ -975,7 +975,7 @@ export class HopperClient {
async #startupInterruption(
deadline: ProviderStartupDeadline,
): Promise<HopperCancelledError | HopperTimeoutError | HopperProtocolError> {
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);
+3 -3
View File
@@ -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;
}
+2 -3
View File
@@ -29,7 +29,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,
@@ -437,8 +437,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(
+3 -3
View File
@@ -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,
@@ -222,8 +222,8 @@ const waitFor = async <T>(
operation: string,
): Promise<Result<T, AnalysisError>> => {
const result = await waitForAbortable(work, signal);
return result === ABORTED
? err(cancelledBy(operation, carriedReason(signal?.reason)))
return result instanceof AbortedWait
? err(cancelledBy(operation, result))
: result;
};
+3 -2
View File
@@ -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;
+26
View File
@@ -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<never>(() => 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"));
});
+14 -6
View File
@@ -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 <Value>(
pending: Promise<Value>,
signal: AbortSignal | undefined,
): Promise<Value | typeof ABORTED> => {
): Promise<Value | AbortedWait> => {
if (signal === undefined) return pending;
let onAbort: (() => void) | undefined;
const cancelled = new Promise<typeof ABORTED>((resolve) => {
const cancelled = new Promise<AbortedWait>((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 {
+2 -2
View File
@@ -31,7 +31,7 @@ import {
type OwnedProcessGroup,
type ProcessCleanupFailure,
} from "./ProcessOwnership.js";
import { ABORTED, waitForAbortable } from "./AbortablePromise.js";
import { AbortedWait, waitForAbortable } from "./AbortablePromise.js";
import {
ProviderStartupDeadline,
waitForAbortableDelay,
@@ -427,7 +427,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(
+5 -7
View File
@@ -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<string>();
@@ -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");
+12 -9
View File
@@ -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<Value> =
@@ -57,9 +55,13 @@ export class SharedStartupAttempt<Value> {
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<Value> {
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;
+2 -2
View File
@@ -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) {
+2 -2
View File
@@ -61,7 +61,7 @@ import {
type OwnedDebuggerDetachResult,
} from "../process/ownedDebuggerSession.js";
import { absoluteCallerPath } from "../filesystem/callerPath.js";
import { ABORTED, waitForAbortable } from "../process/AbortablePromise.js";
import { AbortedWait, waitForAbortable } from "../process/AbortablePromise.js";
const CLEANUP_COMMAND_TIMEOUT_MS = 1_000;
const STARTUP_TIMEOUT_MS = 30_000;
@@ -2072,7 +2072,7 @@ const waitForTurn = (
): Promise<void> => {
if (signal === undefined) return previous;
return waitForAbortable(previous, signal).then((outcome) => {
if (outcome === ABORTED)
if (outcome instanceof AbortedWait)
throw rizinCancellation("rizin_debug_command", signal);
});
};
+59 -1
View File
@@ -12,10 +12,13 @@ import {
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import { z } from "zod";
import { CallerAbort } 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 { currentMcpToolRequest } from "./McpToolRequest.js";
import { createDeferred } from "../../tests/fixtures/binarySession.js";
import { createToolResultDelivery } from "./toolResult.js";
const firstText = (result: {
@@ -102,20 +105,75 @@ 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);
});
});
describe("MCP request cancellation", () => {
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<void>();
const observed = createDeferred<unknown>();
server.registerTool("held", { inputSchema: z.strictObject({}) }, () => {
const signal = currentMcpToolRequest()?.cancellation.signal;
if (signal === undefined) throw new Error("No MCP tool request");
signal.addEventListener("abort", () => observed.resolve(signal.reason), {
once: true,
});
entered.resolve(undefined);
return new Promise(() => undefined);
});
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 entered.promise;
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 {
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();
+17 -6
View File
@@ -42,6 +42,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";
@@ -282,10 +284,11 @@ export const forgetPendingMcpRequest = (
pendingToolLists: Set<RequestId>,
pendingCompletions: Map<RequestId, AbortController>,
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";
@@ -617,13 +620,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,
);
}
}
@@ -641,13 +649,14 @@ class ErrorEvidenceTransport implements Transport {
};
transport.onerror = (error) => this.onerror?.(error);
transport.onclose = () => {
const disconnected = 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?.();
};
@@ -670,11 +679,11 @@ class ErrorEvidenceTransport implements Transport {
} 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();
}
}
@@ -758,11 +767,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,
);
}
}
+6 -2
View File
@@ -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 { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import {
AnalysisCancelledError,
type CallerAbort,
type OwnerCancellation,
} from "../domain/analysisErrorCore.js";
import { err, ok, type Result } from "../domain/result.js";
const currentRequest = new AsyncLocalStorage<McpToolRequest>();
@@ -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();
}
+5 -3
View File
@@ -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);
});
});
+3 -1
View File
@@ -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<string> = 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), {
+6 -3
View File
@@ -39,7 +39,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 +284,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,7 +292,7 @@ class LiveSession {
shutdown(): Promise<void> {
this.#closed = true;
this.#bodyAbort.abort();
this.#bodyAbort.abort(OwnerCancellation.ownerClosed);
return this.#shutdown();
}
}
@@ -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<void>((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);
@@ -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 });
@@ -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(