Skip to content

feat(sync): per-UID backfill sequencer with 202 admission - #19362

Merged
Git-on-my-level merged 6 commits into
mainfrom
feat/sync-backfill-uid-sequencer
Sep 27, 2026
Merged

Git-on-my-level merged 6 commits into
mainfrom
feat/sync-backfill-uid-sequencer

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Sep 27, 2026 •

Copy link
Copy Markdown
Member

Summary

Accept eligible backfill uploads with 202. Phase one ships the new code with sequencing off in dev and prod, so direct jobs retain the post-#19352 behavior and write bounded cutover markers. A later config PR enables the durable per-UID Firestore queue after old revisions and their active direct tasks drain. In on mode, one worker job at a time is promoted for each UID under a renewable job/epoch lease. The existing 30-slot backfill Cloud Tasks queue remains the global pacer; different UIDs fill it independently. The v2 upload path no longer consults the retired Redis in-flight slot, including with the kill switch off. Fair-use, lookback, lane classification, and paid STT provider selection are unchanged.

Design and cutover

  • SYNC_BACKFILL_UID_SEQUENCER=off in dev/prod for phase one. Off sends new jobs directly to Cloud Tasks, writes/refreshes direct-job markers, and preserves the post-fix(sync): turn off per-uid backfill in-flight limit #19352 concurrent behavior; previously sequenced jobs retain their persisted epoch protocol and continue draining through the sweeper.
  • Firestore sync_backfill_sequencer/{uid} owns one active job and epoch. Waiting jobs are append-only sync_backfill_pending/{job_id} documents, ordered by oldest capture time among jobs already waiting. The oldest-pending query runs inside the owner-claim transaction, closing the preselection race with concurrent admission. Admission reads but never writes the owner doc, so a heavy UID's burst of uploads does not contend on one write hotspot. Owner writes occur once per claim/release plus a two-minute active heartbeat. The first client batch can start immediately; later arrivals are ordered oldest-first to reduce conversation bridge work despite mobile's newest-first batching.
  • Admission writes the registry before 202 and verifies uncertain write acknowledgements; known absence returns retryable 503 with cleanup, while unverified uncertainty preserves recovery material. The worker renews a 30-minute lease every two minutes, checks epoch before entering the pipeline, and releases/dispatches next only after terminal or expired Redis state. Cloud Tasks names include the epoch so a lost acknowledgement can be safely redriven. The existing run lock and ledger fences still protect each job. The Redis retry count is retained across task epochs; provider sends and the paid STT policy are unchanged.
  • A two-minute Cloud Scheduler tick uses the existing sync task invoker identity to recover lost dispatches, orphan pending records, and expired leases. It scans/defer-writes at most 100 pending docs per tick (72,000 reads and writes per day at continuous backlog; zero pending writes when empty). It emits a routed production alert at 12 hours waiting age, before the 24-hour Redis/staged-blob expiry. Scheduler execution failures and ten minutes without a sweep heartbeat have separate routed alerts. Normal admission, terminal completion, and delayed cutover wakes dispatch without Scheduler. No HTTP worker waits for a UID slot.
  • Old queued backfill tasks landing on the new revision are registered and redelivered with an epoch when on. On each off-to-on transition, sequenced dispatch is held for a bounded 30-minute window, longer than the 25-minute task deadline and equal to the direct Redis run-lock lifetime. New flag-off admissions leave a per-UID 30-minute Redis marker before enqueue, renewed from direct task start. Already pending sequenced work respects the marker even during flag-off rollback. A named delayed Cloud Task wakes each held UID at the deadline. During rollback, a new flag-off worker migrates direct queued work if that UID still has a sequenced owner or pending record. An old revision that continues admitting direct work after its 30-minute traffic-retirement window is the remaining non-fenceable overlap case; action=cutover_overlap logs it with job ID and HMAC UID hash. The two-phase revision-retirement/drain gate closes this operationally. Old Redis admission-slot keys are ignored.

Rollout / kill switch

  1. Merge with the flag off. The firestore.indexes.json main push triggers gcp_firestore_indexes.yml; approve production schema creation and verify both sync_backfill_pending composite indexes are READY before the Scheduler/code deployment. Separately dispatch its field-exemptions operation in prod with APPLY_FIRESTORE_FIELD_EXEMPTIONS and approval; this saves index cost and does not gate query serving.
  2. Deploy new-code dev and prod revisions with the flag still off (including auto-dev), verify the exact release vector and runtime env, 202 admission, direct marker writes/worker refresh, Scheduler OIDC URL/audience and successful two-minute executions, sweep_summary heartbeat, and all three routed alerts. The lifecycle action now fails deployment on same-name alert-policy filter/duration/channel drift instead of silently accepting it. Keep SYNC_BACKFILL_INFLIGHT_LIMIT=false and SYNC_BACKFILL_ADMISSION_LIMITS=false.
  3. Before a later coordinator-owned config PR flips on, prove old backend-sync and backend-sync-backfill revisions have zero traffic and no old-revision /v2/sync-jobs/run requests for at least 30 minutes after the last request. Cloud Logging drain query: resource.type="cloud_run_revision" AND resource.labels.service_name="backend-sync-backfill" AND (resource.labels.revision_name="OLD_BACKFILL_REVISION_1" OR resource.labels.revision_name="OLD_BACKFILL_REVISION_2") AND httpRequest.requestUrl:"/v2/sync-jobs/run" over that window. Queued tasks delivered to new code write markers off or migrate on. Restart the drain clock if old revision traffic reappears.
  4. Phase two flips on in dev, soaks, then flips on in prod. The first on-mode kick imposes the 30-minute global quiet window, extended by per-UID markers. Verify delayed wakes, ordered serial work, independent UID progress, task redrive, terminal cleanup, and zero cutover_overlap. If a defect requires rollback, set the flag off, keep Scheduler running until persisted sequenced jobs drain, and repeat the drain check before another flip.

Monitoring / prod acceptance

Cloud Logging query base: resource.type="cloud_run_revision" AND (resource.labels.service_name="backend-sync" OR resource.labels.service_name="backend-sync-backfill") AND "event=sync_uid_sequencer". Filter action=sample for capped queued_depth, oldest_waiting_seconds, active_leases; action=sweep_summary for owner/pending scans and errors; action=dispatch for latency_seconds; action=redrive and action=sweep for lease expiry, terminal cleanup and lost dispatch; action=cutover_wait|cutover_overlap for transition risk; action=finished for outcome counts. Stall/wait logs carry job_id and non-reversible HMAC uid_hash, never a raw UID label. The production sync_backfill_uid_sequencer_stall, sync_backfill_uid_sequencer_scheduler_failure, and sync_backfill_uid_sequencer_scheduler_heartbeat metrics route to configured notification channels. Scheduler failure query: resource.type="cloud_scheduler_job" AND resource.labels.job_id="sync-backfill-uid-sequencer" AND severity>=ERROR AND jsonPayload."@type"="type.googleapis.com/google.cloud.scheduler.logging.AttemptFinished". Also watch sync_backfill_dead_letter, event=sync_bridge outcome=failed|deferred, sync_transcription_job_finalized failures, persistence-phase Firestore Aborted, fenced reprocessing, and superseded jobs.

After cutover, verify over a 24-hour prod window: zero /v2/sync-local-files backfill_paced 429s; synthetic multi-batch UID jobs execute one at a time and independent UIDs concurrently; sampled active_leases never exceeds one per owner; oldest waiting age stays bounded well below 12 hours; Scheduler failures/missed heartbeats, sweep errors, cutover overlaps, and nonterminal_ack stay zero; persistence-phase Firestore Aborted, fenced reprocessing, superseded jobs, failed/partial jobs, dead letters, bridge failures, and paid STT usage per processed speech hour do not rise. Specifically compare partial_failure with the observed 5% flag-off level (1.6% before heavy-UID concurrent uploads); the sequencer should remove the cross-job contribution. Investigate any action=wait_alert immediately.

Verification

  • BACKEND_UNIT_TEST_FILE_LIST=.local/sync-sequencer-test-list.txt bash backend/test.sh (339 passing across focused registry/contention, ordering race, alert-policy drift, immutable deploy-control staging, worker/admission, dead-letter, stale-poll, lane, Firestore-index/exemption, and sync import-isolation files)
  • bash backend/scripts/typecheck.sh (0 errors; existing warnings)
  • python3 backend/deploy/compose_runtime_env.py --check
  • python3 backend/scripts/validate-backend-runtime-env.py --env dev --check-workflows
  • python3 backend/scripts/validate-backend-runtime-env.py --env prod --check-workflows
  • make preflight

