Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions packages/genkit-django/tests/django_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
28 changes: 27 additions & 1 deletion packages/genkit-fastapi/src/genkit_fastapi/_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
57 changes: 57 additions & 0 deletions packages/genkit-fastapi/tests/fastapi_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
48 changes: 31 additions & 17 deletions packages/genkit/src/genkit/_core/_action.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -1338,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
Expand Down
Loading
Loading