Skip to content

Commit c6ebc38

Browse files
authored
Merge pull request #4184 from plotly/fix/stream-downlink-close-race
Fix streaming callbacks cancelled after 10s when a downlink closes late
2 parents 9eb645a + af9accf commit c6ebc38

4 files changed

Lines changed: 200 additions & 5 deletions

File tree

‎.ai/ARCHITECTURE.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1509,6 +1509,18 @@ downlink sends `streamCancel: {requestId}` per stream instead;
15091509
the same pump check picks up the per-request key. A pump that stops publishes
15101510
a terminal `{"done": true}` so a late-reconnecting client resolves.
15111511
1512+
A downlink's close reads the record (is it still mine?) and then writes it
1513+
closed: two round trips. When the browser's next downlink opens between them,
1514+
the stale close overwrites a live record. On a busy store that happened to
1515+
1-2% of streams at 4000 browsers, each cancelled at 10s. The rule now: the
1516+
newest downlink of a page owns its record (records carry `opened`). A close
1517+
writes closed over its own record or an older downlink's. An open async
1518+
downlink reads the record every `DOWNLINK_GRACE / 2` and writes it open again
1519+
only when an older downlink closed it, never over an open record or a newer
1520+
downlink's: a relay whose client vanished unnoticed must not keep the page
1521+
alive. Its close waits for a repair in flight. `opened` is wall-clock time, so
1522+
across hosts it assumes clocks agree to well under a round trip.
1523+
15121524
**Shutdown.** ASGI servers drain in-flight responses before stopping and a
15131525
long-lived downlink never ends by itself, so `_stream_hub` installs a
15141526
SIGINT/SIGTERM handler (`install_stream_shutdown_handler`, at import and again

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ This project adheres to [Semantic Versioning](https://semver.org/).
2222
- [#4104](https://github.com/plotly/dash/pull/4104) Allow `update_title=None` in the `Dash` constructor type hints.
2323
- [#4129](https://github.com/plotly/dash/pull/4129) `set_props` now returns `no_update`, so `yield set_props(...)` in a streaming callback sends the side update right away, and a `set_props` called after the last yield is no longer dropped. Fixes [#4127](https://github.com/plotly/dash/issues/4127).
2424
- [#4137](https://github.com/plotly/dash/pull/4137) Fix FastAPI `after_request` hooks to match Flask: multiple hooks run in LIFO order on every route, get the response and can return a new one. Quart `after_request` hooks get the response too.
25+
- [#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.
2526

2627
## [4.5.1] - 2026-11-19
2728

‎dash/_stream_hub.py‎

Lines changed: 50 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -212,20 +212,34 @@ def __init__(
212212
self._key = connection_key(connection_id)
213213
self._token = secrets.token_hex(8)
214214
self._closed = False
215+
self._opened = 0.0
216+
self._refresh: Optional["asyncio.Future[None]"] = None
215217
with _registry_lock:
216218
_active_subscriptions.add(self.subscription)
217219

218220
def _record(self, is_open: bool) -> Any:
221+
now = time.time()
222+
if not self._opened:
223+
self._opened = now
219224
return {
220225
"mode": "stream",
221226
"open": is_open,
222-
"at": time.time(),
227+
"at": now,
223228
"token": self._token,
229+
"opened": self._opened,
224230
}
225231

226232
def _is_mine(self, record: Any) -> bool:
227233
return isinstance(record, dict) and record.get("token") == self._token
228234

235+
def _owns(self, record: Any) -> bool:
236+
"""The newest downlink of a page owns its record: this one's, or an
237+
older downlink's that this one replaced."""
238+
if self._is_mine(record):
239+
return True
240+
opened = record.get("opened") if isinstance(record, dict) else None
241+
return opened is not None and opened < self._opened
242+
229243
def _release(self) -> bool:
230244
"""End the subscription; False if this downlink was already closed."""
231245
if self._closed:
@@ -246,12 +260,39 @@ def close(self) -> None:
246260
if not self._release():
247261
return
248262
with contextlib.suppress(Exception):
249-
if self._is_mine(self.storage.get(self._key)):
263+
if self._owns(self.storage.get(self._key)):
250264
self.storage.set(self._key, self._record(False))
251265

252-
async def _arecord_closed(self) -> None:
266+
async def _akeep_open(self) -> None:
267+
# An older downlink of this connection closing late reads the record,
268+
# then writes it closed: two round trips, between which this one may
269+
# have opened. Checking well inside the grace repairs that before any
270+
# pump counts the browser as gone.
271+
while True:
272+
await asyncio.sleep(DOWNLINK_GRACE / 2)
273+
self._refresh = asyncio.ensure_future(self._arepair())
274+
with contextlib.suppress(Exception):
275+
await asyncio.shield(self._refresh)
276+
277+
async def _arepair(self) -> None:
278+
record = await self.storage.aget(self._key)
279+
if isinstance(record, dict) and (record.get("open") or not self._owns(record)):
280+
# Open, or closed by a newer downlink: this one may be a relay
281+
# whose client is gone, and must not mark the connection alive.
282+
return
283+
await self.aopen()
284+
285+
async def _arecord_closed(self, keep_open: Optional[asyncio.Task]) -> None:
286+
if keep_open is not None:
287+
keep_open.cancel()
288+
await asyncio.wait({keep_open})
289+
if self._refresh is not None:
290+
# A refresh already sent would otherwise land after the closed
291+
# record and mark this downlink open again.
292+
with contextlib.suppress(Exception):
293+
await self._refresh
253294
with contextlib.suppress(Exception):
254-
if self._is_mine(await self.storage.aget(self._key)):
295+
if self._owns(await self.storage.aget(self._key)):
255296
await self.storage.aset(self._key, self._record(False))
256297

257298
def envelopes(self) -> Iterator[Any]:
@@ -270,8 +311,10 @@ def envelopes(self) -> Iterator[Any]:
270311

271312
async def aenvelopes(self) -> AsyncIterator[Any]:
272313
"""Async counterpart of :meth:`envelopes` for ASGI backends."""
314+
keep_open = None
273315
try:
274316
await self.aopen()
317+
keep_open = asyncio.ensure_future(self._akeep_open())
275318
async for seq, message in self.subscription.aiter_with_seq():
276319
yield {**message, "seq": seq}
277320
except SharedStorageGap:
@@ -285,9 +328,11 @@ async def aenvelopes(self) -> AsyncIterator[Any]:
285328
# leaving the record open so the pumps never learn the browser
286329
# left.
287330
with contextlib.suppress(RuntimeError): # the loop is gone
288-
task = asyncio.ensure_future(self._arecord_closed())
331+
task = asyncio.ensure_future(self._arecord_closed(keep_open))
289332
_closing_downlinks.add(task)
290333
task.add_done_callback(_closing_downlinks.discard)
334+
elif keep_open is not None:
335+
keep_open.cancel()
291336

292337

293338
def _log_downlink_failure(exc: Exception) -> None:

‎tests/streaming/test_stream_transport.py‎

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,143 @@ def test_replaced_downlink_does_not_mark_the_new_one_closed():
345345
assert storage.get(hub.connection_key(cid))["open"] is False
346346

347347

348+
def test_stale_close_does_not_end_a_live_downlink(monkeypatch):
349+
"""Under load, a downlink closing late reads the record before the
350+
browser's next downlink opens and writes it closed after. The pumps must
351+
still see the live downlink once the grace has passed."""
352+
from dash import _stream_hub as hub
353+
354+
monkeypatch.setattr(hub, "DOWNLINK_GRACE", 0.6)
355+
storage = _storage("stale-close")
356+
cid = "c-stale"
357+
stale = hub.Downlink(storage, cid)
358+
stale.open()
359+
assert stale._is_mine(storage.get(hub.connection_key(cid)))
360+
361+
async def scenario():
362+
live = hub.Downlink(storage, cid, replay_from=0)
363+
364+
async def relay():
365+
async for _env in live.aenvelopes():
366+
pass
367+
368+
task = asyncio.ensure_future(relay())
369+
await asyncio.sleep(0.1)
370+
stop = hub._stop_check(storage, cid, "r-stale")
371+
await storage.aset(hub.connection_key(cid), stale._record(False))
372+
await asyncio.sleep(1.0)
373+
gone = await stop()
374+
task.cancel()
375+
with contextlib.suppress(asyncio.CancelledError):
376+
await task
377+
await asyncio.gather(*hub._closing_downlinks)
378+
return gone
379+
380+
assert not asyncio.run(scenario())
381+
assert storage.get(hub.connection_key(cid))["open"] is False
382+
storage.close()
383+
384+
385+
def test_refresh_in_flight_does_not_reopen_a_closed_downlink(monkeypatch):
386+
from dash import _stream_hub as hub
387+
388+
monkeypatch.setattr(hub, "DOWNLINK_GRACE", 0.03)
389+
storage = _storage("refresh-close")
390+
cid = "c-refresh"
391+
real_aset = storage.aset
392+
393+
async def slow_aset(key, value, ttl=None):
394+
if value.get("open"):
395+
await asyncio.sleep(0.15)
396+
await real_aset(key, value, ttl)
397+
398+
monkeypatch.setattr(storage, "aset", slow_aset)
399+
400+
stale = hub.Downlink(storage, cid)
401+
stale.open()
402+
403+
async def scenario():
404+
downlink = hub.Downlink(storage, cid)
405+
406+
async def relay():
407+
async for _env in downlink.aenvelopes():
408+
pass
409+
410+
task = asyncio.ensure_future(relay())
411+
await asyncio.sleep(0.2)
412+
await real_aset(hub.connection_key(cid), stale._record(False))
413+
await asyncio.sleep(0.05)
414+
assert downlink._refresh is not None and not downlink._refresh.done()
415+
task.cancel()
416+
with contextlib.suppress(asyncio.CancelledError):
417+
await task
418+
await asyncio.gather(*hub._closing_downlinks)
419+
await asyncio.sleep(0.2)
420+
421+
asyncio.run(scenario())
422+
assert storage.get(hub.connection_key(cid))["open"] is False
423+
storage.close()
424+
425+
426+
def test_relay_of_a_gone_client_does_not_keep_the_connection_alive(monkeypatch):
427+
"""A replaced downlink whose client vanished without the server noticing
428+
keeps relaying. Once the newer downlink closes, the pumps must still see
429+
the browser as gone."""
430+
from dash import _stream_hub as hub
431+
432+
monkeypatch.setattr(hub, "DOWNLINK_GRACE", 0.3)
433+
storage = _storage("zombie")
434+
cid = "c-zombie"
435+
436+
async def scenario():
437+
zombie = hub.Downlink(storage, cid)
438+
newer = hub.Downlink(storage, cid, replay_from=0)
439+
440+
async def relay(downlink):
441+
async for _env in downlink.aenvelopes():
442+
pass
443+
444+
zombie_task = asyncio.ensure_future(relay(zombie))
445+
await asyncio.sleep(0.05)
446+
newer_task = asyncio.ensure_future(relay(newer))
447+
await asyncio.sleep(0.05)
448+
# The zombie's own write lands over the newer open record.
449+
await zombie.aopen()
450+
newer_task.cancel()
451+
with contextlib.suppress(asyncio.CancelledError):
452+
await newer_task
453+
await asyncio.gather(*hub._closing_downlinks)
454+
stop = hub._stop_check(storage, cid, "r-zombie")
455+
await asyncio.sleep(0.6)
456+
gone = await stop()
457+
zombie_task.cancel()
458+
with contextlib.suppress(asyncio.CancelledError):
459+
await zombie_task
460+
await asyncio.gather(*hub._closing_downlinks)
461+
return gone
462+
463+
assert asyncio.run(scenario())
464+
storage.close()
465+
466+
467+
def test_closed_record_from_an_older_dash_is_left_alone():
468+
from dash import _stream_hub as hub
469+
470+
storage = _storage("legacy")
471+
cid = "c-legacy"
472+
473+
async def scenario():
474+
downlink = hub.Downlink(storage, cid)
475+
await downlink.aopen()
476+
legacy = {"mode": "stream", "open": False, "at": time.time(), "token": "x"}
477+
await storage.aset(hub.connection_key(cid), legacy)
478+
await downlink._arepair()
479+
return await storage.aget(hub.connection_key(cid))
480+
481+
assert asyncio.run(scenario())["token"] == "x"
482+
storage.close()
483+
484+
348485
def test_cancelled_async_downlink_still_records_closed():
349486
"""A client disconnect cancels the ASGI response mid-relay; the closed record
350487
must still be written, or pumps never learn the browser left."""

0 commit comments

Comments
 (0)