Skip to content

fix(sync): recover stale sequenced sync jobs and unblock account queues (#21943) - #21999

Open
hardik4love-lang wants to merge 9 commits into
BasedHardware:mainfrom
hardik4love-lang:fix/sync-sequenced-stale-job-recovery
Open

hardik4love-lang wants to merge 9 commits into
BasedHardware:mainfrom
hardik4love-lang:fix/sync-sequenced-stale-job-recovery

Conversation

@hardik4love-lang

@hardik4love-lang hardik4love-lang commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

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

  1. In get_sync_job_status (backend/routers/sync.py), the stale finalizer check explicitly enforced:
    and job.get('dispatch_mode') == 'cloud_tasks'
    and locked_job.get('dispatch_mode') == 'cloud_tasks'
  2. In is_sync_job_stale (backend/database/sync_jobs.py), any job with dispatch_mode == 'sequenced' immediately returned False:
    if job.get('dispatch_mode') == 'sequenced':
        return False
  3. Because backfill jobs are explicitly tagged 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 in queued (or processing) 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%").
  4. Subsequent status polling from the app continuously encountered the stuck job without resolution, flooding the endpoint with 429 rate limits.

Changes

  1. backend/database/sync_jobs.py:
    • Guarded queued retrying jobs (attempt / started_at present) to ensure backoff retries are preserved.
    • For sequenced jobs, 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.
    • For cloud_tasks jobs, preserved the existing 30-minute queued stale threshold and 10-minute processing threshold.
  2. backend/routers/sync.py:
    • Expanded get_sync_job_status stale evaluation to allow both 'cloud_tasks' and 'sequenced' dispatch modes.
    • When a sequenced job is finalized as stale, safely release the backfill slot and unbind/retire the active owner in sync_backfill_sequencer, then kick the sequencer (uid_sequencer.kick) so subsequent queued jobs can proceed immediately.
  3. backend/tests/unit/test_sync_job_stale_self_heal.py:
    • Added unit tests verifying stale evaluation for sequenced processing and queued states, while verifying fresh and retrying jobs remain protected.
    • All 99 backend unit tests in test_sync_backfill_uid_sequencer and test_sync_job_stale_self_heal pass 100%.

@hardik4love-lang

Copy link
Copy Markdown
Contributor Author

Hi @Git-on-my-level, @kodjima33,

All automated CI checks, hygiene preflights, unit test shards, and merge gates are now 100% green:

  • Formatting: PASS
  • Hygiene: PASS (Failure-Class: none & Line-Count-Exception validated)
  • Backend Unit Shards (1/6 – 6/6): PASS
  • Backend Unit Suite: PASS
  • Backend Hermetic Merge Gate: PASS
  • Mobile Release Eligibility: PASS

Ready for maintainer review and merge!

@Git-on-my-level

Copy link
Copy Markdown
Member

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 is_sync_job_stale hoists the queued-retry guard (attempt/started_at set → never stale) ahead of the mode dispatch, which preserves the pending-retry invariant for every dispatch mode, and the sequenced branch keeps a generous 12h default (SYNC_SEQUENCED_STALE_SECONDS) so heavy-account queues aren't reaped mid-wait. Two nits:

  • int(os.getenv('SYNC_SEQUENCED_STALE_SECONDS', '43200')) is unguarded — a malformed env value would raise inside a status poll; the module's existing clamped-TTL-helper pattern is safer.
  • The sequenced branch no longer gates on status, so a completed sequenced job between 12h and the 24h job TTL now evaluates stale. I traced the path: update_sync_job refuses mutations on terminal statuses (sync_jobs.py:477), so finalize_sync_job_failure_now returns None and nothing is flipped — harmless, but an explicit status in ('queued', 'processing') gate would make the intent clearer and skip a pointless lock acquire.

backend/routers/sync.py — admitting 'sequenced' at both the pre-lock check and the post-lock re-read is the right shape (an active worker can still win the lease race). The new release block correctly requires uid_sequencer.production_stage(), releases the owner with finish_job(uid, job_id, epoch, 'stale_failed') only when owner.active_job_id == job_id and the epoch is an int, falls back to retire_expired(uid, job_id) for unbound pending work, then kick(uid)s the queue; exceptions are contained with a logged warning. Nesting under the BACKFILL-lane branch checks out — dispatch_mode: 'sequenced' is only ever set for lane=BACKFILL queued jobs in the migration path (~sync.py:1988).

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 get_sync_job_status), which is the piece that actually unblocks the queue — a focused unit test stubbing sync_backfill_sequencer and asserting the owner-release/kick ordering would lock the behavior in.

One residual worth stating: queued jobs with attempt/started_at set (pending retry after a worker cycle) remain non-reapable by design, so if any of the #21943/#21279 reports fall in that class the deadlock can still persist — there the UID sweeper stays the owner, which the PR preserves deliberately.

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 need human response.

@Git-on-my-level Git-on-my-level added needs-maintainer-review Needs a human maintainer to sign off before merge backend Backend Task (python) labels Oct 17, 2026
@hardik4love-lang

Copy link
Copy Markdown
Contributor Author

Thanks @Git-on-my-level for the thorough review and validation!

Addressed the feedback in commit \4975b7d68e:

  1. Safe Env Parsing: Added _sequenced_stale_seconds()\ helper in \�ackend/database/sync_jobs.py\ to catch \ValueError/\TypeError\ on malformed or negative env values, guaranteeing safe fallback to the default 43,200s window without raising inside the status poll.
  2. Explicit Status Gate: Updated the sequenced branch to \if dispatch_mode == 'sequenced' and status in ('queued', 'processing'):\ ensuring terminal states like \completed\ are never evaluated as stale and skipping unnecessary lock attempts.
  3. Unit Tests: Added unit tests in \�ackend/tests/unit/test_sync_job_stale_self_heal.py\ verifying that completed sequenced jobs are never flagged stale and that malformed env values fall back safely to 43,200s (all 8 tests passing).

Ready for final merge!

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

@Git-on-my-level Git-on-my-level added the needs-tests PR introduces logic that should be covered by tests label Oct 18, 2026
@hardik4love-lang

Copy link
Copy Markdown
Contributor Author

Thanks @Git-on-my-level!

Both items from your review have been completed and pushed in commit 802853b:

  1. Router-level coverage for the sequencer-release block:
    Added 4 comprehensive router-level unit tests directly in �ackend/tests/unit/test_sync_status_read_ownership.py exercising get_sync_job_status end-to-end via FastAPI TestClient:

    • est_poll_sequenced_stale_owned_job_releases_sequencer: verifies inish_job(uid, job_id, epoch, 'stale_failed') and kick(uid) are invoked when owner.active_job_id == job_id.
    • est_poll_sequenced_stale_unowned_job_retires_expired: verifies
      etire_expired(uid, job_id) and kick(uid) are invoked for unowned/expired waiting jobs.
    • est_poll_sequenced_stale_sequencer_exception_does_not_crash_poll: verifies exceptions during sequencer release log a warning and return 200 without crashing client status polling.
    • est_poll_sequenced_stale_non_production_stage_bypasses_sequencer: verifies stage-gating correctly skips sequencer calls outside of production.
      (All 16 unit tests in est_sync_status_read_ownership.py and 8 unit tests in est_sync_job_stale_self_heal.py pass cleanly).
  2. Operational knob documentation:

    • �ackend/docs/runbooks/sync-two-lane.md: documented SYNC_SEQUENCED_STALE_SECONDS (default: 43,200s / 12h) under ## Per-UID backfill dispatch, explaining the stale poll recovery and owner lease release behavior.
    • �ackend/database/sync_backfill_sequencer.py: documented DEFAULT_SEQUENCED_STALE_SECONDS in module constants alongside WAIT_ALERT_SECONDS.

@Git-on-my-level need human response — ready for human maintainer final review and merge!

@Git-on-my-level

Copy link
Copy Markdown
Member

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:

  • backend/tests/unit/test_sync_status_read_ownership.py — the four new router tests cover exactly the release matrix I asked for: an owned stale sequenced job finalizes via finish_job('owner', job, epoch, 'stale_failed') with retire_expired not called and kick('owner') invoked; an unowned one goes through retire_expired with finish_job not called; a sequencer exception still leaves the poll at 200; and a non-production stage bypasses the sequencer entirely. The fake_eval shim reimplements the run-lock Lua scripts on fakeredis, so these exercise the real finalizer path rather than a stubbed one.
  • backend/docs/runbooks/sync-two-lane.md — the new sentence documents SYNC_SEQUENCED_STALE_SECONDS (default 43200s) plus the finish_job('stale_failed') / retire_expired / kick recovery; each claim matches the release block in backend/routers/sync.py (~line 1780) and _sequenced_stale_seconds in backend/database/sync_jobs.py.
  • backend/database/sync_backfill_sequencer.py — nit: DEFAULT_SEQUENCED_STALE_SECONDS is declared here as documentation, but backend/database/sync_jobs.py hardcodes its own '43200' default; the two can silently drift. A follow-up importing the constant (or cross-linking in a comment) would fix it.
  • backend/database/sync_jobs.py and backend/routers/sync.py — unchanged since my last review (verified via the inter-head diff); the earlier correctness verification stands, including that finish_job rechecks owner + epoch transactionally so a racing live worker can never be released early.

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 need human response.

@Git-on-my-level Git-on-my-level added positive-signal Automation verified a genuine fix/quality contribution and removed needs-tests PR introduces logic that should be covered by tests labels Oct 19, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

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:

  • backend/tests/unit/test_sync_status_read_ownership.py — the four new poll tests cover exactly the release-path regression risk I flagged: finish_job called once with ('owner', job, epoch, 'stale_failed') and kick on the owned case, retire_expired + kick on the unowned case, a RuntimeError from get_owner only logging (poll still returns 200/failed), and production_stage()=False skipping sequencer calls entirely. The added fakeredis eval shims and third-party stub finder are self-contained and the suite is green.
  • backend/database/sync_backfill_sequencer.py — the knob comment plus DEFAULT_SEQUENCED_STALE_SECONDS documents the new operational control. One nit: the 43200 default now lives here AND hardcoded in sync_jobs._sequenced_stale_seconds() — worth deriving one from the other so they can't silently diverge.
  • backend/database/sync_jobs.py — unchanged from the previously verified logic apart from black formatting on the upstream merge; cloud_tasks thresholds and the queued-retry guard are behavior-preserving. Residual (deliberate, conservative): a queued sequenced job that already has attempt/started_at set never goes stale — retries are expected to come; if that case can also lose its worker, a runbook sentence would help.
  • backend/routers/sync.py — sequencer-release block unchanged; I confirmed against the sequencer module that finish_job re-verifies active_job_id/active_epoch inside its Firestore transaction and retire_expired proves ownership/absence transactionally, so a racing live worker cannot be displaced by a poller.
  • backend/docs/runbooks/sync-two-lane.md — the new sentence matches the implementation (stale poll finalization -> finish_job('stale_failed') or retire_expired, then kick).
  • backend/tests/unit/test_sync_job_stale_self_heal.py — predicate coverage (processing/queued staleness, retry preservation, completed-never-stale, malformed-env fallback) unchanged and still good.

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 need human response.

aryanorastar added a commit that referenced this pull request Oct 23, 2026
#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).
@hardik4love-lang
hardik4love-lang force-pushed the fix/sync-sequenced-stale-job-recovery branch from fcec0b5 to 6d9b47f Compare October 31, 2026 04:24
@Git-on-my-level

Copy link
Copy Markdown
Member

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:

  • backend/database/sync_jobs.py _sequenced_stale_seconds() hardcodes the 43200 default and fallback instead of reusing DEFAULT_SEQUENCED_STALE_SECONDS from backend/database/sync_backfill_sequencer.py; fine if a shared import would create a cycle, but the two literals can drift silently.
  • The hoisted queued-retry guard means a sequenced job carrying attempt/started_at is never poll-recovered even if its retry pipeline dies. That is the intended backoff preservation (retry liveness belongs to the worker/sweeper) and matches the pre-existing safety model — just noting it bounds what this self-heal covers.

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 need human response.

@aryanorastar aryanorastar left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

6d9b47faec6625fa2076d073baad4983c60ad36e

backend/database/sync_jobs.py — swallowed Exception on sequencer release (pass).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) needs-maintainer-review Needs a human maintainer to sign off before merge positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Offline sync has been stuck since 2026-10-15 ~21:00 KST.

3 participants