run_idle_gates.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. """Idle gates for the gateway's per-profile pollers (heartbeat restore, handoff watcher, loop wakeup).
  2. Entering ``_profile_runtime_scope`` costs a config.yaml load, a ``.env`` parse, secret hydration and a
  3. terminal-policy build; on a multiplex gateway the pollers paid that per profile per tick with nothing
  4. to do. Each gate answers "does this profile's store hold work?" from the goals-cached SessionDB with
  5. ONLY the HERMES_HOME contextvar installed. Every gate fails OPEN: an unavailable store, a failing
  6. read or a corrupt row is "cannot prove emptiness", never "idle".
  7. """
  8. from __future__ import annotations
  9. import logging
  10. from pathlib import Path
  11. from typing import Any, Callable, Optional
  12. logger = logging.getLogger("gateway.run")
  13. def _profile_session_db_probe(profile_home: Path) -> Optional[Any]:
  14. """The goals-cached SessionDB for *profile_home*; None when unavailable."""
  15. from hermes_cli.goals import _get_session_db
  16. from hermes_constants import reset_hermes_home_override, set_hermes_home_override
  17. token = set_hermes_home_override(str(profile_home))
  18. try:
  19. return _get_session_db()
  20. except Exception:
  21. logger.debug("session-db probe failed for %s", profile_home, exc_info=True)
  22. return None
  23. finally:
  24. reset_hermes_home_override(token)
  25. def _gate(profile_home: Path, store_has_work: Callable[[Any], bool]) -> bool:
  26. db = _profile_session_db_probe(profile_home)
  27. if db is None:
  28. return True
  29. try:
  30. return store_has_work(db)
  31. except Exception:
  32. logger.debug("idle probe failed for %s; keeping the full sweep", profile_home, exc_info=True)
  33. return True
  34. def profile_has_active_heartbeat(profile_home: Path) -> bool:
  35. from hermes_cli.heartbeat import store_has_active_heartbeat
  36. return _gate(profile_home, store_has_active_heartbeat)
  37. def profile_has_active_loop(profile_home: Path) -> bool:
  38. from hermes_cli.loops import store_has_active_loop
  39. return _gate(profile_home, store_has_active_loop)
  40. def profile_has_pending_handoff(profile_home: Path) -> bool:
  41. return _gate(profile_home, lambda db: db.has_pending_handoffs())
  42. async def off_loop_gate(runner: object, probe: Callable[[], bool]) -> bool:
  43. """Run a sync gate through the runner's executor hop. Runners without one (bare test stand-ins
  44. for the handoff watcher) keep the historical always-enter behaviour."""
  45. offload = getattr(runner, "_run_in_executor_with_context", None)
  46. if not callable(offload):
  47. return True
  48. return bool(await offload(probe))