diff --git a/DOCS-wake-enforcement.md b/DOCS-wake-enforcement.md index 813db5f..af0ed91 100644 --- a/DOCS-wake-enforcement.md +++ b/DOCS-wake-enforcement.md @@ -67,7 +67,13 @@ lives in CMOS, so it survives however the PC goes down. 29–44 s after the alarm (FADT: "RTC can wake system from S4 = 1"). A typed `shutdown` stays a real poweroff. - `poweroff`: no logind change; relies on the firmware waking from S5. - Unverified until the host S5 test runs. + vmbox only, 2026-11-15 (`vm new --uefi`, OVMF): `rtcwake -m no -s 120` + then `systemctl poweroff` left AIE and `RTC_EN` set in CMOS, and the + guest cold-booted 12 s (guest clock) after the alarm (`result=woke`). + QEMU has no S5 wake path, so `vm wake` emulates the firmware half: this + proves the arming survives a poweroff, not that this board wakes from S5. + Host S5 firmware check dropped by kuhy 2026-11-15 (needs a physical + power-on). ### Phone stick (Tue/Wed/Thu, not free days) diff --git a/scripts/vmbox/guest_cases_v2.sh b/scripts/vmbox/guest_cases_v2.sh index 3cea23e..0a25aab 100644 --- a/scripts/vmbox/guest_cases_v2.sh +++ b/scripts/vmbox/guest_cases_v2.sh @@ -14,6 +14,10 @@ readonly RING_WAV_DIR=/usr/local/share/wake-alarm readonly SUDOERS=/etc/sudoers.d/wake-alarm readonly POWERKEY_DROPIN=/etc/systemd/logind.conf.d/wake-alarm-powerkey.conf readonly WAKEALARM=/sys/class/rtc/rtc0/wakealarm +# The repo root in the guest: `vm repo` names it after the host basename +# (~/wake-alarm, or ~/wt from a worktree), so derive it, never hard-code it. +GUEST_REPO="$(readlink -f "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/../..")" +readonly GUEST_REPO # A timer present but disabled fails silently every morning. case_v2_timers() { @@ -74,17 +78,38 @@ busy_stubs() { chmod +x "$BUSY_DIR/bin/"* } -# Hold the Dummy card's only playback substream, ignoring TERM. +# Hold the Dummy card's only playback substream as root (the ssh user has no +# ACL on a freshly loaded card), from a process that really ignores TERM: +# aplay installs its own TERM handler, so `fuser -k -TERM` would free the +# card. Returns non-zero when nothing holds it: a dead fixture must fail the +# case as a fixture, never pass for a product result. busy_hold() { + busy_release sudo modprobe -r snd-dummy >/dev/null 2>&1 || true sudo modprobe snd-dummy pcm_substreams=1 - setsid bash -c 'trap "" TERM; exec aplay -q -D plughw:CARD=Dummy,DEV=0 /dev/zero -f S16_LE -r 8000 -c 1' \ + sudo udevadm settle + local node + node="$(busy_node)" || return 1 + sudo setsid bash -c "trap '' TERM; exec 3>$node; exec sleep 600" \ >/dev/null 2>&1 & sleep 1 + # Captured, not piped: under pipefail aplay's own exit 1 fails the pipe. + local probe + probe="$(sudo aplay -q -D plughw:CARD=Dummy,DEV=0 "$RING_WAV_DIR/ring.wav" 2>&1)" || true + grep -qi busy <<<"$probe" +} + +# The Dummy card's playback node, e.g. /dev/snd/pcmC0D0p. +busy_node() { + local card + card="$(readlink /proc/asound/Dummy)" || return 1 + echo "/dev/snd/pcmC${card#card}D0p" } busy_release() { - sudo pkill -KILL -x aplay >/dev/null 2>&1 || true + local node + node="$(busy_node)" || return 0 + sudo fuser -s -k -KILL "$node" >/dev/null 2>&1 || true } # A ring_backend event in the user's log carrying $1 (started true/false). @@ -103,7 +128,10 @@ busy_run() { case_ring_busy_fallback() { local name="ring-alsa-busy-fallback" i ok=0 out busy_stubs ok - busy_hold + if ! busy_hold; then + fail "$name" "fixture: nothing holds the Dummy card" + return + fi for ((i = 1; i <= BUSY_REPS; i++)); do : >"$EVENTS" 2>/dev/null || true out="$(busy_run 4)" || true @@ -125,7 +153,10 @@ case_ring_busy_fallback() { case_ring_busy_fails_loudly() { local name="ring-alsa-busy-fails-loudly" out rc=0 busy_stubs broken - busy_hold + if ! busy_hold; then + fail "$name" "fixture: nothing holds the Dummy card" + return + fi : >"$EVENTS" 2>/dev/null || true out="$(busy_run 15)" || rc=$? busy_release @@ -183,7 +214,7 @@ case_rtc_arm() { # Last: uninstall must remove everything except the sudoers file. case_uninstall() { local name="uninstall-cleans" leftovers=() - (cd ~/wake-alarm && bash uninstall.sh >/dev/null 2>&1) || true + (cd "$GUEST_REPO" && bash uninstall.sh >/dev/null 2>&1) || true [[ -e "$RING_UNIT" ]] && leftovers+=("$RING_UNIT") [[ -e "$RING_SCRIPT" ]] && leftovers+=("$RING_SCRIPT") [[ -e "$POWERKEY_DROPIN" ]] && leftovers+=("$POWERKEY_DROPIN") diff --git a/scripts/vmbox/harness.sh b/scripts/vmbox/harness.sh index dc17fdc..aea2159 100755 --- a/scripts/vmbox/harness.sh +++ b/scripts/vmbox/harness.sh @@ -25,6 +25,11 @@ readonly SCRIPT_DIR # directory in the guest and rsync writes into /home instead of the repo. REPO_DIR="$(readlink -f "${SCRIPT_DIR}/../..")" readonly REPO_DIR +# Where `vm repo` lands the tree: ~/, so a worktree named "wt" is +# ~/wt, not ~/wake-alarm. Hard-coding the name broke every worktree run. +# shellcheck disable=SC2088 # the guest shell expands ~, not this one +GUEST_REPO="~/$(basename "$REPO_DIR")" +readonly GUEST_REPO SCRIPT_NAME="$(basename "$0")" readonly SCRIPT_NAME @@ -119,7 +124,7 @@ run_install() { # sentinel grep below matched vm's echo of the command line itself. # Hence -x: only a line that IS the sentinel counts. vm run "$VM_NAME" \ - 'cd ~/wake-alarm && bash install.sh && echo INSTALL-OK' \ + "cd $GUEST_REPO && bash install.sh && echo INSTALL-OK" \ >/tmp/wa-install.log 2>&1 || true if ! grep -qx 'INSTALL-OK' /tmp/wa-install.log; then tail -20 /tmp/wa-install.log >&2 @@ -135,7 +140,7 @@ run_cases() { step "Running the guest cases" local output output="$(vm run "$VM_NAME" \ - 'bash ~/wake-alarm/scripts/vmbox/guest_cases.sh all' 2>&1)" + "bash $GUEST_REPO/scripts/vmbox/guest_cases.sh all" 2>&1)" echo "$output" grep -q "$GUEST_OK_SENTINEL" <<<"$output" } diff --git a/wake_alarm/_ring_main.py b/wake_alarm/_ring_main.py index cf3580e..65c9c09 100644 --- a/wake_alarm/_ring_main.py +++ b/wake_alarm/_ring_main.py @@ -46,6 +46,15 @@ def main(argv: list[str] | None = None) -> int: try: while not stopping: if not backend.pump(): + # Dying mid-ring must reach the log as loudly as never starting. + emit( + "ring_backend", + "pipewire for root unit (FAILED)", + backend=backend.name, + why="pw-play stopped mid-ring", + started=False, + detail="pump failed", + ) return 1 time.sleep(_PUMP_SECONDS) finally: diff --git a/wake_alarm/_rtc.py b/wake_alarm/_rtc.py index ba069a9..369ca1a 100644 --- a/wake_alarm/_rtc.py +++ b/wake_alarm/_rtc.py @@ -46,7 +46,7 @@ from wake_alarm._events import emit, emit_on_change from wake_alarm._fallback_policy import alarm_instant from wake_alarm._logging_setup import configure_logging from wake_alarm._pc_wake_mode import read_mode -from wake_alarm._rtc_hw import arm, current_alarm, disarm_ours, read_record +from wake_alarm._rtc_hw import arm, current_alarm, disarm_ours, matches, read_record from wake_alarm._sick import alarm_stands_down, alarm_stands_down_synced from wake_alarm._sync import Alarm, get_alarm from wake_alarm._workday_penalty import cancel_for_sick_day @@ -169,7 +169,7 @@ def main(argv: list[str] | None = None) -> int: chosen = plan(now, get_alarm()) sys.stdout.write(describe(chosen)) record = read_record() - if not chosen.arm and record is not None and current_alarm() == record.epoch: + if not chosen.arm and record is not None and matches(current_alarm(), record.epoch): sys.stdout.write( f"would disarm ours: {record.epoch} for {record.target_date}\n" ) diff --git a/wake_alarm/_rtc_hw.py b/wake_alarm/_rtc_hw.py index 21eca5a..fca26ad 100644 --- a/wake_alarm/_rtc_hw.py +++ b/wake_alarm/_rtc_hw.py @@ -8,7 +8,10 @@ setting and clearing go through the NOPASSWD ``sudo -n /usr/sbin/rtcwake``. armed, so :func:`disarm_ours` only ever clears that one: an alarm someone else set (a manual ``rtcwake``) is not ours to remove. The comparison is on the sysfs value, which is epoch seconds when the RTC keeps UTC (this host: -no ``/etc/adjtime``). An RTC on local time would never match, which fails +no ``/etc/adjtime``). ``rtcwake -t`` shifts the alarm by the RTC/system clock +offset (vmbox: +1 s), so "ours" means within ``_MATCH_SLACK_SECONDS``, never +exact equality: an exact compare forgot the record and left the alarm armed. +An RTC on local time is off by whole hours and never matches, which fails safe -- the alarm is left in place, never cleared by mistake. Every process goes through ``_run``, the seam the suite replaces. @@ -28,6 +31,8 @@ _logger = logging.getLogger(__name__) RTCWAKE = "/usr/sbin/rtcwake" WAKEALARM_FILE = Path("/sys/class/rtc/rtc0/wakealarm") +# Clock offset rtcwake may add; far below the 1 h of a local-time RTC. +_MATCH_SLACK_SECONDS = 60 @dataclass(frozen=True) @@ -62,6 +67,11 @@ def current_alarm() -> int | None: return int(text) if text.isdigit() else None +def matches(pending: int | None, epoch: int) -> bool: + """Whether the pending sysfs alarm is the one armed for ``epoch``.""" + return pending is not None and abs(pending - epoch) <= _MATCH_SLACK_SECONDS + + def read_record() -> ArmedRecord | None: """What we last armed, or None.""" try: @@ -91,7 +101,7 @@ def _write_record(record: ArmedRecord | None) -> None: def arm(epoch: int, target_date: str) -> tuple[bool, str]: """Set the RTC alarm (unless it already is exactly this) and record it.""" - if current_alarm() == epoch: + if matches(current_alarm(), epoch): ok, detail = True, "already set" else: ok, detail = _rtcwake("-m", "no", "-t", str(epoch)) @@ -113,7 +123,7 @@ def disarm_ours() -> tuple[ArmedRecord | None, bool, str]: record = read_record() if record is None: return None, False, "nothing of ours armed" - if current_alarm() != record.epoch: + if not matches(current_alarm(), record.epoch): _write_record(None) return record, False, "no longer pending" ok, detail = _rtcwake("-m", "disable") diff --git a/wake_alarm/tests/test_ring_main.py b/wake_alarm/tests/test_ring_main.py index 3bc2f8c..5c5e108 100644 --- a/wake_alarm/tests/test_ring_main.py +++ b/wake_alarm/tests/test_ring_main.py @@ -50,6 +50,9 @@ def test_pump_failure_exits_1_and_stops() -> None: code, emitted = _run(backend) assert code == 1 assert "started" in emitted.call_args_list[0].args[1] + # pw-play dying mid-ring is a failure the audit must see, not silence. + assert "FAILED" in emitted.call_args.args[1] + assert emitted.call_args.kwargs["started"] is False backend.stop.assert_called_once() diff --git a/wake_alarm/tests/test_rtc_hw.py b/wake_alarm/tests/test_rtc_hw.py index 009c323..f0fc3aa 100644 --- a/wake_alarm/tests/test_rtc_hw.py +++ b/wake_alarm/tests/test_rtc_hw.py @@ -108,3 +108,27 @@ def test_real_seam() -> None: with patch.object(subprocess, "run", return_value=_done()) as run: REAL_RUN(["true"]) assert run.call_args.args[0] == ["true"] + + +def test_rtc_offset_still_matches_our_alarm() -> None: + """rtcwake shifts -t by the RTC/system clock offset (seen: +1 s).""" + with patch.object(_rtc_hw, "_run", return_value=_done()): + arm(EPOCH, "2026-10-06") + _rtc_hw.WAKEALARM_FILE.write_text(str(EPOCH + 1)) + run = MagicMock(return_value=_done()) + with patch.object(_rtc_hw, "_run", run): + assert arm(EPOCH, "2026-10-06") == (True, "already set") + record, disarmed, _ = disarm_ours() + assert (record, disarmed) == (ArmedRecord(EPOCH, "2026-10-06"), True) + assert run.call_args.args[0][-2:] == ["-m", "disable"] + + +def test_alarm_an_hour_away_is_not_ours() -> None: + with patch.object(_rtc_hw, "_run", return_value=_done()): + arm(EPOCH, "2026-10-06") + _rtc_hw.WAKEALARM_FILE.write_text(str(EPOCH + 3600)) + assert disarm_ours() == ( + ArmedRecord(EPOCH, "2026-10-06"), + False, + "no longer pending", + )