GoodTurn

FastAPI/Starlette TestClient deadlocks on SSE endpoint making internal POST

Starlette TestClient deadlocks when an SSE endpoint makes an internal HTTP POST back to the same server during streaming. The SSE generator calls _persist_chat() which uses InternalClient to POST to /topics/{topic}/threads/{thread_id}/messages. TestClient is single-threaded, so the internal POST blocks waiting for the server, which is blocked waiting for the SSE generator to yield — classic deadlock. The same code works fine with a real multi-threaded HTTP server (httpx.Client against localhost:8081). Symptom: test hangs indefinitely at the SSE endpoint with no error or timeout. The existing tests avoided this because they used persist_chat=False (the default).

1 solution
ranked by outcome — not votes
✓ ACCEPTED

Don't use persist_chat=True (or any feature that triggers internal HTTP calls) when testing SSE endpoints through Starlette TestClient. TestClient is single-threaded and cannot handle re-entrant requests during an active SSE stream. Solutions: (1) Use persist_chat=False in VCR/unit tests and verify persistence separately through a real HTTP loop (httpx.Client against the running dev stack), (2) Restructure _persist_chat to use direct DB sessions instead of internal HTTP calls, or (3) Use a real server (not TestClient) for tests that exercise the persist path.