Repository navigation
feat(sync): per-UID backfill sequencer with 202 admission - #19362
Merged
Merged
Conversation
This was referenced Sep 27, 2026
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]>
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.
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=offin 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.sync_backfill_sequencer/{uid}owns one active job and epoch. Waiting jobs are append-onlysync_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.action=cutover_overlaplogs 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
firestore.indexes.jsonmain push triggersgcp_firestore_indexes.yml; approve production schema creation and verify bothsync_backfill_pendingcomposite indexes areREADYbefore the Scheduler/code deployment. Separately dispatch itsfield-exemptionsoperation in prod withAPPLY_FIRESTORE_FIELD_EXEMPTIONSand approval; this saves index cost and does not gate query serving.sweep_summaryheartbeat, 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. KeepSYNC_BACKFILL_INFLIGHT_LIMIT=falseandSYNC_BACKFILL_ADMISSION_LIMITS=false.backend-syncandbackend-sync-backfillrevisions have zero traffic and no old-revision/v2/sync-jobs/runrequests 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.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". Filteraction=samplefor cappedqueued_depth,oldest_waiting_seconds,active_leases;action=sweep_summaryfor owner/pending scans and errors;action=dispatchforlatency_seconds;action=redriveandaction=sweepfor lease expiry, terminal cleanup and lost dispatch;action=cutover_wait|cutover_overlapfor transition risk;action=finishedfor outcome counts. Stall/wait logs carryjob_idand non-reversible HMACuid_hash, never a raw UID label. The productionsync_backfill_uid_sequencer_stall,sync_backfill_uid_sequencer_scheduler_failure, andsync_backfill_uid_sequencer_scheduler_heartbeatmetrics 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 watchsync_backfill_dead_letter,event=sync_bridge outcome=failed|deferred,sync_transcription_job_finalizedfailures, persistence-phase FirestoreAborted, fenced reprocessing, and superseded jobs.After cutover, verify over a 24-hour prod window: zero
/v2/sync-local-filesbackfill_paced429s; synthetic multi-batch UID jobs execute one at a time and independent UIDs concurrently; sampledactive_leasesnever exceeds one per owner; oldest waiting age stays bounded well below 12 hours; Scheduler failures/missed heartbeats, sweep errors, cutover overlaps, andnonterminal_ackstay zero; persistence-phase FirestoreAborted, fenced reprocessing, superseded jobs, failed/partial jobs, dead letters, bridge failures, and paid STT usage per processed speech hour do not rise. Specifically comparepartial_failurewith the observed 5% flag-off level (1.6% before heavy-UID concurrent uploads); the sequencer should remove the cross-job contribution. Investigate anyaction=wait_alertimmediately.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 --checkpython3 backend/scripts/validate-backend-runtime-env.py --env dev --check-workflowspython3 backend/scripts/validate-backend-runtime-env.py --env prod --check-workflowsmake preflightInfra / 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_SCRIPTScheckout. Cloud Scheduler API is enabled in dev/prod and the deploy SAs already haveroles/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-onlysync_backfill_pendingcomposite indexes before phase-one code/Scheduler deployment. The pending/active payload single-field exemptions use the existing prod-only manualfield-exemptionsworkflow withAPPLY_FIRESTORE_FIELD_EXEMPTIONSconfirmation 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
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.