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
8 changes: 7 additions & 1 deletion .ai/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -939,7 +939,13 @@ 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. 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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
- [#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

### Removed
Expand Down
45 changes: 38 additions & 7 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:
# 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 Down Expand Up @@ -179,7 +210,7 @@ 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)
Expand Down
72 changes: 72 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,72 @@ 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)


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