Skip to content

Finalize pending conversations when a listen session ends inside the retry window - #9960

Merged
kodjima33 merged 1 commit into
BasedHardware:mainfrom
ZachL111:zach/listen-finalize-on-early-shutdown
Jul 18, 2026
Merged

kodjima33 merged 1 commit into
BasedHardware:mainfrom
ZachL111:zach/listen-finalize-on-early-shutdown

Conversation

@ZachL111

@ZachL111 ZachL111 commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

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. 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.

Review in cubic

…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.
@Git-on-my-level

Copy link
Copy Markdown
Member

Verified and this looks like a correct, well-scoped fix to a real regression.

What I checked against main:

  • host.wait is wait_for_event(shutdown_event, seconds) and returns True on early wake (utils/async_tasks.py) — so the current if await self.host.wait(7): return really does drop the work when the session ends inside the window.
  • runtime.py sets shutdown_event then calls drain_monitored(..., cancel=False) — i.e. background work is expected to finish during drain, which is exactly what this PR re-enables.
  • process_pending is launched as a one-shot finite task (pending_convos), so the early-return is indeed wrong here; the if ...: break form belongs to lifecycle_loop, not this path.
  • The pre-split unconditional asyncio.sleep(7.0) claim is consistent with the behavior you're restoring.

The test design is clean — subclassing the real controller (host-only constructor) to record process_conversation / schedule_finalization, no monkey-patching. I reproduced the three cases independently; reverting only the interrupted path makes the two shutdown cases fail exactly as you described in the prove-fail note, and the normal-delay case is unchanged.

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 need human response.

@Git-on-my-level Git-on-my-level added the bug Something isn't working label Jul 18, 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.

backend bug fix (conf 5/5): finalize timed-out conversation when listen session ends inside the 7s window; test

@kodjima33
kodjima33 merged commit 39debda into BasedHardware:main Jul 18, 2026
32 of 35 checks passed
aryanorastar added a commit to aryanorastar/omi that referenced this pull request Jul 23, 2026
…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]>
aryanorastar added a commit to aryanorastar/omi that referenced this pull request Jul 24, 2026
…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]>
aryanorastar added a commit to aryanorastar/omi that referenced this pull request Jul 26, 2026
…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]>
kodjima33 pushed a commit that referenced this pull request Jul 30, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants