From 3c59c46551d48c2ca310d3044eedc5b17ef87df8 Mon Sep 17 00:00:00 2001 From: Brad Shannon Date: Wed, 17 Jun 2026 17:57:12 -0400 Subject: [PATCH 1/2] fix(core): bound blocking future.result() calls so a hung dependency can't freeze the connection Two cross-thread future.result() calls had no timeout, so a stalled dependency blocked the thread indefinitely with no recovery: - connection.py: a hung memory backend froze the chat thread during query_memory(). - tts/base.py: a stalled WebSocket send froze the audio priority thread in sendAudioMessage(). Add a 30s timeout and explicit TimeoutError handling at both sites. On timeout the failure is logged and the loop proceeds (memory falls back to None; the audio frame is skipped) instead of deadlocking. The tool-call fan-in already uses tool_call_timeout, so it is left unchanged. --- main/xiaozhi-server/core/connection.py | 10 ++++++++-- main/xiaozhi-server/core/providers/tts/base.py | 7 ++++++- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index 8772180c7..a850947b6 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -27,7 +27,7 @@ from core.utils.modules_initialize import ( ) from core.handle.reportHandle import report, enqueue_tool_report from core.providers.tts.default import DefaultTTS -from concurrent.futures import ThreadPoolExecutor +from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeoutError from core.utils.dialogue import Message, Dialogue from core.providers.asr.dto.dto import InterfaceType from core.handle.textHandle import handleTextMessage @@ -976,7 +976,13 @@ class ConnectionHandler: future = asyncio.run_coroutine_threadsafe( self.memory.query_memory(query), self.loop ) - memory_str = future.result() + try: + memory_str = future.result(timeout=30) + except FutureTimeoutError: + self.logger.bind(tag=TAG).error( + "Memory query timed out after 30s" + ) + memory_str = None if self.intent_type == "function_call" and functions is not None: # 使用支持functions的streaming接口 diff --git a/main/xiaozhi-server/core/providers/tts/base.py b/main/xiaozhi-server/core/providers/tts/base.py index f9b2e02e1..db57d65c9 100644 --- a/main/xiaozhi-server/core/providers/tts/base.py +++ b/main/xiaozhi-server/core/providers/tts/base.py @@ -459,7 +459,12 @@ class TTSProviderBase(ABC): sendAudioMessage(self.conn, sentence_type, audio_datas, text, sentence_id), self.conn.loop, ) - future.result() + try: + future.result(timeout=30) + except concurrent.futures.TimeoutError: + logger.bind(tag=TAG).error( + "sendAudioMessage timed out after 30s — skipping frame" + ) # 记录输出和报告 if self.conn.max_output_size > 0 and text: From bdc5c6c0ca557c2428795d06190581bd902e5d47 Mon Sep 17 00:00:00 2001 From: Brad Shannon Date: Thu, 18 Jun 2026 11:37:21 -0400 Subject: [PATCH 2/2] test(core): regression guard for bounded future.result() timeouts --- .../test/test_future_timeout_guard.py | 102 ++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 main/xiaozhi-server/test/test_future_timeout_guard.py diff --git a/main/xiaozhi-server/test/test_future_timeout_guard.py b/main/xiaozhi-server/test/test_future_timeout_guard.py new file mode 100644 index 000000000..8ce51c5b3 --- /dev/null +++ b/main/xiaozhi-server/test/test_future_timeout_guard.py @@ -0,0 +1,102 @@ +"""Regression guard for bounded cross-thread ``future.result()`` calls. + +Two ``future.result()`` calls previously had no timeout, so a stalled dependency +(a hung memory backend in ``connection.py``; a stalled WebSocket send in the TTS +audio thread in ``tts/base.py``) blocked the thread indefinitely. The fix added a +timeout plus a ``TimeoutError`` handler at both sites. + +Those call sites live inside large methods / a queue-driven thread loop that can't +be exercised in isolation without a full runtime, so this is a structural guard: +it parses the source and asserts each file still contains a ``try`` block whose +body calls ``.result(timeout=...)`` and whose ``except`` handles a +``*TimeoutError``. It fails if a refactor drops the timeout or the handler. + +Self-contained: stdlib only, no conftest required. +""" + +import ast +import pathlib + +_SERVER_ROOT = pathlib.Path(__file__).resolve().parents[1] + + +def _handler_names(handler): + """Return the trailing identifier(s) of an except handler's exception type.""" + node = handler.type + names = [] + if isinstance(node, ast.Tuple): + candidates = node.elts + elif node is not None: + candidates = [node] + else: + candidates = [] + for cand in candidates: + if isinstance(cand, ast.Name): + names.append(cand.id) + elif isinstance(cand, ast.Attribute): + names.append(cand.attr) + return names + + +def _is_timed_result_call(node): + return ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr == "result" + and any(kw.arg == "timeout" for kw in node.keywords) + ) + + +def _assigns_name(stmt): + """Yield assignment target names for a simple ``name = ...`` statement.""" + if isinstance(stmt, ast.Assign): + for target in stmt.targets: + if isinstance(target, ast.Name): + yield target.id + + +def _try_body_has_timed_result(body, assign_target=None): + for stmt in body: + for node in ast.walk(stmt): + if not _is_timed_result_call(node): + continue + if assign_target is None: + return True + # Require the timed result to be assigned to the named variable so the + # guard targets a specific call site rather than any timed result call. + if assign_target in set(_assigns_name(stmt)): + return True + return False + + +def _guards_a_timed_result_call(source, assign_target=None): + tree = ast.parse(source) + for node in ast.walk(tree): + if not isinstance(node, ast.Try): + continue + if not _try_body_has_timed_result(node.body, assign_target): + continue + for handler in node.handlers: + if any(name.endswith("TimeoutError") for name in _handler_names(handler)): + return True + return False + + +def test_connection_memory_query_result_is_timeout_guarded(): + source = (_SERVER_ROOT / "core" / "connection.py").read_text(encoding="utf-8") + # Target the memory-query site specifically (assigns to ``memory_str``); the + # pre-existing tool-call timeout must not mask a regression here. + assert _guards_a_timed_result_call(source, assign_target="memory_str"), ( + "connection.py must assign memory_str = future.result(timeout=...) inside a " + "try/except that handles a TimeoutError" + ) + + +def test_tts_audio_send_result_is_timeout_guarded(): + source = (_SERVER_ROOT / "core" / "providers" / "tts" / "base.py").read_text( + encoding="utf-8" + ) + assert _guards_a_timed_result_call(source), ( + "tts/base.py must wrap a future.result(timeout=...) call in a try/except " + "that handles a TimeoutError" + )