screen-locker/screen_locker/tests/test_log_mixin_chokepoint.py
Krzysztof kuhy Rudnicki 79879263ba Support multiple workouts per day; fix the dead sync; ban silent failures
The workout log stored ONE workout per calendar day, so a second same-day
workout was silently dropped and could never earn credit.

Multiple workouts per day:
- workout_log.json: {date: entry} -> {date: [entry, ...]}. Legacy entries are
  wrapped on read (_log_io.load_workout_log) so their HMACs stay valid — no
  re-signing; every write normalizes the file, migrating it progressively.
- New write chokepoint (_log_mixin.write_signed_entry) APPENDS and dedups by a
  stable workout_id, returning RecordResult so callers can tell a new workout
  from a duplicate. Re-verifying the same workout is a no-op.
- count_weekly_workouts is anti-gaming: each VERIFIED workout counts
  individually; self-reported manual entries count at most once per day. Four
  real workouts in one day satisfy the week; four manual entries count as one.
- Reward: the day's first counted workout gets the base +2h; an additional
  same-day VERIFIED workout gets +1h; an additional manual gets nothing. The
  old "+1h when weekly_count > 4" gate is replaced — weekly volume is the
  banked bonus's job and shouldn't be paid twice.
- Fixed: the unlock screen labelled the +1h "#{weekly_count - 4}", which can
  render negative under the new rule. Removed the dead runnerup_manual type.
- Flutter: the manual budget counts distinct DAYS, matching the PC.

PC->phone sync (it had never worked once):
- push_pc_manuals pushed from a side-store written at log-time, so anything
  logged before that feature existed could never publish. _manual_push now
  derives the crdt log directly from workout_log.json — the single source of
  truth — covering manual AND verified runs. The record id is the workout's own
  workout_id (derived for legacy entries to match the phone's format) and the
  HLC comes from the entry's own timestamp, so a re-push is byte-identical and
  the repo never churns.
- The phone reads every kind (readMergedWorkoutPayloads) and lists the PC's
  workouts under "SYNCED FROM PC". The manual budget still sees manual-only, so
  a verified run can't consume a self-report slot.
- Settings claimed "Connected." whenever a token STRING existed. It now
  verifies against the API on open, so a revoked token reports 401 instead of
  showing a green lie.

Never fail silently:
- 30 swallowed exceptions across 19 files now log WARNING with the concrete
  cause AND consequence — plus the token guards in _workout_sync that returned
  [] in total silence, the exact bug that hid the dead sync for weeks.
- New pre-commit hook (scripts/check_silent_failures.py) fails any except that
  neither re-raises nor logs loudly. ruff's S110 only catches `except: pass`;
  the real pattern here was `except: log.info(); return []`. Documented in
  CLAUDE.md.

Verified on real data: the Jul 13 run (pulled from its actual TCX over ADB) now
counts alongside that day's manual squash, and all three workouts are published
to kuhyx/syncs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Fv8ULVt3Q67GwCFbM7doHB
2026-07-17 09:22:31 +02:00

125 lines
5.1 KiB
Python

"""Tests for the workout-log write chokepoint (append + workout_id dedup)."""
from __future__ import annotations
import json
from typing import TYPE_CHECKING
from screen_locker._log_io import load_workout_log
from screen_locker._log_mixin import write_signed_entry
if TYPE_CHECKING:
from pathlib import Path
class TestWriteChokepoint:
"""Tests for _derive_workout_id / write_signed_entry append+dedup."""
def test_explicit_workout_id_wins(self, tmp_path: Path) -> None:
"""An explicit workout_id in workout_data is used verbatim."""
log_file = tmp_path / "workout_log.json"
result = write_signed_entry(
log_file,
"2026-07-13",
{"type": "runnerup_verified", "workout_id": "custom:abc"},
)
assert result.appended is True
assert load_workout_log(log_file)["2026-07-13"][0]["workout_id"] == "custom:abc"
def test_manual_without_start_time_falls_back_to_type_date(
self, tmp_path: Path
) -> None:
"""A manual entry lacking start_time keys on ``{type}:{date}``."""
log_file = tmp_path / "workout_log.json"
write_signed_entry(log_file, "2026-07-13", {"type": "manual_workout"})
entry = load_workout_log(log_file)["2026-07-13"][0]
assert entry["workout_id"] == "manual_workout:2026-07-13"
def test_manual_with_start_time_uses_the_sync_record_id(
self, tmp_path: Path
) -> None:
"""A manual entry reuses the sync record id so local+synced dedup."""
log_file = tmp_path / "workout_log.json"
write_signed_entry(
log_file,
"2026-07-13",
{"type": "manual_workout", "start_time": "14:00"},
)
entry = load_workout_log(log_file)["2026-07-13"][0]
assert entry["workout_id"] == "manual:2026-07-13T14:00"
def test_workout_data_without_type_gets_no_id(self, tmp_path: Path) -> None:
"""No type → no derivable id; the entry still appends."""
log_file = tmp_path / "workout_log.json"
assert write_signed_entry(log_file, "2026-07-13", {}).appended is True
assert "workout_id" not in load_workout_log(log_file)["2026-07-13"][0]
def test_duplicate_workout_id_is_not_appended(self, tmp_path: Path) -> None:
"""Re-writing the same workout is a no-op — idempotent by workout_id."""
log_file = tmp_path / "workout_log.json"
data = {"type": "runnerup_verified", "source": "run"}
assert write_signed_entry(log_file, "2026-07-13", data).appended is True
second = write_signed_entry(log_file, "2026-07-13", {**data, "source": "again"})
assert second.appended is False
# prior_entries reports the day as it already stood, and nothing is added.
assert len(second.prior_entries) == 1
assert len(load_workout_log(log_file)["2026-07-13"]) == 1
def test_legacy_entry_without_id_is_not_duplicated(self, tmp_path: Path) -> None:
"""A pre-workout_id entry must match its own synced copy, not double.
Regression: the PC began publishing its history, the phone/timer synced
a legacy manual workout back, and it appended a SECOND copy because the
stored id was None. The id is now derived for comparison.
"""
log_file = tmp_path / "workout_log.json"
legacy = {
"timestamp": "2026-07-13T07:25:12+00:00",
"workout_data": {
"type": "manual_workout",
"source": "squash",
"start_time": "14:00",
},
}
log_file.write_text(json.dumps({"2026-07-13": [legacy]}))
# The same workout arriving back from sync, now carrying its id.
result = write_signed_entry(
log_file,
"2026-07-13",
{
"type": "manual_workout",
"source": "squash",
"start_time": "14:00",
"workout_id": "manual:2026-07-13T14:00",
},
)
assert result.appended is False
assert len(load_workout_log(log_file)["2026-07-13"]) == 1
def test_malformed_existing_entry_does_not_block_the_append(
self, tmp_path: Path
) -> None:
"""An existing entry with junk workout_data has no id, so it can't match."""
log_file = tmp_path / "workout_log.json"
log_file.write_text(
json.dumps({"2026-07-13": [{"timestamp": "t", "workout_data": "junk"}]})
)
result = write_signed_entry(
log_file, "2026-07-13", {"type": "runnerup_verified"}
)
assert result.appended is True
assert len(load_workout_log(log_file)["2026-07-13"]) == 2
def test_distinct_workouts_same_day_both_append(self, tmp_path: Path) -> None:
"""Different workout_ids on one day stack (multiple workouts/day)."""
log_file = tmp_path / "workout_log.json"
write_signed_entry(log_file, "2026-07-13", {"type": "manual_workout"})
result = write_signed_entry(
log_file, "2026-07-13", {"type": "runnerup_verified"}
)
assert result.appended is True
assert len(result.prior_entries) == 1
assert len(load_workout_log(log_file)["2026-07-13"]) == 2