Repository navigation
Finalize pending conversations when a listen session ends inside the retry window - #9960
Conversation
…retry window
LiveConversationController.process_pending defers finalization by 7 seconds, then finalizes
the timed-out conversation and re-dispatches anything still stuck in `processing`. It
currently returns early when that wait is interrupted:
async def process_pending(self, timed_out_id: Optional[str]) -> None:
if await self.host.wait(7):
return
host.wait is wait_for_event(self.state.shutdown_event, seconds) (routers/listen/runtime.py),
which returns True when woken early by shutdown rather than when the sleep elapses
(utils/async_tasks.py). runtime.py then sets shutdown_event and drains background tasks
without cancelling them:
self.state.shutdown_event.set()
await self.task_supervisor.drain_monitored(timeout=self.limits.bg_drain_timeout, cancel=False)
So a listen session that ends within that 7 second window wakes process_pending immediately
with True and it returns, skipping both the timed-out conversation's finalization and the
re-dispatch of conversations stuck in `processing`. The drain deliberately lets background
work finish, so this work should run rather than be dropped.
Before the listen split this was an unconditional sleep (routers/transcribe.py at c7ca348^):
async def process_pending_conversations(timed_out_id: Optional[str]):
await asyncio.sleep(7.0)
if timed_out_id:
await _process_conversation(timed_out_id)
await cleanup_processing_conversations()
The `if await wait(...): return` shape is the polling-loop idiom, and it is correct in
lifecycle_loop, which uses `if await self.host.wait(5): break` to leave a loop.
process_pending is a one-shot deferred action, so an early wake should shorten the wait rather
than cancel the work.
Fix: keep the wait interruptible, drop the early return.
await self.host.wait(7)
Tests (tests/unit/test_listen_process_pending_shutdown.py) subclass LiveConversationController
to record the two finalization calls and drive the real process_pending. The controller takes
only a host, so no patching is required:
- a session woken by shutdown still finalizes the timed-out conversation and re-dispatches processing
- a normal full-delay session behaves exactly as before
- with no timed-out conversation, processing is still re-dispatched
Verification (run in backend/):
- pytest tests/unit/test_listen_process_pending_shutdown.py: 3 passed
- prove-fail: with the source reverted to main, the two shutdown-path tests fail
(assert [] == ['conv-timed-out'] and assert [] == ['conv-a', 'conv-b']) while the
normal-delay test still passes, so the change only affects the interrupted path
- pytest test_conversation_lifecycle_contract.py (13 passed), test_conversation_finalization_jobs.py
(22 passed), test_listen_session_bootstrap.py (4 passed)
- black --line-length 120 --skip-string-normalization --check: clean
- pyright routers/listen/conversations.py: 0 errors
- scripts/check_module_stub_pollution.py: 0 violations
Note: test_listen_persistence.py and test_listen_runtime_regressions.py do not import in my
local environment (deepgram SDK version mismatch, ImportError on DeepgramClientOptions). They
fail identically with this change reverted, so that is a local environment gap rather than a
regression from this PR; CI runs them with the pinned SDK.
I did not exercise a live WebSocket session. The test drives the real process_pending through
the same call the runtime makes.
|
Verified and this looks like a correct, well-scoped fix to a real regression. What I checked against main:
The test design is clean — subclassing the real controller (host-only constructor) to record One heads-up so it doesn't look alarming in the checks: Hygiene, Formatting, and Detect Changes show up as cancelled/skipped on this head — the canonical run (29638398196) has them as skipped (no relevant files changed), and an earlier superseded run had them cancelled. The substantive checks — Backend Unit Tests, Backend Checks, Hermetic Backend E2E, Public Developer API contract — all pass. Recommend merge. Leaving for a human maintainer for the final call since this touches the listen shutdown/finalization path. (This feedback is from an automated maintainer assistant; please use human judgment before merging.) by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with |
kodjima33
left a comment
There was a problem hiding this comment.
backend bug fix (conf 5/5): finalize timed-out conversation when listen session ends inside the 7s window; test
…undaries Conversations from sessions that died before processing sit in in_progress forever, invisible to users (the web app filters to processing/completed). Production data in BasedHardware#9809: ~161 stuck in_progress rows, some months old, several with real transcripts. Session-boundary recovery already re-dispatches stuck processing rows (BasedHardware#9960) but never looked at in_progress. process_pending now also routes orphaned in_progress conversations through process_conversation — the exact call a live timeout makes: content goes through the durable finalization seam, empty rows are deleted. Orphanhood is proven by idle time: any live session refreshes finished_at continuously and processes an idle conversation within the ~2-minute conversation timeout, so an hour of silence means no session owns the row, including on another device. The session's own current conversation is excluded explicitly. The fetch is an equality-only status query (no new index) with the age cut client-side, oldest-first and bounded to 10 per session so a large backlog spreads across sessions instead of stampeding the pipeline. Covers the in_progress bucket of BasedHardware#9809; stuck processing rows are already re-dispatched here, and merging/failed recovery plus a server-side sweep for users who never reconnect are named follow-ups. Failure-Class: none Co-Authored-By: Claude Fable 5 <[email protected]>
…undaries Conversations from sessions that died before processing sit in in_progress forever, invisible to users (the web app filters to processing/completed). Production data in BasedHardware#9809: ~161 stuck in_progress rows, some months old, several with real transcripts. Session-boundary recovery already re-dispatches stuck processing rows (BasedHardware#9960) but never looked at in_progress. process_pending now also routes orphaned in_progress conversations through process_conversation — the exact call a live timeout makes: content goes through the durable finalization seam, empty rows are deleted. Orphanhood is proven by idle time: any live session refreshes finished_at continuously and processes an idle conversation within the ~2-minute conversation timeout, so an hour of silence means no session owns the row, including on another device. The session's own current conversation is excluded explicitly. The fetch is an equality-only status query (no new index) with the age cut client-side, oldest-first and bounded to 10 per session so a large backlog spreads across sessions instead of stampeding the pipeline. Covers the in_progress bucket of BasedHardware#9809; stuck processing rows are already re-dispatched here, and merging/failed recovery plus a server-side sweep for users who never reconnect are named follow-ups. Failure-Class: none Co-Authored-By: Claude Fable 5 <[email protected]>
…undaries Conversations from sessions that died before processing sit in in_progress forever, invisible to users (the web app filters to processing/completed). Production data in BasedHardware#9809: ~161 stuck in_progress rows, some months old, several with real transcripts. Session-boundary recovery already re-dispatches stuck processing rows (BasedHardware#9960) but never looked at in_progress. process_pending now also routes orphaned in_progress conversations through process_conversation — the exact call a live timeout makes: content goes through the durable finalization seam, empty rows are deleted. Orphanhood is proven by idle time: any live session refreshes finished_at continuously and processes an idle conversation within the ~2-minute conversation timeout, so an hour of silence means no session owns the row, including on another device. The session's own current conversation is excluded explicitly. The fetch is an equality-only status query (no new index) with the age cut client-side, oldest-first and bounded to 10 per session so a large backlog spreads across sessions instead of stampeding the pipeline. Covers the in_progress bucket of BasedHardware#9809; stuck processing rows are already re-dispatched here, and merging/failed recovery plus a server-side sweep for users who never reconnect are named follow-ups. Failure-Class: none Co-Authored-By: Claude Fable 5 <[email protected]>
…undaries (#10060) * fix(listen): recover orphaned in_progress conversations at session boundaries Conversations from sessions that died before processing sit in in_progress forever, invisible to users (the web app filters to processing/completed). Production data in #9809: ~161 stuck in_progress rows, some months old, several with real transcripts. Session-boundary recovery already re-dispatches stuck processing rows (#9960) but never looked at in_progress. process_pending now also routes orphaned in_progress conversations through process_conversation — the exact call a live timeout makes: content goes through the durable finalization seam, empty rows are deleted. Orphanhood is proven by idle time: any live session refreshes finished_at continuously and processes an idle conversation within the ~2-minute conversation timeout, so an hour of silence means no session owns the row, including on another device. The session's own current conversation is excluded explicitly. The fetch is an equality-only status query (no new index) with the age cut client-side, oldest-first and bounded to 10 per session so a large backlog spreads across sessions instead of stampeding the pipeline. Covers the in_progress bucket of #9809; stuck processing rows are already re-dispatched here, and merging/failed recovery plus a server-side sweep for users who never reconnect are named follow-ups. Failure-Class: none Co-Authored-By: Claude Fable 5 <[email protected]> * Merge origin/main; raise conversations.py baseline for the #9809 orphan selection * test(listen): prove orphaned in_progress recovery end to end in the stack gauntlet New cloud-orphan-recovery scenario in the listen-pusher gauntlet: seed an in_progress row no session owns (2h idle, content intact — production orphans predate any single cause, so the row is seeded directly while the recovery session itself runs the real listener), open a real session, and prove its process_pending pass admits the orphan into a durable finalization job, the loopback Cloud Tasks delivery completes it through the real worker, and the conversation lands completed with content. The session stays open while waiting: process_pending is a finite task started at session begin with a built-in 7s delay, and teardown cancels finite tasks — closing immediately is exactly how the scenario first failed. Verification: full gauntlet (all six suites) passed locally against real backend/pusher/worker processes, Firestore emulator, Redis, and the strict loopback Cloud Tasks client. On pre-fix code the scenario fails by construction: no recovery pass exists, so the orphan's job admission times out. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(listen): ratchet recovery gauntlet baseline Failure-Class: none * fix(listen): deterministically recover oldest orphaned turns Failure-Class: none * fix(listen): register the #9809 orphan-recovery query and its index The #9809 in-progress recovery query (status == in_progress ordered by finished_at) was added with its composite index hand-written directly into the generated firestore.indexes.json and no entry in the query registry. Two gates rejected it: firestore-index-manifest (the manifest no longer matched its generator) and firestore-query-coverage (new unregistered serving compound shape 3b69cd3fc6dded3d). Regenerating the manifest alone would have silently deleted the index and left the production query failing closed with FailedPrecondition. Register the shape instead and build the read path from it: - add STALE_IN_PROGRESS_CONVERSATIONS_QUERY to the index registry, which both builds the query and declares the status/finished_at composite - get_stale_in_progress_conversations now builds via the spec rather than an inline where() chain - firestore.indexes.json regenerated from the registry; the index is now derived rather than hand-maintained - extend the manifest contract test to pin the new tail index and assert the spec is classified registered - raise the conversations.py ratchet baseline 1704 -> 1708 Failure-Class: FC-undeclared-serving-query-index Verification: - backend/scripts/firestore_query_coverage.py --check-ratchet: exit 0 - backend/scripts/generate_firestore_indexes.py: manifest matches registry - pytest tests/unit/test_firestore_query_contract.py tests/unit/test_listen_process_pending_shutdown.py: 31 passed * test(backend): derive the provisioning argv from the manifest tail test_provision_missing_uses_gcloud_with_every_manifest_field_and_waits_for_ready picks its target index dynamically (manifest['indexes'][-1]) but asserted a hardcoded argv for task_attention_overrides, the index that happened to sit at the tail when the test was written. Appending the #9809 conversations index in e22748a moved the tail, so the expected gcloud command no longer described the index the test actually provisions and the Backend unit suite failed. Assert against the target the test already computes instead of a frozen copy: - collection-group and field-config count derive from `target` - the full argv is compared to gcloud_create_index_command(), the same helper reconcile() calls, so the expectation tracks production rather than restating it - the subcommand prefix, --quiet terminator, and the no-firebase-CLI check keep their independent literal assertions Any future manifest append now leaves this test passing without an edit. Verification: - cd backend && OMI_ENV_STAGE=offline PROVIDER_MODE=offline \ BACKEND_UNIT_TEST_FILE_LIST=<list> bash test.sh: exit 0 (test_reconcile_firestore_indexes.py 29 passed, test_firestore_query_contract.py 22 passed 2 deselected, test_listen_process_pending_shutdown.py 7 passed) - tail-independence proved by temporarily reordering QUERY_SPECS so ACTIVE_ATTENTION_OVERRIDE_QUERY became the tail and regenerating the manifest: 29 passed unchanged; registry and manifest restored after - black --line-length=120 --skip-string-normalization: unchanged --------- Co-authored-by: Claude Fable 5 <[email protected]> Co-authored-by: Max Carter 祁明思 <[email protected]>
Finalize pending conversations when a listen session ends inside the retry window
LiveConversationController.process_pending defers finalization by 7 seconds, then finalizes
the timed-out conversation and re-dispatches anything still stuck in
processing. Itcurrently returns early when that wait is interrupted:
host.wait is wait_for_event(self.state.shutdown_event, seconds) (routers/listen/runtime.py),
which returns True when woken early by shutdown rather than when the sleep elapses
(utils/async_tasks.py). runtime.py then sets shutdown_event and drains background tasks
without cancelling them:
So a listen session that ends within that 7 second window wakes process_pending immediately
with True and it returns, skipping both the timed-out conversation's finalization and the
re-dispatch of conversations stuck in
processing. The drain deliberately lets backgroundwork finish, so this work should run rather than be dropped.
Before the listen split this was an unconditional sleep (routers/transcribe.py at c7ca348^):
The
if await wait(...): returnshape is the polling-loop idiom, and it is correct inlifecycle_loop, which uses
if await self.host.wait(5): breakto leave a loop.process_pending is a one-shot deferred action, so an early wake should shorten the wait rather
than cancel the work.
Fix: keep the wait interruptible, drop the early return.
Tests (tests/unit/test_listen_process_pending_shutdown.py) subclass LiveConversationController
to record the two finalization calls and drive the real process_pending. The controller takes
only a host, so no patching is required:
Verification (run in backend/):
(assert [] == ['conv-timed-out'] and assert [] == ['conv-a', 'conv-b']) while the
normal-delay test still passes, so the change only affects the interrupted path
(22 passed), test_listen_session_bootstrap.py (4 passed)
Note: test_listen_persistence.py and test_listen_runtime_regressions.py do not import in my
local environment (deepgram SDK version mismatch, ImportError on DeepgramClientOptions). They
fail identically with this change reverted, so that is a local environment gap rather than a
regression from this PR; CI runs them with the pinned SDK.
I did not exercise a live WebSocket session. The test drives the real process_pending through
the same call the runtime makes.