Skip to content

fix(app): run bounded cloud sync grace when screen locks (#7221) - #11127

Merged
kodjima33 merged 3 commits into
BasedHardware:mainfrom
aryanorastar:fix/7221-sync-background-grace
Aug 6, 2026
Merged

kodjima33 merged 3 commits into
BasedHardware:mainfrom
aryanorastar:fix/7221-sync-background-grace

Conversation

@aryanorastar

@aryanorastar aryanorastar commented Aug 5, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

When the screen locks, Flutter hits paused and #9763's foreground-only RecordingTransferCoordinator stops all upload/reconcile work. That matches #7221: overnight with the app "open" on fiber Wi-Fi still only drains ~5% of a 1000+ file backlog, and "processing on server" freezes at 0%.

Implementation

  • Pure decideScreenLockedSyncContinuation policy (app/lib/utils/sync_continuation_policy.dart).
  • New WakeTrigger.screenLockedGrace: while backgrounded, runs reconcile + bounded phone-disk uploads only (max 3 batches / ~15 WALs). Skips BLE device discovery/drain.
  • SyncReconciler.onBackground starts that grace when miss/uploaded work exists; iOS beginBackgroundTask via com.omi/sync_background_task.
  • WalSyncs.syncLocalUploadsOnly + LocalWalSyncImpl.maxBatches for the bounded pass.

Out of scope: overnight BGProcessingTask for full 1000+ drain, BLE flash download in background, server job pipeline stalls.

Tests

  • flutter test test/unit/sync_continuation_policy_test.dart
  • flutter test test/services/wals/recording_transfer_coordinator_test.dart

Product invariants affected

none

Failure class (fixes)

Failure-Class: none

Review in cubic

…re#7221)

Foreground-only recovery stopped all uploads/reconcile on pause, so large
backlogs stalled overnight. Allow one phone-disk upload + reconcile pass
under iOS beginBackgroundTask; keep BLE drains deferred.

Failure-Class: none
Co-authored-by: Cursor <[email protected]>
@aryanorastar
aryanorastar requested a review from mdmohsin7 as a code owner August 5, 2026 05:03
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

2 issues found across 10 files

Confidence score: 2/5

  • In app/lib/providers/sync_provider.dart, the screen-lock grace loop can run beyond the intended three-batch cap because failed/rejected batches don’t decrement the maxBatches budget, which risks prolonged background work during outages and battery/network drain — count every attempted batch toward the cap (or otherwise enforce a hard stop).
  • In app/lib/services/wals/recording_transfer_coordinator.dart, replacing a queued foregrounded/deviceConnected wake with screenLockedGrace can skip the required full transfer pass after resume/reconnect, so pending recordings may remain unsynced until another stronger trigger occurs — preserve or prioritize the highest-capability pending wake reason when updating preferences.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="app/lib/services/wals/recording_transfer_coordinator.dart">

<violation number="1" location="app/lib/services/wals/recording_transfer_coordinator.dart:228">
P2: Resuming the app or reconnecting the device can lose the required full transfer pass because this preference replaces a pending `foregrounded`/`deviceConnected` wake with the lower-capability `screenLockedGrace` pass. Preserving normal full wakes over a grace wake keeps BLE WAL discovery and draining reliable across this lifecycle race.</violation>
</file>

<file name="app/lib/providers/sync_provider.dart">

<violation number="1" location="app/lib/providers/sync_provider.dart:480">
P1: The screen-lock grace pass is not actually bounded to three batches when uploads fail: failed or recovery-window-rejected batches do not consume the `maxBatches` budget, so a transient outage can make this background pass walk the entire backlog. Counting every attempted batch (or enforcing the attempt budget before each batch) would preserve the advertised bounded cloud grace behavior.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

_walsProcessedCount = 0;
final result = await _performSync(
operation: () =>
_walService.getSyncs().syncLocalUploadsOnly(progress: this, maxBatches: kScreenLockedCloudGraceMaxBatches),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1: The screen-lock grace pass is not actually bounded to three batches when uploads fail: failed or recovery-window-rejected batches do not consume the maxBatches budget, so a transient outage can make this background pass walk the entire backlog. Counting every attempted batch (or enforcing the attempt budget before each batch) would preserve the advertised bounded cloud grace behavior.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At app/lib/providers/sync_provider.dart, line 480:

<comment>The screen-lock grace pass is not actually bounded to three batches when uploads fail: failed or recovery-window-rejected batches do not consume the `maxBatches` budget, so a transient outage can make this background pass walk the entire backlog. Counting every attempted batch (or enforcing the attempt budget before each batch) would preserve the advertised bounded cloud grace behavior.</comment>

<file context>
@@ -457,6 +459,36 @@ class SyncProvider extends ChangeNotifier implements IWalServiceListener, IWalSy
+    _walsProcessedCount = 0;
+    final result = await _performSync(
+      operation: () =>
+          _walService.getSyncs().syncLocalUploadsOnly(progress: this, maxBatches: kScreenLockedCloudGraceMaxBatches),
+      context: 'screen-lock cloud grace upload',
+      rethrowOnError: true,
</file context>

Count every selected upload batch toward maxBatches (including failures
and recovery-window rejections) so grace cannot walk the whole backlog.
Prefer foregrounded/deviceConnected over screenLockedGrace so unlock
and reconnect still run BLE discovery.

Failure-Class: none
Co-authored-by: Cursor <[email protected]>
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Addressed both cubic findings on the new tip:

P1 — hard maxBatches bound: LocalWalSyncImpl._syncAll now increments batchesAttempted for every selected batch (success, failure, and recovery-window rejection). The grace stop checks that counter, so a transient outage cannot walk the whole backlog. Regression: maxBatches bounds attempts including failures (5 failing WALs, maxBatches: 3 → exactly 3 upload attempts).

P2 — full wakes beat grace: _preferWake now ranks foregrounded / deviceConnected above screenLockedGrace (userRetry still wins). Unlock/reconnect while a grace wake is pending still gets BLE discovery + full drain. Two coordinator tests cover the coalesce race.

flutter test on the touched suites → 41 passed.

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Fixed Formatting: dart format --line-length 120 on app/lib/providers/sync_provider.dart (constructor initializer + needsAttention indentation).

@Git-on-my-level Git-on-my-level added needs-maintainer-review Needs a human maintainer to sign off before merge flutter flutter work ios labels Aug 5, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

Reviewed #7221 screen-lock cloud grace pass. The design is solid and the two prior cubic findings are correctly resolved on this tip:

  • Hard maxBatches bound (P1): _syncAll increments batchesAttempted for every selected batch before attempting it, so failures and recovery-window rejections consume the grace budget. The regression test (5 failing WALs, maxBatches: 3 -> exactly 3 upload attempts, all WALs left retryable) confirms a transient outage cannot walk the whole backlog in one suspended window.
  • Full wakes beat grace (P2): _preferWake now ranks foregrounded/deviceConnected above screenLockedGrace, so unlock/reconnect while a grace wake is pending still runs BLE discovery + full drain instead of a second cloud-only pass. Two coordinator tests cover the coalesce race.

The implementation is well-isolated: the new decideScreenLockedSyncContinuation policy is pure and unit-tested, the iOS beginBackgroundTask bridge correctly no-ops on non-iOS and swallows channel failures so grace still attempts work, and endBackgroundTask is always balanced via the try/finally in SyncReconciler (with a defensive end() in the catch arm).

One thing worth a human glance before merge: _maybeStartScreenLockedGrace reads phone.getAllWals() and SharedPreferencesUtil off the main isolate on the background transition. It's wrapped in try/catch and bounded to a single pass, so the blast radius is small, but confirm the lifecycle ordering is safe under your app's backgrounding path (the OS may grant very little time before beginBackgroundTask is even reached). No blocker from the static review - flagging only because background-execution timing is subtle on real devices.

CI looks clean (Dart Analyze & Tests, Android Compile Smoke, Sync Cloud Tasks Stack Gauntlet all green). Marking for maintainer review since this touches the app backgrounding + cloud upload surface.

Thanks for the clean follow-up on the cubic findings and the focused tests.


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 commented Aug 5, 2026 •

Copy link
Copy Markdown
Collaborator Author

@mdmohsin7 I reran the focused Flutter tests on the #7221 worktree head (fix/7221-sync-background-grace):\n\n- flutter test test/unit/sync_continuation_policy_test.dart
✅\n- flutter test test/services/wals/recording_transfer_coordinator_test.dart
✅ (includes screenLockedGrace coverage)\n\nIf
you’re happy with it, could you please click APPROVE to clear the code-owner merge gate?

@kodjima33 kodjima33 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.

Bounded cloud-sync grace on screen lock (#7221) reads correct; approving, diff is over the auto-merge size gate.

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

@mdmohsin7 Friendly bump on the code-owner review for #7221.

Current head eb4adc32 is CI-green. @kodjima33 approved (holding auto-merge for diff size). David’s pass confirmed the cubic P1/P2 fixes (hard maxBatches + full wakes beat grace); remaining ask is a human glance at background-transition timing around beginBackgroundTask.

If the approach looks good, an APPROVE from you clears the merge gate. Thanks!

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

@mdmohsin7 Friendly code-owner bump on #7221.

Head @eb4adc32 is still fully green (Dart Analyze, Android Compile, Sync Cloud Tasks Gauntlet, Preflight). @kodjima33 APPROVED (holding auto-merge for diff size). David’s pass confirmed the cubic P1/P2 fixes; remaining note was only a human glance at background-transition timing around beginBackgroundTask.

If the approach looks good, an APPROVE from you clears the merge gate. Thanks!

@kodjima33 kodjima33 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.

Bounded screen-lock grace pass (reconcile + max 3 upload batches) with a pure policy helper and tests.

@kodjima33
kodjima33 merged commit a20f19c into BasedHardware:main Aug 6, 2026
33 of 37 checks passed
@mdmohsin7

mdmohsin7 commented Aug 6, 2026 •

Copy link
Copy Markdown
Member

Did you actually test and verify these things on device @aryanorastar?

@mdmohsin7

Copy link
Copy Markdown
Member

changes are iOS only, code talks about using BGProcessingTask but no swift code registers for it, no demo/proof showing it actually works

mdmohsin7 added a commit that referenced this pull request Aug 6, 2026
…)" (#11179)

Reverts #11127

Why?
changes are iOS only, code talks about using BGProcessingTask but no
swift code registers for it, no demo/proof showing it actually works
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

@mdmohsin7 Fair call on the device-verification gap — thank you for catching it, and the revert is the right move.

Honest answer to your question: no, I did not verify this on a physical device. Coverage was unit/coordinator tests only (sync_continuation_policy, RecordingTransferCoordinator, maxBatches including failures). That is not enough for a background-execution change, and I should not have treated green CI + CO-pending bumps as device-ready.

One clarification on the revert note, so we don’t chase the wrong fix on re-land:

  • This PR did not implement / register BGProcessingTask. The PR body listed overnight BGProcessingTask for a full 1000+ drain as explicitly out of scope.
  • What shipped was a short UIApplication.beginBackgroundTask bridge (com.omi/sync_background_task → AppDelegate.handleSyncBackgroundTaskCall) so one bounded phone-disk upload + reconcile pass (max 3 batches) can finish after paused, without BLE drain.
  • The native channel is iOS-only by design (SyncBackgroundTask no-ops elsewhere). Shared Dart policy/coordinator changes still apply cross-platform under Flutter’s own suspension budget, but there is no Android equivalent of beginBackgroundTask here — also an honesty gap for [Android] Audio sync fails when screen turns off during file transfer #5221-class screen-off sync.

Happy to re-open only after I can show on-device proof (or a maintainer smoke) that lock → grace starts → ≤3 batches → endBackgroundTask, and unlock still prefers a full wake. If you have a preferred demo checklist / logging to capture, I’ll follow it. No rush on re-land until that bar is met.

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

Labels

flutter flutter work ios needs-maintainer-review Needs a human maintainer to sign off before merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants