Skip to content

fix(backend): offload the chat answer persistence off the event loop - #15273

Merged
kodjima33 merged 1 commit into
BasedHardware:mainfrom
singhharsh1708:fix/backend-offload-chat-persist
Sep 21, 2026
Merged

kodjima33 merged 1 commit into
BasedHardware:mainfrom
singhharsh1708:fix/backend-offload-chat-persist

Conversation

@singhharsh1708

@singhharsh1708 singhharsh1708 commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #15270

emit_done_frame ran process_message, and with it up to three sequential Firestore writes, directly on the event loop for every completed chat answer. It is now async def and offloads that one call:

ai_message, ask_for_nps = await run_blocking(db_executor, process_message, response, callback_data)

and its two yields became yield await emit_done_frame(response).

That is the whole change. Only process_message moves to the executor; the message construction, base64 encoding, journey_attempt.finish and record_fallback calls are in-memory and stay where they are. The try/except Exception around the persistence still catches the same failures, because run_blocking re-raises in the awaiting frame, so the fail-open contract in the docstring is unchanged: a failed write still emits an in-memory done: frame and still records persist_outcome = 'exhausted'.

db_executor is the pool this generator already uses at line 607 for sync_user_time_zone_from_client, and yield await ... is the shape it already uses at line 710 for emit_stream_error_fallback.

Tests: backend/tests/unit/test_chat_stream_persist_offload.py, an AST guard. It asserts the generator is still async, that the emitter is async, that process_message is not called directly inside it, that it goes through an awaited run_blocking on db_executor, and that no yield emit_done_frame(...) remains without await, which would yield a coroutine object instead of a frame and silently break the stream.

Verification:

$ cd backend && BACKEND_UNIT_TEST_FILE_LIST=<new file> bash test.sh
5 passed in 0.11s

$ BACKEND_UNIT_TEST_FILE_LIST=<88 chat, message, stream, nps and journey suites> bash test.sh
exit 0, no failures

That selection includes test_chat_stream_error_fallback.py, which exercises the done-frame and fallback paths directly, so the behaviour of this function is covered by existing tests rather than only by the new static guard.

With routers/chat.py reverted to its state on main and the guard kept, 4 of the 5 fail; the one that still passes is that generate_stream is async, which is true on main too.

chat.py does not change line count, so no line-count exception is needed.

Note on overlap: #15207, #15210 and #14970 also touch routers/chat.py, for the picked file name on chat uploads. That is a different function and a different defect; I do not expect a textual conflict, and I will rebase if one lands first.

Product invariants affected

none

Failure class (fixes)

Failure-Class: none

Review in cubic

@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @singhharsh1708 — verified this end to end against the head.

backend/routers/chat.py:

  • emit_done_frame is now async def and its only blocking call is offloaded: await run_blocking(db_executor, process_message, response, callback_data). Both call sites were updated to yield await emit_done_frame(...) (lines 690, 700), and there are no remaining direct process_message calls in the router.
  • The fail-open contract is preserved: run_blocking re-raises in the awaiting frame, so the existing except Exception still catches persistence failures and emits the in-memory done: frame with persist_outcome = 'exhausted'.
  • run_blocking copies contextvars, so the usage context set before streaming still applies to record_app_usage running off-loop.
  • Matches the established shape in the same generator (sync_user_time_zone_from_client offload at line 607, yield await emit_stream_error_fallback(...) at line 710).

backend/tests/unit/test_chat_stream_persist_offload.py: ran the suite locally against the head source — 5/5 pass. The AST guard pins the async emitter, the awaited run_blocking on db_executor, and rejects both a direct process_message call and a bare yield emit_done_frame(...) (which would silently yield a coroutine instead of a frame).

One non-blocking observation: db_executor (max_workers=24) is shared with the other offloads in this router, so under Firestore degradation these persists will queue there instead of stalling the event loop — the right trade for the pod, just worth remembering when reading db-executor queue metrics.

Leaving merge sign-off to the maintainers; note the linked issue #15270 requests a bounty payout, which is a maintainer call.

🤖 Automated review on behalf of the maintainers.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added positive-signal Automation verified a genuine fix/quality contribution backend Backend Task (python) labels Sep 20, 2026

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Offloads the blocking Firestore persistence call (process_message) in emit_done_frame off the event loop via run_blocking on the existing db_executor pool, matching the pattern already used elsewhere in this generator (Fixes #15270). Scoped diff, AST-guard test + existing chat/stream/nps suite passes, CI green. Confidence 5/5.

@kodjima33
kodjima33 merged commit d58438d into BasedHardware:main Sep 21, 2026
51 of 52 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Every chat answer persists to Firestore on the event loop

3 participants