The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui,active_sessions): gate-review follow-ups for the idle bot-delivery throttle
kshitijk4poor06c19032b710
diff --git a/hermes_cli/active_sessions.py b/hermes_cli/active_sessions.pyindex ac1ced555b3..b30da541045 100644--- a/hermes_cli/active_sessions.py+++ b/hermes_cli/active_sessions.py@@ -308,16 +308,19 @@ def _process_start_time(pid: int) -> Optional[float]:return None-_OWN_START_TIME: dict[int, Optional[float]] = {}+_OWN_START: tuple[int, float] | None = None # (pid, create_time); published atomically, re-read after forkdef _own_start_time() -> Optional[float]:- """This process's create_time, read from psutil once per pid (survives fork)."""+ """This process's create_time, read from psutil once instead of per lease probe."""+ global _OWN_STARTpid = os.getpid()- if pid not in _OWN_START_TIME:- _OWN_START_TIME.clear()- _OWN_START_TIME[pid] = _process_start_time(pid)- return _OWN_START_TIME[pid]+ if _OWN_START is None or _OWN_START[0] != pid:+ start = _process_start_time(pid)+ if start is None:+ return None+ _OWN_START = (pid, start)+ return _OWN_START[1]def _optional_float(value: Any) -> Optional[float]:@@ -339,22 +342,18 @@ 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():- # Our own pid trivially exists; only the start-time identity check remains- # (a lease claiming our pid with a start we never had is a recycled pid).- exists = True- else:+ is_self = pid_int == os.getpid() # trivially exists; the (pid, start) identity check still applies+ if not is_self:try:from gateway.status import _pid_exists- exists = bool(_pid_exists(pid_int))+ if not _pid_exists(pid_int):+ return Falseexcept Exception:return unknown_dead- if not exists:- return Falseexpected_start = _optional_float(process_start_time)if expected_start is None:return True- current_start = _own_start_time() if pid_int == os.getpid() else _process_start_time(pid_int)+ current_start = _own_start_time() if is_self else _process_start_time(pid_int)if current_start is None:return True if lenient else Nonereturn abs(current_start - expected_start) < 0.001@@ -469,7 +468,7 @@ def _lease_entry("session_id": str(session_id),"surface": str(surface),"pid": os.getpid(),- "process_start_time": _process_start_time(os.getpid()),+ "process_start_time": _own_start_time(),"started_at": now,"updated_at": now,}diff --git a/tests/tui_gateway/test_bot_delivery_poll_throttle.py b/tests/tui_gateway/test_bot_delivery_poll_throttle.pyindex 8d638d2038d..c88128de5c4 100644--- a/tests/tui_gateway/test_bot_delivery_poll_throttle.py+++ b/tests/tui_gateway/test_bot_delivery_poll_throttle.py@@ -4,35 +4,17 @@ from __future__ import annotationsimport threadingimport time-from queue import Empty+import queueimport tui_gateway.server as serverfrom 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).+ 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 (exactly 1)."""calls: list[float] = []@@ -44,7 +26,7 @@ def test_idle_poller_throttles_bot_live_delivery_probe(monkeypatch):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())+ monkeypatch.setattr(process_registry, "completion_queue", queue.Queue())session = {"session_key": "sid-bot-delivery-throttle",@@ -66,7 +48,4 @@ def test_idle_poller_throttles_bot_live_delivery_probe(monkeypatch):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"- )+ assert len(calls) == 1, f"idle bot-delivery probe ran {len(calls)} times in ~1.2s; expected 1, not every 0.5s tick"diff --git a/tests/tui_gateway/test_bot_live_owner_delivery.py b/tests/tui_gateway/test_bot_live_owner_delivery.pyindex 638972b7ac9..a0ec4b1fd6f 100644--- a/tests/tui_gateway/test_bot_live_owner_delivery.py+++ b/tests/tui_gateway/test_bot_live_owner_delivery.py@@ -139,12 +139,11 @@ def test_failing_mailbox_poll_backs_off_and_warns_once_per_window():guarded = rebind(session_notifications._poll_bot_live_delivery_guarded, {"_poll_bot_live_delivery_once": failing, "logger": log,- "_BOT_POLL_FAILURE_BACKOFF_S": session_notifications._BOT_POLL_FAILURE_BACKOFF_S,"_BOT_POLL_WARN_INTERVAL_S": session_notifications._BOT_POLL_WARN_INTERVAL_S})session = {}- for now in (0.0, 0.5, 1.0, 6.0, 12.0, 61.0):+ for now in (0.0, 6.0, 12.0, 61.0): # the poller calls at _BOT_DELIVERY_POLL_SECONDS cadenceguarded("live", session, now)- assert len(attempts) == 4 # 0.0, 6.0, 12.0, 61.0 — the 0.5/1.0 passes sat out the backoff+ assert len(attempts) == 4warnings = [r for r in records if r.levelno == logging.WARNING]assert [r.getMessage() for r in warnings] == ["Bot live-owner delivery poll failed (0 repeat(s) suppressed since the last report)",diff --git a/tui_gateway/session_notifications.py b/tui_gateway/session_notifications.pyindex c6a25017a9f..aadd39e0e33 100644--- a/tui_gateway/session_notifications.py+++ b/tui_gateway/session_notifications.py@@ -134,8 +134,9 @@ def _notification_event_dedup_key(evt: dict) -> tuple:# Mirror gateway/kanban_watchers.py TERMINAL_KINDS: claim silent kinds (archived/unblocked) too so the cursor advances# 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 timeout+# kanban, /loop + /heartbeat and the bot mailbox share one idle-poll cadence; probing the lease registry on+# every 0.5s queue timeout cost ~a core at 11 sessions (#108005).+_KANBAN_POLL_SECONDS = _LOOP_POLL_SECONDS = _BOT_DELIVERY_POLL_SECONDS = 5.0def _notif_release_turn(session: dict) -> None:@@ -649,33 +650,31 @@ def _poll_bot_live_delivery_once(sid: str, session: dict) -> bool:return started-# A failing mailbox poll (typically the active-session registry lock unavailable under contention) retries-# every ``queue.get`` slice; back off between attempts and log the failure once per window, not per attempt.-_BOT_POLL_FAILURE_BACKOFF_S = 5.0+# A failing mailbox poll (typically the active-session registry lock unavailable under contention) is+# retried on the next ``_BOT_DELIVERY_POLL_SECONDS`` pass; log the failure once per window, not per attempt._BOT_POLL_WARN_INTERVAL_S = 60.0-def _poll_bot_live_delivery_guarded(sid: str, session: dict, now: float) -> None:- """One poller-loop pass of the mailbox poll: skipped while backing off after a failure; a failure is- logged at WARNING once per ``_BOT_POLL_WARN_INTERVAL_S`` (with the count of suppressed repeats) and at- DEBUG otherwise. An unthrottled poll logged ``Bot live-owner delivery poll failed`` ~2×/minute per session- for days, 91% of an install's WARNING output (#111719)."""- if now < session.get("_bot_poll_retry_at", 0.0):- return+def _poll_bot_live_delivery_guarded(sid: str, session: dict, now: float) -> bool:+ """One poller-loop pass of the mailbox poll. Returns True when a delivery turn was started, so the+ caller can poll again at tick cadence while the mailbox is draining. A failure is logged at WARNING+ once per ``_BOT_POLL_WARN_INTERVAL_S`` (with the count of suppressed repeats) and at DEBUG otherwise.+ An unthrottled poll logged ``Bot live-owner delivery poll failed`` ~2×/minute per session for days,+ 91% of an install's WARNING output (#111719)."""try:- _poll_bot_live_delivery_once(sid, session)+ started = _poll_bot_live_delivery_once(sid, session)except Exception:- session["_bot_poll_retry_at"] = now + _BOT_POLL_FAILURE_BACKOFF_Ssuppressed = int(session.get("_bot_poll_warn_suppressed", 0))if now - session.get("_bot_poll_warned_at", -_BOT_POLL_WARN_INTERVAL_S) < _BOT_POLL_WARN_INTERVAL_S:session["_bot_poll_warn_suppressed"] = suppressed + 1logger.debug("Bot live-owner delivery poll failed (repeat)", exc_info=True)- return+ return Falsesession["_bot_poll_warned_at"], session["_bot_poll_warn_suppressed"] = now, 0logger.warning("Bot live-owner delivery poll failed (%d repeat(s) suppressed since the last report)",suppressed, exc_info=True)- return+ return Falsesession["_bot_poll_warn_suppressed"] = 0+ return starteddef _notification_poller_loop(stop_event: threading.Event, sid: str, session: dict) -> None:@@ -702,8 +701,8 @@ def _notification_poller_scoped_loop(stop_event: threading.Event, sid: str, sesswhile not stop_event.is_set() and not session.get("_finalized"):now = time.monotonic()if now - last_bot_poll >= _BOT_DELIVERY_POLL_SECONDS:- last_bot_poll = now- _poll_bot_live_delivery_guarded(sid, session, now)+ # A mailbox that just handed out a turn drains at tick cadence; an idle one waits the full window.+ last_bot_poll = 0.0 if _poll_bot_live_delivery_guarded(sid, session, now) else 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: