fix(gateway): request graceful Windows shutdown (#6353)

* fix(gateway): request graceful Windows shutdown

* docs(cli): simplify Windows gateway stop guidance

* test(gateway): compare native Windows owner SIDs
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-21 11:05:30 +08:00
1 parent fd30fda8a2
commit 73a55e0b2f
7 files changed
+554 -25

No files matched your search

+2
View File
@@ -170,6 +170,8 @@ First-run WebUI setup binds to `127.0.0.1` by default. Use manual configuration
| `nanobot gateway install-service --dry-run` | Preview the generated service file and system commands |
| `nanobot gateway uninstall-service` | Remove the installed system service |
On Windows, `gateway stop` waits up to `--timeout` seconds (default: 20) for the gateway to stop normally. If a forced stop is needed, the command displays a warning. Forced stops can interrupt active work.
For custom instances, pass the same selector flags after the management subcommand, as shown below. `--config` and `--workspace` before a management subcommand are rejected with a usage error; they are not inherited.
```bash
+4
View File
@@ -980,6 +980,10 @@ def _run_gateway(
logger.info("Last local client disappeared; stopping on-demand gateway")
tasks.extend([
asyncio.create_task(
gateway_runtime.wait_for_shutdown_request(shutdown_event),
name="nanobot-gateway-stop-request",
),
asyncio.create_task(
watch_config_file(
Path(config_path),
+72 -6
View File
@@ -20,10 +20,12 @@ from datetime import UTC, datetime
from pathlib import Path
from typing import Any, Generator, Literal, cast
from filelock import FileLock
from filelock import FileLock, Timeout
from loguru import logger
from nanobot.config.home import get_selected_home_path
from nanobot.config.paths import get_data_dir
from nanobot.gateway.windows_shutdown import WindowsShutdownEvent, request_windows_shutdown
from nanobot.process_runtime import (
ManagedProcessRuntime,
ProcessResult,
@@ -235,6 +237,7 @@ class GatewayRuntime(ManagedProcessRuntime[GatewayStartOptions]):
subprocess_run=subprocess_run,
sleep=sleep,
)
self._shutdown_signal: WindowsShutdownEvent | None = None
def _build_child_command(self, options: GatewayStartOptions) -> list[str]:
return build_gateway_command(self.python_executable, options)
@@ -339,12 +342,66 @@ class GatewayRuntime(ManagedProcessRuntime[GatewayStartOptions]):
@contextmanager
def foreground_instance(self, options: GatewayStartOptions) -> Generator[None]:
"""Publish this foreground gateway while it is available to local clients."""
self._claim_current_process(options)
"""Publish this process and own its stop signal across asyncio.run()."""
shutdown_signal = None
if self.platform_name == "Windows" and os.name == "nt":
identity = self.process_identity(os.getpid())
if not isinstance(identity, str):
raise OSError("Cannot identify the gateway process for Windows shutdown")
shutdown_signal = WindowsShutdownEvent(os.getpid(), identity)
self._shutdown_signal = shutdown_signal
try:
yield
self._claim_current_process(options)
try:
yield
finally:
self._release_current_process()
finally:
self._release_current_process()
self._shutdown_signal = None
if shutdown_signal is not None:
shutdown_signal.close()
async def wait_for_shutdown_request(self, shutdown_event: asyncio.Event) -> None:
"""Bridge the local Windows signal to the application's existing shutdown."""
signal = self._shutdown_signal
if signal is None:
return
waiter = asyncio.create_task(asyncio.to_thread(signal.wait))
try:
await asyncio.shield(waiter)
logger.info("Gateway shutdown requested by local CLI")
shutdown_event.set()
finally:
# Cancelling to_thread alone leaves its native wait alive. Wake it
# before asyncio.run drains the executor and the owner closes the handle.
signal.signal()
await waiter
def _terminate_windows(self, pid: int, *, timeout_s: int) -> bool:
state = self._read_state()
identity = self._process_identity(pid)
if identity is None:
return not self._is_pid_running(pid)
if self._process_identity_match(state, pid) != "match":
return False
requested = False
if isinstance(identity, str) and state is not None:
try:
requested = request_windows_shutdown(pid, identity, state.get("shutdown_token"))
except OSError as exc:
logger.warning("Could not request gateway shutdown: {}", exc)
if requested and self._wait_for_exit(pid, timeout_s):
return True
current_identity = self._process_identity(pid)
if current_identity is None:
return not self._is_pid_running(pid)
if current_identity != identity:
return False
if requested:
logger.warning("Gateway did not exit within {}s; forcing PID tree {}", timeout_s, pid)
else:
logger.warning("Gateway shutdown signal unavailable; forcing PID tree {}", pid)
return super()._terminate_windows(pid, timeout_s=timeout_s)
def _claim_current_process(self, options: GatewayStartOptions) -> GatewayLaunchMode:
lease = GatewayClientLease(self, kind="gateway-foreground")
@@ -389,6 +446,9 @@ class GatewayRuntime(ManagedProcessRuntime[GatewayStartOptions]):
state.pop("pending_pid_handoff", None)
state.pop("stable_identity", None)
state.update(self.process_identity_record(pid))
state.pop("shutdown_token", None)
if self._shutdown_signal is not None:
state["shutdown_token"] = self._shutdown_signal.token
self._write_state(state)
if launch_mode == "foreground":
lease._try_mark_persistent_locked()
@@ -521,7 +581,13 @@ class GatewayClientLease:
def begin_orphan_shutdown(self) -> bool:
"""Commit shutdown only while an on-demand gateway still has no clients."""
with self.transition_lock, self.lifecycle_lock, self.lock:
# Explicit stop holds this lock while waiting for us to exit. Never
# block the gateway loop (or an executor being drained) behind it.
try:
transition = self.transition_lock.acquire(timeout=0)
except Timeout:
return False
with transition, self.lifecycle_lock, self.lock:
state = self._live_state()
if not bool(state.get("auto_stop")) or self._clients(state):
self._write_or_clear(state)
+149
View File
@@ -0,0 +1,149 @@
"""User-private, process-bound Windows gateway shutdown signals."""
from __future__ import annotations
import ctypes
import re
import uuid
from collections.abc import Generator
from contextlib import contextmanager
from ctypes import wintypes
from functools import lru_cache
from typing import Any
class _SecurityAttributes(ctypes.Structure):
_fields_ = [
("length", wintypes.DWORD),
("descriptor", wintypes.LPVOID),
("inherit", wintypes.BOOL),
]
@lru_cache(maxsize=1)
def _kernel32() -> Any:
kernel = ctypes.WinDLL("kernel32", use_last_error=True)
kernel.GetCurrentProcess.restype = wintypes.HANDLE
kernel.CreateEventW.argtypes = [
ctypes.POINTER(_SecurityAttributes), wintypes.BOOL, wintypes.BOOL, wintypes.LPCWSTR,
]
kernel.CreateEventW.restype = wintypes.HANDLE
kernel.OpenEventW.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.LPCWSTR]
kernel.OpenEventW.restype = wintypes.HANDLE
kernel.SetEvent.argtypes = [wintypes.HANDLE]
kernel.SetEvent.restype = wintypes.BOOL
kernel.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]
kernel.WaitForSingleObject.restype = wintypes.DWORD
kernel.CloseHandle.argtypes = [wintypes.HANDLE]
kernel.CloseHandle.restype = wintypes.BOOL
kernel.LocalFree.argtypes = [wintypes.LPVOID]
kernel.LocalFree.restype = wintypes.LPVOID
return kernel
@contextmanager
def _private_security() -> Generator[_SecurityAttributes]:
kernel = _kernel32()
security = ctypes.WinDLL("advapi32", use_last_error=True)
security.OpenProcessToken.argtypes = [
wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE),
]
security.OpenProcessToken.restype = wintypes.BOOL
security.GetTokenInformation.argtypes = [
wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD,
ctypes.POINTER(wintypes.DWORD),
]
security.GetTokenInformation.restype = wintypes.BOOL
security.ConvertSidToStringSidW.argtypes = [
wintypes.LPVOID, ctypes.POINTER(wintypes.LPWSTR),
]
security.ConvertSidToStringSidW.restype = wintypes.BOOL
security.ConvertStringSecurityDescriptorToSecurityDescriptorW.argtypes = [
wintypes.LPCWSTR, wintypes.DWORD, ctypes.POINTER(wintypes.LPVOID), wintypes.LPVOID,
]
security.ConvertStringSecurityDescriptorToSecurityDescriptorW.restype = wintypes.BOOL
token = wintypes.HANDLE()
if not security.OpenProcessToken(kernel.GetCurrentProcess(), 0x0008, ctypes.byref(token)):
raise ctypes.WinError()
sid_text = wintypes.LPWSTR()
descriptor = wintypes.LPVOID()
try:
size = wintypes.DWORD()
security.GetTokenInformation(token, 1, None, 0, ctypes.byref(size)) # TokenUser
if not size.value:
raise ctypes.WinError()
user = ctypes.create_string_buffer(size.value)
if not security.GetTokenInformation(token, 1, user, len(user), ctypes.byref(size)):
raise ctypes.WinError()
sid = ctypes.cast(user, ctypes.POINTER(wintypes.LPVOID))[0]
if not security.ConvertSidToStringSidW(sid, ctypes.byref(sid_text)):
raise ctypes.WinError()
if not security.ConvertStringSecurityDescriptorToSecurityDescriptorW(
f"O:{sid_text.value}D:P(A;;GA;;;{sid_text.value})", 1,
ctypes.byref(descriptor), None,
):
raise ctypes.WinError()
yield _SecurityAttributes(ctypes.sizeof(_SecurityAttributes), descriptor, False)
finally:
if descriptor:
kernel.LocalFree(descriptor)
if sid_text:
kernel.LocalFree(sid_text)
kernel.CloseHandle(token)
def _event_name(pid: int, identity: str, token: str) -> str:
return rf"Local\nanobot-gateway-stop-{pid}-{identity}-{token}"
class WindowsShutdownEvent:
"""Own one latched signal; close only after the native waiter has drained."""
def __init__(self, pid: int, identity: str) -> None:
self.token = uuid.uuid4().hex
kernel = _kernel32()
with _private_security() as security:
ctypes.set_last_error(0)
handle = kernel.CreateEventW(
ctypes.byref(security), True, False, _event_name(pid, identity, self.token),
)
error = ctypes.get_last_error()
if not handle:
raise ctypes.WinError(error)
if error == 183: # ERROR_ALREADY_EXISTS: the requested DACL was not applied.
kernel.CloseHandle(handle)
raise OSError("Gateway shutdown event already exists")
self._handle: int | None = int(handle)
def wait(self) -> None:
"""Block a worker, never the event loop; signal() also wakes cancellation."""
if _kernel32().WaitForSingleObject(self._handle, 0xFFFFFFFF) != 0:
raise ctypes.WinError()
def signal(self) -> None:
if not _kernel32().SetEvent(self._handle):
raise ctypes.WinError()
def close(self) -> None:
if self._handle is not None:
_kernel32().CloseHandle(self._handle)
self._handle = None
def request_windows_shutdown(pid: int, identity: str, token: object) -> bool:
"""Signal only a validated token in this exact process-birth namespace."""
if not isinstance(token, str) or re.fullmatch(r"[0-9a-f]{32}", token) is None:
return False
kernel = _kernel32()
handle = kernel.OpenEventW(0x0002, False, _event_name(pid, identity, token))
if not handle:
error = ctypes.get_last_error()
if error == 2: # The process exited, or never published this event.
return False
raise ctypes.WinError(error)
try:
if not kernel.SetEvent(handle):
raise ctypes.WinError()
return True
finally:
kernel.CloseHandle(handle)
+12 -14
View File
@@ -390,20 +390,18 @@ class ManagedProcessRuntime(Generic[_StartOptionsT]):
# not an individual process, and can interrupt the caller when a
# detached/no-window child has no addressable console group. Keep
# termination scoped to the recorded PID tree instead.
self._subprocess_run(
["taskkill", "/PID", str(pid), "/T"],
check=False,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
if self._wait_for_exit(pid, timeout_s):
return True
self._subprocess_run(
["taskkill", "/PID", str(pid), "/T", "/F"],
check=False,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
# Cooperative shutdown belongs to the application owner. Non-forced
# taskkill cannot close these windowless trees and only wastes its grace period.
try:
self._subprocess_run(
["taskkill", "/PID", str(pid), "/T", "/F"],
check=False,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=2,
)
except subprocess.TimeoutExpired:
return False
return self._wait_for_exit(pid, 2)
def _wait_for_exit(self, pid: int, timeout_s: int | float) -> bool:
+43 -5
View File
@@ -21,7 +21,7 @@ from nanobot.gateway import (
RuntimeResult,
)
from nanobot.gateway.runtime import monitor_gateway_clients
from nanobot.process_runtime import process_is_running
from nanobot.process_runtime import ManagedProcessRuntime, process_is_running
from nanobot.utils.rotating_output import (
BACKGROUND_LOG_BACKUP_COUNT_ENV,
BACKGROUND_LOG_MAX_BYTES_ENV,
@@ -1263,7 +1263,7 @@ def test_terminate_windows_targets_only_the_recorded_process_tree(tmp_path, monk
def fake_run(command, **kwargs):
taskkill_calls.append({"command": command, "kwargs": kwargs})
runtime = GatewayRuntime(
runtime = ManagedProcessRuntime(
paths=_paths(tmp_path),
platform_name="Windows",
subprocess_run=fake_run,
@@ -1277,25 +1277,63 @@ def test_terminate_windows_targets_only_the_recorded_process_tree(tmp_path, monk
def fake_wait_for_exit(_pid, _timeout_s):
wait_timeouts.append(_timeout_s)
# Simulate a process that only exits after the taskkill fallback runs.
# Simulate a process that exits only after its tree is forcibly terminated.
return bool(taskkill_calls)
monkeypatch.setattr(runtime, "_wait_for_exit", fake_wait_for_exit)
assert runtime._terminate_windows(12345, timeout_s=20) is True
assert wait_timeouts == [20]
assert wait_timeouts == [2]
assert taskkill_calls == [
{
"command": ["taskkill", "/PID", "12345", "/T"],
"command": ["taskkill", "/PID", "12345", "/T", "/F"],
"kwargs": {
"check": False,
"stdout": subprocess.DEVNULL,
"stderr": subprocess.DEVNULL,
"timeout": 2,
},
}
]
def test_orphan_shutdown_yields_to_an_explicit_lifecycle_transition(tmp_path):
runtime = GatewayRuntime(paths=_paths(tmp_path))
lease = GatewayClientLease(runtime, kind="gateway-monitor")
lease.mark_ephemeral()
with runtime._transition_lock():
assert lease.begin_orphan_shutdown() is False
assert "stopping" not in json.loads(lease.state_path.read_text(encoding="utf-8"))
assert lease.begin_orphan_shutdown() is True
def test_windows_stop_does_not_force_a_pid_reused_during_grace(tmp_path, monkeypatch):
killed = []
runtime = GatewayRuntime(
paths=_paths(tmp_path), platform_name="Windows",
subprocess_run=lambda *args, **kwargs: killed.append(args),
)
identity = "original-process"
runtime._write_state({"pid": 12345, "identity": identity, "shutdown_token": "a" * 32})
monkeypatch.setattr(runtime, "_process_identity", lambda _pid: identity)
monkeypatch.setattr(runtime, "_is_pid_running", lambda _pid: True)
monkeypatch.setattr("nanobot.gateway.runtime.request_windows_shutdown", lambda *_args: True)
def exit_and_reuse_pid(_pid, _timeout):
nonlocal identity
identity = "replacement-process"
return False
monkeypatch.setattr(runtime, "_wait_for_exit", exit_and_reuse_pid)
result = runtime.stop(timeout_s=1)
assert result.status.running is False
assert killed == []
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX process groups are unavailable")
def test_terminate_posix_tolerates_process_group_disappearing_before_sigkill(
tmp_path,
+272
View File
@@ -0,0 +1,272 @@
"""Exercise Windows gateway shutdown through real, isolated CLI processes."""
import asyncio
import ctypes
import http.client
import json
import os
import socket
import subprocess
import sys
import time
from ctypes import wintypes
from pathlib import Path
import pytest
from nanobot.gateway import (
GatewayInstance,
GatewayRuntime,
GatewayRuntimePaths,
GatewayStartOptions,
)
from nanobot.gateway.windows_shutdown import WindowsShutdownEvent, request_windows_shutdown
pytestmark = pytest.mark.skipif(sys.platform != "win32", reason="Windows process lifecycle")
def test_windowless_gateway_stop_runs_application_cleanup(tmp_path: Path) -> None:
root = Path(__file__).resolve().parents[2]
with socket.socket() as reservation:
reservation.bind(("127.0.0.1", 0))
port = reservation.getsockname()[1]
config_path = tmp_path / "config.json"
config_path.write_text(json.dumps({
"agents": {"defaults": {
"workspace": str(tmp_path / "workspace"),
"model": "openai/test-only",
"dream": {"enabled": False},
}},
"providers": {"openai": {"apiKey": "test-only", "apiBase": "http://127.0.0.1:9/v1"}},
"gateway": {"host": "127.0.0.1", "port": port, "heartbeat": {"enabled": False}},
"channels": {"websocket": {"enabled": False}},
}), encoding="utf-8")
runtime = GatewayRuntime(paths=GatewayInstance.resolve(config_path=config_path).paths)
env = {**os.environ, "PYTHONPATH": str(root), "PYTHONUTF8": "1"}
log_path = tmp_path / "gateway.log"
with log_path.open("w", encoding="utf-8") as output:
process = subprocess.Popen(
[sys.executable, "-m", "nanobot", "gateway", "--foreground", "--config", str(config_path)],
cwd=root,
env=env,
stdin=subprocess.DEVNULL,
stdout=output,
stderr=subprocess.STDOUT,
creationflags=subprocess.CREATE_NO_WINDOW | subprocess.CREATE_NEW_PROCESS_GROUP,
)
try:
deadline = time.monotonic() + 20
while True:
connection = http.client.HTTPConnection("127.0.0.1", port, timeout=0.2)
try:
connection.request("GET", "/health")
if connection.getresponse().status == 200:
break
except (OSError, http.client.HTTPException):
pass
finally:
connection.close()
assert process.poll() is None, log_path.read_text(encoding="utf-8")
assert time.monotonic() < deadline, log_path.read_text(encoding="utf-8")
time.sleep(0.02)
stopped = subprocess.run(
[sys.executable, "-m", "nanobot", "gateway", "stop", "--config", str(config_path)],
cwd=root,
env=env,
capture_output=True,
text=True,
encoding="utf-8",
timeout=30,
)
assert stopped.returncode == 0, stopped.stdout + stopped.stderr
assert "Gateway stopped" in stopped.stdout
assert process.wait(timeout=5) == 0, log_path.read_text(encoding="utf-8")
assert "Agent loop stopping" in log_path.read_text(encoding="utf-8")
assert not runtime.paths.state_path.exists()
finally:
if process.poll() is None:
runtime.stop(timeout_s=0)
process.wait(timeout=5)
def _event_security(handle: int) -> str:
"""Verify the native owner identity and return the event's rendered security."""
security = ctypes.WinDLL("advapi32", use_last_error=True)
kernel = ctypes.WinDLL("kernel32", use_last_error=True)
kernel.GetCurrentProcess.restype = wintypes.HANDLE
kernel.CloseHandle.argtypes = [wintypes.HANDLE]
kernel.CloseHandle.restype = wintypes.BOOL
security.OpenProcessToken.argtypes = [
wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE),
]
security.OpenProcessToken.restype = wintypes.BOOL
security.GetTokenInformation.argtypes = [
wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD,
ctypes.POINTER(wintypes.DWORD),
]
security.GetTokenInformation.restype = wintypes.BOOL
security.EqualSid.argtypes = [wintypes.LPVOID, wintypes.LPVOID]
security.EqualSid.restype = wintypes.BOOL
security.GetSecurityInfo.argtypes = [
wintypes.HANDLE, ctypes.c_int, wintypes.DWORD,
wintypes.LPVOID, wintypes.LPVOID, wintypes.LPVOID, wintypes.LPVOID,
ctypes.POINTER(wintypes.LPVOID),
]
security.GetSecurityInfo.restype = wintypes.DWORD
security.ConvertSecurityDescriptorToStringSecurityDescriptorW.argtypes = [
wintypes.LPVOID, wintypes.DWORD, wintypes.DWORD,
ctypes.POINTER(wintypes.LPWSTR), wintypes.LPVOID,
]
security.ConvertSecurityDescriptorToStringSecurityDescriptorW.restype = wintypes.BOOL
kernel.LocalFree.argtypes = [wintypes.LPVOID]
kernel.LocalFree.restype = wintypes.LPVOID
descriptor = wintypes.LPVOID()
owner = wintypes.LPVOID()
text = wintypes.LPWSTR()
token = wintypes.HANDLE()
try:
assert security.GetSecurityInfo(
handle, 6, 5, ctypes.byref(owner), None, None, None, ctypes.byref(descriptor),
) == 0
assert security.OpenProcessToken(kernel.GetCurrentProcess(), 0x0008, ctypes.byref(token))
size = wintypes.DWORD()
security.GetTokenInformation(token, 1, None, 0, ctypes.byref(size)) # TokenUser
assert size.value > 0
user = ctypes.create_string_buffer(size.value)
assert security.GetTokenInformation(token, 1, user, len(user), ctypes.byref(size))
current_user = ctypes.cast(user, ctypes.POINTER(wintypes.LPVOID))[0]
# SDDL may abbreviate account SIDs (for example LA); compare their identities.
assert security.EqualSid(owner, current_user)
assert security.ConvertSecurityDescriptorToStringSecurityDescriptorW(
descriptor, 1, 5, ctypes.byref(text), None,
)
assert text.value is not None
return text.value
finally:
if text:
kernel.LocalFree(text)
if descriptor:
kernel.LocalFree(descriptor)
if token:
kernel.CloseHandle(token)
def test_shutdown_signal_is_private_process_bound_and_latched(tmp_path: Path) -> None:
runtime = GatewayRuntime(paths=GatewayRuntimePaths.for_instance(data_dir=tmp_path))
pid = os.getpid()
identity = runtime.process_identity(pid)
assert isinstance(identity, str)
with runtime.foreground_instance(GatewayStartOptions(port=0)):
state = json.loads(runtime.paths.state_path.read_text(encoding="utf-8"))
token = state["shutdown_token"]
signal = runtime._shutdown_signal
assert signal is not None and signal._handle is not None
owner, dacl = _event_security(signal._handle)[2:].split("D:", 1)
assert dacl.startswith("P(A;;") and dacl.endswith(f";;;{owner})")
assert dacl.count("(") == 1 # One owner-only allow ACE, no inherited grants.
assert request_windows_shutdown(pid + 1, identity, token) is False
assert request_windows_shutdown(pid, identity + "1", token) is False
other = WindowsShutdownEvent(pid, identity)
try:
other_name = rf"Local\nanobot-gateway-stop-{pid}-{identity}-{other.token}"
assert request_windows_shutdown(pid, identity, other_name) is False
kernel = ctypes.WinDLL("kernel32", use_last_error=True)
kernel.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]
kernel.WaitForSingleObject.restype = wintypes.DWORD
assert kernel.WaitForSingleObject(other._handle, 0) == 258 # Still unsignaled.
finally:
other.close()
assert request_windows_shutdown(pid, identity, token) is True
shutdown = asyncio.Event()
asyncio.run(runtime.wait_for_shutdown_request(shutdown))
assert shutdown.is_set()
assert request_windows_shutdown(pid, identity, token) is False
def test_cancelling_shutdown_listener_drains_its_native_wait(tmp_path: Path) -> None:
runtime = GatewayRuntime(paths=GatewayRuntimePaths.for_instance(data_dir=tmp_path))
with runtime.foreground_instance(GatewayStartOptions(port=0)):
async def cancel_listener() -> None:
shutdown = asyncio.Event()
listener = asyncio.create_task(runtime.wait_for_shutdown_request(shutdown))
await asyncio.sleep(0) # Admit the wait before exercising ordinary runtime cancellation.
listener.cancel()
with pytest.raises(asyncio.CancelledError):
await asyncio.wait_for(listener, timeout=2)
assert not shutdown.is_set()
asyncio.run(cancel_listener())
assert runtime._shutdown_signal is None
def test_failed_foreground_publication_closes_shutdown_signal(tmp_path: Path, monkeypatch) -> None:
runtime = GatewayRuntime(paths=GatewayRuntimePaths.for_instance(data_dir=tmp_path))
signals = []
def create_signal(pid, identity):
signal = WindowsShutdownEvent(pid, identity)
signals.append(signal)
return signal
def fail_write(_state):
raise OSError("cannot publish state")
monkeypatch.setattr("nanobot.gateway.runtime.WindowsShutdownEvent", create_signal)
monkeypatch.setattr(runtime, "_write_state", fail_write)
with pytest.raises(OSError, match="cannot publish state"):
with runtime.foreground_instance(GatewayStartOptions(port=0)):
pytest.fail("failed publication must not enter the foreground runtime")
assert len(signals) == 1 and signals[0]._handle is None
assert runtime._shutdown_signal is None
_STALLED_GATEWAY = r"""
import json, subprocess, sys, time
from pathlib import Path
from nanobot.gateway import GatewayInstance, GatewayRuntime, GatewayStartOptions
root = Path(sys.argv[1])
runtime = GatewayRuntime(paths=GatewayInstance.resolve(config_path=root / 'config.json').paths)
with runtime.foreground_instance(GatewayStartOptions(port=0)):
child = subprocess.Popen([sys._base_executable, '-c', 'import time; time.sleep(60)'])
(root / 'ready.json').write_text(json.dumps({'child': child.pid}), encoding='utf-8')
time.sleep(60) # Models a blocked event loop that cannot service the kernel event.
"""
@pytest.mark.parametrize("published", [True, False], ids=["stalled", "no-signal"])
def test_windows_stop_forces_only_its_stalled_tree(tmp_path: Path, published: bool) -> None:
runtime = GatewayRuntime(paths=GatewayInstance.resolve(config_path=tmp_path / "config.json").paths)
root = Path(__file__).resolve().parents[2]
env = {**os.environ, "PYTHONPATH": str(root)}
process = subprocess.Popen(
[sys.executable, "-c", _STALLED_GATEWAY, str(tmp_path)], env=env,
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
creationflags=subprocess.CREATE_NO_WINDOW | subprocess.CREATE_NEW_PROCESS_GROUP,
)
ready = tmp_path / "ready.json"
try:
deadline = time.monotonic() + 5
while not ready.exists():
assert process.poll() is None
assert time.monotonic() < deadline
time.sleep(0.01)
child_pid = json.loads(ready.read_text(encoding="utf-8"))["child"]
state = json.loads(runtime.paths.state_path.read_text(encoding="utf-8"))
if not published:
state.pop("shutdown_token")
runtime._write_state(state)
started = time.monotonic()
result = runtime.stop(timeout_s=1 if published else 20)
elapsed = time.monotonic() - started
assert result.ok
assert process.wait(timeout=5) != 0
assert not runtime.process_is_running(child_pid)
assert not runtime.paths.state_path.exists()
assert elapsed < 5 # Missing signals must not consume the 20-second grace.
if published:
assert elapsed >= 1 # A delivered request retains the caller's grace period.
finally:
if process.poll() is None:
runtime.stop(timeout_s=0)
process.wait(timeout=5)