Repository navigation
fix(app): confirm missing sync jobs across restarts; dead backlogs no longer starve new uploads - #22484
Conversation
…klogs starving new uploads The poller kept first-404 observations only in memory and ordered never-polled handles by job id. A phone holding thousands of server-retired handles re-polled the same lexically first handles in every process, never confirmed one, and never reached its new uploads, so On the Way grew with every recording. First-404 times now persist (bounded, 7-day retention), so a later process confirms them. Handles ready to confirm go first. Recent uploads and older handles alternate, newest first within each class. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4f503a9b3a
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| final confirm = all.where(confirmable).toList()..sort(compare); | ||
| final rest = all.where((id) => !confirmable(id)); | ||
| final recent = rest.where((id) => uploaded(id) >= recentFloor).toList()..sort(compare); | ||
| final older = rest.where((id) => uploaded(id) < recentFloor).toList()..sort(compare); | ||
| final out = <String>[...confirm]; |
There was a problem hiding this comment.
Interleave confirmable handles with fresh uploads
When more than 18 persisted handles are ready for confirmation—a reachable state after repeated short-lived processes collect first-404 observations—placing the entire confirm list first exhausts the shared 18-request/minute budget before any recent upload is reached. With the allowed 20,000-entry store, fresh recordings can again remain unpolled for many hours, contradicting the starvation fix; confirmable handles need to share admission with the recent/older queues rather than unconditionally preceding both.
Useful? React with 👍 / 👎.
| void save(Map<String, int> firstMissingEpochMs) { | ||
| try { | ||
| SharedPreferencesUtil().saveString(key, jsonEncode(firstMissingEpochMs)); | ||
| } catch (_) { |
There was a problem hiding this comment.
Await persistence before treating a missing observation as durable
If the app is terminated or restarted shortly after the first 404, this method returns without waiting for the Future<bool> from saveString, so the platform write may still be pending when the process dies and the next process starts without the observation. The surrounding try also cannot catch an asynchronous write failure. This recreates the restart-reset behavior the change is intended to fix; make the store write asynchronous and await it before fetch returns the first-404 result.
Useful? React with 👍 / 👎.
| final kept = _missing.entries.where((e) => !e.value.isBefore(cutoff)).toList() | ||
| ..sort((a, b) => b.value.compareTo(a.value)); | ||
| store.save({for (final e in kept.take(maxPersistedMissing)) e.key: e.value.millisecondsSinceEpoch}); |
There was a problem hiding this comment.
Scope persisted observations to the active account
When a user signs out and another user signs in without restarting the process, the sign-out path clears SharedPreferences and both WAL/job inventories, but the singleton poller's _missing map survives; the next call here serializes the former user's job IDs back into the newly cleared preference store alongside the new user's state. This defeats account-data clearing and can also reuse the former account's confirmation timestamp if a handle is ever reused, so the stored map needs to be keyed by owner or explicitly reset on account changes.
Useful? React with 👍 / 👎.
| final cutoff = now.subtract(const Duration(days: 1)); | ||
| _nextPoll.removeWhere( | ||
| (id, deadline) => deadline.isBefore(cutoff) && !_inFlight.contains(id) && !_missing.containsKey(id), | ||
| ); |
There was a problem hiding this comment.
Prune orphaned missing observations from memory
If a handle disappears from the caller's job inventory after its first 404—for example because its recording is deleted or account state is cleared before confirmation—this condition preserves its _nextPoll entry solely because it remains in _missing, and no later fetch exists to remove it. _saveMissing filters only the serialized copy, not the in-memory map, so a long-lived process can accumulate orphaned observations without the advertised seven-day or 20,000-entry bounds and must sort the entire growing map on every subsequent save; prune expired or no-longer-owned entries from _missing as well.
Useful? React with 👍 / 👎.
| void persistMissingWith(SyncJobMissingStore store) { | ||
| _missingStore = store; | ||
| _missingLoaded = false; |
There was a problem hiding this comment.
Flush observations recorded before persistence is enabled
At startup, LocalRecordingsProvider can use the shared poller and receive a first 404 before LocalWalSync evaluates its lazy _jobPoller initializer and calls this method. In that ordering the observation was added while _missingStore was null; assigning the store here only resets the load flag, and _loadMissing subsequently skips the already-present key without ever saving it. If the process exits before another missing-state mutation, the supposedly durable observation is lost, so persistence should be configured before either polling owner starts or this method should flush existing entries.
Useful? React with 👍 / 👎.
| _missing.remove(jobId); | ||
| _confirmedMissing.add(jobId); | ||
| _saveMissing(); |
There was a problem hiding this comment.
Keep confirmed observations until the owner state is durable
When the second 404 confirms a missing job, this removes and persists the observation before either caller durably removes the job from its WAL or local-recording sidecar. If the process is killed during the subsequent file checks or before _saveWalsToFile/_saveJobs completes, the next process restores the job as still uploaded but no longer has the confirmed observation, forcing the same two-404 cycle from scratch. Retain a durable confirmed marker until the caller acknowledges that its state transition has been saved.
Useful? React 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).
Summary
On the Way grows without bound on phones that hold handles the server retired (the Oct 15–17 expiry path). Production evidence (24h, aggregates) from one heavily affected iPhone:
0–4.bp_uploads, although the server had completed them.Cause, in
SyncJobPoller:Fix:
syncJobFirstMissingV1, 7-day retention, max 20k), so a later process confirms a handle with one more 404 after the 5-minute window. Confirmation and the revert path are otherwise unchanged: retained audio becomesmissand re-uploads; missing audio becomescorrupted. A successful read clears a stale observation.bp_) and vice versa. Callers without upload times (Transcribe Later) keep oldest-due-first.LocalWalSync. Isolated pollers in tests stay hermetic.The companion server change #22483 answers custody-held retired handles with
completed(sync_retired_preserved), which clears them on the first poll. This app fix also covers handles the server cannot acknowledge.Product invariants affected
miss(local audio retained and re-uploaded) or tocorruptedonly when the local file is already absent, exactly as before. Only the timing of confirmation and the poll order change.Failure class (fixes)
Failure-Class: new
Line-Count-Exception: app/lib/services/wals/local_wal_sync.dart | 2752 -> 2757 | passes per-job upload times to the poller and opts the singleton into durable missing confirmation; logic lives in sync_job_poller.dart
UI-Evidence: none -- service-layer poll ordering/persistence only; no widget or layout change
Verification
flutter test test/unit/sync_job_poller_backlog_test.dart test/unit/sync_poll_storm_test.dart test/unit/local_wal_sync_test.dart test/unit/sync_status_privacy_contract_test.dart: 257 passed.bp_uploads, confirmable handles first, and the legacy order without upload times.🤖 Generated with Claude Code