Skip to content

fix(backend): v3 audio purge invalidates record-WAL duplicate custody before erasing - #26294

Merged
Git-on-my-level merged 6 commits into
mainfrom
fix/v3-audio-purge-duplicate-custody
Nov 25, 2026
Merged

Git-on-my-level merged 6 commits into
mainfrom
fix/v3-audio-purge-duplicate-custody

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

Summary

Full review required. This changes a custody and privacy path: the v3 erasure (path E) now invalidates record-WAL duplicate custody and erases its intakes before it erases audio.

Path E is the conversations-v3-sweep audio purge. It runs after a user delete releases a recording's last claim, so it is a user-erasure path. Before this PR, E erased raw-live/ and audio-outbox/ but kept the recording row's wal_duplicate_* custody fields, the wal_duplicate_<file> and wal_duplicate_terminal_<job> intakes, and the alias. A direct user delete (path D) already runs purge_batch_owner before it erases audio. E did not.

The policy is already decided: the user's deletion outranks custody, as in D and in account deletion. E never keeps audio after the user deleted every derived conversation.

Change

  • claim_audio_purge (database/conversations_v3.py). It uses the same transaction and the same refusal predicate as before. When has_retained_custody(row) is true or wal_duplicate_merge_plan_v1 is present, the transaction clears wal_duplicate_settled_v1, wal_duplicate_retained_donors_v1, wal_duplicate_merge_target_v1 and wal_duplicate_merge_plan_v1. That happens in the same commit as deleted / v3_audio_erased and the tombstone. The same commit writes v3_audio_purge_intakes, which records that the intake purge is owed. Custody is gone after the first claim, so this marker is what keeps a retry owing the purge. When conversation batch-purge dispatch is configured, the commit also arms the same conversation_batch_purge_jobs obligation that record_deletion arms for D. The tombstone written in that commit is the obligation runner's deletion intent. The function returns an AudioPurgeClaim(custody_invalidated, intakes, donor_ids), or False as before.

  • service.purge_audio. Intake handling depends on claim.intakes:

    • inline: runs purge_batch_owner(uid, conversation_id=rid), the call record_deletion makes.
    • pending: raises AudioPurgeIntakesPending.
    • done: the armed obligation's owning run removed it.

    Any failure raises before delete_privacy_conversation_audio. (Review round 1 changes to this flow: see "Review round 1" below.) The existing sweep handler then keeps v3_audio_purge_pending and sets the 5-minute v3_audio_purge_retry_after. The blob delete never runs while the intake purge is unfinished.

  • Metric: omi_conversations_v3_audio_purges_total{outcome} with custody_invalidated, intakes_pending, intakes_failed and erased. The labels are static and pre-initialized.

  • Retention contract: audio-outbox/ is added to retain_until_user_deletes for omi-private-cloud-sync, with a matching test_retention_contract.py case.

  • Change note: backend/docs/listen_pusher_pipeline/changes/2026-11-25-v3-audio-purge-duplicate-custody.md.

Merge lineage

I traced record_wal_merge.publication (lines 72–94) and record_wal_handoff.check_owner_authority (lines 96–119), plus every other reader of the custody fields: live_upload, record_audio.fence_record_audio_removal, smart_merge, the v3 projection and sync assignment.

  • The purged row is a donor (SETTLED, MERGE_TARGET=S, and S lists it in RETAINED_DONORS). After the claim, the donor row is deleted, tombstoned and no longer SETTLED.

    • check_owner_authority sets retained only when SETTLED is True. Any later handoff or settlement on the donor raises HandoffConflict.
    • live_upload sees deleted without a MERGE_TARGET and returns OWNER_CONTEXT_MISMATCH.
    • If successor S is merged again, publication re-reads every inherited donor and raises RetainedMergeDeferred, because the donor is no longer SETTLED and is tombstoned. conversation_merge_jobs treats that as a logged deferral, not a failure.

    So S cannot read the erased donor audio through custody without a refusal. In addition, since review round 1, the claim removes the erased id from S's RETAINED_DONORS and sync_merged_from in the same transaction. Both lists drop the same id, so the equality plan_retention checks still holds, and no later delete or merge of S resolves the erased donor.

  • The purged row is a merge target that holds RETAINED_DONORS. Each donor's authority requires not successor.deleted, so after the claim every donor handoff is refused. Since review round 1, the donors are erased in full before the purge completes:

    • The claim commit writes each donor's tombstone and clears the donor's custody fields. With dispatch, it also arms the donor's own obligation.
    • The inline path runs purge_batch_owner(uid, conversation_id=donor) for each donor.
    • The blob step deletes the donors' canonical packs with the recording's (source_ids), then each donor's raw-live/, audio-outbox/ and record-wal/ prefixes (delete_conversation_audio_files).

    The donor ids stay on the row as v3_audio_purge_source_ids until the erase finishes, then the final update clears them. A donor whose merge target now names another conversation is skipped.

  • Settlement races the claim. Both transactions read and write the recording row, so Firestore serializes them.

    • A settlement that commits first is seen by the claim, which clears it, and its intakes are purged.
    • A settlement that commits after the claim is refused, because the row is deleted and tombstoned (BatchPrivacyBlocked).

    Both orders are proven against the Firestore emulator.

