Repository navigation
fix(sync): recover stale sequenced sync jobs and unblock account queues (#21943) - #21999
hardik4love-lang wants to merge 9 commits into
Conversation
|
Hi @Git-on-my-level, @kodjima33, All automated CI checks, hygiene preflights, unit test shards, and merge gates are now 100% green:
Ready for maintainer review and merge! |
|
Thanks @hardik4love-lang — this is a well-scoped fix for a real deadlock class (#21943), and the root-cause writeup matches the code. I verified the diff against the head sources; notes per file: backend/database/sync_jobs.py — the restructured
backend/routers/sync.py — admitting backend/tests/unit/test_sync_job_stale_self_heal.py — good coverage of the processing stale/fresh and queued stale/fresh cases plus the retry-preserved case. Gap: nothing exercises the router's new sequencer-release block (finish_job/retire_expired/kick under One residual worth stating: queued jobs with No blocking defect found; checks are green on head. Because this flips a deliberate liveness-ownership invariant (polling readers previously never finalized sequenced jobs) and adds epoch-verified sequencer release on the user-facing status poll, I'm leaving the merge call to a human maintainer rather than sign-off here. This review was produced by an AI reviewing assistant on behalf of the Omi maintainers. by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with |
|
Thanks @Git-on-my-level for the thorough review and validation! Addressed the feedback in commit \4975b7d68e:
Ready for final merge! |
Git-on-my-level
left a comment
There was a problem hiding this comment.
The production change here is correct and nicely scoped — the deadlock analysis matches the code, and the lease-guarded finalization preserves the existing safety model. One coverage gap below.
Verified against the head:
- backend/database/sync_jobs.py — is_sync_job_stale previously returned False for every sequenced job unconditionally, which is exactly the #21943 deadlock: a lost worker or never-dispatched queued job held the per-UID owner lock forever. The restructure is behavior-preserving for non-sequenced modes (the hoisted queued-retry guard on started_at/attempt is equivalent to the old inline conditions), and sequenced queued/processing jobs now go stale after SYNC_SEQUENCED_STALE_SECONDS with a safe fallback to 43200s on malformed env. Default of 12h sits sensibly above the multi-hour heavy-account queue waits the old comment called out.
- backend/routers/sync.py — extending the stale finalizer to sequenced jobs at both the pre-lock check and the post-lock re-read keeps the run-lease protection intact: a live worker still updating its job can never be failed by a poller. The new sequencer-release block calls finish_job(uid, job_id, epoch, 'stale_failed') when the owner's active_job_id matches, otherwise retire_expired(uid, job_id), then kick(uid); I confirmed all three APIs exist with these signatures and that finish_job/retire_expired are production-only, matching the production_stage() guard. The warning-level catch means a release failure logs rather than breaking the poll response.
- backend/tests/unit/test_sync_job_stale_self_heal.py — good coverage of the pure predicate: processing/queued staleness, retry preservation (attempt/started_at), completed-never-stale, and malformed-env fallback.
What I'd still want:
- Router-level coverage for the new sequencer-release block in get_sync_job_status (the ~16 added lines in backend/routers/sync.py) — e.g. finish_job called with 'stale_failed' on an owned stale job, retire_expired on an unowned one, and kick invoked in both cases. Right now the added tests only exercise is_sync_job_stale, so a regression in the release path would not be caught.
- A note somewhere (env docs or the sequencer module) on SYNC_SEQUENCED_STALE_SECONDS, since it is a new operational knob.
Blast radius: if wrong, a poller could prematurely fail a user's active sync job and release a sequencer slot early — the lease re-read and the 12h bound make that unlikely, but it is the surface a maintainer should eyeball.
USER IMPACT: users whose sync queue has been stuck for days on a lost sequenced job will see it self-heal (job fails with a recoverable error and the queue moves on) instead of hanging at "Processing 0/388 · 0%" indefinitely.
Because this changes terminal failure semantics and UID-sequencer ownership release in the sync core, leaving for human maintainer review before merge.
by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.
…C_SEQUENCED_STALE_SECONDS (BasedHardware#21943)
|
Thanks @Git-on-my-level! Both items from your review have been completed and pushed in commit 802853b:
@Git-on-my-level need human response — ready for human maintainer final review and merge! |
|
Since my last review: addressed (router-level coverage for the sequencer-release block and documentation of SYNC_SEQUENCED_STALE_SECONDS — both verified on this head) · still open (nothing blocking) · newly introduced (nothing in production logic; two non-blocking nits below). Both items I raised are resolved — from my side the code and coverage are in good shape:
One test-hygiene note: the module-level _StubFinder and db_client._firestore_client = MagicMock() run at import time and are process-global. Harmless today (suite green), but worth tightening if cross-module isolation ever flakes. USER IMPACT: a sync queue that has been deadlocked for days by a lost sequenced job will now unblock itself — the stuck job fails with a recoverable error and the rest of the queue proceeds instead of hanging forever. Merge call stays with a human maintainer: this PR changes when a sequenced sync job may be terminal-failed and who may release the per-UID sequencer lease, and that failure-semantics decision in the sync core deserves maintainer sign-off. by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with |
|
Since my last review: addressed (router-level sequencer-release tests — owned job -> finish_job('stale_failed') + kick, unowned -> retire_expired + kick, sequencer-exception resilience, non-production bypass, all in backend/tests/unit/test_sync_status_read_ownership.py; SYNC_SEQUENCED_STALE_SECONDS documented in backend/database/sync_backfill_sequencer.py and the sync-two-lane runbook) | still open (nothing blocking) | newly introduced (two minor nits below). Verdict: both items from my last review are addressed and verified on the current head; nothing blocking remains from my side. Verified per file:
Blast radius: unchanged — a premature stale-fail would fail a user's active sync job, but the post-lock re-read plus the 12h bound keep that unlikely, and the release path is now regression-tested. Performance: one extra owner read only on the rare stale-finalize path. USER IMPACT: users whose sync queue has been stuck for days on a lost sequenced job will see it self-heal (the stuck job fails with a recoverable error and the queue moves on) instead of hanging indefinitely. Nothing further required from me. Two optional nits above (single source for the 43200 default; runbook note on the retrying-queued case). This changes terminal failure semantics and UID-sequencer ownership release in the sync core, so it stays with the needs-maintainer-review label for human sign-off before merge. by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with |
#23233) ## Final merge acceptance — 2026-10-23 Final diff reviewed at `970d03e6e77ed0c65a2a97b9e77eab47660f6611`. Aryan explicitly accepts appropriate simulator/local integration evidence for Omi; the earlier physical-only merge prerequisites below are superseded, not represented as completed physical testing. - Fresh focused run on this head: **45 tests passed**, including startup/provider admission, account/session replacement, callback replacement, coordinator recovery, and paywall navigation. Command: `cd app && flutter test --no-pub --concurrency 1 --reporter expanded test/providers/sync_provider_background_admission_test.dart test/providers/sync_provider_startup_reconciliation_test.dart test/providers/sync_provider_session_generation_test.dart test/services/wals/recording_transfer_coordinator_test.dart test/widgets/trial_paywall_navigation_test.dart`. - **Installed iPhone 16 Pro simulator / iOS 26.5 component-integration run passed all three stages:** persisted synthetic WALs were seeded in process 64239, the host terminated it and verified that PID exited, then relaunched the same app as process 64868. Cold startup surfaced the completed conversation before any new upload; the genuinely queued job retained its handle. Reconnect rediscovered inventory and reset the exhausted local retry budget. A later completed server response surfaced the second conversation and acknowledged only its WAL. - Throughout all stages: **zero upload calls/attempts**, auto-sync opt-out respected, all three original file hashes and capture timestamps unchanged, and transfer-lease refcount returned to zero. The third local recording intentionally remains pending under auto-upload opt-out; no fake all-synced/customer-recovery claim. The production On the Way UI was inspected before/after and driven with Marionette debug controls. - Test composition: unchanged production SyncProvider, RecordingTransferCoordinator, SyncReconciler, LocalWalSync, HTTP/parser, file persistence and native lease bridge. External auth/token I/O, device discovery and loopback server job responses are synthetic; HTTP-header metadata uses the sanctioned local-harness initializer to avoid product telemetry. This is not full shipping-app sign-in/startup, actual STT, BLE, background scheduling/expiration or customer audio recovery. - Build identity: fresh Dart/assets compiled from this head with Flutter 3.44.5/Dart 3.12.2, local_dev/debug isolation. An already-built identical-native simulator shell was reused: `app/ios` and `pubspec.lock` match the previously compiled shell's source; the only pubspec difference is removal of bundled fonts, covered by fresh assets. No new full native-build claim. Simulator BGTaskScheduler scheduling was unavailable, as expected; no physical/background-execution evidence is claimed. - Evidence is retained privately with this maintainer task (phase/result journals, build/test logs, hashes and screenshots). Earlier broad-suite/CI evidence and the explicitly disclosed Siri timing flake in #23380 remain historical; a passing fresh focused run does not erase that record. No production code was modified for this pass. **Merge is separate from release and customer resolution.** Refs #23223 stays open pending release and customer outcome. No deployment, customer-account access, recording deletion or production job mutation is authorized/performed by this verification. Final current-head required checks and approval are rechecked immediately before merge. --- On relaunch, the transfer coordinator can reconcile an uploaded recording while `SyncProvider._admittedWorkGeneration` is still -1: the returned completed conversation is not surfaced, device discovery is skipped, and recovery depends on another upload starting first. Refactoring native keep-alive acquisition alone would also risk admitting an old account after an asynchronous lease wait. The existing coordinator now admits a transfer synchronously before native acquisition. Native lease holds for abandoned bodies do not re-admit work. Reconciliation, discovery, inventory refresh, reconnect retry resets and drains use the admitted account generation. A reconcile pass snapshots its conversation callback with its phone owner, so reattachment cannot deliver an old result into a replacement callback. Auto-sync opt-out remains respected; genuinely queued jobs remain pending with their original handles. Refs #23223. The Discord screenshot (381 recordings / 42 hours / nine almost ready) shows On the Way, not the on-device transcription banner. These are reproduced code defects, not a confirmed diagnosis or recovery of that account's backlog. #22484 is the existing merged missing-handle/poll-order fix; #21999 is a separate open proposal for legacy sequenced jobs and does not establish this account's cause. Validation: - Four regressions fail against unchanged main `a8fdd3889d` and pass after the fix: completed-conversation delivery before a new upload, startup device discovery, account replacement during native acquisition, and callback replacement during a status read. - 41 focused provider/coordinator tests pass. The real provider, coordinator, reconciler and phone WAL owner run against synthetic device/status/persistence boundaries. Completed conversation delivery executes the production HTTP/parser path over a fake HttpClient. The existing On the Way widget renders a pending recording, receives startup completion, renders all synced, and retains the same WAL; queued-job and auto-upload opt-out checks prevent false completion and duplicate sends. - Final full app run: 7,063 passed, four skipped, no failures; the separate opt-in protected spine also passes. All six hermetic mobile journeys pass (23 checks). The final normal pre-push gate passes all 24 selected manifest checks, and the analyzer ratchet passes with the original baseline unchanged. The history-dependent failure-class ratchet explicitly skips this shallow clone; no local full-history coverage is claimed. - The first broad run exposed an existing paywall test tapping the removed `trial_paywall_free` widget; it also failed with all three production sync files restored to unchanged main. A separate test-only commit exercises system back and the actual close control, retaining restore/no-pop/late-completion assertions. All four navigation tests and the final full suite pass; paywall production code is unchanged. - Remote CI on `07ea53ac7898e859f492aa81d4adc257e654f942`, checked 2026-10-23 through Code Review: Dart Analyze & Tests, Android compile/emulator/JVM, metadata, hygiene, formatting and backend merge gate pass; no failed or running checks remain. iOS compile and seeded-journey lanes were skipped; local hermetic journeys above are separate evidence. Cubic reported its review quota exhausted, which is not a completed independent review. - Commands: `TZ=UTC bash app/test.sh`; `(cd app && flutter test test/widgets/trial_paywall_navigation_test.dart)`; `(cd app && flutter test test/providers/sync_provider_background_admission_test.dart test/providers/sync_provider_startup_reconciliation_test.dart test/providers/sync_provider_session_generation_test.dart test/services/wals/recording_transfer_coordinator_test.dart)`; `(cd app && bash scripts/analyze_ratchet.sh)`; `make mobile-verify ARGS="fast --paths app/lib/providers/sync_provider.dart app/lib/services/wals/recording_transfer_coordinator.dart app/lib/services/wals/sync_reconciler.dart"`; `make preflight`. Release and limits: - Needs review/CI, merge and a mobile app release. This change adds no backend API, deployment, firmware, migration, audio deletion or timestamp rewrite. - Public iOS 1.0.570 is confirmed on the App Store on 2026-10-22. Codemagic build #4162 (`1.0.570+1430`, `b859b78f821217c0df0082359cbcf70b6f29987d`) includes #22484 by commit ancestry. The public page does not expose the binary build number, and the customer's installed build is unverified; later TestFlight artifacts are not a public release. - Physical iPhone and customer verification remain: exact app build and private diagnostics must identify the actual pending stage/job outcome; after release verify the queue declines and the corresponding conversations open. No customer account was accessed, audio recovered or production job redriven. Keep #23223 open until the customer outcome is verified. Preserve recordings and app data meanwhile. - Architecture and implementation checklist: `app/docs/offline-sync-stall-recovery.md`, startup transfer admission. ## Product invariants affected - INV-CAP-1: keep the existing capture/custody owner and native lease; change when a scoped recovery pass is admitted, with no audio loss or new pendant-uplink pause. `app/lib/services/capture/OWNERSHIP.md` defines pre-await generation capture and owner-ready recovery. - INV-UI-1 / INV-UI-3 / INV-PERF-1: no layout, copy, palette, new UI controls, UI-isolate audio work or additional poller. Existing queue rendering is exercised headlessly. Failure-Class: FC-sync-gated-on-consumer-trigger UI-Evidence: none -- startup/session wiring only; no widget layout or user-facing copy changes. Existing On the Way transition is tested through the real provider; no physical-device or native-build qualification is claimed. ## Merge verification gate Marked ready for code review on 2026-10-23 at Aryan's request. The former physical-only gate is superseded by the final simulator-first acceptance above; current-commit CI and independent approval still apply. Passing automated CI does not establish recovery of this customer’s recordings. ## 2026-10-23 maintainer review and merge gates Main integration conflict resolved without dropping system-back coverage; pushed c4aa08b. The 45 focused provider/coordinator/navigation tests, analyzer ratchet, 24 selected preflight checks and 23 hermetic cases across six mobile journeys pass. The bounded full Flutter run completed with 7,123 passed, 9 skipped and one failure in the unchanged Siri cooldown timing test. That file and service match main; its isolated suite then passed all 28 tests. This is not a green full-suite claim: the timing failure is tracked in #23380. Exact-head GitHub checks were green at the final review snapshot. The former installed-phone prerequisite is superseded by the final simulator-first acceptance above. Customer-specific verification remains post-release follow-up, not a claim of recovery. No recordings, customer account, or production jobs were changed. Current main was merged again in 970d03e (docs-only conflict).
fcec0b5 to
6d9b47f
Compare
|
Since my last review: addressed (both asks, verified on the new head) — router-level coverage for the sequencer-release block now exists in backend/tests/unit/test_sync_status_read_ownership.py: test_poll_sequenced_stale_owned_job_releases_sequencer asserts finish_job('owner', 'job-seq-owned', 11, 'stale_failed') plus kick, test_poll_sequenced_stale_unowned_job_retires_expired asserts retire_expired plus kick, and the exception-tolerance and non-production-stage paths are covered too. SYNC_SEQUENCED_STALE_SECONDS is now documented as an operational knob in backend/database/sync_backfill_sequencer.py (DEFAULT_SEQUENCED_STALE_SECONDS) and in the backend/docs/runbooks/sync-two-lane.md ownership paragraph, which matches the code. · still open (nothing) · newly introduced (nothing — the intervening commits are tests, knob docs, black formatting, and an upstream-main merge; I re-verified the finish_job/retire_expired/get_owner/kick/production_stage signatures survived the merge). Verdict: ready from my side — every previously requested item is in, and the Backend unit suite plus Backend Hermetic Merge Gate are green on the head. Two non-blocking notes for the record:
Security / blast radius: no new data exposure; the release path runs only behind the existing run-lock and production_stage guards and logs rather than raises on failure. If wrong, the worst case is prematurely failing a job that has actually been stale for 12h and releasing its sequencer slot early — recoverable, and far better than the permanent per-UID deadlock this fixes. USER IMPACT: users whose offline sync queue has been stuck for days on a lost sequenced job will see it self-heal — the job fails with a recoverable error and the queue moves on — instead of hanging indefinitely. Because this changes terminal failure semantics and UID-sequencer ownership release in the sync core, leaving for human maintainer sign-off before merge. by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with |
aryanorastar
left a comment
There was a problem hiding this comment.
6d9b47faec6625fa2076d073baad4983c60ad36e
backend/database/sync_jobs.py — swallowed Exception on sequencer release (pass).
Summary
Resolves #21943 (also addresses recurring offline sync deadlocks as reported in #21279).
Failure-Class: none
Line-Count-Exception: backend/routers/sync.py | 2849 -> 2865 | unblock multi-day offline sync queue deadlocks on stale sequenced jobs
Root Cause
get_sync_job_status(backend/routers/sync.py), the stale finalizer check explicitly enforced:is_sync_job_stale(backend/database/sync_jobs.py), any job withdispatch_mode == 'sequenced'immediately returnedFalse:dispatch_mode: 'sequenced', if a sequenced backfill stalled, exceeded the queue threshold, or lost its worker, it could never be evaluated as stale. The active job remained stuck inqueued(orprocessing) indefinitely, holding the per-UID owner lock (active_job_id) and permanently deadlocking the user's entire sync queue (e.g., "Processing 0/388 · 0%").Changes
backend/database/sync_jobs.py:attempt/started_atpresent) to ensure backoff retries are preserved.sequencedjobs, configured the stale threshold to honor the 12-hour per-UID sequencer queue window (SYNC_SEQUENCED_STALE_SECONDS, defaulting to 43,200s), ensuring normal heavy-account queues are preserved while multi-day deadlocks are caught and resolved.cloud_tasksjobs, preserved the existing 30-minute queued stale threshold and 10-minute processing threshold.backend/routers/sync.py:get_sync_job_statusstale evaluation to allow both'cloud_tasks'and'sequenced'dispatch modes.sync_backfill_sequencer, then kick the sequencer (uid_sequencer.kick) so subsequent queued jobs can proceed immediately.backend/tests/unit/test_sync_job_stale_self_heal.py:test_sync_backfill_uid_sequencerandtest_sync_job_stale_self_healpass 100%.