active_lease_io.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. """Active-session lease releases off the gateway event loop.
  2. ``ActiveSessionLease.release()`` takes the registry's file lock, re-reads and prunes the JSON (a
  3. liveness probe per entry) and atomically rewrites it. Every turn end ran it on the loop, a measured
  4. recurring stall with many turns finishing. Only that file write is deferred: the lease leaves this
  5. process's view of the registry before ``release_soon`` returns (``mark_release_queued``), so the
  6. next claim on the loop -- another session at ``max_concurrent_sessions``, or a Desktop/TUI writer
  7. taking over this session -- sees the slot free, exactly as when the release ran inline. Releases
  8. go to ONE worker so the durable drops land in turn-end order. The lease pinned its registry path
  9. at acquisition, so the worker needs no profile scope.
  10. """
  11. from __future__ import annotations
  12. import concurrent.futures
  13. import logging
  14. import threading
  15. logger = logging.getLogger(__name__)
  16. _pool: concurrent.futures.ThreadPoolExecutor | None = None
  17. _pool_lock = threading.Lock()
  18. def release_soon(lease) -> None:
  19. """Retire *lease* from this process's registry view now and queue its durable release."""
  20. global _pool
  21. from hermes_cli.active_sessions import mark_release_queued
  22. mark_release_queued(lease)
  23. with _pool_lock:
  24. if _pool is None:
  25. _pool = concurrent.futures.ThreadPoolExecutor(max_workers=1, thread_name_prefix="active-lease-io")
  26. pool = _pool
  27. pool.submit(_release, lease)
  28. def _release(lease) -> None:
  29. try:
  30. lease.release()
  31. except Exception:
  32. logger.debug("Failed to release active session slot", exc_info=True)