Reads and writes per sweep row

  • Every purged row: 1 legal-hold document read before the claim, and the blob phase's audio_conversation_deletion gate acquire and release (2 short transactions: 3 reads, 2 writes). Rows with canonical audio already paid that gate inside the storage helper, which now reuses it. The claim itself is unchanged for rows without custody: it reads the row and the tombstone, writes the tombstone if absent, and updates the row. The test asserts the exact row.
  • Custody rows, first sweep:
    • Claim: adds 1 obligation read, plus 1 successor read when the row is a donor. It writes the row update and, when absent, the tombstone. With dispatch configured it also writes the obligation, and when the row is a donor it updates the successor's lineage.
    • Inline mode: one account-gate acquire and release (2 short transactions), then one purge_batch_owner(rid). That is the same cost D pays per delete, bounded by PAGE_SIZE pages over 10 tables × 2 namespaces.
    • Deferred mode: the obligation runner pays that cost off the sweep.
  • Each retained donor (at most 16, MAX_RETAINED_DONORS):
    • 3 reads in the claim (row, tombstone, obligation).
    • Up to 3 writes, first claim only: tombstone, custody clear, obligation.
    • One purge_batch_owner(donor) and one delete_conversation_audio_files(donor). The second call lists the donor's prefixes and the user's raw-sync/ and raw-mobile-batch/ originals, as a user delete does.
  • Each retry (every 5 minutes while an obligation is pending, a hold is active, or a step failed): the same reads, plus the idempotent deletes in inline mode.

Expected cost: while RECORD_WAL_DUPLICATE_PERCENT is off, the only change is 1 hold read plus the audio gate per purged row (rows with canonical audio already paid the gate), because no row carries custody. After that, the extra cost is the per-custody-row and per-donor costs above. Only rows a user has deleted are affected.

Review round 1 (REQUEST CHANGES) dispositions

  1. P1 legal hold. purge_audio runs the queued runner's hold preflight (assert_account_deletion_permitted) before the claim and again before the blobs.
    • The inline purge_batch_owner calls run under legal_holds.destructive_operation_gate(uid, kind=conversation_batch_purge_jobs.GATE_KIND). That is the account gate a synchronous user delete holds around record_deletion, and its acquisition re-checks the hold transactionally.
    • I used the whole-operation gate, not the runner's bounded_destructive_unit, because purge_batch_owner is not split into units.
    • Under a hold nothing is deleted, the row stays pending, and the purge is counted as outcome="held".
    • Superseded in review round 2: the second preflight is replaced by one gate over the whole blob phase.
  2. P1 donor erasure. Covered in Merge lineage above. A partial failure leaves the pending bit and the donor list in place, and the retry repeats every idempotent step.
  3. P2 residual identifiers. The final update clears v3_audio_purge_source_ids. The successor lineage is removed in the claim transaction.
  4. P3 imports. conversation_batch_purge_jobs, batch_pipeline_purge, legal_holds, cloud_tasks and storage are module-level imports. Collection showed no cycle.

Review round 2 dispositions

  1. P1, the hold gate does not span every blob delete. Fixed. Every irreversible blob deletion now runs under one legal_holds.destructive_operation_gate(uid, kind='audio_conversation_deletion'): canonical packs, the recording's raw-live/, audio-outbox/, record-wal/ and other prefixes, and every donor's packs and prefixes. That is the kind the user-delete blob helper takes.
    • Gate semantics (database/legal_holds.py). Acquisition re-checks the hold in its transaction (_assert_hold_inactive). While a fresh gate is running, place_legal_hold raises DestructiveOperationInProgress. So a hold cannot be placed while the blob phase runs.
    • No duplicated logic. A nested destructive_operation_gate with the same uid and kind reuses the active token (_ACTIVE_GATE). The canonical step in delete_privacy_conversation_audio, and the merged_into link in delete_conversation_audio_files, therefore run under the outer gate and do not take a second one. The kind is the named constant service.AUDIO_GATE_KIND; storage.py is unchanged.
    • The remaining window is between the intake gate's release and the audio gate's acquisition. A hold placed there is read by the audio gate's acquisition transaction before any blob delete. The second point preflight is removed.
    • Tests.
      • test_no_hold_lands_between_canonical_and_prefix_deletes runs the real canonical helper. A hold attempted after the first canonical pack delete is refused, then the raw and donor prefix deletes run. Gate acquisitions are exactly one intake gate and one audio gate, so the helper nested. This test fails on the previous head.
      • test_hold_landing_after_the_intake_purge_stops_every_blob_delete: a hold placed as the intake gate releases. Result: no canonical, raw or donor delete, the row stays pending with its donors, and the purge is counted as held.
      • Every purge_world storage fake now asserts the audio gate is held.
  2. Moved-donor regression test. Added. test_moved_donor_is_not_erased_with_its_former_target: a donor whose wal_duplicate_merge_target_v1 names another target gets no tombstone, no custody clear, no intake purge and no prefix delete. Its row is byte-identical, and the other donor is still erased.

