Abort signal is delivered to `appRoute` but the flow keeps generating
Repo: firebase/genkit · Versions: [email protected], @genkit-ai/[email protected],
@genkit-ai/google-genai (Gemini), Next.js 16.3.2, Node 22, Windows dev server.
Summary
When a browser client disconnects mid-stream, the AbortSignal does reach the route
handler — but the flow continues, completes at least one more model generation, and only
surfaces ~79s later as an unhandledRejection: ResponseAborted when it tries to write to
the closed response.
The cost is real: on a metered surface, 52% of a run's total token spend was billed after the user pressed Stop — more than the run had spent up to that point.
This reproduced on 1.41.0 and again, unchanged, on 1.42.0.
Evidence
A single traced run (b521a986-b56f-46c1-ab55-840841d084c9), stopped from the UI once two
tool calls were in flight. The route registers its own listener on request.signal:
const startedAt = Date.now();
request.signal.addEventListener("abort", () => {
console.warn(`[ask] the caller disconnected after ${Date.now() - startedAt}ms`);
});
Server log:
00:19:44.905 ✓ Compiled in 1250ms
00:20:09.941 WARN [ask] the caller disconnected after 21431ms (trace b521a986…)
00:21:29.022 ERROR ⨯ "unhandledRejection:" ResponseAborted
So the signal fires at 00:20:09, and 79 seconds later something is still writing to
the response.
Billing, read from our own usage ledger (not from a live subscription — see the note below):
| tokens billed, in credits | |
|---|---|
| before the run | 2,536 |
| at the moment of Stop | 2,674 |
| after the run finally ended | 2,826 |
152 of the run's 290 credits were spent after the abort.
Measurement note for anyone reproducing this: our in-page meter still read
2,674a full 80 seconds after the stop, because it is a realtime subscription and the post-abort billing is a server-side write that never pushes to it. A page reload showed the real figure. A live client-side counter will tell you this is fixed when it is not.
What has been ruled out
Every hop outside genkit was checked, by reading the installed source or by measurement:
- The client aborts its own
AbortControllerand the fetch carries the signal. - Next.js fires
request.signal— confirmed by the route's own listener above, and separately by a standalone Next 16.3.2 probe. @genkit-ai/next'sappRouteforwardsreq.signalasabortSignaltoaction.run(lib/index.js, both the streaming and non-streaming branches).agent-core'ssetupAbortwires an external signal to its own controller.googleai/gemini.jspassesabortSignalas the model call's fetchsignal.
So the break appears to be inside that chain — between appRoute receiving the signal
and the model call honouring it.
Expected
An aborted request stops the flow: no further model generations are started, and any in-flight one is cancelled via the signal already being passed down.
Actual
The flow runs to completion, including at least one further generation, and the abort is only observed indirectly when a write fails against the closed response.
Related, and ruled out
#5331 ("retry middleware silently retries AbortError, ignoring abortSignal passed to
generateStream", closed 2026-05-21) is the closest prior report: an abort being defeated
because a component downstream did not honour it. It is not this. That failure re-issues
the aborted call from the retry middleware; we do not use retry at all — our model
middleware list is two project-local entries (an effort rewriter and a usage meter) — and
nothing here is a retry. The flow simply carries on to its next generation.
Worth flagging as a possible shared theme rather than a duplicate: in both cases the signal reaches the process and something between it and the model call declines to act on it.
(Search caveat: GitHub's issue search returns HTTP 422 for this repo through my token, so this was found by listing the 400 most recent issues and filtering locally. An older duplicate could exist outside that window.)
Minimal reproduction sketch
- A Genkit flow that makes ≥2 sequential model calls (e.g. a tool-using agent).
- Serve it through
@genkit-ai/next'sappRoute. - Stream it to a browser client; abort the client fetch after the first tool call.
- Observe:
request.signalfires immediately; the flow's later generations still complete and are billed.
Happy to supply a runnable repro if useful.
A likely lead, found after filing — GitHub's issue search 422s for repo:firebase/genkit
but works for repo:genkit-ai/genkit, which is how I missed it first time.
#3507 ("fix(ai): propagate abortSignal in recursive generateHelper calls", merged 2025-09-08) describes this symptom almost exactly:
When
generateHelperrecursively calls itself during tool iterations, theabortSignalwas not being passed to the recursive call. This caused abort signals to be lost after the first tool iteration, preventing proper cancellation of long-running operations with multiple tool calls. […] Fixes issue where task cancellation fails whenmaxTurns > 1.
That is what I am seeing — abort honoured up to the first tool iteration, then the loop
carries on — except we are on the Agents API, not generateHelper directly:
export const askAbacistAgent = ai.defineAgent({
// …
maxTurns: MAX_TURNS,
use: [/* two project-local middlewares; no `retry` */],
});
defineAgent landed after #3507 (#5251), so a plausible reading is that the agent turn
loop does not inherit the propagation that generateHelper's recursion was fixed to do —
i.e. the same defect on a newer path rather than a regression of the old one. I have not
read the agent loop's source to confirm that, so treat it as a lead rather than a
diagnosis.
If it helps narrow things: our abort is observed arriving at the route handler, and the
next generation still completes ~79s later, so whatever drops it sits below appRoute and
above the model call.
I will take this issue. Please assign it to me.
The problem seems to be that the AbortSignal reaches the route handler, but the flow continues processing. I will first inspect the action.run function in lib/index.js to ensure it properly handles the abortSignal. Specifically, I'll check if there is a mechanism to stop the generation process when the signal is received. I will add a small fix to ensure that the generation halts immediately upon receiving the abort signal, preventing further token usage. To prove the fix, I'll run a test to confirm that no additional tokens are billed after the abort.
@genkit-bot triage verify how request.signal is propagated from @genkit-ai/next appRoute into flow and model generation execution in js/ and identify where abort cancellation drops.
Triage: P2 · S · implement: Core agent and tool-loop abort propagation is already fixed on main, but google-genai getAbortSignal drops already-aborted signals, next appRoute leaks unhandled rejections on client disconnect, and defineGenerateAction drops abortSignal.
Area: js
Root cause: Core agent and tool-loop abort propagation from 1.42.0 is already fixed on main (agent.ts and generate/action.ts), but three bugs remain: getAbortSignal in js/plugins/google-genai ignores already-aborted signals (allowing requests to proceed if aborted during async middleware or token fetch), appRoute in js/plugins/next leaves writer.write/writer.close rejections unhandled on disconnect, and defineGenerateAction in js/ai drops abortSignal.
Plan:
- Check
clientOptions.signal.abortedup front ingetAbortSignal(googleai/client.ts,vertexai/client.ts), safely handle closed-stream writer rejections inappRoute, and forwardabortSignalindefineGenerateAction. - Reproduce before and verify after with offline unit tests in
js/plugins/google-genai,js/plugins/next, andjs/ai.
Details
Already fixed on main (1.44.0)
js/plugins/next/src/index.ts:177,230:appRouteforwardsabortSignal: req.signaltoaction.runin both non-streaming and streaming branches.js/core/src/action.ts:603,661,783,815andjs/core/src/flow.ts:160:action.run,action.stream,bidiAction,streamBidi, andflowActionforwardabortSignal. (Note: custom flows wrappinggenerateor an agent must still pass theirFlowSideChannel.abortSignalexplicitly, asabortSignalis not stored in AsyncLocalStorage.)js/ai/src/agent-core.ts:1038-1065andjs/ai/src/agent.ts:1978-1988,2029,2152,2444,2640:setupAbort,defineCustomAgent,SessionRunner, anddefinePromptAgentwireabortSignalthrough togenerateStream. Covered byjs/ai/tests/agent_test.ts:5195-5485.js/ai/src/generate/action.ts:689-691,697,787,837:generateActionTurnchecksif (abortSignal?.aborted)beforedispatchModel, passes{ abortSignal }toresolveToolRequests, and preservesabortSignalin recursivegenerateHelperturns. Covered byjs/ai/tests/generate/generate_test.ts:1272-1347.
Remaining bugs to fix
-
getAbortSignaldrops already-aborted signalsjs/plugins/google-genai/src/googleai/client.ts:386-403js/plugins/google-genai/src/vertexai/client.ts:537-552- Both functions only register
clientOptions.signal.addEventListener('abort', () => controller.abort())without checkingif (clientOptions.signal.aborted). An already-aborted signal produces a livecontroller.signal(aborted === false), sofetch()still executes and bills tokens. This can trigger on direct model calls, or when the caller aborts while async model middleware (e.g.downloadRequestMediaor userusemiddleware) or Vertex AIgetToken()(vertexai/client.ts:524-530) is awaiting beforegetAbortSignalruns. - Fix: if
clientOptions.signal.abortedis true, immediately callcontroller.abort(clientOptions.signal.reason)and returncontroller.signalwithout starting the timeout timer; otherwise register{ once: true }forwardingclientOptions.signal.reason. - Note:
js/plugins/google-genai/tests/googleai/client_test.ts:989-1006reuses the already-abortedclientOptionsforsignal2; update that timeout case to use a freshAbortControllerand add explicit tests for already-aborted signals in bothgoogleaiandvertexaiclient tests. - Repro / verify:
pnpm --dir js/plugins/google-genai testwith a unit test passing an already-abortedAbortController.signaltogetAbortSignalandgenerateContent/generateContentStream(assertingsignal.aborted === trueand fetch receives an aborted signal).
-
appRoutestreaming IIFE throws unhandled rejections on client disconnectjs/plugins/next/src/index.ts:220-274- When the client aborts/disconnects, the
TransformStreamreadable side is cancelled, sowriter.write(...)andwriter.close()reject (surfacing asResponseAbortedin Next.js). Because the streaming work runs in an unawaited IIFE withfinally { await taskQueue.merge(); await writer.close(); }and no closed-stream guard or rejection handling (unlikejs/plugins/express/src/index.ts:208,230,246), this produces anunhandledRejection. - Fix: track closed/errored writer state (or wrap
writer.write/writer.closesafely) so closed-response writes are skipped/absorbed without rejecting the background IIFE, while still allowingdurableStreamwrites to complete viataskQueuewhenstreamManageris configured. - Repro / verify:
pnpm --dir js/plugins/next testwith a unit test that invokesappRoutewith a streaming flow/agent and anAbortControlleronNextRequest, cancelsresponse.bodyand aborts mid-stream, and verifiesabortSignalfires in the action and nounhandledRejectionoccurs.
-
defineGenerateActiondropsabortSignaljs/ai/src/generate/action.ts:99-125- The action handler destructures
{ streamingRequested, sendChunk, context }and omitsabortSignalwhen callinggenerateActionImpl. - Fix: destructure
abortSignaland pass it intogenerateActionImpl. - Repro / verify:
pnpm --dir js/ai testwith a unit test invoking the registered/util/generateaction with an abortedabortSignaland asserting the model is not called.
Run 31a99852-846a-4e4d-8c17-fae4b8690266 · Cloud Run logs · Dashboard
Opened #7366 (run f080f80b-16bc-4eb6-81a2-6a7ebab82ffe, Cloud Run logs, Dashboard)