Repository navigation
fix(listen): restore-aware discard fence for batch recording obligations (supersedes #24119) - #24896
Conversation
…ership Preserve Dimank92 original commit; resolve pipeline documentation through a dated change note and correct register_recording/record_pending names. Retry restored generations only after current ownership admission, keeping stale fences and projection outcomes intact. Targeted validation: 463 passing backend unit tests across 13 files. Emulator contention and hermetic stack validation follow on this local candidate. Failure-Class: FC-durable-terminal-projection
Use a deterministic barrier between concurrent Firestore transactions rather than assuming parent read locks exclude another reader. The emulator proves restore refusal, real record_pending registration, successful retry and exactly-once terminal projection.
Keep child handles on cleanup failure, attempt every registered child, and preserve the original scenario error with secondary cleanup diagnostics. Reap terminal direct children before metadata calls; require kernel proof of group absence and reject unknown ownership before signaling. Add bounded real-child and policy regressions. The corrected real Darwin probe and full stack remain pending; historical EPERM cause is unproven.
Include the current monitoring, F-join and pusher admission changes before exact-head validation. Preserve the original author commit and cleanup checkpoint.
Record snapshot-to-lookup ESRCH with an unknown SID for every observed state. Unknown rows cannot authorize a signal; success still requires reaping the owned direct child and kernel proof that its group is absent. Cover live and terminal cases without relaxing denials or timeout bounds.
When the sole retained direct child has an unknown SID from ESRCH, avoid signaling and use the existing bounded KILL wait solely for that child. Require actual reap and independent kernel proof of group absence.
Gate the real SDK's public document read at the target conversation while calling the production public fanout wrapper. Keep real transaction/retry IO, all projection and ordering assertions, and the existing event/join bounds. Seed the projection fixture from its stored generation and shard schema.
Keep the existing completed-fanout replay assertion unchanged and wrap its monkeypatch call with the repository's pinned backend formatter.
Accept and verify expected_discarded in the existing claim double for every replay mode while retaining all vector, fanout and suppression assertions.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
1 issue found across 14 files
Confidence score: 5/5
backend/docs/listen_pusher_pipeline/changes/2026-11-07-restore-aware-discard-fence.mdmixes the lifecycle-simulator supervisor cleanup narrative into an unrelated discard-fence note, making it harder to scan. Move the supervisor cleanup material to its own note.
You’re at about 96% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact [email protected].
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="backend/docs/listen_pusher_pipeline/changes/2026-11-07-restore-aware-discard-fence.md">
<violation number="1" location="backend/docs/listen_pusher_pipeline/changes/2026-11-07-restore-aware-discard-fence.md:23">
P3: This note combines two unrelated changes. The lifecycle-simulator supervisor cleanup narrative does not belong in the discard-fence change note, and it makes the note hard to scan. Move the supervisor cleanup material to its own dated change note, or drop it from this PR, and keep this note to the fence, its rollout, and its evidence.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Re-trigger cubic
| fanout claim, then verifies refusal and durable recording registration before a | ||
| successful retry. These are local lifecycle guarantees, not deployment evidence. | ||
|
|
||
| The hermetic listen-stack supervisor retains child handles until the leader is |
There was a problem hiding this comment.
P3: This note combines two unrelated changes. The lifecycle-simulator supervisor cleanup narrative does not belong in the discard-fence change note, and it makes the note hard to scan. Move the supervisor cleanup material to its own dated change note, or drop it from this PR, and keep this note to the fence, its rollout, and its evidence.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/docs/listen_pusher_pipeline/changes/2026-11-07-restore-aware-discard-fence.md, line 23:
<comment>This note combines two unrelated changes. The lifecycle-simulator supervisor cleanup narrative does not belong in the discard-fence change note, and it makes the note hard to scan. Move the supervisor cleanup material to its own dated change note, or drop it from this PR, and keep this note to the fence, its rollout, and its evidence.</comment>
<file context>
@@ -0,0 +1,53 @@
+fanout claim, then verifies refusal and durable recording registration before a
+successful retry. These are local lifecycle guarantees, not deployment evidence.
+
+The hermetic listen-stack supervisor retains child handles until the leader is
+reaped and its original process group is proved absent. Cleanup checks session
+and UID ownership before each group signal, attempts every registered child,
</file context>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 43611dd8a3
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| """Retain required audio obligations; discarded and proven-empty rows have none.""" | ||
| return ( | ||
| row.get('record_lane_owner') == 'batch_live_v1' | ||
| and not row.get('discarded') |
There was a problem hiding this comment.
Re-register recordings restored after the discard fence
For a sealed batch_live_v1 capture with no prior recording job (record_audio_closed=True, no record_audio_partial), restoring after the discarded pass commits its fanout fence leaves the kept row without a recording obligation and with a terminal finalization job. restore_conversation_from_discarded() only updates conversation metadata, and the /reprocess restore flow never calls register_recording; the batch drain requires an existing record_pending job, while record_seal_cluster_repair.discover() excludes these sealed rows. Consequently, the restored recording has no automatic path to final batch transcription, and cold WAL uploads remain blocked at RECORD_JOBS_MISSING. The new expected_discarded guard protects only restores before the claim, so preserve a registration/re-enqueue path for restores afterward as well.
Useful? React with 👍 / 👎.
…ath; emulator and test assertions The emulator scope has no snapshot variable. Read and retain its initial discarded conversation row as discarded_conversation before the concurrent restore, then use that row for the refused-registration assertion.
…ed sealed capture (P1)
…for pyright Overloads make return_snapshot=True return Optional[dict] and the default return bool. The runtime body is unchanged. Clears the pre-push pyright errors at lifecycle.py:640 (Literal[True] has no attribute get).
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7b32462c8f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if conversation_data.get('discarded'): | ||
| logger.info('event=server_batch_finalization outcome=discarded') | ||
| return ConversationFinalizationDisposition.discarded |
There was a problem hiding this comment.
Commit a terminal fanout state before returning discarded
For a newly claimed discarded server-batch capture with no transcript or photos, the job still has fanout_status='pending' when this return runs. Both run_listen_finalization_job() and process_conversation_task() pass this disposition to mark_finalization_completed(), whose transaction rejects any fanout state other than completed (backend/database/conversation_finalization_jobs.py:1031-1032). Consequently, the HTTP worker returns 409 completion_conflict and pusher reports job_completion_conflict, leaving the job leased instead of terminal. Commit a lease- and restore-aware terminal transition before returning. The regression test currently masks this by mocking completion to succeed unconditionally; retain the real completion guard with StrictFirestore.
AGENTS.md reference: backend/AGENTS.md:L232-L232
Useful? React with 👍 / 👎.
| if restored.get('record_lane_owner') != 'batch_live_v1' or not restored.get('record_audio_closed'): | ||
| return True |
There was a problem hiding this comment.
Register restores before the upload barrier is closed
If a completed batch_live_v1 capture without a recording job is restored after its discard fence but while pusher is still draining (record_audio_closed=False), this newly added gate returns success without registering its obligation. If pusher then seals before the next repair sweep, seal_record_audio() only updates the closure metadata, while automatic repair discovery excludes closed, non-partial rows (backend/utils/batch_pipeline/record_seal_cluster_repair.py:276-281). The successfully restored capture therefore has no automatic batch-transcription path. Persist the obligation even before sealing: register_recording() permits this, and the batch drain already enforces the upload barrier before admission.
Useful? React with 👍 / 👎.
| current = tx.get('conversations', f'{uid}/{conversation_id}') | ||
| if not current.get('record_audio_closed'): | ||
| return False | ||
| return register_recording(uid, {**current, 'id': conversation_id}, transaction=tx) |
There was a problem hiding this comment.
Preserve the proven-empty exemption during restoration
For a sealed photo-only server-batch capture with a proven-empty audio archive, this registration always returns False: register_recording() rejects server-batch rows without an audio span at backend/utils/batch_pipeline/live.py:129-130. The wrapper then raises RestoredRecordingRegistrationUnavailable, so /reprocess returns 503 on every retry even though the restore metadata has committed. These captures intentionally have no recording obligation, as enforced by _record_registration_required() and covered by test_record_finalizer_photo_registration.py. Apply the same proven-empty exemption during restore instead of treating the intentionally absent audio obligation as a retryable failure.
Useful? React with 👍 / 👎.
…rded finalize; register closed-false and proven-empty restores
…; window-ordering test
…ations; flip refused-restore test
…ore-origin marker lead2 ruling d64ce0: the orphan obligation stays parked by design, and the record_pending terminal transition moves to a follow-up. This reverts the orphan helper, its seal call sites, the new test file and the change doc from 0eb8048. The refused-restore test flip and the restore-origin marker (registration_origin='restore') stay.
…tore obligations A restore-origin job on a still-discarded row stays parked, by design (lead2 ruling d64ce0). The terminal record_pending transition is deferred to a follow-up. This adds only a log line (event=record_seal_refused outcome=orphan_parked) and a counter, so the parked orphans are visible. No returns, writes or transitions change.
Resolves the live.py import conflict: keep main's config.batch_pipeline import block and this branch's is_soft_deleted import. No other conflicts.
…versation row observe_existing_orphan (record_seal_nojob) now reads the snapshot and checks the row inside its try, so a deleted conversation neither raises nor emits orphan_parked; the already_registered result is unchanged. observe_orphan_parked (record_seal_repair) returns early for a missing row. Tests cover both sites.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ce1df9e566
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if not await run_blocking( | ||
| db_executor, | ||
| lifecycle_service.complete_finalization_fanout, |
There was a problem hiding this comment.
Acknowledge completed fanout on discarded-capture replays
If a worker dies after this call commits but before mark_finalization_completed(), the next delivery re-enters this branch and fails with fanout_completion_conflict. _mark_finalization_fanout_completed_txn() accepts an already-completed fanout only when fanout_lease_epoch matches, but this new direct completion bypasses the claim that normally stamps that field; even repeating within the original lease returns False. The HTTP worker therefore burns additional attempts, while the inline pusher lane cannot close the job through its normal retry path. Honor an already-completed fanout on replay or use an idempotent terminal discard transaction.
Useful? React with 👍 / 👎.
| if restoring: | ||
| if is_soft_deleted(conversation) or conversation.get('sync_merged_into'): | ||
| return False | ||
| elif conversation.get('discarded'): |
There was a problem hiding this comment.
Keep sealed restore obligations fenced until metadata commits
For a completed, sealed, non-partial capture, allowing registration while discarded=True does not leave the obligation parked if the subsequent restore metadata write fails. The job is immediately due (UPLOAD_GRACE_SECONDS=0), the full-archive admit_recording() path accepts its closed barrier, and batch_pipeline_intake.admit() rejects discarded targets only for partial admissions. Consequently, a failed restore can still launch paid batch processing; for an automatic discard, replace_record() can also clear the discard without the restore metadata ever committing. Add a restore-pending fence to full-archive admission as well, or commit registration and restore metadata atomically.
Useful? React with 👍 / 👎.
| return register_recording(uid, current, transaction=tx, restoring=True) | ||
|
|
||
| try: | ||
| registered = FirestoreStore(f'batch_pipeline_{current_stage()}').run(register) |
There was a problem hiding this comment.
Preserve metadata-only restores in local and offline stages
In the supported OMI_ENV_STAGE=local and offline harnesses, this constructs batch_pipeline_local or batch_pipeline_offline, but FirestoreStore.__init__() rejects both namespaces with ValueError. Construction happens before register() can inspect the row, so even legacy/non-batch restores now raise, causing /reprocess and user-selected sync processing to fail despite requiring no batch obligation. Keep metadata-only restores independent of batch namespace validation, or provide a stage-compatible store.
AGENTS.md reference: backend/AGENTS.md:L16-L16
Useful? React with 👍 / 👎.
…the same lease - lifecycle: import register_recording inside register() so the module loads without google.cloud.storage (shard 8 ImportError). - lifecycle: only batch_live_v1 rows enter the batch store path; non-batch restores skip FirestoreStore/current_stage (shard 4 InvalidSyncStage). restore_discarded pre-reads the raw document, avoiding the photo-attaching getter that StrictFirestore rejects. - finalization_jobs: stamp fanout_lease_epoch when fanout completes, so a replay under the same lease is accepted after a discarded close. - test_reprocess_app_selection (shard 3): restore.call_count expectation changes from `int(discarded)` to `int(discarded or stored_keep)`. A user_kept row re-runs restore registration on reprocess (register-first retry), so the old expectation undercounted it. - Retarget register_recording patches to live.register_recording, where the name is now resolved. - Add a local non-batch restore test and a discarded fanout replay test.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a2b8586335
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| lifecycle_service.complete_finalization_fanout, | ||
| finalization_job_id, | ||
| dispatch_generation, | ||
| lease_epoch, |
There was a problem hiding this comment.
Close the capture lifecycle before acknowledging a discard
For a zero-preview capture discarded after it enters processing, this branch completes the fanout and job without advancing the conversation status. A subsequent restore through routers/developer.py:2570 clears the discard metadata but leaves that status unchanged, so the newly registered recording obligation fails require_record_audio_barrier() in config/record_audio.py:28. The successfully acknowledged recording then waits for stale-orphan reconciliation instead of proceeding to transcription; the normal complete_server_batch_capture() path explicitly completes the parent row. Terminalize the still-bound parent as well, and cover an initially processing parent with the real StrictFirestore completion guard.
AGENTS.md reference: backend/AGENTS.md:L232-L232
Useful? React with 👍 / 👎.
…g its fanout A zero-preview capture discarded after it enters processing closed its fanout and job but never advanced the still-bound conversation. A later restore then left the row in processing, so its batch admission failed require_record_audio_barrier until stale-orphan reconciliation. complete_discarded_server_batch_fanout now closes the fanout and, when the parent is still bound to this job and revision, moves processing to completed in the same transaction. Redelivery of the same lease replays; a stale lease and a parent owned by a newer finalization are left alone. Tests: the StrictFirestore completion path (processing parent, replay, stale lease, unbound parent) and a restore that passes the barrier after the fanout close. The discard fast-path tests now patch the new function.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: adeb3a8da8
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| ): | ||
| return True | ||
| current['id'] = conversation_id | ||
| return register_recording(uid, current, transaction=tx, restoring=True) |
There was a problem hiding this comment.
Skip fulfilled recording obligations after receipt expiry
For an already-finalized batch_live_v1 conversation restored after its completed receipts expire, this unconditional registration creates a second record_pending obligation. retention._expire_completed_segment() gives the job and intake a 45-day TTL, whereas the parent survives with its record_projection_revision; register_recording() only deduplicates against the now-missing job, and full-record admission does not exempt already-projected recordings. The restored row can therefore incur duplicate batch transcription if raw audio remains, or leave a non-expiring pending job retrying if it does not. Distinguish fulfilled recordings from never-registered captures before creating restore debt, and cover restoration after receipt expiry.
Useful? React with 👍 / 👎.
Restore's proven-empty shortcut checked record_audio_closed but not server_batch_audio_closed, so an open server archive could restore with no obligation. It now uses config.server_batch.proven_empty, the predicate the finalizer applies, plus the capture's own record_audio_closed gate. A projected row (record_projection_revision, the marker phase.py reads) was already fulfilled. Its receipt expires after 45 days, and register_recording dedupes only against the job, so restore registration would transcribe the audio again. Such rows register nothing. The discarded zero-preview fanout close now routes its processing-to-completed write through claim_conversation_status_in_txn, the strict terminal owner, instead of writing the status literal from the jobs module. The bound-parent and lease checks are unchanged. The relevance decision comes from the owner. Tests: restore after receipt expiry on a projected row creates no obligation; an open server archive with record_audio_closed registers exactly one obligation; a closed, proven-empty archive registers none.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b7898c6e69
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if (was_discarded or user_kept) and not processed_conversation.discarded: | ||
| restored = lifecycle_service.restore_discarded(uid, conversation_id) |
There was a problem hiding this comment.
Register restore debt before reprocessing publishes visibility
For a sealed, discarded batch_live_v1 capture with no recording job and an already-terminal finalizer, this registration runs too late. process_conversation() first persists discarded=False and sync_relevance_user_kept=True (backend/utils/conversations/process_conversation.py:2891-2948), then can raise on a selected-app failure at lines 3178-3189. That error bypasses this restore call entirely, leaving a visible, kept recording without its transcription obligation. The recording drain requires an existing job, and repair discovery excludes sealed, non-partial rows, so another explicit restore is needed to recover it. Register the obligation before the processor's visibility write, or atomically with that write, and cover the persist-then-fail path rather than mocking the processor.
Useful? React with 👍 / 👎.
…mits (#24927) <!-- claude-projects-attribution: {"github_login":"Git-on-my-level"} --> _Requested by **David** · [project thread](https://claude.ai/code/project/chan_01DkCywHd8HiN61t59mu7kXF?thread=cmsg_01DkCywHd8HiN61t59mu7kXFReBVorHLQv1x1Xmz4fgMU8)_ ## What changed and why This is a follow-up to #24896 (merged), per lead2's 812335 ruling, option B. On `/reprocess`, the processing persist wrote `discarded=False` for a kept verdict before the router's restore registered the recording obligation. A selected-app failure raised after that persist and skipped the restore. The result was a visible, kept recording with no recording obligation. The fix keeps visibility behind the restore: - `process_conversation` takes `restores_discarded` from the router. For a discarded row being restored, the persist keeps `discarded=True`. - The router runs `restore_discarded` (registers the obligation, then commits the metadata). The response's `discarded` flag reflects the restore result. Only the restore writes visibility for a discarded row. A selected-app failure now leaves the row hidden with no obligation, and a successful reprocess registers exactly one obligation. Out of scope, per lead2's ed3b20: P2 C (the admission-time discarded fence in `batch_pipeline_intake` and the `replace_record` discard clearing). It is tracked separately for #24893's owner. Files: `backend/utils/conversations/process_conversation.py`, `backend/routers/conversations.py`, and the new `backend/tests/unit/test_reprocess_restore_visibility.py`. ## Product invariants affected - INV-MEM-4 - INV-TASK-2 ## How it was verified Gates ran on the exact head `9e7d5432061` (on top of the #24896 merge commit `2ca7a20228b`): - Unit targets: 39 files, including the new test file. `BACKEND_PYTEST_FILE_ISOLATION=1`. 39 of 39 passed. - Typecheck (`backend/scripts/typecheck.sh`): 0 errors. - Real-store lifecycle emulator (`npm run test:listen-lifecycle:emulator`): PASS. - `scripts/pr-preflight`: see the result line below. ## Tests `tests/unit/test_reprocess_restore_visibility.py` runs the real `/reprocess` route and the real `process_conversation` against the strict store. Only the model, selected-app, Redis, dream-marker, and app-output-write boundaries are stubbed. - Selected-app failure after the persist: the row stays hidden, no restore registration, no recording job. The test fails on the pre-fix code (`discarded` read as `False`), so it catches the bug. - Successful reprocess: exactly one restore registration, the row becomes visible, and a `record_pending` job exists. The existing reprocess and restore suites (`test_reprocess_app_selection.py`, `test_restore_recording_obligation.py`, `test_discarded_fanout_replay.py`) still pass unchanged. ## UI evidence UI-Evidence: none -- backend change only ## Failure class (fixes) Failure-Class: FC-rule-discard-left-visible The reprocess shortcut must persist a discard decision and its visibility atomically. Here the persist made a discarded row visible before the restore committed its obligation. Line-Count-Exception: backend/routers/conversations.py | 2588 -> 2590 | 2-line restore-visibility change for the /reprocess fix (lead2 812335 option B); split deferred so the reviewed fix lands unchanged Line-Count-Exception: backend/utils/conversations/process_conversation.py | 3403 -> 3408 | 5-line restores_discarded kwarg and persist guard for the /reprocess fix (lead2 812335 option B); split deferred so the reviewed fix lands unchanged 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/24927?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
Requested by David · project thread
What changed and why
Supersedes #24119. This is a replacement PR, not an edit to the contributor's branch.
#24119 (fix/issue-24110-restore-aware-discard-fence, from the Dimank92 fork) adds the restore-aware discard fence for batch recording obligations. The original author is @Dimank92; their commit 5c72460 is carried over with its authorship preserved.
The head b7898c6 adds the restore fixes described under "Restore: shared proven-empty predicate and projected rows", and routes the zero-preview write through the strict owner (see "Zero-preview discard"). adeb3a8 added the zero-preview discard fix. Before it, a2b8586 adds the CI fixes described under "How it was verified", and c679690 added three things on top of the carried-over fix:
Merge of current origin/main (49c579f), plus a two-line test-fixture repair (4159ae8).
d1428a5b400: the server-batch fast path infinalize_persisted_conversationnow returns a terminaldiscardeddisposition for a discarded row before anyregister_recordingcall (Codex/cubic P2). Emitsevent=server_batch_finalization outcome=discarded. Also: the emulator asserts a refused registration for a discarded row, the stale-read assertion intest_record_finalizer_discard_registration.pynow checks the persisted state, and supervisor-cleanup material is removed from the change doc.c679690bc37: restoring a discarded sealed capture (restore_conversation_from_discarded) now registers its recording obligation through the normalregister_recordingpath, under the same privacy, discard and ownership fences. Registration is idempotent and bounded; a refusal fails closed and surfaces a retryable state (lead2 ruling dd4c94, Codex restore P1).24e98a08a01: explicit restorability check for the register-first restore (no synthetic discarded=False shape); the register-first call passesrestoring=True, and only a restorable row (not deleted, tombstoned or merged, same lane) may register while discarded. Window-ordering test added.0eb804839+e4e0f99bea8: an orphan-terminal attempt and its revert (net: none).92635af2cda: observability-onlyorphan_parkedsignal (log + counter); no behavior change.The fix itself is the discard fence described in backend/docs/listen_pusher_pipeline/changes/2026-11-07-restore-aware-discard-fence.md, and the restore change is in backend/docs/listen_pusher_pipeline/changes/2026-11-08-restore-recording-obligation.md.
Product invariants affected
none
How it was verified
Gates ran on the exact head a2b8586 (local commit on ce1df9e, which merged origin/main ec0e7af):
BACKEND_UNIT_TEST_FILE_LISTwith the 32 touched, finalizer-named and new restore test files (C repro excluded),BACKEND_PYTEST_FILE_ISOLATION=1,BACKEND_UNIT_FILE_BUDGET_SECONDS=900. Result: all 32 files passed, 0 failed, exit 0.npm run test:listen-lifecycle:emulator(firebase emulators:exec, Firestore, demo-listen). Result:PASS: Firestore emulator fenced cleanup races and preserved listen content through fresh-generation replay, exit 0.backend/scripts/typecheck.sh(pyright): 0 errors (76689 pre-existing warnings), exit 0.The a2b8586 commit fixes three CI failures: shard 3 (a stale expectation in
test_reprocess_app_selection.py, changed fromint(discarded)toint(discarded or stored_keep)because a user_kept row re-runs restore registration on reprocess), shard 4 (non-batch restores no longer construct the batch store), and shard 8. For shard 8:lifecycle.pyno longer importsutils.batch_pipeline.liveat module level (commit a2b8586 removes base line 26; the import now sits insideregister()atlifecycle.py:651). That removed the transitivegoogle.cloud.storageimport vialive.py:48->artifact_policy.py:10->artifacts.py:20.The unit file budget was set to 900 seconds for this run; every test in the list still runs and must pass.
Known failures on main, not caused by this PR. Both reproduce on origin/main 9dc8553 in a clean worktree:
tests/unit/test_batch_pipeline_startup.py::test_load_pyannote_pair_missing_deps(regex mismatch; backend unit shard 2/8)tests/unit/test_feedback_task_provenance.py::test_tool_error_is_visible_and_does_not_writeand::test_langchain_tool_uses_the_same_source_boundary(backend unit shard 5/8)Tests
UI evidence
UI-Evidence: none -- backend change only
Follow-up (deferred by design)
An orphan obligation (a restore-origin job registered before a failed restore metadata write, on a row that stays discarded) stays parked by design, per lead2 ruling d64ce0. The terminal
record_pendingtransition is deferred to a follow-up PR. This PR adds only observability: a restore-origin job parked on a discarded row emitsevent=record_seal_refused outcome=orphan_parkedand incrementsomi_record_seal_orphan_parked_total. No behavior changes.Zero-preview discard
Codex P2 on a2b8586 (
finalizer.py:289in the discarded branch,finalizer.py:283-293). A zero-preview capture discarded after it entersprocessingclosed its fanout and job, but left the conversation inprocessing. A later restore then failedrequire_record_audio_barrieruntil stale-orphan reconciliation.finalizer.pynow callscomplete_discarded_server_batch_fanout(call atfinalizer.py:286). It closes the fanout and, when the parent is still bound to this job and revision, advances it fromprocessingtocompletedin one transaction. The processing-to-completed write goes throughclaim_conversation_status_in_txn, the strict terminal owner, which carries its relevance decision; a discard verdict is preserved. Replay of the same lease is idempotent, and a stale lease is refused. A parent owned by a newer finalization is left alone.Tests:
test_discarded_fanout_replay.py(StrictFirestore completion path: processing parent, replay, stale lease, unbound parent kept) andtest_restore_recording_obligation.py(restore passes the barrier after the fanout close). The discard fast-path tests now patch the new function.Restore: shared proven-empty predicate and projected rows
Custody review (babfa2) P1 at
lifecycle.py:662. The restore's proven-empty shortcut checkedrecord_audio_closedbut notserver_batch_audio_closed, so an open server archive could restore with no obligation and its later audio would be orphaned. The shortcut now usesconfig.server_batch.proven_empty, the predicate the finalizer applies (finalizer.pycalls the same helper), plusrecord_audio_closed.Codex P2 at
lifecycle.py:670. A projected row (record_projection_revision, the markerphase.pyreads) was already fulfilled. Its receipt expires after 45 days (retention.py:279-283), andregister_recordingdedupes only against the job (live.py:175-180), so restore registration would transcribe the audio again. Such rows register nothing.Tests (
test_restore_recording_obligation.py): restore after receipt expiry on a projected row creates no obligation; an open server archive withrecord_audio_closed=Trueregisters exactly one obligation; a closed, proven-empty archive registers none. The never-registered sealed case is covered by the existing single-registration test.Known gap
Known gap (lead2 ed3b20): if the restore metadata write fails after registration, paid batch work can start for a still-discarded conversation until the follow-up (admission-time discarded re-read on every path, replace_record never clears discarded) lands.
Merge note: origin/main (ec0e7af) was merged in as ce1df9e to resolve a live.py import conflict.
History note:
0eb804839added an orphan-terminal attempt ande4e0f99bea8reverts it. Both are in the pushed history; the net diff has no orphan-terminal code.Failure class (fixes)
Failure-Class: none
Line-Count-Exception: backend/database/conversation_finalization_jobs.py | 3551 -> 3630 | 8-line restore-aware discard fence carried over from contributor PR #24119, a 1-line fanout_lease_epoch stamp, and a ~68-line discarded zero-preview fanout close that also advances the still-bound processing parent in the same transaction (complete_discarded_server_batch_fanout); split deferred to a follow-up so the reviewed fix lands unchanged
Line-Count-Exception: backend/routers/conversations.py | 2574 -> 2581 | 7-line restore re-registration wiring for the restore P1 (lead2 dd4c94); split deferred to a follow-up so the reviewed fix lands unchanged
Line-Count-Exception: backend/database/conversations.py | 4938 -> 4950 | 12-line typing overloads for restore_conversation_from_discarded (pyright fix); runtime unchanged; split deferred to a follow-up
Rollback:
git revertof this PR's commits (c679690, d1428a5), or of the merge commit.🤖 Generated with Claude Code