8000 fix(sync): eliminate error-flood, silent stalls, and lost-progress restarts in P2P sync by ahmet-cetinkaya · Pull Request #303 · ahmet-cetinkaya/whph · GitHub
[go: up one dir, main page]

Skip to content

fix(sync): eliminate error-flood, silent stalls, and lost-progress restarts in P2P sync - #303

Merged
ahmet-cetinkaya merged 11 commits into
mainfrom
fix/sync-errors
Aug 24, 2026
Merged

ahmet-cetinkaya merged 11 commits into
mainfrom
fix/sync-errors

Conversation

@ahmet-cetinkaya
Copy link
Copy Markdown
Owner

🚀 Context

Real device-to-device sync sessions were producing 610 ERROR-level log lines in a
single run, silent stalls, and syncs that restarted from scratch (lastSyncDate reset to
2000-01-01) instead of resuming. Root-caused and fixed seven distinct issues across the
sync stack: re-entrancy, timeout handling, LAN-discovery noise, duplicate logging, page-level
retry, retry bounding, and socket lifecycle.

🔗 Related

  • N/A (no linked issue; found and fixed during hands-on sync reliability investigation)

⚙️ Implementation Details

Commit Fix
39cdb301 Guard runPaginatedSync against concurrent invocations (re-entrancy).
1fbb70ea WebSocket timeout now completeErrors instead of silently resolving, so the retry loop actually engages.
d0c19334 LAN discovery scan failures downgraded ERROR → DEBUG (failed probes are expected during discovery); channel.ready is now awaited explicitly instead of leaking an unhandled async error to the global zone handler.
f99f5335 Removed a duplicate Received message log line on the server path.
67721140 A failed page is now retried (up to N attempts) before the entity sync is abandoned — previously a single page failure discarded the whole run (e.g. AppUsage failing at 85% transmitted, page 28/33, threw away all prior progress).
6152afc1 Capped page retries at 2 (was 3) to bound worst-case stall to ~3 min instead of ~5 min, since the transport layer already retries 3× with 15/30/45s backoff.
e6eb64a5 WebSocket is now closed explicitly after a successful page send (previously only closed on the failure path), preventing dangling connections.

Note

docs/SYNC-ERRORS-ANALYSIS.md was intentionally written during investigation and then
fully removed from history before pushing — it was a scratch analysis doc, not meant to
ship.

Validation performed:

  • flutter analyze: 949 → 7 issues; remaining 7 are pre-existing drift migration test
    schema issues, unrelated to this change.
  • Full flutter test suite: 2066/2066 passing on this branch, identical baseline
    comparison run before rebase showed zero regressions vs main.
  • One test (sync_pagination_service_test.dart — "should handle communication failure")
    updated to expect called(2) instead of called(1), matching the new intentional
    per-page retry behavior.
  • Live end-to-end validation: ran a real Linux desktop instance (server mode) and a
    real Android emulator instance (client) side by side, paired them over the local network
    (10.0.2.2 ↔ 10.0.2.16), and performed an actual full sync with debug logging enabled.
    Result: 0 ERROR, 0 WARNING in the sync log (vs. 610 ERROR pre-fix), all 19
    HabitRecord pages transmitted sequentially with no duplicate/retry noise, WebSocket
    closed normally after each page, and lastSyncDate updated correctly on completion.
sequenceDiagram
    participant C as Client (Android)
    participant S as Server (Linux)
    Note over C,S: Before fix: single page failure aborts<br/>entire entity sync, next run restarts from 2000-01-01
    Note over C,S: After fix: page-level retry (max 2 attempts)<br/>keeps prior pages, WebSocket closed cleanly on success
    C->>S: paginated_sync (page N)
    alt page fails
        S-->>C: error
        C->>S: retry page N (attempt 2)
    end
    S-->>C: page N result
    C->>C: close WebSocket
Loading

📋 Checklist for Reviewer

  • Tests passed locally (2066/2066, flutter test).
  • Commit history is clean and descriptive (7 commits, all fix(sync): ...).
  • Documentation updated (if applicable) — N/A, no user-facing docs affected.
  • Code quality standards met (flutter analyze: 949 → 7 pre-existing unrelated issues).
  • Live sync validated by reviewer on their own devices (validated by author on
    Linux desktop ↔ Android emulator; a second confirmation is welcome given the
    severity of the original bug).

Logs showed a manual sync and a delayed background sync
("Running delayed initial sync ... after 60 seconds") starting
~20s apart with no re-entrancy check, causing the second call to
reset pagination progress for all 18 entity types mid-flight while
the first sync was still transmitting. AppUsage and
AppUsageTimeRecord page sends then interleaved on the same
connection, correlating with a connection abort and subsequent
WebSocket timeouts.

Add a _syncInProgress guard so a new runPaginatedSync call is a
no-op while one is already running, released in a finally block.
The per-page timeout Timer completed the Completer with a success:false
value instead of an error. _executeSync returned that value normally,
so sendPaginatedDataToDevice's retry loop took the 'return response'
path and exited after a single attempt — the logged
'(attempt 1/3)' was misleading, retries 2 and 3 never ran.

Logs confirm this: every '\u23f0 WebSocket timeout' line was immediately
followed by 'Failed to send ... page N: Operation failed', never by
'Waiting 2s before retry...', which only appeared for genuine
connection-level exceptions.

Complete the timeout with a TimeoutException instead, so it is caught
by the existing catch block and the retry/backoff logic runs as
intended.
Device discovery connects to every IP in the local /24 subnet
(150+ addresses); most are unreachable, which is the expected outcome
of a scan, not an application error. Two issues combined to make this
598 of 610 ERROR lines in a single sync session:

1. The stream onError handler logged connection failures
   (No route to host / Connection refused) at ERROR level.
2. channel.ready's error completion was never awaited, so Dart also
   reported it as an unhandled async error to the global zone error
   handler (GlobalErrorHandlerService), doubling the noise and
   triggering an unnecessary 'error overlay not available' log path.

Await channel.ready explicitly and handle its error locally, and
downgrade the onError log to debug, since a failed scan probe is
normal, not exceptional.
Every inbound WebSocket message was logged twice at DEBUG level: once
in the ws.listen callback and again at the top of
_handleWebSocketMessage, which the callback calls immediately after.
Verified harmless (message is only processed once - the
'Processing paginated sync request...' count matched the actual
request count) but it doubled log volume for every sync page and
initially looked like duplicate message processing during triage.

Keep the log inside _handleWebSocketMessage since it also covers any
other caller of that function.
A single page failure aborted the entire entity sync, which failed the
whole device sync, which skipped the lastSyncDate update - so the next
run restarted the initial sync from page 0. In the captured logs
AppUsage failed on page 28 of 33 (85% transmitted) and all of that
work was discarded; the following run started over from
lastSync 2000-01-01 and failed again the same way.

Re-attempt the failing page up to 3 times with linear backoff before
giving up on the entity. Re-sending a page is safe: the receiving side
looks each item up by id and routes an already-present item through
conflict resolution ('Create operation for existing item, treating as
update'), so a duplicate page does not create duplicate rows.

Update the communication-failure test, which pinned the old
single-attempt behavior, to assert the retry contract instead.
The page retry loop multiplies with the transport retry loop in
SyncCommunicationService (3 attempts at 15s/30s/45s). At 3 page
attempts a single unreachable peer could hold the sync for ~5 minutes
before the entity was abandoned; at 2 it is ~3 minutes, while still
recovering the transient-failure case the retry was added for.
sendPaginatedDataToDevice opens a connection per page but only closed
it on the failure path; successful sends returned without closing and
relied on the peer tearing the socket down. Across an initial sync of
~250 pages that holds sockets open against the server's connection
limits (10 total / 5 per IP) longer than needed.

Close the socket explicitly before returning the successful response.
@ahmet-cetinkaya ahmet-cetinkaya added bug Something isn't working android Issues related to Android platform sync Synchronization related issues linux Linux specific issues labels Aug 23, 2026
@ahmet-cetinkaya ahmet-cetinkaya self-assigned this Aug 23, 2026
@ahmet-cetinkaya
ahmet-cetinkaya marked this pull request as ready for review August 24, 2026 05:34
@ahmet-cetinkaya
ahmet-cetinkaya merged commit 1f75103 into main Aug 24, 2026
3 checks passed
@ahmet-cetinkaya
ahmet-cetinkaya deleted the fix/sync-errors branch August 24, 2026 05:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

android Issues related to Android platform bug Something isn't working linux Linux specific issues sync Synchronization related issues

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

0