The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui): throttle idle bot-delivery poll to stop sessions² CPU
KoNit-Kbfc28a2cc308
diff --git a/hermes_cli/active_sessions.py b/hermes_cli/active_sessions.pyindex 2be0ccad5a4..92af24b780f 100644--- a/hermes_cli/active_sessions.py+++ b/hermes_cli/active_sessions.py@@ -327,6 +327,8 @@ def _pid_liveness(pid: Any, process_start_time: Any = None, *, lenient: bool = Fpid_int = 0if pid_int <= 0:return unknown_dead+ if pid_int == os.getpid():+ return Truetry:from gateway.status import _pid_existsexists = bool(_pid_exists(pid_int))diff --git a/tests/hermes_cli/test_active_sessions.py b/tests/hermes_cli/test_active_sessions.pyindex 245df44223a..edbb97cc883 100644--- a/tests/hermes_cli/test_active_sessions.py+++ b/tests/hermes_cli/test_active_sessions.py@@ -726,3 +726,30 @@ def test_liveness_guard_keeps_a_just_acquired_own_lease_it_cannot_vouch_for() as active:assert active is Falseassert active_sessions.active_session_registry_snapshot(home) == []+++def test_pid_liveness_self_pid_skips_exists_probe(monkeypatch):+ """The probing process is trivially live: no psutil sweep for os.getpid() (#108005)."""+ exists_calls: list = []++ def _count_exists(pid):+ exists_calls.append(pid)+ return True++ monkeypatch.setattr("gateway.status._pid_exists", _count_exists)+ assert active_sessions._pid_liveness(os.getpid()) is True+ assert exists_calls == []+++def test_pid_liveness_foreign_pid_still_calls_exists(monkeypatch):+ """CONTROL: a different positive pid still goes through gateway.status._pid_exists."""+ exists_calls: list = []++ def _count_exists(pid):+ exists_calls.append(pid)+ return False++ monkeypatch.setattr("gateway.status._pid_exists", _count_exists)+ foreign = os.getpid() + 99999+ assert active_sessions._pid_liveness(foreign) is False+ assert exists_calls == [foreign]diff --git a/tests/tui_gateway/test_bot_delivery_poll_throttle.py b/tests/tui_gateway/test_bot_delivery_poll_throttle.pynew file mode 100644index 00000000000..f79afcf9cda--- /dev/null+++ b/tests/tui_gateway/test_bot_delivery_poll_throttle.py@@ -0,0 +1,79 @@+"""Idle notification poller must not probe bot-delivery on every 0.5s queue tick (#108005)."""++from __future__ import annotations++import threading+import time+from queue import Empty++import tui_gateway.server as server+from tools.process_registry import process_registry+++class _IdleTimeoutQueue:+ """Stand-in for ``completion_queue`` that only ever takes the idle timeout path."""++ def get(self, timeout=None):+ if timeout:+ time.sleep(float(timeout))+ raise Empty()++ def get_nowait(self):+ raise Empty()++ def qsize(self):+ return 0++ def put(self, _item):+ return None+++def test_idle_poller_throttles_bot_live_delivery_probe(monkeypatch):+ """Drive the bound poller: ~1.2s of 0.5s idle ticks must not call the probe every iteration.++ Pre-fix every loop iteration hits ``_poll_bot_live_delivery_once`` (~2/s → ≥3 calls).+ Post-fix the first iteration fires promptly, then the 5.0s cadence holds (1, or ≤2).+ """+ calls: list[float] = []++ def _probe(_sid, _session):+ calls.append(time.monotonic())+ return False++ monkeypatch.setattr(server, "_poll_bot_live_delivery_once", _probe)+ monkeypatch.setattr(server, "_notif_poll_kanban", lambda *_a, **_k: None)+ monkeypatch.setattr(server, "_maybe_fire_tui_loop_tick", lambda *_a, **_k: None)+ monkeypatch.setattr(server, "_maybe_fire_tui_heartbeat_tick", lambda *_a, **_k: None)+ monkeypatch.setattr(process_registry, "completion_queue", _IdleTimeoutQueue())++ session = {+ "session_key": "sid-bot-delivery-throttle",+ "history_lock": threading.Lock(),+ "_finalized": False,+ }+ stop = threading.Event()+ thread = threading.Thread(+ target=server._notification_poller_loop,+ args=(stop, "sid-bot-delivery-throttle", session),+ daemon=True,+ name="tui-notif-poller-bot-delivery-throttle",+ )+ thread.start()+ try:+ time.sleep(1.2)+ finally:+ stop.set()+ thread.join(timeout=5)++ assert thread.is_alive() is False+ assert 1 <= len(calls) <= 2, (+ f"idle bot-delivery probe ran {len(calls)} times in ~1.2s; "+ "expected 1 (or ≤2 with first-iteration immediate fire), not every 0.5s tick"+ )+++def test_bot_delivery_poll_seconds_bound_on_server_after_bind():+ """Supplement: the throttle constant is visible on the rebound server module."""+ cadence = server._BOT_DELIVERY_POLL_SECONDS+ assert 2.0 <= cadence <= 5.0+ assert cadence == 5.0diff --git a/tui_gateway/session_notifications.py b/tui_gateway/session_notifications.pyindex e6d8d5de310..c6a25017a9f 100644--- a/tui_gateway/session_notifications.py+++ b/tui_gateway/session_notifications.py@@ -135,6 +135,7 @@ def _notification_event_dedup_key(evt: dict) -> tuple:# past them and they can't wedge a later completed/blocked event behind an unclaimed row._KANBAN_NOTIFY_KINDS = ("completed", "blocked", "gave_up", "crashed", "timed_out", "status", "archived", "unblocked")_KANBAN_POLL_SECONDS = _LOOP_POLL_SECONDS = 5.0 # /loop and /heartbeat share one idle-poll cadence+_BOT_DELIVERY_POLL_SECONDS = 5.0 # idle CPU: do not probe leases on every 0.5s queue timeoutdef _notif_release_turn(session: dict) -> None:@@ -697,10 +698,12 @@ def _notification_poller_scoped_loop(stop_event: threading.Event, sid: str, sessemitted = session.setdefault("_notification_emitted", set())handle = lambda events, deferred: _notif_handle_ready( # noqa: E731sid, session, events, emitted, process_registry, format_process_notification, deferred)- last_kanban_poll = last_loop_poll = 0.0+ last_kanban_poll = last_loop_poll = last_bot_poll = 0.0while not stop_event.is_set() and not session.get("_finalized"):now = time.monotonic()- _poll_bot_live_delivery_guarded(sid, session, now)+ if now - last_bot_poll >= _BOT_DELIVERY_POLL_SECONDS:+ last_bot_poll = now+ _poll_bot_live_delivery_guarded(sid, session, now)# /loop and /heartbeat wakeup drivers: fire a due tick for THIS session while idle (same claim-under-lock# as kanban dispatch). An active non-parked /goal owns the idle boundary and defers the loop tick.if now - last_loop_poll >= _LOOP_POLL_SECONDS: