web_server_idle_proof.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. """Diagnostic work snapshot for a Desktop-pooled ``hermes serve`` child.
  2. Reads process admission, session/worker, delegation, cron and human-input ledgers. Unreadable
  3. state is indeterminate, never idle. This snapshot alone is NOT permission to retire: only
  4. ``backend_retirement.RetirementFence.prepare`` freezes admission before taking the snapshot,
  5. and only a confirmed commit permits the client to stop that exact backend generation.
  6. The separate messaging gateway process owns its own lifecycle and drain protocol.
  7. """
  8. from __future__ import annotations
  9. import logging
  10. from typing import Callable, Optional
  11. from hermes_cli.web_server_idle_exit import busy_ledger
  12. _log = logging.getLogger(__name__)
  13. _input_probe_failure_logged = False
  14. def pending_human_input() -> Optional[int]:
  15. """Count of prompts waiting on a human (clarify/approval/sudo/secret requests plus queued
  16. gateway approvals); ``None`` when a ledger cannot be read."""
  17. global _input_probe_failure_logged
  18. try:
  19. from tui_gateway import server_requests
  20. from tools.approval import pending_gateway_approval_count
  21. return server_requests.open_request_count() + pending_gateway_approval_count()
  22. except Exception:
  23. if not _input_probe_failure_logged:
  24. _input_probe_failure_logged = True
  25. _log.warning("idle-proof input probe unavailable; this backend will report indeterminate",
  26. exc_info=True)
  27. return None
  28. def idle_proof(turn_probe: Callable[[], bool | str | None] = busy_ledger,
  29. input_probe: Callable[[], Optional[int]] = pending_human_input) -> dict:
  30. """``{"idle": True | False | None, "reason": str | None}`` plus ``"detail"`` naming the busy ledger.
  31. ``True`` only when no turn is in flight (session table AND cron ledger) and nothing is waiting
  32. on a human. ``None`` whenever either probe is indeterminate — the caller treats it exactly like
  33. busy. ``turn_probe`` may answer with a bool or with :func:`busy_ledger`'s name; the name is
  34. surfaced as ``detail`` so a backend that refuses to retire says which work it is protecting.
  35. """
  36. turn = turn_probe()
  37. if turn is None:
  38. return {"idle": None, "reason": "turn_probe_unavailable"}
  39. if turn:
  40. return {"idle": False, "reason": "turn_in_flight", "detail": turn if isinstance(turn, str) else None}
  41. pending = input_probe()
  42. if pending is None:
  43. return {"idle": None, "reason": "input_probe_unavailable"}
  44. if pending:
  45. return {"idle": False, "reason": "awaiting_human_input"}
  46. return {"idle": True, "reason": None}