Skip to content

The agent that grows with you

refactor(web_server): move _process_start_marker with the lifecycle cluster

Teknium7d43c20af7ab
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index 570506d2737..ca73c4fd256 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -84,85 +84,8 @@ WEB_DIST = Path(os.environ["HERMES_WEB_DIST"]) if "HERMES_WEB_DIST" in os.enviro
_log = logging.getLogger(__name__)
-def _process_start_marker(pid: int) -> str:
- """Return a cross-runtime marker for the current incarnation of ``pid``.
-
- ``ProcessLookupError`` means the process is absent. Other failures are left
- distinct so callers can fail safe rather than killing a healthy backend.
- """
- if sys.platform == "linux":
- try:
- stat_line = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8")
- except FileNotFoundError as exc:
- raise ProcessLookupError(pid) from exc
-
- # The command in field 2 may contain spaces or parentheses. Splitting
- # after its final ')' leaves field 3 at index zero and field 22 at 19.
- fields = stat_line.rsplit(")", 1)[1].strip().split()
- if len(fields) < 20 or not fields[19].isdigit():
- raise OSError(f"invalid /proc stat data for PID {pid}")
- return f"linux:{fields[19]}"
-
- if os.name == "nt":
- import ctypes
- from ctypes import wintypes
-
- process_query_limited_information = 0x1000
- kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
- kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
- kernel32.OpenProcess.restype = wintypes.HANDLE
- kernel32.GetProcessTimes.argtypes = [
- wintypes.HANDLE,
- ctypes.POINTER(wintypes.FILETIME),
- ctypes.POINTER(wintypes.FILETIME),
- ctypes.POINTER(wintypes.FILETIME),
- ctypes.POINTER(wintypes.FILETIME),
- ]
- kernel32.GetProcessTimes.restype = wintypes.BOOL
- kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
- kernel32.CloseHandle.restype = wintypes.BOOL
- handle = kernel32.OpenProcess(process_query_limited_information, False, pid)
- if not handle:
- error = ctypes.get_last_error()
- if error in (87, 1168): # invalid parameter / not found
- raise ProcessLookupError(pid)
- raise OSError(error, f"OpenProcess failed for PID {pid}")
-
- creation = wintypes.FILETIME()
- exit_time = wintypes.FILETIME()
- kernel = wintypes.FILETIME()
- user = wintypes.FILETIME()
- try:
- if not kernel32.GetProcessTimes(
- handle,
- ctypes.byref(creation),
- ctypes.byref(exit_time),
- ctypes.byref(kernel),
- ctypes.byref(user),
- ):
- error = ctypes.get_last_error()
- raise OSError(error, f"GetProcessTimes failed for PID {pid}")
- finally:
- kernel32.CloseHandle(handle)
-
- filetime = (creation.dwHighDateTime << 32) | creation.dwLowDateTime
- return f"win:{filetime + 504911232000000000}"
-
- result = subprocess.run(
- ["ps", "-p", str(pid), "-o", "lstart="],
- capture_output=True,
- text=True,
- check=False,
- )
- marker = result.stdout.strip()
- if result.returncode == 0 and marker:
- return f"ps:{marker}"
- if result.returncode == 1 and not marker:
- raise ProcessLookupError(pid)
- raise OSError(f"ps could not inspect PID {pid}: {result.stderr.strip()}")
-
-
from hermes_cli.web_server_lifecycle import ( # noqa: E402,F401 — re-exported; routers/tests reach these via web_server.<name>
+ _process_start_marker,
PORT_IN_USE_EXIT_CODE,
_dashboard_forwarded_allow_ips,
_eager_reconcile_own_session_db,
diff --git a/hermes_cli/web_server_lifecycle.py b/hermes_cli/web_server_lifecycle.py
index 01fae465eeb..5aef1598673 100644
--- a/hermes_cli/web_server_lifecycle.py
+++ b/hermes_cli/web_server_lifecycle.py
@@ -9,17 +9,99 @@ import logging
import ipaddress
import json
import os
+import subprocess
import sys
import tempfile
import threading
import time
from pathlib import Path
-from typing import Any, Optional
+from typing import TYPE_CHECKING, Any, Optional
+
+if TYPE_CHECKING: # pragma: no cover - annotation only
+ import uvicorn
# Same logger the code used before extraction (record parity).
_log = logging.getLogger("hermes_cli.web_server")
+def _process_start_marker(pid: int) -> str:
+ """Return a cross-runtime marker for the current incarnation of ``pid``.
+
+ ``ProcessLookupError`` means the process is absent. Other failures are left
+ distinct so callers can fail safe rather than killing a healthy backend.
+ """
+ if sys.platform == "linux":
+ try:
+ stat_line = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8")
+ except FileNotFoundError as exc:
+ raise ProcessLookupError(pid) from exc
+
+ # The command in field 2 may contain spaces or parentheses. Splitting
+ # after its final ')' leaves field 3 at index zero and field 22 at 19.
+ fields = stat_line.rsplit(")", 1)[1].strip().split()
+ if len(fields) < 20 or not fields[19].isdigit():
+ raise OSError(f"invalid /proc stat data for PID {pid}")
+ return f"linux:{fields[19]}"
+
+ if os.name == "nt":
+ import ctypes
+ from ctypes import wintypes
+
+ process_query_limited_information = 0x1000
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
+ kernel32.OpenProcess.restype = wintypes.HANDLE
+ kernel32.GetProcessTimes.argtypes = [
+ wintypes.HANDLE,
+ ctypes.POINTER(wintypes.FILETIME),
+ ctypes.POINTER(wintypes.FILETIME),
+ ctypes.POINTER(wintypes.FILETIME),
+ ctypes.POINTER(wintypes.FILETIME),
+ ]
+ kernel32.GetProcessTimes.restype = wintypes.BOOL
+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
+ kernel32.CloseHandle.restype = wintypes.BOOL
+ handle = kernel32.OpenProcess(process_query_limited_information, False, pid)
+ if not handle:
+ error = ctypes.get_last_error()
+ if error in (87, 1168): # invalid parameter / not found
+ raise ProcessLookupError(pid)
+ raise OSError(error, f"OpenProcess failed for PID {pid}")
+
+ creation = wintypes.FILETIME()
+ exit_time = wintypes.FILETIME()
+ kernel = wintypes.FILETIME()
+ user = wintypes.FILETIME()
+ try:
+ if not kernel32.GetProcessTimes(
+ handle,
+ ctypes.byref(creation),
+ ctypes.byref(exit_time),
+ ctypes.byref(kernel),
+ ctypes.byref(user),
+ ):
+ error = ctypes.get_last_error()
+ raise OSError(error, f"GetProcessTimes failed for PID {pid}")
+ finally:
+ kernel32.CloseHandle(handle)
+
+ filetime = (creation.dwHighDateTime << 32) | creation.dwLowDateTime
+ return f"win:{filetime + 504911232000000000}"
+
+ result = subprocess.run(
+ ["ps", "-p", str(pid), "-o", "lstart="],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ marker = result.stdout.strip()
+ if result.returncode == 0 and marker:
+ return f"ps:{marker}"
+ if result.returncode == 1 and not marker:
+ raise ProcessLookupError(pid)
+ raise OSError(f"ps could not inspect PID {pid}: {result.stderr.strip()}")
+
+
def _valid_parent_start_marker(marker: str) -> bool:
prefix, separator, value = marker.partition(":")
if not separator or not value or value != value.strip():
@@ -235,7 +317,6 @@ def _is_serve_orphaned(
fail-safe: keep serving rather than killing a backend whose owner could not
be conclusively shown to be dead.
"""
- from hermes_cli.web_server import _process_start_marker
try:
if expected_start_marker is not None:
probe = process_start_marker or _process_start_marker