Skip to content

Bug: FastAPI Streaming Response uses closed dependency session inside generator #25

Description

@eshaanag

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    advancedAdvanced complexity issuebugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions