Skip to content

backend: make listen conversation lifecycle durable - #9700

Merged
Git-on-my-level merged 23 commits into
BasedHardware:mainfrom
Git-on-my-level:codex/durable-listen-lifecycle
Jul 14, 2026
Merged

Git-on-my-level merged 23 commits into
BasedHardware:mainfrom
Git-on-my-level:codex/durable-listen-lifecycle

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Jul 14, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #9687
Closes #9516
Closes #9351

This is the one-PR landing requested by #9687. It deliberately supersedes #9516's earlier two-PR landing sequence while retaining the tests-before-refactor contract as strict commit order:

  1. 66f13d02f / a825ffbbd characterize current admission behavior and add the deterministic finalization-decision ordering fuzzer against unmodified production writes.
  2. 513e25f04 centralizes lifecycle mutation ownership and registers the lifecycle-write static guard in the deterministic checks manifest.
  3. 2ea541143 persists durable recording sessions and routes all session lifecycle operations through that service.
  4. d0347f2ad / c2529047f / 8f42b84f0 / 0d8f8e9c9 / 8e8fbc7d0 / 8a18d57fe / 166cd7d34 / b82e6b568 / 6fbb8a5ad / 3443cd43f / ffd55aa95 / 9040edec6 / a435d3746 / 321f9161b / 89e0855 close the independent-review race, fanout, rollover, dual-write, envelope-isolation, static-guard, isolation-boundary, fenced-job, atomic fanout-admission, deleted-row, mismatch-envelope, create-vs-processor-write, fenced-completion-signal, legacy-admission-leak, post-fanout deletion-replay, discarded-reconnect, empty-session tombstone-reuse, post-persistence legacy fanout, late-content cleanup, photo-only finalization, and lifecycle-storage API boundary findings without weakening the three phases above.

Failure-class closure

Failure class Root cause Durable guard and recurrence evidence
Plural mutation authority Routers, pusher, finalizers, and storage helpers could independently write lifecycle fields or conflate an initial create with a stale processor update. 513e25f04 creates the exclusive lifecycle service; the manifest-enforced AST guard rejects direct lifecycle writes, including generic DB and Firestore transaction forms. c2529047f hardens the checker with bypass regressions. 6fbb8a5ad separates explicit idempotent initial creation from fail-closed processing-result persistence. 89e0855 exposes the storage primitives only as the lifecycle service’s guard-tracked boundary, so strict type checking rejects neither an intentional private escape nor a second owner.
Disconnect finalization races Late disconnects, stale processors, or a concurrent deletion could re-admit, overwrite, resurrect, or falsely report completion for a terminal conversation. a825ffbbd supplies the ordering fuzzer; c2529047f evaluates its reducer on the transaction snapshot and fences processing/terminal writes with CAS contracts. 8e8fbc7d0 preserves the transaction result through write preparation, and 8a18d57fe moves durable acceptance ahead of all derived writes. b82e6b568 makes a missing row a fail-closed no-resurrection fence, including the initial finalizer read. 3443cd43f preserves terminal fenced through the pusher protocol so a listener retires the request without issuing a false completed envelope. a435d3746 also reports a later core-persistence fence back to each legacy endpoint before it can trigger direct integrations.
Identity and binding drift Redis/global in-progress pointers and reconnects were not a durable recording identity. 2ea541143 introduces immutable (uid, recording_session_id) bindings and ordered envelopes; d0347f2ad adds rollover generations, terminal immutability, delayed completion routing, and 0d8f8e9c9 keeps a dual-write legacy route from borrowing the canonical envelope. b82e6b568 ensures that same legacy route keeps delivering processing/completed envelopes on a dual-write mapping conflict, while the canonical binding remains untouched. 8e8fbc7d0 immediately rolls a terminal reconnect before it can accept audio. ffd55aa95 suppresses a discarded terminal reconnect rather than replaying it as completed. 9040edec6 tombstones an empty session before deleting its row, and any missing bound row forces a fresh recording generation instead of recreating the old conversation ID.
Teardown and fanout edges A lease could expire between conversation completion and external integration fanout, while an empty cleanup could race with late segments or photos. d0347f2ad persists a fenced fanout state and stable idempotency key on the finalization job, so replay completes the same fanout boundary before job completion. 8a18d57fe adds an explicit, lease-fenced terminal no-fanout job disposition for a discarded or superseded processor. 166cd7d34 moves the conversation’s completed, non-discarded, job-id, and revision checks into the claim transaction itself; interleaving regressions cover both discard and newer-binding fences. 3443cd43f gives the legacy finalization endpoint the same fail-closed admission branch, returning its durable winner before processor or integration side effects. ffd55aa95 recognizes a durable fanout acknowledgement before fencing a deleted-row replay, allowing the worker to atomically finish without a duplicate delivery. a435d3746 atomically tombstones/deletes only an empty parent while segment and photo writes share the parent transaction and set has_content; a late writer wins the retry and routes durable finalization instead of losing content. 321f9161b admits that durable marker so a photo-only conversation reaches its finalization job.