Infra / review notes

The existing sync-backfill lifecycle composite declares the Cloud Scheduler job and three production sequencer log metrics/alerts, alongside budget/dispatch alerts. It now verifies every same-name policy's filter, duration, and channels and fails loudly on drift or duplicate names. Its verifier runs from the immutable staged DEPLOY_CONTROL_SCRIPTS checkout. Cloud Scheduler API is enabled in dev/prod and the deploy SAs already have roles/cloudscheduler.admin; no manual Scheduler IAM grant is needed. The existing sync task invoker service account serves the sweep and delayed-wake routes. No new queue, secret, service account, IAM binding, or workflow is introduced. Manual schema gate: the existing Firestore schema workflow must approve/finish the create-only sync_backfill_pending composite indexes before phase-one code/Scheduler deployment. The pending/active payload single-field exemptions use the existing prod-only manual field-exemptions workflow with APPLY_FIRESTORE_FIELD_EXEMPTIONS confirmation after merge; they save index cost and are not a serving prerequisite. The v2 sync router is already large; this feature keeps admission and worker boundaries there while placing durable state/reconciliation in dedicated modules.

Product invariants

  • INV-MEM-4: The new sweep route does not change memory mutation or the existing conversation pipeline.

Failure-Class: none

Line-Count-Exception: backend/routers/sync.py | 2187 -> 2397 | Admission and OIDC worker dispatch boundaries remain in the existing route; Firestore queue and reconciliation live in dedicated modules.
Line-Count-Exception: backend/database/firestore_index_registry.py | 1513 -> 1527 | The existing index registry owns the two required pending-query composites and payload field exemptions; a separate registry would split one generated manifest's authority.

@Git-on-my-level
Git-on-my-level merged commit 28ca03d into main Sep 27, 2026
61 checks passed
@Git-on-my-level
Git-on-my-level deleted the feat/sync-backfill-uid-sequencer branch September 27, 2026 11:52
aryanorastar added a commit that referenced this pull request Oct 5, 2026
…job (#19437)

* fix(sync): keep job reads behind terminal ownership

Reproduce five live-reader failures, including completed-result clobbering. Keep lookups read-only and let the existing run-lease finalizer own recovery. The real-route regression matrix preserves legacy, active, inline, standby and abandoned-task semantics.

Verified: 379 focused backend tests; 0 pyright errors; local Uvicorn + curl with fake Redis and outbound network blocked; 32 repository preflight checks.

Refs #19373

Failure-Class: FC-split-mutation-authority

* refactor(sync): collapse the two read-only job readers into get_sync_job

Stacked on #19379. Once that change makes get_sync_job read-only, main's
get_raw_sync_job (added by #19362 for the per-UID sequencer) is the same
function: both read the job key, return None on a missing, corrupt or non-dict
blob, and write nothing. Checked structurally rather than by eye -- the two
bodies are AST-identical modulo the local variable name. Two copies of one
read-only primitive is exactly how read-side mutation creeps back into one of
them, so this keeps a single reader.

- database/sync_jobs.py: remove get_raw_sync_job and _read_raw_sync_job.
- routers/sync.py, utils/sync/uid_sequencer.py: point the five callers at
  get_sync_job and drop the now-duplicate import name.
- Tests that patched the removed name now patch get_sync_job.

One fixture needed a deliberate change rather than a rename.
test_sync_task_persistence_fence_terminalizes_backfill_and_releases_its_slot
runs a backfill task with no sequencer epoch, which first reads its own job to
decide whether the UID sequencer should adopt it. Its harness stubs the whole
database.sync_jobs module with a bare MagicMock, so before this change that read
returned an auto-mock whose status never equalled 'queued' and the migration
branch was skipped by accident. After consolidation the read consumes from the
test's explicit get_sync_job sequence, sees the real 'queued' job, and migrates.

Rather than feed it a sentinel, the test now states its scenario: the legacy
direct path with the sequencer disabled, no owner and nothing pending, and the
migration read gets its own entry ahead of the processor's three. Flipping the
sequencer on makes the test fail, so the gate is load-bearing rather than
decorative.

Verified: every test_sync_* suite, 952 passed and 0 failed; typecheck 0 errors.
No behaviour change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(sync): finish consolidating read-only job lookup

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
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