Skip to content

fix(backend): conversation deletes wait for the account gate and return fast - #25124

Merged
kodjima33 merged 6 commits into
mainfrom
fix/conversation-delete-serialize
Nov 12, 2026
Merged

kodjima33 merged 6 commits into
mainfrom
fix/conversation-delete-serialize

Conversation

@kodjima33

@kodjima33 kodjima33 commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

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

…rn fast

A cascade delete held the account-wide destructive gate for 9-366 s because
record_deletion ran purge_batch_owner(uid, conversation_id), which scans every
batch-pipeline row the owner has, plus 128 sequential chunk-slot deletes. Every
other delete from the same phone got an immediate 409.

- destructive_operation_gate(wait_seconds=) waits (bounded, backoff) behind a
  running gate of the same kind; other kinds, legal holds and unreadable gates
  still fail fast. The conversation delete route waits up to 20 s.
- The per-conversation batch purge leaves the request path: record_deletion
  marks batch_purge_pending on the tombstone and the route enqueues a named
  Cloud Task on the account-deletion queue; backend-sync runs it via
  POST /v1/conversations/deletion-batch-purges/run (legal-hold checked,
  idempotent, retried). Enqueue failure falls back to the inline purge.
- purge_chunks commits its 128 slot deletes in one batch.
- scripts/complete_half_deleted_conversations.py counts (default) or completes
  tombstoned conversations whose document still exists, via the route.

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

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 11, 2026
…nsumer-dispatched

Review round 1 on #25124:
- Erasure runs in per-page units under the account destructive-operation gate
  (purge_batch_owner unit_guard), so a legal hold or account wipe that commits
  mid-scan stops the next unit; the scan itself holds nothing.
- A delete arms conversation_batch_purge_jobs/{id} in the same batch commit as
  its tombstone. A leader-leased reconciler on backend-sync is the only
  dispatcher: generation-numbered task names, run lease, removal only by a
  completed run of the current generation, automatic redrive after loss,
  exhaustion, failure and hold release.
- Producers no longer enqueue; the reconciler probes the live handler route
  before dispatching, so rollout or rollback order can only delay a purge.
- The cleanup script binds --execute to a runtime digest of every data plane
  the route touches and re-reads each tombstone before mutating.
- The task route is classified as an undocumented internal route in OpenAPI.
- Removes a pre-push artifact accidentally committed in the previous commit.

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
kodjima33 and others added 4 commits November 11, 2026 16:20
…urge

Review round 2 on #25124:
- The background purge no longer reuses purge_batch_owner (restored to main).
  A phase-ordered pass persists matching segment ids before any erasure,
  erases artifacts/projections/intakes/shadow jobs (matched by conversation or
  persisted segment) before the job/result binding that links them, and drops
  each segment record only after its binding is gone. A hold or crash between
  results and artifacts can no longer strand a segment-only artifact, and the
  run refuses completion while segment work is still recorded.
- Each run owns the obligation by run_token with a 300 s lease renewed (and
  ownership proven) by every checkpoint and destructive unit; superseded or
  expired executions stop before their next erasure. Runs hand off at a
  1200 s budget and the next generation resumes from a per-page cursor.
- Destructive units are bounded (10 rows or 1.5 s), release the account gate
  and yield 0.6 s so a waiting foreground delete gets in; storage deletes in a
  unit have a 5 s deadline.
- Unknown consumer readiness records a degraded fallback before dispatching.
- The bounded gate wait also absorbs Firestore transaction contention.

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ore every unit

Review round 3 on #25124:
- database/rpc_deadline: inside a bounded unit every Firestore RPC on the
  run's clients (reads, queries, commits, transaction begin/rollback) runs
  once with retry=None and timeout = time left, and is not sent past the
  deadline; storage deletes use retry=None (the generation-match default
  retried for 120 s) and a session whose max_allowed_time covers credential
  refresh. legal_holds.bounded_destructive_unit bounds body (5 s) and release
  (8 s) from the winning acquisition attempt and stamps the gate with a 10 s
  expires_at that _gate_blocks honours, so a lost release cannot outlast the
  20 s foreground wait.
