Skip to content

fix(listen): recover orphaned in_progress conversations at session boundaries - #10060

Merged
kodjima33 merged 8 commits into
BasedHardware:mainfrom
aryanorastar:fix/9809-recover-stale-in-progress
Jul 30, 2026
Merged

kodjima33 merged 8 commits into
BasedHardware:mainfrom
aryanorastar:fix/9809-recover-stale-in-progress

Conversation

@aryanorastar

@aryanorastar aryanorastar commented Jul 19, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • process_pending (the session-boundary recovery pass that already re-dispatches stuck processing conversations, Finalize pending conversations when a listen session ends inside the retry window #9960) now also recovers orphaned in_progress conversations — the largest stuck bucket in Bug: conversations get stuck in processing states and never finalize #9809 (~161 rows in production, some months old, several with real transcripts, all invisible to users because the web app filters to processing,completed).
  • Recovery routes each orphan through process_conversation — the exact call a live conversation timeout makes: content goes through the durable finalization job seam; empty rows are deleted by delete_empty_recording_conversation. No new recovery mechanism, no new state.
  • Orphanhood is proven by idle time, not status alone: any live session refreshes finished_at on every segment and its lifecycle loop processes an idle conversation within the ~2-minute conversation timeout, so an hour of silence means no session owns the row — including a session on another device. The session's own current conversation is excluded explicitly.
  • The fetch is an equality-only status query (no composite index, no firestore.indexes.json change), age-cut client-side on a bounded read, oldest-first, capped at 10 per session so a large backlog spreads across reconnects instead of fanning dozens of LLM finalizations out of one.

Addresses the in_progress bucket of #9809.

Root cause

A listen session that dies between conversation creation and finalization leaves the row in_progress with no automatic owner: the lifecycle loop only watches the current conversation, process_pending only re-dispatched processing, and the durable-job reconciler only replays rows that already have a finalization job. A recovery path does exist — POST /v1/conversations (the app's force-processing action) falls back to get_in_progress_conversation, a status query — but it is user-initiated only and limit(1) newest-first, so an orphan behind a newer in_progress row never qualifies, and a user who never taps force-processing never triggers it. (Corrected from an earlier version of this description that overstated this as "nothing ever asked" — thanks to beastoin for the push-back.) The manual /v1/conversations/{id}/finalize workaround in #9809 proves the content is intact and the pipeline works when asked.

Failure class

Failure-Class: none

No registered class on main covers this. The honest classification is FC-session-scoped-durable-work — the class #10044 proposes (durable work must not silently share the fate of the session that dispatched it; this instance is the admission-side gap, where the session died before durable finalization intent existed). If #10044 lands first, I'll update this declaration to cite it.

Durable guard

  • Recovery reuses the two existing owner seams (process_conversation → durable finalization intent / empty-row deletion) rather than adding a parallel path; the revision-fenced create_or_get_finalization_intent makes re-recovery idempotent.
  • select_stale_in_progress is a pure decision function (age proof, missing/bad finished_at excluded as unprovable, oldest-first, bounded) with direct tests.
  • Named follow-ups, deliberately out of scope: merging/failed recovery (different machinery — reprocess is an inline LLM call), and a server-side sweep for users who never open another session (needs a cross-user collection-group index and spend controls; belongs with the monitoring contract in [P1] Make monitoring delivery and telemetry coverage an explicit production contract #9587).

Product invariants affected

none (verified with scripts/pr-preflight --suggest)

Validation

  • Old-code regression check (controller change stashed): pytest tests/unit/test_listen_process_pending_shutdown.py → 2 failed (orphans never recovered); new code → 6 passed.
  • Related suites: pytest tests/unit/test_listen_process_pending_shutdown.py tests/unit/test_lazy_conversation_processing.py tests/unit/test_listen_fallback_removal.py → 36 passed.
  • Tests execute the real process_pending/recover_stale_in_progress through the same host seam Finalize pending conversations when a listen session ends inside the retry window #9960's regression tests established (no patching, no sys.modules mutation), plus direct tests on select_stale_in_progress covering the age filter, unprovable-clock exclusion, ordering, and the batch bound.
  • make preflight (local lane, this PR body) → all selected checks pass.
  • black --line-length 120 --skip-string-normalization clean on the three changed files.
  • Live local stack e2e: new cloud-orphan-recovery scenario in the listen-pusher gauntlet (backend/testing/listen_pusher_stack/run.sh) — a seeded 2h-idle orphan row, a real listen session, real backend/pusher/finalization-worker processes, Firestore emulator, Redis, loopback Cloud Tasks. The session-boundary pass admits the orphan into a durable finalization job, the worker completes it, and the row lands completed with content. Full gauntlet (all six suites) passed locally. On pre-fix code the scenario fails by construction (no recovery pass exists; job admission times out).

Not exercised live: a real device session against production Firestore (no credentials in this environment). The recovery path from process_conversation down is the same code every live conversation timeout already exercises in production; this PR only adds the orphan selection in front of it.

Review in cubic

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@Git-on-my-level Git-on-my-level added needs-maintainer-review Needs a human maintainer to sign off before merge security-review Touches auth, provider routing, secrets, or security-sensitive surfaces labels Jul 20, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks for the careful write-up and tests here. This looks like the right recovery shape to me: stale in_progress rows are selected conservatively, the session's current conversation is explicitly skipped, and recovered rows are sent back through the existing process_conversation / durable finalization path instead of adding a second finalization mechanism.

I verified the focused regression suite locally on the PR head:

OMI_ENV_STAGE=offline PROVIDER_MODE=offline uv run pytest tests/unit/test_listen_process_pending_shutdown.py -q → 6 passed.

Because this touches listen-session recovery for user conversation data and can dispatch finalization work, I’m not formally approving it from automation. A human maintainer should still review the operational assumptions before merge, especially that the 1-hour stale threshold and bounded status == in_progress read are appropriate for the current production backlog and expected future backlog size. No code changes requested from my side.


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

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Thanks @Git-on-my-level. Some concrete numbers on the two operational questions, for whoever does the human pass:

Bounded read vs backlog size: the query is capped at .limit(200) documents, read once per listen session inside process_pending (so at most one bounded read per session start, after the existing processing re-dispatch read). The worst per-user backlog observed in #9809 is ~161 in_progress rows — inside the cap. Typical users hold 0–2 rows, so steady-state read amplification is negligible (relevant to the concerns in #9889). If a user ever exceeds 200 stuck rows, recovery still converges: each session drains up to 10 oldest rows, shrinking the set the next read sees.

1-hour threshold: any session that owns an in_progress row refreshes finished_at on every transcript segment, and its lifecycle loop force-processes an idle conversation at the ~120s conversation timeout. One hour is therefore ~30× the longest a legitimately-owned row can sit idle, including a session on another device. Rows with a missing or non-datetime finished_at are excluded as unprovable rather than recovered.

Drain rate: ≤10 recoveries per session start, oldest first, means the reported 161-row backlog clears over ~17 sessions for that user — spread out by design so one reconnect never fans out dozens of LLM finalizations. The manual /v1/conversations/{id}/finalize route remains available for anyone who wants their backlog cleared immediately.

Happy to adjust the threshold or the caps if the maintainer pass prefers different numbers — both are single constants (STALE_IN_PROGRESS_RECOVERY_AGE_SECONDS, STALE_IN_PROGRESS_RECOVERY_BATCH).

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

Reviewed by automated PR reviewer — approving; holding merge (see notes).

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Fixed the failing PR Metadata Preflight: main's ratchet baseline for database/conversations.py moved under this PR (now 1580 on main); raised to the exact post-change count (1616) with justification and merged current main. Local preflight 21/21 green, recovery suite still 6/6. Ready when you are @kodjima33.

@Git-on-my-level

Copy link
Copy Markdown
Member

Re-reviewed the current head (8b108d5) after the ratchet-baseline update. I still don’t see a code-level blocker in the recovery path: the new stale in_progress selection is conservative, skips the live session’s current conversation, and routes recovery through the existing process_conversation / durable finalization seam rather than inventing a parallel processor.

Verification I ran locally on this head with secrets stripped/offline mode:

OMI_ENV_STAGE=offline PROVIDER_MODE=offline .venv/bin/pytest tests/unit/test_listen_process_pending_shutdown.py -q → 6 passed.

I also reproduced the two files named by the current Backend unit suite failure via test.sh; those failures are in tests/unit/test_ws_b_short_term_lifecycle.py validation paths and a test_desktop_transcribe.py duration guard, not in the listen recovery test added here. I’m therefore not requesting PR changes from the listen recovery diff itself.

Keeping this as human-maintainer review rather than automation approval because it touches user conversation recovery and can dispatch finalization jobs. The maintainer pass should still sign off on the operational caps/thresholds (3600s, 10 per session, bounded status == in_progress read) before merge.


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

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

@Git-on-my-level @undivisible This PR is fully approved. I've pushed a fix for the pre-existing Backend unit suite timebomb that was failing CI (the short-term lifecycle tests hardcoded June 20, 2026 and hit +30 days expiry validation failures today). CI should be green shortly. Could you please merge when you have a chance?

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Thanks for the re-review. The operational caps are all single constants for easy adjustment: STALE_IN_PROGRESS_RECOVERY_AGE_SECONDS = 3600, STALE_IN_PROGRESS_RECOVERY_BATCH = 10, and the equality-only status == in_progress read. Happy to tune any of them if the maintainer pass prefers different numbers.

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

@kodjima33 approved and green. The operational caps flagged for the human pass are all single constants for easy tuning — STALE_IN_PROGRESS_RECOVERY_AGE_SECONDS = 3600, STALE_IN_PROGRESS_RECOVERY_BATCH = 10, and the equality-only status == in_progress read. Happy to adjust any, but nothing's blocking. Ready to merge when you lift the hold.

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

@Git-on-my-level need human response — requesting David's merge sign-off. Approved by @kodjima33, all checks green, no conflicts. The item flagged for a human is the operational caps on orphan recovery — all single constants (STALE_IN_PROGRESS_RECOVERY_AGE_SECONDS = 3600, STALE_IN_PROGRESS_RECOVERY_BATCH = 10), trivially adjustable. Ready to merge.

@aryanorastar
aryanorastar force-pushed the fix/9809-recover-stale-in-progress branch from 0fea84c to f69b82b Compare July 23, 2026 12:49
@Git-on-my-level

Copy link
Copy Markdown
Member

Reviewed the current head (f69b82b) after the added listen-pusher stack gauntlet coverage. I still don’t see a code-level blocker in the recovery path: stale in_progress candidates are selected conservatively, the live session’s current conversation is skipped, and recovered rows go through the existing process_conversation / durable finalization path rather than a parallel processor.

Verification:

OMI_ENV_STAGE=offline PROVIDER_MODE=offline .venv/bin/pytest tests/unit/test_listen_process_pending_shutdown.py -q → 6 passed locally.

I also attempted the listen-pusher stack gauntlet locally, but this runner only has the wrong Java for the Firestore emulator (run.sh requires Java 21). The PR’s current CI did run that gauntlet and Listen Pusher Stack Gauntlet passed. The current failing Hermetic Backend E2E is in test_canonical_memory_pipeline.py’s memory surface matrix, not in the listen recovery path touched here.

No code changes requested from my side. I’m still not formally approving from automation because this touches user conversation-data recovery and can enqueue finalization jobs; a human maintainer should sign off on the operational constants (3600s stale age, 10 recoveries per session, bounded status == in_progress read) before merge.


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

aryanorastar and others added 3 commits July 26, 2026 21:59
…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]>
…tack 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]>
@aryanorastar
aryanorastar force-pushed the fix/9809-recover-stale-in-progress branch from 5225d14 to 4056cee Compare July 26, 2026 16:31

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the continued updates here. The listen recovery path itself still looks sound to me, and I re-ran the focused regression locally on the current head:

cd backend && OMI_ENV_STAGE=offline PROVIDER_MODE=offline .venv/bin/pytest tests/unit/test_listen_process_pending_shutdown.py -q → 6 passed.

However, I do need to request changes for the current head because the required Hygiene check is failing in product-file-line-count-ratchet:

backend/testing/listen_pusher_stack/run.py: grew from baseline 1711 to 1790 lines. Split the file, or raise its exact baseline with a one-line justification in .github/scripts/product_file_line_count_ratchet_baseline/backend-other.json.

Given this PR intentionally adds the cloud-orphan-recovery stack scenario, updating that ratchet baseline with a narrow justification may be the smallest fix, unless you prefer to split the gauntlet helper/scenario out. Once Hygiene is green again, the remaining sign-off is still the human maintainer call on the operational recovery constants (3600s stale age, 10 per session, bounded status == in_progress read) because this touches user conversation recovery and can enqueue finalization jobs.


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

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

Recovering orphaned in_progress conversations at session boundaries reads correct; holding the merge only because the branch has conflicts with main.

@Git-on-my-level
Git-on-my-level dismissed their stale review July 27, 2026 21:21

Resolved on current head a2d4546: backend/testing/listen_pusher_stack/run.py ratchet baseline is raised with a narrow #9809 justification and required checks are green. Dismissing only this automation-authored stale request-changes review.

Resolve line-count ratchet baseline conflicts by taking origin/main's
shards and re-applying only the BasedHardware#9809 raises:

- backend/database/conversations.py 1667 -> 1704 (+37)
- backend/testing/listen_pusher_stack/run.py 1711 -> 1790 (+79)

main had independently rewritten both raise_justifications, so its text
is preserved and the BasedHardware#9809 clause appended rather than overwriting.
Stale HEAD entries dropped in favour of main's current values
(validate-backend-runtime-env.py 1836, users.py 2046,
memory_apply_store.py 1912).

Verification:
- check_product_file_line_count_ratchet.py --base origin/main: OK, no
  line-count increase across 3 changed product source files
- pytest tests/unit/test_listen_process_pending_shutdown.py: 7 passed
…d its index

The BasedHardware#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
@Git-on-my-level Git-on-my-level added the needs-tests PR introduces logic that should be covered by tests label Jul 29, 2026

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the update registering the conversations_in_progress_by_finished_at Firestore index. The recovery path itself still looks directionally sound, but the current head has a PR-caused required-test failure that needs to be fixed before merge.

I reproduced the failure locally with the CI runner contract:

cd backend && OMI_ENV_STAGE=offline PROVIDER_MODE=offline BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-pr10060-tests.txt bash test.sh

The focused recovery tests pass, but tests/unit/test_reconcile_firestore_indexes.py::test_provision_missing_uses_gcloud_with_every_manifest_field_and_waits_for_ready still hard-codes the old last manifest index (task_attention_overrides). Since this PR appends the new conversations index, that test now expects the wrong gcloud firestore indexes composite create ... command and the Backend unit suite fails. Please update that reconcile-index provisioning test/fixture to match the new generated manifest behavior (or make it robust to whichever target index it selects) and rerun the failed file through test.sh.

I’m keeping the human-maintainer hold for the operational recovery constants as before (3600s stale age, batch 10, and the bounded ordered status == in_progress read), and I’m not requesting changes to the core listen recovery logic beyond the failing test contract.


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

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 BasedHardware#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

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

Recovers orphaned in_progress conversations (#9809) through the existing finalization seam — bounded, oldest-first, tests + index registered.

@kodjima33
kodjima33 merged commit ea7acf5 into BasedHardware:main Jul 30, 2026
31 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-maintainer-review Needs a human maintainer to sign off before merge needs-tests PR introduces logic that should be covered by tests security-review Touches auth, provider routing, secrets, or security-sensitive surfaces

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants