Flag a phone that stopped pushing in the audit

The phone uploaded nothing from 11-13 to 11-16, and only the morning
fallback ring revealed it. New check_phone_push flags a phone whose
newest HLC is more than 24 h old. An unreachable Firebase counts as
"could not check", so the audit fails toward reporting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WzxdWWfb63jncj9Lca2jeX
This commit is contained in:
Krzysztof Rudnicki 2026-11-16 08:30:34 +01:00
parent f0de01f9aa
commit dec4ecc0cb
8 changed files with 185 additions and 8 deletions

View File

@ -244,7 +244,7 @@ PC (`events.jsonl` `event`): `fallback_tick` (only on decision change),
## Evidence for Claude
`python -m wake_alarm._audit [YYYY-MM-DD]` and the 11:05 timer write
`~/data/wake-alarm/incidents/<date>.md`: a merged phone + PC timeline, then
expected-vs-observed checks (alarm known, RTC armed the night before, PC up
by `A`, ring/fallback, penalty, lockdown), mismatches and escape uses first.
Outside the repo on purpose: it holds personal data.
`~/data/wake-alarm/incidents/<date>.md` (outside the repo: personal data): a merged
phone + PC timeline, then expected-vs-observed checks (alarm known, RTC armed, PC up
by `A`, ring/fallback, penalty, lockdown, phone pushed within `PHONE_PUSH_STALE_SECONDS`
= 24 h by newest dated HLC; n/a when Firebase is unreachable), mismatches and escapes first.

View File

@ -15,7 +15,7 @@ Outside the repo on purpose: the report holds personal data.
from __future__ import annotations
import argparse
from datetime import date, datetime
from datetime import UTC, date, datetime
import sys
from typing import TYPE_CHECKING
@ -79,6 +79,11 @@ def gather(day: date) -> tuple[Evidence, bool]:
escapes=[e for e in view.escapes if e.date == day.isoformat()],
ring_started=view.ring_started_on(day.isoformat()),
stick_state=view.stick_state,
last_push=(
None
if view.last_push is None
else datetime.fromtimestamp(view.last_push, tz=UTC).astimezone()
),
),
)
return evidence, published is not None

View File

@ -20,7 +20,7 @@ from wake_alarm._audit_evidence import (
phone_on_day,
)
from wake_alarm._audit_stick import check_lockdown, check_penalty
from wake_alarm._constants import RTC_WAKE_LEAD
from wake_alarm._constants import PHONE_PUSH_STALE_SECONDS, RTC_WAKE_LEAD
from wake_alarm._enforcement_payload import is_honoured
from wake_alarm._enforcement_records import parse_instant
@ -127,8 +127,26 @@ def check_fallback_stop(ev: Evidence) -> Check:
return ok("fallback stopped correctly", ", ".join(reasons))
def check_phone_push(ev: Evidence) -> Check:
"""The phone wrote to Firebase within the last day.
Not applicable (could not check) when no dated record is readable --
Firebase unreachable, locked, or nothing stamped -- which is not the
phone's silence.
"""
name = "phone pushed to Firebase"
if ev.last_push is None:
return na(name, "could not check: no dated phone write readable")
age = (ev.now - ev.last_push).total_seconds()
detail = f"last write {ev.last_push:%Y-%m-%d %H:%M}, {age / 3600:.0f} h ago"
if age > PHONE_PUSH_STALE_SECONDS:
return bad(name, detail)
return ok(name, detail)
CHECKS = (
check_alarm,
check_phone_push,
check_rtc,
check_up_by_alarm,
check_ring,

View File

@ -9,12 +9,13 @@ ring screen and the stick streak), plus the day and its alarm.
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime
from typing import TYPE_CHECKING
from wake_alarm._enforcement_records import parse_instant
if TYPE_CHECKING:
from datetime import date, datetime
from datetime import date
from wake_alarm._audit_sources import PcEvent, Up
from wake_alarm._enforcement_records import Escape, PhoneEvent, StickState
@ -38,6 +39,13 @@ class PhoneSide:
escapes: list[Escape] = field(default_factory=list)
ring_started: bool = False
stick_state: StickState | None = None
# Newest dated write to Firebase by any phone; None = unreadable/undated.
last_push: datetime | None = None
def _now() -> datetime:
"""The audit's clock: an aware local instant."""
return datetime.now().astimezone()
@dataclass(frozen=True)
@ -52,6 +60,7 @@ class Evidence:
pc_side: PcSide = field(default_factory=PcSide)
phone_side: PhoneSide = field(default_factory=PhoneSide)
sick_day: bool = False
now: datetime = field(default_factory=_now)
@property
def pc(self) -> list[PcEvent]:
@ -93,6 +102,11 @@ class Evidence:
"""The phone's streak, as published now."""
return self.phone_side.stick_state
@property
def last_push(self) -> datetime | None:
"""When the phone last wrote anything to Firebase, if readable."""
return self.phone_side.last_push
@dataclass(frozen=True)
class Check:

View File

@ -119,6 +119,12 @@ PUBLISHED_ALARM_MAX_AGE_SECONDS: float = 14 * 24 * 60 * 60
ALARM_CACHE_MAX_AGE_SECONDS: float = 300.0
# The daily audit flags a phone whose newest Firebase write is older than
# this. A phone that stopped uploading (2026-11-13) was only noticed when the
# PC fallback rang three days later; a day of silence is the evening-before
# catch for a morning that would otherwise ring as ``phone_silent``.
PHONE_PUSH_STALE_SECONDS: float = 24 * 60 * 60
# How long after the alarm instant the trigger will still fire. Covers a
# suspended PC, a missed timer tick, and a machine booted mid-window. Also the
# reason a phone alarm moved *earlier* mid-window still fires promptly.

View File

@ -20,7 +20,7 @@ import json
import logging
from typing import TYPE_CHECKING, Any
from wake_alarm._alarm_payload import extract_hlc
from wake_alarm._alarm_payload import extract_hlc, hlc_instant
from wake_alarm._constants import (
ESCAPE_HATCH_LAST_DAY,
ESCAPE_REASON_MIN_CHARS,
@ -54,6 +54,8 @@ class EnforcementView:
escapes: tuple[Escape, ...] = ()
stick_state: StickState | None = None
phone_events: tuple[PhoneEvent, ...] = ()
# Epoch seconds of the newest dated write on any device; None = undatable.
last_push: float | None = None
def ring_started_on(self, day: str) -> bool:
"""Whether the phone's ring screen opened on ``day``."""
@ -152,10 +154,29 @@ def parse_logs(published: list[tuple[str, str]]) -> list[tuple[str, dict[str, An
return logs
def newest_push(logs: list[tuple[str, dict[str, Any]]]) -> float | None:
"""Epoch seconds of the newest dated HLC of any field on any device.
Every phone write stamps the field it changed, so the largest instant is
when the phone last uploaded anything. A stamp that cannot be dated is
skipped: None means "cannot tell", never "old".
"""
stamps: list[float] = []
for _, log in logs:
record = log.get("alarm")
fields = record.get("fields") if isinstance(record, dict) else None
for name in fields if isinstance(fields, dict) else ():
at = hlc_instant(extract_hlc(log, name))
if at is not None:
stamps.append(at)
return max(stamps, default=None)
def enforcement_view(published: list[tuple[str, str]]) -> EnforcementView:
"""Merge every device's v2 fields into one view."""
logs = parse_logs(published)
return EnforcementView(
last_push=newest_push(logs),
ring_started=_newest(logs, RING_STARTED_FIELD, ring_started_from),
escapes=_union(logs, ESCAPES_FIELD, escape_from, lambda e: e.id),
stick_state=_newest(logs, STICK_STATE_FIELD, stick_state_from),

View File

@ -0,0 +1,96 @@
"""The audit's "has the phone pushed to Firebase lately" check."""
from __future__ import annotations
from datetime import UTC, date, datetime, timedelta
import json
from typing import TYPE_CHECKING
from unittest.mock import patch
import pytest
from wake_alarm import _audit
from wake_alarm._audit import gather
from wake_alarm._audit_checks import check_phone_push, run_checks
from wake_alarm._audit_evidence import Evidence, PhoneSide
from wake_alarm._constants import PHONE_PUSH_STALE_SECONDS
from wake_alarm._sync import Alarm
if TYPE_CHECKING:
from collections.abc import Generator
NOW = datetime(2026, 11, 15, 20, 0, tzinfo=UTC)
LAST_PUSH = datetime(2026, 11, 13, 17, 38, tzinfo=UTC)
def _ev(last_push: datetime | None) -> Evidence:
return Evidence(
day=date(2026, 11, 16),
stick_day=True,
free_day=False,
alarm_at=None,
alarm_source="t",
phone_side=PhoneSide(last_push=last_push),
now=NOW,
)
def test_threshold_is_a_day() -> None:
assert PHONE_PUSH_STALE_SECONDS == 24 * 60 * 60
def test_a_stale_phone_is_a_mismatch() -> None:
check = check_phone_push(_ev(LAST_PUSH))
assert check.ok is False
assert "2026-11-13 17:38" in check.detail
assert "50 h" in check.detail
def test_a_fresh_phone_is_ok() -> None:
check = check_phone_push(_ev(NOW - timedelta(hours=3)))
assert check.ok is True
assert "3 h" in check.detail
def test_exactly_a_day_old_is_still_ok() -> None:
assert check_phone_push(_ev(NOW - timedelta(hours=24))).ok is True
def test_a_push_stamped_in_the_future_is_ok() -> None:
assert check_phone_push(_ev(NOW + timedelta(minutes=5))).ok is True
def test_no_dated_record_is_unknown_not_ok_not_bad() -> None:
check = check_phone_push(_ev(None))
assert check.ok is None
assert "could not check" in check.detail
@pytest.fixture(autouse=True)
def _sources() -> Generator[None]:
with (
patch.object(_audit, "get_alarm", return_value=Alarm(7, 0, "cache")),
patch.object(_audit, "boots", return_value=[]),
patch.object(_audit, "resumes", return_value=[]),
):
yield
def _published(hlc: str) -> list[tuple[str, str]]:
fields = {"alarm_hour": [7, hlc]}
return [("p", json.dumps({"alarm": {"fields": fields}}))]
def test_gather_feeds_the_check_and_it_runs_with_the_rest() -> None:
published = _published("2026-11-13T17:38:00.000Z-0001-p")
with patch.object(_audit, "fetch_firebase_logs", return_value=published):
evidence, _ = gather(date(2026, 11, 16))
assert evidence.phone_side.last_push == LAST_PUSH
assert "phone pushed to Firebase" in [c.name for c in run_checks(evidence)]
def test_gather_unreachable_firebase_is_unknown() -> None:
with patch.object(_audit, "fetch_firebase_logs", return_value=None):
evidence, reachable = gather(date(2026, 11, 16))
assert not reachable
assert check_phone_push(evidence).ok is None

View File

@ -2,6 +2,7 @@
from __future__ import annotations
from datetime import UTC, datetime
import json
from wake_alarm._enforcement_payload import (
@ -85,3 +86,19 @@ def test_only_honoured_escapes_count() -> None:
def test_is_honoured_rejects_a_bad_date() -> None:
assert not is_honoured(Escape("x", "someday", "", REASON))
assert not is_honoured(Escape("x", "2026-10-01", "", " " * 50))
def test_last_push_is_the_newest_dated_hlc_of_any_field_on_any_device() -> None:
old = _log(alarm_hour=(7, "2026-11-12T08:00:00.000Z-0000-a"))
new = _log(
alarm_hour=(7, "2026-11-01T08:00:00.000Z-0000-b"),
phone_events=([], "2026-11-13T17:38:00.000Z-0001-b"),
stick_state=({"streak": 0}, "garbled"),
)
view = enforcement_view([("a", old), ("b", new), ("c", "{bad")])
assert view.last_push == datetime(2026, 11, 13, 17, 38, tzinfo=UTC).timestamp()
def test_last_push_is_none_without_a_dated_stamp() -> None:
assert enforcement_view([("a", _log(alarm_hour=(7, "h")))]).last_push is None
assert enforcement_view([]).last_push is None