Skip to content

fix(backend): conversation cascade deletes no longer block on their own deletion gate - #24988

Merged
kodjima33 merged 4 commits into
mainfrom
fix/conversation-delete-self-gate
Nov 11, 2026
Merged

kodjima33 merged 4 commits into
mainfrom
fix/conversation-delete-self-gate

Conversation

@kodjima33

@kodjima33 kodjima33 commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

Problem (P0, privacy)

DELETE /v1/conversations/{id}?cascade=true answers 409 account_gate_busy for everyone. Prod (Cloud Run backend), 2026-11-09 09:00 to 11:35 UTC: 371 of 374 such DELETEs returned 409, 0 returned 204 (the other 3: 2×504, 1×401), across 31 client IPs and 186 distinct conversations. Memory deletes look the same: DELETE /v3/memories* since 06:00 UTC, 1487 of 1491 returned 409.

The route turns the gate exceptions into a 409 without logging, so these requests leave no traceback. The evidence below comes from Firestore and the code path:

  • legal_hold_deletion_gates (one doc per uid, read-only query): explicit_memory_deletion gates ending in failed (acquired, then the body raised) go from 0 on 2026-10-26 to 49 on 10-27 and 80–170/day since. Today: 80 failed vs 12 completed. Only 7 gates are running, so stale gates across accounts are not the cause.
  • 272 of the 371 conversation 409s return in under 0.2 s. These are retries hitting a gate held by the same account. About 99 run longer: those acquired the gate and failed inside the body.

