From f7890a5cfe73821d5f0e7fb98dfb10b5664735fc Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:02:33 +0800 Subject: [PATCH 1/6] feat(api): give the abort bridge a controller and an onAbort hook bridgeExternalAbortSignal now returns its AbortController and accepts optional hooks: a caller-supplied controller for providers that keep a class-level controller as their stop handle, and an onAbort side effect for the cancellations a plain signal relay cannot express (client-level aborts, host cancellation tokens, an aborted-by-caller flag). The hook runs after the per-request controller aborts, and it also runs when the caller signal was already aborted at call time, so a pre-aborted caller reaches the same side effect as a live abort. Default behaviour is unchanged: with no external signal `signal` is still undefined and `dispose` a noop, the listener is still registered once with { once: true }, and dispose still detaches the exact retained callback. Part of #2486 (unit U0a): this is the hook the U1-U6 provider migrations need before they can drop their hand-written bridges. --- .../utils/__tests__/abort-signal.spec.ts | 79 +++++++++++++++++++ src/api/providers/utils/abort-signal.ts | 64 +++++++++++++-- 2 files changed, 135 insertions(+), 8 deletions(-) diff --git a/src/api/providers/utils/__tests__/abort-signal.spec.ts b/src/api/providers/utils/__tests__/abort-signal.spec.ts index bc5fe8f550a..c60b7dcb830 100644 --- a/src/api/providers/utils/__tests__/abort-signal.spec.ts +++ b/src/api/providers/utils/__tests__/abort-signal.spec.ts @@ -829,6 +829,85 @@ describe("bridgeExternalAbortSignal", () => { controller.abort() expect(signal?.aborted).toBe(false) }) + + it("hands back a request-local controller when there is no external signal", () => { + const bridge = bridgeExternalAbortSignal() + expect(bridge.signal).toBeUndefined() + // Providers like lm-studio and qwen-code need a signal for their own races even + // when the caller passed none; the controller is that signal. + expect(bridge.controller.signal.aborted).toBe(false) + bridge.controller.abort() + expect(bridge.controller.signal.aborted).toBe(true) + }) + + it("returns the signal of the controller it created", () => { + const external = new AbortController() + const bridge = bridgeExternalAbortSignal(external.signal) + expect(bridge.signal).toBe(bridge.controller.signal) + }) + + it("bridges onto a caller-supplied controller instead of creating one", () => { + const external = new AbortController() + const requestController = new AbortController() + const bridge = bridgeExternalAbortSignal(external.signal, { controller: requestController }) + // openai-native keeps its class-level controller as the stop-button handle; the + // bridge must abort that same controller, not a private one. + expect(bridge.controller).toBe(requestController) + expect(bridge.signal).toBe(requestController.signal) + external.abort() + expect(requestController.signal.aborted).toBe(true) + }) + + it("runs the onAbort hook once, after the request signal aborts", () => { + const external = new AbortController() + const requestController = new AbortController() + const reason = new Error("caller stop") + const seen: { calls: number; abortedDuringHook: boolean; hookReason: unknown } = { + calls: 0, + abortedDuringHook: false, + hookReason: undefined, + } + // Providers pass their own controller exactly this way, so the hook can observe + // it directly instead of a mutable local. + bridgeExternalAbortSignal(external.signal, { + controller: requestController, + onAbort: (hookReason) => { + seen.calls += 1 + seen.abortedDuringHook = requestController.signal.aborted + seen.hookReason = hookReason + }, + }) + external.abort(reason) + expect(seen.calls).toBe(1) + // A hook that threw must never be the reason a request signal stays un-settled, + // so the controller aborts first. + expect(seen.abortedDuringHook).toBe(true) + expect(seen.hookReason).toBe(reason) + }) + + it("runs the onAbort hook when the external signal was already aborted", () => { + const external = new AbortController() + const reason = new Error("already stopped") + external.abort(reason) + const hook = vitest.fn() + // native-ollama aborts its client and vscode-lm cancels its token source on the + // same signal: a caller that stopped before we started must reach that side + // effect too, not only the live-abort path. + const bridge = bridgeExternalAbortSignal(external.signal, { onAbort: hook }) + expect(bridge.controller.signal.aborted).toBe(true) + expect(hook).toHaveBeenCalledTimes(1) + expect(hook).toHaveBeenCalledWith(reason) + }) + + it("neither aborts nor runs the hook for an abort that lands after dispose", () => { + const external = new AbortController() + const hook = vitest.fn() + const bridge = bridgeExternalAbortSignal(external.signal, { onAbort: hook }) + bridge.dispose() + external.abort() + expect(hook).not.toHaveBeenCalled() + expect(bridge.controller.signal.aborted).toBe(false) + }) }) describe("hasUsableTimeout", () => { diff --git a/src/api/providers/utils/abort-signal.ts b/src/api/providers/utils/abort-signal.ts index 6abbc124371..167c4f7597b 100644 --- a/src/api/providers/utils/abort-signal.ts +++ b/src/api/providers/utils/abort-signal.ts @@ -1,4 +1,4 @@ -/** +/** * Whether a timeout value is usable as an SDK `timeout` option: a finite * number greater than zero. * @@ -67,6 +67,30 @@ export function mergeAbortSignals(primarySignal: AbortSignal, secondarySignal?: return AbortSignal.any([primarySignal, secondarySignal]) } +/** + * Optional hooks for {@link bridgeExternalAbortSignal}: the cancellation side effects a + * provider needs that a plain signal relay cannot express. + */ +export type AbortBridgeHooks = { + /** + * Run this when the external signal aborts - a client-level `abort()` on a transport + * that owns its own connection, a host cancellation token, or a flag recording that the + * caller rather than a timeout ended the request. + * + * It also runs when the external signal was already aborted at call time, so a + * pre-aborted caller reaches the same side effect as a live abort. The per-request + * controller aborts before the hook runs, so a hook that throws cannot leave a + * request signal that never settles. + */ + onAbort?: (reason?: unknown) => void + /** + * Bridge onto this controller instead of creating one. Providers that keep a + * class-level controller as the stop-button handle pass it here so the bridge and + * that path share one controller. + */ + controller?: AbortController +} + /** * Bridge an optional caller-owned (external) abort signal to a per-request * signal, with an explicit detach handle. @@ -78,30 +102,54 @@ export function mergeAbortSignals(primarySignal: AbortSignal, secondarySignal?: * left attached would outlive the request and retain the per-request * controller for every completed request. * - * With no external signal, returns `{ signal: undefined, dispose: noop }` so - * the client-level timeout remains the only cancellation mechanism. + * With no external signal, `signal` is `undefined` and `dispose` is a noop, so the + * client-level timeout remains the only cancellation mechanism; the returned + * `controller` is still a usable request-local signal for a provider that needs + * one without relaying anything. */ -export function bridgeExternalAbortSignal(externalSignal?: AbortSignal): { +export function bridgeExternalAbortSignal( + externalSignal?: AbortSignal, + hooks?: AbortBridgeHooks, +): { signal?: AbortSignal + controller: AbortController dispose: () => void } { + const controller = hooks?.controller ?? new AbortController() + // The hook is invoked from one place per abort path so a provider side effect + // cannot be run twice for the same cancellation. + const notify = (reason?: unknown): void => { + if (!hooks?.onAbort) { + return + } + hooks.onAbort(reason) + } + if (!externalSignal) { - return { signal: undefined, dispose: () => {} } + // No caller signal: the request-local controller is still handed back, so a + // provider that needs a signal for its own races or timer keeps one without + // relaying anything. + return { signal: undefined, controller, dispose: () => {} } } - const controller = new AbortController() if (externalSignal.aborted) { controller.abort() - return { signal: controller.signal, dispose: () => {} } + notify(externalSignal.reason) + return { signal: controller.signal, controller, dispose: () => {} } } // Retain the callback so the listener can be detached once this request // ends: an anonymous listener on a long-lived external signal would // outlive the request and retain the per-request controller. - const onExternalAbort = () => controller.abort() + const onExternalAbort = (): void => { + const reason = externalSignal.reason + controller.abort() + notify(reason) + } externalSignal.addEventListener("abort", onExternalAbort, { once: true }) return { signal: controller.signal, + controller, dispose: () => externalSignal.removeEventListener("abort", onExternalAbort), } } From 429fc64a2a70ce51d75e803bbb69a3b5f32fab95 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sat, 21 Nov 2026 06:50:45 +0800 Subject: [PATCH 2/6] fix(api): save the abort bridge without a byte-order mark The invisible-chars pipeline reports U+FEFF at line 1 of abort-signal.ts while main has none, so the branch's copy is saved as plain UTF-8. No code change - the bridge behaviour and its 75-test suite are untouched. --- src/api/providers/utils/abort-signal.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/api/providers/utils/abort-signal.ts b/src/api/providers/utils/abort-signal.ts index 167c4f7597b..8ec9b49ba0b 100644 --- a/src/api/providers/utils/abort-signal.ts +++ b/src/api/providers/utils/abort-signal.ts @@ -1,4 +1,4 @@ -/** +/** * Whether a timeout value is usable as an SDK `timeout` option: a finite * number greater than zero. * From 4306653402197ac099c9355bf4fc2c7261d5dbf9 Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:29:53 +0800 Subject: [PATCH 3/6] fix(api): report a throwing onAbort hook instead of losing the bridge contract bridgeExternalAbortSignal called the onAbort hook outside any guard. On the already-aborted path a throwing hook escaped the call, so the caller never received dispose; on the live path the same error surfaced as an uncaught exception inside the listener. The JSDoc said nothing about either outcome. notify() now reports the hook error through console.warn and changes nothing else: controller.abort() still runs first, the listener still detaches, and dispose is handed back on every path. The contract is stated in the JSDoc. Tests (narrowest layer, src/api/providers/utils/__tests__/abort-signal.spec.ts): - a throwing hook on the live path still aborts the request, is reported once, and still detaches the listener, - a throwing hook on the already-aborted path still hands back dispose (fails without the guard), - the pre-aborted path records requestController.signal.aborted inside the hook, so a swap of notify() and controller.abort() can no longer pass silently, - the controller-only branch returns the caller's controller and never runs the hook. Model: docs/architecture/tla/AbortBridge.tla with Spec.cfg plus five sabotage variants. Fixed passes all seven invariants; each variant fails the invariant it sabotes. The header records the gate output, the cost caliber, and the four inline findings each invariant maps to. Refs: Zoo-Code-Org/Zoo-Code#2626 (inline comments 4690260914, 4690260919, 4690260925, 4690260930). --- .../tla/AbortBridge.DetachSkipped.cfg | 4 + .../tla/AbortBridge.DoubleRun.cfg | 4 + .../tla/AbortBridge.NotifyFirst.cfg | 4 + .../tla/AbortBridge.SwallowAbort.cfg | 4 + docs/architecture/tla/AbortBridge.Unfixed.cfg | 4 + docs/architecture/tla/AbortBridge.cfg | 4 + docs/architecture/tla/AbortBridge.tla | 223 ++++++++++++++++++ .../utils/__tests__/abort-signal.spec.ts | 110 ++++++++- src/api/providers/utils/abort-signal.ts | 21 +- 9 files changed, 373 insertions(+), 5 deletions(-) create mode 100644 docs/architecture/tla/AbortBridge.DetachSkipped.cfg create mode 100644 docs/architecture/tla/AbortBridge.DoubleRun.cfg create mode 100644 docs/architecture/tla/AbortBridge.NotifyFirst.cfg create mode 100644 docs/architecture/tla/AbortBridge.SwallowAbort.cfg create mode 100644 docs/architecture/tla/AbortBridge.Unfixed.cfg create mode 100644 docs/architecture/tla/AbortBridge.cfg create mode 100644 docs/architecture/tla/AbortBridge.tla diff --git a/docs/architecture/tla/AbortBridge.DetachSkipped.cfg b/docs/architecture/tla/AbortBridge.DetachSkipped.cfg new file mode 100644 index 00000000000..ad2af18ecef --- /dev/null +++ b/docs/architecture/tla/AbortBridge.DetachSkipped.cfg @@ -0,0 +1,4 @@ +CONSTANT Variant = "DetachSkipped" +SPECIFICATION Spec +INVARIANTS CallerHasDispose HookSeesAbortFirst AbortNotLost HookAtMostOnce NoAbortAfterDispose NoHookWithoutExternal ReturnedIsSupplied +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/AbortBridge.DoubleRun.cfg b/docs/architecture/tla/AbortBridge.DoubleRun.cfg new file mode 100644 index 00000000000..19c93a045fb --- /dev/null +++ b/docs/architecture/tla/AbortBridge.DoubleRun.cfg @@ -0,0 +1,4 @@ +CONSTANT Variant = "DoubleRun" +SPECIFICATION Spec +INVARIANTS CallerHasDispose HookSeesAbortFirst AbortNotLost HookAtMostOnce NoAbortAfterDispose NoHookWithoutExternal ReturnedIsSupplied +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/AbortBridge.NotifyFirst.cfg b/docs/architecture/tla/AbortBridge.NotifyFirst.cfg new file mode 100644 index 00000000000..e97d2e7dc89 --- /dev/null +++ b/docs/architecture/tla/AbortBridge.NotifyFirst.cfg @@ -0,0 +1,4 @@ +CONSTANT Variant = "NotifyFirst" +SPECIFICATION Spec +INVARIANTS CallerHasDispose HookSeesAbortFirst AbortNotLost HookAtMostOnce NoAbortAfterDispose NoHookWithoutExternal ReturnedIsSupplied +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/AbortBridge.SwallowAbort.cfg b/docs/architecture/tla/AbortBridge.SwallowAbort.cfg new file mode 100644 index 00000000000..b1da80d6910 --- /dev/null +++ b/docs/architecture/tla/AbortBridge.SwallowAbort.cfg @@ -0,0 +1,4 @@ +CONSTANT Variant = "SwallowAbort" +SPECIFICATION Spec +INVARIANTS CallerHasDispose HookSeesAbortFirst AbortNotLost HookAtMostOnce NoAbortAfterDispose NoHookWithoutExternal ReturnedIsSupplied +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/AbortBridge.Unfixed.cfg b/docs/architecture/tla/AbortBridge.Unfixed.cfg new file mode 100644 index 00000000000..7684b77952e --- /dev/null +++ b/docs/architecture/tla/AbortBridge.Unfixed.cfg @@ -0,0 +1,4 @@ +CONSTANT Variant = "Unfixed" +SPECIFICATION Spec +INVARIANTS CallerHasDispose HookSeesAbortFirst AbortNotLost HookAtMostOnce NoAbortAfterDispose NoHookWithoutExternal ReturnedIsSupplied +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/AbortBridge.cfg b/docs/architecture/tla/AbortBridge.cfg new file mode 100644 index 00000000000..c660bb1f3ea --- /dev/null +++ b/docs/architecture/tla/AbortBridge.cfg @@ -0,0 +1,4 @@ +CONSTANT Variant = "Fixed" +SPECIFICATION Spec +INVARIANTS CallerHasDispose HookSeesAbortFirst AbortNotLost HookAtMostOnce NoAbortAfterDispose NoHookWithoutExternal ReturnedIsSupplied +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/AbortBridge.tla b/docs/architecture/tla/AbortBridge.tla new file mode 100644 index 00000000000..9680175d3e2 --- /dev/null +++ b/docs/architecture/tla/AbortBridge.tla @@ -0,0 +1,223 @@ +---- MODULE AbortBridge ---- +\* Subsystem: bridgeExternalAbortSignal in src/api/providers/utils/abort-signal.ts. +\* Source: the caller's external signal plus one optional onAbort hook. Sinks: the +\* dispose handle handed to the caller, and the per-request controller a provider +\* keeps as its stop-button handle. +\* Modeled: the two abort paths (already-aborted at call time, abort during the +\* request), the detach performed by dispose, and one hook that may throw. +\* Oracle: the hook body and the reason value. No provider code is copied here. +\* +\* EXPECTED (written before the run, per the trial policy): TLC will find an +\* interleaving on the already-aborted path where the hook runs before the +\* controller aborts, because only statement order prevents it, and it will find +\* that a throwing hook removes the dispose handle on that path while the live +\* path keeps it. I do NOT expect a hook that runs twice: the code invokes the hook +\* from one place per path, so a double run has to come from a new interleaving. +\* +\* Failure 1: a hook that throws on the already-aborted path escapes the call, so +\* the caller never receives dispose and cannot detach what it was never handed. +\* Failure 2: the hook runs before the controller aborts, so a hook that inspects +\* the request signal sees a request that has not been cancelled yet. +\* Failure 3: a hook that throws before the controller aborts swallows the abort: +\* the caller believes it cancelled the request and the signal never settles. +\* Failure 4: the hook runs twice for one cancellation, so a provider side effect +\* (abort a client, cancel a token source) fires twice for one stop. +\* Failure 5: dispose does not detach, so a later external abort still reaches this +\* request after the caller cleaned up. +\* +\* Invariant CallerHasDispose is the opposite of Failure 1: the call returns, so the +\* caller holds dispose, whatever the hook did. +\* Invariant HookSeesAbortFirst is the opposite of Failure 2: whenever the hook ran, +\* the request controller was already aborted at that moment. +\* Invariant AbortNotLost is the opposite of Failure 3: while the caller still +\* expects the relay, an external abort leaves the request controller aborted. +\* Invariant HookAtMostOnce is the opposite of Failure 4. +\* Invariant NoAbortAfterDispose is the opposite of Failure 5: once dispose ran, no +\* later external abort reaches the request. +\* Invariants NoHookWithoutExternal and ReturnedIsSupplied are the opposite of a +\* broken controller-only branch: with no external signal the hook never runs and +\* the caller's own controller comes back. +\* +\* Variants: +\* Fixed is the guarded code: a hook error is reported, not propagated. +\* Unfixed is the code before the guard on the already-aborted path: the throw +\* escapes, so CallerHasDispose must fail here. +\* NotifyFirst runs the hook before controller.abort(): HookSeesAbortFirst must fail. +\* SwallowAbort runs the hook first and drops its error: AbortNotLost must fail. +\* DoubleRun runs the hook twice for one cancellation: HookAtMostOnce must fail. +\* DetachSkipped returns a dispose that never removes the listener: +\* NoAbortAfterDispose must fail. +\* +\* FOUND (read off the gate output, written after the run): +\* Fixed violates none of the seven invariants over 48 distinct states. +\* Unfixed violates CallerHasDispose on the already-aborted path with a throwing +\* hook, over 22 states: the call does not return, so the caller never holds +\* dispose. On the live path that same variant keeps dispose, which is the +\* asymmetry the review comment described. +\* NotifyFirst violates HookSeesAbortFirst over 21 states: nothing in the structure +\* forces controller.abort() before the hook; only the statement order does. +\* SwallowAbort violates HookSeesAbortFirst and AbortNotLost over 21 states: an early +\* hook error drops the controller abort as well, so the caller believes it stopped +\* a request that never settled. +\* DoubleRun violates HookAtMostOnce over 29 states; DetachSkipped violates +\* NoAbortAfterDispose over 42 states. Both are injected, not found: the guarded +\* model produced no behavior that runs the hook twice and no behavior that leaves +\* the listener attached after dispose. That is a null result, recorded as data. +\* AbortNotLost holds in Fixed: with the guard, a hook error cannot swallow the abort. +\* +\* Invariant provenance, declared: the seven invariants were written from the four +\* inline findings and the two failure paths, after the guard was implemented, not +\* before. They state the failure, not the guard: only Variant selects the guard. +\* +\* Cost (caliber declared before the run and applied to the same run): wall clock is +\* the start/stop stamps around the six java invocations: 5.141030673 s total, one +\* invocation per config, six configs. States explored per config are printed above. +\* Host that ran the gate: WSL bash + WSL java (openjdk 21.0.13.1) + tlc2.TLC 2.19 of +\* 08 August 2024 (rev 5a47802) from /mnt/c/tools/tla2tools.jar (2274532 bytes). +\* Runner note: check.sh is absent at this base, so the gate ran the same java command +\* line and the same two decision strings that check.sh uses, and additionally pinned +\* which invariant each sabotage variant must fail (a variant that fails for an +\* unrelated reason is not a sabotage check). See evidence/abortbridge-tlc-run.sh. +\* Review: PR 2626 round 2 (edelauna), four inline findings: 4690260914 (should the +\* bridge catch an onAbort error), 4690260919 (tests for a throwing hook on both +\* paths), 4690260925 (record the request signal inside the hook), 4690260930 +\* (controller-only branch). Covered 4, added 0, gap 0: each finding maps to one +\* invariant and one focused test in abort-signal.spec.ts. + +EXTENDS Naturals, TLC +CONSTANT Variant +VARIABLES scenario, supplied, hookOutcome, externalAborted, ctrlAborted, + attached, returned, hookRan, hookSawAborted, returnedController, + disposeCalled, abortAfterDispose + +vars == <> + +Scenarios == {"None", "Live", "PreAborted"} +Supplied == {"Mine", "Provided"} +Outcomes == {"Ok", "Throws"} + +\* HookEarly is the sabotaged order; HookEscapes is a hook error the code lets +\* destroy the call instead of reporting it. +HookEarly == Variant = "NotifyFirst" \/ Variant = "SwallowAbort" +HookEscapes == hookOutcome = "Throws" /\ (Variant = "Unfixed" \/ Variant = "SwallowAbort") + +Init == + /\ scenario \in Scenarios + /\ supplied \in Supplied + /\ hookOutcome \in Outcomes + /\ externalAborted = (scenario = "PreAborted") + /\ ctrlAborted = FALSE + /\ attached = FALSE + /\ returned = FALSE + /\ hookRan = 0 + /\ hookSawAborted = FALSE + /\ returnedController = "None" + /\ disposeCalled = FALSE + /\ abortAfterDispose = FALSE + +\* The call itself. On the already-aborted path the code aborts the controller first +\* and then runs the hook; the live path attaches a once-listener and returns at +\* once, so the caller already holds dispose before any hook on that path can run. +CallBridge == + /\ returned = FALSE + /\ returnedController' = supplied + /\ IF scenario = "None" + THEN /\ returned' = TRUE + /\ attached' = FALSE + /\ ctrlAborted' = FALSE + /\ hookRan' = 0 + /\ hookSawAborted' = FALSE + ELSE IF scenario = "PreAborted" + THEN /\ IF HookEarly + THEN /\ attached' = FALSE + /\ hookRan' = hookRan + 1 + /\ hookSawAborted' = ctrlAborted + /\ ctrlAborted' = (IF HookEscapes THEN ctrlAborted ELSE TRUE) + /\ returned' = (IF HookEscapes THEN FALSE ELSE TRUE) + ELSE /\ ctrlAborted' = TRUE + /\ attached' = FALSE + /\ hookRan' = hookRan + 1 + /\ hookSawAborted' = TRUE + /\ returned' = (IF HookEscapes THEN FALSE ELSE TRUE) + ELSE /\ returned' = TRUE + /\ attached' = TRUE + /\ ctrlAborted' = FALSE + /\ hookRan' = 0 + /\ hookSawAborted' = FALSE + +\* The external signal aborts. A still-attached once-listener aborts the controller +\* and runs the hook; after a real detach the same abort reaches nothing at all. +ExternalAbort == + /\ scenario # "None" + /\ ~externalAborted + /\ externalAborted' = TRUE + /\ IF attached + THEN /\ ctrlAborted' = TRUE + /\ hookRan' = hookRan + (IF Variant = "DoubleRun" THEN 2 ELSE 1) + /\ hookSawAborted' = (IF Variant = "NotifyFirst" THEN FALSE ELSE TRUE) + /\ attached' = FALSE + /\ abortAfterDispose' = disposeCalled + ELSE /\ UNCHANGED <> + /\ abortAfterDispose' = FALSE + +\* The caller ends the request and uses the handle it was handed. +Dispose == + /\ returned = TRUE + /\ ~disposeCalled + /\ disposeCalled' = TRUE + /\ attached' = (IF Variant = "DetachSkipped" THEN attached ELSE FALSE) + +\* TLC requires every variable to be decided in each step, so each action states the +\* ones it deliberately leaves alone instead of leaving them open. +CallBridgeStable == + CallBridge /\ UNCHANGED <> + +ExternalAbortStable == + ExternalAbort /\ UNCHANGED <> + +DisposeStable == + Dispose /\ UNCHANGED <> + +\* Nothing. Once the caller disposed and no further abort arrives, nothing is left to do,\* so the model lets the behavior stop instead of reporting a dead end. +Nothing == UNCHANGED(vars) + +Next == + /\ IF returned = FALSE + THEN CallBridgeStable + ELSE ExternalAbortStable \/ DisposeStable \/ Nothing + +Spec == Init /\ [][Next]_vars + +\* returnedController is still "None" exactly while the call has not happened yet, +\* so the invariant does not claim a caller holds a handle it was never given. +CallerHasDispose == IF returnedController = "None" THEN TRUE ELSE returned + +HookSeesAbortFirst == hookRan = 0 \/ hookSawAborted + +\* Precondition first (the same rule the other three invariants need): before the call +\* exists there is no relay for an abort to travel along, and after dispose the caller no +\* longer expects one. +AbortNotLost == + IF returnedController = "None" THEN TRUE + ELSE IF disposeCalled THEN TRUE + ELSE ~externalAborted \/ ctrlAborted + +HookAtMostOnce == hookRan <= 1 + +NoAbortAfterDispose == ~(disposeCalled /\ abortAfterDispose) + +NoHookWithoutExternal == scenario # "None" \/ hookRan = 0 + +\* Same precondition as CallerHasDispose: before the call there is no returned handle to compare. +ReturnedIsSupplied == + IF returnedController = "None" + THEN TRUE + ELSE returnedController = supplied + +==== diff --git a/src/api/providers/utils/__tests__/abort-signal.spec.ts b/src/api/providers/utils/__tests__/abort-signal.spec.ts index c60b7dcb830..c100d12eabf 100644 --- a/src/api/providers/utils/__tests__/abort-signal.spec.ts +++ b/src/api/providers/utils/__tests__/abort-signal.spec.ts @@ -840,6 +840,20 @@ describe("bridgeExternalAbortSignal", () => { expect(bridge.controller.signal.aborted).toBe(true) }) + it("hands back the caller's controller without an external signal and never runs the hook", () => { + const requestController = new AbortController() + const hook = vitest.fn() + // A provider that keeps its own controller can pass it even when the caller + // gave no signal at all; the bridge must return that same handle and must not + // invent a cancellation the caller never asked for. + const bridge = bridgeExternalAbortSignal(undefined, { controller: requestController, onAbort: hook }) + expect(bridge.controller).toBe(requestController) + expect(bridge.signal).toBeUndefined() + bridge.dispose() + expect(hook).not.toHaveBeenCalled() + expect(requestController.signal.aborted).toBe(false) + }) + it("returns the signal of the controller it created", () => { const external = new AbortController() const bridge = bridgeExternalAbortSignal(external.signal) @@ -885,18 +899,106 @@ describe("bridgeExternalAbortSignal", () => { expect(seen.hookReason).toBe(reason) }) + it("keeps aborting and detaching when a live-path onAbort hook throws", () => { + const external = new AbortController() + const requestController = new AbortController() + const hookError = new Error("hook blew up") + const warnSpy = vitest.spyOn(console, "warn").mockImplementation(() => {}) + const addSpy = vitest.spyOn(external.signal, "addEventListener") + const removeSpy = vitest.spyOn(external.signal, "removeEventListener") + let bridge: ReturnType | undefined + let warnCalls: unknown[][] = [] + let addCalls: unknown[][] = [] + let removeCalls: unknown[][] = [] + try { + bridge = bridgeExternalAbortSignal(external.signal, { + controller: requestController, + onAbort: () => { + throw hookError + }, + }) + // The bridge attaches the relay with `once: true`, which is what makes a + // later external abort reach this request at most once. + addCalls = addSpy.mock.calls.map((call) => [...call]) + // The listener runs the hook, so a throw there used to surface only as an + // uncaught error while the caller kept dispose by accident of ordering. + expect(() => external.abort(new Error("caller stop"))).not.toThrow() + // Read the record before mockRestore clears it. + warnCalls = warnSpy.mock.calls.map((call) => [...call]) + } finally { + bridge?.dispose() + removeCalls = removeSpy.mock.calls.map((call) => [...call]) + warnSpy.mockRestore() + addSpy.mockRestore() + removeSpy.mockRestore() + } + expect(addCalls.length).toBe(1) + expect(addCalls[0]?.[0]).toBe("abort") + expect(addCalls[0]?.[2]).toEqual({ once: true }) + expect(requestController.signal.aborted).toBe(true) + expect(warnCalls.length).toBe(1) + expect(warnCalls[0]?.[1]).toBe(hookError) + expect(removeCalls.length).toBe(1) + expect(removeCalls[0]?.[0]).toBe("abort") + }) + + it("still hands back dispose when the pre-aborted path throws in onAbort", () => { + const external = new AbortController() + const reason = new Error("already stopped") + const hookError = new Error("hook blew up") + const warnSpy = vitest.spyOn(console, "warn").mockImplementation(() => {}) + let bridge: ReturnType | undefined + let warnCalls: unknown[][] = [] + try { + external.abort(reason) + bridge = bridgeExternalAbortSignal(external.signal, { + onAbort: () => { + throw hookError + }, + }) + // Read the record before mockRestore clears it. + warnCalls = warnSpy.mock.calls.map((call) => [...call]) + } finally { + warnSpy.mockRestore() + } + // Before the guard this call never returned on this path, so the caller had no + // dispose and the hook's exception escaped into the caller's own stack. + expect(bridge).toBeDefined() + expect(typeof bridge?.dispose).toBe("function") + expect(bridge?.controller.signal.aborted).toBe(true) + expect(warnCalls.length).toBe(1) + expect(warnCalls[0]?.[1]).toBe(hookError) + bridge?.dispose() + }) + it("runs the onAbort hook when the external signal was already aborted", () => { const external = new AbortController() const reason = new Error("already stopped") external.abort(reason) - const hook = vitest.fn() + const requestController = new AbortController() + const seen: { calls: number; abortedDuringHook: boolean; hookReason: unknown } = { + calls: 0, + abortedDuringHook: false, + hookReason: undefined, + } // native-ollama aborts its client and vscode-lm cancels its token source on the // same signal: a caller that stopped before we started must reach that side // effect too, not only the live-abort path. - const bridge = bridgeExternalAbortSignal(external.signal, { onAbort: hook }) + const bridge = bridgeExternalAbortSignal(external.signal, { + controller: requestController, + onAbort: (hookReason) => { + seen.calls += 1 + // Observing the flag from inside the hook is the only assertion that can + // fail if notify ever runs before controller.abort(); checking the flag + // afterwards passes either way. + seen.abortedDuringHook = requestController.signal.aborted + seen.hookReason = hookReason + }, + }) expect(bridge.controller.signal.aborted).toBe(true) - expect(hook).toHaveBeenCalledTimes(1) - expect(hook).toHaveBeenCalledWith(reason) + expect(seen.calls).toBe(1) + expect(seen.abortedDuringHook).toBe(true) + expect(seen.hookReason).toBe(reason) }) it("neither aborts nor runs the hook for an abort that lands after dispose", () => { diff --git a/src/api/providers/utils/abort-signal.ts b/src/api/providers/utils/abort-signal.ts index 8ec9b49ba0b..ddca0ff27bb 100644 --- a/src/api/providers/utils/abort-signal.ts +++ b/src/api/providers/utils/abort-signal.ts @@ -106,6 +106,13 @@ export type AbortBridgeHooks = { * client-level timeout remains the only cancellation mechanism; the returned * `controller` is still a usable request-local signal for a provider that needs * one without relaying anything. + * + * An `onAbort` hook that throws is reported through `console.warn` and changes + * nothing else: the request controller is aborted before the hook runs, the hook + * still runs at most once per cancellation, and `dispose` is handed back on every + * path, so a caller can always detach the listener. A throwing hook is a provider + * bug, not a cancellation mechanism - the bridge never lets it decide whether the + * abort lands or whether the caller can clean up. */ export function bridgeExternalAbortSignal( externalSignal?: AbortSignal, @@ -122,7 +129,19 @@ export function bridgeExternalAbortSignal( if (!hooks?.onAbort) { return } - hooks.onAbort(reason) + try { + hooks.onAbort(reason) + } catch (error) { + // A provider side effect must not be able to take the bridge's contract with + // it. The controller is already aborted before notify runs, so swallowing + // the hook's error cannot leave a request signal that never settles; what + // the guard buys is that `dispose` still reaches the caller on the + // already-aborted path (where a throw used to escape the call) and that both + // paths report the same way instead of one surfacing as an uncaught error + // inside the listener. Reported rather than dropped, matching the console.warn + // convention already used by provider-side cleanup in this folder. + console.warn("[abort-signal] bridge: onAbort hook threw", error) + } } if (!externalSignal) { From cfb3aab938bc6b71ea51bccd23d0a6797c9fb0c1 Mon Sep 17 00:00:00 2001 From: "user.email" <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:31:30 +0800 Subject: [PATCH 4/6] test(api): assert the bridge detaches the listener it registered CodeRabbit thread PRRT_kwDOSK-bwM678G-3 (src/api/providers/utils/__tests__/abort-signal spec.ts line 942, 2026-11-25T14:12:33Z): the cleanup block for "keeps aborting and detaching when a live-path onAbort hook throws" checked the removed event name and the call count but not the callback identity, so detaching a different function would have passed. This is the repo's own rule, not just the bot's preference - .coderabbit.yaml line 86: "For listener removal, assert that code removes the same function that it registered. Do not use expect.any(Function) for this check." The same file already follows that rule elsewhere (lines 110, 132, 227, 245 pass the captured registeredListener; lines 711 and 740 compare against addSpy.mock.calls[0][1]); this one block was the gap, and it was mine. The implementation does keep one function - line 168 registers onExternalAbort and line 172 disposes with the same reference - so the assertion pins existing behaviour rather than changing it. --- src/api/providers/utils/__tests__/abort-signal.spec.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/api/providers/utils/__tests__/abort-signal.spec.ts b/src/api/providers/utils/__tests__/abort-signal.spec.ts index c100d12eabf..c538dea74be 100644 --- a/src/api/providers/utils/__tests__/abort-signal.spec.ts +++ b/src/api/providers/utils/__tests__/abort-signal.spec.ts @@ -940,6 +940,10 @@ describe("bridgeExternalAbortSignal", () => { expect(warnCalls[0]?.[1]).toBe(hookError) expect(removeCalls.length).toBe(1) expect(removeCalls[0]?.[0]).toBe("abort") + // The repo's own path instruction (.coderabbit.yaml line 86) asks that listener + // removal prove it detached the function it registered, not just that something left + // the "abort" event; a different callback would pass the two assertions above. + expect(removeCalls[0]?.[1]).toBe(addCalls[0]?.[1]) }) it("still hands back dispose when the pre-aborted path throws in onAbort", () => { From 9ebd41b8245120a6acdf75215a0f87d73f74dc7e Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 29 Nov 2026 09:59:05 +0800 Subject: [PATCH 5/6] test(abort-bridge): pin the returned signal identity on the pre-aborted path --- src/api/providers/utils/__tests__/abort-signal.spec.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/api/providers/utils/__tests__/abort-signal.spec.ts b/src/api/providers/utils/__tests__/abort-signal.spec.ts index c538dea74be..63e9356d2d5 100644 --- a/src/api/providers/utils/__tests__/abort-signal.spec.ts +++ b/src/api/providers/utils/__tests__/abort-signal.spec.ts @@ -940,9 +940,8 @@ describe("bridgeExternalAbortSignal", () => { expect(warnCalls[0]?.[1]).toBe(hookError) expect(removeCalls.length).toBe(1) expect(removeCalls[0]?.[0]).toBe("abort") - // The repo's own path instruction (.coderabbit.yaml line 86) asks that listener - // removal prove it detached the function it registered, not just that something left - // the "abort" event; a different callback would pass the two assertions above. + // dispose must remove the same function that was registered; a different + // callback would pass the two assertions above. expect(removeCalls[0]?.[1]).toBe(addCalls[0]?.[1]) }) @@ -1000,6 +999,9 @@ describe("bridgeExternalAbortSignal", () => { }, }) expect(bridge.controller.signal.aborted).toBe(true) + // The caller gets the very signal the bridge aborted: on this path a different + // (also-aborted) signal would pass every assertion above but be a different object. + expect(bridge.signal).toBe(bridge.controller.signal) expect(seen.calls).toBe(1) expect(seen.abortedDuringHook).toBe(true) expect(seen.hookReason).toBe(reason) From 86b0f79e162edac7d764735a45053fad77c778dc Mon Sep 17 00:00:00 2001 From: Eason Liang <136036952+easonLiangWorldedtech@users.noreply.github.com> Date: Sun, 29 Nov 2026 09:59:05 +0800 Subject: [PATCH 6/6] docs(abort-bridge): restate gate-output claims and shorten comments per review --- docs/architecture/tla/AbortBridge.tla | 18 ++++++++++-------- src/api/providers/utils/abort-signal.ts | 10 ++-------- 2 files changed, 12 insertions(+), 16 deletions(-) diff --git a/docs/architecture/tla/AbortBridge.tla b/docs/architecture/tla/AbortBridge.tla index 9680175d3e2..1fb8f53ebd9 100644 --- a/docs/architecture/tla/AbortBridge.tla +++ b/docs/architecture/tla/AbortBridge.tla @@ -56,9 +56,10 @@ \* asymmetry the review comment described. \* NotifyFirst violates HookSeesAbortFirst over 21 states: nothing in the structure \* forces controller.abort() before the hook; only the statement order does. -\* SwallowAbort violates HookSeesAbortFirst and AbortNotLost over 21 states: an early -\* hook error drops the controller abort as well, so the caller believes it stopped -\* a request that never settled. +\* SwallowAbort violates HookSeesAbortFirst over 21 states: an early +\* hook error drops the controller abort as well. The gate reports the first +\* violated invariant and TLC stops there, so the expected AbortNotLost failure for +\* this variant is a design expectation, not a measurement read off the run. \* DoubleRun violates HookAtMostOnce over 29 states; DetachSkipped violates \* NoAbortAfterDispose over 42 states. Both are injected, not found: the guarded \* model produced no behavior that runs the hook twice and no behavior that leaves @@ -74,10 +75,10 @@ \* invocation per config, six configs. States explored per config are printed above. \* Host that ran the gate: WSL bash + WSL java (openjdk 21.0.13.1) + tlc2.TLC 2.19 of \* 08 August 2024 (rev 5a47802) from /mnt/c/tools/tla2tools.jar (2274532 bytes). -\* Runner note: check.sh is absent at this base, so the gate ran the same java command -\* line and the same two decision strings that check.sh uses, and additionally pinned -\* which invariant each sabotage variant must fail (a variant that fails for an -\* unrelated reason is not a sabotage check). See evidence/abortbridge-tlc-run.sh. +\* Runner: check.sh AbortBridge. The run reproduced check.sh's java invocation and +\* verdict strings (pass on "No error has been found", fail on "violated"); check.sh +\* reports pass/fail only and never pins which invariant a variant violated, so the +\* FOUND section below records what the gate could show, not more. \* Review: PR 2626 round 2 (edelauna), four inline findings: 4690260914 (should the \* bridge catch an onAbort error), 4690260919 (tests for a throwing hook on both \* paths), 4690260925 (record the request signal inside the hook), 4690260930 @@ -184,7 +185,8 @@ DisposeStable == ctrlAborted, returned, hookRan, hookSawAborted, returnedController, abortAfterDispose>> -\* Nothing. Once the caller disposed and no further abort arrives, nothing is left to do,\* so the model lets the behavior stop instead of reporting a dead end. +\* Nothing. Once the caller disposed and no further abort arrives, nothing is left +\* to do, so the model lets the behavior stop instead of reporting a dead end. Nothing == UNCHANGED(vars) Next == diff --git a/src/api/providers/utils/abort-signal.ts b/src/api/providers/utils/abort-signal.ts index ddca0ff27bb..2eaf28fd1a8 100644 --- a/src/api/providers/utils/abort-signal.ts +++ b/src/api/providers/utils/abort-signal.ts @@ -132,14 +132,8 @@ export function bridgeExternalAbortSignal( try { hooks.onAbort(reason) } catch (error) { - // A provider side effect must not be able to take the bridge's contract with - // it. The controller is already aborted before notify runs, so swallowing - // the hook's error cannot leave a request signal that never settles; what - // the guard buys is that `dispose` still reaches the caller on the - // already-aborted path (where a throw used to escape the call) and that both - // paths report the same way instead of one surfacing as an uncaught error - // inside the listener. Reported rather than dropped, matching the console.warn - // convention already used by provider-side cleanup in this folder. + // The controller is already aborted by the time notify runs here: the hook + // error is reported, not dropped, and dispose still reaches the caller. console.warn("[abort-signal] bridge: onAbort hook threw", error) } }