Skip to content

Fix the socket never reconnecting after a transient connectivity drop - #6663

Open
aleksandar-apostolov wants to merge 4 commits into
developfrom
fix/socket-stuck-network-disconnected-v7
Open

Fix the socket never reconnecting after a transient connectivity drop#6663
aleksandar-apostolov wants to merge 4 commits into
developfrom
fix/socket-stuck-network-disconnected-v7

Conversation

@aleksandar-apostolov

@aleksandar-apostolov aleksandar-apostolov commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

Port of #6662 to develop.

Goal

Fixes AND-1450 — socket gets into Disconnected.Network and never comes back out, client stays offline until the process dies.

Implementation

Provider now records direct isConnected() reads so the cached flag can't go stale. Disconnected.Network handles Event.Resume. Lifecycle observer only swallows the replayed resume. All internal, no API change.

Testing

New unit tests.

Summary by CodeRabbit

  • Bug Fixes
    • Improved lifecycle handling so resume events are delivered correctly after subscribing or returning to the foreground.
    • Improved network connectivity tracking, including reliable disconnect and reconnect notifications.
    • Chat connections now restart automatically when the app resumes after a network-related disconnection.
  • Tests
    • Added coverage for lifecycle, connectivity, and socket reconnection scenarios.

NetworkStateProvider only notifies listeners when its cached flag changes,
but ChatSocket concluded "no network" from the live isConnected() read
without the provider ever learning. The cached value stayed true, so the
network coming back was not seen as a transition and listeners were never
told, leaving the socket offline for the lifetime of the process.

Record the result of every direct read, and route the "all networks lost"
branch of onLost through the same writer so it cannot desync either.

Also drop NET_CAPABILITY_VALIDATED from the check. It reports whether the
platform's connectivity probe passed, not whether a socket can be opened,
so captive portals and revalidating networks read as a hard outage.
The state stopped the health monitor without scheduling a replacement and
declared no transition for Event.Resume, so it could only be left if a
network callback arrived. One missed callback stranded the socket until the
process was killed.

Keep a backed-off retry armed and restart the connection on resume, matching
Disconnected.Stopped. The existing state machine test pinned the old
behaviour, asserting that a resume left NetworkDisconnected unchanged.
observe() suppressed the first ON_RESUME in order to swallow the replay that
addObserver dispatches when the owner is already resumed. Subscribing from a
process that is not resumed gets no replay, so the suppression discarded a
genuine foregrounding instead.

Only suppress when the owner is already resumed at subscribe time.
Recording a positive read consumed the transition the listeners wait for, when
isConnected() ran after the network returned but before the system callback
landed. That is the same defect this PR fixes, mirrored, and it is reachable
from app code through ClientState.isNetworkAvailable. Only a negative answer is
recorded now, which is the direction that can strand the socket.

Restore healthMonitor.stop() in NetworkDisconnected. The replacement retry
emitted Event.WebSocketEventLost, which that state does not handle, so it was
inert; worse, a pending one could knock a later Connecting state into
Disconnected.WebSocketEventLost.

Restore the NET_CAPABILITY_VALIDATED check. With the provider fixed a false
negative is no longer terminal, so the behaviour change is not worth its risk
in this PR.
@github-actions

Copy link
Copy Markdown
Contributor

PR checklist ✅

All required conditions are satisfied:

  • Title length is OK (or ignored by label).
  • At least one pr: label exists.
  • Sections ### Goal, ### Implementation, and ### Testing are filled, or the PR is bot-authored.
  • An issue is linked (Linear ticket or GitHub issue), or the PR is bot-authored.

🎉 Great job! This PR is ready for review.

@github-actions

Copy link
Copy Markdown
Contributor

SDK Size Comparison 📏

SDK Before After Difference Status
stream-chat-android-client 6.07 MB 6.07 MB 0.00 MB 🟢
stream-chat-android-ui-components 11.37 MB 11.37 MB 0.00 MB 🟢
stream-chat-android-compose 12.85 MB 12.85 MB 0.00 MB 🟢

@sonarqubecloud

Copy link
Copy Markdown

@aleksandar-apostolov
aleksandar-apostolov marked this pull request as ready for review August 26, 2026 13:47
@aleksandar-apostolov
aleksandar-apostolov requested a review from a team as a code owner August 26, 2026 13:47
@coderabbitai

coderabbitai Bot commented Aug 26, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 0f8e70c5-b91c-4e58-b130-015b0f8efae3

📥 Commits

Reviewing files that changed from the base of the PR and between 89b0344 and d26aa00.

📒 Files selected for processing (6)
  • stream-chat-android-client/src/main/java/io/getstream/chat/android/client/StreamLifecycleObserver.kt
  • stream-chat-android-client/src/main/java/io/getstream/chat/android/client/network/NetworkStateProvider.kt
  • stream-chat-android-client/src/main/java/io/getstream/chat/android/client/socket/ChatSocketStateService.kt
  • stream-chat-android-client/src/test/java/io/getstream/chat/android/client/StreamLifecycleObserverTest.kt
  • stream-chat-android-client/src/test/java/io/getstream/chat/android/client/network/NetworkStateProviderTest.kt
  • stream-chat-android-client/src/test/java/io/getstream/chat/android/client/socket/experimental/ChatSocketStateServiceTest.kt

Included review availability: Your plan provides up to 4 included reviews per hour; 3 remain after this review.


Walkthrough

The changes correct lifecycle resume event delivery, centralize network connectivity transitions, and restart network-disconnected sockets on lifecycle resume. New tests cover lifecycle replay, connectivity callbacks, deduplication, disconnection, and socket recovery.

Changes

Lifecycle and connectivity recovery

Layer / File(s) Summary
Lifecycle resume event handling
stream-chat-android-client/src/main/java/io/getstream/chat/android/client/StreamLifecycleObserver.kt, stream-chat-android-client/src/test/java/io/getstream/chat/android/client/StreamLifecycleObserverTest.kt
observe now distinguishes subscriptions made from resumed and non-resumed lifecycle states. Tests verify replay suppression and later resume delivery.
Network state transitions
stream-chat-android-client/src/main/java/io/getstream/chat/android/client/network/NetworkStateProvider.kt, stream-chat-android-client/src/test/java/io/getstream/chat/android/client/network/NetworkStateProviderTest.kt
Network updates use synchronized, deduplicated state changes. Tests cover connectivity reads, callbacks, repeated usable states, and loss of the final network.
Socket resume recovery
stream-chat-android-client/src/main/java/io/getstream/chat/android/client/socket/ChatSocketStateService.kt, stream-chat-android-client/src/test/java/io/getstream/chat/android/client/socket/experimental/ChatSocketStateServiceTest.kt
NetworkDisconnected now transitions to RestartConnection(LIFECYCLE_RESUME) on lifecycle resume. The parameterized expectation reflects this transition.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Merge Risk: ⚪ Minimal · up to d26aa

The change targets socket recovery and includes unit tests; no actionable merge-blocking risk remains beyond normal checks and review.

Suggested reviewers: andremion

Poem

A rabbit watched the signals flow
Resume woke the socket from below
Networks changed with careful pace
Duplicate hops left not a trace
The tests now guard each winding trail

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.22% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 18 functions across 6 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the primary change: restoring socket reconnection after a transient connectivity drop.
Description check ✅ Passed The description includes the goal, implementation, and testing details. It explains the affected socket behavior, the internal fixes, the lack of API changes, and the new unit tests. UI, checklist, re…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description includes the goal, implementation, and testing details. It explains the affected socket behavior, the internal fixes, the lack of API changes, and the new unit tests. UI, checklist, reviewer, and GIF sections are omitted, but they are not critical for this non-UI change.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/socket-stuck-network-disconnected-v7

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

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

Labels

pr:bug Bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants