Skip to content

fix(realtime): prevent null check crash in connect() during rapid lifecycle transitions - #1321

Merged
grdsdev merged 6 commits into
supabase:mainfrom
brunovsiqueira:fix/realtime-connect-race-condition
Mar 25, 2026
Merged

grdsdev merged 6 commits into
supabase:mainfrom
brunovsiqueira:fix/realtime-connect-race-condition

Conversation

@brunovsiqueira

@brunovsiqueira brunovsiqueira commented Mar 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • connect() in realtime_client.dart: Capture WebSocketChannel in a local variable before await ready, then check conn != localConn afterward as a staleness guard. This prevents the TypeError: Null check operator used on a null value crash at conn!.stream.listen(...) when disconnect() nullifies conn during the await.
  • onResumed() in supabase.dart: Replace realtime.conn!.sink.done with a stored _disconnectFuture field, eliminating a second NPE risk when conn is nullified between the null check and the access during rapid lifecycle transitions.
  • 3 new unit tests covering: disconnect during await ready, state change during await ready, and rapid connect-disconnect-connect cycles.

Fixes #1320

Test plan

  • dart test passes in packages/realtime_client (29 tests, including 3 new race condition tests)
  • flutter test passes in packages/supabase_flutter (36 tests)

Manual testing

  1. Create a Flutter app with a Supabase Realtime channel subscription
  2. Connect to a realtime channel:
    final channel = Supabase.instance.client
        .channel('test')
        .onPostgresChanges(
          event: PostgresChangeEvent.all,
          schema: 'public',
          callback: (payload) => print('Change: $payload'),
        )
        .subscribe();
  3. Trigger rapid lifecycle flapping on Android via one of:
    • Enable "Don't keep activities" in Developer Settings, then quickly switch between apps
    • Rapidly enter/exit split-screen mode
    • Simulate memory pressure: adb shell am memory-factor critical, then immediately resume
  4. Verify:
    • App reconnects to realtime after resuming
    • Channel subscriptions still receive events after recovery

…ecycle transitions

Capture the WebSocketChannel in a local variable before awaiting ready,
then add a staleness guard (conn != localConn) after the await to bail
out if disconnect() ran concurrently. This prevents the TypeError when
conn is nullified between the await and the stream.listen() call.

Also replace the conn!.sink.done access in onResumed() with a stored
_disconnectFuture to eliminate a second NPE risk during lifecycle
flapping.

Fixes supabase#1320

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR addresses a race condition during rapid app lifecycle transitions that could trigger null-check crashes when disconnect() interleaves with connect() in the realtime client, and adjusts Supabase lifecycle reconnect logic to avoid dereferencing a nullified connection.

Changes:

  • Update RealtimeClient.connect() to capture the created WebSocketChannel in a local variable and add a post-await ready staleness guard before listening to the stream.
  • Update Supabase.onResumed() to wait on a stored disconnect future instead of accessing realtime.conn!.sink.done.
  • Add unit tests in socket_test.dart covering connect/disconnect race scenarios.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.

File Description
packages/supabase_flutter/lib/src/supabase.dart Track disconnect completion via _disconnectFuture and use it to sequence reconnect on resume without conn! access.
packages/realtime_client/lib/src/realtime_client.dart Prevent null-check crash by using a local socket reference across await ready and guarding against staleness.
packages/realtime_client/test/socket_test.dart Add regression tests for rapid connect/disconnect interleavings.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

… in post-await guard

Address review feedback:
- Add conn != localConn guard inside the catch block to avoid firing
  error handlers for a stale connection attempt.
- Strengthen the post-await guard to also check connState == connecting,
  preventing connect() from proceeding if disconnect() has already set
  connState to disconnecting but hasn't yet nulled conn.
…ad of eagerly

Address review feedback from icnahom: if a second resumed event fires
while disconnect is still in progress (e.g. paused → resumed → inactive
→ resumed), the eagerly-nulled _disconnectFuture causes the second
resumed to fall into the else branch where connect() no-ops because
conn is still non-null.

Move _disconnectFuture = null into the .then() callback with a guard to
avoid overwriting a newer future set by a subsequent paused event.
Add transport field to RealtimeClientOptions (non-breaking, additive)
so tests can inject a mock WebSocket transport. Add two lifecycle tests:
- paused → resumed reconnects after disconnect completes
- paused → resumed → inactive → resumed still reconnects (validates
  _disconnectFuture is not eagerly cleared)
@brunovsiqueira
brunovsiqueira requested a review from icnahom March 23, 2026 17:05

@icnahom icnahom left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Although I have my reservations about introducing a second source of truth (_disconnectFuture), the PR effectively resolves the primary issue.

A follow up PR could be created to further improve the app lifecycle based connection management logic.

For example, double resumed call will forceRejoin channels. But instead of putting another band aid, we could rewrite the logic to better handle edge cases.

Pseudo-code:

// 1. Event Queue ensures operations never overlap
// Dart Future Chaining or external Package like `synchronized` or `pool`
TaskQueue taskQueue

// Track the absolute most recent state
AppState latestState 

onLifecycleChange(newState):
    // Update synchronously before queuing
    latestState = newState 
    
    // Append to queue instead of tracking 'in-flight' futures
    taskQueue.enqueue(() => processLifecycle(newState))

processLifecycle(targetState):
    // 2. Built-in Cancellation: Did the app switch states while we 
    // were waiting in the queue? If so, abort this outdated task.
    if targetState != latestState:
        return 

    // 3. Single Source of Truth (SSOT): Ask the socket itself
    bool isConnectionActive = RealtimeClient.isConnected OR RealtimeClient.isConnecting

    if targetState == RESUMED:
        // 4. Idempotency: If already connected, do nothing. 
        // This safely handles "double resumed" naturally.
        if isConnectionActive: 
            return 
            
        RealtimeClient.connect()

    if targetState == PAUSED:
        // Idempotency: If already disconnected, do nothing.
        if not isConnectionActive: 
            return 
            
        RealtimeClient.disconnect()

@brunovsiqueira

Copy link
Copy Markdown
Contributor Author

Hi @icnahom. Much thanks for reviewing the PR, and I agree with your suggestion.

Would it make sense to merge this PR, and work together on a more structural follow up PR, as you suggested? I can take it, but this would require deeper testing and review.

@icnahom

icnahom commented Mar 25, 2026

Copy link
Copy Markdown
Contributor

@grdsdev Could you please merge this when you have a moment?

@grdsdev grdsdev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks @brunovsiqueira for the fix.

As @icnahom suggested, we need to refactor this.

I'm approving this PR, but feel free to open another one improving this implementation.

@grdsdev
grdsdev merged commit 61f7cd1 into supabase:main Mar 25, 2026
14 of 15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Race condition: Null check crash in RealtimeClient.connect() during rapid lifecycle transitions

4 participants