- The purge checks the run budget before every unit, page read and discovery
  point read; an expiry mid-page saves nothing for that page and the resume
  replays it. A run saves one step before honouring its budget.
- Foreground waiters poll on lock-free reads with jitter, and the route gate
  release retries transaction contention instead of pinning the gate.

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hile a remote delete is unresolved

Review round 4 on #25124:
- Every destructive Firestore commit of the background purge re-proves the
  unit's gate token and the absence of a hold inside its own transaction
  (UnitAuthority.fence; optional fence on the shared erasure helpers).
- An object delete marks the gate remote_inflight before it is sent; the gate
  ignores its expiry while the mark is set, so no takeover or hold can proceed
  until the outcome is known. Any HTTP response (or a refused send) is
  definitive; an unknown outcome is re-issued twice and otherwise fails closed,
  and the next run settles the stuck gate under its own token. max_allowed_time
  is dropped (it fired only after a response).
- Segment-binding reads check the run budget one by one, and every RPC of a run
  is bounded by budget + 120 s (< 1500 s). A bounded delete_batch_object caller
  gets one attempt (retry=None).

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…akeover while in flight; run deadline from entry

Review round 5 on #25124:
- An unanswered remote delete is settled (immediately or by the next run) only
  when the same generation-pinned delete proves the generation is gone:
  returned (deleted/404) or 412. A 503/403/timeout/refusal keeps the gate held.
- A gate with an unresolved remote_inflight blocks regardless of age: no expiry
  and no 6 h stale takeover; past 6 h it logs
  event=destructive_gate_remote_unresolved.
- The run's absolute RPC deadline and budget start at entry, so the admission
  transaction is bounded and its time is debited.

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@kodjima33
kodjima33 merged commit 3f98d03 into main Nov 12, 2026
66 checks passed
@kodjima33
kodjima33 deleted the fix/conversation-delete-serialize branch November 12, 2026 00:19
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. -->
kodjima33 added a commit that referenced this pull request Nov 14, 2026
## What changed and why

#25124/#25197 put conversation batch purges and accepted-delete erasures
on the `account-deletion` Cloud Tasks queue (prod: 4 concurrent
dispatches). Their handler also ran on the same 4-worker
`cleanup_executor` as account wipes. On 2026-11-14 a cleanup of 533
half-deleted conversations queued about 760 tasks there. The queue
drained 2 to 3 tasks a minute. 32 real users' accepted deletes and 2
account deletions waited up to 40 minutes. The reconciler also redrove
every obligation that had waited longer than `REDRIVE_SECONDS` (600 s),
which added duplicate tasks to the same backlog.

1. **Own queue.** A new `CONVERSATION_ERASURE_TASKS_QUEUE` (prod value
`conversation-erasure`) is set on all 5 hosts that run the reconciler:
backend-listen (manifest and chart), backend, backend-sync,
backend-sync-backfill and backend-integration. Both kinds of erasure
unit now dispatch there. Account wipes stay alone on `account-deletion`.
The prod dispatch contract pins the literal.
2. **Own pool.** `/v1/conversations/deletion-batch-purges/run` now runs
on a new `erasure_executor` with 20 workers. Without this, wipes and
units would still contend on `cleanup`'s 4 threads inside each
backend-sync instance.
3. **No duplicate redrive.** Before the reconciler mints a new
generation, it probes the previous generation's task by name, first in
`conversation-erasure` and then in `account-deletion`. If that task is
still waiting, delivering or retrying, it is left to run that same
generation, and the obligation is re-checked after `REDRIVE_SECONDS`.
Only an authoritative NotFound in both queues allows a redrive. If the
probe fails (permission or transport error), the reconciler redrives as
before and records the fallback (`blind_redrive`, once per pass), so no
obligation is stranded.
4. **Deploy creates the queue.** On every prod deploy,
`deploy-backend-stack` creates or updates `conversation-erasure` before
any traffic shift. It uses the same list-based step as
`batch-quarantine-recovery`, and an inventory error fails the step.
Staging gets `staging-conversation-erasure` in `queue_map` and
`create_queues.sh`.

