Files
ai-agent/sidecar/inhibit.py
gabrielvidalandClaude Opus 5.5 4d79a4a44f feat(sidecar): hold a logind sleep lock on a Linux worker while a run is live
The EVOX2 auto-suspends on input idle and a busy GPU doesn't count, so a
long run there died with the box. sidecar/inhibit.py holds a
`systemd-inhibit --what=sleep --mode=block` lock while pids.list_live() is
non-empty: poked on /spawn, /resume and /fork, re-checked by a small loop
(5 s held, 15 s idle) so it drops right after the last run ends, released
at lifespan teardown. The lock child is `cat` on a pipe we hold, so it also
dies if the sidecar is killed (KillMode=process would otherwise leak it).

On by default on a Linux worker (SIDECAR_INHIBIT_SLEEP=0|1), a no-op on
macOS, without the binary, or when logind/polkit refuses (reported, retried
every minute). /health reports sleepInhibitor {enabled, available, engaged}.
worker/README documents the polkit rule a service-started worker needs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 22:06:45 +01:00

223 lines
8.2 KiB
Python

"""
Keep a Linux worker awake while it has a live agent run.
The EVOX2 auto-suspends on *input* idle (GDM's ``gsd-power``): a busy CPU or
GPU doesn't count, so an hour-long run there was killed by the box falling
asleep under it. While at least one run is live (``pids.list_live()``) the
sidecar holds a systemd-logind ``sleep`` **block** inhibitor, and drops it as
soon as the last run ends — so the box still sleeps when it is really idle.
The same pattern as the brain's (``~/projects/brain/brain/inhibit.py``).
Mechanism: ``systemd-inhibit --what=sleep --mode=block … cat`` holds the lock
for its own lifetime. The child is ``cat`` on a pipe we hold, not ``sleep
infinity``: the sidecar's unit runs with ``KillMode=process`` (runs survive its
restarts), so a lock child would survive a crash of the sidecar too — with
``cat``, our end of the pipe closes whenever this process dies, however it
dies, ``cat`` reads EOF and exits, and the lock goes with it. A release closes
the pipe, then signals the lock's own process group and *waits* on it: no
zombie, no orphaned grandchild.
When does it change: right after ``/spawn`` and ``/resume`` (``poke``), and
from a small background loop (every ``ENGAGED_S`` while held, ``IDLE_S``
otherwise) that releases it once the runs are gone even if nothing polls
``/sessions``. The lifespan teardown releases it.
Graceful no-op: not Linux, ``SIDECAR_INHIBIT_SLEEP=0``, no ``systemd-inhibit``,
or logind refusing the lock (no system D-Bus, or polkit denying a
non-interactive user ``org.freedesktop.login1.inhibit-block-sleep`` — see
worker/README) — logged once, reported in ``/health``'s ``sleepInhibitor``,
retried every ``RETRY_S`` in case it was fixed. Stdlib only.
"""
from __future__ import annotations
import os
import shutil
import signal
import subprocess
import sys
import threading
import time
from typing import Callable
WHO = "ai-agent-worker"
WHY = "active agent runs"
ENGAGED_S = 5.0 # loop period while the lock is held
IDLE_S = 15.0 # …and while it isn't (spawn/resume poke it at once)
RETRY_S = 60.0 # after logind refused the lock
PROBE_S = 0.4 # how long a just-started lock child must survive
def _log(msg: str) -> None:
print(f"[inhibit] {msg}", flush=True)
class SleepInhibitor:
def __init__(self, enabled: bool, live: Callable[[], list], *,
binary: str = "systemd-inhibit", platform: str = sys.platform) -> None:
self.enabled = bool(enabled) and platform == "linux"
self._live = live
self._bin = shutil.which(binary) if self.enabled else None
self._proc: subprocess.Popen | None = None
self._lock = threading.RLock()
self._wake = threading.Event()
self._stop = threading.Event()
self._thread: threading.Thread | None = None
self._denied_until = 0.0
self.reason: str | None = None if self._bin or not self.enabled else (
f"{binary} not found")
if self.enabled and not self._bin:
_log(f"{binary} not found — the machine may suspend mid-run")
# ---- state -------------------------------------------------------------
@property
def available(self) -> bool:
return bool(self.enabled and self._bin and self.reason is None)
@property
def engaged(self) -> bool:
with self._lock:
return self._proc is not None and self._proc.poll() is None
def status(self) -> dict:
out = {"enabled": self.enabled, "available": self.available,
"engaged": self.engaged}
if self.reason:
out["reason"] = self.reason
return out
# ---- engage / release ----------------------------------------------------
def sync(self) -> bool:
"""Hold the lock iff a run is live. Never raises. Returns ``engaged``."""
if not self.enabled or not self._bin:
return False
try:
active = bool(self._live())
except Exception as e: # noqa: BLE001 — a bad pid scan never crashes the loop
_log(f"live-run check failed: {e!r}")
return self.engaged
with self._lock:
if active:
self._engage()
else:
self._release()
return self.engaged
def _engage(self) -> None:
if self._proc is not None:
if self._proc.poll() is None:
return
self._reap() # the lock child died on its own: restart it
if time.monotonic() < self._denied_until:
return
try:
proc = subprocess.Popen(
[self._bin, "--what=sleep", f"--who={WHO}", f"--why={WHY}",
"--mode=block", "cat"],
stdin=subprocess.PIPE, stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE, start_new_session=True, close_fds=True)
except OSError as e:
self._refused(repr(e))
return
deadline = time.monotonic() + PROBE_S
while time.monotonic() < deadline and proc.poll() is None:
time.sleep(0.05)
if proc.poll() is not None: # logind / polkit said no
err = b""
try:
err = proc.stderr.read() if proc.stderr else b""
except OSError:
pass
self._close(proc)
self._refused(err.decode(errors="replace").strip()
or f"exit {proc.returncode}")
return
if proc.stderr:
proc.stderr.close() # nothing more to read; no fd kept
self._proc = proc
if self.reason:
_log("lock accepted again")
self.reason = None
_log("sleep inhibitor engaged (live agent runs)")
def _refused(self, why: str) -> None:
self._denied_until = time.monotonic() + RETRY_S
if why != self.reason:
_log(f"could not take the sleep lock: {why}")
self.reason = why[:300]
def _release(self) -> None:
if self._proc is None:
return
self._reap()
_log("sleep inhibitor released (no live runs)")
def _reap(self) -> None:
"""Stop the lock child (if still up) and wait on it — always."""
proc, self._proc = self._proc, None
if proc is not None:
self._close(proc)
@staticmethod
def _close(proc: subprocess.Popen) -> None:
for f in (proc.stdin, proc.stderr):
try:
if f:
f.close() # EOF to `cat`: it exits, the lock goes
except OSError:
pass
for sig, wait in ((signal.SIGTERM, 2.0), (signal.SIGKILL, 2.0)):
if proc.poll() is not None:
break
try:
os.killpg(proc.pid, sig)
except OSError:
pass
try:
proc.wait(timeout=wait)
except subprocess.TimeoutExpired:
continue
try:
proc.wait(timeout=0.5)
except subprocess.TimeoutExpired:
pass
# ---- the loop --------------------------------------------------------------
def poke(self) -> None:
"""A run just started (or stopped): re-check now, without blocking."""
if self.enabled and self._bin:
self._wake.set()
def _run(self) -> None:
while not self._stop.is_set():
self.sync()
self._wake.wait(ENGAGED_S if self.engaged else IDLE_S)
self._wake.clear()
def start(self) -> None:
if not self.enabled or not self._bin or self._thread is not None:
return
self._stop.clear()
self._thread = threading.Thread(target=self._run, name="sleep-inhibit",
daemon=True)
self._thread.start()
def stop(self) -> None:
"""Lifespan teardown: end the loop, drop the lock."""
self._stop.set()
self._wake.set()
t, self._thread = self._thread, None
if t is not None:
t.join(timeout=5)
with self._lock:
self._reap()
def _make() -> SleepInhibitor:
import pids # noqa: PLC0415
from config import INHIBIT_SLEEP # noqa: PLC0415
return SleepInhibitor(INHIBIT_SLEEP, pids.list_live)
INHIBITOR = _make()