Skip to content

fix(realtime): ammend reconnect logic to not unsubscribe - #1346

Merged
o-santi merged 2 commits into
mainfrom
realtime/fix-reconnect
Jan 8, 2026
Merged

o-santi merged 2 commits into
mainfrom
realtime/fix-reconnect

Conversation

@o-santi

@o-santi o-santi commented Jan 7, 2026

Copy link
Copy Markdown
Contributor

What kind of change does this PR introduce?

Fixes #1311. The core of the problem is explained in the issue thread, but to summarize:

  1. If the websocket connection is lost and subsequently restated, the client needs to re-subscribe to all existing channels, given that they're now invalid.
  2. In order to keep the same object references valid, it does not create a new channel. Instead, there's a custom _rejoin function that is called on all existing channels, which resubscribes by re-sending the same payload as the first time.
  3. The problem is that the _rejoin first tries to unsubscribe each channel before re-sending the original join_push, and unsubscribe removes the channel from the channels field, and only after that does it send the join_push.
  4. When the eventual ack comes back, the channel is not registered anymore in the channels field, so the ack message (phx_reply) is completly ignored, leaving it in a CLOSED state forever.

The fix

Given that the websocket connection is new, we can just ignore the unsubscribe call and just re-send the join_push again. This way, the external channel references still remain valid, and the state is correctly set.

As a bonus, I've added a state change when the reconnect tries to rejoin to signal that an error occured.

@coveralls

coveralls commented Jan 7, 2026 •

Copy link
Copy Markdown

Pull Request Test Coverage Report for Build 20796463304

Details

  • 0 of 0 changed or added relevant lines in 0 files are covered.
  • 44 unchanged lines in 2 files lost coverage.
  • Overall coverage decreased (-0.05%) to 91.142%

Files with Coverage Reduction New Missed Lines %
src/realtime/_async/channel.py 1 71.11%
src/realtime/_async/client.py 43 71.57%
Totals Coverage Status
Change from base Build 20758881845: -0.05%
Covered Lines: 8952
Relevant Lines: 9822

💛 - Coveralls

@Krishna-js45

Copy link
Copy Markdown

Reviewed the reconnect logic change.
Skipping the unsubscribe during rejoin avoids removing the channel before the join ack is processed, which directly addresses the race condition described in #1311.
The fix looks correct and consistent with the intended reconnect behaviour.

@o-santi
o-santi merged commit cfbe594 into main Jan 8, 2026
@o-santi
o-santi deleted the realtime/fix-reconnect branch January 8, 2026 13:29
zeekay pushed a commit to Dream-AI-4444/supabase-py that referenced this pull request Sep 10, 2026
spydon added a commit that referenced this pull request Nov 3, 2026
…1675)

Fixes #1299

#1299 got closed after #1346, but the "realtime goes quiet and never
comes back" part still happens on main. The log in the last comment
there is the giveaway: ws state CLOSED, close code 1001, channel still
JOINED.

What's going on: when the server (or a proxy in front of Realtime)
closes the socket with 1000 or 1001, websockets just ends the `async for
msg in ws` loop instead of raising. `_listen` only handled
`ConnectionClosedError`, so it returned quietly. `_ws_connection` stayed
set, `is_connected` kept saying True, and the channel stayed JOINED.
Heartbeats then hit `ConnectionClosedOK`, which gets swallowed, so
nothing ever reconnected. Close codes like 1012 already worked because
they raise.

The fix:
- if the listen loop ends normally and the socket is still the current
one, treat it as a server close and reconnect (only when
`auto_reconnect` is on), same as the error path
- `close()` now clears `_ws_connection` before closing, so a close we
started ourselves doesn't look like a server close and trigger a
reconnect

I reproduced it against the local Realtime from `infra/` with a tiny
relay in front that closes the client with 1001:

```
before: ws.state=CLOSED ws.close_code=1001 | is_connected=True channel.state=JOINED | relay connections so far=1
        received total: ['before-close']  -> STUCK
after:  ws.state=OPEN ws.close_code=None | is_connected=True channel.state=JOINED | relay connections so far=2
        received total: ['before-close', 'after-close']  -> RECOVERED
```

I added tests for 1000 and 1001 (reconnect and rejoin), and one that
checks `close()` doesn't reconnect. Both close-code tests fail on main,
and the `close()` test fails without the reorder. The full realtime
suite passes locally (34 passed), and ruff and mypy are clean.

---------

Co-authored-by: Lukas Klingsbo <[email protected]>
spydon added a commit that referenced this pull request Nov 3, 2026
Resolves SDK-2676.

## What

Removes `AsyncRealtimeClient._leave_open_topic()`. Nothing called it, so
coverage always reported it as uncovered. Also removes the `AsyncMock`
stub for it in `tests/test_presence.py`.

## Why delete instead of wiring it up

- **realtime-js never called it from `channel()`.** In realtime-js v2
(and in phoenix.js, where it comes from), the only caller of
`_leaveOpenTopic` was `RealtimeChannel._rejoin()`. `channel()` returned
the existing channel for the topic. realtime-js removed it in
supabase/supabase-js#2119 when it switched to phoenix's JS client.
- **Python already removed that same caller on purpose.** `git log -S
_leave_open_topic` shows that cfbe594 (#1346, "ammend reconnect logic
to not unsubscribe") replaced the call in `_rejoin()` with a log line.
During a reconnect the helper found the rejoining channel itself and
unsubscribed it. The method has been dead since then. Its only other
appearance is the test stub added in 6be6c0c.
- **It can't find a duplicate.** `self.channels` is a dict keyed by
topic, so the helper could only ever match `self.channels[topic]`, which
is the channel being joined. When `channel()` replaces a leaving
channel, the old instance is dropped from the dict and is already
leaving, not joined or joining. `_remove_channel()` only deletes the
entry if it is still the same instance, so the replacement is safe
without this helper.

## Testing

- `git grep leave_open` returns nothing.
- `make ruff` is clean.
- With realtime infra running, `uv run --frozen --package realtime
pytest tests` gives 116 passed, including `test_channel_rejoin.py`,
`test_subscription_status.py` and `test_presence.py`.
- `uv run --frozen --package realtime mypy src/realtime tests` reports
no issues.

## Review

I reviewed the diff with `/code-review` (high effort). It found no
issues, so nothing changed.
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.

Realtime auto-reconnect doesn't work correctly: it reconnects the websocket but the channel gets CLOSED

5 participants