From a9c01430ccbfa49ab591b515a4edfbb54714aa83 Mon Sep 17 00:00:00 2001 From: philippe Date: Tue, 24 Nov 2026 10:13:43 -0500 Subject: [PATCH 1/3] Keep a live stream downlink's record open when an older downlink closes late --- .ai/ARCHITECTURE.md | 9 ++ CHANGELOG.md | 5 + dash/_stream_hub.py | 45 ++++++++- tests/streaming/test_stream_transport.py | 117 +++++++++++++++++++++++ 4 files changed, 173 insertions(+), 3 deletions(-) diff --git a/.ai/ARCHITECTURE.md b/.ai/ARCHITECTURE.md index 5cae8f69bc..b5c64012fe 100644 --- a/.ai/ARCHITECTURE.md +++ b/.ai/ARCHITECTURE.md @@ -1509,6 +1509,15 @@ downlink sends `streamCancel: {requestId}` per stream instead; the same pump check picks up the per-request key. A pump that stops publishes a terminal `{"done": true}` so a late-reconnecting client resolves. +A downlink's close reads the record (is it still mine?) and then writes it +closed: two round trips. When the browser's next downlink opens between them, +the stale close overwrites a live record. On a busy store that happened to +1-2% of streams at 4000 browsers, each cancelled at 10s. So an open async +downlink reads the record every `DOWNLINK_GRACE / 2` and writes it open again +only when an older downlink closed it. It leaves an open record or one closed +by a newer downlink alone: a relay whose client vanished unnoticed must not +keep the connection alive. Its own close waits for a repair in flight. + **Shutdown.** ASGI servers drain in-flight responses before stopping and a long-lived downlink never ends by itself, so `_stream_hub` installs a SIGINT/SIGTERM handler (`install_stream_shutdown_handler`, at import and again diff --git a/CHANGELOG.md b/CHANGELOG.md index ef3c33f9cf..d296f452f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ All notable changes to `dash` will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org/). +## [UNRELEASED] + +### Fixed +- [#]() Fix ASGI streaming callbacks being cancelled after 10 seconds under load, when a browser's previous downlink closed late and marked its new one closed. + ## [4.5.1] - 2026-11-19 ### Removed diff --git a/dash/_stream_hub.py b/dash/_stream_hub.py index 7fd14aabe9..d8fb05539d 100644 --- a/dash/_stream_hub.py +++ b/dash/_stream_hub.py @@ -212,15 +212,21 @@ def __init__( self._key = connection_key(connection_id) self._token = secrets.token_hex(8) self._closed = False + self._opened = 0.0 + self._refresh: Optional["asyncio.Future[None]"] = None with _registry_lock: _active_subscriptions.add(self.subscription) def _record(self, is_open: bool) -> Any: + now = time.time() + if not self._opened: + self._opened = now return { "mode": "stream", "open": is_open, - "at": time.time(), + "at": now, "token": self._token, + "opened": self._opened, } def _is_mine(self, record: Any) -> bool: @@ -249,7 +255,36 @@ def close(self) -> None: if self._is_mine(self.storage.get(self._key)): self.storage.set(self._key, self._record(False)) - async def _arecord_closed(self) -> None: + async def _akeep_open(self) -> None: + # An older downlink of this connection closing late reads the record, + # then writes it closed: two round trips, between which this one may + # have opened. Checking well inside the grace repairs that before any + # pump counts the browser as gone. + while True: + await asyncio.sleep(DOWNLINK_GRACE / 2) + self._refresh = asyncio.ensure_future(self._arepair()) + with contextlib.suppress(Exception): + await asyncio.shield(self._refresh) + + async def _arepair(self) -> None: + record = await self.storage.aget(self._key) + if isinstance(record, dict) and ( + record.get("open") or record.get("opened", 0.0) > self._opened + ): + # Open, or closed by a newer downlink: this one may be a relay + # whose client is gone, and must not mark the connection alive. + return + await self.aopen() + + async def _arecord_closed(self, keep_open: Optional[asyncio.Task]) -> None: + if keep_open is not None: + keep_open.cancel() + await asyncio.wait({keep_open}) + if self._refresh is not None: + # A refresh already sent would otherwise land after the closed + # record and mark this downlink open again. + with contextlib.suppress(Exception): + await self._refresh with contextlib.suppress(Exception): if self._is_mine(await self.storage.aget(self._key)): await self.storage.aset(self._key, self._record(False)) @@ -270,8 +305,10 @@ def envelopes(self) -> Iterator[Any]: async def aenvelopes(self) -> AsyncIterator[Any]: """Async counterpart of :meth:`envelopes` for ASGI backends.""" + keep_open = None try: await self.aopen() + keep_open = asyncio.ensure_future(self._akeep_open()) async for seq, message in self.subscription.aiter_with_seq(): yield {**message, "seq": seq} except SharedStorageGap: @@ -285,9 +322,11 @@ async def aenvelopes(self) -> AsyncIterator[Any]: # leaving the record open so the pumps never learn the browser # left. with contextlib.suppress(RuntimeError): # the loop is gone - task = asyncio.ensure_future(self._arecord_closed()) + task = asyncio.ensure_future(self._arecord_closed(keep_open)) _closing_downlinks.add(task) task.add_done_callback(_closing_downlinks.discard) + elif keep_open is not None: + keep_open.cancel() def _log_downlink_failure(exc: Exception) -> None: diff --git a/tests/streaming/test_stream_transport.py b/tests/streaming/test_stream_transport.py index c5ee1877f3..176d006bee 100644 --- a/tests/streaming/test_stream_transport.py +++ b/tests/streaming/test_stream_transport.py @@ -345,6 +345,123 @@ def test_replaced_downlink_does_not_mark_the_new_one_closed(): assert storage.get(hub.connection_key(cid))["open"] is False +def test_stale_close_does_not_end_a_live_downlink(monkeypatch): + """Under load, a downlink closing late reads the record before the + browser's next downlink opens and writes it closed after. The pumps must + still see the live downlink once the grace has passed.""" + from dash import _stream_hub as hub + + monkeypatch.setattr(hub, "DOWNLINK_GRACE", 0.6) + storage = _storage("stale-close") + cid = "c-stale" + stale = hub.Downlink(storage, cid) + stale.open() + assert stale._is_mine(storage.get(hub.connection_key(cid))) + + async def scenario(): + live = hub.Downlink(storage, cid, replay_from=0) + + async def relay(): + async for _env in live.aenvelopes(): + pass + + task = asyncio.ensure_future(relay()) + await asyncio.sleep(0.1) + stop = hub._stop_check(storage, cid, "r-stale") + await storage.aset(hub.connection_key(cid), stale._record(False)) + await asyncio.sleep(1.0) + gone = await stop() + task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await task + await asyncio.gather(*hub._closing_downlinks) + return gone + + assert not asyncio.run(scenario()) + assert storage.get(hub.connection_key(cid))["open"] is False + storage.close() + + +def test_refresh_in_flight_does_not_reopen_a_closed_downlink(monkeypatch): + from dash import _stream_hub as hub + + monkeypatch.setattr(hub, "DOWNLINK_GRACE", 0.03) + storage = _storage("refresh-close") + cid = "c-refresh" + real_aset = storage.aset + + async def slow_aset(key, value, ttl=None): + if value.get("open"): + await asyncio.sleep(0.15) + await real_aset(key, value, ttl) + + monkeypatch.setattr(storage, "aset", slow_aset) + + stale = hub.Downlink(storage, cid) + stale.open() + + async def scenario(): + downlink = hub.Downlink(storage, cid) + + async def relay(): + async for _env in downlink.aenvelopes(): + pass + + task = asyncio.ensure_future(relay()) + await asyncio.sleep(0.2) + await real_aset(hub.connection_key(cid), stale._record(False)) + await asyncio.sleep(0.05) + assert downlink._refresh is not None and not downlink._refresh.done() + task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await task + await asyncio.gather(*hub._closing_downlinks) + await asyncio.sleep(0.2) + + asyncio.run(scenario()) + assert storage.get(hub.connection_key(cid))["open"] is False + storage.close() + + +def test_relay_of_a_gone_client_does_not_keep_the_connection_alive(monkeypatch): + """A replaced downlink whose client vanished without the server noticing + keeps relaying. Once the newer downlink closes, the pumps must still see + the browser as gone.""" + from dash import _stream_hub as hub + + monkeypatch.setattr(hub, "DOWNLINK_GRACE", 0.3) + storage = _storage("zombie") + cid = "c-zombie" + + async def scenario(): + zombie = hub.Downlink(storage, cid) + newer = hub.Downlink(storage, cid, replay_from=0) + + async def relay(downlink): + async for _env in downlink.aenvelopes(): + pass + + zombie_task = asyncio.ensure_future(relay(zombie)) + await asyncio.sleep(0.05) + newer_task = asyncio.ensure_future(relay(newer)) + await asyncio.sleep(0.05) + newer_task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await newer_task + await asyncio.gather(*hub._closing_downlinks) + stop = hub._stop_check(storage, cid, "r-zombie") + await asyncio.sleep(0.6) + gone = await stop() + zombie_task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await zombie_task + await asyncio.gather(*hub._closing_downlinks) + return gone + + assert asyncio.run(scenario()) + storage.close() + + def test_cancelled_async_downlink_still_records_closed(): """A client disconnect cancels the ASGI response mid-relay; the closed record must still be written, or pumps never learn the browser left.""" From ac491f57d4bc6c97bd525ee98d643acf6983992e Mon Sep 17 00:00:00 2001 From: philippe Date: Tue, 24 Nov 2026 10:18:05 -0500 Subject: [PATCH 2/3] Let the newest downlink own the record: close over older ones, leave records without opened alone --- .ai/ARCHITECTURE.md | 11 +++++++---- dash/_stream_hub.py | 16 +++++++++++----- tests/streaming/test_stream_transport.py | 20 ++++++++++++++++++++ 3 files changed, 38 insertions(+), 9 deletions(-) diff --git a/.ai/ARCHITECTURE.md b/.ai/ARCHITECTURE.md index b5c64012fe..692bb02646 100644 --- a/.ai/ARCHITECTURE.md +++ b/.ai/ARCHITECTURE.md @@ -1512,11 +1512,14 @@ a terminal `{"done": true}` so a late-reconnecting client resolves. A downlink's close reads the record (is it still mine?) and then writes it closed: two round trips. When the browser's next downlink opens between them, the stale close overwrites a live record. On a busy store that happened to -1-2% of streams at 4000 browsers, each cancelled at 10s. So an open async +1-2% of streams at 4000 browsers, each cancelled at 10s. The rule now: the +newest downlink of a page owns its record (records carry `opened`). A close +writes closed over its own record or an older downlink's. An open async downlink reads the record every `DOWNLINK_GRACE / 2` and writes it open again -only when an older downlink closed it. It leaves an open record or one closed -by a newer downlink alone: a relay whose client vanished unnoticed must not -keep the connection alive. Its own close waits for a repair in flight. +only when an older downlink closed it, never over an open record or a newer +downlink's: a relay whose client vanished unnoticed must not keep the page +alive. Its close waits for a repair in flight. `opened` is wall-clock time, so +across hosts it assumes clocks agree to well under a round trip. **Shutdown.** ASGI servers drain in-flight responses before stopping and a long-lived downlink never ends by itself, so `_stream_hub` installs a diff --git a/dash/_stream_hub.py b/dash/_stream_hub.py index d8fb05539d..d01e36d3ab 100644 --- a/dash/_stream_hub.py +++ b/dash/_stream_hub.py @@ -232,6 +232,14 @@ def _record(self, is_open: bool) -> Any: def _is_mine(self, record: Any) -> bool: return isinstance(record, dict) and record.get("token") == self._token + def _owns(self, record: Any) -> bool: + """The newest downlink of a page owns its record: this one's, or an + older downlink's that this one replaced.""" + if self._is_mine(record): + return True + opened = record.get("opened") if isinstance(record, dict) else None + return opened is not None and opened < self._opened + def _release(self) -> bool: """End the subscription; False if this downlink was already closed.""" if self._closed: @@ -252,7 +260,7 @@ def close(self) -> None: if not self._release(): return with contextlib.suppress(Exception): - if self._is_mine(self.storage.get(self._key)): + if self._owns(self.storage.get(self._key)): self.storage.set(self._key, self._record(False)) async def _akeep_open(self) -> None: @@ -268,9 +276,7 @@ async def _akeep_open(self) -> None: async def _arepair(self) -> None: record = await self.storage.aget(self._key) - if isinstance(record, dict) and ( - record.get("open") or record.get("opened", 0.0) > self._opened - ): + if isinstance(record, dict) and (record.get("open") or not self._owns(record)): # Open, or closed by a newer downlink: this one may be a relay # whose client is gone, and must not mark the connection alive. return @@ -286,7 +292,7 @@ async def _arecord_closed(self, keep_open: Optional[asyncio.Task]) -> None: with contextlib.suppress(Exception): await self._refresh with contextlib.suppress(Exception): - if self._is_mine(await self.storage.aget(self._key)): + if self._owns(await self.storage.aget(self._key)): await self.storage.aset(self._key, self._record(False)) def envelopes(self) -> Iterator[Any]: diff --git a/tests/streaming/test_stream_transport.py b/tests/streaming/test_stream_transport.py index 176d006bee..01cd8578b2 100644 --- a/tests/streaming/test_stream_transport.py +++ b/tests/streaming/test_stream_transport.py @@ -445,6 +445,8 @@ async def relay(downlink): await asyncio.sleep(0.05) newer_task = asyncio.ensure_future(relay(newer)) await asyncio.sleep(0.05) + # The zombie's own write lands over the newer open record. + await zombie.aopen() newer_task.cancel() with contextlib.suppress(asyncio.CancelledError): await newer_task @@ -462,6 +464,24 @@ async def relay(downlink): storage.close() +def test_closed_record_from_an_older_dash_is_left_alone(): + from dash import _stream_hub as hub + + storage = _storage("legacy") + cid = "c-legacy" + + async def scenario(): + downlink = hub.Downlink(storage, cid) + await downlink.aopen() + legacy = {"mode": "stream", "open": False, "at": time.time(), "token": "x"} + await storage.aset(hub.connection_key(cid), legacy) + await downlink._arepair() + return await storage.aget(hub.connection_key(cid)) + + assert asyncio.run(scenario())["token"] == "x" + storage.close() + + def test_cancelled_async_downlink_still_records_closed(): """A client disconnect cancels the ASGI response mid-relay; the closed record must still be written, or pumps never learn the browser left.""" From 97813c4125a201d3877397f35f311e1d0365ae3a Mon Sep 17 00:00:00 2001 From: philippe Date: Tue, 24 Nov 2026 10:23:56 -0500 Subject: [PATCH 3/3] Add PR number to changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d296f452f7..818abd4ecb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ This project adheres to [Semantic Versioning](https://semver.org/). ## [UNRELEASED] ### Fixed -- [#]() Fix ASGI streaming callbacks being cancelled after 10 seconds under load, when a browser's previous downlink closed late and marked its new one closed. +- [#4184](https://github.com/plotly/dash/pull/4184) Fix ASGI streaming callbacks being cancelled after 10 seconds under load, when a browser's previous downlink closed late and marked its new one closed. ## [4.5.1] - 2026-11-19