From 148a29e7fe9e628c592eec1b690c91d0ef70971a Mon Sep 17 00:00:00 2001 From: Jakub Trllo <43494761+iLLiCiTiT@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:24:58 +0100 Subject: [PATCH 1/3] Port websocket robustness fixes from ayon-core event hub - Reconnect a working connection silently before reporting it as lost, emit 'connection.interrupted' instead. Server restart is still reported as closed right away. - Count receive timeouts instead of measuring wall-clock time, so a host holding the GIL does not make the connection look dead. - Block SIGPIPE in the websocket thread, some hosts reset it to the default action which terminates the process. Co-Authored-By: Claude Opus 5.5 --- ayon_api/events.py | 50 +++++++++++---- tests/test_event_hub_ping.py | 120 +++++++++++++++++++++++++---------- 2 files changed, 127 insertions(+), 43 deletions(-) diff --git a/ayon_api/events.py b/ayon_api/events.py index 318e828a8..b5c651725 100644 --- a/ayon_api/events.py +++ b/ayon_api/events.py @@ -7,8 +7,8 @@ import logging import os import re +import signal import threading -import time import typing from typing import Any, Callable import weakref @@ -493,7 +493,10 @@ def _validate_ref(self) -> None: # when nothing was received for this amount of time. _PING_INTERVAL: float = 5.0 # Connection is considered dead if nothing (not even pong) was received -# for this amount of time. +# while waiting on the socket for this amount of time. Wall-clock time +# is not used, the thread might not run for a long time (e.g. DCC main +# thread holds the GIL while rendering) while server messages are +# waiting in the socket. _RECV_TIMEOUT: float = 15.0 # Timeout for opening websocket connection and for the auth check request. _CONNECT_TIMEOUT: float = 5.0 @@ -531,9 +534,8 @@ class _LoopState: auth_required: bool = False # Some message was received with current websocket connection received_message: bool = False - # When last frame (message, ping or pong) was received - # ('time.monotonic') - last_received: float = 0.0 + # Receive timeouts in a row with current websocket connection + recv_timeouts: int = 0 # Connection state reported via events # - 'None' means unknown (nothing was reported yet) connected: bool | None = None @@ -572,6 +574,9 @@ class EventHub: Internal topics: - 'connection.opened' first message received after (re)connection. - 'connection.closed' connection was lost or could not be created. + - 'connection.interrupted' connection was lost and is reconnected + without reporting it as closed. Events might have been missed, + 'connection.opened' is emitted once reconnected. - 'auth.failed' server rejected the token. Args: @@ -581,6 +586,7 @@ class EventHub: # Topics emitted by the hub itself TOPIC_CONNECTION_OPENED: str = "connection.opened" TOPIC_CONNECTION_CLOSED: str = "connection.closed" + TOPIC_CONNECTION_INTERRUPTED: str = "connection.interrupted" TOPIC_AUTH_FAILED: str = "auth.failed" # Topic sent by server TOPIC_SERVER_RESTART_REQUESTED: str = "server.restart_requested" @@ -941,11 +947,28 @@ def _on_connection_lost( if stop_event.is_set(): return + reason = exc if exc is not None else "Closed by server" + # Working connection can be closed by the server when the client + # did not answer its pings (host held the GIL for a long time), + # by a proxy or a network hiccup. Report it as lost only if + # reconnecting fails. Server restart is reported right away, the + # restart overlay is hidden only by 'connection.opened'. + if received_message and not state.server_is_restarting: + self._log.info( + "Websocket connection closed, reconnecting: %s", reason + ) + # State is unknown until reconnected, 'connection.opened' is + # emitted on first message + with self._state_lock: + state.connected = None + self.emit_event(Event(self.TOPIC_CONNECTION_INTERRUPTED)) + self._wait(stop_event, _RECONNECT_DELAYS[0]) + return + # Log only first failure, reconnection attempts would spam the log if state.connected is not False: self._log.warning( - "Lost connection to AYON server websocket: %s", - exc if exc is not None else "Closed by server", + "Lost connection to AYON server websocket: %s", reason ) self._set_connected(False) @@ -973,6 +996,11 @@ def _wait(self, stop_event: threading.Event, timeout: float) -> None: wake_event.clear() def _thread_loop(self, stop_event: threading.Event) -> None: + # Writing to a connection closed by the server raises SIGPIPE. + # Python ignores it, but some hosts reset it to the default + # action which terminates the process (e.g. Silhouette on Linux). + if hasattr(signal, "pthread_sigmask"): + signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGPIPE}) try: self._loop(stop_event) except Exception: @@ -1004,7 +1032,7 @@ def _loop(self, stop_event: threading.Event) -> None: break self._ws_connection = ws_con state.received_message = False - state.last_received = time.monotonic() + state.recv_timeouts = 0 state.auth_required = True if state.auth_required: @@ -1023,8 +1051,8 @@ def _loop(self, stop_event: threading.Event) -> None: try: op_code, message = ws_con.recv_data(control_frame=True) except WebSocketTimeoutException as exc: - elapsed = time.monotonic() - state.last_received - if elapsed >= _RECV_TIMEOUT: + state.recv_timeouts += 1 + if state.recv_timeouts * _PING_INTERVAL >= _RECV_TIMEOUT: # Server did not respond to ping self._on_connection_lost(stop_event, exc) continue @@ -1040,7 +1068,7 @@ def _loop(self, stop_event: threading.Event) -> None: self._on_connection_lost(stop_event, exc) continue - state.last_received = time.monotonic() + state.recv_timeouts = 0 if op_code == ABNF.OPCODE_CLOSE: self._on_connection_lost(stop_event) continue diff --git a/tests/test_event_hub_ping.py b/tests/test_event_hub_ping.py index b14885b89..4be2d7a47 100644 --- a/tests/test_event_hub_ping.py +++ b/tests/test_event_hub_ping.py @@ -12,30 +12,27 @@ from ayon_api.events import EventHub HEARTBEAT = (ABNF.OPCODE_TEXT, json.dumps({"topic": "heartbeat"})) +RESTART = ( + ABNF.OPCODE_TEXT, + json.dumps({"topic": "server.restart_requested"}), +) +CLOSE = (ABNF.OPCODE_CLOSE, b"") PONG = (ABNF.OPCODE_PONG, b"") SERVER_PING = (ABNF.OPCODE_PING, b"") TIMEOUT = "timeout" -class FakeClock: - def __init__(self) -> None: - self.value = 1000.0 - - def monotonic(self) -> float: - return self.value - - class FakeWebSocket: """Replays scripted results of 'recv_data'. - Timeout moves the clock forward by the socket timeout as a real - socket would. When the script is exhausted the test is stopped. + When the script is exhausted the connection is closed, or the test is + stopped if this is the last connection. """ - def __init__(self, clock, responses, stop_event) -> None: - self._clock = clock + def __init__(self, responses, stop_event, is_last) -> None: self._responses = list(responses) self._stop_event = stop_event + self._is_last = is_last self.pings = 0 def send(self, data) -> None: @@ -49,11 +46,11 @@ def abort(self) -> None: def recv_data(self, control_frame: bool = False): if not self._responses: - self._stop_event.set() - raise ConnectionError("End of test") + if self._is_last: + self._stop_event.set() + raise ConnectionError("End of script") response = self._responses.pop(0) if response == TIMEOUT: - self._clock.value += events_module._PING_INTERVAL raise WebSocketTimeoutException("timed out") return response @@ -74,21 +71,32 @@ def on_event(self, event) -> None: @pytest.fixture def run_hub(monkeypatch): - """Run event hub loop with scripted websocket responses.""" - clock = FakeClock() - monkeypatch.setattr(events_module, "time", clock) + """Run event hub loop with scripted websocket responses. + + Each item of 'scripts' is a list of responses of one connection, + 'None' means that the connection attempt fails. + + """ monkeypatch.setattr(events_module, "_RECONNECT_DELAYS", (0.0,)) - def _run_hub(responses): + def _run_hub(*scripts): stop_event = threading.Event() - fake_ws = FakeWebSocket(clock, responses, stop_event) - connections = [fake_ws] + connections = [ + None if responses is None else FakeWebSocket( + responses, stop_event, idx == len(scripts) - 1 + ) + for idx, responses in enumerate(scripts) + ] + remaining = list(connections) def create_ws_connection(): - if connections: - return connections.pop(0) - stop_event.set() - raise ConnectionError("End of test") + if not remaining: + stop_event.set() + raise ConnectionError("End of test") + ws_con = remaining.pop(0) + if ws_con is None: + raise ConnectionError("Connection refused") + return ws_con hub = EventHub(FakeConnection()) monkeypatch.setattr( @@ -98,7 +106,7 @@ def create_ws_connection(): recorder = EventsRecorder() hub.add_callback("connection.*", recorder.on_event, connect=False) hub._loop(stop_event) - return recorder.topics, fake_ws + return recorder.topics, connections return _run_hub @@ -111,7 +119,7 @@ def test_busy_server_without_heartbeat_is_connected(run_hub): """ responses = [HEARTBEAT] + [TIMEOUT, PONG] * 10 - topics, fake_ws = run_hub(responses) + topics, (fake_ws,) = run_hub(responses) assert topics == ["connection.opened"] assert fake_ws.pings == 10 @@ -119,22 +127,70 @@ def test_busy_server_without_heartbeat_is_connected(run_hub): def test_server_ping_keeps_connection_alive(run_hub): responses = [HEARTBEAT] + [TIMEOUT, TIMEOUT, SERVER_PING] * 5 - topics, fake_ws = run_hub(responses) + topics, _ = run_hub(responses) assert topics == ["connection.opened"] -def test_no_response_to_ping_is_connection_lost(run_hub): +def test_no_response_to_ping_interrupts_connection(run_hub): + """Working connection that stopped responding is reconnected silently.""" responses = [HEARTBEAT, TIMEOUT, TIMEOUT, TIMEOUT] - topics, fake_ws = run_hub(responses) + topics, (fake_ws,) = run_hub(responses) - assert topics == ["connection.opened", "connection.closed"] + assert topics == ["connection.opened", "connection.interrupted"] assert fake_ws.pings == 2 +def test_timeouts_are_counted_not_measured(run_hub, monkeypatch): + """Time spent outside of socket wait does not count as silence. + + Host might hold the GIL for minutes, messages waiting in the socket + are received once the thread runs again. + + """ + monkeypatch.setattr(events_module, "_RECV_TIMEOUT", 15.0) + monkeypatch.setattr(events_module, "_PING_INTERVAL", 5.0) + responses = [HEARTBEAT] + [TIMEOUT, TIMEOUT, HEARTBEAT] * 5 + topics, (fake_ws,) = run_hub(responses) + + assert topics == ["connection.opened"] + + +def test_interrupted_connection_reports_opened_on_reconnect(run_hub): + topics, _ = run_hub([HEARTBEAT, CLOSE], [HEARTBEAT]) + + assert topics == [ + "connection.opened", + "connection.interrupted", + "connection.opened", + ] + + +def test_failed_reconnect_reports_closed(run_hub): + """Connection is reported as lost when reconnection fails.""" + topics, _ = run_hub([HEARTBEAT, CLOSE], None) + + assert topics == [ + "connection.opened", + "connection.interrupted", + "connection.closed", + ] + + +def test_server_restart_reports_closed(run_hub): + """Server restart is reported right away, not as interruption.""" + topics, _ = run_hub([HEARTBEAT, RESTART, CLOSE], [HEARTBEAT]) + + assert topics == [ + "connection.opened", + "connection.closed", + "connection.opened", + ] + + def test_pong_does_not_report_connected(run_hub): """Pong does not tell if client is authorized.""" responses = [PONG, PONG] - topics, fake_ws = run_hub(responses) + topics, _ = run_hub(responses) assert "connection.opened" not in topics From cf388b59d429d6a576149a92735baee6b95de07a Mon Sep 17 00:00:00 2001 From: Jakub Trllo <43494761+iLLiCiTiT@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:24:43 +0100 Subject: [PATCH 2/3] Report logout as closed connection and guard timeout counting - Reconnect silently only while there is a token, logout closed the connection and was reported as 'connection.interrupted' with unknown state instead of 'connection.closed'. - Say in docstring that 'connection.interrupted' should be handled like 'connection.closed' by anything caching server data. - Timeout counting test now simulates GIL stall with a jumping clock, it passed with wall-clock based detection before. Co-Authored-By: Claude Opus 5.5 --- ayon_api/events.py | 12 ++++++++++-- tests/test_event_hub_lifecycle.py | 13 +++++++++++++ tests/test_event_hub_ping.py | 19 +++++++++++++++++-- 3 files changed, 40 insertions(+), 4 deletions(-) diff --git a/ayon_api/events.py b/ayon_api/events.py index b5c651725..9e46b9e72 100644 --- a/ayon_api/events.py +++ b/ayon_api/events.py @@ -576,7 +576,9 @@ class EventHub: - 'connection.closed' connection was lost or could not be created. - 'connection.interrupted' connection was lost and is reconnected without reporting it as closed. Events might have been missed, - 'connection.opened' is emitted once reconnected. + 'connection.opened' is emitted once reconnected. Anything that + caches server data and resyncs on 'connection.closed' should + handle it the same way. - 'auth.failed' server rejected the token. Args: @@ -953,7 +955,13 @@ def _on_connection_lost( # by a proxy or a network hiccup. Report it as lost only if # reconnecting fails. Server restart is reported right away, the # restart overlay is hidden only by 'connection.opened'. - if received_message and not state.server_is_restarting: + # Connection closed because the token was removed (logout) is + # reported as closed right away too. + if ( + received_message + and not state.server_is_restarting + and self._connection.access_token + ): self._log.info( "Websocket connection closed, reconnecting: %s", reason ) diff --git a/tests/test_event_hub_lifecycle.py b/tests/test_event_hub_lifecycle.py index 8ea711ff4..60e288ff1 100644 --- a/tests/test_event_hub_lifecycle.py +++ b/tests/test_event_hub_lifecycle.py @@ -160,6 +160,19 @@ def test_token_change_wakes_hub_after_auth_failure(con, sockets, hubs): assert sockets[-1].tokens == ["token-b"] +def test_reset_token_reports_connection_closed(con, sockets, hubs): + """Logout is reported as closed, not as interrupted connection.""" + hub = con.get_event_hub() + recorder = _start_hub(hub, hubs) + assert wait_for(lambda: recorder.count(EventHub.TOPIC_CONNECTION_OPENED)) + + con.reset_token() + + assert wait_for(lambda: recorder.count(EventHub.TOPIC_CONNECTION_CLOSED)) + assert recorder.count(EventHub.TOPIC_CONNECTION_INTERRUPTED) == 0 + assert hub.get_connection_state() is False + + def test_stopped_hub_is_garbage_collected(sockets): con = ServerAPI("http://server-a:0", "token-a", create_session=False) hub = con.get_event_hub() diff --git a/tests/test_event_hub_ping.py b/tests/test_event_hub_ping.py index 4be2d7a47..bb9480d82 100644 --- a/tests/test_event_hub_ping.py +++ b/tests/test_event_hub_ping.py @@ -141,6 +141,18 @@ def test_no_response_to_ping_interrupts_connection(run_hub): assert fake_ws.pings == 2 +class StalledClock: + """Clock jumping forward on each read, as if the GIL was held.""" + + def __init__(self, stall: float) -> None: + self._stall = stall + self._value = 1000.0 + + def monotonic(self) -> float: + self._value += self._stall + return self._value + + def test_timeouts_are_counted_not_measured(run_hub, monkeypatch): """Time spent outside of socket wait does not count as silence. @@ -148,8 +160,11 @@ def test_timeouts_are_counted_not_measured(run_hub, monkeypatch): are received once the thread runs again. """ - monkeypatch.setattr(events_module, "_RECV_TIMEOUT", 15.0) - monkeypatch.setattr(events_module, "_PING_INTERVAL", 5.0) + # Wall-clock based detection would report the connection as lost + # on first timeout. Module does not import 'time' anymore. + monkeypatch.setattr( + events_module, "time", StalledClock(300.0), raising=False + ) responses = [HEARTBEAT] + [TIMEOUT, TIMEOUT, HEARTBEAT] * 5 topics, (fake_ws,) = run_hub(responses) From 029408efc1b4458933268d2faded6304093fd091 Mon Sep 17 00:00:00 2001 From: Jakub Trllo <43494761+iLLiCiTiT@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:28:39 +0100 Subject: [PATCH 3/3] Mention blocked SIGPIPE in EventHub docstring Co-Authored-By: Claude Opus 5.5 --- ayon_api/events.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ayon_api/events.py b/ayon_api/events.py index 9e46b9e72..1d58e125a 100644 --- a/ayon_api/events.py +++ b/ayon_api/events.py @@ -570,6 +570,10 @@ class EventHub: Callbacks are triggered in the websocket thread! Use own queue to process them in main thread, especially if a callback touches Qt widgets. + SIGPIPE is blocked in the websocket thread (see '_thread_loop'). + Threads and subprocesses started from a callback inherit the + blocked signal, e.g. 'yes | head' prints 'Broken pipe' instead + of exiting quietly. Internal topics: - 'connection.opened' first message received after (re)connection.