Follow-up, not changed here: path D has the same gap. The user conversation delete schedules delete_privacy_conversation_audio as a background task after the request's explicit_memory_deletion gate has released (routers/conversations.py _delete_conversation_under_gate, add_task(purge_audio, ...); erase_accepted_conversation runs it after with gate exits). The helper holds its audio gate only around the canonical packs. The raw prefixes, record-wal/ and the raw-sync/ and raw-mobile-batch/ originals are deleted after that gate releases, with no hold re-check. The same fix applies: run the helper's prefix deletes inside its gate.

Rollout and rollback

  • This change has no flag. It changes erasure correctness, and rows without custody are untouched.
  • Rollback: revert this PR. v3_audio_purge_intakes and v3_audio_purge_source_ids left on rows are inert to the old code. An armed obligation is still run by the existing reconciler.
  • This PR gates the first RECORD_WAL_DUPLICATE_PERCENT=1 step of SCA-3376. Do not ramp until this is merged and serving on backend-sync.

Test plan

Current head: ab5b3408 (round 3: the CI fix that writes the custody-clear and successor-lineage patches with explicit keys; no semantic change).

  • Round 3 (head ab5b3408, current):
    • bin/omi-heavy run of tests/unit/test_lifecycle_state_table_writers.py plus the eight focused files listed in round 2: 2358 passed.
    • Emulator test_record_wal_handoff_emulator.py: 37 passed.
    • The independent custody/privacy PASS (14:11Z, at fec6551f) was carried to ab5b3408 at 14:28Z after a recheck of _custody_clear, the lineage patch and the new key-pinning test.

Earlier rounds are historical. Each result below is tied to the SHA it ran on.

  • Round 2 (historical tests at commit fec6551f): bin/omi-heavy run -- .venv/bin/python -m pytest tests/unit/test_conversations_v3_transactions.py tests/unit/test_conversations_v3_review.py tests/unit/test_conversations_v3_backfill.py tests/unit/test_owner_storage_purge_and_gate.py tests/unit/test_record_wal_erasure.py tests/unit/test_retention_contract.py tests/unit/test_conversation_delete_wire_contract.py tests/unit/test_conversation_delete_gate_wait.py: 360 passed.
  • Round 1 (historical tests at commit df2357a7): bin/omi-heavy run -- .venv/bin/python -m pytest tests/unit/test_conversations_v3_transactions.py tests/unit/test_conversations_v3_review.py: 142 passed. tests/unit/test_conversations_v3_backfill.py: 66 passed. The new and updated cases are:
    • (a) Each of the four custody fields: fields cleared, intakes purged before the erase, custody_invalidated incremented, and donors purged, passed as source_ids and prefix-erased.
    • (b) No custody: the row is exactly as before, with no intake purge and no obligation.
    • (c) The intake purge fails: no blob delete, the row stays pending, and the retry purges before it erases. intakes_failed is counted.
    • Deferred mode: the recording's and the donor's obligations are armed in the claim commit, and the erase waits until both are gone.
    • Hold active before the claim: nothing is deleted or written, and held is counted. Hold placed after the claim: the real account gate refuses, so there is no WAL, intake or blob deletion, and the row stays owed.
    • Round 2: a hold attempted between the canonical and prefix deletes is refused by the audio gate. A hold placed after the intake gate stops every blob delete. A moved donor is skipped.
    • A merge target with two donors erases both donors' intakes and prefixes and their tombstones are written. A partial failure (donor intake, or donor prefix) retries without completing.
    • The blob delete raises: the pending bit stays set and the next sweep completes.
    • An erased donor leaves its successor's lineage.
  • (d) Emulator: firebase emulators:exec --project demo-omi-unit --only firestore 'GOOGLE_CLOUD_PROJECT=demo-omi-unit pytest tests/unit/test_record_wal_handoff_emulator.py', 37 passed (historical; re-run at round 2 on fec6551f, and passed again at round 3 on ab5b3408). The tests cover settle_then_purge and purge_then_settle. A new claim test checks the donor commit on real Firestore field-delete semantics: donor tombstones, the donor custody clear, the successor lineage, and a retry that keeps the donors.
  • Not verified: no deployed or live run. GCS deletes are exercised through fakes only. The gate race is proven on the strict in-memory Firestore fake with the real legal_holds code, not on the emulator.

Line count

Line-Count-Exception: backend/database/conversations_v3.py | 1506 -> 1632 | the custody clear (with explicit keys for the terminal-writer ratchet), donor intents, successor lineage and obligation arms must commit inside claim_audio_purge's existing transaction, next to release_claims; moving the purge claim out is a separate refactor

Product invariants affected

none

Failure class (fixes)

Failure-Class: none

🤖 Generated with Claude Code

Git-on-my-level and others added 2 commits November 25, 2026 07:27
… before erasing

The conversations-v3-sweep purge (path E) erased a released recording's audio
but left the wal_duplicate_* custody fields and the duplicate intakes. The
claim now clears custody in the commit that closes the owner, records the owed
intake purge, and the sweep erases intakes (inline or through the armed
conversation batch-purge obligation) before any blob delete.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-25T14:28:10.539816Z ab5b340 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 260ec9642b

ℹ️ 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".

Comment thread backend/database/conversations_v3.py Outdated
intakes are owed erasure (arming the obligation when ``defer_intake_purge``).
Returns False when the row is not purgeable, else an ``AudioPurgeClaim``.
"""
from database.conversation_batch_purge_jobs import arm_fields, job_ref

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Move the new function-local imports to module scope

The import here, along with the newly added imports inside service.purge_audio and the new tests, violates the explicit backend/AGENTS.md requirement: “All imports at module top level — never inside functions.” Move these new imports to their respective module import sections, retaining lazy client construction where necessary.

AGENTS.md reference: backend/AGENTS.md:L168-L174

Useful? React with 👍 / 👎.


# The same per-conversation purge a user delete runs (record_deletion); the claim wrote its tombstone.
try:
purge_batch_owner(uid, conversation_id=rid)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Acquire deletion authority before purging intakes inline

When batch-purge dispatch is disabled and a legal hold lands after the user's deletion but before the sweep, this call erases held data without acquiring the account's destructive-operation gate. purge_batch_owner immediately calls purge_record_wal_owner, which deletes every record-wal/<uid>/<rid>/ object generation, and then removes batch metadata; neither helper checks legal holds. With BUCKET_CANONICAL_AUDIO configured, the previous path reached delete_privacy_conversation_audio first and its destructive_operation_gate rejected the hold before erasing audio. The new ordering deletes WAL audio before that rejection, whereas the deferred obligation runner explicitly checks holds and gates destructive units. Acquire and retain deletion authority around the inline purge rather than relying on the later blob-deletion gate.

Useful? React with 👍 / 👎.

Git-on-my-level and others added 2 commits November 25, 2026 08:15
…ed donors

Review findings on the inline intake purge and merge-target erasure:

- Legal hold: purge_audio runs the obligation runner's hold preflight
  (assert_account_deletion_permitted) before the claim and again before the
  blobs, and runs the inline purge_batch_owner calls under the account gate
  a synchronous user delete holds (destructive_operation_gate, GATE_KIND),
  whose acquisition re-checks the hold. A held purge deletes nothing, stays
  pending and is counted as outcome="held".
- Donors: the claim writes each retained donor's tombstone, clears its
  custody and arms its obligation (dispatch mode) in the same commit. The
  inline path purges each donor's batch owner; the blob step deletes each
  donor's raw-live/, audio-outbox/ and record-wal/ prefixes after the
  canonical packs. A failure anywhere leaves the pending bit set.
- Residual ids: the final update clears v3_audio_purge_source_ids, and an
  erased donor is removed from its successor's retained donors and
  sync_merged_from in the claim transaction.
- Imports: the function-local imports move to module level.

Tests: hold before and after the claim, two-donor erasure, partial donor
failure retry, blob-delete fault retry, successor lineage; emulator proof of
the claim's donor commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Review round 1 dispositions. Code is in 448b45e; the changes note and PR body are in df2357a.

  1. P1 legal hold: fixed (448b45e).
    • purge_audio runs the queued runner's preflight, assert_account_deletion_permitted, before the claim and again before the blobs.
    • The inline purge_batch_owner calls run inside legal_holds.destructive_operation_gate(uid, kind=conversation_batch_purge_jobs.GATE_KIND). A synchronous user delete holds this same gate around record_deletion, and acquiring it re-checks the hold in a transaction. I did not write a new gate.
    • I used the whole-operation gate rather than the runner's bounded_destructive_unit, because purge_batch_owner is not split into units.
    • Under a hold nothing is deleted, the row stays pending, and the purge counts as outcome="held".
    • The canonical-pack delete inside delete_privacy_conversation_audio takes its own audio_conversation_deletion gate, so the blob step cannot nest inside the intake gate. The second preflight covers that step.
    • Tests: with a hold placed before the claim, nothing is written or deleted. With a hold placed after the claim, the real gate on the strict client refuses, so there is no WAL, intake or blob delete, and the row stays owed.
  2. P1 donor erasure: fixed (448b45e).
    • In the claim commit: each retained donor gets a tombstone (purge_batch_owner requires one, and handoff refuses a tombstoned donor). The donor's custody fields are cleared. With dispatch, the donor's own obligation is armed.
    • Inline path: purge_batch_owner(uid, conversation_id=donor) runs for each donor under the same gate.
    • Blob step: the canonical packs go through source_ids, then delete_conversation_audio_files(uid, donor) erases each donor's raw-live/, audio-outbox/ and record-wal/ prefixes.
    • The pending bit clears last, and every step is idempotent.
    • Tests: a two-donor erase; partial failures at a donor's intake purge and at a donor's prefix delete, each retried without marking complete; deferred mode waits on both obligations. An emulator test proves the donor commit on real Firestore.
  3. P2 residual identifiers: fixed (448b45e). The final update clears v3_audio_purge_source_ids. When the erased row is a donor, the claim transaction removes its id from the successor's wal_duplicate_retained_donors_v1 and sync_merged_from. Both lists drop the same id, so plan_retention's equality check still holds. Covered by unit and emulator tests.
  4. P3 imports: fixed (448b45e). All the new imports are module-level, and so is the existing storage one. No cycle showed up in test collection.

Also added: a blob-delete fault-injection test. The pending bit stays set and the next sweep completes.

I updated the per-row cost in the PR body and the changes note. Every purged row now pays 2 hold reads, and each donor adds 3 claim reads, up to 3 writes, one purge_batch_owner and one prefix erase.

Tests:

  • test_conversations_v3_transactions.py + test_conversations_v3_review.py: 142 passed.
  • test_conversations_v3_backfill.py: 66 passed.
  • test_record_wal_handoff_emulator.py under the Firestore emulator: 37 passed.

Not verified: no live or deployed run; the GCS deletes are exercised through fakes only.

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

VERDICT: REQUEST CHANGES — independently reviewed df2357a7cce4264376750d9706e61bee02800768.

P1 — legal hold can become active before prefix erasure completes. The second _assert_erasure_permitted is a point preflight. delete_privacy_conversation_audio gates canonical pack deletion only, then releases the gate before delete_conversation_audio_files sweeps derived prefixes; donor prefix sweeps are also outside a gate. A hold can be committed after the preflight / canonical gate release and before those prefix deletes, allowing raw-live/, audio-outbox/, and record-wal/ objects to be erased while the hold is active. This affects inline purge and queued purge after its intake obligations finish. Keep a legal-hold gate active across every irreversible blob deletion, including donor prefixes, and add deterministic race coverage for a hold placed between canonical and prefix deletion.

The earlier inline-intake P1 is fixed: intake deletion runs behind the account gate, and queued deletion waits on per-owner obligations. Donor custody fields and successor arrays are cleaned, donor prefixes including record-wal/ are included, and intake/blob failures keep the purge pending for retry. Focused local backend suites passed through bin/omi-heavy; the Firestore loopback emulator suite passed 37 tests. Same-head CI still has pending backend shards and emulator proofs; no live GCS evidence was available.

GitHub rejected a formal REQUEST_CHANGES review because the authenticated reviewer is the PR author, so this review comment records the request-changes verdict instead.

if claim.donor_ids:
# A merge target's retained donors served only this recording, as a user delete erases them:
# their canonical packs with the recording's, then each donor's own prefixes.
storage.delete_privacy_conversation_audio(uid, rid, source_ids=list(claim.donor_ids))

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is where the unfenced prefix phase starts. The preflight above is only a point read; storage gates canonical packs but releases that gate before deleting these prefixes, and the donor sweeps below are ungated. A hold can land between phases and the remaining prefixes are still erased. Keep a legal-hold gate across canonical, owner-prefix, and donor-prefix deletion; cover this gap with a hold-race test.

…donor test

The v3 sweep's blob phase (canonical packs, raw prefixes, donor packs and
prefixes) now runs under one audio_conversation_deletion account gate. Its
acquisition re-checks the legal hold and place_legal_hold refuses while it
runs, so no hold lands between the canonical and prefix deletes. The storage
helpers' gate nests in it. Adds the hold-race tests and a moved-donor test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Review round 2 dispositions. Fix commit: fec6551f8e1de0bca585f4015c8677f6c2aee0a2 (on top of df2357a7).

1. P1, the hold gate does not span every irreversible blob delete. Fixed in fec6551f.

  • service.purge_audio now runs the whole blob phase under one legal_holds.destructive_operation_gate(uid, kind='audio_conversation_deletion'): canonical packs, the recording's raw prefixes, and every donor's packs and prefixes. That is the kind the user-delete blob helper takes. The second point preflight is removed.
  • Gate semantics, read from database/legal_holds.py:
    • Acquisition re-checks the hold transactionally.
    • place_legal_hold raises DestructiveOperationInProgress while a fresh gate runs, so the gate excludes hold creation.
    • A nested gate with the same uid and kind reuses the active token. delete_privacy_conversation_audio's canonical step therefore runs under the outer gate with no second acquire. No parameter or duplicated logic was needed, and storage.py is unchanged.
  • Tests:
    • test_no_hold_lands_between_canonical_and_prefix_deletes runs the real canonical helper. A hold attempted after the first pack delete is refused, then the raw and donor prefixes are deleted. Exactly two gate acquisitions occur (intake, audio). This test fails on df2357a7.
    • test_hold_landing_after_the_intake_purge_stops_every_blob_delete: a hold placed as the intake gate releases. Result: no canonical, raw or donor delete, the row stays pending with its donors, and the purge is counted as held.
    • All purge_world storage fakes now assert the audio gate is held.

2. Moved-donor regression test. Added in fec6551f. test_moved_donor_is_not_erased_with_its_former_target: there is no tombstone, no custody clear, no intake purge and no prefix delete for the moved donor, and its row is unchanged. The other donor is still erased.

Path D has the same gap, and it is not changed here. The user delete runs delete_privacy_conversation_audio as a background task after the request's explicit_memory_deletion gate releases (routers/conversations.py, add_task(purge_audio, …); erase_accepted_conversation runs it after with gate exits). The helper holds its audio gate only around the canonical packs, so the raw, record-wal/ and raw-sync//raw-mobile-batch/ deletes run with no hold re-check. It is listed as a follow-up in the PR body.

Verification

  • Unit tests: bin/omi-heavy run -- .venv/bin/python -m pytest over test_conversations_v3_transactions, _review, _backfill, test_owner_storage_purge_and_gate, test_record_wal_erasure, test_retention_contract, test_conversation_delete_wire_contract and test_conversation_delete_gate_wait: 360 passed.
  • Emulator: test_record_wal_handoff_emulator.py, 37 passed.
  • The pre-push gate passed.
  • Not verified: no deployed run, and GCS is exercised through fakes only.

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

VERDICT: PASS — re-reviewed PR #26294 at fec6551f8e1de0bca585f4015c8677f6c2aee0a2; no blocking findings remain in this PR’s custody/privacy scope.

The hold race is closed: after intake work, one audio_conversation_deletion gate spans canonical packs, the recording’s raw prefixes, and each donor’s packs and prefixes. The gate acquisition rechecks legal-hold authority transactionally; the nested storage helper reuses the same uid/kind gate. A hold after intake completion stops all blob deletion. The moved-donor case preserves a donor whose current merge target is elsewhere. This PR leaves the separate conversation-delete path D unchanged, as tracked in SCA-4363.

Local verification on M1 through bin/omi-heavy: eight focused unit files completed successfully; the three added hold/moved-donor tests passed; Firestore loopback emulator suite passed 37 tests. Same-head CI is still running. No live GCS behavior or production serving-writer fence evidence was established here; keep 1% and shadow dark pending Release’s evidence and written go-ahead.

GitHub identifies the authenticated reviewer as the PR author, so this SHA-anchored COMMENT records the PASS verdict instead of a formal approval.

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

VERDICT: PASS — independent custody/privacy re-review of fec6551f8e1de0bca585f4015c8677f6c2aee0a2; no blocking findings remain in the requested Path E purge scope.

One audio_conversation_deletion gate now spans the canonical packs, the recording’s raw prefixes, and every retained donor’s packs and prefixes. Its acquisition revalidates the legal hold transactionally; storage’s nested canonical gate reuses the same uid/kind gate. In inline flow, a hold attempted between canonical and prefix deletion is refused while the gate runs. After inline or queued intake work, a hold already placed prevents audio-gate acquisition and all blob deletes. The moved-donor case is preserved under the new target.

M1 verification through bin/omi-heavy: eight focused unit files completed successfully; the three hold-window/moved-donor regressions passed; Firestore loopback emulator suite passed 37 tests. Same-head CI still has backend shards and emulator checks pending. Path D remains out of scope and tracked in SCA-4363. No production serving-writer fence evidence or matched readback was established; keep 1% and shadow dark pending Release’s evidence, preflight, and written go-ahead.

GitHub identifies the authenticated reviewer as the PR author, so this SHA-anchored COMMENT records the PASS verdict rather than a formal approval.

…iter ratchet

The terminal-writer ratchet flagged claim_audio_purge.claim as a new
terminal conversation status writer. Its three new patches (the donor
custody clear, the successor lineage update and the owner custody clear)
were dict comprehensions, which the scanner conservatively treats as
opaque because generated keys could restore `status`. None of them writes
`status`: their keys are only the four record-WAL custody fields and
`sync_merged_from`.

Fix choice (a), not an allowlist entry: build the same patches with
fixed, explicit keys (`_custody_clear` and an explicit lineage dict),
so the scanner sees the real key set. The stored result is unchanged:
the same fields are deleted under the same presence conditions, and
the same lineage lists are filtered under the same membership checks.
The write order and reads are unchanged too. A unit test pins
_custody_clear's keys to AUDIO_PURGE_CUSTODY_FIELDS.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Fix for the Backend unit shard 3/8 failure (test_terminal_status_writers_match_strict_owner_allowlist[database/conversations_v3.py]), pushed as ab5b340.

Cause. claim_audio_purge.claim writes no conversation status. Its three new patches were dict comprehensions: the donor custody clear, the successor lineage update and the owner custody clear. The terminal-writer scanner treats any comprehension-built conversation payload as opaque, because generated keys could carry status.

Fix: option (a), no allowlist entry and no routing through claim_conversation_status_in_txn. No terminal status write exists, so neither of those fits. The same patches are now built with explicit keys:

  • _custody_clear(row) holds a literal dict of the four custody fields (SETTLED_FIELD, RETAINED_DONORS_FIELD, MERGE_TARGET_FIELD, MERGE_PLAN_FIELD). It drops the ones the row lacks.
  • The successor lineage is built with one explicit if rid in ... assignment each for RETAINED_DONORS_FIELD and sync_merged_from.

The scanner now resolves the real key set and inventories only commit_projection.commit in this file. The ratchet logic and allowlist are unchanged.

Semantics are unchanged. The same fields are deleted under the same per-field presence check, and the same lineage lists are filtered under the same membership check. The reads, write order, transaction and return value are all the same. A new unit test pins _custody_clear's keys to AUDIO_PURGE_CUSTODY_FIELDS. The PR body's Line-Count-Exception is updated to 1506 -> 1632.

Verification (local, lane worktree at ab5b340):

  • test_lifecycle_state_table_writers plus the eight focused files: 2358 passed.
  • test_record_wal_handoff_emulator on the Firestore emulator: 37 passed.
  • The pre-push gate passed with this PR body.

Other checks at fec6551. Backend unit suite failed only because it aggregates shard 3. Backend emulator proofs passed.

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

VERDICT: PASS — narrow exact-head re-review of ab5b34080f7d71b0181436cb1b0b5c0e0cbedab0. The PASS on fec6551f8e1de0bca585f4015c8677f6c2aee0a2 carries to this SHA as a mechanical delta.

_custody_clear spells out the same four custody fields, removes only keys absent from the row, and is used at the same donor and recording transaction writes as before. The two explicit lineage branches preserve the prior membership conditions, list filtering, and update order. No status field is written. The added test pins the helper’s key set to AUDIO_PURGE_CUSTODY_FIELDS.

Verification through bin/omi-heavy: test_lifecycle_state_table_writers.py passed (1,997 tests); the focused conversations_v3_transactions.py suite completed successfully, including the helper test (also run directly: 1 passed); Firestore loopback emulator suite passed 37 tests. Same-head CI is rerunning per handoff.

GitHub identifies the authenticated reviewer as the PR author, so this SHA-anchored COMMENT records the verdict instead of a formal approval.

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

VERDICT: PASS carries to current head ab5b34080f7d71b0181436cb1b0b5c0e0cbedab0 as a mechanical delta. I rechecked only _custody_clear, the successor-lineage patch, and the added test. _custody_clear deletes the same four custody fields only when present; its application sites and transaction order are unchanged. The explicit lineage branches preserve the earlier membership checks, filtering, and update order. The test pins the key set, and no status field is written.

Disposition of the older open/outdated GitHub threads, as requested by Release: the imports are now at module scope; inline intake deletion runs under the account destructive-operation gate (queued work uses bounded gated units); and the prefix-deletion race is closed by the single audio gate spanning canonical, row, and donor deletes. These findings are addressed in code, though the old GitHub threads remain open/outdated.

At this SHA, focused local checks passed: lifecycle writer ratchet 1,997 passed; custody transaction checks passed; emulator 37 passed. CI is still rerunning. GitHub identifies the authenticated reviewer as PR author, so this COMMENT records the exact-head verdict rather than a formal approval.

@Git-on-my-level
Git-on-my-level merged commit 23b2faa into main Nov 25, 2026
78 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/v3-audio-purge-duplicate-custody branch November 25, 2026 16:50
Git-on-my-level added a commit that referenced this pull request Nov 26, 2026
…#26329)

## What

Adds `omi_conversations_v3_audio_purges_total` to the backend-sync Cloud
Run GMP sidecar's explicit metric allow-list
(`backend/deploy/cloud_run_gmp_sync.yaml`), and pins it with a scrape
test.

## Why

The Path E v3 audio purge (#26294) runs on backend-sync as well as
backend. `utils/conversations/v3/metrics.py` pre-creates all five
`outcome` series at import, but the sync sidecar keeps an explicit
`omi_conversations_v3_*` list instead of `omi_.*`, and that list omitted
this counter. During the 2026-11-25 Sync canary of `6e3204f2`, GMP
returned the series only for `service_name="backend"` (85 series) and
nothing for backend-sync. "No series" on Sync cannot be told apart from
a purge path that never ran (SCA-3376).

The backend sidecar (`cloud_run_gmp_sidecar.yaml`) keeps `omi_.*` and is
unchanged.

Failure-Class: FC-metric-dropped-by-scrape-allowlist

## Tests

- New `tests/unit/test_v3_audio_purge_metric_is_scraped.py`. It fails on
the unfixed allow-list and passes with the fix: 1 failed / 2 passed
before, 3 passed after.
- Ran with the related scrape and sidecar suites
(`test_projection_finish_guard_metrics_are_scraped.py`,
`test_attach_cloud_run_gmp_sidecar.py`,
`test_monitoring_telemetry_contract.py`): 186 passed.

## Rollback

Revert this commit. It changes observability only, with no runtime or
behaviour change. It takes effect on the next backend-sync deploy.

🤖 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/26329?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>
<a
href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/26329?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F26329&source=description"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img
alt="Turn on auto-fix"
src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
Git-on-my-level added a commit that referenced this pull request Nov 27, 2026
…s (SCA-4363) (#26316)

## What changed and why

SCA-4363 holds one `audio_conversation_deletion` gate across canonical
pack erasure and every conversation audio prefix delete. Both the
post-response cleanup and the accepted-delete worker use the shared
helper, including when the canonical bucket is disabled. This applies
the gate pattern from [the v3 purge
fix](#26294).

If a hold arrives between the request and audio gates, post-response
cleanup records a durable erasure job and marks the tombstone for
hold-release follow-up. The worker preserves merge donor IDs and retries
after release. A worker that claimed the job before the donor IDs were
recorded leaves it queued for another pass.

Full review requested for the custody and privacy change. No rollout
flag is required. Roll back by reverting the PR.

## Product invariants affected

none

## How it was verified

202 tests passed on M1 in six focused backend suites, run in separate
pytest processes through `omi-heavy` with a 180-second timeout. The
suites cover accepted deletes, storage purge, record WAL erasure, v3
transactions, delete gate waits, and the delete wire contract. The
regression exercises the actual FastAPI delete route with hermetic
storage and Firestore interfaces. Production Backend serving
verification is pending release.

`make preflight` passed with this PR body supplied. The local
failure-class history check skipped its 90-day scan because the managed
checkout is shallow.

## Tests

`test_delete_holds_one_audio_gate_through_every_blob_delete` attempts
hold placement just before the first prefix delete. It checks every blob
delete uses the same running gate token and covers both route cleanup
and accepted erasure with canonical storage on and off. The
accepted-delete cases reproduced the missing protection on the original
code.

The follow-up passed 257 focused backend tests on an Apple M1 Max
through `omi-heavy`. The deterministic test reaches the FastAPI delete
route, places the hold after the request gate, verifies that no audio is
deleted while held, and exercises the release scan and erasure retry. A
second test verifies that completion preserves donor IDs added after a
worker has claimed the job.

Run from `backend/` on M1:

```sh
omi-heavy run --wait 120 --timeout 120 -- .venv/bin/python -m pytest -q tests/unit/test_conversation_delete_accept.py -k 'hold_between_request_and_response_audio_gates or completion_keeps_donors'
```

Line-Count-Exception: backend/routers/conversations.py | 3203 -> 3208 |
Handle legal-hold refusal at the post-response cleanup boundary.

## UI evidence

UI-Evidence: none -- backend-only legal-hold change

## Failure class (fixes)

Failure-Class: none


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/26316?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>
<a
href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/26316?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F26316&source=description"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img
alt="Turn on auto-fix"
src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant