Repository navigation
fix(sync): eliminate error-flood, silent stalls, and lost-progress restarts in P2P sync - #303
Merged
Merged
Conversation
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
🚀 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 (
lastSyncDatereset to2000-01-01) instead of resuming. Root-caused and fixed seven distinct issues across thesync stack: re-entrancy, timeout handling, LAN-discovery noise, duplicate logging, page-level
retry, retry bounding, and socket lifecycle.
🔗 Related
⚙️ Implementation Details
39cdb301runPaginatedSyncagainst concurrent invocations (re-entrancy).1fbb70eacompleteErrors instead of silently resolving, so the retry loop actually engages.d0c19334channel.readyis now awaited explicitly instead of leaking an unhandled async error to the global zone handler.f99f5335Received messagelog line on the server path.67721140AppUsagefailing at 85% transmitted, page 28/33, threw away all prior progress).6152afc1e6eb64a5Note
docs/SYNC-ERRORS-ANALYSIS.mdwas intentionally written during investigation and thenfully 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 testschema issues, unrelated to this change.
flutter testsuite: 2066/2066 passing on this branch, identical baselinecomparison run before rebase showed zero regressions vs
main.sync_pagination_service_test.dart— "should handle communication failure")updated to expect
called(2)instead ofcalled(1), matching the new intentionalper-page retry behavior.
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
HabitRecordpages transmitted sequentially with no duplicate/retry noise, WebSocketclosed normally after each page, and
lastSyncDateupdated 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📋 Checklist for Reviewer
flutter test).fix(sync): ...).flutter analyze: 949 → 7 pre-existing unrelated issues).Linux desktop ↔ Android emulator; a second confirmation is welcome given the
severity of the original bug).