Skip to content
Merged
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
9 changes: 8 additions & 1 deletion .ai/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -939,7 +939,14 @@ transport and stream over HTTP, one connection per stream.
worker races to become the single **owner** for the machine by binding a stable
address (`AF_UNIX` on POSIX, `127.0.0.1` loopback on Windows); the winner hosts
the engine, losers proxy over the socket. The bind *is* the lease — when the
owner dies the address frees and a survivor re-elects. A single-process
owner dies the address frees and a survivor re-elects. A leftover unix socket
counts as dead only when a connect is refused, the file is gone or it is not a
socket. An owner too busy to accept (full backlog, probe timeout) is alive:
taking its socket over started a second, empty store at 4000 streaming
browsers. macOS and the BSDs also refuse on a full backlog, so there a refused
probe means dead only once the owner's pid (in the `.addr` advertisement) is
gone. The owner listens as soon as it binds, before it recovers persisted data,
so a starting owner queues connections instead of looking dead. A single-process
deployment is its own owner and pays no socket overhead. Knobs: `namespace`
(defaults to a hash of cwd + argv[0]), `buffer_size` (default 32 — small on
purpose, since each topic retains that many arbitrary payloads; raise it for a
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ This project adheres to [Semantic Versioning](https://semver.org/).
- [#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.
- [#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.
- [#4185](https://github.com/plotly/dash/pull/4185) Fix `RedisSharedStorage` streaming callbacks failing under load with redis-py 8 (`MaxConnectionsError: Too many connections`): calls now wait for a free connection.
- [#4186](https://github.com/plotly/dash/pull/4186) Fix `LocalSharedStorage` electing a second, empty owner under load when the owner was too busy to accept connections, which reset every open stream.

## [4.5.1] - 2026-11-19

Expand Down
86 changes: 66 additions & 20 deletions dash/_shared_storage/local.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import asyncio
import atexit
import contextlib
import errno
import hashlib
import json
import os
Expand Down Expand Up @@ -68,7 +69,12 @@ def _tcp_port(namespace: str) -> int:

def _write_advertisement(addr_path, family, address, token) -> None:
payload = json.dumps(
{"family": int(family), "address": address, "token": token}
{
"family": int(family),
"address": address,
"token": token,
"pid": os.getpid(),
}
).encode("utf-8")
tmp = f"{addr_path}.{os.getpid()}.tmp"
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
Expand All @@ -92,26 +98,51 @@ def _read_advertisement(addr_path, retries=100, delay=0.05):
raise ConnectionError("shared-storage owner advertisement not found")


def _unix_is_stale(path: str) -> bool:
def _owner_alive(addr_path: str) -> bool:
try:
with open(addr_path, "rb") as f:
pid = json.loads(f.read().decode("utf-8"))["pid"]
os.kill(pid, 0)
except PermissionError:
return True # the process exists, it is just not ours
except (OSError, ValueError, KeyError, TypeError):
return False
return True


def _unix_is_stale(path: str, addr_path: Optional[str] = None) -> bool:
"""Whether the socket file at ``path`` has no owner behind it. An owner
too busy to accept is alive: taking its socket over would start a second,
empty store."""
probe = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
probe.settimeout(0.5)
try:
probe.connect(path)
return False # a live owner answered
except OSError:
return True # refused / no listener -> stale socket file
except FileNotFoundError:
return True
except ConnectionRefusedError:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A refusal here can also mean the owner is still starting up. Could you add logic to handle that situation?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call, it was a real gap: the owner bound the socket, then recovered persisted data, and only then listened, so a re-election in that window got refused and started a second owner. Fixed in d75dbf0: the owner now listens right after it binds, so a starting owner queues connections instead of refusing them. Also 9c49167: if election fails after the bind (for example recovery raises), the socket and advertisement are released, so they can't pass for a live owner. Tests for both.

# Linux refuses only when nobody listens. macOS and the BSDs also
# refuse when the backlog is full, so there the owner's process
# decides.
if sys.platform.startswith("linux") or addr_path is None:
return True
return not _owner_alive(addr_path)
except OSError as exc:
# Not a socket at all, or (a timeout, a full backlog) a busy owner.
return exc.errno == errno.ENOTSOCK
finally:
probe.close()


def _try_bind(namespace: str, sock_path: str):
def _try_bind(namespace: str, sock_path: str, addr_path: Optional[str] = None):
"""Try to become the owner. Returns (listen_sock, family, address) or None."""
if _HAS_AF_UNIX:
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
s.bind(sock_path)
except OSError:
if _unix_is_stale(sock_path):
if _unix_is_stale(sock_path, addr_path):
try:
os.unlink(sock_path)
s.bind(sock_path)
Expand All @@ -122,6 +153,9 @@ def _try_bind(namespace: str, sock_path: str):
s.close()
return None
os.chmod(sock_path, 0o600)
# Listen now, not once the owner is ready to serve: a probe refused
# while a starting owner recovers its data would take it for stale.
s.listen(128)
return s, socket.AF_UNIX, sock_path

port = _tcp_port(namespace)
Expand All @@ -132,6 +166,7 @@ def _try_bind(namespace: str, sock_path: str):
except OSError:
s.close()
return None
s.listen(128)
return s, socket.AF_INET, ("127.0.0.1", port)


Expand Down Expand Up @@ -179,24 +214,35 @@ def is_owner(self) -> bool:
return self._role == "owner"

def _elect(self) -> None:
bound = _try_bind(self._namespace, self._sock_path)
bound = _try_bind(self._namespace, self._sock_path, self._addr_path)
if bound:
listen_sock, family, address = bound
token = secrets.token_hex(16)
_write_advertisement(self._addr_path, family, address, token)
engine = StoreEngine(self._buffer_size)
if self._mode != "memory":
assert self._path is not None
persistence = _Persistence(
self._path, self._mode, self._flush_interval, engine
)
# Recover before serving (so clients see the restored state) and
# before attaching (so restored keys are not re-marked dirty).
persistence.recover()
engine.attach_persistence(persistence)
persistence.start()
server = OwnerServer(engine, listen_sock, token)
server.start()
try:
_write_advertisement(self._addr_path, family, address, token)
if self._mode != "memory":
assert self._path is not None
persistence = _Persistence(
self._path, self._mode, self._flush_interval, engine
)
# Recover before serving (so clients see the restored state)
# and before attaching (so restored keys are not re-marked
# dirty).
persistence.recover()
engine.attach_persistence(persistence)
persistence.start()
server = OwnerServer(engine, listen_sock, token)
server.start()
except BaseException:
# The socket already listens: left open, it would pass for a
# live owner that never answers.
listen_sock.close()
engine.close()
for path in (self._sock_path, self._addr_path):
with contextlib.suppress(OSError):
os.unlink(path)
raise
self._engine, self._server = engine, server
self._family, self._address, self._token = family, address, token
self._role = "owner"
Expand Down
121 changes: 121 additions & 0 deletions tests/shared_storage/test_local_cross_process.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@
socket transport, not the in-process fast path.
"""
import multiprocessing as mp
import os
import signal
import json
import socket
import subprocess
import sys
import threading
import time
import uuid
Expand Down Expand Up @@ -176,6 +182,121 @@ def test_reelection_after_owner_killed(owner):
client.close()


@pytest.mark.skipif(
not hasattr(socket, "AF_UNIX") or not hasattr(signal, "SIGSTOP"),
reason="needs unix sockets and SIGSTOP",
)
def test_busy_owner_is_not_replaced(owner):
"""An owner too busy to accept (its backlog full) is alive. A client that
re-elects must not take its socket over and start a second, empty store."""
ns, o = owner
client = LocalSharedStorage(namespace=ns)
client.start()
o.do("set", "before", "value")
assert client.get("before") == "value"

os.kill(o.proc.pid, signal.SIGSTOP)
held = []
try:
for _ in range(200):
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.setblocking(False)
try:
sock.connect(client._coord._sock_path)
except OSError:
pass
held.append(sock)
client._coord.on_owner_lost()
assert not client._coord.is_owner()
finally:
os.kill(o.proc.pid, signal.SIGCONT)
for sock in held:
sock.close()

assert client.get("before") == "value"
client.close()


@pytest.mark.skipif(not hasattr(socket, "AF_UNIX"), reason="needs unix sockets")
def test_stale_socket_probe(tmp_path, monkeypatch):
from dash._shared_storage import local

sock_path = str(tmp_path / "s.sock")
addr_path = str(tmp_path / "s.addr")
assert local._unix_is_stale(sock_path, addr_path) # no file

leftover = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
leftover.bind(sock_path)
leftover.close() # the file stays, nobody listens
assert local._unix_is_stale(sock_path, addr_path)

stray = tmp_path / "stray"
stray.write_text("not a socket")
assert local._unix_is_stale(str(stray), addr_path)

# macOS and the BSDs also refuse when the backlog is full: there a refused
# probe means stale only once the advertised owner process is gone.
monkeypatch.setattr(local.sys, "platform", "darwin")
assert local._unix_is_stale(sock_path, addr_path) # no advertisement
with open(addr_path, "w", encoding="utf-8") as f:
json.dump({"pid": os.getpid()}, f)
assert not local._unix_is_stale(sock_path, addr_path)
gone = subprocess.Popen([sys.executable, "-c", ""])
gone.wait()
with open(addr_path, "w", encoding="utf-8") as f:
json.dump({"pid": gone.pid}, f)
assert local._unix_is_stale(sock_path, addr_path)


@pytest.mark.skipif(not hasattr(socket, "AF_UNIX"), reason="needs unix sockets")
def test_starting_owner_is_not_stale(tmp_path):
"""An owner that has bound its socket but is still recovering its data
before serving is alive, so a re-election must not take its socket over."""
from dash._shared_storage import local

sock_path = str(tmp_path / "s.sock")
addr_path = str(tmp_path / "s.addr")
listen_sock, _, _ = local._try_bind("unused", sock_path, addr_path)
try:
assert not local._unix_is_stale(sock_path, addr_path)
assert local._try_bind("unused", sock_path, addr_path) is None
finally:
listen_sock.close()


@pytest.mark.skipif(not hasattr(socket, "AF_UNIX"), reason="needs unix sockets")
def test_failed_election_releases_the_socket(tmp_path, monkeypatch):
"""An election that fails after binding (here, recovering persisted data)
must not leave a listening socket that would pass for a live owner."""
from dash._shared_storage import local

pytest.importorskip("msgspec")
real_recover = local._Persistence.recover

def broken(self):
raise OSError("disk unreadable")

monkeypatch.setattr(local._Persistence, "recover", broken)
store = LocalSharedStorage(
namespace=f"t-{uuid.uuid4().hex[:8]}",
mode="persist",
path=str(tmp_path / "store"),
)
# Keep the traceback alive, as a logged or stored error would: its frames
# must not be what holds the socket open.
with pytest.raises(OSError, match="disk unreadable") as failure:
store.start()
assert failure.traceback
assert local._unix_is_stale(store._coord._sock_path, store._coord._addr_path)

monkeypatch.setattr(local._Persistence, "recover", real_recover)
store._coord.ensure()
assert store._coord.is_owner()
store.set("k", "v")
assert store.get("k") == "v"
store.close()


def test_reelection_recovers_persisted_data(tmp_path):
"""With mode='persist', a re-elected owner recovers the killed owner's data
from disk instead of coming up cold."""
Expand Down
Loading