From 3490b0e051a08ea427ffcf26c7a32736ea92988d Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Thu, 12 Nov 2026 00:16:24 -0600 Subject: [PATCH 1/3] fix(py): stop orphaned stream runs on reader disconnect --- packages/genkit/src/genkit/_core/_action.py | 15 ++- packages/genkit/src/genkit/_core/_channel.py | 122 ++++++++++++++++-- .../genkit/ai/generate_stream_cancel_test.py | 97 ++++++++++++++ .../genkit/tests/genkit/core/channel_test.py | 116 +++++++++++++++++ 4 files changed, 335 insertions(+), 15 deletions(-) diff --git a/packages/genkit/src/genkit/_core/_action.py b/packages/genkit/src/genkit/_core/_action.py index 5c77db936..942b9ce0f 100644 --- a/packages/genkit/src/genkit/_core/_action.py +++ b/packages/genkit/src/genkit/_core/_action.py @@ -237,9 +237,10 @@ class StreamResponse(Generic[ChunkT_co, OutputT_co]): ``await result.aclose()``) stops the run and awaits ``finally:`` cleanup; ``.response`` then raises ``GenkitError`` with status ``CANCELLED`` (``ModelStreamResponse`` - resolves with ``finish_reason == ABORTED`` instead). Reading to the end - or leaving a bare ``async for`` without closing doesn't stop the run. - See ``Action.stream``. + resolves with ``finish_reason == ABORTED`` instead). A reader cancelled + mid-``async for`` (e.g. a client disconnect) also stops the run, and so + does dropping a stream left unfinished after ``break``. Not iterating at + all leaves the run going. See ``Action.stream``. Example: ```python @@ -1296,9 +1297,11 @@ def _stream( Iterate ``.stream`` for chunks and await ``.response`` for the output. Closing early via ``async with my_flow.stream(x) as res:`` (or ``await res.aclose()``) cancels the run and awaits ``finally:`` cleanup, - and ``.response`` then raises ``GenkitError`` with status ``CANCELLED``. Python does not tear down an - ``AsyncIterator`` on ``break`` alone, so wrap the stream in ``async with`` - when exiting early should cancel the action. + and ``.response`` then raises ``GenkitError`` with status ``CANCELLED``. Cancelling + the reader mid-``async for`` stops the run the same way. Python does not + tear down an ``AsyncIterator`` on ``break`` alone: the run stops once the + stream is dropped, so wrap it in ``async with`` when the stop should + happen (and finish) right at the ``break``. Example: async with my_flow.stream(x) as res: diff --git a/packages/genkit/src/genkit/_core/_channel.py b/packages/genkit/src/genkit/_core/_channel.py index 80d6f59da..c828f893f 100644 --- a/packages/genkit/src/genkit/_core/_channel.py +++ b/packages/genkit/src/genkit/_core/_channel.py @@ -19,7 +19,9 @@ from __future__ import annotations import asyncio +import contextlib import sys +import weakref from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Callable, Coroutine from typing import Any, Generic, TypeVar @@ -182,21 +184,49 @@ def _settle(done: asyncio.Future[_ResultT]) -> None: return mirror +_pending_stops: set[asyncio.Task[None]] = set() + + +def _spawn_stop(stop: Callable[[], Awaitable[None]], *, on_done: Callable[[], None] | None = None) -> None: + task = asyncio.ensure_future(stop()) + _pending_stops.add(task) + + def _finish(done: asyncio.Task[None]) -> None: + _pending_stops.discard(done) + if on_done is not None: + on_done() + + task.add_done_callback(_finish) + + class StoppableStream(AsyncIterator[T]): """Single-pass ``AsyncIterator`` over a run's chunks, with explicit ``aclose()``. - ``__aiter__`` returns ``self`` (``aiter(s) is s``), so reading zero chunks, - pulling individual chunks with ``await anext(s)``, or exiting a bare - ``async for`` without closing leaves the background run going. Closing via + ``__aiter__`` returns ``self`` (``aiter(s) is s``). Closing via ``async with`` or ``await s.aclose()`` stops the run if it hasn't finished - and waits for cleanup. + and waits for cleanup. Without a close, the run is also stopped when: + + - the task reading it ends cancelled or with an unhandled exception before + the stream finishes (a web adapter cancelling the flow on client + disconnect, a failing ``TaskGroup``, or an exception raised inside the + ``async for`` body). A timeout around one ``__anext__()`` or ``anext()`` + (an SSE heartbeat tick) doesn't count: the reader carries on. + - the reader started iterating, then dropped the stream unfinished (a bare + ``async for`` that hits ``break``, then lets the stream go out of scope). + + Both stops are scheduled on the loop; use ``async with`` to wait for + cleanup. Reading zero chunks leaves the run going, so + ``await s.response`` alone still works. """ def __init__(self, *, chunks: AsyncIterable[T], stop: Callable[[], Awaitable[None]] | None) -> None: - self._chunks = chunks + self._chunks: AsyncIterable[T] | None = chunks self._source: AsyncIterator[T] | None = None self._stop = stop self._finished = False + self._stopped = False + self._loop_ref: weakref.ref[asyncio.AbstractEventLoop] | None = None + self._watched: weakref.WeakSet[asyncio.Task[Any]] = weakref.WeakSet() @override def __aiter__(self) -> Self: @@ -207,23 +237,94 @@ async def __anext__(self) -> T: if self._finished: raise StopAsyncIteration if self._source is None: + assert self._chunks is not None self._source = self._chunks.__aiter__() + self._loop_ref = weakref.ref(asyncio.get_running_loop()) + self._watch_reader() try: return await self._source.__anext__() except StopAsyncIteration: self._finished = True + self._chunks = None + self._source = None + self._stop = None + self._loop_ref = None raise + def _watch_reader(self) -> None: + """Stop the run once a reader task dies cancelled or with an unhandled exception. + + A cancelled or crashing `async for` without `async with` never calls + aclose(), so the run would keep generating (and calling tools) with + nobody reading. The decision waits for the task to end because a + timeout around a single __anext__() or anext() cancels only that await, + and the reader keeps going. Uses a weakref to ``self`` so the task's + done-callback list does not pin a dropped stream until the task ends. + """ + task = asyncio.current_task() + if self._stop is None or task is None or task in self._watched: + return + # A task whose whole job is this one __anext__() (wait_for before + # 3.12, ensure_future(anext(s)), or 2-arg anext(s, default)) is a poll, + # not the reader. + coro = task.get_coro() + if getattr(coro, 'cr_code', None) is _RAW_ANEXT_CODE or type(coro).__name__ == 'anext_awaitable': + return + self._watched.add(task) + stream_ref = weakref.ref(self) + + def _on_reader_done(done_task: asyncio.Task[Any]) -> None: + if done_task.cancelled() or done_task.exception() is not None: + stream = stream_ref() + if stream is not None: + stream._stop_run() + + task.add_done_callback(_on_reader_done) + + def _clear_stop_ref(self) -> None: + self._stop = None + + def _stop_run(self) -> None: + stop = self._stop + if stop is None or self._stopped or self._finished: + return + self._stopped = True + self._loop_ref = None + stream_ref = weakref.ref(self) + _spawn_stop(stop, on_done=lambda: (s := stream_ref()) is not None and s._clear_stop_ref()) # type: ignore[func-returns-value] + + def __del__(self) -> None: + # A bare `async for` that breaks never calls aclose(). Once the reader + # lets go of a stream it started reading, stop the run. + stop = self._stop + loop = self._loop_ref() if self._loop_ref is not None else None + if stop is None or self._stopped or self._finished or loop is None or loop.is_closed(): + return + self._stopped = True + self._stop = None + self._loop_ref = None + with contextlib.suppress(RuntimeError): # loop already closed + loop.call_soon_threadsafe(_spawn_stop, stop) + async def aclose(self) -> None: """Stop the run if it hasn't finished, and wait for it to end.""" if self._finished: return + self._stopped = True + self._loop_ref = None target = self._source if self._source is not None else self._chunks + self._chunks = None + self._source = None source_aclose = getattr(target, 'aclose', None) - if source_aclose is not None: - await source_aclose() - if self._stop is not None: - await self._stop() + stop = self._stop + try: + if source_aclose is not None: + await source_aclose() + if stop is not None: + await stop() + finally: + self._finished = True + self._stop = None async def __aenter__(self) -> Self: return self @@ -232,6 +333,9 @@ async def __aexit__(self, *exc: object) -> None: await self.aclose() +_RAW_ANEXT_CODE = StoppableStream.__anext__.__code__ + + def run_loop(coro: Coroutine[object, object, T], *, debug: bool | None = None) -> T: """Run a coroutine using uvloop if available, otherwise asyncio.""" try: diff --git a/packages/genkit/tests/genkit/ai/generate_stream_cancel_test.py b/packages/genkit/tests/genkit/ai/generate_stream_cancel_test.py index 8e50db66d..10d2c2d14 100644 --- a/packages/genkit/tests/genkit/ai/generate_stream_cancel_test.py +++ b/packages/genkit/tests/genkit/ai/generate_stream_cancel_test.py @@ -687,3 +687,100 @@ async def test_generate_cancel_before_hop_body_enters_emits_no_runtime_warning() runtime_warnings = [w for w in caught if issubclass(w.category, RuntimeWarning)] assert runtime_warnings == [] assert model.calls <= 1 + + +@pytest.mark.asyncio +async def test_generate_stream_reader_cancelled_mid_async_for_stops_the_model() -> None: + """Cancelling a task blocked in a bare `async for` cancels the model once the task ends. + + This is the web-adapter path: serve_flow cancels the flow on client + disconnect while it waits for the next chunk. + """ + ai, model = setup() + reading = asyncio.Event() + + async def bare_reader() -> None: + stream = ai.generate_stream(model='slow', prompt='hi') + async for _ in stream: + reading.set() + + task = asyncio.create_task(bare_reader()) + await settle(reading.wait()) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + await settle(model.cancelled.wait()) + + +@pytest.mark.asyncio +async def test_flow_reader_cancelled_mid_async_for_stops_inner_generate() -> None: + """A flow cancelled while reading a bare `ai.generate_stream` loop stops that model call too.""" + ai, model = setup() + reading = asyncio.Event() + + @ai.flow() + async def chef(order: str, ctx: FlowContext) -> str: + stream = ai.generate_stream(model='slow', prompt=order) + async for chunk in stream: + reading.set() + ctx.send_chunk(chunk.text) + return (await stream.response).text + + served = chef.stream('ramen') + + async def serve() -> None: + async for _ in served.stream: + pass + + task = asyncio.create_task(serve()) + await settle(reading.wait()) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + await settle(model.cancelled.wait()) + + +@pytest.mark.asyncio +async def test_generate_stream_break_then_drop_stops_the_model() -> None: + """A bare `async for` that breaks stops the model once the stream goes out of scope.""" + ai, model = setup() + + async def peek() -> Awaitable[ModelResponse]: + stream = ai.generate_stream(model='slow', prompt='hi') + async for _ in stream: + break + return stream.response + + response_future = await peek() + response = await settle(response_future) + + assert model.cancelled.is_set() + assert response.finish_reason == FinishReason.ABORTED + + +@pytest.mark.asyncio +async def test_generate_stream_break_while_held_keeps_the_model_running() -> None: + """Breaking out but keeping the stream lets the run finish; `.response` still resolves.""" + ai, model = setup() + stream = ai.generate_stream(model='slow', prompt='hi') + async for _ in stream: + break + model.release.set() + + response = await settle(stream.response) + + assert not model.cancelled.is_set() + assert response.text == 'one two' + + +@pytest.mark.asyncio +async def test_generate_stream_response_only_is_not_stopped_when_stream_is_dropped() -> None: + """`await ai.generate_stream(...).response` without iterating runs to completion.""" + ai, model = setup(release=True) + + response = await settle(ai.generate_stream(model='slow', prompt='hi').response) + + assert not model.cancelled.is_set() + assert response.text == 'one two' diff --git a/packages/genkit/tests/genkit/core/channel_test.py b/packages/genkit/tests/genkit/core/channel_test.py index 1754401ad..3f686b516 100644 --- a/packages/genkit/tests/genkit/core/channel_test.py +++ b/packages/genkit/tests/genkit/core/channel_test.py @@ -271,3 +271,119 @@ async def test_channel_anext_timeout_does_not_lose_next_chunk() -> None: assert await anext(channel) == 'second' with pytest.raises(StopAsyncIteration): await anext(channel) + + +@pytest.mark.asyncio +async def test_stoppable_stream_two_arg_anext_timeout_does_not_stop_run() -> None: + """Cancelling a 2-arg `anext(s, default)` poll task (Python 3.10/3.11 `wait_for` shape) leaves the run going.""" + from genkit._core._channel import StoppableStream + + channel: Channel[str, str] = Channel() + done: asyncio.Future[str] = asyncio.get_running_loop().create_future() + channel.set_close_future(done) + stopped = asyncio.Event() + + async def stop() -> None: + stopped.set() + + stream = StoppableStream(chunks=channel, stop=stop) + channel.send('first') + assert await anext(stream, None) == 'first' + + # Exercise both `wait_for(anext(s, None), timeout=...)` and an explicit task + # wrapping `anext_awaitable` (which is what `wait_for` builds on 3.10/3.11). + with pytest.raises(asyncio.TimeoutError): + await asyncio.wait_for(anext(stream, None), timeout=0.01) + + poll_task = asyncio.create_task(anext(stream, None)) # type: ignore[arg-type] + await asyncio.sleep(0) + poll_task.cancel() + with pytest.raises(asyncio.CancelledError): + await poll_task + + await asyncio.sleep(0) + assert not stopped.is_set() + + channel.send('second') + done.set_result('ok') + assert await anext(stream, None) == 'second' + assert await anext(stream, 'eof') == 'eof' + assert not stopped.is_set() + + +@pytest.mark.asyncio +async def test_stoppable_stream_reader_raising_in_loop_body_stops_run_without_gc() -> None: + """An unhandled error inside an `async for` body stops the producer immediately even if the stream is retained.""" + from genkit._core._channel import StoppableStream + + channel: Channel[str, str] = Channel() + done: asyncio.Future[str] = asyncio.get_running_loop().create_future() + channel.set_close_future(done) + stopped = asyncio.Event() + + async def stop() -> None: + stopped.set() + + # Keep `retained` in outer scope so `__del__` cannot fire on task failure. + retained = StoppableStream(chunks=channel, stop=stop) + channel.send('first') + + async def crashing_reader() -> None: + async for chunk in retained: + if chunk == 'first': + raise ValueError('bad chunk payload') + + reader_task = asyncio.create_task(crashing_reader()) + with pytest.raises(ValueError, match='bad chunk payload'): + await reader_task + + await asyncio.wait_for(stopped.wait(), timeout=1.0) + assert retained is not None + + +def test_stoppable_stream_retained_after_finish_or_aclose_does_not_pin_closed_loop() -> None: + """Retaining a finished or closed `StoppableStream` across loops does not keep closed event loops alive.""" + import gc + import weakref + from collections.abc import AsyncIterator + + from genkit._core._channel import StoppableStream + + retained: list[StoppableStream[str]] = [] + loop_refs: list[weakref.ref[asyncio.AbstractEventLoop]] = [] + + async def two_chunks() -> AsyncIterator[str]: + yield 'a' + yield 'b' + + async def drain_to_completion() -> None: + loop_refs.append(weakref.ref(asyncio.get_running_loop())) + stopped = asyncio.Event() + + async def stop() -> None: + stopped.set() + + s = StoppableStream(chunks=two_chunks(), stop=stop) + retained.append(s) + assert [c async for c in s] == ['a', 'b'] + + async def close_early() -> None: + loop_refs.append(weakref.ref(asyncio.get_running_loop())) + stopped = asyncio.Event() + + async def stop() -> None: + stopped.set() + + s = StoppableStream(chunks=two_chunks(), stop=stop) + retained.append(s) + async with s: + async for c in s: + assert c == 'a' + break + + asyncio.run(drain_to_completion()) + asyncio.run(close_early()) + gc.collect() + + assert len(retained) == 2 + assert [r() for r in loop_refs] == [None, None] From d59a83fa1a659011ce42b8719ae46f76ef46b5dd Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Thu, 12 Nov 2026 16:37:20 -0600 Subject: [PATCH 2/3] fix(py): harden StoppableStream aclose, reader callbacks, and nested stop draining --- packages/genkit/src/genkit/_core/_action.py | 33 ++-- packages/genkit/src/genkit/_core/_channel.py | 45 ++++-- .../genkit/ai/generate_stream_cancel_test.py | 69 +++++++++ .../genkit/tests/genkit/core/channel_test.py | 144 ++++++++++++++++++ 4 files changed, 270 insertions(+), 21 deletions(-) diff --git a/packages/genkit/src/genkit/_core/_action.py b/packages/genkit/src/genkit/_core/_action.py index 942b9ce0f..4b3afa822 100644 --- a/packages/genkit/src/genkit/_core/_action.py +++ b/packages/genkit/src/genkit/_core/_action.py @@ -25,7 +25,7 @@ import time import types from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Callable, Mapping, Sequence -from contextvars import ContextVar +from contextvars import ContextVar, copy_context from dataclasses import dataclass from typing import ( Any, @@ -44,7 +44,7 @@ from pydantic.errors import PydanticInvalidForJsonSchema, PydanticSchemaGenerationError, PydanticUserError from typing_extensions import Self, TypeVar -from genkit._core._channel import Channel, CloseableQueue, StoppableStream +from genkit._core._channel import Channel, CloseableQueue, StoppableStream, _stop_scope from genkit._core._compat import StrEnum from genkit._core._config_check import ( check_config_json_schema, @@ -1341,19 +1341,30 @@ def send_chunk(c: ChunkT) -> None: init=init, input_stream=input_stream, ) - run_task = asyncio.create_task(resp) + child_stops: set[asyncio.Task[None]] = set() + + def _create_run_task() -> asyncio.Task[ActionResponse[OutputT]]: + _stop_scope.set(child_stops) + return asyncio.create_task(resp) + + run_task = copy_context().run(_create_run_task) channel.set_close_future(run_task) reader_stopped = asyncio.Event() async def stop() -> None: - if run_task.done(): - return - if not reader_stopped.is_set(): - reader_stopped.set() - run_task.cancel() - # waiting here is what lets aclosing(...) promise the run is over - # once the block exits. - await asyncio.wait([run_task]) + if not run_task.done(): + if not reader_stopped.is_set(): + reader_stopped.set() + run_task.cancel() + # waiting here is what lets aclosing(...) promise the run is over + # once the block exits. + await asyncio.wait([run_task]) + # Let done-callbacks on run_task (e.g. inner StoppableStream._on_reader_done) + # schedule their _spawn_stop tasks, then drain any stops spawned in this scope. + await asyncio.sleep(0) + while child_stops: + await asyncio.wait(list(child_stops)) + await asyncio.sleep(0) # Mirror the run's terminal state onto .response so a caller awaiting it # sees the same success/error/cancel the run ended with, instead of diff --git a/packages/genkit/src/genkit/_core/_channel.py b/packages/genkit/src/genkit/_core/_channel.py index c828f893f..a5c4549a8 100644 --- a/packages/genkit/src/genkit/_core/_channel.py +++ b/packages/genkit/src/genkit/_core/_channel.py @@ -20,6 +20,7 @@ import asyncio import contextlib +import contextvars import sys import weakref from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Callable, Coroutine @@ -185,14 +186,22 @@ def _settle(done: asyncio.Future[_ResultT]) -> None: _pending_stops: set[asyncio.Task[None]] = set() +_stop_scope: contextvars.ContextVar[set[asyncio.Task[None]] | None] = contextvars.ContextVar( + '_stop_scope', default=None +) def _spawn_stop(stop: Callable[[], Awaitable[None]], *, on_done: Callable[[], None] | None = None) -> None: task = asyncio.ensure_future(stop()) _pending_stops.add(task) + scope = _stop_scope.get() + if scope is not None: + scope.add(task) def _finish(done: asyncio.Task[None]) -> None: _pending_stops.discard(done) + if scope is not None: + scope.discard(done) if on_done is not None: on_done() @@ -224,9 +233,12 @@ def __init__(self, *, chunks: AsyncIterable[T], stop: Callable[[], Awaitable[Non self._source: AsyncIterator[T] | None = None self._stop = stop self._finished = False + self._closing = False self._stopped = False self._loop_ref: weakref.ref[asyncio.AbstractEventLoop] | None = None - self._watched: weakref.WeakSet[asyncio.Task[Any]] = weakref.WeakSet() + self._watched: weakref.WeakKeyDictionary[asyncio.Task[Any], Callable[[asyncio.Task[Any]], None]] = ( + weakref.WeakKeyDictionary() + ) @override def __aiter__(self) -> Self: @@ -234,7 +246,7 @@ def __aiter__(self) -> Self: @override async def __anext__(self) -> T: - if self._finished: + if self._finished or self._closing: raise StopAsyncIteration if self._source is None: assert self._chunks is not None @@ -249,8 +261,14 @@ async def __anext__(self) -> T: self._source = None self._stop = None self._loop_ref = None + self._unwatch_readers() raise + def _unwatch_readers(self) -> None: + for task, cb in list(self._watched.items()): + task.remove_done_callback(cb) + self._watched.clear() + def _watch_reader(self) -> None: """Stop the run once a reader task dies cancelled or with an unhandled exception. @@ -270,15 +288,16 @@ def _watch_reader(self) -> None: coro = task.get_coro() if getattr(coro, 'cr_code', None) is _RAW_ANEXT_CODE or type(coro).__name__ == 'anext_awaitable': return - self._watched.add(task) stream_ref = weakref.ref(self) def _on_reader_done(done_task: asyncio.Task[Any]) -> None: + stream = stream_ref() + if stream is None or stream._finished or stream._stopped or stream._closing: + return if done_task.cancelled() or done_task.exception() is not None: - stream = stream_ref() - if stream is not None: - stream._stop_run() + stream._stop_run() + self._watched[task] = _on_reader_done task.add_done_callback(_on_reader_done) def _clear_stop_ref(self) -> None: @@ -290,12 +309,14 @@ def _stop_run(self) -> None: return self._stopped = True self._loop_ref = None + self._unwatch_readers() stream_ref = weakref.ref(self) _spawn_stop(stop, on_done=lambda: (s := stream_ref()) is not None and s._clear_stop_ref()) # type: ignore[func-returns-value] def __del__(self) -> None: # A bare `async for` that breaks never calls aclose(). Once the reader # lets go of a stream it started reading, stop the run. + self._unwatch_readers() stop = self._stop loop = self._loop_ref() if self._loop_ref is not None else None if stop is None or self._stopped or self._finished or loop is None or loop.is_closed(): @@ -310,8 +331,10 @@ async def aclose(self) -> None: """Stop the run if it hasn't finished, and wait for it to end.""" if self._finished: return + self._closing = True self._stopped = True self._loop_ref = None + self._unwatch_readers() target = self._source if self._source is not None else self._chunks self._chunks = None self._source = None @@ -320,11 +343,13 @@ async def aclose(self) -> None: try: if source_aclose is not None: await source_aclose() - if stop is not None: - await stop() finally: - self._finished = True - self._stop = None + try: + if stop is not None: + await stop() + finally: + self._finished = True + self._stop = None async def __aenter__(self) -> Self: return self diff --git a/packages/genkit/tests/genkit/ai/generate_stream_cancel_test.py b/packages/genkit/tests/genkit/ai/generate_stream_cancel_test.py index 10d2c2d14..866795c82 100644 --- a/packages/genkit/tests/genkit/ai/generate_stream_cancel_test.py +++ b/packages/genkit/tests/genkit/ai/generate_stream_cancel_test.py @@ -784,3 +784,72 @@ async def test_generate_stream_response_only_is_not_stopped_when_stream_is_dropp assert not model.cancelled.is_set() assert response.text == 'one two' + + +@pytest.mark.asyncio +async def test_nested_stream_cleanup_finishes_before_outer_aclose_returns() -> None: + """Outer aclose() waits for nested generate_stream cancellation/finally before returning.""" + ai = Genkit() + reading = asyncio.Event() + model_finally_ran = asyncio.Event() + + async def slow_model(_request: ModelRequest, ctx: ModelContext) -> ModelResponse: + try: + ctx.send_chunk(ModelResponseChunk(role=Role.MODEL, content=[Part.from_text('one')])) + await asyncio.sleep(10) + return ModelResponse( + finish_reason=FinishReason.STOP, + message=Message(role=Role.MODEL, content=[Part.from_text('done')]), + ) + finally: + await asyncio.sleep(0) + model_finally_ran.set() + + ai.define_model(name='slow_finally', fn=slow_model) + + @ai.flow() + async def chef(order: str, ctx: FlowContext) -> str: + stream = ai.generate_stream(model='slow_finally', prompt=order) + async for chunk in stream: + reading.set() + ctx.send_chunk(chunk.text) + return (await stream.response).text + + served = chef.stream('ramen') + + async def read_first() -> None: + async for _ in served.stream: + await reading.wait() + break + + await read_first() + await served.stream.aclose() + # Must already be set without yielding to the loop again (Flask _iter_over_async shape). + assert model_finally_ran.is_set() + + +@pytest.mark.asyncio +async def test_to_sse_disconnect_cancels_flow_and_model() -> None: + """Closing to_sse() early (web handler disconnect path) cancels the flow and inner model.""" + import contextlib + + from genkit.web._sse import to_sse + + ai, model = setup() + + @ai.flow() + async def chef(order: str, ctx: FlowContext) -> str: + stream = ai.generate_stream(model='slow', prompt=order) + async for chunk in stream: + ctx.send_chunk(chunk.text) + return (await stream.response).text + + served = chef.stream('ramen') + frames: list[str] = [] + async with contextlib.aclosing(to_sse(served)) as lines: + async for line in lines: + frames.append(line) + break + + assert len(frames) == 1 + assert model.cancelled.is_set() diff --git a/packages/genkit/tests/genkit/core/channel_test.py b/packages/genkit/tests/genkit/core/channel_test.py index 3f686b516..15d9d2813 100644 --- a/packages/genkit/tests/genkit/core/channel_test.py +++ b/packages/genkit/tests/genkit/core/channel_test.py @@ -387,3 +387,147 @@ async def stop() -> None: assert len(retained) == 2 assert [r() for r in loop_refs] == [None, None] + + +@pytest.mark.asyncio +async def test_stoppable_stream_aclose_from_another_task_ends_reader_cleanly() -> None: + """Calling aclose() from another task while a reader is mid-loop ends __anext__ with StopAsyncIteration.""" + from genkit._core._channel import StoppableStream + + channel: Channel[str, str] = Channel() + done: asyncio.Future[str] = asyncio.get_running_loop().create_future() + channel.set_close_future(done) + release_stop = asyncio.Event() + in_stop = asyncio.Event() + + async def stop() -> None: + in_stop.set() + await release_stop.wait() + + stream = StoppableStream(chunks=channel, stop=stop) + channel.send('first') + + got_first = asyncio.Event() + proceed_next = asyncio.Event() + reader_ended_cleanly = False + + async def reader() -> None: + nonlocal reader_ended_cleanly + async for chunk in stream: + assert chunk == 'first' + got_first.set() + await proceed_next.wait() + reader_ended_cleanly = True + + reader_task = asyncio.create_task(reader()) + await got_first.wait() + + close_task = asyncio.create_task(stream.aclose()) + await in_stop.wait() + + # Reader calls __anext__ while aclose() is suspended in stop(). + proceed_next.set() + await reader_task + assert reader_ended_cleanly + + release_stop.set() + await close_task + + +@pytest.mark.asyncio +async def test_stoppable_stream_removes_reader_callback_on_finish_and_aclose() -> None: + """Finished and closed StoppableStreams remove their done callback from long-lived reader tasks.""" + from collections.abc import AsyncIterator + + from genkit._core._channel import StoppableStream + + async def one_chunk() -> AsyncIterator[str]: + yield 'a' + + async def noop_stop() -> None: + return None + + task = asyncio.current_task() + assert task is not None + baseline = len(getattr(task, '_callbacks', ())) + + for _ in range(25): + s = StoppableStream(chunks=one_chunk(), stop=noop_stop) + assert [c async for c in s] == ['a'] + + for _ in range(25): + s = StoppableStream(chunks=one_chunk(), stop=noop_stop) + async with s: + async for _ in s: + break + + assert len(getattr(task, '_callbacks', ())) == baseline + + +@pytest.mark.asyncio +async def test_stoppable_stream_fire_and_forget_reader_still_logs_unretrieved_exception() -> None: + """A fire-and-forget task that finishes a StoppableStream and later raises still reports its exception.""" + import gc + from collections.abc import AsyncIterator + + from genkit._core._channel import StoppableStream + + async def one_chunk() -> AsyncIterator[str]: + yield 'a' + + async def noop_stop() -> None: + return None + + loop = asyncio.get_running_loop() + unretrieved: list[dict[str, object]] = [] + prev_handler = loop.get_exception_handler() + loop.set_exception_handler(lambda _loop, ctx: unretrieved.append(dict(ctx))) + try: + + async def fire_and_forget() -> None: + s = StoppableStream(chunks=one_chunk(), stop=noop_stop) + assert [c async for c in s] == ['a'] + raise RuntimeError('post-stream failure') + + task = asyncio.create_task(fire_and_forget()) + await asyncio.wait([task]) + del task + gc.collect() + await asyncio.sleep(0) + finally: + loop.set_exception_handler(prev_handler) + + assert len(unretrieved) == 1 + assert isinstance(unretrieved[0].get('exception'), RuntimeError) + + +@pytest.mark.asyncio +async def test_stoppable_stream_source_aclose_error_still_runs_stop() -> None: + """If source.aclose() raises, StoppableStream.aclose() still calls stop() and marks finished.""" + from genkit._core._channel import StoppableStream + + stopped = False + + class FailingSource: + def __aiter__(self) -> FailingSource: + return self + + async def __anext__(self) -> str: + return 'chunk' + + async def aclose(self) -> None: + raise RuntimeError('source close failed') + + async def stop() -> None: + nonlocal stopped + stopped = True + + stream = StoppableStream(chunks=FailingSource(), stop=stop) + assert await anext(stream) == 'chunk' + + with pytest.raises(RuntimeError, match='source close failed'): + await stream.aclose() + + assert stopped + with pytest.raises(StopAsyncIteration): + await anext(stream) From 7c3ffb032d108082fc6de72cdcb3f58a75945876 Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Thu, 12 Nov 2026 21:31:25 -0600 Subject: [PATCH 3/3] fix(fastapi): cancel non-streaming action runs on client disconnect --- packages/genkit-django/tests/django_test.py | 60 +++++++++++++++++++ .../src/genkit_fastapi/_handler.py | 28 ++++++++- packages/genkit-fastapi/tests/fastapi_test.py | 57 ++++++++++++++++++ 3 files changed, 144 insertions(+), 1 deletion(-) diff --git a/packages/genkit-django/tests/django_test.py b/packages/genkit-django/tests/django_test.py index 824930497..cdc15aed6 100644 --- a/packages/genkit-django/tests/django_test.py +++ b/packages/genkit-django/tests/django_test.py @@ -567,6 +567,66 @@ async def send(message: dict[str, Any]) -> None: assert flow_cancelled.is_set() +@pytest.mark.asyncio +async def test_django_non_streaming_client_disconnect_cancels_flow(monkeypatch: pytest.MonkeyPatch) -> None: + """Django ASGIHandler cancels a non-streaming flow view when the client disconnects.""" + ai = Genkit() + flow_started = asyncio.Event() + flow_cancelled = asyncio.Event() + cleanup_finished = asyncio.Event() + + @genkit_django_handler(ai) + @ai.flow() + async def slow(_: str) -> str: + flow_started.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + flow_cancelled.set() + raise + finally: + await asyncio.sleep(0.02) + cleanup_finished.set() + return 'never' + + module = types.ModuleType('genkit_django_nonstream_disconnect_urls') + module.urlpatterns = [path('slow', slow)] # type: ignore[attr-defined] # pyrefly: ignore[missing-attribute] + monkeypatch.setitem(sys.modules, 'genkit_django_nonstream_disconnect_urls', module) + + request_read = False + + async def receive() -> dict[str, Any]: + nonlocal request_read + if not request_read: + request_read = True + return {'type': 'http.request', 'body': json.dumps({'data': 'x'}).encode(), 'more_body': False} + await flow_started.wait() + return {'type': 'http.disconnect'} + + async def send(_message: dict[str, Any]) -> None: + return + + scope = { + 'type': 'http', + 'asgi': {'version': '3.0'}, + 'http_version': '1.1', + 'method': 'POST', + 'scheme': 'http', + 'path': '/slow', + 'raw_path': b'/slow', + 'root_path': '', + 'query_string': b'', + 'headers': [(b'content-type', b'application/json')], + 'client': ('testclient', 50000), + 'server': ('testserver', 80), + } + with override_settings(ROOT_URLCONF='genkit_django_nonstream_disconnect_urls'): + await asyncio.wait_for(ASGIHandler()(scope, receive, send), timeout=5) + + assert flow_cancelled.is_set() + await asyncio.wait_for(cleanup_finished.wait(), timeout=1.0) + + @pytest.mark.asyncio async def test_django_failure_logs_name_the_flow( urlconf: None, # noqa: ARG001 diff --git a/packages/genkit-fastapi/src/genkit_fastapi/_handler.py b/packages/genkit-fastapi/src/genkit_fastapi/_handler.py index eb304e26a..2df58502c 100644 --- a/packages/genkit-fastapi/src/genkit_fastapi/_handler.py +++ b/packages/genkit-fastapi/src/genkit_fastapi/_handler.py @@ -182,14 +182,40 @@ async def event_stream() -> AsyncIterator[str]: return StreamingResponse(event_stream(), media_type='text/event-stream') + run_task = asyncio.create_task(action_obj.run(input=action_input, context=context, init=resolved_init)) + + async def _watch_disconnect() -> None: + while not run_task.done(): + try: + if await request.is_disconnected() is True: + run_task.cancel() + return + except Exception: + # Test stubs or custom Request objects without a receive() channel + # shouldn't fail the request. + return + await asyncio.sleep(0.05) + + watch_task = asyncio.create_task(_watch_disconnect()) try: - response = await action_obj.run(input=action_input, context=context, init=resolved_init) + response = await run_task if response.response is None and empty_status is not None: return Response(status_code=empty_status) return Response(content=result_json(response.response), media_type='application/json') + except asyncio.CancelledError: + if run_task.cancelled(): + return Response(status_code=499) + run_task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await run_task + raise except Exception as e: _log_failure(error=e, flow=action_obj.name, where='run') return json_error_response(e) + finally: + watch_task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await watch_task def genkit_fastapi_handler( diff --git a/packages/genkit-fastapi/tests/fastapi_test.py b/packages/genkit-fastapi/tests/fastapi_test.py index b7e0fd56c..b7d7fd4a2 100644 --- a/packages/genkit-fastapi/tests/fastapi_test.py +++ b/packages/genkit-fastapi/tests/fastapi_test.py @@ -1317,3 +1317,60 @@ async def slow(_: str, ctx: FlowContext) -> str: assert bodies == [b'data: {"message":1}\n\n'] assert flow_cancelled.is_set() await asyncio.wait_for(cleanup_finished.wait(), timeout=1.0) + + +@pytest.mark.asyncio +async def test_fastapi_non_streaming_client_disconnect_cancels_flow() -> None: + """A client that disconnects during a non-streaming POST cancels the flow and awaits cleanup.""" + ai = Genkit() + flow_started = asyncio.Event() + flow_cancelled = asyncio.Event() + cleanup_finished = asyncio.Event() + + @ai.flow() + async def slow(_: str) -> str: + flow_started.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + flow_cancelled.set() + raise + finally: + await asyncio.sleep(0.02) + cleanup_finished.set() + return 'never' + + app = FastAPI() + app.include_router(serve_flow(slow, base_path='/slow')) + + request_read = False + + async def receive() -> dict[str, Any]: + nonlocal request_read + if not request_read: + request_read = True + return {'type': 'http.request', 'body': json.dumps({'data': 'x'}).encode(), 'more_body': False} + await flow_started.wait() + return {'type': 'http.disconnect'} + + async def send(_message: MutableMapping[str, Any]) -> None: + return + + scope = { + 'type': 'http', + 'asgi': {'version': '3.0', 'spec_version': '2.3'}, + 'http_version': '1.1', + 'method': 'POST', + 'scheme': 'http', + 'path': '/slow', + 'raw_path': b'/slow', + 'root_path': '', + 'query_string': b'', + 'headers': [(b'content-type', b'application/json')], + 'client': ('testclient', 50000), + 'server': ('testserver', 80), + } + await asyncio.wait_for(app(scope, receive, send), timeout=5) + + assert flow_cancelled.is_set() + await asyncio.wait_for(cleanup_finished.wait(), timeout=1.0)