Repository navigation
fix(backend): accept conversation deletes immediately and erase them in order - #25197
Merged
Merged
Conversation
…in order A cascade delete that finds a same-account delete holding the account gate no longer waits up to 20 s and then answers 409. One transaction writes the tombstone, marks the row deleted (every product read drops it), and arms a durable conversation_erasure_jobs obligation. The route answers 204 at once. The reconciler dispatches erasures (at most 6 per account per pass) over the existing account-deletion queue. The runner performs the request's own cascade under the gate, one at a time, and the cascade arms the batch purge as before. - A free gate keeps the synchronous cascade. - Busy is decided by a lock-free gate read or a single-attempt acquisition, never by SDK transaction backoff. - A legal hold at request time still rejects. A hold placed after acceptance stops erasure; the conversation stays hidden and retained. - An account wipe supersedes: no tombstone means complete. - A lost or old-consumer task is redriven; an older consumer answers missing, so it can never drop the obligation. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…t a time deleteConversationServer retries a 409 (account_gate_busy) after the server's Retry-After (clamped to 1-10 s, default 2 s) within a 30 s budget and still succeeds only on 204. Server deletes from the provider go out one at a time in commit order: a multi-select delete committed every row at once, so most of a burst collided on the account gate. Optimistic removal, undo and error handling are unchanged. A queued delete is dropped if the user signed out or switched accounts before its turn. Co-Authored-By: Claude Opus 5.5 <[email protected]>
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. -->
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:conversation_tombstones.accept_deletion) does three things. It writes the tombstone, keeping the original on a retry. It marks the rowdeleted: True, so list/get/search/count/chat-RAG/MCP/developer/shared reads drop it at once throughis_visible_conversation. It armsconversation_erasure_jobs/{opaque id}with merge-donor ids read while the row still exists. The route answers 204 right away and erases nothing.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.run_erasure_job, on backend-sync via the existingaccount-deletionqueue and handler, payloadkind: erasure):erase_accepted_conversation) under the account gate, one at a time. That cascade also arms the batch purge exactly as before.busy: due again in 30 s, no failure, attempts reset.maxConcurrentDispatches: 4). It scans 4× wider so one account's backlog cannot hide other accounts.held, rechecked hourly). The conversation stays hidden and retained.missingand 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.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 forconversation_erasure_jobs(25 reads/delete, 40k/day).App (
fix(app), separate commit).deleteConversationServerretries a 409 afterRetry-After(clamped 1-10 s, default 2 s) within a 30 s budget, and still succeeds only on 204.Known gaps until an accepted delete's erasure finishes (normally ≤ 1-2 min, longer for a large burst):
total_conversations.Product invariants affected
none
How it was verified
gcloud run services describe backend|backend-sync: both run image 83c5eaa withACCOUNT_DELETION_DISPATCH_MODE=cloud_tasks, theaccount-deletionqueue, handler URL and invoker SA set. Soaccepts_conversation_deletes()is true onbackend.gcloud tasks queues describe account-deletion:maxConcurrentDispatches: 4,maxAttempts: 5.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.held, and the row is retained withdeleted: True.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.flutter teston 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 analyzeon touched files is clean, anddart format(3.44.5) made no changes.Not verified:
Tests
backend/tests/unit/test_conversation_delete_accept.py(13 tests), on the real route, gate, accept writer, reconciler and runner:no_tombstoneand never erases.missingand cannot drop it.busyand retried soon.kind: erasure.test_conversation_delete_gate_wait.pyandtest_conversation_tombstones.pyfor 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.dartandapp/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.backend/tests/unit/test_conversation_delete_accept.py. Evidence PRs: fix(backend): conversation cascade deletes no longer block on their own deletion gate #24988, fix(backend): conversation deletes wait for the account gate and return fast #25124.🤖 Generated with Claude Code