genkit icon indicating copy to clipboard operation
genkit copied to clipboard

Abort signal is delivered to `appRoute` but the flow keeps generating

Open JoFont opened this issue 2 months ago • 5 comments

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,674 a 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 AbortController and 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's appRoute forwards req.signal as abortSignal to action.run (lib/index.js, both the streaming and non-streaming branches).
  • agent-core's setupAbort wires an external signal to its own controller.
  • googleai/gemini.js passes abortSignal as the model call's fetch signal.

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

  1. A Genkit flow that makes ≥2 sequential model calls (e.g. a tool-using agent).
  2. Serve it through @genkit-ai/next's appRoute.
  3. Stream it to a browser client; abort the client fetch after the first tool call.
  4. Observe: request.signal fires immediately; the flow's later generations still complete and are billed.

Happy to supply a runnable repro if useful.

JoFont avatar Sep 08 '26 17:09 JoFont

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 generateHelper recursively calls itself during tool iterations, the abortSignal was 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 when maxTurns > 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.

JoFont avatar Sep 08 '26 17:09 JoFont

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.

modelpath-dev avatar Sep 09 '26 07:09 modelpath-dev

@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.

ssbushi avatar Nov 25 '26 16:11 ssbushi

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.aborted up front in getAbortSignal (googleai/client.ts, vertexai/client.ts), safely handle closed-stream writer rejections in appRoute, and forward abortSignal in defineGenerateAction.
  • Reproduce before and verify after with offline unit tests in js/plugins/google-genai, js/plugins/next, and js/ai.
Details

Already fixed on main (1.44.0)

  • js/plugins/next/src/index.ts:177,230: appRoute forwards abortSignal: req.signal to action.run in both non-streaming and streaming branches.
  • js/core/src/action.ts:603,661,783,815 and js/core/src/flow.ts:160: action.run, action.stream, bidiAction, streamBidi, and flowAction forward abortSignal. (Note: custom flows wrapping generate or an agent must still pass their FlowSideChannel.abortSignal explicitly, as abortSignal is not stored in AsyncLocalStorage.)
  • js/ai/src/agent-core.ts:1038-1065 and js/ai/src/agent.ts:1978-1988,2029,2152,2444,2640: setupAbort, defineCustomAgent, SessionRunner, and definePromptAgent wire abortSignal through to generateStream. Covered by js/ai/tests/agent_test.ts:5195-5485.
  • js/ai/src/generate/action.ts:689-691,697,787,837: generateActionTurn checks if (abortSignal?.aborted) before dispatchModel, passes { abortSignal } to resolveToolRequests, and preserves abortSignal in recursive generateHelper turns. Covered by js/ai/tests/generate/generate_test.ts:1272-1347.

Remaining bugs to fix

  1. getAbortSignal drops already-aborted signals

    • js/plugins/google-genai/src/googleai/client.ts:386-403
    • js/plugins/google-genai/src/vertexai/client.ts:537-552
    • Both functions only register clientOptions.signal.addEventListener('abort', () => controller.abort()) without checking if (clientOptions.signal.aborted). An already-aborted signal produces a live controller.signal (aborted === false), so fetch() still executes and bills tokens. This can trigger on direct model calls, or when the caller aborts while async model middleware (e.g. downloadRequestMedia or user use middleware) or Vertex AI getToken() (vertexai/client.ts:524-530) is awaiting before getAbortSignal runs.
    • Fix: if clientOptions.signal.aborted is true, immediately call controller.abort(clientOptions.signal.reason) and return controller.signal without starting the timeout timer; otherwise register { once: true } forwarding clientOptions.signal.reason.
    • Note: js/plugins/google-genai/tests/googleai/client_test.ts:989-1006 reuses the already-aborted clientOptions for signal2; update that timeout case to use a fresh AbortController and add explicit tests for already-aborted signals in both googleai and vertexai client tests.
    • Repro / verify: pnpm --dir js/plugins/google-genai test with a unit test passing an already-aborted AbortController.signal to getAbortSignal and generateContent / generateContentStream (asserting signal.aborted === true and fetch receives an aborted signal).
  2. appRoute streaming IIFE throws unhandled rejections on client disconnect

    • js/plugins/next/src/index.ts:220-274
    • When the client aborts/disconnects, the TransformStream readable side is cancelled, so writer.write(...) and writer.close() reject (surfacing as ResponseAborted in Next.js). Because the streaming work runs in an unawaited IIFE with finally { await taskQueue.merge(); await writer.close(); } and no closed-stream guard or rejection handling (unlike js/plugins/express/src/index.ts:208,230,246), this produces an unhandledRejection.
    • Fix: track closed/errored writer state (or wrap writer.write / writer.close safely) so closed-response writes are skipped/absorbed without rejecting the background IIFE, while still allowing durableStream writes to complete via taskQueue when streamManager is configured.
    • Repro / verify: pnpm --dir js/plugins/next test with a unit test that invokes appRoute with a streaming flow/agent and an AbortController on NextRequest, cancels response.body and aborts mid-stream, and verifies abortSignal fires in the action and no unhandledRejection occurs.
  3. defineGenerateAction drops abortSignal

    • js/ai/src/generate/action.ts:99-125
    • The action handler destructures { streamingRequested, sendChunk, context } and omits abortSignal when calling generateActionImpl.
    • Fix: destructure abortSignal and pass it into generateActionImpl.
    • Repro / verify: pnpm --dir js/ai test with a unit test invoking the registered /util/generate action with an aborted abortSignal and asserting the model is not called.

Run 31a99852-846a-4e4d-8c17-fae4b8690266 · Cloud Run logs · Dashboard

genkit-bot avatar Nov 25 '26 16:11 genkit-bot

Opened #7366 (run f080f80b-16bc-4eb6-81a2-6a7ebab82ffe, Cloud Run logs, Dashboard)

genkit-bot avatar Nov 25 '26 20:11 genkit-bot