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>
216 lines
7.2 KiB
Python
216 lines
7.2 KiB
Python
"""The worker's sleep inhibitor (inhibit.py): a fake ``systemd-inhibit`` that
|
|
runs its command (the lock child) or refuses like polkit does."""
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import subprocess
|
|
import time
|
|
|
|
import pytest
|
|
|
|
import inhibit
|
|
import pids
|
|
|
|
|
|
def _fake(tmp_path: pathlib.Path, body: str) -> str:
|
|
p = tmp_path / "systemd-inhibit"
|
|
p.write_text("#!/bin/sh\n" + body + "\n")
|
|
p.chmod(0o755)
|
|
return str(p)
|
|
|
|
|
|
@pytest.fixture
|
|
def ok_bin(tmp_path):
|
|
# drop the --flags, exec the command — like the real one, the lock child
|
|
# (`cat`) lives as long as its stdin stays open
|
|
return _fake(tmp_path, 'while [ "${1#--}" != "$1" ]; do shift; done\nexec "$@"')
|
|
|
|
|
|
@pytest.fixture
|
|
def denied_bin(tmp_path):
|
|
return _fake(tmp_path, 'echo "Failed to inhibit: Access denied" >&2; exit 1')
|
|
|
|
|
|
def _gone(pid: int) -> bool:
|
|
try:
|
|
os.kill(pid, 0)
|
|
except ProcessLookupError:
|
|
return True
|
|
return pids._proc_state(pid) == "Z"
|
|
|
|
|
|
def _wait(cond, timeout=3.0):
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
if cond():
|
|
return True
|
|
time.sleep(0.02)
|
|
return cond()
|
|
|
|
|
|
def test_engage_and_release(ok_bin):
|
|
live = ["s1"]
|
|
inh = inhibit.SleepInhibitor(True, lambda: live, binary=ok_bin, platform="linux")
|
|
assert inh.status() == {"enabled": True, "available": True, "engaged": False}
|
|
assert inh.sync() is True
|
|
proc = inh._proc
|
|
assert proc is not None and proc.poll() is None
|
|
assert inh.sync() is True and inh._proc is proc # idempotent
|
|
live.clear()
|
|
assert inh.sync() is False
|
|
assert not inh.engaged and inh._proc is None
|
|
assert proc.returncode is not None # waited on: no zombie
|
|
assert _gone(proc.pid)
|
|
|
|
|
|
def test_lock_child_restarted_if_it_dies(ok_bin):
|
|
inh = inhibit.SleepInhibitor(True, lambda: ["s"], binary=ok_bin, platform="linux")
|
|
inh.sync()
|
|
first = inh._proc
|
|
first.kill()
|
|
first.wait()
|
|
assert inh.sync() is True and inh._proc is not first
|
|
inh.stop()
|
|
|
|
|
|
@pytest.mark.parametrize("platform", ["darwin", "win32"])
|
|
def test_not_linux_is_a_noop(ok_bin, platform):
|
|
inh = inhibit.SleepInhibitor(True, lambda: ["s"], binary=ok_bin, platform=platform)
|
|
assert inh.status() == {"enabled": False, "available": False, "engaged": False}
|
|
assert inh.sync() is False
|
|
inh.start()
|
|
assert inh._thread is None
|
|
inh.stop()
|
|
|
|
|
|
def test_disabled_by_config(ok_bin):
|
|
inh = inhibit.SleepInhibitor(False, lambda: ["s"], binary=ok_bin, platform="linux")
|
|
assert inh.sync() is False and not inh.status()["enabled"]
|
|
|
|
|
|
def test_missing_binary():
|
|
inh = inhibit.SleepInhibitor(True, lambda: ["s"], binary="no-such-systemd-inhibit-x",
|
|
platform="linux")
|
|
st = inh.status()
|
|
assert st["enabled"] and not st["available"] and not st["engaged"]
|
|
assert "not found" in st["reason"]
|
|
assert inh.sync() is False
|
|
inh.poke()
|
|
inh.start()
|
|
assert inh._thread is None
|
|
|
|
|
|
def test_logind_refusal_is_reported_and_backed_off(denied_bin, monkeypatch):
|
|
calls = []
|
|
real = subprocess.Popen
|
|
monkeypatch.setattr(inhibit.subprocess, "Popen",
|
|
lambda *a, **k: calls.append(a) or real(*a, **k))
|
|
inh = inhibit.SleepInhibitor(True, lambda: ["s"], binary=denied_bin, platform="linux")
|
|
assert inh.sync() is False
|
|
st = inh.status()
|
|
assert st == {"enabled": True, "available": False, "engaged": False,
|
|
"reason": "Failed to inhibit: Access denied"}
|
|
assert inh.sync() is False
|
|
assert len(calls) == 1 # retried only after RETRY_S
|
|
|
|
|
|
def test_idle_release_after_run_exits(ok_bin, tmp_path, monkeypatch):
|
|
"""The background loop drops the lock once the last run's process is gone,
|
|
with nobody polling /sessions — the real pids.list_live on a real run."""
|
|
monkeypatch.setattr(pids, "LOG_DIR", tmp_path)
|
|
monkeypatch.setattr(inhibit, "ENGAGED_S", 0.05)
|
|
monkeypatch.setattr(inhibit, "IDLE_S", 0.05)
|
|
run = subprocess.Popen(["sleep", "0.4"], start_new_session=True)
|
|
pids._procs["run1"] = run
|
|
(tmp_path / "run1.pid").write_text(json.dumps(
|
|
{"pid": run.pid, "starttime": pids._proc_starttime(run.pid)}))
|
|
assert pids.list_live() == ["run1"]
|
|
|
|
inh = inhibit.SleepInhibitor(True, pids.list_live, binary=ok_bin, platform="linux")
|
|
inh.start()
|
|
try:
|
|
assert _wait(lambda: inh.engaged)
|
|
lock = inh._proc
|
|
assert _wait(lambda: not inh.engaged, timeout=5)
|
|
assert pids.list_live() == []
|
|
assert not (tmp_path / "run1.pid").exists() # stale pidfile dropped
|
|
assert lock.returncode is not None and _gone(lock.pid)
|
|
finally:
|
|
inh.stop()
|
|
pids._procs.pop("run1", None)
|
|
assert inh._thread is None
|
|
|
|
|
|
def test_poke_engages_without_waiting_for_the_loop(ok_bin, monkeypatch):
|
|
monkeypatch.setattr(inhibit, "IDLE_S", 60.0)
|
|
live: list = []
|
|
inh = inhibit.SleepInhibitor(True, lambda: live, binary=ok_bin, platform="linux")
|
|
inh.start()
|
|
try:
|
|
time.sleep(0.1)
|
|
live.append("s")
|
|
inh.poke()
|
|
assert _wait(lambda: inh.engaged, timeout=2)
|
|
finally:
|
|
inh.stop()
|
|
|
|
|
|
def test_stop_releases(ok_bin):
|
|
inh = inhibit.SleepInhibitor(True, lambda: ["s"], binary=ok_bin, platform="linux")
|
|
inh.start()
|
|
assert _wait(lambda: inh.engaged)
|
|
lock = inh._proc
|
|
inh.stop()
|
|
assert not inh.engaged and lock.returncode is not None and _gone(lock.pid)
|
|
|
|
|
|
def test_lock_dies_with_its_pipe(ok_bin):
|
|
"""If the sidecar dies without a teardown, the closed pipe ends the lock."""
|
|
inh = inhibit.SleepInhibitor(True, lambda: ["s"], binary=ok_bin, platform="linux")
|
|
inh.sync()
|
|
proc = inh._proc
|
|
proc.stdin.close() # what the kernel does when we die
|
|
assert proc.wait(timeout=3) == 0
|
|
inh.stop()
|
|
|
|
|
|
def test_live_check_failure_never_raises(ok_bin):
|
|
def boom():
|
|
raise OSError("disk gone")
|
|
inh = inhibit.SleepInhibitor(True, boom, binary=ok_bin, platform="linux")
|
|
assert inh.sync() is False
|
|
|
|
|
|
def test_health_reports_it(ok_bin, monkeypatch):
|
|
import routes_accounts
|
|
inh = inhibit.SleepInhibitor(True, lambda: ["s"], binary=ok_bin, platform="linux")
|
|
monkeypatch.setattr(inhibit, "INHIBITOR", inh)
|
|
assert routes_accounts.health()["sleepInhibitor"] == {
|
|
"enabled": True, "available": True, "engaged": False}
|
|
inh.sync()
|
|
try:
|
|
assert routes_accounts.health()["sleepInhibitor"]["engaged"] is True
|
|
finally:
|
|
inh.stop()
|
|
assert routes_accounts.health()["sleepInhibitor"]["engaged"] is False
|
|
|
|
|
|
def test_default_config(monkeypatch):
|
|
import importlib
|
|
import config
|
|
monkeypatch.delenv("SIDECAR_INHIBIT_SLEEP", raising=False)
|
|
try:
|
|
for token, plat, want in (("", "linux", True), ("t", "linux", False),
|
|
("", "darwin", False)):
|
|
monkeypatch.setenv("SIDECAR_TOKEN", token)
|
|
monkeypatch.setattr("sys.platform", plat)
|
|
assert importlib.reload(config).INHIBIT_SLEEP is want
|
|
monkeypatch.setenv("SIDECAR_TOKEN", "")
|
|
monkeypatch.setattr("sys.platform", "linux")
|
|
monkeypatch.setenv("SIDECAR_INHIBIT_SLEEP", "0")
|
|
assert importlib.reload(config).INHIBIT_SLEEP is False
|
|
finally:
|
|
monkeypatch.undo()
|
|
importlib.reload(config)
|