Child closure criteria

  • refactor(backend): converge conversation lifecycle onto a single mutation owner #9516: one lifecycle mutation authority owns initial creation, admission, transitions, discard protection, and terminal processing; raw lifecycle writes are prevented by a CI-manifest static contract and runtime regressions cover late failed/discarded/deleted finalization plus fresh direct/deferred creation. The legacy endpoints also observe a core persistence refusal and return the durable row without integration fanout.
  • Introduce durable recording sessions for listen lifecycle #9351: a recording session now owns immutable conversation binding plus ordered lifecycle envelopes; reconnect retries return the canonical binding, silence rollover starts a new generation, terminal phases cannot change, and shadow/dual-write/enforce provide a compatibility ramp. An empty generation is terminally tombstoned before deletion; reconnecting a missing bound row starts a new recording/conversation ID, never recreates the tombstoned generation. Cleanup and segment/photo writes share a parent transaction, so late content cancels cleanup and follows durable finalization. Dual-write preserves the legacy route on a mismatch without emitting the canonical envelope for a different conversation, while still delivering its processing/completed compatibility envelopes.
  • Epic: durable listen→conversation lifecycle — single mutation owner + durable recording sessions (parent of #9516, #9351) #9687: every finalization handoff is transactionally admitted, lease-fenced, replayable, and only marked complete after idempotency-keyed external fanout completes. A lost fanout race or deleted row is atomically recorded as terminal fenced, except a previously acknowledged fanout is normally completed on deletion replay; neither case can duplicate integration, retry forever, dead-letter, or emit a false listener-completed transition. Both finalization endpoints return the durable winner before derived side effects, including when core persistence loses its later fence.

Shipped #9516 ownership matrix

Concern Exclusive owner Drivers/projections
Status transitions and claims utils.conversations.lifecycle transcribe, pusher, sync/import/router/merge paths submit intents or read state
Processing admission utils.conversations.lifecycle.admit_processing live finalization, pusher, imports, manual router and merge paths
Finalization, merge, and reprocess handoff utils.conversations.lifecycle durable finalization worker and postprocess stages
Content fields Existing narrow/generic content writes title, starred, events, integrations, audio metadata, and other non-lifecycle content

The static guard scans production backend sources with a zero baseline and rejects both the lifecycle persistence primitives and generic/raw writes of lifecycle fields outside the exclusive owner. Its self-tests include pasted-back direct, anonymized Firestore, generic-API, and finalization-admission escape hatches.

Scope fence

#9355 (sync change feed) is explicitly excluded. It has a separate data/rollback plan and must land independently; this PR neither changes its feed protocol nor relies on it for lifecycle correctness.

Verification

  • cd backend && PYTHON=.venv/bin/python bash test-preflight.sh — 18 checks passed, 0 failed (the remaining optional integration-provider/service checks are warnings only).
  • cd backend && ./test.sh — 584 backend unit-test files passed after the final review-fix commit.
  • cd backend && .venv/bin/python -m pytest tests/unit/test_conversation_finalization_jobs.py tests/unit/test_listen_finalization_cloud_tasks.py tests/unit/utils/test_listen_pusher_session.py tests/unit/test_conversation_search_date_validation.py -q — 77 targeted finalization, protocol, and legacy-admission tests passed after 3443cd43f.
  • cd backend && .venv/bin/python -m pytest tests/unit/test_transcribe_decisions.py tests/unit/test_listen_finalization_cloud_tasks.py -q — 63 reconnect and finalization-replay tests passed after ffd55aa95.
  • cd backend && .venv/bin/python -m pytest tests/unit/test_recording_sessions.py -q — 22 durable binding/tombstone tests passed after 9040edec6, including empty-session deletion and reconnect rollover.
  • cd backend && .venv/bin/python -m pytest tests/unit/test_conversation_finalization_jobs.py tests/unit/test_recording_sessions.py tests/unit/test_conversation_search_date_validation.py tests/unit/test_process_conversation_usage_context.py tests/unit/test_transcribe_conversation_cache.py -q — 92 targeted lifecycle and legacy-route tests passed after 321f9161b, including photo-only finalization admission, persistence-fence fanout suppression, and late-content empty-cleanup races.
  • cd backend && .venv/bin/python -m pytest tests/unit/test_conversation_lifecycle_contract.py tests/unit/test_process_conversation_usage_context.py tests/unit/test_developer_from_segments_idempotency.py tests/unit/test_listen_finalization_cloud_tasks.py tests/unit/test_recording_sessions.py -q — 91 lifecycle contracts passed, including deleted-row fencing, no derived work, terminal finalization, dual-write compatibility, and fresh/deferred creation.
  • cd backend && bash scripts/typecheck.sh — 0 errors (existing strict-Pyright warnings only) after 89e0855.
  • make preflight — deterministic manifest checks passed (existing architecture warnings only).
  • cd desktop/macos && xcrun swift build -c debug --package-path Desktop — passed.
  • cd desktop/macos && xcrun swift test --package-path Desktop --filter StopReconciliationTests — 40 tests passed.
  • Built and launched named test bundle omi-durable-recording-sessions through ./run.sh --yolo; the non-production automation bridge responded. The seeded named bundle was signed out, so no authenticated live listen session was available; durable lifecycle behavior is exercised by the backend contracts and fuzzer above.

The finalization fuzzer runs four checked-in named edge corpus sequences plus 250 seeded randomized sequences (1–32 events each) on every test run. The default seed is OMI_FUZZ_SEED=9687; failures preserve the seed through the environment variable for deterministic replay.

Invariants

No product invariants affected (scripts/pr-preflight --suggest).

Review in cubic

@Git-on-my-level

Copy link
Copy Markdown
Member Author

Monitor run summary

Fixed 5 hermetic backend E2E test failures caused by the lifecycle guard introduced in this PR.

Root cause: The lifecycle guard in update_conversation blocks direct writes to lifecycle fields (status, discarded). This broke:

  1. Reprocessing completed conversations — persist_processed_conversation only accepted existing status in {processing, merging}, fencing out reprocess over already-completed conversations.
  2. E2E test fakes — fake process_conversation callbacks called update_conversation with status, triggering the guard.
  3. Sync test fake — called upsert_conversation which was renamed to upsert_conversation_with_lifecycle.

Fixes:

  • lifecycle.py: added completed to expected_statuses in persist_processed_conversation so reprocess overwrites are not fenced.
  • test_canonical_memory_pipeline.py, test_conversation_processing_deterministic.py: removed status from update_conversation calls in fake functions (conversations were already completed).
  • test_core_flow_expansion.py: removed status from update_conversation, added explicit lifecycle.complete() call to match the production finalize flow.
  • test_sync_lifecycle.py: updated upsert_conversation → upsert_conversation_with_lifecycle (renamed by this PR).

Verification: full hermetic e2e suite passes locally (104 passed, 3 skipped). CI: all checks green including Hermetic Backend E2E.

@Git-on-my-level

Copy link
Copy Markdown
Member Author

@cursor address merge conflicts and do a review + fix round

Boundary Test added 23 commits July 15, 2026 01:47
Characterizes reconnect reuse of the existing finalization job before lifecycle refactoring.

Verification: cd backend && .venv/bin/python -m pytest tests/unit/test_conversation_finalization_jobs.py tests/unit/test_workflow_contracts.py -q (31 passed); cd backend && .venv/bin/python scripts/check_workflow_contracts.py; cd backend && black --check --line-length 120 --skip-string-normalization tests/unit/test_conversation_finalization_jobs.py.
Adds the seeded BasedHardware#9687 reducer contract before routing runtime lifecycle callers through it.

Verification: cd backend && .venv/bin/python -m pytest tests/unit/test_finalization_decision.py tests/unit/test_conversation_finalization_jobs.py tests/unit/test_workflow_contracts.py -q (38 passed); cd backend && .venv/bin/python scripts/check_workflow_contracts.py; black --check --line-length 120 --skip-string-normalization utils/conversations/finalization_decision.py tests/unit/test_finalization_decision.py.
Routes lifecycle creation, admission, transitions, finalization handoff, merge, import, and discard through one typed owner; deletes public writer seams and the temporary legacy counter.

Verification: cd backend && bash test.sh (583 files passed); cd backend && .venv/bin/python -m pytest tests/unit/test_check_conversation_lifecycle_writes.py tests/unit/test_conversation_lifecycle_contract.py tests/unit/test_conversation_revision_contract.py tests/unit/test_listen_finalization_cloud_tasks.py -q (46 passed); scripts/check_conversation_lifecycle_writes.py; scripts/check_workflow_contracts.py.
Phase 3 of BasedHardware#9687: bind each listen recording to a durable canonical conversation and emit versioned monotonic lifecycle envelopes consumed by macOS.

Verification: backend/test.sh (584 unit files); targeted lifecycle suite (59 passed); xcrun swift build/test StopReconciliationTests (40 passed); named omi-durable-recording-sessions bundle launched via automation bridge.
The lifecycle guard introduced by this PR inadvertently blocked:
1. Reprocessing already-completed conversations (persist_processed_conversation
   only accepted status in {processing, merging}, fencing out reprocess)
2. E2E test fakes that called update_conversation with lifecycle fields

Production fix: add 'completed' to the expected_statuses set in
persist_processed_conversation so reprocess overwrites are not fenced.

Test fixes: update E2E fake process_conversation functions to respect
the lifecycle boundary — use update_conversation for non-lifecycle fields
and lifecycle_service.complete() for status transitions. Update
upsert_conversation call to renamed upsert_conversation_with_lifecycle.

Verification: full hermetic e2e suite passes (104 passed, 3 skipped).
Firestore server transactions can let empty cleanup terminalize a generation before a late segment or photo write acquires the parent lock. Replay that buffered batch once through a fresh recording generation instead of resurrecting the tombstoned conversation, and persist first-segment started_at atomically with content.\n\nVerification:\n- npm run test:listen-lifecycle:emulator\n- cd backend && .venv/bin/python -m pytest tests/unit/test_live_content_rollover.py tests/unit/test_listen_lifecycle_emulator_harness_wiring.py tests/unit/test_recording_sessions.py tests/unit/test_conversation_finalization_jobs.py tests/unit/test_conversation_lifecycle_contract.py -q\n- cd backend && bash scripts/typecheck.sh (0 errors)\n- make preflight (20 checks)\n- cd backend && ./test.sh (586 test files)
@Git-on-my-level
Git-on-my-level force-pushed the codex/durable-listen-lifecycle branch from 65a578b to 99ca271 Compare July 14, 2026 19:02
@Git-on-my-level
Git-on-my-level merged commit 4c6fd68 into BasedHardware:main Jul 14, 2026
23 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant