From 2a6abfda8194eb944894b5fc647778f82aa977f5 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Mon, 9 Nov 2026 04:04:21 -0600 Subject: [PATCH 1/3] fix(power-guard): detect dead systemd-inhibit child, re-engage loudly, reap on release (#6534) --- nixos/services/power-guard/power-guard.py | 90 +++++++++++++- .../services/power-guard/test_power_guard.py | 111 ++++++++++++++++++ 2 files changed, 196 insertions(+), 5 deletions(-) diff --git a/nixos/services/power-guard/power-guard.py b/nixos/services/power-guard/power-guard.py index 4eb2d178f..61d845e17 100644 --- a/nixos/services/power-guard/power-guard.py +++ b/nixos/services/power-guard/power-guard.py @@ -150,9 +150,56 @@ class Inhibitor: def __init__(self): self.proc = None + def _reap(self, proc, timeout=5): + """Wait for a child to exit so it does not remain a zombie. + + The child is already dead or has just been terminated; wait() + returns immediately in the common case. On timeout, escalate + to kill() so a wedged child cannot accumulate. + """ + try: + return proc.wait(timeout=timeout) + except subprocess.TimeoutExpired: + try: + proc.kill() + except Exception: + pass + try: + return proc.wait(timeout=timeout) + except Exception: + return proc.poll() + except Exception: + try: + return proc.poll() + except Exception: + return None + + def _dead_exit_code(self): + """Return the exit code if the real child is dead, else None. + + Never raises: a poll failure is treated as unknown, not alive, + so the caller reaps and re-engages loudly rather than + believing a lock it cannot verify. + """ + proc = self.proc + if proc is None or proc == "stub": + return None + try: + return proc.poll() + except Exception as exc: + log(f"INHIBIT child poll failed ({exc!r}); treating as dead") + return -1 + def engage(self): if self.proc is not None: - return + if self.proc == "stub": + return + rc = self._dead_exit_code() + if rc is None: + return + log(f"INHIBIT child died (exit={rc}); re-engaging") + self._reap(self.proc) + self.proc = None if NO_INHIBIT: log("INHIBIT(block sleep) [stubbed]") self.proc = "stub" @@ -168,6 +215,10 @@ def engage(self): "infinity", ], stdout=subprocess.DEVNULL, + # stderr is deliberately discarded (the child is `sleep + # infinity`, which is silent on success); the exit status + # is logged loudly on death in engage()/release() so the + # failure stays diagnosable from the journal. stderr=subprocess.DEVNULL, ) log("INHIBIT(block sleep) engaged") @@ -175,14 +226,43 @@ def engage(self): def release(self): if self.proc is None: return - if self.proc != "stub": - self.proc.terminate() + if self.proc == "stub": + self.proc = None + log("INHIBIT released") + return + proc = self.proc self.proc = None - log("INHIBIT released") + rc = None + try: + rc = proc.poll() + except Exception: + rc = None + if rc is not None: + self._reap(proc) + log(f"INHIBIT child already dead (exit={rc}); reaped") + log("INHIBIT released") + return + try: + proc.terminate() + except Exception as exc: + log(f"INHIBIT terminate failed ({exc!r}); killing") + try: + proc.kill() + except Exception: + pass + rc = self._reap(proc) + log(f"INHIBIT released (child exit={rc})") @property def held(self): - return self.proc is not None + if self.proc is None: + return False + if self.proc == "stub": + return True + try: + return self.proc.poll() is None + except Exception: + return False def main(): diff --git a/nixos/services/power-guard/test_power_guard.py b/nixos/services/power-guard/test_power_guard.py index 752bade4f..a8508d00e 100644 --- a/nixos/services/power-guard/test_power_guard.py +++ b/nixos/services/power-guard/test_power_guard.py @@ -23,6 +23,7 @@ import tempfile import time import unittest +import unittest.mock from pathlib import Path HERE = Path(__file__).resolve().parent @@ -246,5 +247,115 @@ def test_valid_small_confirm_still_fires_after_sustained_critical(self): self.assertTrue(self.marker.exists(), "sustained critical state never fired") +class FakeProc: + """Minimal Popen stand-in for Inhibitor unit tests (#6534).""" + + def __init__(self, poll_result=None): + self._poll_result = poll_result + self.terminated = False + self.killed = False + self.waited = 0 + self.wait_return = poll_result + + def poll(self): + return self._poll_result + + def wait(self, timeout=None): + self.waited += 1 + return self.wait_return + + def terminate(self): + self.terminated = True + # Simulate a clean exit after terminate for the live path. + if self._poll_result is None: + self._poll_result = -15 + self.wait_return = -15 + + def kill(self): + self.killed = True + + +class InhibitorDeadChildTests(unittest.TestCase): + """Oracle: issue #6534 acceptance — dead child detected/handled, + live child undisturbed, NO_INHIBIT stub unchanged, release reaps.""" + + def setUp(self): + self.logs = [] + self._orig_log = pg.log + pg.log = self.logs.append + self.addCleanup(setattr, pg, "log", self._orig_log) + + def test_dead_child_is_detected_and_reengaged_with_exit_logged(self): + # Repro from the issue: stub systemd-inhibit exits 1 at once. + dead = FakeProc(poll_result=1) + live = FakeProc(poll_result=None) + inh = pg.Inhibitor() + inh.proc = dead + # held must reflect poll(), not handle non-None. + self.assertFalse(inh.held) + with unittest.mock.patch.object( + pg.subprocess, "Popen", return_value=live + ) as popen: + inh.engage() + popen.assert_called_once() + self.assertIs(inh.proc, live) + self.assertTrue(inh.held) + self.assertGreaterEqual(dead.waited, 1, "dead child was not reaped") + self.assertTrue( + any("exit=1" in m for m in self.logs), + f"exit status not logged loudly: {self.logs}", + ) + + def test_live_child_is_not_disturbed(self): + live = FakeProc(poll_result=None) + inh = pg.Inhibitor() + inh.proc = live + self.assertTrue(inh.held) + with unittest.mock.patch.object(pg.subprocess, "Popen") as popen: + inh.engage() + popen.assert_not_called() + self.assertIs(inh.proc, live) + self.assertEqual(live.waited, 0) + + def test_stub_path_unchanged(self): + orig = pg.NO_INHIBIT + pg.NO_INHIBIT = True + try: + inh = pg.Inhibitor() + inh.engage() + self.assertEqual(inh.proc, "stub") + self.assertTrue(inh.held) + inh.engage() + self.assertEqual(inh.proc, "stub") + inh.release() + self.assertIsNone(inh.proc) + self.assertFalse(inh.held) + finally: + pg.NO_INHIBIT = orig + + def test_release_reaps_live_child(self): + live = FakeProc(poll_result=None) + inh = pg.Inhibitor() + inh.proc = live + inh.release() + self.assertIsNone(inh.proc) + self.assertFalse(inh.held) + self.assertTrue(live.terminated) + self.assertGreaterEqual(live.waited, 1) + + def test_release_reaps_already_dead_child(self): + dead = FakeProc(poll_result=3) + inh = pg.Inhibitor() + inh.proc = dead + inh.release() + self.assertIsNone(inh.proc) + self.assertFalse(dead.terminated, "terminate() must not run on a dead child") + self.assertGreaterEqual(dead.waited, 1) + self.assertTrue( + any("exit=3" in m for m in self.logs), + f"dead-child exit not logged on release: {self.logs}", + ) + + if __name__ == "__main__": unittest.main() From 91de65d05f5da5ae44fb563270086676d2b863fb Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Tue, 10 Nov 2026 12:45:50 -0600 Subject: [PATCH 2/3] fix(power-guard): reap stalled inhibitor child off the sampling loop (#8183) release() waited synchronously through wait(5s) + kill + wait(5s), so a stalled systemd-inhibit child blocked the sampling loop for up to ~10s and delayed a confirmed emergency sleep (CodeRabbit finding on #8025, issue #8183). - Live child: short REAP_GRACE wait inline; on timeout the kill-escalation reap finishes on a background thread while sampling continues. Timeout/kill safeguards preserved. - A release is never silently believed: the background reap logs the exit, or logs UNCONFIRMED when the child survives escalation. - held/engage account for an in-flight reap (no stacked inhibitor, lock not reported released while the child runs). - Confirmed-sleep path: main() starts the release when the state confirms, keeps sampling, and issues the sleep command only once the release has settled. - Regression test: a fake child that ignores terminate/kill exercises the non-blocking reap path in test_power_guard.py (14 tests pass). --- nixos/services/power-guard/power-guard.py | 106 ++++++++++++++++-- .../services/power-guard/test_power_guard.py | 77 +++++++++++++ 2 files changed, 176 insertions(+), 7 deletions(-) diff --git a/nixos/services/power-guard/power-guard.py b/nixos/services/power-guard/power-guard.py index 61d845e17..cc53396c4 100644 --- a/nixos/services/power-guard/power-guard.py +++ b/nixos/services/power-guard/power-guard.py @@ -31,6 +31,7 @@ import os import subprocess import sys +import threading import time SYSFS = os.environ.get("POWER_GUARD_SYSFS", "/sys/class/power_supply") @@ -93,6 +94,10 @@ def timing_from_env(name, default): EDGE_CONFIRM = timing_from_env("POWER_GUARD_EDGE_CONFIRM", "60") NO_INHIBIT = os.environ.get("POWER_GUARD_NO_INHIBIT") == "1" SLEEP_CMD = os.environ.get("POWER_GUARD_SLEEP_CMD", "systemctl hybrid-sleep") +# #8183: how long release() may wait inline for a terminated child +# before the reap moves to a background thread. The full reap used +# to block the sampling loop for up to ~10s (wait 5s, kill, wait 5s). +REAP_GRACE = 0.5 def log(msg): @@ -149,6 +154,8 @@ def sample(): class Inhibitor: def __init__(self): self.proc = None + # #8183: in-flight background reap, {"proc", "event", "rc"}. + self._pending = None def _reap(self, proc, timeout=5): """Wait for a child to exit so it does not remain a zombie. @@ -191,6 +198,13 @@ def _dead_exit_code(self): return -1 def engage(self): + if self._pending is not None: + if not self._pending["event"].is_set(): + # A previous release is still reaping; the old child + # may still hold the lock, so do not stack a second + # inhibitor on top of it (#8183). + return + self._pending = None if self.proc is not None: if self.proc == "stub": return @@ -224,12 +238,24 @@ def engage(self): log("INHIBIT(block sleep) engaged") def release(self): + """Begin releasing the inhibitor; return True once settled. + + #8183: reaping a stalled child used to block the caller for + the full wait/kill/wait sequence (~10s) inside the sampling + loop. A live child now gets a short grace wait (REAP_GRACE) + inline; if it has not exited by then, the kill-escalation + reap finishes on a background thread while sampling + continues. "Settled" means the child was reaped, or the + escalation was exhausted and logged loudly as UNCONFIRMED -- + the release is never silently believed. The confirmed-sleep + path in main() waits for settled before issuing sleep. + """ if self.proc is None: - return + return self.reap_settled() if self.proc == "stub": self.proc = None log("INHIBIT released") - return + return True proc = self.proc self.proc = None rc = None @@ -241,7 +267,7 @@ def release(self): self._reap(proc) log(f"INHIBIT child already dead (exit={rc}); reaped") log("INHIBIT released") - return + return True try: proc.terminate() except Exception as exc: @@ -250,11 +276,66 @@ def release(self): proc.kill() except Exception: pass - rc = self._reap(proc) - log(f"INHIBIT released (child exit={rc})") + try: + rc = proc.wait(timeout=REAP_GRACE) + log(f"INHIBIT released (child exit={rc})") + return True + except Exception: + pass + pending = {"proc": proc, "event": threading.Event(), "rc": None} + self._pending = pending + threading.Thread( + target=self._finish_reap, args=(pending,), daemon=True + ).start() + log( + "INHIBIT release pending: stalled child reap moved off " + "the sampling loop (#8183)" + ) + return False + + def _finish_reap(self, pending): + """Background reap: preserve the kill escalation + bounded wait.""" + proc = pending["proc"] + try: + proc.kill() + except Exception: + pass + rc = None + try: + rc = proc.wait(timeout=5) + except Exception: + try: + rc = proc.poll() + except Exception: + rc = None + pending["rc"] = rc + if rc is None: + log( + "INHIBIT release UNCONFIRMED: child still running " + "after kill escalation; not believed released (#8183)" + ) + else: + log(f"INHIBIT released (child exit={rc}, reaped in background)") + pending["event"].set() + + def reap_settled(self): + """True when no background reap is still in flight.""" + return self._pending is None or self._pending["event"].is_set() + + def poll_reap(self): + """Clear a finished background reap; called once per sample.""" + if self._pending is not None and self._pending["event"].is_set(): + self._pending = None @property def held(self): + if self._pending is not None and not self._pending["event"].is_set(): + # Reap in flight: the child may still hold the lock. + try: + if self._pending["proc"].poll() is None: + return True + except Exception: + return True if self.proc is None: return False if self.proc == "stub": @@ -269,6 +350,7 @@ def main(): inh = Inhibitor() critical_since = None edge_since = None + sleep_pending = None log( f"started: poll={POLL}s low={LOW_PCT}% crit={CRITICAL_PCT}% " f"edge={EDGE_PCT}% confirm={CONFIRM}s edge_confirm={EDGE_CONFIRM}s " @@ -276,6 +358,7 @@ def main(): ) while True: on_ac, cap, status, tte = sample() + inh.poll_reap() now = time.monotonic() discharging = (not on_ac) and status == "Discharging" and cap is not None low = discharging and (cap <= LOW_PCT or (tte is not None and tte <= 900)) @@ -291,6 +374,7 @@ def main(): ) inh.release() critical_since = edge_since = None + sleep_pending = None else: inh.engage() critical_since = critical_since if critical else None @@ -306,12 +390,20 @@ def main(): fire = f"edge sustained {now - edge_since:.0f}s at cap={cap}" elif critical_since is not None and now - critical_since >= CONFIRM: fire = f"critical sustained {now - critical_since:.0f}s at cap={cap} tte={tte}" - if fire: - log(f"CONFIRMED: {fire}; releasing inhibitor and sleeping") + if fire and sleep_pending is None: + # #8183: start the release, but do not issue the + # sleep command until the release has settled -- a + # stalled reap no longer blocks this loop, and the + # samples above keep running while it drains. + log(f"CONFIRMED: {fire}; releasing inhibitor before sleep") + sleep_pending = fire inh.release() + if sleep_pending is not None and inh.reap_settled(): + log(f"CONFIRMED: {sleep_pending}; inhibitor release settled; sleeping") subprocess.run(SLEEP_CMD, shell=True) log("sleep command issued; cooling down") critical_since = edge_since = None + sleep_pending = None time.sleep(120) time.sleep(POLL) diff --git a/nixos/services/power-guard/test_power_guard.py b/nixos/services/power-guard/test_power_guard.py index a8508d00e..fe10f3073 100644 --- a/nixos/services/power-guard/test_power_guard.py +++ b/nixos/services/power-guard/test_power_guard.py @@ -21,6 +21,7 @@ import subprocess import sys import tempfile +import threading import time import unittest import unittest.mock @@ -357,5 +358,81 @@ def test_release_reaps_already_dead_child(self): ) +class FakeStalledProc: + """Child that ignores terminate and kill (#8183 regression). + + wait() raises TimeoutExpired on the caller's grace wait, then + blocks inside the background reap until the test unblocks it, + then raises TimeoutExpired again (the kill did not work either). + """ + + def __init__(self): + self.terminated = False + self.killed = False + self.wait_calls = 0 + self.unblock = threading.Event() + + def poll(self): + return None + + def terminate(self): + self.terminated = True + + def kill(self): + self.killed = True + + def wait(self, timeout=None): + self.wait_calls += 1 + if self.wait_calls > 1: + self.unblock.wait(timeout=10) + raise subprocess.TimeoutExpired(cmd="fake-inhibit", timeout=timeout) + + +class InhibitorNonBlockingReapTests(unittest.TestCase): + """Oracle: issue #8183 acceptance -- a stalled reap must not block + the sampling loop for the full double-wait, the timeout/kill + safeguards are preserved, and the lock is not believed released + while the child is still running.""" + + def setUp(self): + self.logs = [] + self._orig_log = pg.log + pg.log = self.logs.append + self.addCleanup(setattr, pg, "log", self._orig_log) + + def test_stalled_child_reap_moves_off_the_calling_loop(self): + proc = FakeStalledProc() + inh = pg.Inhibitor() + inh.proc = proc + start = time.monotonic() + settled = inh.release() + elapsed = time.monotonic() - start + self.assertFalse(settled, "stalled reap reported settled synchronously") + self.assertLess( + elapsed, 2.0, "release() blocked on the stalled child (old path: ~10s)" + ) + self.assertTrue(proc.terminated) + self.assertIsNone(inh.proc) + self.assertFalse(inh.reap_settled(), "sleep could fire before release settles") + self.assertTrue(inh.held, "lock believed released while child still runs") + # Sampling continues while the reap is pending; once the + # background escalation finishes, the release settles, the + # kill safeguard has run, and the unconfirmed exit is loud. + proc.unblock.set() + deadline = time.time() + 5 + while not inh.reap_settled() and time.time() < deadline: + inh.poll_reap() + time.sleep(0.01) + self.assertTrue(inh.reap_settled()) + self.assertTrue(proc.killed, "kill escalation was not preserved") + self.assertGreaterEqual(proc.wait_calls, 2) + inh.poll_reap() + self.assertFalse(inh.held) + self.assertTrue( + any("UNCONFIRMED" in m for m in self.logs), + f"unconfirmed release not logged loudly: {self.logs}", + ) + + if __name__ == "__main__": unittest.main() From 718b96d02e9859b799a764359db2dc5e0b6e1ebb Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Sat, 14 Nov 2026 15:15:03 -0600 Subject: [PATCH 3/3] fix(power-guard): no re-engage while sleep is pending; log recovery on a dead child handle Shepherd fixes for the two remaining CodeRabbit items on PR #8025 (task 17249): 1. main() no longer calls engage() while a sleep is pending on the inhibitor release settling: once the background reap settled, engage() would start a fresh block-mode inhibitor in the same iteration that then issued the sleep command (re-review thread 4511572429). 2. The recovery log in main() now fires when a child handle exists, not only while held: a child that died since the last sample reads held=False, but the recovery and its reaping release still happen and belong in the journal with the battery readings (thread 4511572453). Full suite: python3 -I nixos/services/power-guard/test_power_guard.py -> 14 tests OK. --- nixos/services/power-guard/power-guard.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/nixos/services/power-guard/power-guard.py b/nixos/services/power-guard/power-guard.py index cc53396c4..3269f6fa9 100644 --- a/nixos/services/power-guard/power-guard.py +++ b/nixos/services/power-guard/power-guard.py @@ -368,7 +368,13 @@ def main(): edge = discharging and cap <= EDGE_PCT if not low: - if inh.held: + # Log recovery whenever a child handle exists, not only + # while held: a child that died since the last sample + # reads held=False, but the recovery (and the release + # below, which reaps it) still happened and belongs in + # the journal with the battery readings (PR #8025 + # review, thread 4511572453). + if inh.held or inh.proc is not None: log( f"recovered (ac={on_ac} cap={cap} status={status} tte={tte}); releasing" ) @@ -376,7 +382,12 @@ def main(): critical_since = edge_since = None sleep_pending = None else: - inh.engage() + if sleep_pending is None: + inh.engage() + # While a sleep is pending on the inhibitor release + # settling, engaging would stack a fresh block lock + # directly in front of the sleep command once the reap + # settles (PR #8025 re-review, thread 4511572429). critical_since = critical_since if critical else None if critical and critical_since is None: critical_since = now