fix: log WebUI shutdown diagnostics

This commit is contained in:
ai-ag2026
2026-05-28 22:55:38 +02:00
parent cf003ae986
commit 53f16c4ee6
4 changed files with 165 additions and 0 deletions

View File

@@ -8,6 +8,7 @@ import os
import re
import socket
import sys
import threading
import time
import traceback
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
@@ -403,6 +404,63 @@ def _raise_fd_soft_limit(target: int = 4096) -> dict:
return {"status": "raised", "soft": desired, "hard": hard, "previous_soft": soft}
_SHUTDOWN_AUDIT_LOGGED = False
_SHUTDOWN_LOG_VALUE_RE = re.compile(r"[\x00-\x1f\x7f]+")
def _shutdown_log_value(value, *, default: str = "unknown", max_len: int = 160) -> str:
"""Return a bounded single-line value safe for shutdown diagnostics."""
if value is None:
return default
try:
text = str(value)
except Exception:
return default
text = _SHUTDOWN_LOG_VALUE_RE.sub("?", text).strip()
if not text:
return default
if len(text) > max_len:
text = f"{text[:max_len]}"
return text
def _log_shutdown_audit(reason: str = "serve_forever_exit") -> None:
"""Log runtime context when the WebUI server is exiting."""
global _SHUTDOWN_AUDIT_LOGGED
if _SHUTDOWN_AUDIT_LOGGED:
return
active_sessions = []
try:
from api.models import LOCK, SESSIONS
with LOCK:
session_items = list(SESSIONS.items())
for sid, session in session_items:
stream_id = getattr(session, "active_stream_id", None)
if stream_id:
pending = bool(getattr(session, "pending_user_message", None))
active_sessions.append(
"sid=%s stream=%s pending=%s"
% (
_shutdown_log_value(sid),
_shutdown_log_value(stream_id),
pending,
)
)
except Exception:
logger.debug("Failed to collect active-session shutdown audit state", exc_info=True)
_SHUTDOWN_AUDIT_LOGGED = True
logger.info(
"[shutdown-audit] reason=%s pid=%s thread=%s(%s) active_sessions=[%s]",
_shutdown_log_value(reason),
os.getpid(),
_shutdown_log_value(threading.current_thread().name),
threading.current_thread().ident,
"; ".join(active_sessions) if active_sessions else "none",
)
def main() -> None:
from api.config import print_startup_config, verify_hermes_imports, _HERMES_FOUND
@@ -516,6 +574,7 @@ def main() -> None:
try:
httpd.serve_forever()
finally:
_log_shutdown_audit()
# Stop the gateway watcher on shutdown
try:
from api.gateway_watcher import stop_watcher