Say every reason a lock decision had, not just the first one
Some checks failed
pre-commit / pre-commit (push) Has been cancelled
Tests / test (3.10) (push) Has been cancelled
Tests / test (3.11) (push) Has been cancelled
Tests / test (3.12) (push) Has been cancelled
Tests / lock-popup-safety (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled

The decision ladders are first-match-wins: the matching branch calls
sys.exit(0), so no later condition is ever evaluated or recorded. That made

    DECISION lock=no reason=early_bird_window_active

ambiguous in the one way that matters -- it cannot say whether the workout was
also already done, or the weekly minimum already met. Reading it, the 08:30
re-check looks like it is about to lock a machine that has nothing left to
prove, and the only way to find out was to re-derive the ladder by hand.

Keep the acting reason exactly as it was: it is the branch that actually
controlled behaviour, and it stays a stable grep-able slug that can be counted
across runs. Add the conditions that also held as an "also=" extra, which
as_line() already renders as key=value. A decision with a single reason still
renders the line it always did, so the common case needs no new format.

Only side-effect-free predicates are collected. _try_auto_upgrade_* writes log
entries and does ADB/network work, and _save_early_bird_pending writes state;
running either to produce a log line would turn a reporting change into a
state mutation in the enforcer. Verified that annotating leaves log.json and
early_bird_pending.json byte-identical.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PCUN9mdfJzJXqEZatHnUCD
This commit is contained in:
Krzysztof Rudnicki 2026-08-23 07:02:41 +02:00
parent 7b61619a7a
commit 589b9e227d
4 changed files with 205 additions and 5 deletions

View File

@ -13,7 +13,9 @@ import sys
from screen_locker import _sick_tracker
from screen_locker._decision_log import LockDecision, record_decision
from screen_locker._decision_reasons import reasons_extra
from screen_locker._wake_state import has_workout_skip_today
from screen_locker._weekly_check import has_weekly_minimum, is_relaxed_day
_logger = logging.getLogger(__name__)
@ -32,7 +34,37 @@ def _skip(reason: str, detail: str, **extra: object) -> None:
sys.exit(0)
class AutoUpgradeMixin:
class _ReasonsMixin:
"""Supplies the side-effect-free conditions that annotate a decision.
The ladder below is first-match-wins, so only the acting reason was ever
recorded. These predicates let a line also name the conditions that held
but were never reached -- notably "the workout is already logged" hiding
behind "the early-bird window is open".
"""
def _other_conditions(self, acting: str) -> dict[str, object]:
"""Return the ``also=`` extra naming every other condition that holds.
Strictly read-only. ``_try_auto_upgrade_*`` and
``_save_early_bird_pending`` are deliberately absent: they write log
entries and state, and must never run to produce a log line.
"""
return reasons_extra(
acting,
{
"scheduled_skip_day": self._is_scheduled_skip_today,
"early_bird_window_active": self._is_early_bird_pending,
"sick_day": self._is_sick_day_today,
"workout_logged_today": self.has_logged_today,
"wake_alarm_skip": has_workout_skip_today,
"relaxed_day": is_relaxed_day,
"weekly_minimum_met": lambda: has_weekly_minimum(self.log_file),
},
)
class AutoUpgradeMixin(_ReasonsMixin):
"""Handles today-state detection and silent log-entry upgrading.
Relies on methods from EarlyBirdMixin, PhoneVerificationMixin,
@ -71,6 +103,7 @@ class AutoUpgradeMixin:
"Early bird window still active — deferring to the 08:30/09:05 "
"re-check timer.",
recheck_by="early-bird-workout-check.timer",
**self._other_conditions("early_bird_window_active"),
)
elif self._is_sick_day_today():
if self._try_auto_upgrade_sick_day():
@ -79,11 +112,23 @@ class AutoUpgradeMixin:
"Auto-upgraded today's sick_day entry to phone_verified.",
)
else:
_skip("sick_day", "Sick day already logged today.")
_skip(
"sick_day",
"Sick day already logged today.",
**self._other_conditions("sick_day"),
)
elif self.has_logged_today():
_skip("workout_logged_today", "Workout already logged today.")
_skip(
"workout_logged_today",
"Workout already logged today.",
**self._other_conditions("workout_logged_today"),
)
elif has_workout_skip_today():
_skip("wake_alarm_skip", "Wake alarm earned a workout skip.")
_skip(
"wake_alarm_skip",
"Wake alarm earned a workout skip.",
**self._other_conditions("wake_alarm_skip"),
)
elif self._is_early_bird_time():
self._save_early_bird_pending()
_skip(

View File

@ -0,0 +1,74 @@
"""Collect *every* condition that bears on a lock decision, not just the first.
The decision ladders in ``_auto_upgrade`` and ``_startup_checks`` are
first-match-wins: the branch that matches calls ``sys.exit(0)``, so every
later condition is never evaluated and never recorded. That made a line like
DECISION lock=no reason=early_bird_window_active
ambiguous in the one way that matters: it cannot say whether the workout was
*also* already done. A reader seeing only the early-bird reason cannot tell a
deferred-but-compliant day from a deferred-and-idle one, which is precisely
the question "was it right to skip?" that the decision log exists to answer.
So the acting reason stays exactly as it was -- it is the branch that actually
controlled behaviour, and it stays a stable grep-able slug -- and this module
supplies the *other* conditions that also held, as an ``also=`` extra.
Only side-effect-free predicates belong here. ``_try_auto_upgrade_*`` writes
log entries and does ADB/network work, and ``_save_early_bird_pending`` writes
state; calling any of those to produce a *log line* would turn a reporting
change into a state mutation in the enforcer. Every predicate below is a pure
read.
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Callable, Mapping
_logger = logging.getLogger(__name__)
__all__ = ["collect_reasons", "reasons_extra"]
def _holds(slug: str, predicate: Callable[[], bool]) -> bool:
"""Return whether ``predicate`` holds, reporting rather than raising.
A predicate that fails is reported at ``warning`` and treated as not
holding: this runs to *annotate* a decision, so a broken annotation must
never take down the decision itself. Silence would defeat the point --
a missing reason would otherwise read as a condition that did not hold.
"""
try:
return predicate()
except (OSError, ValueError, KeyError, TypeError) as exc:
_logger.warning(
"Could not evaluate the '%s' condition while annotating a lock "
"decision (%s) — it is omitted from this line, so treat its "
"absence as unknown rather than false",
slug,
exc,
)
return False
def collect_reasons(predicates: Mapping[str, Callable[[], bool]]) -> list[str]:
"""Return the slugs of every predicate that currently holds."""
return [slug for slug, pred in predicates.items() if _holds(slug, pred)]
def reasons_extra(
acting: str, predicates: Mapping[str, Callable[[], bool]]
) -> dict[str, object]:
"""Build the ``also=`` extra for a decision whose acting reason is ``acting``.
Returns an empty mapping when nothing else applied, so a genuinely
single-reason decision keeps rendering exactly the line it did before and
no reader has to learn a new format for the common case.
"""
others = [slug for slug in collect_reasons(predicates) if slug != acting]
return {"also": ",".join(others)} if others else {}

View File

@ -68,7 +68,10 @@ class StartupChecksMixin(SyncMixin):
detail=detail,
weekly_count=count_weekly_workouts(self.log_file),
weekly_required=WEEKLY_WORKOUT_MINIMUM,
extra=extra,
# Annotate with the conditions this first-match-wins ladder
# never reached, so "why not lock?" is answerable from the one
# line rather than by re-deriving the ladder by hand.
extra={**self._other_conditions(reason), **extra},
)
)

View File

@ -0,0 +1,78 @@
"""Tests for the multi-reason annotation on lock decisions."""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from screen_locker._decision_reasons import collect_reasons, reasons_extra
if TYPE_CHECKING:
import pytest
class TestCollectReasons:
"""Every condition that holds is reported, not just the first."""
def test_returns_only_the_predicates_that_hold(self) -> None:
held = collect_reasons(
{"a": lambda: True, "b": lambda: False, "c": lambda: True}
)
assert held == ["a", "c"]
def test_empty_when_nothing_holds(self) -> None:
assert collect_reasons({"a": lambda: False}) == []
def test_a_failing_predicate_is_reported_and_skipped(
self, caplog: pytest.LogCaptureFixture
) -> None:
"""A broken annotation must not take down the decision it annotates."""
def boom() -> bool:
msg = "log unreadable"
raise OSError(msg)
with caplog.at_level(logging.WARNING):
held = collect_reasons({"a": lambda: True, "boom": boom})
assert held == ["a"]
# The omission must be loud: an invisible gap would read as "the
# condition did not hold", which is the opposite of what happened.
assert "boom" in caplog.text
assert "log unreadable" in caplog.text
class TestReasonsExtra:
"""The acting reason is never repeated back as an 'also'."""
def test_excludes_the_acting_reason(self) -> None:
extra = reasons_extra(
"early_bird_window_active",
{
"early_bird_window_active": lambda: True,
"workout_logged_today": lambda: True,
},
)
assert extra == {"also": "workout_logged_today"}
def test_orders_and_joins_every_other_condition(self) -> None:
extra = reasons_extra(
"early_bird_window_active",
{
"early_bird_window_active": lambda: True,
"workout_logged_today": lambda: True,
"weekly_minimum_met": lambda: True,
},
)
assert extra == {"also": "workout_logged_today,weekly_minimum_met"}
def test_empty_when_the_acting_reason_is_the_only_one(self) -> None:
"""A single-reason decision keeps rendering exactly its old line."""
extra = reasons_extra(
"early_bird_window_active",
{
"early_bird_window_active": lambda: True,
"workout_logged_today": lambda: False,
},
)
assert extra == {}