wake-alarm/wake_alarm/_trigger.py
Krzysztof kuhy Rudnicki e8f50828e6 Phase 5: the power button no longer ends the alarm (item 2)
Two defences, because one press and one held press are different problems.

**Prevention — _inhibit.py.** A logind block-mode inhibitor on
handle-power-key:shutdown:idle, taken while the alarm is audible and released
in on_close(). Confirmed on the host before writing it that
PowerKeyIgnoreInhibited=no is in force, so no logind.conf drop-in is needed --
and none is added: a drop-in changes the machine permanently, an inhibitor is
scoped to the alarm.

Verified live: the inhibitor appears in `systemd-inhibit --list` as
`wake-alarm ... shutdown:idle:handle-power-key ... block` and disappears on
release.

The child runs `sleep 7200`, never `sleep infinity`. An orphaned block-mode
inhibitor would hold the power button down until reboot -- worse than the bug
being fixed -- so it self-terminates, and a stale one is cleared at startup.

That cleanup was wrong on the first attempt and the host run caught it:
`pkill -f "--who=wake-alarm"` matched the *shell that had just typed the
pattern* and killed it, leaving the real inhibitor alive (`killed 0`, one
inhibitor still listed). Substring matching is inherently self-matching. Now
it lists `pgrep -x systemd-inhibit` and confirms each pid via
/proc/<pid>/cmdline. Re-verified: orphan reaped, exactly one live inhibitor,
zero remaining after release.

**Consequence — _alarm_session.py.** The real gap was that nothing on disk
ever said "ringing, not yet dismissed": wake_state.json is written only on
dismissal, so a hard power-off left no trace and the catch-up window closed
while the machine was down. A signed record is now written at fire time, and
_trigger re-fires on one still marked ringing, ignoring the window.

Deliberately no date field. _state.py keys by UTC and
screen_locker/_wake_state.py mirrors that helper to read the very same file
from another repo, so the UTC basis there is load-bearing. The plan's
_today_str() flip is therefore NOT done -- it would have made any dismissal
between 00:00-02:00 local read as yesterday's in screen-locker and silently
lose an earned workout skip. This record carries only an aware fired_at and
compares elapsed time, so the midnight question never arises.

Age-bounded at 5400 s: an alarm that dies before dismissal leaves a record
nothing ever clears, and unbounded this would restart the alarm every minute
forever.

Two bugs the unit tests could not see, both found by running it:

- A future-stamped record returned None, i.e. "not ringing". But a backward
  clock jump is routine on a machine that hibernates nightly (NTP correcting
  after resume), so that failed *open* on exactly the escape it closes: ring
  on a fast clock, clock corrects, power-off works again. Now clamped to zero
  within a 900 s tolerance and logged.
- _alarm.py derived the correlation id from the alarm's *start* instant. On a
  catch-up or re-fire the PC would write wake-...-0735 while the phone wrote
  wake-...-0700 and the two log streams stop joining. Now
  correlation_id_for_today() derives it from the resolved alarm time, which is
  what _correlation.py always specified.

Every trigger test patched should_refire, so _decide against a real record was
untested -- which is why only the manual run found the first one. There is now
an end-to-end test that writes a real session and asserts the decision.

Splits carried: test_trigger.py 294 -> 197 + test_trigger_main.py,
test_alarm_part2.py 266 -> 170 + test_alarm_timers_flash.py. The inhibitor
handle moved into _AlarmHardware, which also settles pylint's attribute count
and puts it beside the other thing on_close() gives back.

No new suppressions: the one inline pylint disable was redundant, since
consider-using-with is already disabled repo-wide in pyproject.toml.

452 tests pass, 100% branch coverage.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EckWmyfetYq3Mi8MAnUudh
2026-08-27 20:26:37 +02:00

209 lines
7.0 KiB
Python

"""Per-minute tick that fires the morning routine at the phone's alarm time.
Run by ``wake-alarm-trigger.timer`` once a minute. Exits in milliseconds on an
ordinary tick; on the alarm minute it starts ``morning-routine.service`` and
exits.
Why a timer rather than a resident scheduler: each tick is a fresh, stateless
process, so there is no long-lived daemon to die silently and no wall-clock
jump to reason about when the machine suspends and resumes.
Why it starts the *orchestrator* and not ``wake-alarm.service``: the
orchestrator runs the alarm first and the workout lock afterwards, so the two
never fight for the fullscreen. Bypassing it is the exact failure ``CLAUDE.md``
documents. Starting an already-running unit is a no-op, which also means an
alarm currently on screen needs no extra dedupe bookkeeping.
All times are **local**. The phone stores a wall-clock H:M, so the fire instant
must be built in the same timezone the user reads off their phone.
"""
from __future__ import annotations
import argparse
from datetime import datetime, timedelta, timezone
import logging
import subprocess
import sys
from wake_alarm._alarm_session import should_refire
from wake_alarm._constants import (
ALARM_DAYS,
TRIGGER_CATCHUP_MINUTES,
TRIGGER_TARGET_UNIT,
)
from wake_alarm._logging_setup import configure_logging
from wake_alarm._state import (
was_alarm_dismissed_today,
was_workout_logged_today,
)
from wake_alarm._sync import Alarm, get_alarm
_logger = logging.getLogger(__name__)
def _now() -> datetime:
"""Return the current time as an aware datetime in the system's timezone.
Aware-and-local, not naive: the phone stores a wall-clock H:M, so the fire
instant has to be built in the timezone the user reads off their phone —
but carrying the offset explicitly keeps the comparisons unambiguous.
Returns:
The current local time, with tzinfo set. Also the seam tests patch.
"""
return datetime.now(tz=timezone.utc).astimezone()
def _fire_window(alarm: Alarm, now: datetime) -> tuple[datetime, datetime]:
"""Compute today's fire instant and the end of its catch-up window.
Args:
alarm: The resolved alarm time.
now: Current local time, used only for its date.
Returns:
A (fire_at, window_end) pair in local time.
"""
# Drop to a naive wall-clock time before substituting H:M, then let
# astimezone() re-derive the offset. Calling replace() straight on an
# aware datetime would keep *now*'s UTC offset, which is wrong across a
# DST boundary — e.g. deciding a 06:40 alarm from a 03:00 tick on the
# night the clocks move.
fire_at = (
now.replace(tzinfo=None)
.replace(hour=alarm.hour, minute=alarm.minute, second=0, microsecond=0)
.astimezone()
)
return fire_at, fire_at + timedelta(minutes=TRIGGER_CATCHUP_MINUTES)
def _skip_reason(now: datetime) -> str | None:
"""Return why the alarm must not fire right now, or None if it may.
Checks only the gates that are independent of the clock: the day gate and
the two "already handled today" gates shared with ``_alarm.py``.
Args:
now: Current local time.
Returns:
A human-readable reason, or None when nothing blocks firing.
"""
if now.weekday() not in ALARM_DAYS:
return "not an alarm day"
if was_alarm_dismissed_today():
return "alarm already dismissed today"
if was_workout_logged_today():
return "workout already logged today"
return None
def _start_target_unit() -> bool:
"""Start the morning routine unit.
Returns:
True if systemd accepted the start, False otherwise. A failure is
logged and swallowed: the next tick retries, and the catch-up window
means a transient failure does not cost the whole wake-up.
"""
cmd = ["systemctl", "--user", "start", TRIGGER_TARGET_UNIT]
try:
result = subprocess.run(cmd, check=False, capture_output=True)
except OSError:
_logger.warning("Failed to run %s", " ".join(cmd), exc_info=True)
return False
if result.returncode != 0:
_logger.warning(
"%s failed (rc=%d): %s",
" ".join(cmd),
result.returncode,
result.stderr.decode("utf-8", "replace").strip(),
)
return False
return True
def _decide(now: datetime, alarm: Alarm) -> tuple[bool, str]:
"""Decide whether this tick should fire the alarm.
Args:
now: Current local time.
alarm: The resolved alarm time.
Returns:
A (should_fire, reason) pair; *reason* explains the decision either
way and is what ``--dry-run`` prints.
"""
skip = _skip_reason(now)
if skip is not None:
return False, skip
# An alarm that was cut short -- almost always a power-button press or a
# hard power-off -- left a "ringing" session record that nothing cleared.
# It re-fires regardless of the catch-up window, because the whole point is
# that the machine may have been off for the rest of that window. The day /
# dismissed / workout gates above still apply, and the record itself is
# age-bounded, so this cannot loop forever on a crashed alarm.
if should_refire(now=now):
return True, "an earlier alarm was cut short and never dismissed"
fire_at, window_end = _fire_window(alarm, now)
if now < fire_at:
return False, f"alarm {alarm} is still ahead"
if now >= window_end:
return False, (
f"alarm {alarm} passed over "
f"{TRIGGER_CATCHUP_MINUTES} minutes ago — window closed"
)
return True, f"alarm {alarm} is due (since {fire_at:%H:%M})"
def _parse_args(argv: list[str]) -> argparse.Namespace:
"""Parse CLI arguments for the trigger."""
parser = argparse.ArgumentParser(
description="Fire the morning routine at the phone's alarm time."
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Print the decision without starting anything.",
)
return parser.parse_args(argv)
def main() -> None:
"""Entry point for one timer tick."""
configure_logging(component="trigger")
args = _parse_args(sys.argv[1:])
now = _now()
alarm = get_alarm()
should_fire, reason = _decide(now, alarm)
if args.dry_run:
verdict = "WOULD FIRE" if should_fire else "not firing"
sys.stdout.write(f"{now:%Y-%m-%d %H:%M} — {verdict}: {reason}\n")
return
if not should_fire:
_logger.debug("Not firing: %s", reason)
return
# The one moment a degraded read is worth shouting about: we are firing
# now, and the time we are firing at did not come from the phone.
if alarm.source not in {"remote", "cache"}:
_logger.warning(
"Firing on a degraded alarm source (%s) — the phone's alarm "
"could not be read; check ~/.config/wake_alarm/sync.json",
alarm.source,
)
_logger.warning("Firing %s: %s", TRIGGER_TARGET_UNIT, reason)
_start_target_unit()
if __name__ == "__main__":
main()