Skip to content

Batch pipeline worker: fair priority queue, ordered merge, batched GPU chain - #21674

Merged
Git-on-my-level merged 62 commits into
mainfrom
batch-pipeline-worker
Oct 15, 2026
Merged

Git-on-my-level merged 62 commits into
mainfrom
batch-pipeline-worker

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

Cohort sync uploads now stage encrypted conversation-sized units and atomically select a durable batch protocol, so an admitted upload cannot also enter the legacy sequencer. Dedicated GPU workers pull through a priority queue with duration DRR and 64 owner-hash control shards. Results publish through an ordered predecessor log, existing conversation assignment, content accounting, and coalesced enrichment. Every switch remains default-off.

Compute failures and expired leases keep their ordered head in retry with a 600-second backoff cap and a retry-age signal. Historical dead heads have an authenticated redrive route and authorized client-poll recovery. Privacy-fenced recovery is isolated per segment. Late captures receive normal 202 admission, preserve their capture clock, and append after the committed tail without regressing the capture high watermark. Admission rollback continues draining accepted work with 20-second heartbeats. Shard reactivation uses an indexed virtual-service frontier, avoiding stale or reset credits without a global writer.

Multipart projection reuses the legacy VAD grouping and assignment path, with resumable receipts and deletion fences across every part and artifact. The dedicated GPU chain, service-OIDC compute admission, queue-age metrics, runtime packaging and chart are included in this shared PR. GPU OOM fences/replaces the process while refunding the interrupted lease; staging uses resumable transport. Backfill consumes dedicated capacity or explicitly qualified short shared-live slack; conversation-sized units never run on live Parakeet pods.

Validation at published head a2a0c47: A’s scheduler/intake/merge changes pass 96 focused tests and 71 real loopback Firestore tests, including encrypted late intake through durable completion. The CI-driven legacy import/lifecycle repairs pass 406 targeted tests without changing stubs, assertions or timing budgets. The normal push gate passes all 44 preflight checks, full backend typechecking with zero errors, 17 runtime-image contracts, 754 bounded backend tests, OpenAPI compatibility, release checks and formatting. CI runs the PR merge ref; cde’s merge-ref run exposed additional listen/action-item/contention-fixture failures and a stale app-client snapshot, while the exact published branch snapshot check passes locally. Focused Grok4.7-high re-review PASS on exact a2 confirms A findings1/2/4/5 and the two isolation repairs. Exact-head CI confirms69 transcription-preference and15 lifecycle cases pass; other merge-ref integration failures remain for the lead; this PR has not been merged or deployed.

Before enabling a cohort, the lead must obtain production indexes READY, qualify the dedicated GPU image/full-chain memory and quality, and complete live privacy/accounting/product acceptance. No deployment, index apply, cohort enablement or PR merge is performed by this work. Published merge history is preserved.

Failure-Class: FC-runtime-image-boundary

Product invariants affected

  • INV-DATA-1 (canonical customer data plane): the existing diarizer deployment workflow gains the default-off dedicated batch worker path. Explicit stage-qualified queue namespaces and existing customer-data client authority are preserved; no production-family routing authority is changed by this work.

Git-on-my-level and others added 20 commits October 15, 2026 19:58
- wal_audio_coverage metrics: reuse the registered counter when the
  import-isolation harness re-executes the module, instead of raising
  Duplicated timeseries across test_sync_capture_pipeline fixtures.
- utils/stt/vad: guard the onnxruntime import so pusher-reachable
  stored-audio compaction paths import cleanly on images that ship
  without onnxruntime; local Silero VAD then raises and compaction
  abstains to original audio. Register the sanctioned pusher
  dependency-probe exclusion.
- workflow contracts test: materialize the relocated
  database/sync_pipeline_indexes module in the hermetic firestore
  readiness control root.
