Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .ai/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -1509,6 +1509,18 @@ 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. 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, 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
SIGINT/SIGTERM handler (`install_stream_shutdown_handler`, at import and again
Expand Down
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ This project adheres to [Semantic Versioning](https://semver.org/).
## [UNRELEASED]

### Fixed

- [#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.
- [#4104](https://github.com/plotly/dash/pull/4104) Allow `update_title=None` in the `Dash` constructor type hints.

## [4.5.1] - 2026-11-19
Expand Down
55 changes: 50 additions & 5 deletions dash/_stream_hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,20 +212,34 @@ 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:
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:
Expand All @@ -246,12 +260,39 @@ 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 _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 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
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)):
if self._owns(await self.storage.aget(self._key)):
await self.storage.aset(self._key, self._record(False))

def envelopes(self) -> Iterator[Any]:
Expand All @@ -270,8 +311,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:
Expand All @@ -285,9 +328,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:
Expand Down
137 changes: 137 additions & 0 deletions tests/streaming/test_stream_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,143 @@
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()

Check warning on line 414 in tests/streaming/test_stream_transport.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Split this composite assertion into separate assertions.

See more on https://sonarcloud.io/project/issues?id=plotly_dash&issues=AaIOKQAGI_zITBTTMgA6&open=AaIOKQAGI_zITBTTMgA6&pullRequest=4184
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)
# 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
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_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."""
Expand Down
Loading