Skip to content

fix(py): Django WSGI streaming, ModelResponse JSON isolation, run_main thread safety - #7143

Closed
huangjeff5 wants to merge 9 commits into
mainfrom
fix/py-1.0-pr5-web-serving
Closed

huangjeff5 wants to merge 9 commits into
mainfrom
fix/py-1.0-pr5-web-serving

Conversation

@huangjeff5

Copy link
Copy Markdown
Contributor

Web adapter serving fixes for Django, Flask, and FastAPI.

Main Changes

  • Thread-safe loop execution in run_main: Enables reflection server to operate safely when invoked from background thread pools.
  • Isolated ModelResponse.request from wire serialization: Excludes raw model request dumps from SSE streams and JSON endpoints.
  • Django SSE under WSGI: Fixed streaming response handling under WSGI worker setups.

genkit_flask_handler created one loop at decoration time and every
streamed response drove it with run_until_complete. Two concurrent SSE
requests on a threaded WSGI server collided with "This event loop is
already running" (7 of 8 returned 500). The body also iterated after
Flask popped the request context, so flask.g and flask.request raised
inside streamed flows.

Each streamed response now owns a loop, driven from the thread that
iterates the body and closed after the flow's cleanup runs. The body is
wrapped in stream_with_context. genkit-flask depends on flask[async] so
the async view works in a clean venv (asgiref).
…ockets

_LoopLocal keyed a WeakKeyDictionary on the event loop, but the cached
client's keep-alive transport references that loop, so the key never
died. Every asyncio.run() (Celery tasks) or async_to_sync call (Flask,
Django WSGI) pinned its closed loop, client, and sockets until EMFILE.

Entries are now keyed by id(loop) and hold a weakref to the loop. Each
entry registers an async-generator finalizer with its loop, so
loop.shutdown_asyncgens() (asyncio.run, uvloop.run, asgiref) awaits the
client's aclose() / async close() while the loop can still run it. A
loop closed without that step is dropped on the next call from any loop.
Registry._plugin_init_tasks drops closed loops the same way (a Task
holds its loop).

8 sequential asyncio.run() calls: FDs +16 -> +0 (httpx keep-alive),
+8 -> +0 (live Gemini); closed loops alive 9/9 -> 0/9 (httpx).
StoppableStream is a plain AsyncIterator, so async for never calls
aclose(). When serve_flow cancelled a flow on client disconnect while it
read a bare `async for chunk in ai.generate_stream(...)`, the model kept
generating and calling tools in the background until it finished.

The stream now stops its run when:
- the task reading it is cancelled mid-wait and ends cancelled. The
  decision waits for the task to end, so a timeout around a single
  __anext__() (an SSE heartbeat tick) still leaves the run going.
- the reader started iterating and dropped the stream unfinished (a bare
  async for that breaks, then goes out of scope).

Uvicorn TCP disconnect after 3 chunks (serve_flow, StreamingResponse
generator, to_sse): runs stopped 3/9 -> 9/9; chunks generated after
disconnect 37 -> 0 per stream. Live Gemini: 3/3 stopped.
Channel._pop treated a None chunk as end-of-stream, while the fast path
(queue already non-empty) returned it. A FlowContext[str | None] stream
was truncated or not depending on timing. Nothing sends None as EOF; the
close future ends the stream, so _pop now returns every chunk.
serve_flow's context_dependency and genkit_fastapi_handler's
context_provider passed only dict values through; a Pydantic principal,
dataclass, or MappingProxyType became None with no warning, so the flow
ran with no auth context.

Mappings, Pydantic models, and dataclasses now become a shallow dict of
their fields (nested values keep their types). Anything else raises
TypeError naming the hook.
…tion status

PublicError(429, ...) was accepted unvalidated, then http_status_code
raised KeyError while the response was written, cutting the SSE stream
with no error frame. PublicError now maps HTTP codes to status names
(429 -> RESOURCE_EXHAUSTED) and raises ValueError for anything that names
nothing; http_status_code falls back to 500.

A fastapi.HTTPException(403) raised inside a served flow became a 500.
The non-streaming route now re-raises it, so it keeps its status and
detail, as one raised from a context provider already did.
to_sse and result_json serialized a ModelResponse whole, including
request: the system prompt, tool definitions, retrieved docs, and
history went to the browser in the final frame of ai.generate_stream()
or any flow returning the response. The framing now drops request; the
message, usage, and finish reason are unchanged.

Wire change: clients reading result.request get nothing. No opt-in was
added; flows that want to expose it can return it explicitly.
Django's WSGIHandler drains an async StreamingHttpResponse body to a
list before sending, so SSE under gunicorn/wsgiref arrived in one piece
at the end (TTFB = total time). Under a WSGIRequest the view now returns
a sync iterator that drives the flow on a private event loop in the
worker thread. ASGI is unchanged.

Docs: the view is async, so context providers read the user with
await request.auser(); request.user raises SynchronousOnlyOperation.
README, module, and handler docs now say WSGI works and Django 5.0+
(not 4.1+, not ASGI-only); classifiers add Django 5.2 and 6.0.

Threaded WSGI, 5 chunks at 200 ms: TTFB 1.07 s -> 0.03 s; 8 concurrent
streams 8/8 with max TTFB 1.07 s -> 0.02 s.
run_main opened anyio.open_signal_receiver unconditionally once
reflection was on. On a worker thread (a WSGI worker, a Celery task)
with GENKIT_ENV=dev that raised "set_wakeup_fd only works in main
thread". Off the main thread it now skips signal handling and waits for
the reflection server alone.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces WSGI support for Genkit's Django and Flask integrations, enabling concurrent SSE streaming by driving async generators on private, per-response event loops. It also enhances FastAPI context handling to support Pydantic models, dataclasses, and custom mappings, and ensures that HTTPException status codes are preserved. In the core package, improvements were made to automatically cancel background runs when stream readers disconnect or exit early, prevent socket leaks in the event-loop client cache, and omit sensitive request data from serialized ModelResponse SSE frames. Feedback on the changes highlights critical missing asyncio imports in the Django and Flask handlers, and suggests improvements for exception traversal in FastAPI and safe garbage collection during interpreter shutdown in StoppableStream.__del__.

@@ -20,10 +20,11 @@
import contextlib

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The module uses asyncio in _iter_over_async but does not import it. This will cause a NameError at runtime when handling WSGI requests.

Suggested change
import contextlib
import asyncio
import contextlib

@@ -20,11 +20,10 @@
import contextlib

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The module uses asyncio in _iter_over_async but does not import it (the previous import of AbstractEventLoop from asyncio was removed). This will cause a NameError at runtime.

Suggested change
import contextlib
import asyncio
import contextlib

Comment on lines +226 to +231
seen: BaseException | None = error
while seen is not None:
if isinstance(seen, StarletteHTTPException):
return seen
seen = seen.__cause__
return None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The exception traversal currently only checks __cause__. In Python, exceptions can also be chained via __context__ (implicit chaining). Traversing both __cause__ and __context__ while protecting against potential cycles (using a visited set) makes this helper much more robust.

Suggested change
seen: BaseException | None = error
while seen is not None:
if isinstance(seen, StarletteHTTPException):
return seen
seen = seen.__cause__
return None
visited = set()
seen: BaseException | None = error
while seen is not None and id(seen) not in visited:
visited.add(id(seen))
if isinstance(seen, StarletteHTTPException):
return seen
seen = seen.__cause__ or seen.__context__
return None

Comment on lines +267 to +274
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.
if self._stop is None or self._stopped or self._finished or self._loop is None:
return
self._stopped = True
with contextlib.suppress(RuntimeError): # loop already closed
self._loop.call_soon_threadsafe(_spawn_stop, self._stop)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

During interpreter shutdown, module-level globals like contextlib and _spawn_stop can be garbage collected and set to None, which can cause NameError or TypeError inside __del__. Capturing them as default arguments or checking for None prevents these noisy shutdown warnings.

Suggested change
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.
if self._stop is None or self._stopped or self._finished or self._loop is None:
return
self._stopped = True
with contextlib.suppress(RuntimeError): # loop already closed
self._loop.call_soon_threadsafe(_spawn_stop, self._stop)
def __del__(self, *, suppress=contextlib.suppress, spawn_stop=_spawn_stop) -> None:
# A bare `async for` that breaks never calls aclose(). Once the reader
# lets go of a stream it started reading, stop the run.
if self._stop is None or self._stopped or self._finished or self._loop is None:
return
self._stopped = True
if suppress is not None and spawn_stop is not None:
with suppress(RuntimeError):
self._loop.call_soon_threadsafe(spawn_stop, self._stop)

@huangjeff5

Copy link
Copy Markdown
Contributor Author

Closing: migrated to standalone repository genkit-ai/genkit-python (PR #51): genkit-ai/genkit-python#51

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant