What is missing / Why it matters
In backend/features/llm_analysis/router.py, the /explain/stream endpoint injects the database session using db: AsyncSession = Depends(get_db). It then defines an event_generator() coroutine which yields tokens and commits the newly generated narrative using await db.commit().
Because FastAPI yields/closes the dependency context as soon as the route handler returns the StreamingResponse object (which happens before the generator starts yielding or completes), the database session db is closed by the time the stream writes to the database. This leads to connection leakage, connection pool depletion, or runtime transaction failures during active LLM streaming.
Acceptance Criteria
- Refactor
explain_commit_stream in backend/features/llm_analysis/router.py to obtain a dedicated database session within the generator scope using async with AsyncSessionLocal() as stream_db: instead of using the injected db dependency inside the streaming generator block.
- Verify that streaming responses function properly without logging database errors when the connection is released or closed.
What is missing / Why it matters
In
backend/features/llm_analysis/router.py, the/explain/streamendpoint injects the database session usingdb: AsyncSession = Depends(get_db). It then defines anevent_generator()coroutine which yields tokens and commits the newly generated narrative usingawait db.commit().Because FastAPI yields/closes the dependency context as soon as the route handler returns the
StreamingResponseobject (which happens before the generator starts yielding or completes), the database sessiondbis closed by the time the stream writes to the database. This leads to connection leakage, connection pool depletion, or runtime transaction failures during active LLM streaming.Acceptance Criteria
explain_commit_streaminbackend/features/llm_analysis/router.pyto obtain a dedicated database session within the generator scope usingasync with AsyncSessionLocal() as stream_db:instead of using the injecteddbdependency inside the streaming generator block.