Skip to content

fix(finalizer): handle batch discard and restore without losing recording obligations (#24110) - #24119

Merged
Git-on-my-level merged 9 commits into
BasedHardware:mainfrom
Dimank92:fix/issue-24110-restore-aware-discard-fence
Nov 8, 2026
Merged

Git-on-my-level merged 9 commits into
BasedHardware:mainfrom
Dimank92:fix/issue-24110-restore-aware-discard-fence

Conversation

@Dimank92

@Dimank92 Dimank92 commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Processing a batch discard must not register a recording obligation that cannot be fulfilled. A restored retained capture must register its durable record_pending obligation 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.

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

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_required now skips registration when the processed model marked the row discarded (merged over the stale initial read), removing the register_recording-refused retry churn for intentional discards; expected_discarded=conversation.discarded at the fanout_claim stage is the right fence, since the finalizer already converts a non-claimed/completed/fenced status into ConversationFinalizationError('fanout_lease_conflict') — a restore racing the transaction retries on fresh durable state and registers the obligation.
  • backend/database/conversation_finalization_jobs.py — the expected_discarded guard returns lease_conflict with no job write before _conversation_admits_fanout runs, so a restored kept capture cannot be admitted or terminally fenced without its record_pending obligation; 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. the claim_fanout stubs around lines 1675–2060, all failing at stage=fanout_claim with TypeError: ... unexpected keyword argument 'expected_discarded'.
  • tests/unit/test_duplicate_capture_policy.py — 28 failures; the harness lambda stubbing claim_finalization_fanout hits 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 Git-on-my-level added the backend Backend Task (python) label Oct 30, 2026
@Dimank92

Copy link
Copy Markdown
Contributor Author

@Git-on-my-level Thank you for the detailed and spot-on review!

Addressed in commit a739893990:

  1. Updated stubs in backend/tests/unit/test_duplicate_capture_policy.py (lines 86-90, line 387) to accept *a, **kw.
  2. Updated stubs in backend/tests/unit/test_listen_finalization_cloud_tasks.py (lines 1673-1677, lines 1802-1806, lines 1857-1861, lines 2237-2241, lines 2299-2303, line 2381) to accept *args, **kwargs.
  3. Hardened backend/utils/conversations/finalizer.py with conversation_discarded = bool(getattr(conversation, 'discarded', False)) and conditioned claim_kwargs = {'expected_discarded': True} if conversation_discarded else {} so non-discarded flows preserve the original 3-positional call signature without passing empty/false kwargs.

Verified test suites locally:

  • backend/tests/unit/test_duplicate_capture_policy.py: 36/36 passed (0 failures).
  • backend/tests/unit/test_listen_finalization_cloud_tasks.py: 160/160 passed (0 failures).
  • backend/tests/unit/test_conversation_finalization_jobs.py & backend/tests/unit/test_record_finalizer_discard_registration.py: 65/65 passed (0 failures).

Ready for re-review!

@Git-on-my-level

Copy link
Copy Markdown
Member

Since my last review: addressed (the blocking test-suite breakage from the new expected_discarded keyword — all 8 harness stubs in test_listen_finalization_cloud_tasks.py and test_duplicate_capture_policy.py now accept **kwargs, and finalizer.py was hardened to omit the keyword entirely when the processed conversation is not discarded, which also covers untouched bare stubs like test_desktop_batch_only.py:447) · still open (an emulator-backed Firestore-transactional race regression, nice-to-have) · newly introduced (none).

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 a739893 in a hermetic container (no secrets): 418 passed / 0 failed across test_record_finalizer_discard_registration.py, test_conversation_finalization_jobs.py, test_duplicate_capture_policy.py, test_listen_finalization_cloud_tasks.py, and test_conversation_smart_merge_finalizer.py — the two previously red suites are green again.

Per-file notes:

  • backend/utils/conversations/finalizer.py — conversation_discarded = bool(getattr(conversation, 'discarded', False)) merged over the initial read is the right authority for registration, and claim_kwargs = {'expected_discarded': True} if conversation_discarded else {} is a nice hardening: non-discarded paths keep the exact old call shape, so assertion-style stubs (e.g. test_finalizer_fences_a_deleted_conversation_before_processing's assert_called_once_with('job-1', 2, 3)) stay valid.
  • backend/database/conversation_finalization_jobs.py — the expected_discarded guard returns lease_conflict with no job write before _conversation_admits_fanout runs, so a restored kept capture cannot be admitted or terminally fenced without its record_pending obligation; the not-a-Mapping branch split-out is behavior-preserving.
  • backend/utils/conversations/lifecycle.py — keyword-only pass-through wrapper, signature-compatible with all prior callers.
  • backend/docs/listen_pusher_pipeline.mdx — the new section accurately describes the implemented fence and retry semantics.
  • backend/tests/unit/test_record_finalizer_discard_registration.py — 4 cases covering persisted discard, stale-snapshot revival, silent discard, and the restore race with retry-through-lease_conflict; the attempt-0/attempt-1 structure in test_concurrent_restore_before_fanout_retries_and_retains_obligation mirrors the real retry path well.
  • backend/tests/unit/test_conversation_finalization_jobs.py — the lease_conflict test asserts no transaction writes on the conflict path, which is the important invariant.
  • backend/tests/unit/test_duplicate_capture_policy.py and backend/tests/unit/test_listen_finalization_cloud_tasks.py — mechanical **kwargs stub updates, correct.

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 expected_discarded fence, since the current tests simulate the race through the fake transaction harness.

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

@Git-on-my-level
Git-on-my-level dismissed their stale review October 31, 2026 18:06

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.

@Git-on-my-level Git-on-my-level added positive-signal Automation verified a genuine fix/quality contribution needs-maintainer-review Needs a human maintainer to sign off before merge labels Oct 31, 2026
@Dimank92
Dimank92 force-pushed the fix/issue-24110-restore-aware-discard-fence branch from a739893 to 6f83e3e Compare November 4, 2026 02:41

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

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 skips record_pending registration only when the row is actually discarded, and finalize_persisted_conversation (finalizer.py:454-455) merges the post-processing conversation.discarded into 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 new expected_discarded guard (conversation_finalization_jobs.py:1231-1232): if the finalizer processed the row as discarded but a concurrent restore persisted discarded: false before the fanout transaction, the claim returns lease_conflict and writes no terminal fence, so the job stays retryable. I traced the retry end-to-end: the finalizer raises fanout_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 the lease_conflict return 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.

@Dimank92
Dimank92 force-pushed the fix/issue-24110-restore-aware-discard-fence branch from 6f83e3e to 5c72460 Compare November 5, 2026 18:28
@Dimank92

Dimank92 commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

@Git-on-my-level Thank you for the review!

Addressed all blocking and review items in commit 5c724607b1:

  1. Line Endings: Re-saved backend/docs/listen_pusher_pipeline.mdx with strict LF line endings. The diff now cleanly shows only the 8 new lines for the "Restore-aware discard fence" section, eliminating the CRLF churn.
  2. Test Cleanup: Removed the commented-out # print("RUN FUNCTION:", ...) line in backend/tests/unit/test_record_finalizer_discard_registration.py.
  3. Rebase: Rebased cleanly onto the latest upstream/main (396b9c0c9d).

Branch is clean, conflict-free, and ready for maintainer merge!

@Git-on-my-level

Copy link
Copy Markdown
Member

Since my last review: addressed (the CRLF rewrite of backend/docs/listen_pusher_pipeline.mdx — verified on this head: zero stray CR bytes in the diff, the docs change is a single clean 8-line addition) · still open (none) · newly introduced (two typos in the new docs section, below).

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 5c7246:

  • backend/utils/conversations/finalizer.py — _record_registration_required (finalizer.py:236) now also requires not row.get('discarded'), and finalize_persisted_conversation (finalizer.py:466-472) merges the post-processing conversation.discarded into that decision before registering, so an intentional discard persisted during processing no longer causes register_recording-refused retry churn while a revival still registers the audio obligation. claim_kwargs (finalizer.py:489) passes expected_discarded only when the finalizer saw the row discarded.
  • backend/database/conversation_finalization_jobs.py — the expected_discarded guard (conversation_finalization_jobs.py:1408-1409) returns lease_conflict with no job write before _conversation_admits_fanout runs, so a concurrently restored capture is neither admitted without its record_pending obligation nor terminally fenced; the job stays retryable and the retry re-evaluates the restored state. The not-a-Mapping branch split-out is behavior-preserving.
  • backend/utils/conversations/lifecycle.py — clean pass-through of the new kwargs; existing callers unaffected via keyword defaults.
  • Tests — test_conversation_finalization_jobs.py asserts the lease_conflict return with no transaction update; the new test_record_finalizer_discard_registration.py covers both discard/revival flip directions, the silent-backfill fence, and the two-attempt restore race; the *args, **kwargs stub updates in test_duplicate_capture_policy.py and test_listen_finalization_cloud_tasks.py fix the earlier stub TypeError breakage. Note no backend CI workflow runs on this PR, so the 90/90 claim rests on local runs — worth a container re-run before merge.

One non-blocking nit: in the new docs section (backend/docs/listen_pusher_pipeline.mdx), two identifiers lost their leading "r" — the added lines read "registration (" then "egister_recording)" and "obligation (" then "ecord_pending)". Please restore register_recording and record_pending in a small follow-up commit.

Blast radius: batch_live_v1 finalization fanout only; other lanes and existing callers keep prior behavior via keyword defaults. Performance: the guard adds one field comparison inside the already-open fanout transaction — negligible.

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 batch_live_v1 finalization/recording-obligation path, and it is a first contribution to that surface.


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

@Git-on-my-level
Git-on-my-level dismissed their stale review November 5, 2026 21:35

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 Git-on-my-level added the ci:full Maintainer-granted: run full CI on this fork PR label Nov 7, 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.

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.py now passes expected_discarded=True to claim_finalization_fanout whenever the processed conversation was discarded. The claim stub in backend/tests/unit/test_process_conversation_free_tier_branch.py:881 is still def claim(*args):, so the three discarded_replay parametrizations of test_finalizer_summary_vector_requires_winning_claim fail with TypeError: ... 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 in test_listen_finalization_cloud_tasks.py and test_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 - the expected_discarded check sits after the missing/discarded/superseded terminal fences and before the claim write, so only an otherwise-current restored generation gets lease_conflict, and the retry path mutates nothing (your new tests assert transaction.updates == [], which matches the code).
  • backend/utils/conversations/finalizer.py - _record_registration_required gains a discarded exemption, and overlaying the processed conversation.discarded onto the initial read's archive/producer metadata keeps the registration decision consistent with the payload actually handed to register_recording.
  • backend/utils/conversations/lifecycle.py - keyword-only passthrough plus firestore_client injection 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, and run.py also 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.

Copy link
Copy Markdown
Member

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

Git-on-my-level added a commit that referenced this pull request Nov 8, 2026
…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)
@Git-on-my-level
Git-on-my-level merged commit 858175b into BasedHardware:main Nov 8, 2026
48 of 50 checks passed
@Dimank92
Dimank92 deleted the fix/issue-24110-restore-aware-discard-fence branch November 27, 2026 15:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) ci:full Maintainer-granted: run full CI on this fork PR needs-maintainer-review Needs a human maintainer to sign off before merge positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants