From ef1d24e40d619e8255a046a0a990ea94826868c2 Mon Sep 17 00:00:00 2001 From: Yanhan Ruan <121672362+yanhanruan@users.noreply.github.com> Date: Mon, 12 Oct 2026 10:00:28 +0800 Subject: [PATCH 1/4] =?UTF-8?q?fix(server):=20=E4=BF=AE=E5=A4=8D=E4=B8=B4?= =?UTF-8?q?=E6=97=B6=E4=BA=8B=E4=BB=B6=E5=BE=AA=E7=8E=AF=E7=BB=93=E6=9D=9F?= =?UTF-8?q?=E5=90=8E=20HTTP=20=E5=AE=A2=E6=88=B7=E7=AB=AF=E6=9C=AA?= =?UTF-8?q?=E9=87=8A=E6=94=BE=E7=9A=84=E9=97=AE=E9=A2=98=20(#3416)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../config/manage_api_client.py | 104 +++++-------- .../reproduce_manage_api_client_retention.py | 62 ++++++++ .../tests/test_manage_api_client_lifecycle.py | 139 ++++++++++++++++++ 3 files changed, 235 insertions(+), 70 deletions(-) create mode 100644 main/xiaozhi-server/tests/reproduce_manage_api_client_retention.py create mode 100644 main/xiaozhi-server/tests/test_manage_api_client_lifecycle.py diff --git a/main/xiaozhi-server/config/manage_api_client.py b/main/xiaozhi-server/config/manage_api_client.py index d0512d03a..08a4b9938 100644 --- a/main/xiaozhi-server/config/manage_api_client.py +++ b/main/xiaozhi-server/config/manage_api_client.py @@ -22,7 +22,6 @@ class DeviceBindException(Exception): class ManageApiClient: _instance = None _instance_lock = threading.Lock() # 保护 _instance 与 _closed 的读写 - _async_clients = {} # 为每个事件循环存储独立的客户端 _secret = None _closed = False # safe_close() 后置为 True,关闭后不再创建新连接 @@ -52,72 +51,47 @@ class ManageApiClient: cls.max_retries = cls.config.get("max_retries", 6) # 最大重试次数 cls.retry_delay = cls.config.get("retry_delay", 10) # 初始重试延迟(秒) # 不在这里创建 AsyncClient,延迟到实际使用时创建 - cls._async_clients = {} cls._closed = False @classmethod async def _ensure_async_client(cls): - """确保异步客户端已创建(为每个事件循环创建独立的客户端)""" - import asyncio - - try: - loop = asyncio.get_running_loop() - loop_id = id(loop) - - # 检查关闭状态与创建连接池必须是同一个临界区,避免 safe_close() - # 清空连接池后又有请求将新客户端写回。 - with cls._instance_lock: - if cls._closed: - raise Exception("ManageApiClient已关闭,不再创建新的HTTP客户端") - - if loop_id not in cls._async_clients: - # 服务端可能主动关闭连接,httpx 连接池无法正确检测和清理 - limits = httpx.Limits( - max_keepalive_connections=0, # 禁用 keep-alive,每次都新建连接 - ) - cls._async_clients[loop_id] = httpx.AsyncClient( - base_url=cls.config.get("url"), - headers={ - "User-Agent": f"PythonClient/2.0 (PID:{os.getpid()})", - "Accept": "application/json", - "Authorization": "Bearer " + cls._secret, - }, - timeout=cls.config.get("timeout", 30), - limits=limits, # 使用限制 - trust_env=False, - ) - return cls._async_clients[loop_id] - except RuntimeError: - # 如果没有运行中的事件循环,创建一个临时的 - raise Exception("必须在异步上下文中调用") + """创建请求专用客户端,避免临时事件循环的客户端永久累积。""" + with cls._instance_lock: + if cls._closed: + raise Exception("ManageApiClient已关闭,不再创建新的HTTP客户端") + return httpx.AsyncClient( + base_url=cls.config.get("url"), + headers={ + "User-Agent": f"PythonClient/2.0 (PID:{os.getpid()})", + "Accept": "application/json", + "Authorization": "Bearer " + cls._secret, + }, + timeout=cls.config.get("timeout", 30), + limits=httpx.Limits(max_keepalive_connections=0), + trust_env=False, + ) @classmethod async def _async_request(cls, method: str, endpoint: str, **kwargs) -> Dict: - """发送单次异步HTTP请求并处理响应""" - # 确保客户端已创建 + """客户端由本次请求持有,并在创建它的事件循环中关闭。""" client = await cls._ensure_async_client() - endpoint = endpoint.lstrip("/") - response = None - try: - response = await client.request(method, endpoint, **kwargs) - response.raise_for_status() - - result = response.json() - - # 处理API返回的业务错误 - if result.get("code") == 10041: - raise DeviceNotFoundException(result.get("msg")) - elif result.get("code") == 10042: - raise DeviceBindException(result.get("msg")) - elif result.get("code") != 0: - raise Exception(f"API返回错误: {result.get('msg', '未知错误')}") - - # 返回成功数据 - return result.get("data") if result.get("code") == 0 else None - finally: - # 确保响应被关闭(即使异常也会执行) - if response is not None: - await response.aclose() + async with client: + endpoint = endpoint.lstrip("/") + response = None + try: + response = await client.request(method, endpoint, **kwargs) + response.raise_for_status() + result = response.json() + if result.get("code") == 10041: + raise DeviceNotFoundException(result.get("msg")) + elif result.get("code") == 10042: + raise DeviceBindException(result.get("msg")) + elif result.get("code") != 0: + raise Exception(f"API返回错误: {result.get('msg', '未知错误')}") + return result.get("data") if result.get("code") == 0 else None + finally: + if response is not None: + await response.aclose() @classmethod def _should_retry(cls, exception: Exception) -> bool: @@ -173,21 +147,11 @@ class ManageApiClient: @classmethod def safe_close(cls): - """安全关闭所有异步连接池""" - import asyncio - + """关闭请求入口;在途请求在各自事件循环中释放客户端。""" with cls._instance_lock: cls._closed = True - clients = list(cls._async_clients.values()) - cls._async_clients.clear() cls._instance = None - for client in clients: - try: - asyncio.run(client.aclose()) - except Exception: - pass - def api_guard(error_msg: str = None, raise_when_closed: bool = False): """装饰器:统一获取单例实例、判空与异常兜底 diff --git a/main/xiaozhi-server/tests/reproduce_manage_api_client_retention.py b/main/xiaozhi-server/tests/reproduce_manage_api_client_retention.py new file mode 100644 index 000000000..9c4f2a389 --- /dev/null +++ b/main/xiaozhi-server/tests/reproduce_manage_api_client_retention.py @@ -0,0 +1,62 @@ +"""Offline reproduction: no real devices, credentials, HTTP server or model APIs. + +Usage: python -B reproduce.py path/to/config/manage_api_client.py +Keeps CLOSED loop objects alive to avoid Python reusing their integer IDs. +This makes the cache-lifetime check deterministic; it is not an RSS benchmark. +""" +import asyncio +import gc +import importlib.util +import json +import sys +import weakref +from unittest.mock import patch + +import httpx + + +def main(): + spec = importlib.util.spec_from_file_location("client_under_test", sys.argv[1]) + api = importlib.util.module_from_spec(spec) + spec.loader.exec_module(api) + cls = api.ManageApiClient + cls({"manager-api": {"url": "http://offline.invalid/xiaozhi", + "secret": "synthetic-test", "max_retries": 0}}) + real_client = httpx.AsyncClient + refs, loops = [], [] + + def factory(**kwargs): + transport = httpx.MockTransport( + lambda request: httpx.Response(200, json={"code": 0, "data": True}) + ) + client = real_client(transport=transport, **kwargs) + refs.append(weakref.ref(client)) + return client + + try: + with patch.object(api.httpx, "AsyncClient", side_effect=factory): + for _ in range(100): + loop = asyncio.new_event_loop() + loops.append(loop) + try: + assert loop.run_until_complete( + cls._execute_async_request("POST", "/synthetic-report") + ) is True + finally: + loop.close() + gc.collect() + retained = [ref() for ref in refs if ref() is not None] + print(json.dumps({ + "requests_completed": 100, + "all_loops_closed": all(loop.is_closed() for loop in loops), + "cached_clients_after_gc": len(getattr(cls, "_async_clients", {})), + "live_clients_after_gc": len(retained), + "unclosed_clients_after_gc": sum(not client.is_closed for client in retained), + }, sort_keys=True)) + finally: + cls.safe_close() + loops.clear() + + +if __name__ == "__main__": + main() diff --git a/main/xiaozhi-server/tests/test_manage_api_client_lifecycle.py b/main/xiaozhi-server/tests/test_manage_api_client_lifecycle.py new file mode 100644 index 000000000..ed73e211f --- /dev/null +++ b/main/xiaozhi-server/tests/test_manage_api_client_lifecycle.py @@ -0,0 +1,139 @@ +"""Run directly with unittest; no application/model dependencies or network.""" +import asyncio +from concurrent.futures import ThreadPoolExecutor +import importlib.util +import os +from pathlib import Path +import unittest +from unittest.mock import patch + +import httpx + + +class ManageApiClientLifecycleTest(unittest.IsolatedAsyncioTestCase): + def setUp(self): + source = Path(os.environ.get('CLIENT_UNDER_TEST', str( + Path(__file__).resolve().parents[1] / 'config/manage_api_client.py'))) + spec = importlib.util.spec_from_file_location('_lifecycle_client', source) + self.api = importlib.util.module_from_spec(spec) + spec.loader.exec_module(self.api) + self.cls = self.api.ManageApiClient + self.cls({'manager-api': {'url': 'http://offline.invalid/xiaozhi', + 'secret': 'synthetic-test', 'max_retries': 1, 'retry_delay': 0}}) + self.clients = [] + self.requests = [] + self.real_client = httpx.AsyncClient + + def transport(self, handler): + def factory(**kwargs): + async def handle(request): + self.requests.append(request) + return await handler(request) + client = self.real_client(transport=httpx.MockTransport(handle), **kwargs) + self.clients.append(client) + return client + return patch.object(self.api.httpx, 'AsyncClient', side_effect=factory) + + async def asyncTearDown(self): + try: + self.assertTrue(all(c.is_closed for c in self.clients), 'client escaped its request') + finally: + for client in self.clients: + if not client.is_closed: + await client.aclose() + self.cls.safe_close() + + async def test_success_preserves_url_headers_and_payload(self): + async def handle(request): + self.assertEqual(str(request.url), 'http://offline.invalid/xiaozhi/report') + self.assertEqual(request.headers['authorization'], 'Bearer synthetic-test') + self.assertEqual(request.content, b'{"value":123}') + return httpx.Response(200, json={'code': 0, 'data': {'ok': True}}) + with self.transport(handle): + self.assertEqual(await self.cls._execute_async_request('POST', '/report', + json={'value': 123}), {'ok': True}) + + async def test_retry_closes_each_attempt(self): + async def handle(request): + if len(self.requests) == 1: + return httpx.Response(503) + self.assertTrue(self.clients[0].is_closed) + return httpx.Response(200, json={'code': 0, 'data': True}) + with self.transport(handle): + self.assertTrue(await self.cls._execute_async_request('POST', '/report')) + self.assertEqual(len(self.clients), 2) + + async def test_timeout_exhaustion_closes_all_attempts(self): + async def handle(request): + raise httpx.ReadTimeout('synthetic timeout', request=request) + with self.transport(handle), self.assertRaises(httpx.ReadTimeout): + await self.cls._execute_async_request('POST', '/report') + self.assertEqual(len(self.clients), 2) + + async def test_nonretryable_http_error(self): + async def handle(request): + return httpx.Response(403) + with self.transport(handle), self.assertRaises(httpx.HTTPStatusError): + await self.cls._execute_async_request('POST', '/report') + self.assertEqual(len(self.clients), 1) + + async def test_business_error_and_invalid_json_release_client(self): + for response, error in [ + (httpx.Response(200, json={'code': 10041, 'msg': 'missing'}), self.api.DeviceNotFoundException), + (httpx.Response(200, json={'code': 10042, 'msg': 'bind'}), self.api.DeviceBindException), + (httpx.Response(200, content=b'not-json'), ValueError), + ]: + async def handle(request): + return response + with self.transport(handle), self.assertRaises(error): + await self.cls._execute_async_request('POST', '/report') + self.assertTrue(self.clients[-1].is_closed) + self.assertEqual(len(self.clients), 3) + + async def test_cancellation_does_not_close_concurrent_request(self): + entered = [asyncio.Event(), asyncio.Event()] + release = asyncio.Event() + async def handle(request): + index = len(self.requests) - 1 + entered[index].set() + await release.wait() + return httpx.Response(200, json={'code': 0, 'data': True}) + with self.transport(handle): + first = asyncio.create_task(self.cls._execute_async_request('POST', '/first')) + await asyncio.wait_for(entered[0].wait(), 2) + second = asyncio.create_task(self.cls._execute_async_request('POST', '/second')) + await asyncio.wait_for(entered[1].wait(), 2) + first.cancel() + with self.assertRaises(asyncio.CancelledError): + await first + self.assertTrue(self.clients[0].is_closed) + self.assertFalse(self.clients[1].is_closed) + release.set() + self.assertTrue(await asyncio.wait_for(second, 2)) + + async def test_shutdown_allows_inflight_cleanup_and_blocks_report_entry(self): + async def handle(request): + self.cls.safe_close() + return httpx.Response(200, json={'code': 0, 'data': True}) + with self.transport(handle): + self.assertTrue(await self.api.report('device', 'session', 1, 'text', None, 0)) + self.assertIsNone(await self.api.report('device', 'session', 1, 'later', None, 0)) + if hasattr(self.cls, '_closed'): + with self.assertRaisesRegex(Exception, '已关闭'): + await self.cls._execute_async_request('POST', '/report') + self.assertEqual(len(self.clients), 1) + + async def test_many_temporary_loops_leave_no_open_clients(self): + async def handle(request): + return httpx.Response(200, json={'code': 0, 'data': True}) + def report_once(_): + return asyncio.run(self.cls._execute_async_request('POST', '/report')) + with self.transport(handle), ThreadPoolExecutor(max_workers=5) as pool: + results = list(pool.map(report_once, range(100))) + self.assertTrue(all(results)) + self.assertEqual(len(self.clients), 100) + self.assertTrue(all(c.is_closed for c in self.clients)) + + +if __name__ == '__main__': + unittest.main() From e5f326285e1e9ef3a47e5cff552503c8f89a5225 Mon Sep 17 00:00:00 2001 From: Sakura-RanChen <1908198662@qq.com> Date: Mon, 12 Oct 2026 15:42:51 +0800 Subject: [PATCH 2/4] =?UTF-8?q?update:=20=E4=BC=98=E5=8C=96client=20?= =?UTF-8?q?=E7=94=9F=E5=91=BD=E5=91=A8=E6=9C=9F=E5=AF=B9=E9=BD=90=E4=B8=9A?= =?UTF-8?q?=E5=8A=A1=E8=AF=B7=E6=B1=82=E2=80=94=E2=80=94=E9=87=8D=E8=AF=95?= =?UTF-8?q?=E5=86=85=E8=BF=9E=E6=8E=A5=E5=A4=8D=E7=94=A8=E3=80=81=E9=94=81?= =?UTF-8?q?=E5=A4=96=E6=9E=84=E9=80=A0=E3=80=81safe=5Fclose=20=E5=8F=AF?= =?UTF-8?q?=E6=89=93=E6=96=AD=E9=87=8D=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../config/manage_api_client.py | 187 ++++++++++++------ .../tests/test_manage_api_client_lifecycle.py | 45 ++++- 2 files changed, 168 insertions(+), 64 deletions(-) diff --git a/main/xiaozhi-server/config/manage_api_client.py b/main/xiaozhi-server/config/manage_api_client.py index 08a4b9938..772c2741b 100644 --- a/main/xiaozhi-server/config/manage_api_client.py +++ b/main/xiaozhi-server/config/manage_api_client.py @@ -1,11 +1,19 @@ import os +import ssl import base64 +import asyncio import functools import threading +import traceback from typing import Optional, Dict import httpx +# 跨请求共享的 SSLContext:httpx 默认每个 AsyncClient 都重新 +# create_default_context() 并加载系统 CA(100+ 证书,毫秒级 CPU)。 +# Context 构造后只读,跨 client / 线程共享安全。 +_SHARED_SSL_CONTEXT = ssl.create_default_context() + TAG = __name__ @@ -54,44 +62,71 @@ class ManageApiClient: cls._closed = False @classmethod - async def _ensure_async_client(cls): - """创建请求专用客户端,避免临时事件循环的客户端永久累积。""" + def _build_client(cls) -> httpx.AsyncClient: + """构造单次业务请求专用的 AsyncClient。 + + client 生命周期与"一次业务请求(含重试)"对齐:调用方用 + ``async with`` 在创建它的同一事件循环里关闭它。不存在任何 + 跨请求 / 跨 loop 缓存,临时 loop 守护线程场景同样安全, + 不会出现客户端随 loop 累积的问题。 + + 锁内只做关闭检查和配置快照,client 构造在锁外进行, + 避免并发请求在 ``threading.Lock`` 上串行阻塞事件循环线程。 + """ with cls._instance_lock: if cls._closed: raise Exception("ManageApiClient已关闭,不再创建新的HTTP客户端") - return httpx.AsyncClient( - base_url=cls.config.get("url"), - headers={ - "User-Agent": f"PythonClient/2.0 (PID:{os.getpid()})", - "Accept": "application/json", - "Authorization": "Bearer " + cls._secret, - }, - timeout=cls.config.get("timeout", 30), - limits=httpx.Limits(max_keepalive_connections=0), - trust_env=False, - ) + base_url = cls.config.get("url") + secret = cls._secret + timeout = cls.config.get("timeout", 30) + return httpx.AsyncClient( + base_url=base_url, + headers={ + "User-Agent": f"PythonClient/2.0 (PID:{os.getpid()})", + "Accept": "application/json", + "Authorization": "Bearer " + secret, + }, + timeout=timeout, + # 连接复用限于单次业务请求内部:重试(含 retry_delay 级 + # sleep)期间 keep-alive 连接保持在池中,下一次尝试直接 + # 复用,仅在连接真坏掉时才重新握手。keepalive_expiry 需 + # 覆盖 retry_delay,否则 sleep 期间连接已被池判定过期, + # 复用落空(退化为每次尝试重新握手,行为仍正确)。 + # 请求结束 async with 必关 client,连接不会跨请求驻留。 + limits=httpx.Limits( + max_keepalive_connections=1, + keepalive_expiry=30, + ), + trust_env=False, + verify=_SHARED_SSL_CONTEXT, + ) @classmethod - async def _async_request(cls, method: str, endpoint: str, **kwargs) -> Dict: - """客户端由本次请求持有,并在创建它的事件循环中关闭。""" - client = await cls._ensure_async_client() - async with client: - endpoint = endpoint.lstrip("/") - response = None - try: - response = await client.request(method, endpoint, **kwargs) - response.raise_for_status() - result = response.json() - if result.get("code") == 10041: - raise DeviceNotFoundException(result.get("msg")) - elif result.get("code") == 10042: - raise DeviceBindException(result.get("msg")) - elif result.get("code") != 0: - raise Exception(f"API返回错误: {result.get('msg', '未知错误')}") - return result.get("data") if result.get("code") == 0 else None - finally: - if response is not None: + async def _async_request( + cls, client: httpx.AsyncClient, method: str, endpoint: str, **kwargs + ) -> Dict: + """在给定 client 上执行单次请求;响应读取后立即释放回连接池。""" + endpoint = endpoint.lstrip("/") + response = None + try: + response = await client.request(method, endpoint, **kwargs) + response.raise_for_status() + result = response.json() + if result.get("code") == 10041: + raise DeviceNotFoundException(result.get("msg")) + elif result.get("code") == 10042: + raise DeviceBindException(result.get("msg")) + elif result.get("code") != 0: + raise Exception(f"API返回错误: {result.get('msg', '未知错误')}") + return result.get("data") if result.get("code") == 0 else None + finally: + if response is not None: + try: await response.aclose() + except Exception: + # 吞掉释放异常:否则它会覆盖原始业务异常, + # 破坏 _execute_async_request 的重试判断 + pass @classmethod def _should_retry(cls, exception: Exception) -> bool: @@ -102,6 +137,12 @@ class ManageApiClient: ): return True + # 请求间启用了池内 keep-alive 复用:服务端 / 负载均衡可能在 + # keepalive 窗口内提前回收连接,复用时表现为对端断开, + # 重新握手重试即可。 + if isinstance(exception, httpx.RemoteProtocolError): + return True + # HTTP状态码错误 if isinstance(exception, httpx.HTTPStatusError): status_code = exception.response.status_code @@ -110,31 +151,59 @@ class ManageApiClient: return False @classmethod - async def _execute_async_request(cls, method: str, endpoint: str, **kwargs) -> Dict: - """带重试机制的异步请求执行器""" - import asyncio + async def _retry_wait(cls): + """可被 safe_close() 打断的重试等待。 - retry_count = 0 - - while retry_count <= cls.max_retries: - try: - # 执行异步请求 - return await cls._async_request(method, endpoint, **kwargs) - except Exception as e: - # 判断是否应该重试 - if retry_count < cls.max_retries and cls._should_retry(e): - retry_count += 1 - print( - f"{method} {endpoint} 异步请求失败,将在 {cls.retry_delay:.1f} 秒后进行第 {retry_count} 次重试" - ) - await asyncio.sleep(cls.retry_delay) - continue - else: - # 不重试,直接抛出异常 - raise + 以 100ms 分片轮询 _closed:服务关闭后立即返回,由调用方 + 跳过剩余重试。不分片一次睡满 retry_delay 的话,container + SIGTERM 场景下在途请求要拖满 max_retries × retry_delay + (默认 60s)才收尾,会吃光进程退出宽限期。 + """ + remaining = cls.retry_delay + while remaining > 0 and not cls._closed: + step = min(0.1, remaining) + await asyncio.sleep(step) + remaining -= step @classmethod - def _get_instance(cls): + async def _execute_async_request(cls, method: str, endpoint: str, **kwargs) -> Dict: + """带重试机制的业务请求执行器。 + + client 只构造一次,整个重试过程复用(重试间隔期间连接 + keep-alive 在池内保持),重试结束(成功或放弃)后由 + ``async with`` 关闭 client 并释放连接。 + + safe_close() 不取消已开始的尝试(由它跑完当前这一次), + 但会打断重试等待:之后不再发起新尝试,请求以最后一次 + 失败原因收尾。 + """ + client = cls._build_client() + async with client: + retry_count = 0 + + while retry_count <= cls.max_retries: + try: + # 执行异步请求 + return await cls._async_request(client, method, endpoint, **kwargs) + except Exception as e: + # 判断是否应该重试 + if retry_count < cls.max_retries and cls._should_retry(e): + retry_count += 1 + print( + f"{method} {endpoint} 异步请求失败,将在 {cls.retry_delay:.1f} 秒后进行第 {retry_count} 次重试" + ) + await cls._retry_wait() + if cls._closed: + # safe_close 打断了重试等待:不发起新尝试, + # 以本次失败原因收尾(已开始的尝试未被取消) + raise + continue + else: + # 不重试,直接抛出异常 + raise + + @classmethod + def _get_instance(cls) -> Optional["ManageApiClient"]: """线程安全地获取单例实例引用 调用方应使用返回的局部引用,而不是判空后再次读取 @@ -147,7 +216,11 @@ class ManageApiClient: @classmethod def safe_close(cls): - """关闭请求入口;在途请求在各自事件循环中释放客户端。""" + """关闭请求入口;在途请求在各自事件循环中释放客户端。 + + 已开始的请求不会被取消,但重试等待会被打断(加速收尾), + 详见 _execute_async_request / _retry_wait。 + """ with cls._instance_lock: cls._closed = True cls._instance = None @@ -177,7 +250,9 @@ def api_guard(error_msg: str = None, raise_when_closed: bool = False): try: return await func(instance, *args, **kwargs) except Exception as e: - print(f"{error_msg}: {e}") + # format_exc 拼进同一条 print:保持模块统一走 stdout, + # 且保留完整堆栈便于生产定位 + print(f"{error_msg}: {e}\n{traceback.format_exc()}") return None return wrapper diff --git a/main/xiaozhi-server/tests/test_manage_api_client_lifecycle.py b/main/xiaozhi-server/tests/test_manage_api_client_lifecycle.py index ed73e211f..d98e9e185 100644 --- a/main/xiaozhi-server/tests/test_manage_api_client_lifecycle.py +++ b/main/xiaozhi-server/tests/test_manage_api_client_lifecycle.py @@ -53,22 +53,28 @@ class ManageApiClientLifecycleTest(unittest.IsolatedAsyncioTestCase): self.assertEqual(await self.cls._execute_async_request('POST', '/report', json={'value': 123}), {'ok': True}) - async def test_retry_closes_each_attempt(self): + async def test_retry_reuses_client_until_request_ends(self): + """重试在同一个 client(池内同一 keep-alive 连接)上进行, + 整个业务请求结束后才关闭——client 生命周期与业务请求对齐, + 而不是与单次尝试对齐。""" async def handle(request): if len(self.requests) == 1: return httpx.Response(503) - self.assertTrue(self.clients[0].is_closed) + # 第二次尝试时第一个 client 仍在服务(未被提前关闭) + self.assertFalse(self.clients[0].is_closed) return httpx.Response(200, json={'code': 0, 'data': True}) with self.transport(handle): self.assertTrue(await self.cls._execute_async_request('POST', '/report')) - self.assertEqual(len(self.clients), 2) + self.assertEqual(len(self.clients), 1) + self.assertTrue(self.clients[0].is_closed) - async def test_timeout_exhaustion_closes_all_attempts(self): + async def test_timeout_exhaustion_reuses_client_until_request_ends(self): async def handle(request): raise httpx.ReadTimeout('synthetic timeout', request=request) with self.transport(handle), self.assertRaises(httpx.ReadTimeout): await self.cls._execute_async_request('POST', '/report') - self.assertEqual(len(self.clients), 2) + self.assertEqual(len(self.clients), 1) + self.assertTrue(self.clients[0].is_closed) async def test_nonretryable_http_error(self): async def handle(request): @@ -118,11 +124,34 @@ class ManageApiClientLifecycleTest(unittest.IsolatedAsyncioTestCase): with self.transport(handle): self.assertTrue(await self.api.report('device', 'session', 1, 'text', None, 0)) self.assertIsNone(await self.api.report('device', 'session', 1, 'later', None, 0)) - if hasattr(self.cls, '_closed'): - with self.assertRaisesRegex(Exception, '已关闭'): - await self.cls._execute_async_request('POST', '/report') + with self.assertRaisesRegex(Exception, '已关闭'): + await self.cls._execute_async_request('POST', '/report') self.assertEqual(len(self.clients), 1) + async def test_safe_close_interrupts_retry_backoff(self): + """safe_close 打断重试等待:已开始的尝试跑完,但不发起新尝试。 + + 防回归:重试间隔若一次睡满 retry_delay,container SIGTERM + 场景在途请求会拖满 max_retries × retry_delay 才收尾。 + """ + async def handle(request): + return httpx.Response(503) + original_delay = self.cls.retry_delay + self.cls.retry_delay = 5.0 # setUp 默认 0,观察不到打断 + try: + with self.transport(handle): + task = asyncio.create_task( + self.cls._execute_async_request('POST', '/report')) + await asyncio.sleep(0.2) # 进入重试等待 + self.cls.safe_close() + with self.assertRaises(httpx.HTTPStatusError): + await task + # 只有第一次尝试:重试等待被打断,未发起新尝试 + self.assertEqual(len(self.clients), 1) + self.assertEqual(len(self.requests), 1) + finally: + self.cls.retry_delay = original_delay + async def test_many_temporary_loops_leave_no_open_clients(self): async def handle(request): return httpx.Response(200, json={'code': 0, 'data': True}) From b8f23ffa66f35c463315bb41141cb6f9a35be499 Mon Sep 17 00:00:00 2001 From: Sakura-RanChen <1908198662@qq.com> Date: Tue, 13 Oct 2026 10:40:47 +0800 Subject: [PATCH 3/4] =?UTF-8?q?=E8=B0=83=E6=95=B4=E7=9B=B8=E5=85=B3?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../config/manage_api_client.py | 92 +++++++++---------- .../reproduce_manage_api_client_retention.py | 7 +- .../tests/test_manage_api_client_lifecycle.py | 33 ++++++- 3 files changed, 80 insertions(+), 52 deletions(-) diff --git a/main/xiaozhi-server/config/manage_api_client.py b/main/xiaozhi-server/config/manage_api_client.py index 772c2741b..3fd2d5bc1 100644 --- a/main/xiaozhi-server/config/manage_api_client.py +++ b/main/xiaozhi-server/config/manage_api_client.py @@ -1,5 +1,4 @@ import os -import ssl import base64 import asyncio import functools @@ -9,13 +8,11 @@ from typing import Optional, Dict import httpx -# 跨请求共享的 SSLContext:httpx 默认每个 AsyncClient 都重新 -# create_default_context() 并加载系统 CA(100+ 证书,毫秒级 CPU)。 -# Context 构造后只读,跨 client / 线程共享安全。 -_SHARED_SSL_CONTEXT = ssl.create_default_context() - TAG = __name__ +# _retry_wait 的分片粒度:safe_close 后 ~100ms 内收尾,轮询开销可忽略 +_RETRY_WAIT_SLICE = 0.1 + class DeviceNotFoundException(Exception): pass @@ -65,13 +62,10 @@ class ManageApiClient: def _build_client(cls) -> httpx.AsyncClient: """构造单次业务请求专用的 AsyncClient。 - client 生命周期与"一次业务请求(含重试)"对齐:调用方用 - ``async with`` 在创建它的同一事件循环里关闭它。不存在任何 - 跨请求 / 跨 loop 缓存,临时 loop 守护线程场景同样安全, - 不会出现客户端随 loop 累积的问题。 - - 锁内只做关闭检查和配置快照,client 构造在锁外进行, - 避免并发请求在 ``threading.Lock`` 上串行阻塞事件循环线程。 + 约束:client 生命周期与单次业务请求(含重试)对齐,由调用方 + ``async with`` 在同一事件循环内关闭,禁止跨请求 / 跨 loop + 缓存。锁内只做关闭检查与配置快照,构造在锁外执行,避免并发 + 请求在 threading.Lock 上串行阻塞事件循环。 """ with cls._instance_lock: if cls._closed: @@ -87,18 +81,18 @@ class ManageApiClient: "Authorization": "Bearer " + secret, }, timeout=timeout, - # 连接复用限于单次业务请求内部:重试(含 retry_delay 级 - # sleep)期间 keep-alive 连接保持在池中,下一次尝试直接 - # 复用,仅在连接真坏掉时才重新握手。keepalive_expiry 需 - # 覆盖 retry_delay,否则 sleep 期间连接已被池判定过期, - # 复用落空(退化为每次尝试重新握手,行为仍正确)。 - # 请求结束 async with 必关 client,连接不会跨请求驻留。 + # 约束:连接复用仅限单次业务请求内部,请求结束必关 client; + # keepalive_expiry 动态覆盖 retry_delay,保证重试等待期间 + # 池内连接不过期;连接真坏掉由 RemoteProtocolError 重试兜底。 limits=httpx.Limits( max_keepalive_connections=1, - keepalive_expiry=30, + keepalive_expiry=max(30, cls.retry_delay + 5), ), trust_env=False, - verify=_SHARED_SSL_CONTEXT, + # 约束:不共享 SSLContext——httpcore 建连会原地改写传入的 + # context(OpenSSL 侧无锁),共享单例并发握手有竞态;走 + # httpx 默认路径按 client 现建(certifi 信任库)。 + verify=True, ) @classmethod @@ -118,14 +112,13 @@ class ManageApiClient: raise DeviceBindException(result.get("msg")) elif result.get("code") != 0: raise Exception(f"API返回错误: {result.get('msg', '未知错误')}") - return result.get("data") if result.get("code") == 0 else None + return result.get("data") finally: if response is not None: try: await response.aclose() except Exception: - # 吞掉释放异常:否则它会覆盖原始业务异常, - # 破坏 _execute_async_request 的重试判断 + # 约束:必须吞掉释放异常,避免覆盖业务异常、破坏重试判断 pass @classmethod @@ -137,11 +130,13 @@ class ManageApiClient: ): return True - # 请求间启用了池内 keep-alive 复用:服务端 / 负载均衡可能在 - # keepalive 窗口内提前回收连接,复用时表现为对端断开, - # 重新握手重试即可。 + # 约束:RemoteProtocolError 仅在"未收到响应"(without sending + # a response)时重试——响应从未开始,重试安全;响应截断 + # (incomplete message body)变体意味着服务端可能已处理请求, + # 重试非幂等 POST 会重复提交。文案依赖 httpcore,变更时退化 + # 为不重试(安全方向)。 if isinstance(exception, httpx.RemoteProtocolError): - return True + return "without sending a response" in str(exception) # HTTP状态码错误 if isinstance(exception, httpx.HTTPStatusError): @@ -152,16 +147,14 @@ class ManageApiClient: @classmethod async def _retry_wait(cls): - """可被 safe_close() 打断的重试等待。 + """可被 safe_close() 打断的重试等待:100ms 分片轮询 _closed。 - 以 100ms 分片轮询 _closed:服务关闭后立即返回,由调用方 - 跳过剩余重试。不分片一次睡满 retry_delay 的话,container - SIGTERM 场景下在途请求要拖满 max_retries × retry_delay - (默认 60s)才收尾,会吃光进程退出宽限期。 + 约束:不得一次睡满 retry_delay——否则服务关闭后在途请求要 + 拖满 max_retries × retry_delay 才收尾,超出进程退出宽限期。 """ remaining = cls.retry_delay while remaining > 0 and not cls._closed: - step = min(0.1, remaining) + step = min(_RETRY_WAIT_SLICE, remaining) await asyncio.sleep(step) remaining -= step @@ -169,13 +162,10 @@ class ManageApiClient: async def _execute_async_request(cls, method: str, endpoint: str, **kwargs) -> Dict: """带重试机制的业务请求执行器。 - client 只构造一次,整个重试过程复用(重试间隔期间连接 - keep-alive 在池内保持),重试结束(成功或放弃)后由 - ``async with`` 关闭 client 并释放连接。 - - safe_close() 不取消已开始的尝试(由它跑完当前这一次), - 但会打断重试等待:之后不再发起新尝试,请求以最后一次 - 失败原因收尾。 + 约束:client 整个重试过程只构造一次,重试结束(成功或放弃) + 后由 ``async with`` 关闭并释放连接。safe_close() 不取消已开始 + 的尝试,但会打断重试等待:不再发起新尝试,以最后一次失败 + 原因收尾。 """ client = cls._build_client() async with client: @@ -204,12 +194,11 @@ class ManageApiClient: @classmethod def _get_instance(cls) -> Optional["ManageApiClient"]: - """线程安全地获取单例实例引用 + """线程安全地获取单例实例引用。 - 调用方应使用返回的局部引用,而不是判空后再次读取 - ManageApiClient._instance:即使随后 safe_close() 将 _instance - 置为 None,已获取的引用仍指向原对象,从而消除"判空之后、 - 使用之前实例被置空"的 TOCTOU 竞态窗口。 + 约束:调用方必须持有并使用返回的局部引用,禁止判空后再次 + 读取 ManageApiClient._instance——safe_close() 可能在判空之后 + 将其置 None(TOCTOU 竞态窗口)。 """ with cls._instance_lock: return cls._instance @@ -218,7 +207,7 @@ class ManageApiClient: def safe_close(cls): """关闭请求入口;在途请求在各自事件循环中释放客户端。 - 已开始的请求不会被取消,但重试等待会被打断(加速收尾), + 已开始的请求不取消;重试等待被打断、跳过剩余重试, 详见 _execute_async_request / _retry_wait。 """ with cls._instance_lock: @@ -250,9 +239,12 @@ def api_guard(error_msg: str = None, raise_when_closed: bool = False): try: return await func(instance, *args, **kwargs) except Exception as e: - # format_exc 拼进同一条 print:保持模块统一走 stdout, - # 且保留完整堆栈便于生产定位 - print(f"{error_msg}: {e}\n{traceback.format_exc()}") + # 约束:httpx / 解析异常打全堆栈;业务语义异常只打 + # message(消息自带上下文,堆栈是高频噪声) + if isinstance(e, (httpx.HTTPError, ValueError)): + print(f"{error_msg}: {e}\n{traceback.format_exc()}") + else: + print(f"{error_msg}: {e}") return None return wrapper diff --git a/main/xiaozhi-server/tests/reproduce_manage_api_client_retention.py b/main/xiaozhi-server/tests/reproduce_manage_api_client_retention.py index 9c4f2a389..3af2a4dd9 100644 --- a/main/xiaozhi-server/tests/reproduce_manage_api_client_retention.py +++ b/main/xiaozhi-server/tests/reproduce_manage_api_client_retention.py @@ -1,9 +1,14 @@ """Offline reproduction: no real devices, credentials, HTTP server or model APIs. -Usage: python -B reproduce.py path/to/config/manage_api_client.py +Usage: python -B tests/reproduce_manage_api_client_retention.py path/to/config/manage_api_client.py Keeps CLOSED loop objects alive to avoid Python reusing their integer IDs. This makes the cache-lifetime check deterministic; it is not an RSS benchmark. + +依赖真实 httpx.AsyncClient + MockTransport,不进 pytest 套件 +(tests/conftest.py 的 mock 层会全局替换 AsyncClient)。 """ +__test__ = False + import asyncio import gc import importlib.util diff --git a/main/xiaozhi-server/tests/test_manage_api_client_lifecycle.py b/main/xiaozhi-server/tests/test_manage_api_client_lifecycle.py index d98e9e185..ff0ebdd89 100644 --- a/main/xiaozhi-server/tests/test_manage_api_client_lifecycle.py +++ b/main/xiaozhi-server/tests/test_manage_api_client_lifecycle.py @@ -1,4 +1,12 @@ -"""Run directly with unittest; no application/model dependencies or network.""" +"""ManageApiClient 生命周期回归测试:直接以 unittest 运行,不依赖应用/模型与网络。 + +不进 pytest 套件:tests/conftest.py 的 mock 层(import 时全局替换 +asyncio.sleep 与 httpx.AsyncClient)与本文件的时序断言、MockTransport +注入互相破坏;__test__ = False 使 pytest 跳过收集,请直接用 unittest 运行。 +Usage: python -B tests/test_manage_api_client_lifecycle.py -v +""" +__test__ = False + import asyncio from concurrent.futures import ThreadPoolExecutor import importlib.util @@ -76,6 +84,29 @@ class ManageApiClientLifecycleTest(unittest.IsolatedAsyncioTestCase): self.assertEqual(len(self.clients), 1) self.assertTrue(self.clients[0].is_closed) + async def test_remote_protocol_error_without_response_triggers_retry(self): + """stale keep-alive 场景:响应从未开始,重试安全。""" + async def handle(request): + if len(self.requests) == 1: + raise httpx.RemoteProtocolError( + 'Server disconnected without sending a response.', + request=request) + return httpx.Response(200, json={'code': 0, 'data': True}) + with self.transport(handle): + self.assertTrue(await self.cls._execute_async_request('POST', '/report')) + self.assertEqual(len(self.requests), 2) + + async def test_remote_protocol_error_incomplete_body_not_retried(self): + """响应中途截断:服务端很可能已处理完请求,重试非幂等 POST + 会重复提交,必须直接失败。""" + async def handle(request): + raise httpx.RemoteProtocolError( + 'Peer closed connection without sending complete message body ' + '(discarded 10 of 100 read bytes)', request=request) + with self.transport(handle), self.assertRaises(httpx.RemoteProtocolError): + await self.cls._execute_async_request('POST', '/report') + self.assertEqual(len(self.requests), 1) + async def test_nonretryable_http_error(self): async def handle(request): return httpx.Response(403) From 2057b99aeb380f7a3720353553c115f225386bf2 Mon Sep 17 00:00:00 2001 From: Sakura-RanChen <1908198662@qq.com> Date: Tue, 13 Oct 2026 14:31:21 +0800 Subject: [PATCH 4/4] =?UTF-8?q?=E8=BF=81=E7=A7=BB=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E7=94=A8=E4=BE=8B=EF=BC=8C=E4=BC=98=E5=8C=96=E7=9B=B8=E5=85=B3?= =?UTF-8?q?=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../config/manage_api_client.py | 52 ++++++-------- .../reproduce_manage_api_client_retention.py | 67 ------------------- .../tests/test_manage_api_client_lifecycle.py | 18 +++-- 3 files changed, 33 insertions(+), 104 deletions(-) delete mode 100644 main/xiaozhi-server/tests/reproduce_manage_api_client_retention.py diff --git a/main/xiaozhi-server/config/manage_api_client.py b/main/xiaozhi-server/config/manage_api_client.py index 3fd2d5bc1..1cdee642c 100644 --- a/main/xiaozhi-server/config/manage_api_client.py +++ b/main/xiaozhi-server/config/manage_api_client.py @@ -24,6 +24,10 @@ class DeviceBindException(Exception): super().__init__(f"设备绑定异常,绑定码: {bind_code}") +class ManageApiShutdownError(Exception): + """safe_close 打断重试等待后的收尾异常,__cause__ 保留最后一次失败原因。""" + + class ManageApiClient: _instance = None _instance_lock = threading.Lock() # 保护 _instance 与 _closed 的读写 @@ -60,12 +64,9 @@ class ManageApiClient: @classmethod def _build_client(cls) -> httpx.AsyncClient: - """构造单次业务请求专用的 AsyncClient。 + """构造单次业务请求(含重试)专用的 AsyncClient。 - 约束:client 生命周期与单次业务请求(含重试)对齐,由调用方 - ``async with`` 在同一事件循环内关闭,禁止跨请求 / 跨 loop - 缓存。锁内只做关闭检查与配置快照,构造在锁外执行,避免并发 - 请求在 threading.Lock 上串行阻塞事件循环。 + 约束:由调用方 ``async with`` 在同一 loop 内关闭,禁止跨请求缓存;构造在锁外执行,避免并发请求阻塞事件循环。 """ with cls._instance_lock: if cls._closed: @@ -81,17 +82,15 @@ class ManageApiClient: "Authorization": "Bearer " + secret, }, timeout=timeout, - # 约束:连接复用仅限单次业务请求内部,请求结束必关 client; - # keepalive_expiry 动态覆盖 retry_delay,保证重试等待期间 - # 池内连接不过期;连接真坏掉由 RemoteProtocolError 重试兜底。 + # 连接复用仅限本次请求;keepalive_expiry 动态覆盖 retry_delay, + # 防止重试等待期间池内连接过期。 limits=httpx.Limits( max_keepalive_connections=1, keepalive_expiry=max(30, cls.retry_delay + 5), ), trust_env=False, - # 约束:不共享 SSLContext——httpcore 建连会原地改写传入的 - # context(OpenSSL 侧无锁),共享单例并发握手有竞态;走 - # httpx 默认路径按 client 现建(certifi 信任库)。 + # verify=True 现建 context:httpcore 建连会原地改写传入 + # context(无锁),共享单例并发握手有竞态。 verify=True, ) @@ -130,11 +129,8 @@ class ManageApiClient: ): return True - # 约束:RemoteProtocolError 仅在"未收到响应"(without sending - # a response)时重试——响应从未开始,重试安全;响应截断 - # (incomplete message body)变体意味着服务端可能已处理请求, - # 重试非幂等 POST 会重复提交。文案依赖 httpcore,变更时退化 - # 为不重试(安全方向)。 + # RPE 仅"without sending a response"(响应未开始,安全)变体重试; + # 截断变体可能已处理请求会重复提交,文案变更时退化为不重试。 if isinstance(exception, httpx.RemoteProtocolError): return "without sending a response" in str(exception) @@ -147,10 +143,9 @@ class ManageApiClient: @classmethod async def _retry_wait(cls): - """可被 safe_close() 打断的重试等待:100ms 分片轮询 _closed。 + """可被 safe_close() 打断的重试等待(100ms 分片轮询 _closed)。 - 约束:不得一次睡满 retry_delay——否则服务关闭后在途请求要 - 拖满 max_retries × retry_delay 才收尾,超出进程退出宽限期。 + 约束:不得一次睡满 retry_delay,否则关闭后收尾要拖满整个重试周期。 """ remaining = cls.retry_delay while remaining > 0 and not cls._closed: @@ -162,10 +157,7 @@ class ManageApiClient: async def _execute_async_request(cls, method: str, endpoint: str, **kwargs) -> Dict: """带重试机制的业务请求执行器。 - 约束:client 整个重试过程只构造一次,重试结束(成功或放弃) - 后由 ``async with`` 关闭并释放连接。safe_close() 不取消已开始 - 的尝试,但会打断重试等待:不再发起新尝试,以最后一次失败 - 原因收尾。 + 约束:client 整个重试过程只构造一次,结束后由 ``async with`` 关闭;safe_close 不取消已开始的尝试,只打断重试等待(抛 ManageApiShutdownError)。 """ client = cls._build_client() async with client: @@ -184,9 +176,10 @@ class ManageApiClient: ) await cls._retry_wait() if cls._closed: - # safe_close 打断了重试等待:不发起新尝试, - # 以本次失败原因收尾(已开始的尝试未被取消) - raise + # 收尾必须可区分:裸 raise 会把 shutdown 早退伪装 + # 成网络抖动,掩盖服务下线信号 + raise ManageApiShutdownError( + f"safe_close 已打断重试等待: {e}") from e continue else: # 不重试,直接抛出异常 @@ -196,9 +189,7 @@ class ManageApiClient: def _get_instance(cls) -> Optional["ManageApiClient"]: """线程安全地获取单例实例引用。 - 约束:调用方必须持有并使用返回的局部引用,禁止判空后再次 - 读取 ManageApiClient._instance——safe_close() 可能在判空之后 - 将其置 None(TOCTOU 竞态窗口)。 + 约束:调用方必须持有返回的局部引用,禁止判空后重读 _instance(TOCTOU 窗口)。 """ with cls._instance_lock: return cls._instance @@ -207,8 +198,7 @@ class ManageApiClient: def safe_close(cls): """关闭请求入口;在途请求在各自事件循环中释放客户端。 - 已开始的请求不取消;重试等待被打断、跳过剩余重试, - 详见 _execute_async_request / _retry_wait。 + 已开始的请求不取消;重试等待被打断、跳过剩余重试(见 _retry_wait)。 """ with cls._instance_lock: cls._closed = True diff --git a/main/xiaozhi-server/tests/reproduce_manage_api_client_retention.py b/main/xiaozhi-server/tests/reproduce_manage_api_client_retention.py deleted file mode 100644 index 3af2a4dd9..000000000 --- a/main/xiaozhi-server/tests/reproduce_manage_api_client_retention.py +++ /dev/null @@ -1,67 +0,0 @@ -"""Offline reproduction: no real devices, credentials, HTTP server or model APIs. - -Usage: python -B tests/reproduce_manage_api_client_retention.py path/to/config/manage_api_client.py -Keeps CLOSED loop objects alive to avoid Python reusing their integer IDs. -This makes the cache-lifetime check deterministic; it is not an RSS benchmark. - -依赖真实 httpx.AsyncClient + MockTransport,不进 pytest 套件 -(tests/conftest.py 的 mock 层会全局替换 AsyncClient)。 -""" -__test__ = False - -import asyncio -import gc -import importlib.util -import json -import sys -import weakref -from unittest.mock import patch - -import httpx - - -def main(): - spec = importlib.util.spec_from_file_location("client_under_test", sys.argv[1]) - api = importlib.util.module_from_spec(spec) - spec.loader.exec_module(api) - cls = api.ManageApiClient - cls({"manager-api": {"url": "http://offline.invalid/xiaozhi", - "secret": "synthetic-test", "max_retries": 0}}) - real_client = httpx.AsyncClient - refs, loops = [], [] - - def factory(**kwargs): - transport = httpx.MockTransport( - lambda request: httpx.Response(200, json={"code": 0, "data": True}) - ) - client = real_client(transport=transport, **kwargs) - refs.append(weakref.ref(client)) - return client - - try: - with patch.object(api.httpx, "AsyncClient", side_effect=factory): - for _ in range(100): - loop = asyncio.new_event_loop() - loops.append(loop) - try: - assert loop.run_until_complete( - cls._execute_async_request("POST", "/synthetic-report") - ) is True - finally: - loop.close() - gc.collect() - retained = [ref() for ref in refs if ref() is not None] - print(json.dumps({ - "requests_completed": 100, - "all_loops_closed": all(loop.is_closed() for loop in loops), - "cached_clients_after_gc": len(getattr(cls, "_async_clients", {})), - "live_clients_after_gc": len(retained), - "unclosed_clients_after_gc": sum(not client.is_closed for client in retained), - }, sort_keys=True)) - finally: - cls.safe_close() - loops.clear() - - -if __name__ == "__main__": - main() diff --git a/main/xiaozhi-server/tests/test_manage_api_client_lifecycle.py b/main/xiaozhi-server/tests/test_manage_api_client_lifecycle.py index ff0ebdd89..36769396e 100644 --- a/main/xiaozhi-server/tests/test_manage_api_client_lifecycle.py +++ b/main/xiaozhi-server/tests/test_manage_api_client_lifecycle.py @@ -9,11 +9,13 @@ __test__ = False import asyncio from concurrent.futures import ThreadPoolExecutor +import gc import importlib.util import os from pathlib import Path import unittest from unittest.mock import patch +import weakref import httpx @@ -160,11 +162,8 @@ class ManageApiClientLifecycleTest(unittest.IsolatedAsyncioTestCase): self.assertEqual(len(self.clients), 1) async def test_safe_close_interrupts_retry_backoff(self): - """safe_close 打断重试等待:已开始的尝试跑完,但不发起新尝试。 - - 防回归:重试间隔若一次睡满 retry_delay,container SIGTERM - 场景在途请求会拖满 max_retries × retry_delay 才收尾。 - """ + """safe_close 打断重试等待:已开始的尝试跑完,不发起新尝试, + 以 ManageApiShutdownError 收尾(与重试耗尽的网络异常可区分)。""" async def handle(request): return httpx.Response(503) original_delay = self.cls.retry_delay @@ -175,8 +174,9 @@ class ManageApiClientLifecycleTest(unittest.IsolatedAsyncioTestCase): self.cls._execute_async_request('POST', '/report')) await asyncio.sleep(0.2) # 进入重试等待 self.cls.safe_close() - with self.assertRaises(httpx.HTTPStatusError): + with self.assertRaises(self.api.ManageApiShutdownError) as ctx: await task + self.assertIsInstance(ctx.exception.__cause__, httpx.HTTPStatusError) # 只有第一次尝试:重试等待被打断,未发起新尝试 self.assertEqual(len(self.clients), 1) self.assertEqual(len(self.requests), 1) @@ -193,6 +193,12 @@ class ManageApiClientLifecycleTest(unittest.IsolatedAsyncioTestCase): self.assertTrue(all(results)) self.assertEqual(len(self.clients), 100) self.assertTrue(all(c.is_closed for c in self.clients)) + # 缓存回归网:释放测试持有的强引用后 client 必须可被 GC 回收, + # 任何类级缓存(id(loop) dict / WeakKeyDictionary)重引入都会让存活数 > 0 + refs = [weakref.ref(c) for c in self.clients] + self.clients.clear() + gc.collect() + self.assertEqual(sum(ref() is not None for ref in refs), 0) if __name__ == '__main__':