- listen_pusher_pipeline.mdx: resolve the appended-section conflict
  with main's sync assignment contention section.
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Monitor fix round: rebased onto current main and repaired the four failing backend unit checks.

  • Rebased the branch onto latest main (resolves the appended-section conflict in backend/docs/listen_pusher_pipeline.mdx with main's sync assignment contention section; PR is mergeable again).
  • utils/sync/wal_audio_coverage_metrics: reuse the registered Prometheus collector when the sanctioned import-isolation harness re-executes the module, instead of Duplicated timeseries fixture errors across test_sync_capture_pipeline.py (shard 1/6).
  • utils/stt/vad: guard the onnxruntime import so pusher-reachable stored-audio compaction paths import cleanly on images that ship without onnxruntime (pusher lock has no onnx/torch/pyannote/speechbrain). Local Silero VAD raises a clean RuntimeError there and compaction abstains to original audio — the PR's conservative-abstention contract. Registered the sanctioned pusher dependency_probe_exclusions entry in runtime_images.json (shard 5/6).
  • test_workflow_contracts: materialize the relocated database/sync_pipeline_indexes module in the hermetic firestore-readiness control root (shard 6/6).
  • Added Failure-Class: FC-runtime-image-boundary to the PR body (required by the failure-class protocol for fix: commits).

Verification: the three previously-failing tests plus adjacent suites pass locally (test_sync_capture_pipeline, test_runtime_image_contracts, test_workflow_contracts firestore composite, test_final_pass_vad_compaction, test_wal_audio_coverage_pipeline, test_batch_pipeline_metrics); pusher-no-onnxruntime import/abstain simulated; pre-push preflight passed; pushed as 80d498a61f. CI on the new head: all workflows green, backend unit shards 1–6 + suite success, no failing checks.

Git-on-my-level and others added 16 commits October 15, 2026 21:47
The contention-retry runner moved from conversations.assign_sync_conversation
into database.sync_assignment.run_sync_assignment, which resolves
run_with_transaction_contention_retry from its source module at call time.
Update the fixture to patch database.firestore_transaction_retry so the
seam keeps controlling production instead of a vestigial conversations
attribute.
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Monitor fix round for the failing checks at head a2a0c475f8:

  • Merged current main into the branch. This alone repaired the Public Developer API contract failure (main's regenerated app-client-openapi.json arrives via the merge) and eight of the nine failing unit-test files — those tests were newly added or updated on main (e4b1600c5b and later) and only collided with this branch at the merge ref.
  • Root-caused the remaining file, tests/unit/test_sync_assignment_contention_retry.py: the branch's extracted assignment runner (database.sync_assignment.run_sync_assignment) resolves run_with_transaction_contention_retry from its source module at call time, so the fixture's patch of the former conversations.run_with_transaction_contention_retry seam no longer controlled production and raised at setup. The fixture now patches database.firestore_transaction_retry (the same seam test_batch_pipeline_projection.py already uses).
  • Verified locally through backend/test.sh: the fixed file (9/9), all previously failing files (287 tests), the branch's 33 changed test files plus the sync/conversation neighbors (742 tests) — zero failures. Pushed ca555ad0f1 (fast-forward on top of 877cd0d9c1), with the pre-push gate passing.
  • Post-push CI on ca555ad0f1: all six backend unit shards, the backend unit suite, backend unit guardrails, and the Public Developer API contract check now pass. No unresolved review threads.

@Git-on-my-level
Git-on-my-level marked this pull request as ready for review October 15, 2026 23:28
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-15T23:36:43.862633Z 5697afd Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

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

@Git-on-my-level
Git-on-my-level merged commit 6f70846 into main Oct 15, 2026
62 checks passed
@Git-on-my-level
Git-on-my-level deleted the batch-pipeline-worker branch October 15, 2026 23:36

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5697afd4b1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

- {name: OMI_FIRESTORE_DATA_PLANE_PROJECT, value: {{ required "explicit customer data plane project required" .Values.dataPlaneProject | quote }}}
- {name: OMI_ENV_STAGE, value: {{ .Values.stage | quote }}}
- {name: BATCH_PIPELINE_NAMESPACE, value: {{ .Values.namespace | quote }}}
- {name: BUCKET_BATCH_PIPELINE, value: {{ required "dedicated staging bucket required" .Values.bucket | quote }}}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Provide the compute-admission endpoint configuration

When this chart is enabled, every real intake lease has requires_compute_admission=True, but the pod receives neither BATCH_PIPELINE_API_URL nor BATCH_PIPELINE_WORKER_AUDIENCE. Consequently compute_client_from_env() rejects the empty configuration, Pump.run_once() treats every lease as denied and defers it without invoking the GPU, so admitted uploads remain queued indefinitely. Add required chart values and inject both variables into the worker environment.

Useful? React with 👍 / 👎.

Comment on lines +31 to +34
allowed_buckets = {
value
for name in ('BUCKET_BATCH_PIPELINE', 'BUCKET_TEMPORAL_SYNC_LOCAL')
if (value := os.getenv(name, '').strip())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Allow erasure from both stage-specific buckets

When a UID has batch artifacts in the other stage, account deletion or a protection-level change cannot complete: purge_batch_owner() deliberately scans both the prod and dev namespaces on the shared customer data plane, while this allowlist accepts only the current process's single BUCKET_BATCH_PIPELINE. The supplied values use different prod and dev buckets, so encountering a cross-stage artifact raises ValueError before the recursive user wipe and leaves the privacy purge unfinished. Configure and validate both stage buckets, including the orphan-prefix sweep, rather than only the current-stage bucket.

Useful? React with 👍 / 👎.

Comment on lines +162 to +168
compute = asyncio.create_task(
run_blocking(sync_executor, self.worker.process_batch, [v.item for v in leases])
)
# Cancelling an asyncio wrapper does not stop CUDA. Keep renewal and
# wait for the bounded model operation before leaving this process.
try:
results = await asyncio.shield(compute)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Refresh HPA metrics while GPU inference runs

When a model batch takes longer than 60 seconds, this await prevents the pump from executing its only metrics refresh until inference finishes. One-hour units are permitted and can readily exceed that interval, while the accompanying Prometheus adapter explicitly drops samples older than 60 seconds; once all current workers are busy, the HPA therefore loses the queue-age signal precisely when it needs to scale up for waiting work. Run metric sampling independently of the non-preemptible compute wait.

Useful? React with 👍 / 👎.

Comment on lines +17 to +20
worker:
batchSize: 8
unitSeconds: 3600
paddedSeconds: 272

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Align the intake and worker unit-duration limits

With the supplied deployment configuration, the GPU worker rejects captures that the backend can durably admit: the backend-side provider_config() defaults to a 7,200-second unit and no backend runtime binding overrides it, while this chart limits the worker to 3,600 seconds. A continuous capture between one and two hours is therefore staged and queued as one item, then PipelineWorker.process_batch() raises before processing it on every attempt, leaving the accepted upload in an endless retry loop. Use one shared deployment value or configure the backend intake to the same 3,600-second ceiling.

Useful? React with 👍 / 👎.

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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant