JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat(debug): add SIGUSR1 async-state dump to service entrypoints
alan_chenge0927e00017d
diff --git a/jiuwenswarm/app.py b/jiuwenswarm/app.pyindex f42025665c..44c093524b 100644--- a/jiuwenswarm/app.py+++ b/jiuwenswarm/app.py@@ -1,4 +1,4 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved."""Orchestrate AgentServer + Gateway in two processes (split layout, one command).Runs ``jiuwenswarm.server.app_agentserver`` then ``jiuwenswarm.gateway.app_gateway`` with the same@@ -20,6 +20,7 @@ from jiuwenswarm.dotenv_early import parse_dotenv_early, get_parsed_dotenvparse_dotenv_early("jiuwenswarm-app")# --- Now safe to import jiuwenswarm modules ---+from jiuwenswarm.common.debug_dump import install_async_dump_handlerfrom jiuwenswarm.common.utils import (cleanup_team_files,get_env_file,@@ -68,6 +69,8 @@ def main() -> None:)args = parser.parse_args()+ install_async_dump_handler("app")+# Handle --name: check if bootstrap .env was loaded successfully# (parse_dotenv_early() already processed it at module import time)dotenv_path = _parsed_dotenv_pathdiff --git a/jiuwenswarm/channels/web/app_web.py b/jiuwenswarm/channels/web/app_web.pyindex 7e9c0a2d4c..781bb51562 100644--- a/jiuwenswarm/channels/web/app_web.py+++ b/jiuwenswarm/channels/web/app_web.py@@ -32,6 +32,7 @@ parse_dotenv_early("jiuwenswarm-web")# --- Now safe to import jiuwenswarm modules ---from jiuwenswarm.agents.harness.common.tools.ssl_config import get_insecure_ssl_context, get_ssl_verifyfrom jiuwenswarm.agents.harness.team.bootstrap import configure_agent_teams_home+from jiuwenswarm.common.debug_dump import install_async_dump_handlerfrom jiuwenswarm.common.ws_diagnostics import describe_ws_exception, format_ws_diagnosticsfrom jiuwenswarm.common.utils import get_agent_root_dir, get_logs_dir, \get_agent_sessions_dir, get_root_dir, get_user_workspace_dir, is_package_installation, wait_for_tcp_port@@ -1191,6 +1192,8 @@ def main() -> None:)args = parser.parse_args()+ install_async_dump_handler("web")+dist_dir = Path(args.dist).expanduser().resolve()if not dist_dir.exists():raise SystemExit(f"dist directory not found: {dist_dir}")diff --git a/jiuwenswarm/common/debug_dump.py b/jiuwenswarm/common/debug_dump.pynew file mode 100644index 0000000000..9fdd3f3c4f--- /dev/null+++ b/jiuwenswarm/common/debug_dump.py@@ -0,0 +1,164 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Live async-state dump for diagnosing coroutine stalls and deadlocks.++Service entrypoints call :func:`install_async_dump_handler` once; afterwards+``kill -USR1 <pid>`` snapshots the process without stopping it: every thread+stack, every pending asyncio task (repr, awaited future, coroutine stack) and+every asyncio primitive/queue that currently has waiters. Suspended coroutines+live on no thread stack, so thread-level tools (py-spy, faulthandler) cannot+see them; this dump is the coroutine-level complement.++SIGUSR1 does not exist on Windows, so installation is a no-op there.+:func:`dump_async_state` remains directly callable on all platforms.+"""++from __future__ import annotations++import asyncio+import gc+import io+import logging+import os+import signal+import sys+import threading+import time+import traceback+from pathlib import Path+from types import FrameType+from typing import TextIO++from jiuwenswarm.common.utils import get_logs_dir++logger = logging.getLogger(__name__)++_SYNC_PRIMITIVE_TYPES = (asyncio.Lock, asyncio.Event, asyncio.Condition, asyncio.Semaphore)+++def _write_thread_stacks(out: TextIO) -> None:+ out.write("\n########## THREAD STACKS ##########\n")+ thread_names = {t.ident: t.name for t in threading.enumerate()}+ for thread_id, frame in sys._current_frames().items():+ out.write(f"\n--- Thread {thread_id} ({thread_names.get(thread_id, '?')}) ---\n")+ out.write("".join(traceback.format_stack(frame)))+++def _collect_async_objects() -> tuple[list[asyncio.Task], list[object], list[asyncio.Queue]]:+ """Scan the gc heap once for tasks, sync primitives and queues.++ ``asyncio.all_tasks()`` needs a running loop in the calling thread and+ misses loops owned by other threads, so a full gc scan is used instead.+ """+ tasks: list[asyncio.Task] = []+ primitives: list[object] = []+ queues: list[asyncio.Queue] = []+ for obj in gc.get_objects():+ try:+ if isinstance(obj, asyncio.Task):+ tasks.append(obj)+ elif isinstance(obj, _SYNC_PRIMITIVE_TYPES):+ primitives.append(obj)+ elif isinstance(obj, asyncio.Queue):+ queues.append(obj)+ except Exception:+ continue+ return tasks, primitives, queues+++def _write_tasks(out: TextIO, tasks: list[asyncio.Task]) -> None:+ pending = [t for t in tasks if not t.done()]+ out.write("\n########## ASYNCIO TASKS ##########\n")+ out.write(f"total={len(tasks)} pending={len(pending)}\n")+ for index, task in enumerate(pending):+ out.write(f"\n===== Task #{index} =====\n")+ try:+ out.write(f"repr: {task!r}\n")+ out.write(f"waiting on: {getattr(task, '_fut_waiter', None)!r}\n")+ stack_buf = io.StringIO()+ task.print_stack(file=stack_buf)+ out.write(stack_buf.getvalue())+ except Exception as exc:+ out.write(f"<error dumping task: {exc!r}>\n")+++def _write_waiting_primitives(out: TextIO, primitives: list[object], queues: list[asyncio.Queue]) -> None:+ out.write("\n########## SYNC PRIMITIVES WITH WAITERS ##########\n")+ waiting_count = 0+ for primitive in primitives:+ try:+ waiters = getattr(primitive, "_waiters", None)+ if waiters:+ waiting_count += 1+ out.write(f"{primitive!r} waiters={len(waiters)}\n")+ except Exception:+ continue+ for queue in queues:+ try:+ getters = getattr(queue, "_getters", ())+ putters = getattr(queue, "_putters", ())+ if getters or putters:+ waiting_count += 1+ out.write(f"{queue!r} getters={len(getters)} putters={len(putters)}\n")+ except Exception:+ continue+ out.write(f"primitives_with_waiters={waiting_count}\n")+++def dump_async_state(service_name: str) -> Path | None:+ """Write a full thread/coroutine snapshot to the dump directory.++ Safe to call from a signal handler: it only reads interpreter state and+ never raises. The gc heap scan can pause the process for a few seconds,+ which is acceptable while diagnosing a stall.++ Args:+ service_name: Short service identifier used in the dump file name.++ Returns:+ Path of the written dump file, or None if the dump failed.+ """+ try:+ dump_dir = get_logs_dir() / "async_dump"+ dump_dir.mkdir(parents=True, exist_ok=True)+ now = time.time()+ millis = int(now * 1000) % 1000+ timestamp = time.strftime("%Y%m%d_%H%M%S", time.localtime(now)) + f"_{millis:03d}"+ dump_path = dump_dir / f"{service_name}_{os.getpid()}_{timestamp}.txt"+ with open(dump_path, "w", encoding="utf-8") as out:+ out.write(f"===== ASYNC STATE DUMP service={service_name} pid={os.getpid()} time={timestamp} =====\n")+ out.write(f"argv: {sys.argv!r}\n")+ _write_thread_stacks(out)+ tasks, primitives, queues = _collect_async_objects()+ _write_tasks(out, tasks)+ _write_waiting_primitives(out, primitives, queues)+ out.write("\n===== END OF DUMP =====\n")+ logger.info("[debug_dump] async state dumped to %s", dump_path)+ return dump_path+ except Exception:+ logger.exception("[debug_dump] async state dump failed")+ return None+++def install_async_dump_handler(service_name: str) -> None:+ """Register a SIGUSR1 handler that snapshots live async state to a file.++ Must be called from the main thread, before the event loop starts. On+ platforms without SIGUSR1 (Windows) this is a no-op.++ Args:+ service_name: Short service identifier used in dump file names.+ """+ if not hasattr(signal, "SIGUSR1"):+ logger.debug("[debug_dump] SIGUSR1 unavailable; async dump handler not installed")+ return++ def _handler(_signum: int, _frame: FrameType | None) -> None:+ dump_async_state(service_name)++ signal.signal(signal.SIGUSR1, _handler)+ logger.info(+ "[debug_dump] async dump handler installed for %s: kill -USR1 %s",+ service_name,+ os.getpid(),+ )diff --git a/jiuwenswarm/gateway/app_gateway.py b/jiuwenswarm/gateway/app_gateway.pyindex aff7485e6b..9dac53f628 100644--- a/jiuwenswarm/gateway/app_gateway.py+++ b/jiuwenswarm/gateway/app_gateway.py@@ -1,4 +1,4 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved."""Standalone Gateway entrypoint (split deployment).This process starts:@@ -41,6 +41,7 @@ from jiuwenswarm.gateway.channel_manager.protocol.acp.acp_connect import AcpGatefrom jiuwenswarm.gateway.routing.agent_request_timeout import coerce_client_timeout_msfrom jiuwenswarm.common.security.ws_origin import get_header_valuefrom jiuwenswarm.gateway.routing.route_binding import GatewayRouteBinding+from jiuwenswarm.common.debug_dump import install_async_dump_handlerfrom jiuwenswarm.common.utils import (get_cron_jobs_path,get_env_file,@@ -2435,6 +2436,7 @@ def main() -> None:web_port = args.port or int(os.getenv("WEB_PORT", "19000"))web_path = args.web_path or os.getenv("WEB_PATH", "/ws")+ install_async_dump_handler("gateway")asyncio.run(_run(agent_server_url=agent_server_url,diff --git a/jiuwenswarm/server/app_agentserver.py b/jiuwenswarm/server/app_agentserver.pyindex 841be853bb..1d3abbe3ba 100644--- a/jiuwenswarm/server/app_agentserver.py+++ b/jiuwenswarm/server/app_agentserver.py@@ -1,4 +1,4 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.+# Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved."""Standalone AgentServer entrypoint.This process only starts:@@ -28,6 +28,7 @@ from jiuwenswarm.dotenv_early import parse_dotenv_earlyparse_dotenv_early("jiuwenswarm-agentserver")# --- Now safe to import jiuwenswarm modules ---+from jiuwenswarm.common.debug_dump import install_async_dump_handlerfrom jiuwenswarm.common.utils import (get_env_file,get_root_dir,@@ -271,6 +272,7 @@ def main() -> None:else:port = 18092+ install_async_dump_handler("agentserver")asyncio.run(_run(host=host, port=port))