Keep the session when a client token connects again: a token can have several sockets
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):
- 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.
- Page-load supersede is keyed by token.
hydrate_and_loadcancels the token's earlier unfinishedon_loadchain, 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_sidonly adds a socket and always returnsNone; 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_updateemits 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 isSADD+EXPIREin oneMULTI; disconnect isSREM(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 theSET NXrestore). A socket that disconnects while itsSADDis 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
- A reconnect that races the old socket's disconnect keeps the token and the state (the bug).
- 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. - 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. - The backend no longer emits
new_tokenfor a token that connects again. The frontend handler andEventNamespace.link_token_to_sid's handling of a replacement token are kept: a custom token manager may still return one, and #7362 emitsnew_tokento rebind tokens to a session. router.session.session_idis the socket that sent the latest event (unchanged), so it differs between tabs sharing a token;router.pagelikewise follows the tab that sent the latest event.- 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. token_to_sid/token_to_socketare deprecated (below).
Compatibility
sid_to_tokenis unchanged (one token per sid still holds).EventNamespace.token_to_sid,TokenManager.token_to_sidandTokenManager.token_to_socketkeep working as read-only views of each token's newest socket and callconsole.deprecate(0.11.1 → 1.0).token_to_socketused to be a writable dict; it is read-only now.- New:
TokenManager.token_to_sidsand the read-onlyEventNamespace.token_to_sids(sockets connected to this instance). Docs that recommendedtoken in app.event_namespace.token_to_sidnow usetoken_to_sids.
"Canonical sid" call sites audited
| Site | Now |
|---|---|
TokenManager.token_to_socket / token_to_sid | deprecated views of the newest socket; storage is token_to_sids |
TokenManager.sid_to_token | unchanged, local sockets only (the Redis manager no longer caches foreign sids in it) |
LocalTokenManager / RedisTokenManager.link_token_to_sid | add a socket, never replace the token |
…disconnect_token, disconnect_all | remove one socket; token dropped with the last |
RedisTokenManager._get_token_owner / _fetch_socket_record | replaced 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_connected | any local socket, else any other owner in Redis |
emit_lost_and_found | publishes 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_disconnect | cancels 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_error | unchanged: resolve the token from the sending sid |
reflex/istate/shared.py _do_update_other_tokens | unchanged, 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_tokento 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_factoryargument tolink_token_to_sidfor the replacement token of a duplicate tab. That argument has nothing left to do after this PR and will conflict textually; its ownnew_tokenemits (rebinding a token to a session) are unaffected. - #6771 (draft, atomic
SET NXclaim): 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_connectedyields "the" sid) and will need to iteratetoken_to_sidsafter 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_tokenhandler. - 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_sidandtest_link_token_to_sid_duplicate_detectedasserted that a new token is minted. Replaced bytest_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, plustest_sockets_disconnecting_together_end_the_page_lifecycle.- The Redis record tests (
SET/GETof a pickledSocketRecord,NXrestore, 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_foundis 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_URLpointing at a localredis-server: 762 passed;test_token_manager.py8 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.pydeselected, it needs a browser build this machine does not have): 16279 passed, 67 skipped.- Playwright
test_linked_state.py(4 passed, 1 skipped) andtest_background_task.py(7 passed), each on its own;test_lifespan.py24 passed.test_lifespan.pyandtest_linked_state.pyin one process fail 4 linked-state tests with aKeyErroron a lifespan app state;mainfails 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.pyon real Redis: 359 passed; Playwrighttest_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-commiton the changed files: clean.- No javascript changed.
closes #6345