Repository navigation
fix(finalizer): handle batch discard and restore without losing recording obligations (#24110) - #24119
Conversation
982dc61 to
6cae500
Compare
Git-on-my-level
left a comment
There was a problem hiding this comment.
The production logic here is sound and covers all four outcomes in #24110, but one blocking issue: the new keyword argument breaks two existing test suites, so this needs a small follow-up before merge.
What I verified on 6cae500 (hermetic container, no secrets):
backend/utils/conversations/finalizer.py—_record_registration_requirednow skips registration when the processed model marked the row discarded (merged over the stale initial read), removing theregister_recording-refused retry churn for intentional discards;expected_discarded=conversation.discardedat thefanout_claimstage is the right fence, since the finalizer already converts a non-claimed/completed/fenced status intoConversationFinalizationError('fanout_lease_conflict')— a restore racing the transaction retries on fresh durable state and registers the obligation.backend/database/conversation_finalization_jobs.py— theexpected_discardedguard returnslease_conflictwith no job write before_conversation_admits_fanoutruns, so a restored kept capture cannot be admitted or terminally fenced without itsrecord_pendingobligation; the not-a-Mapping split-out is behavior-preserving; the keyword-only default keeps every other caller on the old behavior.backend/utils/conversations/lifecycle.py— pass-through wrapper, signature-compatible with prior callers.backend/docs/listen_pusher_pipeline.mdx— the new section accurately describes the implemented behavior.- Tests: the three touched suites pass 90/90 in a clean container.
Blocking issue — existing suites broken by the signature change: finalize_persisted_conversation now calls lifecycle_service.claim_finalization_fanout(..., expected_discarded=...), and existing harness stubs do not accept the keyword:
tests/unit/test_listen_finalization_cloud_tasks.py— 172 failures, e.g. theclaim_fanoutstubs around lines 1675–2060, all failing at stage=fanout_claimwithTypeError: ... unexpected keyword argument 'expected_discarded'.tests/unit/test_duplicate_capture_policy.py— 28 failures; the harness lambda stubbingclaim_finalization_fanouthits the same TypeError.
Both suites are green on the merge base (4cd3c77) and red on this head in an identical container, so this is deterministic breakage from this diff, not an environment issue. The fix is mechanical: have those stubs accept the new keyword (e.g. **kwargs) and run both suites in CI — no CI workflows ran on this head, so the breakage was invisible to the checks shown here.
USER IMPACT: users who discard a recording while it is processing stop triggering silent retry loops, and a discard-then-restore race can no longer finalize a kept recording without its audio obligation; nothing else changes visibly.
What I'd still want: (1) the stub updates above; (2) issue #24110 asks for a real Firestore-transaction race regression — the added tests simulate the restore race through the fake transaction harness, which is good, but an emulator-backed regression would lock in the actual transactional semantics.
After the stub fix this should be ready; since it gates audio-obligation persistence, final sign-off stays with a human maintainer.
— automated maintainer review on David's behalf
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 Thank you for the detailed and spot-on review! Addressed in commit
Verified test suites locally:
Ready for re-review! |
|
Since my last review: addressed (the blocking test-suite breakage from the new Verdict: the blocking issue from my last review is fixed and verified — from my side this is ready; final merge sign-off stays with a human maintainer. Verified on Per-file notes:
USER IMPACT: users who discard a recording while it is processing stop triggering silent retry loops, and a discard-then-restore race can no longer finalize a kept recording without its audio obligation; nothing else changes visibly. What I'd still want before merge: CI to actually run on this head (no workflows have run on either commit), and ideally an emulator-backed regression locking in the real Firestore transactional semantics of the Leaving for human maintainer review: this gates durable user-recording obligation persistence, so it deserves a maintainer's merge sign-off. by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with |
Dismissed: the blocking concern (expected_discarded kwarg breaking test_listen_finalization_cloud_tasks.py and test_duplicate_capture_policy.py stubs) is fixed on a739893 — all affected stubs accept **kwargs and finalizer.py now omits the kwarg when not discarded; verified 418 passed / 0 failed for the five finalizer suites in a hermetic container.
a739893 to
6f83e3e
Compare
Git-on-my-level
left a comment
There was a problem hiding this comment.
The production fix here is correct and the race coverage is genuinely good - one blocking (but mechanical) item before merge: the docs file was re-saved with CRLF line endings.
Verified in the diff:
backend/utils/conversations/finalizer.py-_record_registration_required(finalizer.py:211) now skipsrecord_pendingregistration only when the row is actually discarded, andfinalize_persisted_conversation(finalizer.py:454-455) merges the post-processingconversation.discardedinto that decision, so a revival during processing still registers the audio obligation. Both flip directions are covered by the new parametrized test.backend/database/conversation_finalization_jobs.py- the newexpected_discardedguard (conversation_finalization_jobs.py:1231-1232): if the finalizer processed the row as discarded but a concurrent restore persisteddiscarded: falsebefore the fanout transaction, the claim returnslease_conflictand writes no terminal fence, so the job stays retryable. I traced the retry end-to-end: the finalizer raisesfanout_lease_conflict(finalizer.py:488), observability classifies it retryable, and on retry the restored row registers the recording before claiming fanout. This is a real data-loss fix for #24110.backend/utils/conversations/lifecycle.py:969- clean pass-through of the new kwargs; no behavior change for existing callers.backend/tests/unit/test_conversation_finalization_jobs.py:749- asserts thelease_conflictreturn with no transaction update.backend/tests/unit/test_record_finalizer_discard_registration.py- 4 hermetic tests including the two-attempt restore race (no registration on attempt 0, registration + completion on retry).backend/tests/unit/test_duplicate_capture_policy.py/test_listen_finalization_cloud_tasks.py- mechanical stub-signature updates for the new kwargs.
Blocking: backend/docs/listen_pusher_pipeline.mdx - all 9,018 lines were rewritten with CRLF endings; only ~8 lines are real content (the new "Restore-aware discard fence" section, plus a stray blank line near "### Live audio projection"). That is ~630KB of pure line-ending churn: it buries the actual doc addition, and breaks git blame for the whole file. Please re-apply just the new section on the LF version of the file so the diff shows only your addition. While at it, the commented-out # print("RUN FUNCTION:", ...) debug line in the new test file can go.
Performance: no extra reads - the discard check reuses the conversation already fetched inside the existing Firestore transaction. Security/data: no new surfaces; this closes a path where a kept capture could complete without its audio obligation.
USER IMPACT: fixes a rare race where restoring a just-discarded recording could leave its audio permanently unregistered; intentional discards now finalize without wasted retries.
Once the line endings are fixed I have no further code asks - leaving final sign-off to a human maintainer, since concurrent-restore semantics in the finalization pipeline (audio-obligation persistence) warrant maintainer judgment 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.
6f83e3e to
5c72460
Compare
|
@Git-on-my-level Thank you for the review! Addressed all blocking and review items in commit
Branch is clean, conflict-free, and ready for maintainer merge! |
|
Since my last review: addressed (the CRLF rewrite of Verdict: my only blocking item is resolved; the production fix is correct and I have no remaining blocking concerns — leaving for human maintainer sign-off before merge. Re-verified on
One non-blocking nit: in the new docs section ( Blast radius: USER IMPACT: users who restore a just-discarded capture while it is still processing will no longer end up with a "kept" conversation that silently lost its recording — the finalizer retries and registers the audio. Still want as a reviewer: the two-line docs typo fix, and a container run of the three touched suites before merge since CI does not exercise them here. Leaving for human maintainer review: this changes data-integrity handling in the by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with |
The blocking concern from this review (backend/docs/listen_pusher_pipeline.mdx rewritten with CRLF line endings) is resolved on head 5c72460: the diff now contains zero CR bytes and the docs change is a single clean 8-line addition.
…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.
Git-on-my-level
left a comment
There was a problem hiding this comment.
Verdict: the production change is correct and well-fenced, but this head cannot merge as-is - it deterministically breaks three existing unit tests, and the fix is one line.
Blocking (CI red on this head)
backend/utils/conversations/finalizer.pynow passesexpected_discarded=Truetoclaim_finalization_fanoutwhenever the processed conversation was discarded. The claim stub inbackend/tests/unit/test_process_conversation_free_tier_branch.py:881is stilldef claim(*args):, so the threediscarded_replayparametrizations oftest_finalizer_summary_vector_requires_winning_claimfail withTypeError: ... claim() got an unexpected keyword argument 'expected_discarded', which is what makes "Backend unit shard 8/8" and "Backend unit suite" red. You updated the identical stubs intest_listen_finalization_cloud_tasks.pyandtest_duplicate_capture_policy.py; this file was missed.def claim(*args, **kwargs):should do it.
Correctness of the production change (verified against the diff)
backend/database/conversation_finalization_jobs.py- theexpected_discardedcheck sits after the missing/discarded/superseded terminal fences and before the claim write, so only an otherwise-current restored generation getslease_conflict, and the retry path mutates nothing (your new tests asserttransaction.updates == [], which matches the code).backend/utils/conversations/finalizer.py-_record_registration_requiredgains adiscardedexemption, and overlaying the processedconversation.discardedonto the initial read's archive/producer metadata keeps the registration decision consistent with the payload actually handed toregister_recording.backend/utils/conversations/lifecycle.py- keyword-only passthrough plusfirestore_clientinjection for the emulator test; default behavior unchanged.backend/scripts/listen_lifecycle_emulator_test.py- the restore-commits-before-the-claim's-conversation-read emulator scenario is a genuinely strong regression for exactly this race.backend/tests/unit/test_restore_fanout_terminal_overlap.py,test_record_finalizer_discard_registration.py,test_conversation_finalization_jobs.py- good fence matrix plus retry/re-registration coverage.backend/testing/listen_pusher_stack/cleanup.py,backend/testing/listen_pusher_stack/run.py,backend/tests/unit/test_listen_pusher_stack_cleanup.py- local stack harness only; verifying UID/session ownership before every group signal is the right fail-closed posture, andrun.pyalso fixes a leaked log file handle (with log_path.open('ab')). No production process policy changes.backend/docs/listen_pusher_pipeline/changes/2026-11-07-restore-aware-discard-fence.md- accurate and appropriately hedged ("local lifecycle guarantees, not deployment evidence").
Blast radius: batch_live_v1 recording obligations and finalization fanout. If this logic were wrong in the other direction, users could lose the audio obligation for a restored capture (or churn registrations for intentionally discarded ones); the fence here preserves the obligation on restore, which is the safe side.
USER IMPACT: none by design - this fixes a race where restoring a just-discarded live capture could lose its pending recording; discard/restore behavior otherwise feels the same.
Still wanted as a reviewer: the one-line stub fix above and a green "Backend unit suite" on the new head (the description notes a targeted local shard passed - please run the full test_process_conversation_free_tier_branch.py before pushing).
Because discard/restore interacts with exactly-once fanout and user-data retention, I'm leaving the existing needs-maintainer-review label in place for a human maintainer to sign off on the semantics even after CI goes green.
by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.
|
Cross-link: this fix is carried into #24896, a ready replacement PR on the same head work (43611dd). #24896 keeps the original author's commit 5c72460 and its authorship, so no credit moves. Lead2 and the coordinator decided on the replacement because a push to this branch was not possible from our side. This PR stays open for David to close or keep. Generated by Claude Code |
…ons (supersedes #24119) (#24896) <!-- 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 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 in `finalize_persisted_conversation` now returns a terminal `discarded` disposition for a discarded row before any `register_recording` call (Codex/cubic P2). Emits `event=server_batch_finalization outcome=discarded`. Also: the emulator asserts a refused registration for a discarded row, the stale-read assertion in `test_record_finalizer_discard_registration.py` now 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 normal `register_recording` path, 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 passes `restoring=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-only `orphan_parked` signal (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): - Unit targets: `BACKEND_UNIT_TEST_FILE_LIST` with 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. - Real-store lifecycle emulator: `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. - Typecheck: `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 from `int(discarded)` to `int(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.py` no longer imports `utils.batch_pipeline.live` at module level (commit a2b8586 removes base line 26; the import now sits inside `register()` at `lifecycle.py:651`). That removed the transitive `google.cloud.storage` import via `live.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_write` and `::test_langchain_tool_uses_the_same_source_boundary` (backend unit shard 5/8) ## Tests - tests/unit/test_restore_recording_obligation.py (8 regression cases): restored sealed batch_live_v1 row with no job gets exactly one recording obligation, restoring twice still gives one; restored-then-discarded gets none; privacy-blocked row is refused with the retryable state surfaced. - tests/unit/test_record_finalizer_discard_registration.py: discarded fast path reaches terminal exactly once with zero register_recording calls. ## 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_pending` transition is deferred to a follow-up PR. This PR adds only observability: a restore-origin job parked on a discarded row emits `event=record_seal_refused outcome=orphan_parked` and increments `omi_record_seal_orphan_parked_total`. No behavior changes. ## Zero-preview discard Codex P2 on a2b8586 (`finalizer.py:289` in the discarded branch, `finalizer.py:283-293`). A zero-preview capture discarded after it enters `processing` closed its fanout and job, but left the conversation in `processing`. A later restore then failed `require_record_audio_barrier` until stale-orphan reconciliation. `finalizer.py` now calls `complete_discarded_server_batch_fanout` (call at `finalizer.py:286`). It closes the fanout and, when the parent is still bound to this job and revision, advances it from `processing` to `completed` in one transaction. The processing-to-completed write goes through `claim_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) and `test_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 checked `record_audio_closed` but not `server_batch_audio_closed`, so an open server archive could restore with no obligation and its later audio would be orphaned. The shortcut now uses `config.server_batch.proven_empty`, the predicate the finalizer applies (`finalizer.py` calls the same helper), plus `record_audio_closed`. Codex P2 at `lifecycle.py:670`. A projected row (`record_projection_revision`, the marker `phase.py` reads) was already fulfilled. Its receipt expires after 45 days (`retention.py:279-283`), and `register_recording` dedupes 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 with `record_audio_closed=True` registers 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: `0eb804839` added an orphan-terminal attempt and `e4e0f99bea8` reverts 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 revert` of this PR's commits (c679690, d1428a5), or of the merge commit. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Processing a batch discard must not register a recording obligation that cannot be fulfilled. A restored retained capture must register its durable
record_pendingobligation before fanout. This change preserves Dimank92's original commit unchanged and resolves it against main, retaining current-generation restore retries and stale-generation terminal/projection fences. Photo-only proven-empty captures keep their registration exemption.Regression coverage includes discard/restore registration, restore-versus-fanout contention and real Firestore lifecycle checks. The stack harness also retains child handles until reap and process-group absence are verified, validates ownership before signaling, and attempts all cleanup while preserving the original scenario error. Those changes affect the local test harness, not production process policy.
Failure-Class: FC-durable-terminal-projection
Product invariants affected: none (preflight path selection).
Line-Count-Exception: backend/database/conversation_finalization_jobs.py | 3549 -> 3557 | Extend the existing atomic fanout owner with the restore registration fence; extracting transaction ownership is outside this conflict resolution.
Local validation at858175b: targeted backend shard passed, including all44 cleanup cases; the real Firestore lifecycle emulator passed through the public fanout wrapper with a real SDK read barrier. All12 changed Python files pass the pinned formatter. The full local stack did not pass at its earlier32122fb source: Darwin reap/ps-census limits and a later unchanged-run concurrent REST read timeout are preserved in the lane evidence. Full-stack qualification must pass in Linux CI before merge; no local failure is represented as green. Normal pre-push gates, including the repaired test-script typecheck boundary, remain mandatory. Two independent read-only Luna reviews (correctness and production safety) follow CI. No production write or deploy is performed by this PR.