sleep_clock.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. """Clocks that stop while the computer sleeps.
  2. A laptop that sleeps in the middle of a request freezes Hermes and the local model server
  3. together. Timers measured on the wall clock or on Python's ``time.monotonic`` on Windows keep
  4. counting through the sleep, so every stall watchdog fires the moment the machine wakes and kills
  5. work that was about to continue. Watchdogs that judge "no progress" use these clocks instead.
  6. """
  7. from __future__ import annotations
  8. import sys
  9. import time
  10. from collections.abc import Callable
  11. _SLEEP_THRESHOLD_S = 5.0
  12. def _windows_unbiased_clock() -> Callable[[], float] | None:
  13. """The unbiased interrupt time in seconds, or None where kernel32 lacks it."""
  14. try:
  15. import ctypes
  16. query = ctypes.windll.kernel32.QueryUnbiasedInterruptTime
  17. except (AttributeError, OSError):
  18. return None
  19. def clock() -> float:
  20. value = ctypes.c_ulonglong(0)
  21. query(ctypes.byref(value))
  22. return value.value / 10_000_000
  23. return clock
  24. #: Seconds the machine has spent awake, from an arbitrary start. Windows: the unbiased interrupt
  25. #: time, which excludes sleep and hibernation. Linux and macOS: ``time.monotonic``, which already
  26. #: stops during suspend there.
  27. awake_seconds: Callable[[], float] = (
  28. (_windows_unbiased_clock() if sys.platform == "win32" else None) or time.monotonic)
  29. class SleepWatch:
  30. """Reports how long this process was stopped since the last check, for a caller that checks
  31. every ``interval`` seconds: the wall time past one interval. That covers a machine that slept
  32. and a process that Modern Standby froze, without relying on how any clock treats either.
  33. Gaps under five seconds (clock sync, scheduling noise) don't count.
  34. """
  35. def __init__(self, interval: float) -> None:
  36. self._interval = interval
  37. self._wall = time.time()
  38. def slept(self) -> float:
  39. """Seconds stopped since the previous call, or 0.0."""
  40. wall = time.time()
  41. stopped, self._wall = wall - self._wall - self._interval, wall
  42. return stopped if stopped >= _SLEEP_THRESHOLD_S else 0.0