### Rollout safety (no task lost)
- Old revisions ignore the new env and keep dispatching to
`account-deletion`. Their tasks still reach the same handler, and the
new reconciler probes both queues for them.
- If `conversation-erasure` does not exist at enqueue time (NotFound),
the unit goes to `account-deletion` instead. This is recorded via
`record_fallback`, `conversation_erasure_queue ->
account_deletion_queue`. A rollback deploy therefore never strands work.
- Generation fencing (`begin_run` and `run_token`) is unchanged. A late
duplicate is still `superseded` and the lease still prevents overlap.
- The ~760 tasks already on `account-deletion` are left alone. They
drain there, and new passes stop adding duplicates on top of them.

### Queue sizing
`--max-concurrent-dispatches=20 --max-dispatches-per-second=5
--max-attempts=5 --min-backoff=5s --max-backoff=300s`
- **Throughput.** 4 slots drained 2 to 3 units a minute, which is
roughly 80 to 120 s per slot including gate waits. The cleanup armed
about 400 units an hour (6.7 a minute). 20 slots give about 12 to 15 a
minute, so the arming peak drains with about 2x headroom.
- **Firestore.** Units serialize per account on its gate. A purge unit
touches at most 10 rows per 1.5 s, then yields 0.6 s. 20 concurrent
units are at most about 100 row deletes a second, far below Firestore
write limits. Accepted-delete cascades run the same work the foreground
DELETE route already runs inline.
- **backend-sync.** Container concurrency is 20 and max scale is 40
(read 2026-11-14), so 20 dispatches fit one instance. The 20-worker
`erasure` pool means a delivered task never waits for a thread against
its 1500 s dispatch deadline.
- **Rate cap.** 5/s only bounds bursts. The reconciler enqueues at most
about 100 units per 60 s pass.

### Infra step
**The deploy creates the queue.** The new step `Configure production
conversation-erasure Cloud Tasks queue` runs on the next prod backend
deploy, before traffic moves. Nothing manual is needed. The equivalent
command, for reference only:

```
gcloud tasks queues create conversation-erasure --location=us-central1 --project=based-hardware \
  --max-concurrent-dispatches=20 --max-dispatches-per-second=5 --max-attempts=5 \
  --min-backoff=5s --max-backoff=300s
```

No IAM change is needed. Read-only on 2026-11-14: `backend-runtime@` and
`backend-listen-runtime@` already hold project-level
`roles/cloudtasks.enqueuer` and `roles/cloudtasks.viewer` (the viewer
role covers the `tasks.get` probe). `omi-ci-deployer-prod@` holds
`roles/cloudtasks.queueAdmin`. Neither queue has queue-level IAM
bindings. Staging: run `backend/deploy/staging/create_queues.sh --apply`
on the dev-operator tier.

## Product invariants affected

- INV-MEM-4: path-triggered by `backend/main.py` (a log condition only).
Memory promotion is not touched.

## How it was verified

UNVERIFIED in production. Nothing here is deployed, and I created and
changed no live queue. Prod reads only: `gcloud tasks queues
describe/list/get-iam-policy`, `gcloud projects get-iam-policy`, `gcloud
run services describe backend-sync`.

Run locally in a Python 3.11.15 worktree venv:
- Targeted suites: `pytest
tests/unit/test_conversation_erasure_queue_deploy.py
test_conversation_delete_gate_wait.py test_conversation_delete_accept.py
test_conversation_batch_purge_{resumable,authority,deadlines}.py
test_executors.py`: 146+ passed.
- Deploy/manifest suites: `test_backend_runtime_env_validator` (271),
`test_render_backend_runtime_env` (93), `test_staging_overlay` (21),
`test_cross_service_deploy_contract` (30, 3 skipped),
`test_sync_cloud_tasks` (209), `test_cloud_run_live_caps` (50),
`test_batch_pipeline_recovery_runtime_contract` (8),
`tests/routers/test_users.py` (327): all passed.
- Firestore emulator:
`tests/integration/test_conversation_batch_purge_emulator.py` 14 passed.
- `backend/scripts/pre-deploy-check.sh`: 578 passed.
`scan_async_blockers`, `check_module_stub_pollution`,
`scan_import_time_side_effects`, `verify_pusher_cohost_env_diff`,
`check_agents_md_lean`: clean.

## Tests

- `test_generation_still_in_its_queue_is_not_redriven`: a backlog older
than the redrive delay leaves generation 1 queued, and the waiting task
still purges it. This would have caught the duplicate backlog.
- `test_generation_gone_from_its_queue_is_redriven`,
`test_unanswered_probe_redrives_rather_than_strand`,
`test_one_unanswered_probe_per_pass`,
`test_running_generation_is_skipped_without_a_probe`,
`test_queued_hold_never_touches_a_newer_generation`.
-
`test_units_ride_the_conversation_erasure_queue_apart_from_account_wipes`,
`test_task_probe_looks_in_the_erasure_queue_then_the_shared_one`,
`test_missing_erasure_queue_keeps_units_on_the_shared_queue`.
- `test_task_handler_runs_on_its_own_pool_not_the_account_wipe_pool`.
- `test_conversation_erasure_queue_deploy.py`: the deploy step runs
before the traffic shift with the bounded flags and fails closed on
inventory errors. Every prod dispatcher, the GKE chart and staging name
the queue, and the prod contract rejects erasure units on the wipe
queue.

## UI evidence

UI-Evidence: none -- backend and deploy only

## Failure class (fixes)

Failure-Class: FC-backlog-release-shares-lane-with-fresh-work

The redrive half also matches
`FC-queued-delivery-invalidated-by-redrive`: queue delay past the retry
interval made the dispatcher mint new generations for tasks that were
still queued.

🤖 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/25299?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/25299?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25299&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. -->
kodjima33 added a commit that referenced this pull request Nov 15, 2026
…ds off instead of failing its task (#25393)

## Problem

On Cloud Run `backend-sync`, `POST
/v1/conversations/deletion-batch-purges/run` has answered HTTP 500 1,461
times since 2026-11-12T18:05Z. Per day: 53 on 11-12, 1,179 on 11-13, 85
on 11-14 and 144 on 11-15 up to about 11:07Z. The first 500 came an hour
after `backend-sync-83c5eaa` (2026-11-12T17:04Z), the first revision to
serve the route from #25124. The 11-13 peak was before #25299 (queue
switch) and #25298, so neither of those caused it.

The handler did log every failure, but only the exception class, and the
line is not attached to the request trace. Across the WARNING lines
(kept in full), 1,293 of 1,462 failures are
`DestructiveOperationInProgress`. The rest are scattered transient
Firestore errors (`DeadlineExceeded`, `ServiceUnavailable`, `ValueError`
commit contention, `ReadTimeout`).

## Root cause

A purge unit waits `UNIT_GATE_WAIT_SECONDS` (30 s) for the account's
destructive gate. A same-account multi-delete arms one obligation per
conversation, and the reconciler dispatches all of them at once. They
then queue on that one gate together with the account's accepted-delete
erasures and foreground deletes. A unit that waits past 30 s raises
`DestructiveOperationInProgress`. `run_job` treated that as a hard
failure: `last_outcome=failed`, a 600 s redrive, and a 500 that also
burns the queue's 5 retries. Most 500s therefore take about 30 s, the
wait budget. #25197 added the `busy` outcome for erasures
(`run_erasure_job`), but batch purges never got it.

## Fix

- `run_job` maps a unit that lost the gate to a same-kind peer
(`_lost_gate_to_peer`, the helper `run_erasure_job` already uses) to the
existing `busy` outcome. That means a 200, the lease released, and a
redrive in `BUSY_RETRY_SECONDS`.
- `busy` is safe because a unit acquires the gate before erasing
anything, so the losing unit erased nothing. The scan position and
segment records were already checkpointed under the run's ownership, and
the next generation resumes from them.
- Privacy invariants from #25124 are unchanged:
- An account wipe, retention or audio-deletion gate is never a peer. It
still fails the run (tested for each kind).
  - A legal hold still ends as `held`.
  - Every erasure is still fenced by its unit's authority.
  - Run and unit deadlines are unchanged.
- A stuck remote-erasure gate is still settled by `settle()` before each
unit, and is still reported by
`event=destructive_gate_remote_unresolved`.
- The handler's failure line now includes the obligation kind,
generation, exception type and `sanitize(str(e))`, so every 500 states
its reason.
- Re-pinned the `run_job` `BODY_DIGEST`. It adds no query: its only
stream is still `segment_records`, and the gate check is the existing
point read.

## Blast radius (read-only)

- 301 distinct obligations failed at least one attempt since 11-12, 202
of them with `DestructiveOperationInProgress`.
- None is stuck: all 301 are gone from `conversation_batch_purge_jobs`
and `conversation_erasure_jobs`, so they completed.
- Success lines look missing for 237 of them only because app stdout
INFO is kept at 10% by the `_Default` sink exclusion
`app-stdout-info-sample90`. 2xx request logs are also kept at 10%
(`cost-audit-cloud-run-success-sample`).
- Live right now: 19 batch-purge and 5 erasure obligations, all from one
account and all under 1 h old. 18 tasks are queued on
`conversation-erasure`.
- The roughly 300 403s a day on this path are the reconciler's
unauthenticated readiness probe
(`conversation_batch_purge_consumer_ready`), which is expected.

## Not in this PR

- `/v2/audio-merge-jobs/run` 500s on 11-15 (171 so far) have a different
cause. All of them are `stamped playback source could not be read`
(`utils/other/storage.py`, strict-source download failure), across 7
conversations, and each fails in under 1 s. They have nothing to do with
the gate.
- The reconciler still dispatches every due batch-purge obligation of
one account at once. A per-account spread like
`MAX_ERASURES_PER_ACCOUNT` would cut how many gate waiters there are.
With this fix those waiters hand off with `busy` instead of failing, so
the spread is a follow-up.

## Tests

-
`test_unit_losing_its_gate_wait_to_a_same_account_peer_hands_off_busy_and_resumes`
reproduces the prod failure. On `main` it raises
`DestructiveOperationInProgress: another destructive operation owns the
account gate`. With the fix it returns `busy`, erases nothing without
the gate, keeps progress, and the next generation purges.
-
`test_unit_blocked_by_another_destructive_kind_still_fails_the_run[account_deletion|retention_cleanup|audio_conversation_deletion]`.
- `test_task_handler_maps_run_outcomes_to_queue_retry` gains a `busy`
case (200). `test_task_handler_logs_why_a_run_failed` checks the new
failure line and that it is sanitized.
- Purge, gate and accept suites pass (111 tests):
`test_conversation_batch_purge_{resumable,deadlines,authority}.py`,
`test_conversation_delete_gate_wait.py`,
`test_conversation_delete_accept.py`. `test_firestore_query_shapes.py`
also passes. `make preflight` was run.

## Product invariants affected

none

## Failure class (fixes)

Failure-Class: FC-user-intent-queued-behind-account-exclusive-work

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