Root cause: the request blocks on its own gate

  1. delete_conversation takes destructive_operation_gate(uid, kind='explicit_memory_deletion') for the whole cascade body. Introduced by fix(sync): prevent tombstone privacy stalls in owner projection #23783 (David Zhang, commits fe4499a + 1bba122, merged 2026-10-27 06:38 UTC). The analyst found the last normal success at 2026-10-27 16:57 UTC.
  2. Inside the body, delete_conversation_and_frame_evidence → delete_conversation_with_sync_sources → conversations_db.delete_conversation starts with speaker_auto_enroll.retract_conversation (feat(speakers): auto-enroll retained voices from explicit tags #23625, 2026-10-26), which runs external_write_fence(uid, transaction=...). delete_transcript_chunk_vectors is fenced the same way without a transaction (fix(dream): harden gate retries and minute headroom #22835, 2026-10-20).
  3. external_write_fence reads legal_hold_deletion_gates/{uid}, sees the request's own running gate, and raises DestructiveOperationInProgress: external data write blocked by destructive operation. The _EXTERNAL_TRANSACTION reuse only covers writes nested inside another transactional fence, not writes under a gate the request owns.

Effect: the tombstone is written and memories and action items are retracted, but the conversation doc, its vectors and its audio stay. The client retries and gets 409 every time. One Windows client retried 144 times.

Fix

external_write_fence now lets a write through only when the running gate is the one this context acquired: _ACTIVE_GATE == (uid, gate.kind, gate.token) and gate.uid == uid. Unchanged:

  • other requests (they have no _ACTIVE_GATE), other accounts, and a holder displaced by a stale takeover (its token no longer matches) are still blocked;
  • account deletion (account_deletions/{uid}) still blocks, including the gate owner;
  • a pass through the owner's own gate sees a running gate, so reusable stays false and the result is never cached for other writers;
  • canonical intake (assert_no_destructive_operation_transaction) stays strict even inside the owner's context. test_ws_j_delete_privacy::test_delete_all_final_rescan_tombstones_concurrent_write still proves an inline intake write is refused.

Tests

  • New: test_legal_holds.py::test_gate_owner_nested_writes_are_not_blocked_by_their_own_gate[False|True], …exemption_never_reaches_other_requests_or_accounts, …exemption_ends_after_peer_takeover_and_never_skips_account_deletion.
  • New, route level with the real gate on a fake Firestore: test_conversation_delete_wire_contract.py::test_cascade_delete_nested_fenced_writes_do_not_hit_their_own_gate. Before the fix it fails with 409 != 204. The existing wire tests replaced the gate with nullcontext(), which is why they never caught this.
  • Without the fix, the 3 new reproduction tests fail. With it, all 83 unit test files that reference the gate or fences pass (3128 tests).

Not proven

  • Which nested call blocks memory deletes (MemoryService.delete / delete_batch under _legal_hold_gated_deletion). The fix covers any nested external_write_fence in that path. If a memory-path self-block goes through assert_no_destructive_operation_transaction instead, this PR does not fix it. Check memory DELETE 409 rates after deploy.
  • Conversations left half-deleted between 2026-10-27 and the deploy (tombstoned but still stored) need a cleanup pass. Not in this PR.

Scope after review

This fixes cascade conversation deletes only. Memory deletes (routers/memories.py) never reach a nested external_write_fence; their 409s are tracked separately (likely #24886, which made stale memory-vector cleanup on read paths take the exclusive account gate). About 272 of the 371 conversation 409s sampled today fail before the delete body runs (gate acquisition), which this PR does not change; check the 204 rate after deploy.

Added after review: test_gate_owner_pass_is_never_cached_for_other_writers (privacy_ttl60 on): the owner passes its own fence, a writer in a fresh context still raises and re-reads live authority every time. It fails if the owner pass is made reusable (legal_holds.py:534).

Product invariants affected

none

Failure-Class: FC-destructive-gate-keyed-on-proxy-for-intent

UI-Evidence: none

🤖 Generated with Claude Code

View guided diff Turn on auto-fix

…r own deletion gate

Cascade conversation deletes acquire the account's explicit_memory_deletion
gate (#23783) and then run nested provider writes that each open
external_write_fence for the same uid (speaker auto-enroll retraction inside
conversations_db.delete_conversation, transcript-chunk vector delete). The
fence read the request's own running gate and raised
DestructiveOperationInProgress, so every cascade delete answered 409
account_gate_busy and left the conversation in place.

external_write_fence now lets through only the context that acquired the
running gate (same uid, kind and token). Other requests, other accounts, a
displaced holder after takeover, and account deletion still block, and
canonical intake (assert_no_destructive_operation_transaction) stays strict.

Failure-Class: FC-destructive-gate-keyed-on-proxy-for-intent

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@kodjima33 kodjima33 added the mux-proposal Mobile UX improver (MUX) proposal; waits for Nik's ship label Nov 9, 2026
@kodjima33 kodjima33 changed the title fix(backend): conversation and memory deletes no longer block on their own deletion gate fix(backend): conversation cascade deletes no longer block on their own deletion gate Nov 9, 2026
…te-self-gate

# Conflicts:
#	backend/tests/unit/test_privacy_ttl_cache.py
…te-self-gate

# Conflicts:
#	backend/tests/unit/test_conversation_delete_wire_contract.py
@kodjima33

Copy link
Copy Markdown
Collaborator Author

Auto-ship: SHIP review round 2 (Codex) on 4dcbfa7, CI green. Merging, then prod backend deploy and live delete check.

@kodjima33
kodjima33 merged commit 084128c into main Nov 11, 2026
61 of 62 checks passed
@kodjima33
kodjima33 deleted the fix/conversation-delete-self-gate branch November 11, 2026 18:43
kodjima33 added a commit that referenced this pull request Nov 12, 2026
…rn fast (#25124)

## Problem (P0, privacy)

After #24988 (Cloud Run `backend-084128c-43081136287-1`, 100%),
conversation deletes still mostly fail. Prod, 2026-11-11 since 19:00
UTC: 48 `DELETE /v1/conversations/{id}?cascade=true`, 45 × 409
`account_gate_busy` in 0.1-0.3 s, and only 3 × 204, which took 9.3 s,
31.8 s and 53.6 s. 2 of 17 user attempts (12%) ever got a 204.

Each delete holds the account-wide `legal_hold_deletion_gates/{uid}`
gate for tens of seconds. Every other delete from that phone
(multi-select, retries) gets an immediate 409 from
`_acquire_destructive_operation_transaction`. The app sends one DELETE,
treats anything except 204 as a failure, and times out reads after 30 s.

## Where the 9-366 s goes (evidence)

No per-step logs or traces exist (Cloud Run drops 2xx request logs, app
INFO is sampled, and there is no Cloud Trace bucket). The evidence is
the gate docs plus a profile of the real route.

**1. `record_deletion` → `purge_batch_owner(uid, conversation_id=…)`
(dominant, unbounded).** The per-conversation batch purge scans *every*
batch-pipeline row the owner has: 6 tables × 2 namespaces, pages of 100,
plus one point read per job. It runs again for every merge donor. The
gate's `started_at`→`finished_at` scales with the owner's batch-row
count (read-only Firestore; one gate doc per uid, latest op):

| owner batch rows | gate held |
|---|---|
| 237 | 9.1 s |
| 1,000 | 12.1 s |
| 1,683 | 23.2 s |
| 2,621 | 31.6 s (the 31.8 s 204) |
| 6,261 | 53.5 s (the 53.6 s 204) |
| 19,294 | 69.4 s |
| 34,438 | 366.1 s |
| 61,149 | 1,752.9 s (failed) |

Several of these accounts have 0 memories and 0 action items, so memory
retraction and the history scan are not the cost. This step came in with
#21674 (2026-10-15), and it got slower as batch history built up.

**2. `purge_chunks` (fixed cost).** It runs 128 sequential
single-document deletes on every delete, whether or not any chunk was
ever staged. That is 128 commits, a few seconds in prod. It explains why
deleting a *non-existent* conversation takes 9-12 s.

Firestore emulator profile of the real route (real tombstone writer,
batch purge, canonical retraction, lake and frame evidence; only
GCS/Pinecone stubbed):

| | owner batch rows | Firestore RPCs in request |
|---|---|---|
| before | 240 | 272 (purge 81, chunk slots 128) |
| before | 2,400 | 842 (purge 651, chunk slots 128) |
| after | 240 or 2,400 | **65** (constant) |

Memory retraction is 26 RPCs, and frame evidence + lake + document
delete is 22.

## Fix

- **Same-kind gate wait.** `destructive_operation_gate(...,
wait_seconds=)` retries acquisition with backoff (0.1→0.5 s) while a
*running gate of the same kind* holds the account. The conversation
delete route waits up to 20 s, then answers the existing 409 +
`Retry-After: 2`. A gate of another kind (account deletion, retention,
audio deletion), an active legal hold, or an unreadable gate still fails
at once. Every other caller keeps `wait_seconds=0` (fail-fast).
- **The request only arms a durable obligation.** Inside the route,
`record_deletion` writes `conversation_batch_purge_jobs/{opaque id}` in
the **same batch commit as the tombstone**. A retried delete re-arms it
and keeps the original tombstone. The obligation is written before any
fallible cleanup. **Producers never enqueue anything.**
- **The consumer side owns dispatch**
(`utils/conversations/deletion_batch_purge.py`). A leader-leased
reconcile loop runs at startup and every 60 s (registered in
`fsr_leader_lease`). It queries due obligations (single-field `due_at`,
registered query driver). It then probes the live handler URL without
credentials, and dispatches only if the new route answers with its own
403 (an old revision answers 404/405). Each dispatch is a **new
generation with a new task name** (`…-g<N>`), so a completed, deleted or
still-reserved name never swallows a redrive. The payload is opaque
(`job_id`, `generation`). Rollout order (backend before backend-sync)
and a backend-sync rollback can therefore only delay a purge, never
strand it. The deploy action is unchanged.
- **Runner (`database/conversation_batch_purge_jobs.run_job`)**, on
backend-sync via the `account-deletion` queue and the handler's own OIDC
audience.
- Each run owns the obligation through a unique `run_token` and a 300 s
lease. Every checkpoint and every destructive unit renews that lease in
a transaction that first proves `(generation, run_token)`. An expired,
superseded or duplicate execution therefore stops (`superseded`) before
its next erasure, even if its worker thread outlived the task deadline.
A duplicate delivery during a live lease gets `in_progress`.
- The run hands off at a 1,200 s budget (`checkpointed`, due at once,
`attempts` reset), well under the 1,500 s task deadline; the next
generation resumes from the saved position.
- A missing tombstone (account wiped) completes. An active hold is
answered `held`, rechecked after 1 h. A failure is retried by the queue,
and a lost generation is redriven after 10 min, doubling to 6 h; the
obligation is never dropped.
- Only the owning run may remove the obligation, and only when no
segment work is still recorded.
- **Resumable, phase-ordered purge
(`database/batch_pipeline_conversation_purge.py`).** `purge_batch_owner`
itself is unchanged (it is still used by the inline, account-wipe and
data-protection paths). The background path no longer calls it, because
it links artifacts and intakes through segment ids held only in memory,
after erasing the jobs/results that carry the link. The new pass:
1. `discover` (read-only): every matching job/result segment id is
persisted (content-free, under run ownership) before anything is erased;
2. `dependents`: artifacts/projections/intakes/shadow jobs matching the
conversation **or a persisted segment** are erased;
  3. `parked`: owner-id fallback artifacts, matched the same way;
4. `segments`: each persisted segment's job/result binding is erased
**last**, and its record is removed only after;
5. `shadow`: only in shadow mode (`BATCH_JOBSTORE_MODE` is unset in
prod).
The scan position is checkpointed per page with a name cursor that stays
valid after its row is erased, so a resume skips an already-scanned
prefix.
- **Authority, not a timer, decides when an erasure may still happen
(round 4).** A background unit holds the account gate through
`legal_holds.bounded_destructive_unit`, which yields a `UnitAuthority`:
- **Fenced Firestore erasures.** Every destructive commit (job unlink,
result erase, artifact metadata, dependent delete) calls
`authority.fence(transaction)` inside its own transaction. That
re-proves this unit's gate token and the absence of an active hold
(`assert_destructive_operation_transaction`). After a takeover or a
hold, the erasing commit fails rather than landing. The shared helpers
take an optional `fence`; existing callers are unchanged.
- **Remote (object) erasures keep the gate.** Before sending,
`authority.remote` transactionally marks the gate `remote_inflight`
(with its target), re-checking token and hold. `_gate_blocks` ignores
the unit's expiry while the mark is set, so neither a foreground
takeover nor the hold writer can proceed until the outcome is known.
- **Outcomes (round 5).** Any HTTP response to the original request, or
a call refused before sending, is definitive and clears the mark. With
no response at all, the same generation-pinned delete is re-issued
twice, and the mark settles **only on proof that the pinned generation
is gone**: the retry returns (deleted now, or 404 absent) or answers 412
(not that generation). A 503, 403, timeout or refused send proves
nothing about the earlier request, so the unit **does not release**
(fail closed). The obligation's next run settles a gate stuck for 60 s
or more by the same rule, under the stuck gate's own token. An
unresolved `remote_inflight` gate **blocks regardless of age**: no
expiry and no 6 h stale takeover. Every time it blocks past 6 h it logs
`event=destructive_gate_remote_unresolved` for ops.
- **Timers bound latency only.** Body RPCs on deadline-bound clients get
5 s with no SDK retry, the release the rest of 8 s, and Firestore-only
units expire at 10 s, which their fenced commits make safe.
`max_allowed_time` is gone: it raised only after a response had already
arrived.
- **Run budget before every unit and read (rounds 3-4).**
`_ensure_budget` runs before every unit, every page read, every
discovery point read and **every segment-binding read**. Every RPC of a
run, **from entry, including the admission transaction (`begin_run`)**,
inside or outside units (reads, queries, checkpoints, finalization), is
bounded by `entry + 1,200 s budget + 120 s` (< 1,500 s task deadline),
one attempt each, and admission time is debited from the budget (round
5). When it expires mid-page, nothing about that page is saved, so the
resume replays it from the previous cursor and no unprocessed match is
skipped. A run must save one step before it honours its budget, which
guarantees progress.
- **Foreground gate under contention (round 3).** Waiters poll on plain
lock-free reads; a transactional retry per poll locked the gate document
and slowed the holder's release. They retry with up to 100 ms jitter
once it reads free. The gate release retries transaction contention, so
a lost release can no longer pin the route's gate until it goes stale.
- **Gate wait under contention.** Inside the same bounded wait, the
conversation delete waiter also retries a gate transaction that
Firestore aborted for contention (`Failed to commit transaction…`),
instead of returning 500. Other errors and fail-fast callers are
unchanged.
- **Readiness fail-open is instrumented.** When the consumer probe
cannot answer (network), the reconciler still dispatches (the redrive
covers loss) and records `record_fallback(component='other',
from='verified_consumer_dispatch', to='unverified_dispatch',
outcome='degraded')`.
- **`purge_chunks`** commits its 128 slot deletes in one `WriteBatch`.
- **Cleanup script**
`backend/scripts/complete_half_deleted_conversations.py`. The default
dry-run only reads and prints counts. Without `--project` it scans
through the backend runtime's own client and prints that runtime's
bindings (Firestore project/database, data-plane project, Pinecone
index, `BUCKET_*`) plus a `runtime_digest`. `--execute` refuses
`--project`, refuses a missing or mismatched `--confirm-runtime
<digest>`, and refuses if the delete route resolves a different
Firestore project. All three refusals happen before any mutation. It
re-reads each tombstone in that plane right before running the route, is
rate-limited (`--max-per-minute`), and exits non-zero on failures. It
only counts batch-purge obligations; the reconciler owns them. **Not run
against prod.**
- **OpenAPI:** `POST /v1/conversations/deletion-batch-purges/run` is
listed in `UNDOCUMENTED_PUBLIC_ROUTES` as a service-OIDC Cloud Tasks
worker (`include_in_schema=False`). The public, app-client and
integration contracts are all current.

## Half-deleted conversations (dry-run, read-only, prod, tombstones
since 2026-10-27)

```
accounts_with_live_leftovers=1057
conversation_gone=14893
conversation_live=3679
conversation_soft_deleted=932
tombstones=19504
```

There are 3,679 conversations the user deleted that are still live
(3,392 completed `omi` source). By tombstone day: about 0/day from 10-28
to 11-03 (55 on 10-27, 17 on 11-01), then 290 on 11-04, 657 on 11-05,
and 338-575/day since. Soft-deleted rows (`deleted: true`) are counted
but never touched.

## Tests

- Round 5, one test per item, each failing on the previous head
`8f68971309`:
- `test_a_retry_503_does_not_settle_an_unanswered_delete`: the gate
stays held and the hold is rejected; only a delete/404 or 412 settles.
-
`test_unresolved_remote_gate_blocks_past_the_stale_bound_and_reports_it`:
at 7 h, hold, foreground and account-wipe acquisitions are all rejected,
and the event is logged.
-
`test_admission_is_inside_the_run_deadline_and_debited_from_the_budget`:
admission runs under the entry deadline (1,320 s), and the run is
expired at 1,200 s from entry.
- Real-transport emulator regression
`test_unanswered_delete_is_not_settled_by_a_retry_503_real_transport`:
the first DELETE is unanswered but lands later and the retries get 503.
The gate stays held, so no hold commits before the late erasure; the
next run settles only on 404.
- The reviewer's round-5 probes, run unchanged, now fail at their bug
points: 503 retries no longer settle (3 calls, gate held); the 6 h hold
is rejected; the run is expired at handler time 1,500 s.
- `tests/unit/test_conversation_batch_purge_authority.py` (16, rounds
4-5):
- An in-flight remote erasure keeps the gate past its expiry: a
foreground takeover fails, the hold writer is rejected, and authority
transfers only after the outcome is known.
- A fenced erasure fails inside its own transaction after a takeover or
under a hold, and a remote erasure is never sent once the gate is lost.
- An unknown outcome fails closed, then the next run settles it under
the same token, but only on a definitive answer.
- Outcome classification: HTTP response or refused-before-send is known;
timeout or reset is unknown.
- **The reviewer's segment-prefetch probe:** no read starts past the
budget, and the resume erases all 10.
- Every RPC of a run is bounded by the run deadline, which is < 1,500 s.
- `tests/unit/test_conversation_batch_purge_deadlines.py` (10),
`test_conversation_batch_purge_resumable.py` (12),
`test_conversation_delete_gate_wait.py` (42): earlier rounds, updated
for fences, authority and the bounded-caller retry rule.
- `tests/integration/test_conversation_batch_purge_emulator.py` (12,
Firestore emulator, real transactions, 3× green):
- **The reviewer's round-4 slow-response probe as a regression.** Real
`google-cloud-storage` SDK and requests transport over a loopback
socket; the response is still progressing past the unit's 10 s expiry. A
legal hold attempted mid-erasure is **rejected**, the foreground delete
gets **204 only after the erasure has landed**, and the hold can be
placed afterwards.
  - The round-3 real-SDK 503 probe still gives the foreground 204.
- Six parallel public deletes, holds between units, segment-only
artifact resume, real-cursor resume, and the account-wipe gate.
- **All three reviewer probes, run unchanged, now fail at their bug
assertions:**
  - round-4 expiry/hold: `erase_after_hold` is False;
  - round-4 segment budget: stops at 1,219 s, not 1,599 s;
  - round-3 storage retry: a bounded delete now sends `retry=None`.
- Also: the Firestore query guard set (re-pinned `run_job` digest), the
singleton-loop test, repo `scripts/typecheck.sh`, the scanners,
route-policy baseline, OpenAPI contract, and every backend unit file
referencing the touched modules (one process each).

## Not proven

- Prod latency after deploy. I expect about 65 Firestore RPCs plus a few
GCS/Pinecone calls, roughly 2-4 s per delete. The 20 s wait bounds
waiting only, so a 7th or later delete in one burst can still get a 409
(the app does not retry 409).
- Prod Cloud Tasks delivery to the new route, and the live-URL probe
from backend-sync.
- Fail-closed liveness: while GCS gives no definitive answer for an
unanswered delete, the user's deletes can 409 until the next run settles
the stuck gate. That takes at least 60 s; the next run comes from the
queue retry or a 10 min redrive, and it lasts as long as GCS keeps
answering 503. A gate that stays unresolved past 6 h logs
`event=destructive_gate_remote_unresolved`. Shadow mode
(`BATCH_JOBSTORE_MODE=shadow`, not set in prod) runs a Postgres owner
purge that is not deadline-bound.
- Queue sharing: `account-deletion` (4 concurrent dispatches) and the
4-thread `cleanup_executor` are shared with account wipes. Heavy purges
now hand off every 20 min instead of hogging a slot, but can still delay
(not drop) wipes. A dedicated queue is the follow-up.
- The waiter is not FIFO, and checkpoint hand-offs re-dispatch through
the 60 s reconciler (up to about a minute between runs).
- The 3,679 live leftovers are **not** cleaned; `--execute` on prod is
an operator decision.

## Product invariants affected

none. No product invariant governs conversation deletion or legal holds
today; the enforced privacy contract is the account gate in
`database/legal_holds.py`, which this change keeps on every irreversible
step (request cascade under the route gate, background erasure per
unit).

Line-Count-Exception: backend/routers/conversations.py | 2601 -> 2612 |
bounded gate wait constant and the deferral scope on the delete route;
dispatch logic lives in utils/conversations/deletion_batch_purge.py
Line-Count-Exception: backend/routers/users.py | 2759 -> 2793 | Cloud
Tasks handler sits next to the account-deletion wipe handler that shares
its queue and invoker; routers/users.py is the API_WORKERS mount that
backend-sync serves

Failure-Class: FC-bounded-read-exceeds-request-budget

UI-Evidence: none

🤖 Generated with [Claude Code](https://claude.com/claude-code)
kodjima33 added a commit that referenced this pull request Nov 13, 2026
…in order (#25197)

## What changed and why

P0, privacy. Since 2026-11-12 17:30 UTC prod logged 1,021 phone `DELETE
/v1/conversations/{id}?cascade=true`: 169 × 204 (median 4.8 s, p90 19 s)
and 848 × 409, 843 of them after the full ~20 s gate wait. Only 22.7% of
730 (client, conversation) attempts ever succeeded. One phone sent 53
deletes in the same second. Each delete holds the account gate for ~5 s,
so only ~4 fit in 20 s. The app treats anything but 204 as a failure and
never retries.

**Server (`fix(backend)`).** A cascade delete that finds a same-account
delete holding the account gate is now *accepted* instead of waiting:

- **One transaction** (`conversation_tombstones.accept_deletion`) does
three things. It writes the tombstone, keeping the original on a retry.
It marks the row `deleted: True`, so
list/get/search/count/chat-RAG/MCP/developer/shared reads drop it at
once through `is_visible_conversation`. It arms
`conversation_erasure_jobs/{opaque id}` with merge-donor ids read while
the row still exists. The route answers 204 right away and erases
nothing.
- **Free gate keeps the synchronous cascade** (live proof today: 204 in
2.1 s). "Busy" is decided by a lock-free gate read, or a
**single-attempt** acquisition (`max_attempts=1`). It is never decided
by Firestore SDK contention backoff: on the emulator that backoff made
all 53 requests of a burst wait 2.3 / 4.4 / 10.4 s.
- **Runner** (`run_erasure_job`, on backend-sync via the existing
`account-deletion` queue and handler, payload `kind: erasure`):
- It uses the same generation, lease and redrive machinery as #25124's
batch-purge obligations.
- It runs the request's own cascade (`erase_accepted_conversation`)
under the account gate, one at a time. That cascade also arms the batch
purge exactly as before.
  - It is fully idempotent on retry.
- Losing the gate to a same-account erasure is `busy`: due again in 30
s, no failure, attempts reset.
- **Reconciler** sends at most 6 erasures per account per pass and
spreads the rest over later passes. This keeps one account out of the
shared queue's 4 dispatch slots (prod `maxConcurrentDispatches: 4`). It
scans 4× wider so one account's backlog cannot hide other accounts.
- **Privacy precedence:**
  - A legal hold active at request time still rejects, as today.
- A hold placed after acceptance stops erasure (`held`, rechecked
hourly). The conversation stays hidden and retained.
- An account wipe supersedes: its gate makes the erasure fail and be
redriven, and once the tombstone is gone the obligation completes
without erasing.
- Another destructive kind holding the gate (wipe, retention, audio)
still answers 409 at request time. Nothing is written in that case.
- **Rollout safety.** Erasures live in a collection older code never
reads, under an id namespace distinct from batch purges. An older
consumer handed an erasure task answers `missing` and the reconciler
redrives it. An old runner therefore cannot run only the batch purge and
then delete an owed erasure. Rollout order or rollback can delay an
erasure but never drop it.
- Instrumented: `record_fallback(component='other',
from='synchronous_erasure', to='accepted_deferred_erasure',
outcome='degraded')` on every acceptance.
- `.github/firestore-collection-budgets.json`: planning-bound read
budget for `conversation_erasure_jobs` (25 reads/delete, 40k/day).

**App (`fix(app)`, separate commit).**
- `deleteConversationServer` retries a 409 after `Retry-After` (clamped
1-10 s, default 2 s) within a 30 s budget, and still succeeds only on
204.
- The provider sends server deletes one at a time in commit order. The
multi-select commit loop and the pending-delete timers used to fire them
all at once.
- A queued delete is dropped if the account changed before its turn.
- This covers old backends and transient contention.

Known gaps until an accepted delete's erasure finishes (normally ≤ 1-2
min, longer for a large burst):
- Memories and action items derived from the conversation stay visible.
- Two reads still count the soft-deleted row: the data-export photo
manifest and the MCP daily-summary `total_conversations`.

## Product invariants affected

none

## How it was verified

- Read-only prod checks:
- `gcloud run services describe backend|backend-sync`: both run image
83c5eaa with `ACCOUNT_DELETION_DISPATCH_MODE=cloud_tasks`, the
`account-deletion` queue, handler URL and invoker SA set. So
`accepts_conversation_deletes()` is true on `backend`.
- `gcloud tasks queues describe account-deletion`:
`maxConcurrentDispatches: 4`, `maxAttempts: 5`.
- Firestore emulator,
`tests/integration/test_conversation_batch_purge_emulator.py`: 14/14, 3
consecutive green runs. It uses real transactions and the real route,
gate, hold writer, accept writer, reconciler and runner.
- **53 same-second deletes:** all 204 in under 5 s. Every conversation
is tombstoned and hidden at once. After draining, all 53 are erased,
never two cascades inside the gate at once, and every erasure armed its
batch purge. An unrelated conversation is kept.
- **Hold placed after acceptance:** the runner answers `held`, and the
row is retained with `deleted: True`.
- **Slow-remote-erasure probe (updated):** while a batch-purge unit's
remote erasure is unresolved, the foreground delete of another
conversation is accepted, *not erased*. The hold that later lands wins.
- Unit: the 471 test files that reference the changed modules ran
file-isolated. All pass except `test_empty_capture_recovery.py`, which
needs native libopus that is not installed on this machine (unrelated).
Firestore query shapes/contract: 626 pass. Import-purity scans clean.
`scripts/typecheck.sh`: 0 errors. `make preflight`: pass.
- App: `flutter test` on the new retry test, the hub actions test (bulk
delete, one in flight at a time) and the pending-delete tests: 36 pass.
The helper agent ran a wider 1,157 pass, 2 skipped. `flutter analyze` on
touched files is clean, and `dart format` (3.44.5) made no changes.

**Not verified:**
- Not run on prod or any deployed environment. Nothing was deployed.
- No device run of the app change.

## Tests

- `backend/tests/unit/test_conversation_delete_accept.py` (13 tests), on
the real route, gate, accept writer, reconciler and runner:
- The 53-delete burst all return 204 quickly and all end erased,
serially. With acceptance disabled the same test fails: 5.9 s
serialized, and 409 behind a busy peer.
- A hold placed after acceptance, and a hold racing the eraser's gate,
both stop erasure. The row stays hidden and retained, and is erased
after release.
- Account deletion supersedes: the erasure is failed and kept, then
completes with `no_tombstone` and never erases.
- The reconciler redrives a lost task under a new task name. A
pre-erasure consumer answers `missing` and cannot drop it.
  - Busy gate → `busy` and retried soon.
  - A hold or account wipe at request time rejects and writes nothing.
  - A free gate keeps the synchronous cascade.
- Merge-donor audio recorded at acceptance survives a retry after the
row link is lost.
- Over the strict fixture, the accept transaction reads before it writes
and keeps the first tombstone.
  - The handler routes `kind: erasure`.
- Updated fakes in `test_conversation_delete_gate_wait.py` and
`test_conversation_tombstones.py` for the new collection, payload kind
and field mask. The emulator suite gains the burst and hold tests.
- `app/test/backend/http/conversation_delete_retry_test.dart` and
`app/test/widgets/conversation_hub_actions_test.dart`.

## Line-count exceptions

Line-Count-Exception: backend/routers/conversations.py | 2612 -> 2702 |
the accepted-delete eraser re-runs this router's own cascade
(_delete_conversation_under_gate) verbatim, so it lives beside it
Line-Count-Exception: backend/routers/users.py | 2793 -> 2804 | the
existing batch-purge task handler routes the new erasure payload kind
Line-Count-Exception: app/lib/backend/http/api/conversations.dart | 1494
-> 1524 | bounded 409 retry inside the existing delete call
Line-Count-Exception: app/lib/providers/conversation_provider.dart |
2294 -> 2313 | one-at-a-time server delete queue at the existing delete
site

## UI evidence

UI-Evidence: none -- no visual change; the app change only retries and
orders delete requests

## Failure class (fixes)

Failure-Class: new

## Failure-class transition narrative (only when needed)

New class `FC-user-intent-queued-behind-account-exclusive-work`.

- **Violated contract:** a user request whose intent can be recorded
durably must not wait behind, or be refused by, other same-account work
that an exclusive account gate serializes. #24988 and #25124 each
shortened the serialized delete. Bursts still produced a 409 wall that
the released client never retries.
- **Canonical guard:** commit the intent and a durable, leased
obligation in one transaction, answer at once, and let one owner do the
exclusive work in order while honouring holds and account deletion.
Decide "busy" from a lock-free read or a single-attempt acquisition.
- **Prevention artifact:**
`backend/tests/unit/test_conversation_delete_accept.py`. Evidence PRs:
#24988, #25124.

🤖 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/25197?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/25197?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25197&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

mux-proposal Mobile UX improver (MUX) proposal; waits for Nik's ship

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant