Keep the session when a client token connects again: a token can have several sockets

Draft
FA
10d ago
+1597-977

All Submissions:

  • Have you followed the guidelines stated in CONTRIBUTING.md file?
  • Have you checked to ensure there aren't any other open Pull Requests for the desired changed?

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

Changes To Core Features:

  • Have you added an explanation of what your changes do and why you'd like us to include them?
  • Have you written new tests for your core changes, as applicable?
  • Have you successfully ran tests with your changes locally?

Draft, because two parts of the multi-tab design are incomplete (the reconnect fix itself is complete and tested):

  1. Cross-instance ordering. Tabs sharing a token on different instances get updates over two paths (a direct emit on the instance that produced it, lost+found for the others). An instance can emit its own newer delta before its subscriber delivers another instance's older one, leaving that tab on the older value until the next update. Fixing it needs an order number on updates or a single ordered delivery path, which is a design decision.
  2. Page-load supersede is keyed by token. hydrate_and_load cancels the token's earlier unfinished on_load chain, so one tab loading a page can cancel another tab's in-flight load. Keeping that per tab needs a per-connection id (#6252 item 4).

Neither affects a single tab reconnecting, on one instance or several.

The bug

link_token_to_sid treated a client_token that connected while it still had a socket as a duplicate tab, minted a new token and emitted new_token. State is keyed by the token, so the session was dropped. That also happened on every websocket reconnect whose new connect was processed before the old socket's disconnect (#6345: ~800 ms behind a proxy, every time). The new regression tests fail on current main with exactly that (link_token_to_sid returns a fresh UUID for the second sid).

The design

masenf on #6345:

the preferred fix is that multiple tabs can use the same session id consistently. as it stands now, the code is assuming that client_token maps to a single sid -- this assumption should be broken. when the system needs to emit an update for a token, it should send the update to all connected sids, on all instances of the app. but that could be a little tricky due to how the lost+found mechanism currently works.

How this PR does that:

  • token → set of sockets. TokenManager.token_to_sids: dict[str, tuple[str, ...]] holds the sockets of this instance for each token (oldest first). link_token_to_sid only adds a socket and always returns None; nothing mints a token any more.
  • Disconnect removes one socket. disconnect_token(token, sid) drops that sid only, and the token entry with its last sid. A stale disconnect of an old sid cannot unlink the socket that replaced it.
  • Updates go to every socket, once. EventNamespace.emit_update emits to each local sid of the token, then relays the update through lost+found to every other instance that owns a socket of it. The lost+found subscriber now emits to its own sockets only (_emit_update_local) and never relays further, so each socket gets the update exactly once.
  • Redis. The sockets of a token are a Redis set token_manager_sockets_<token> of <instance_id>:<sid> members. Link is SADD + EXPIRE in one MULTI; disconnect is SREM (Redis deletes the set with its last member). There is no check-then-set left: each instance only writes its own members, so instances cannot overwrite each other, and an expired set is restored by each owner for its own sockets (idempotent, replaces the SET NX restore). A socket that disconnects while its SADD is in flight is removed again afterwards.
  • Per-event cost. A locally owned token costs a dict lookup and one emit per socket; the other owners of a token are cached per token, invalidated by the existing keyspace subscriber (sadd/srem/del/expired) and re-read after 5 s at most, because keyspace notifications are not guaranteed. An answer that would leave an update without any recipient is never served from the cache.

Behaviour a user can observe

  1. A reconnect that races the old socket's disconnect keeps the token and the state (the bug).
  2. A duplicated tab shares the session of the tab it was duplicated from (sessionStorage, and with it the token, is copied by the browser). Both tabs render the same state and each sees the other's updates. Before, the duplicate started an empty session.
  3. Frontend events go to every tab of the token as well: a handler that returns rx.redirect, rx.toast, rx.download, rx.call_script… reaches all of them. Chained backend events are queued in the backend and still run once. This is the point I would most like a maintainer to confirm: it follows the sentence quoted above, and #6252 lists per-tab routing of these as an open question.
  4. The backend no longer emits new_token for a token that connects again. The frontend handler and EventNamespace.link_token_to_sid's handling of a replacement token are kept: a custom token manager may still return one, and #7362 emits new_token to rebind tokens to a session.
  5. router.session.session_id is the socket that sent the latest event (unchanged), so it differs between tabs sharing a token; router.page likewise follows the tab that sent the latest event.
  6. Redis key layout changed (token_manager_socket_record_<token> string → token_manager_sockets_<token> set). Old and new instances do not see each other's sockets during a rolling upgrade.
  7. token_to_sid / token_to_socket are deprecated (below).

Compatibility

  • sid_to_token is unchanged (one token per sid still holds).
  • EventNamespace.token_to_sid, TokenManager.token_to_sid and TokenManager.token_to_socket keep working as read-only views of each token's newest socket and call console.deprecate (0.11.1 → 1.0). token_to_socket used to be a writable dict; it is read-only now.
  • New: TokenManager.token_to_sids and the read-only EventNamespace.token_to_sids (sockets connected to this instance). Docs that recommended token in app.event_namespace.token_to_sid now use token_to_sids.

"Canonical sid" call sites audited

SiteNow
TokenManager.token_to_socket / token_to_siddeprecated views of the newest socket; storage is token_to_sids
TokenManager.sid_to_tokenunchanged, local sockets only (the Redis manager no longer caches foreign sids in it)
LocalTokenManager / RedisTokenManager.link_token_to_sidadd a socket, never replace the token
…disconnect_token, disconnect_allremove one socket; token dropped with the last
RedisTokenManager._get_token_owner / _fetch_socket_recordreplaced by _get_remote_owners / _fetch_remote_owners (a set of instances); own members without a live local link are still ignored as stale
is_token_connectedany local socket, else any other owner in Redis
emit_lost_and_foundpublishes to every other owning instance
EventNamespace.emit_update (used by App.modify_state, the event processor's emit_delta / emit_event, background tasks, shared-state fan-out, upload handlers)every socket of the token, on every instance
EventNamespace.on_disconnect → processor._on_disconnectcancels pending hydrate / page-load work only once the token has no socket left on this instance (checked after unlinking), so neither a stale disconnect nor a closing tab cancels another socket's load. It stays per instance: the pending work it cancels was queued by this instance's sockets
EventNamespace.on_connect / link_token_to_sid (router_data session_id, client_token)unchanged: records the connecting sid; each event still carries its own socket's sid, headers and client IP
EventNamespace.on_event, on_client_errorunchanged: resolve the token from the sending sid
reflex/istate/shared.py _do_update_other_tokensunchanged, goes through is_token_connected
screenshot plugin /_active_connections (reflex-base)same {token: sid} shape, built from sid_to_token (newest socket)

Related PRs / issues

  • #6252 (rework new_token to allow tabs sharing a token): this is its "Option 3" for state and update delivery. Not covered here: its open question on routing frontend-only events to one tab (item 3 above sends them to all, per the sentence quoted) and a config flag to keep the old behaviour.
  • #7361 (signed sessions, bound client tokens): no overlap; it does not touch the token manager or the event namespace.
  • #7362 (next in that stack): adds a token_factory argument to link_token_to_sid for the replacement token of a duplicate tab. That argument has nothing left to do after this PR and will conflict textually; its own new_token emits (rebinding a token to a session) are unaffected.
  • #6771 (draft, atomic SET NX claim): made obsolete rather than duplicated. The check-then-set it fixes is gone, since there is no claim to win.
  • #6126 (TokenManager lifecycle APIs): not implemented here. It is written against one sid per token (token_is_connected yields "the" sid) and will need to iterate token_to_sids after this.

Deliberately left out

  • Ordered delivery across instances and per-tab page-load supersede (the two draft items above).
  • Per-tab routing of frontend-only events and a per-connection tab id (#6252 items 3–4).
  • A config switch for the old "duplicate tab gets a fresh session" behaviour.
  • Removing the frontend new_token handler.
  • Migration of existing Redis records (they expire on their own).
  • Known limit: a socket that joined a token on another instance is picked up by this instance's cache on the keyspace notification, or after 5 s at most without one. Updates produced here in that window are not relayed to it; the tab hydrates in full on connect, so only deltas in that window are affected.

Tests

Changed existing expectations (old duplicate-tab behaviour → new):

  • test_link_token_to_sid_duplicate_token_different_sid and test_link_token_to_sid_duplicate_detected asserted that a new token is minted. Replaced by test_reconnect_before_old_sid_disconnects_keeps_token, which asserts the token is kept and both sids are linked.
  • test_disconnect_only_cancels_current_local_socket → test_disconnect_only_cancels_with_last_local_socket, plus test_sockets_disconnecting_together_end_the_page_lifecycle.
  • The Redis record tests (SET/GET of a pickled SocketRecord, NX restore, foreign-record cache) are rewritten for the set layout; the class-based tests in the file became module-level functions with full-value assertions.
  • test_redis_token_manager_lost_and_found is kept with its assertions unchanged, and now also runs against the mock Redis.

New (tests/units/utils/test_token_manager.py, Local and Redis): reconnect keeps the token, late disconnect of the old sid keeps the new one, last disconnect removes the token, an update reaches every sid once (local; and across three instances through lost+found), socket moving tokens, disconnect during link, expiry restore of all local sockets, owner cache invalidation/age/race, deprecated views. tests/units/test_app.py: token_to_sids and the deprecated token_to_sid.

Playwright (tests/integration/tests_playwright/test_connection_banner.py, existing app): test_reconnect_before_old_socket_closes_keeps_session relays the page's websocket through page.route_web_socket, closes only the page side so the client reconnects while the backend still holds the old socket, checks token and state survive, then delivers the late disconnect; then opens a second tab with the same token and checks both tabs see each other's updates. It fails on main (the reconnecting socket gets a new token).

Ran locally:

  • uv run pytest tests/units/utils/test_token_manager.py tests/units/test_app.py tests/units/istate tests/units/reflex_base/event/processor/test_base_state_processor.py tests/units/test_mock_redis.py tests/benchmarks/test_event_loop.py tests/benchmarks/test_shared_state.py — mock Redis: 1046 passed, 6 skipped (the real-Redis variants).
  • The token manager / app / shared / processor files with REFLEX_REDIS_URL pointing at a local redis-server: 762 passed; test_token_manager.py 8 runs in a row, 54 passed each.
  • Playwright test_connection_banner.py: 6 passed without Redis, 6 passed with Redis.
  • uv run pytest tests/units (mock Redis; tests/units/reflex_bench/drivers/test_browser.py deselected, it needs a browser build this machine does not have): 16279 passed, 67 skipped.
  • Playwright test_linked_state.py (4 passed, 1 skipped) and test_background_task.py (7 passed), each on its own; test_lifespan.py 24 passed. test_lifespan.py and test_linked_state.py in one process fail 4 linked-state tests with a KeyError on a lifespan app state; main fails the same way, so it is not from this PR.
  • After the review fixes (second commit): token manager / app / shared / processor / benchmark files, mock Redis: 773 passed, 6 skipped; test_token_manager.py + test_app.py on real Redis: 359 passed; Playwright test_connection_banner.py: 6 passed. The full unit suite was not rerun after that commit.
  • uv run ruff check ., uv run ruff format ., uv run pyright reflex + changed test files, pre-commit on the changed files: clean.
  • No javascript changed.

closes #6345

https://claude.ai/code/session_01LwJUCUVZdDdk6rVjYEdTnk