Skip to content

fix(app): drain offline-sync history oldest-first and honor 5xx Retry-After - #23679

Merged
Git-on-my-level merged 2 commits into
mainfrom
lane/sync-503
Oct 26, 2026
Merged

Git-on-my-level merged 2 commits into
mainfrom
lane/sync-503

Conversation

@Git-on-my-level

Copy link
Copy Markdown
Member

fix(app): drain offline-sync history oldest-first and honor 5xx Retry-After

What

Offline Sync could leave the oldest pending audio untried for weeks — observed on iOS 1.0.577: 395 pending phone WALs (3h27m of audio), the oldest 20.6 days — while every drain spent its progress on the newest recordings first, and unscoped 503s from /v2/sync-local-files failed batch after batch without any pause.

Two app-side changes:

  1. Deadline-ordered drain. nextSyncUploadBatch keeps live capture first (newest-first — the only audio that can still claim its conversation's capture manifest) and orders everything older oldest-first. The server permanently refuses audio older than SYNC_BACKFILL_MAX_AGE_SECONDS (30 days) with 422 backfill_lookback_exceeded, which retires the recording terminal (outsideRecoveryWindow). A drain that is interrupted — rate-limit break, cancelled run, app backgrounding — truncates from the tail, so ordering history newest-first starved exactly the recordings with the least recovery time left; oldest-first makes every interruption cost the audio with the most slack instead. Conversation/session/location grouping and batch budgets are unchanged.
  2. Paced 5xx handling. SyncUploadHttpException now carries the server's Retry-After when a 5xx provides one, and SyncUploadGate installs the in-memory backendBusy cooldown for it — one refusal stops the drain instead of failing every remaining batch against the same condition (the backend's sync_dispatch_unavailable and ledger-fence 503s always carry Retry-After: 30–60). Unscoped 5xx (platform shedding under load) get a growing inter-batch pause (2s doubling, capped at 30s) instead of immediately re-uploading the next full multipart body.

Production evidence (2026-10-26, times UTC)

  • Phone drain 03:24–03:30Z: SyncUploadHttpException(status=503) at batches 2/4/6/15/26 (terminal=false); wal_stale_missing pending_wal_count=395 pending_audio_seconds=12460 oldest_pending_age_seconds=1777438.
  • backend-sync Cloud Run request logs, POST /v2/sync-local-files 02:00–06:00Z: 10× 503; in the 03:25–03:30 slice 5× 503 vs 97× 202 and 154× 400. Two 503 families:
    • Platform 503 (209-byte body, zero application logs, latency 3–9.7s ≈ full body upload): backend-sync is pinned at its max-instance ceiling 24/7 (80 until 2026-10-24 08:00Z, 50 since); the request proxy sheds these after the body arrives. Fleet-wide on this route only: 463 on Oct-20, 78 on Oct-25, 10 through 05:30Z on Oct-26.
    • Application 503 sync_dispatch_unavailable (232-byte, sub-second, Retry-After: 30): DestructiveOperationInProgress from the legal-holds owner_storage_write_gate raised during _stage_files_to_gcs staging. Chronic: Oct-19 ≥1,892, Oct-20 341, Oct-21 ≥1,959 (both query-capped at 2,000), Oct-22 328, Oct-23 93, Oct-24 19, Oct-25 65, Oct-26 (partial) 8.
  • No loss from app retention: the admission count cap (720 vs retained 5,314, blocked_count=0) is warning-only — pending copies are never evicted and admission is never refused for count; autoRemoveSyncedCopies deletes only synced copies with a known syncedAt. The real cliff is the server's 30-day recovery window: the Oct 5 backlog starts being refused permanently around Nov 4, which is why the oldest files must drain first.

Product invariants affected

INV-CAP-1: neither change discards or evicts pending audio. Reordering only changes which durably-retained WAL uploads first, and the new 5xx pauses stop transmission while every pending file stays retained on disk — the invariant's allowed pause-while-retaining case; the 720-count cap and auto-remove policies are untouched.

Client-compat

Additive only: SyncUploadHttpException gains an optional named field (retryAfterSeconds); no wire-format or request changes.

Testing

  • flutter test test/unit/local_wal_sync_test.dart test/unit/wal_upload_resilience_test.dart test/unit/sync_upload_gate_test.dart test/services/wals/mobile_standard_batch_test.dart — all passing (235 tests). The batch-ordering contract is updated deliberately: historical batches now assert oldest-first; live-capture priority, conversation grouping, and budgets are unchanged.
  • New coverage: the gate installs the backendBusy cooldown on a 503 with Retry-After and refuses the next upload client-side; a drain stops after one refused batch with no retry-budget spend; an unscoped 503 drain keeps attempting every batch with a [2,4,8,16]s pause sequence; syncServerUnavailablePauseSeconds caps at 30s; mixed live/historical ordering.
  • Full app hermetic suite: bash test.sh — 7,504 passed, 9 skipped, 0 failed.
  • Backend untouched: BACKEND_UNIT_TEST_FILE_LIST=<empty> bash test.sh selects no backend unit tests.

Failure-Class: new

Line-Count-Exception: app/lib/services/wals/local_wal_sync.dart | 2611 -> 2636 | unscoped-5xx inter-batch pause needs the drain-loop streak state and a testable sleep seam beside the existing retry metadata in this file

UI-Evidence: none -- service-layer sync ordering and retry pacing only; no UI files changed

🤖 Generated with Claude Code

…-After

Offline Sync ordered its pending backlog newest-first, so every interrupted
drain (rate-limit break, cancel, backgrounding) spent its progress on the
audio with the most recovery-deadline slack and the oldest recordings were
attempted last indefinitely — observed as 395 pending WALs with the oldest
20.6 days old, nine days from the server's permanent backfill_lookback
refusal. Live capture still leads newest-first (only it can claim its
conversation's capture manifest); everything older now drains oldest-first.

Unscoped 503s also failed batch after batch with no pacing. A 5xx that
carries Retry-After (sync_dispatch_unavailable behind an account gate,
ledger-fence cutover) now installs the in-memory backendBusy cooldown, so
one refusal stops the drain; unscoped 5xx (platform shedding at the
max-instance ceiling) get a growing 2s..30s inter-batch pause instead of an
immediate full-body re-upload.

Failure-Class: new (FC-offline-drain-newest-first-starves-recovery-deadline)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 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-26T06:36:49.444244Z 143d09f PR opened
ℹ️ 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 e459203 into main Oct 26, 2026
45 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/sync-503 branch October 26, 2026 07:16
Git-on-my-level added a commit that referenced this pull request Oct 28, 2026
### What does this PR do?

Re-implementation of community PR #17825 by @TheRWX (approved, but
conflicted and unmoved since 2026-10-05) on today's sync code and the
rulings that landed since. Fixes #15501: Android users silently lost
days of pendant recordings with no "device not syncing" warning; others
only sync when they open the app.

A new `SyncHealthWatchdog` (app/lib/services/sync_health_watchdog.dart)
watches the paired pendant's pipeline:

- **Activity signals.** BLE audio bytes arriving, a WAL accepted by the
server (`onWalSynced` — every upload path, manual and drain), a batch
recording finalized, and the pendant (re)connecting. Any of them proves
recordings are moving — audio is then safe on the phone or on the
server, and the #23679/#23822 drains (oldest-first, Retry-After, quiet
refusals) own recovery. Only silence across **every** signal is a stall
the user must hear about. Refusal-only stretches stay quiet by design: a
refusal with live ingestion is not data loss, and #23822 deliberately
keeps refusals out of user attention.
- **Stall threshold: 24 hours.** Longer than the longest normal daily
gap — a pendant taken off and charged overnight (~8–12h silent) — and
far inside the reported 4-day silent losses, with #23679's 30-day server
backfill window still far away. (The original 4h threshold would alert
every morning when quiet hours end.)
- **Alert cadence.** At most one reminder per day (24h cooldown), never
22:00–08:00 local (quiet hours do not spend the cooldown), notification
id 15501, tap lands on Device settings (`/settings/device`, the
capture-recovery push precedent). The silence clock seeds on first run,
so the app update itself cannot alarm.
- **Not a disconnect push (#3328).** No per-event notification; onboard
storage keeps recording across BLE drops. This alert fires only after a
full day of zero flow — the state where users actually lost data. Acute
stalls stay the wedge monitor's job in-app (connected-no-bytes within
minutes, upload silence at 2h with a backlog); this is the out-of-app
last resort.
- **Scope.** Paired pendant types only (`omi`, `friendPendant`); watches
and glasses sync on their own cadence. Ships on by default with a kill
switch ("Sync Health Alerts", Device Settings).

**Surfacing, per #22119** (capture/sync problems speak on the live
capture page and the Activity bell, never Home):

- Activity → Needs attention: "Omi isn't syncing · No recordings synced
for over N hours" (cloud-off row, opens Offline Sync; ordered after the
upload row as the broadest, slowest condition). Fed through
`CaptureWedgeMonitor.observeSyncSilence`, so the bell's unseen-dot
machinery is reused unchanged.
- Device Settings: the "Sync Health Alerts" toggle sits under the device
group; its subtitle switches to the live stall duration while stalled.
- The original PR's Home indicator is deliberately **not**
re-implemented.

The watchdog's periodic loop starts in app bootstrap (main.dart, after
prefs init); `DeviceProvider` wires each evaluation into the wedge
monitor and exposes `isSyncStalled`/`syncHealth`. Timer ownership stays
out of the provider so provider tests never hold a pending timer.

### Renders (headless visual-audit captures, synthetic state)

Activity — the new sync stall row:
![Activity sync stall
row](https://raw.githubusercontent.com/BasedHardware/omi/bf706226c6f7/.agent-artifacts/ui-evidence/cs-syncalerts/001-mobile-ios-activity-sync-stall.png)

Device Settings — the alert toggle with the stall subtitle:
![Device Settings stall
toggle](https://raw.githubusercontent.com/BasedHardware/omi/bf706226c6f7/.agent-artifacts/ui-evidence/cs-syncalerts/002-mobile-ios-device-stall-toggle.png)

Activity — the existing capture rows, unchanged by this PR:
![Activity capture rows
unchanged](https://raw.githubusercontent.com/BasedHardware/omi/bf706226c6f7/.agent-artifacts/ui-evidence/cs-syncalerts/003-mobile-ios-activity-capture-attention.png)

## Product invariants affected

- INV-DATA-1
- INV-CAP-1

INV-DATA-1 applies because `app/lib/main.dart` is a protected data-plane
routing authority; this PR only starts the watchdog's periodic timer
there after prefs init — no routing, endpoint, build define, or bundled
env value changes.

INV-CAP-1: touches `app/lib/services/capture/capture_wedge_monitor.dart`
only to add a slow-burn `CaptureSyncSilence` row (declared and ended
solely by the watchdog's evaluation) to Needs attention and the bell's
unseen logic. Ingress, retention and admission behavior are unchanged;
the new row makes no saved-audio claim.

## How it was verified

- `flutter test` (full hermetic `bash test.sh` CI suite): 7921 passed /
9 skipped; the single failure during the run was this PR's own new
visual-audit scenario before a fixture fix, green on re-run (`flutter
test test/visual_audit/visual_audit_smoke_test.dart`: 158 passed).
- New suites: `test/unit/sync_health_watchdog_test.dart` (device gating,
24h threshold arithmetic, daily cooldown, quiet hours, toggle, seeding,
throttle incl. no clock rewind, timer lifecycle) and new groups in
`test/services/capture/capture_wedge_monitor_test.dart` (sync-silence
row + bell) and `test/widgets/needs_attention_capture_test.dart` (row
render, absence, Offline Sync tap, ordering behind the upload row).
- `make mobile-verify ARGS="fast --all"`: 31/31 journeys passed
(full-suite fallback selected — cross-cutting `app/lib` change).
- `flutter analyze`: no new findings (pre-existing environment-only
errors in flavor-generated files aside, which `test.sh` bootstrap
generates).
- `python3 app/scripts/l10n.py check`: ok, 49 locales; 6 new keys via
the tool.
- `check_mobile_ux_contract.py` on the two touched UI files: clean.
- `tool/perf_shell.py --check`: PASS (shell regenerated for the
main.dart import).
- Renders above: `app/scripts/visual_audit.sh --head WORKTREE --only
activity-sync-stall,device-sync-stall-alerts,activity-capture-attention`.

## Not verified / limitations

- The watchdog evaluates only while the app process runs (the capture
foreground service keeps it alive on Android). If the OS kills the
process, no alert can fire until it runs again — the same boundary the
original PR had.
- The Activity row's hour count refreshes on watchdog ticks (30 min),
not per minute.
- No on-device run: all verification is hermetic (widget tests,
journeys, headless renders).

Line-Count-Exception: app/lib/backend/preferences.dart | 1612 -> 1630 |
three persisted sync-health keys: alert toggle, last activity timestamp,
last alert timestamp
Line-Count-Exception: app/lib/providers/device_provider.dart | 1624 ->
1663 | watchdog wiring, stall getters, connect/disconnect hooks
Line-Count-Exception: app/lib/services/capture/capture_controller.dart |
4602 -> 4609 | record sync-activity on BLE audio and batch finalization

Failure-Class: none

Closes #15501
Re-implements #17825 (original by @TheRWX, co-authored there)


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/23884?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<a
href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/23884?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F23884&source=description"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img
alt="Turn on auto-fix"
src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
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