mirror of
https://github.com/kuhyx/diet-guard.git
synced 2026-11-20 03:54:21 +01:00
Bring three files back under 250 lines
pre-commit --all-files failed the file-length gate on AGENTS.md (262), test_sync_e2e.py (309) and test_sync_refresh.py (254), which would turn CI red. AGENTS.md prose is rewrapped (same words), test_sync_e2e.py moves its last three classes to test_sync_e2e_copy.py unchanged, and two docstrings in test_sync_refresh.py are tightened. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WzxdWWfb63jncj9Lca2jeX
This commit is contained in:
parent
49144a2c49
commit
eb6a9cf8c3
125
AGENTS.md
125
AGENTS.md
@ -1,18 +1,14 @@
|
||||
# CLAUDE.md — diet_guard
|
||||
|
||||
A log-to-unlock gate. Every ~15 min `diet-guard-gate.timer` checks whether a
|
||||
meal slot (08:00, 12:00, 16:00, 20:00 by default — the schedule is
|
||||
user-configurable, see below) elapsed unlogged; if so it opens a
|
||||
fullscreen Tk window that blocks the desktop until the user logs what they
|
||||
ate. It also tracks a daily calorie/macro budget, seeded from biometrics at
|
||||
`init` and freely editable afterward on either device. A History tab
|
||||
(`_gatelock_calendar.py`) and the phone's Calendar screen show adherence,
|
||||
streaks, a YTD tally and weekly/monthly averages, all derived from
|
||||
`_daystatus.py` / `day_status_service.dart` and `_averages.py` /
|
||||
`average_service.dart`.
|
||||
A log-to-unlock gate. Every ~15 min `diet-guard-gate.timer` checks whether a meal slot (08:00,
|
||||
12:00, 16:00, 20:00 by default — the schedule is user-configurable, see below) elapsed unlogged; if
|
||||
so it opens a fullscreen Tk window that blocks the desktop until the user logs what they ate. It
|
||||
also tracks a daily calorie/macro budget, seeded from biometrics at `init` and freely editable
|
||||
afterward on either device. A History tab (`_gatelock_calendar.py`) and the phone's Calendar screen
|
||||
show adherence, streaks, a YTD tally and weekly/monthly averages, all derived from `_daystatus.py` /
|
||||
`day_status_service.dart` and `_averages.py` / `average_service.dart`.
|
||||
|
||||
`docs/DOCS-design.md` holds the original spec (slot timing, the Tue/Wed/Thu
|
||||
catch-up rule).
|
||||
`docs/DOCS-design.md` holds the original spec (slot timing, the Tue/Wed/Thu catch-up rule).
|
||||
|
||||
## Commands
|
||||
|
||||
@ -29,35 +25,31 @@ catch-up rule).
|
||||
|
||||
## Scheduling
|
||||
|
||||
`diet-guard-gate.timer` is wall-clock (`OnCalendar=*-*-* *:00/15:00`,
|
||||
`Persistent=true`), not boot-relative — a boot-relative timer collided with
|
||||
fullscreen games grabbing input. `diet-guard-gate.service` is `Type=oneshot`
|
||||
and exits 0 at once when no lock is due (free/sick day: [docs/DOCS-sick-days.md](docs/DOCS-sick-days.md)).
|
||||
Needs `DISPLAY`/`XAUTHORITY`; see the unit file and `wait_for_display()`.
|
||||
`diet-guard-gate.timer` is wall-clock (`OnCalendar=*-*-* *:00/15:00`, `Persistent=true`), not
|
||||
boot-relative — a boot-relative timer collided with fullscreen games grabbing input.
|
||||
`diet-guard-gate.service` is `Type=oneshot` and exits 0 at once when no lock is due (free/sick day:
|
||||
[docs/DOCS-sick-days.md](docs/DOCS-sick-days.md)). Needs `DISPLAY`/`XAUTHORITY`; see the unit file
|
||||
and `wait_for_display()`.
|
||||
|
||||
## Cross-device sync
|
||||
|
||||
A sync tick pulls every other device's log from `kuhyx/syncs`
|
||||
(`diet-guard-sync/`, dumb file storage via the REST Contents API), merges
|
||||
(`_sync_merge.merge_logs`: union by `id`, tombstone wins, legacy
|
||||
`(time, desc)` dedup), **re-signs every persisted entry**, rebuilds the food
|
||||
bank, pushes back.
|
||||
A sync tick pulls every other device's log from `kuhyx/syncs` (`diet-guard-sync/`, dumb file storage
|
||||
via the REST Contents API), merges (`_sync_merge.merge_logs`: union by `id`, tombstone wins, legacy
|
||||
`(time, desc)` dedup), **re-signs every persisted entry**, rebuilds the food bank, pushes back.
|
||||
|
||||
**End-to-end encrypted** (since 2026-11-12, `_sync_e2e.py` /
|
||||
`app/lib/services/sync_e2e.dart`): everything lives on
|
||||
`diet-guard-sync/devices-e2e` (revs `revs-e2e`, header `diet-guard-sync/e2e`),
|
||||
fields sealed with a key from the shared passphrase
|
||||
(`~/.config/crdt-sync/password`; keystore + lock icon in Settings on the
|
||||
phone). Record ids, tombstones and clocks stay clear, so the food banks' ids
|
||||
(food names) are visible. The old plaintext `diet-guard-sync/devices` (and
|
||||
its `export_keys.json` keyring) is copied over and never written or deleted.
|
||||
Locked = `SyncError` / `SyncLockedException`: nothing is pulled or pushed.
|
||||
The PC keeps its derived key and copy memo in `~/.local/share/diet_guard/e2e`.
|
||||
The wake-alarm weigh-ins come from `wake-alarm-sync/devices-e2e` (own header).
|
||||
**End-to-end encrypted** (since 2026-11-12, `_sync_e2e.py` / `app/lib/services/sync_e2e.dart`):
|
||||
everything lives on `diet-guard-sync/devices-e2e` (revs `revs-e2e`, header `diet-guard-sync/e2e`),
|
||||
fields sealed with a key from the shared passphrase (`~/.config/crdt-sync/password`; keystore + lock
|
||||
icon in Settings on the phone). Record ids, tombstones and clocks stay clear, so the food banks' ids
|
||||
(food names) are visible. The old plaintext `diet-guard-sync/devices` (and its `export_keys.json`
|
||||
keyring) is copied over and never written or deleted. Locked = `SyncError` / `SyncLockedException`:
|
||||
nothing is pulled or pushed. The PC keeps its derived key and copy memo in
|
||||
`~/.local/share/diet_guard/e2e`. The wake-alarm weigh-ins come from `wake-alarm-sync/devices-e2e`
|
||||
(own header).
|
||||
|
||||
**On the PC, sync is event-driven — there is no periodic timer.** The old
|
||||
`diet-guard-sync.timer` (~15 min) was deleted: it paid a network round-trip on
|
||||
every idle tick to approximate the two moments state actually changes here.
|
||||
**On the PC, sync is event-driven — there is no periodic timer.** The old `diet-guard-sync.timer`
|
||||
(~15 min) was deleted: it paid a network round-trip on every idle tick to approximate the two
|
||||
moments state actually changes here.
|
||||
|
||||
- **Before a lock** — `_cli_gate._should_lock` runs the cheap local
|
||||
`gate_is_due()` first and pulls *only* when a lock is otherwise due, so a
|
||||
@ -121,19 +113,18 @@ every idle tick to approximate the two moments state actually changes here.
|
||||
|
||||
## Production dependency installation
|
||||
|
||||
`diet-guard-gate.service` runs `/usr/bin/python`, **not** a venv. Any new
|
||||
non-stdlib dependency must go into system Python's user site-packages:
|
||||
`diet-guard-gate.service` runs `/usr/bin/python`, **not** a venv. Any new non-stdlib dependency must
|
||||
go into system Python's user site-packages:
|
||||
|
||||
```bash
|
||||
/usr/bin/python3 -m pip install --user --break-system-packages -e .
|
||||
```
|
||||
|
||||
Verify against `/usr/bin/python3 -c "import <dep>"`, not the dev venv.
|
||||
Installing only into `.venv` caused a 3-day production outage (2026-06-19).
|
||||
Verify against `/usr/bin/python3 -c "import <dep>"`, not the dev venv. Installing only into `.venv`
|
||||
caused a 3-day production outage (2026-06-19).
|
||||
|
||||
Run `install.sh` from a **durable** clone (`~/src/diet-guard`), never a scratch
|
||||
dir — it does `pip install -e`, so the clone must persist for `git pull` to
|
||||
reach the running service.
|
||||
Run `install.sh` from a **durable** clone (`~/src/diet-guard`), never a scratch dir — it does `pip
|
||||
install -e`, so the clone must persist for `git pull` to reach the running service.
|
||||
|
||||
## Operational gotchas
|
||||
|
||||
@ -168,16 +159,14 @@ reach the running service.
|
||||
|
||||
## The companion app's desktop target is a web build
|
||||
|
||||
`app/` builds for **Android** and **web** only. There is no `app/linux/` —
|
||||
Flutter's GTK embedder manages ~20fps at 3840x2160 where the same Dart in
|
||||
Chrome sustains ~144fps (`~/src/todo/docs/DOCS-desktop-performance-findings.md`). The
|
||||
desktop app is the web build served by `bin/diet_guard_desktop.dart` in a
|
||||
Chrome `--app` window.
|
||||
`app/` builds for **Android** and **web** only. There is no `app/linux/` — Flutter's GTK embedder
|
||||
manages ~20fps at 3840x2160 where the same Dart in Chrome sustains ~144fps
|
||||
(`~/src/todo/docs/DOCS-desktop-performance-findings.md`). The desktop app is the web build served by
|
||||
`bin/diet_guard_desktop.dart` in a Chrome `--app` window.
|
||||
|
||||
Enforced by `app/test/repo_invariants_test.dart`: no `app/linux/`, `dart:io`
|
||||
only in `*_io.dart` seams and `lib/desktop/`, port 8732 and the
|
||||
`diet-guard-desktop` Chrome profile pinned (IndexedDB is keyed by origin, so
|
||||
changing either hides the entire local food log).
|
||||
Enforced by `app/test/repo_invariants_test.dart`: no `app/linux/`, `dart:io` only in `*_io.dart`
|
||||
seams and `lib/desktop/`, port 8732 and the `diet-guard-desktop` Chrome profile pinned (IndexedDB is
|
||||
keyed by origin, so changing either hides the entire local food log).
|
||||
|
||||
- Branch on `kIsWeb` *before* any `Platform.is…`, which itself throws on web.
|
||||
`dart:io` does not fail a web compile — it throws at runtime, so the symptom
|
||||
@ -190,19 +179,17 @@ changing either hides the entire local food log).
|
||||
|
||||
## The meal schedule
|
||||
|
||||
Slots are **minutes of day**: a first meal and a last meal (any `HH:MM`) and
|
||||
how many meals fall between them; interior slots round to the 15-min grid.
|
||||
Default `(480, 1200, 4)` is the old hardcoded 08/12/16/20. The load-bearing
|
||||
rules (integer-only arithmetic, the additive `slot`+`slot_min` /
|
||||
`f`/`l`/`n`+`fm`/`lm` wire, the count clamp, the `last + 120 min` cutoff,
|
||||
nearest-slot satisfaction), the forward-only history, and the two edit
|
||||
surfaces are in [docs/DOCS-meal-schedule.md](docs/DOCS-meal-schedule.md) —
|
||||
read it before touching `_slots.py` / `_slot_wire.py` / `slot.dart`.
|
||||
Slots are **minutes of day**: a first meal and a last meal (any `HH:MM`) and how many meals fall
|
||||
between them; interior slots round to the 15-min grid. Default `(480, 1200, 4)` is the old hardcoded
|
||||
08/12/16/20. The load-bearing rules (integer-only arithmetic, the additive `slot`+`slot_min` /
|
||||
`f`/`l`/`n`+`fm`/`lm` wire, the count clamp, the `last + 120 min` cutoff, nearest-slot
|
||||
satisfaction), the forward-only history, and the two edit surfaces are in
|
||||
[docs/DOCS-meal-schedule.md](docs/DOCS-meal-schedule.md) — read it before touching `_slots.py` /
|
||||
`_slot_wire.py` / `slot.dart`.
|
||||
|
||||
## Averages (`_averages.py` / `average_service.dart`)
|
||||
|
||||
Three load-bearing rules; changing any silently changes what "under budget"
|
||||
means:
|
||||
Three load-bearing rules; changing any silently changes what "under budget" means:
|
||||
|
||||
- **Denominator is logged days, not elapsed days.** An unlogged day is not a
|
||||
zero-kcal day.
|
||||
@ -212,10 +199,9 @@ means:
|
||||
week" is empty on a Monday, and reports `no logged days yet` rather than a
|
||||
fake average.
|
||||
|
||||
Band boundaries reuse `_daystatus.OVER_BUDGET_YELLOW_CEILING` /
|
||||
`kOverBudgetYellowCeiling` **by import, not by copy**. The MCP `get_averages`
|
||||
tool drops `avg_budget` (budget secrecy on the network only); the CLI, gate and
|
||||
phone show both.
|
||||
Band boundaries reuse `_daystatus.OVER_BUDGET_YELLOW_CEILING` / `kOverBudgetYellowCeiling` **by
|
||||
import, not by copy**. The MCP `get_averages` tool drops `avg_budget` (budget secrecy on the network
|
||||
only); the CLI, gate and phone show both.
|
||||
|
||||
## Do NOT
|
||||
|
||||
@ -251,9 +237,10 @@ phone show both.
|
||||
|
||||
## Flutter/Dart AI rules
|
||||
|
||||
_Vendored from [flutter/flutter docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md)
|
||||
via `~/.claude/CLAUDE.md` Flutter AI tooling setup. Re-fetch periodically.
|
||||
Split across five files to stay under the 250-line cap._
|
||||
_Vendored from [flutter/flutter
|
||||
docs/rules/rules.md](https://github.com/flutter/flutter/blob/main/docs/rules/rules.md) via
|
||||
`~/.claude/CLAUDE.md` Flutter AI tooling setup. Re-fetch periodically. Split across five files to
|
||||
stay under the 250-line cap._
|
||||
|
||||
- [Language, style and architecture](docs/DOCS-flutter-rules-language.md)
|
||||
- [Architecture, lint rules, state and data](docs/DOCS-flutter-rules-state-and-data.md)
|
||||
|
||||
@ -2,7 +2,7 @@ name: diet_guard_app
|
||||
description: "Companion phone app for diet_guard: log meals on the go."
|
||||
publish_to: 'none'
|
||||
|
||||
version: 1.0.161+1
|
||||
version: 1.0.162+1
|
||||
|
||||
environment:
|
||||
sdk: ^3.12.2
|
||||
|
||||
@ -13,20 +13,15 @@ from unittest.mock import patch
|
||||
|
||||
from crdt_sync import (
|
||||
E2eCipher,
|
||||
E2eDecryptError,
|
||||
E2eLayout,
|
||||
E2eLockedError,
|
||||
MirrorSyncClient,
|
||||
seal_log_text,
|
||||
)
|
||||
import pytest
|
||||
|
||||
from diet_guard import _sync, _sync_client, _sync_e2e
|
||||
from diet_guard._body_ingest import fetch_alarm_logs
|
||||
from diet_guard._device import device_id
|
||||
from diet_guard._state import load_log, log_meal
|
||||
from diet_guard._state_sync import read_raw_log, write_raw_log
|
||||
from diet_guard._sync_banks import _primary_only_text
|
||||
from diet_guard.sync_merge import daylog_to_log
|
||||
from diet_guard.tests._sync_fakes import DictStore, _nutrition, _write_token
|
||||
|
||||
@ -195,115 +190,3 @@ class TestUndecryptablePeer:
|
||||
assert layout.prefix == _NEW
|
||||
assert "skipping" in caplog.text
|
||||
assert _all_meals() == ["mine"]
|
||||
|
||||
|
||||
_COPY = "crdt_sync._e2e_store.copy_to_encrypted"
|
||||
|
||||
|
||||
class TestCopyMemo:
|
||||
def _store_with_old_revs(self) -> DictStore:
|
||||
return DictStore(
|
||||
{
|
||||
f"{_OLD}/phone/budget.json": "{}",
|
||||
"diet-guard-sync/revs/phone": "rev-1",
|
||||
}
|
||||
)
|
||||
|
||||
def test_a_new_process_skips_the_copy_when_old_revisions_are_unchanged(
|
||||
self,
|
||||
) -> None:
|
||||
store = self._store_with_old_revs()
|
||||
_sync_e2e.open_e2e(store)
|
||||
with (
|
||||
patch.dict("crdt_sync._e2e_store._copied", clear=True),
|
||||
patch(_COPY, return_value=0) as copy,
|
||||
):
|
||||
_sync_e2e.open_e2e(store)
|
||||
copy.assert_not_called()
|
||||
|
||||
def test_changed_old_revisions_copy_again(self) -> None:
|
||||
store = self._store_with_old_revs()
|
||||
_sync_e2e.open_e2e(store)
|
||||
store.files["diet-guard-sync/revs/phone"] = "rev-2"
|
||||
with patch(_COPY, return_value=1) as copy:
|
||||
_sync_e2e.open_e2e(store)
|
||||
copy.assert_called_once()
|
||||
|
||||
def test_the_cached_key_opens_without_the_passphrase(self, tmp_path: Path) -> None:
|
||||
store = DictStore()
|
||||
_sync_e2e.open_e2e(store)
|
||||
with patch.object(_sync_e2e, "PASSWORD_FILE", tmp_path / "gone"):
|
||||
assert _sync_e2e.open_e2e(store).layout.prefix == _NEW
|
||||
|
||||
def test_wake_alarm_copies_once_per_process(self) -> None:
|
||||
store = DictStore()
|
||||
_sync_e2e.open_e2e(store, _sync_e2e.LEGACY_WAKE_ALARM_DIR)
|
||||
assert not (_sync_e2e.E2E_STATE_DIR).exists()
|
||||
with (
|
||||
patch.dict("crdt_sync._e2e_store._copied", clear=True),
|
||||
patch(_COPY, return_value=0) as copy,
|
||||
):
|
||||
_sync_e2e.open_e2e(store, _sync_e2e.LEGACY_WAKE_ALARM_DIR)
|
||||
copy.assert_called_once()
|
||||
|
||||
def test_a_copy_meeting_an_unopenable_blob_is_locked(self) -> None:
|
||||
store = DictStore()
|
||||
with (
|
||||
patch(_COPY, side_effect=E2eDecryptError("bad")),
|
||||
pytest.raises(E2eLockedError),
|
||||
):
|
||||
_sync_e2e.open_e2e(store)
|
||||
|
||||
|
||||
class TestWakeAlarmIngest:
|
||||
def test_old_plaintext_alarm_is_copied_and_read_decrypted(self) -> None:
|
||||
alarm = json.dumps(
|
||||
{
|
||||
"alarm": {
|
||||
"id": "alarm",
|
||||
"fields": {"alarm_hour": [7, "2026-11-01T00:00:00.000Z-0000-p"]},
|
||||
"deleted": False,
|
||||
}
|
||||
}
|
||||
)
|
||||
store = DictStore({"wake-alarm-sync/devices/p1/alarm.json": alarm})
|
||||
diet = _sync_e2e.open_e2e(store)
|
||||
|
||||
published = fetch_alarm_logs(diet)
|
||||
|
||||
assert [device for device, _ in published] == ["p1"]
|
||||
assert json.loads(published[0][1])["alarm"]["fields"]["alarm_hour"][0] == 7
|
||||
sealed = store.files["wake-alarm-sync/devices-e2e/p1/alarm.json"]
|
||||
assert "alarm_hour" not in sealed
|
||||
assert "wake-alarm-sync/e2e" in store.files
|
||||
|
||||
def test_locked_wake_alarm_is_skipped(self, tmp_path: Path) -> None:
|
||||
store = DictStore()
|
||||
diet = _sync_e2e.open_e2e(store)
|
||||
with patch.object(_sync_e2e, "PASSWORD_FILE", tmp_path / "gone"):
|
||||
assert fetch_alarm_logs(diet) == []
|
||||
|
||||
def test_reads_only_the_firebase_half_of_a_mirror(self) -> None:
|
||||
primary = DictStore()
|
||||
mirror = DictStore()
|
||||
client = MirrorSyncClient(primary, mirror)
|
||||
diet = _sync_e2e.open_e2e(client)
|
||||
mirror.puts.clear()
|
||||
fetch_alarm_logs(diet)
|
||||
assert not any(p.startswith("wake-alarm-sync") for p in mirror.puts)
|
||||
|
||||
|
||||
class TestPrimaryOnly:
|
||||
def test_e2e_store_reads_the_primary_decrypted(self) -> None:
|
||||
primary = DictStore()
|
||||
mirror = DictStore()
|
||||
diet = _sync_e2e.open_e2e(MirrorSyncClient(primary, mirror))
|
||||
path = f"{_NEW}/peer/body.json"
|
||||
diet.put_file_text(path, '{"x": 1}', message="t")
|
||||
mirror.files.pop(path)
|
||||
assert _primary_only_text(diet, path) == '{"x": 1}'
|
||||
assert '"x"' not in primary.files[path]
|
||||
|
||||
def test_plain_store_is_read_directly(self) -> None:
|
||||
store = DictStore({"a/b": "text"})
|
||||
assert _primary_only_text(store, "a/b") == "text"
|
||||
|
||||
138
diet_guard/tests/test_sync_e2e_copy.py
Normal file
138
diet_guard/tests/test_sync_e2e_copy.py
Normal file
@ -0,0 +1,138 @@
|
||||
"""E2E sync: the copy memo, the wake-alarm ingest and the primary-only read.
|
||||
|
||||
Split out of ``test_sync_e2e`` to keep both files under the repo's 250-line cap.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import patch
|
||||
|
||||
from crdt_sync import (
|
||||
E2eDecryptError,
|
||||
E2eLockedError,
|
||||
MirrorSyncClient,
|
||||
)
|
||||
import pytest
|
||||
|
||||
from diet_guard import _sync_e2e
|
||||
from diet_guard._body_ingest import fetch_alarm_logs
|
||||
from diet_guard._sync_banks import _primary_only_text
|
||||
from diet_guard.tests._sync_fakes import DictStore
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
_OLD = "diet-guard-sync/devices"
|
||||
_NEW = "diet-guard-sync/devices-e2e"
|
||||
_COPY = "crdt_sync._e2e_store.copy_to_encrypted"
|
||||
|
||||
|
||||
class TestCopyMemo:
|
||||
def _store_with_old_revs(self) -> DictStore:
|
||||
return DictStore(
|
||||
{
|
||||
f"{_OLD}/phone/budget.json": "{}",
|
||||
"diet-guard-sync/revs/phone": "rev-1",
|
||||
}
|
||||
)
|
||||
|
||||
def test_a_new_process_skips_the_copy_when_old_revisions_are_unchanged(
|
||||
self,
|
||||
) -> None:
|
||||
store = self._store_with_old_revs()
|
||||
_sync_e2e.open_e2e(store)
|
||||
with (
|
||||
patch.dict("crdt_sync._e2e_store._copied", clear=True),
|
||||
patch(_COPY, return_value=0) as copy,
|
||||
):
|
||||
_sync_e2e.open_e2e(store)
|
||||
copy.assert_not_called()
|
||||
|
||||
def test_changed_old_revisions_copy_again(self) -> None:
|
||||
store = self._store_with_old_revs()
|
||||
_sync_e2e.open_e2e(store)
|
||||
store.files["diet-guard-sync/revs/phone"] = "rev-2"
|
||||
with patch(_COPY, return_value=1) as copy:
|
||||
_sync_e2e.open_e2e(store)
|
||||
copy.assert_called_once()
|
||||
|
||||
def test_the_cached_key_opens_without_the_passphrase(self, tmp_path: Path) -> None:
|
||||
store = DictStore()
|
||||
_sync_e2e.open_e2e(store)
|
||||
with patch.object(_sync_e2e, "PASSWORD_FILE", tmp_path / "gone"):
|
||||
assert _sync_e2e.open_e2e(store).layout.prefix == _NEW
|
||||
|
||||
def test_wake_alarm_copies_once_per_process(self) -> None:
|
||||
store = DictStore()
|
||||
_sync_e2e.open_e2e(store, _sync_e2e.LEGACY_WAKE_ALARM_DIR)
|
||||
assert not (_sync_e2e.E2E_STATE_DIR).exists()
|
||||
with (
|
||||
patch.dict("crdt_sync._e2e_store._copied", clear=True),
|
||||
patch(_COPY, return_value=0) as copy,
|
||||
):
|
||||
_sync_e2e.open_e2e(store, _sync_e2e.LEGACY_WAKE_ALARM_DIR)
|
||||
copy.assert_called_once()
|
||||
|
||||
def test_a_copy_meeting_an_unopenable_blob_is_locked(self) -> None:
|
||||
store = DictStore()
|
||||
with (
|
||||
patch(_COPY, side_effect=E2eDecryptError("bad")),
|
||||
pytest.raises(E2eLockedError),
|
||||
):
|
||||
_sync_e2e.open_e2e(store)
|
||||
|
||||
|
||||
class TestWakeAlarmIngest:
|
||||
def test_old_plaintext_alarm_is_copied_and_read_decrypted(self) -> None:
|
||||
alarm = json.dumps(
|
||||
{
|
||||
"alarm": {
|
||||
"id": "alarm",
|
||||
"fields": {"alarm_hour": [7, "2026-11-01T00:00:00.000Z-0000-p"]},
|
||||
"deleted": False,
|
||||
}
|
||||
}
|
||||
)
|
||||
store = DictStore({"wake-alarm-sync/devices/p1/alarm.json": alarm})
|
||||
diet = _sync_e2e.open_e2e(store)
|
||||
|
||||
published = fetch_alarm_logs(diet)
|
||||
|
||||
assert [device for device, _ in published] == ["p1"]
|
||||
assert json.loads(published[0][1])["alarm"]["fields"]["alarm_hour"][0] == 7
|
||||
sealed = store.files["wake-alarm-sync/devices-e2e/p1/alarm.json"]
|
||||
assert "alarm_hour" not in sealed
|
||||
assert "wake-alarm-sync/e2e" in store.files
|
||||
|
||||
def test_locked_wake_alarm_is_skipped(self, tmp_path: Path) -> None:
|
||||
store = DictStore()
|
||||
diet = _sync_e2e.open_e2e(store)
|
||||
with patch.object(_sync_e2e, "PASSWORD_FILE", tmp_path / "gone"):
|
||||
assert fetch_alarm_logs(diet) == []
|
||||
|
||||
def test_reads_only_the_firebase_half_of_a_mirror(self) -> None:
|
||||
primary = DictStore()
|
||||
mirror = DictStore()
|
||||
client = MirrorSyncClient(primary, mirror)
|
||||
diet = _sync_e2e.open_e2e(client)
|
||||
mirror.puts.clear()
|
||||
fetch_alarm_logs(diet)
|
||||
assert not any(p.startswith("wake-alarm-sync") for p in mirror.puts)
|
||||
|
||||
|
||||
class TestPrimaryOnly:
|
||||
def test_e2e_store_reads_the_primary_decrypted(self) -> None:
|
||||
primary = DictStore()
|
||||
mirror = DictStore()
|
||||
diet = _sync_e2e.open_e2e(MirrorSyncClient(primary, mirror))
|
||||
path = f"{_NEW}/peer/body.json"
|
||||
diet.put_file_text(path, '{"x": 1}', message="t")
|
||||
mirror.files.pop(path)
|
||||
assert _primary_only_text(diet, path) == '{"x": 1}'
|
||||
assert '"x"' not in primary.files[path]
|
||||
|
||||
def test_plain_store_is_read_directly(self) -> None:
|
||||
store = DictStore({"a/b": "text"})
|
||||
assert _primary_only_text(store, "a/b") == "text"
|
||||
@ -4,12 +4,10 @@ The full tick measured ~21s against the live remote, which is far too slow to
|
||||
sit in front of a fullscreen lock. ``_sync_refresh`` answers the gate's single
|
||||
question -- "has a peer already logged this slot?" -- from the peer logs alone.
|
||||
|
||||
The three state invariants below are the traps that make this pass dangerous
|
||||
if it drifts, so each has its own regression test:
|
||||
|
||||
* ``pushed_rev`` must survive verbatim (this pass never pushes),
|
||||
* ``peer_revs`` must be *merged*, never replaced (only changed peers visited),
|
||||
* the log must be written before the state.
|
||||
Three state invariants are the traps that make this pass dangerous if it
|
||||
drifts, each with its own regression test: ``pushed_rev`` survives verbatim
|
||||
(this pass never pushes), ``peer_revs`` is *merged*, never replaced (only
|
||||
changed peers are visited), and the log is written before the state.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@ -44,9 +42,8 @@ def _state_store() -> FileSyncStateStore:
|
||||
def _peer_log_text() -> str:
|
||||
"""Return the wire text a peer would push for one logged meal.
|
||||
|
||||
Built through ``log_meal`` into the (redirected) local log, serialised, then
|
||||
the local log is emptied again -- so the merge under test is unambiguously
|
||||
the peer's record arriving, not one that was already there.
|
||||
Built through ``log_meal``, serialised, then the local log is emptied again,
|
||||
so the merge under test is unambiguously the peer's record arriving.
|
||||
"""
|
||||
log_meal("peer porridge", _nutrition(), 8)
|
||||
text = json.dumps(
|
||||
@ -109,9 +106,8 @@ class TestPeerIsCurrent:
|
||||
Using ``.get(...) is not None`` here would re-download those peers on
|
||||
every single tick, forever.
|
||||
"""
|
||||
# A real ``sync_state.json`` holds explicit nulls here even though the
|
||||
# annotation says ``str`` -- that mismatch is exactly what this test
|
||||
# pins, so the value is cast in rather than suppressed at the line.
|
||||
# A real ``sync_state.json`` holds explicit nulls here though the
|
||||
# annotation says ``str``; this test pins that, so the value is cast in.
|
||||
peer_revs = cast("dict[str, str]", {"pc": None})
|
||||
state = SyncState(pushed_rev=None, peer_revs=peer_revs)
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user