mirror of
https://github.com/kuhyx/diet-guard.git
synced 2026-11-19 05:04:22 +01:00
Close the open gate when a phone meal arrives
A meal logged on the phone while the gate window was up changed nothing until Fetch was pressed: the new credit watch only fires on a local write to the food log, and the PC never pulled on its own. While a non-demo window is open it now pulls peer logs every 30 s, with the Fetch button's own narrow pull on a worker thread. One pull is in flight at a time (shared with the button), failures are logged and retried, and the window stays up. The pull's write trips the watch, which closes through the usual reconcile path. gatelock moves to 0.14.0 for watch_credit. refresh_peer_logs also read the local log before the peer downloads and wrote it after, so a meal logged during the pull was overwritten. It now merges the peers first and reads the local log just before the write. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WzxdWWfb63jncj9Lca2jeX
This commit is contained in:
parent
f793545468
commit
dfd60d4f7b
@ -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.159+1
|
||||
version: 1.0.160+1
|
||||
|
||||
environment:
|
||||
sdk: ^3.12.2
|
||||
|
||||
@ -57,12 +57,11 @@ from gatelock import (
|
||||
from diet_guard._gate import due_slots
|
||||
from diet_guard._gatelock_calendar import _GateCalendar, make_calendar_vars
|
||||
from diet_guard._gatelock_core import _GateState
|
||||
from diet_guard._gatelock_credit import arm_credit_watch
|
||||
from diet_guard._gatelock_groups import GateWidgetsGroup
|
||||
from diet_guard._gatelock_lockfile import acquire_gate_lock, release_gate_lock
|
||||
from diet_guard._gatelock_ui import (
|
||||
GateCallbacks,
|
||||
make_vars,
|
||||
)
|
||||
from diet_guard._gatelock_peerpull import arm_peer_pull
|
||||
from diet_guard._gatelock_ui import GateCallbacks, make_vars
|
||||
from diet_guard._hold import watch_hold
|
||||
from diet_guard._meal_schedule_store import current_schedule
|
||||
from diet_guard._slots import current_slot, day_slots
|
||||
@ -105,8 +104,7 @@ def _pending_slots(*, demo_mode: bool) -> list[int]:
|
||||
return pending
|
||||
if demo_mode:
|
||||
schedule = current_schedule()
|
||||
# `is None`, not `or`: slot 0 (midnight) is falsy. Both arms happen to
|
||||
# agree (0 is necessarily the first slot), but intent shouldn't hinge on it.
|
||||
# `is None`, not `or`: slot 0 (midnight) is falsy.
|
||||
elapsed = current_slot(now_local(), schedule)
|
||||
return [elapsed if elapsed is not None else day_slots(schedule)[0]]
|
||||
return []
|
||||
@ -126,16 +124,13 @@ class MealGate(_GateCalendar):
|
||||
_assert_not_under_pytest()
|
||||
self.demo_mode = demo_mode
|
||||
self._pending = _pending_slots(demo_mode=demo_mode)
|
||||
# All mutable logical state (provenance, suggestions, meal-in-progress)
|
||||
# lives in one bundle; see _GateState for the per-field rationale.
|
||||
# All mutable logical state lives in one bundle (see _GateState).
|
||||
self._state = _GateState()
|
||||
self.root = GateRoot()
|
||||
self.root.on_callback_error = self.on_callback_error
|
||||
self.root.title("Diet Gate") # OS-level app name: the one kept noun
|
||||
# No bg=/fg=/... overrides here: LockConfig's own defaults already
|
||||
# are the unified-design-system palette, and _gatelock_ui reads the
|
||||
# same LockConfig() rather than a separate hardcoded copy -- see
|
||||
# DESIGN_AUDIT_TODO.md for why an override here previously drifted.
|
||||
# No colour overrides: LockConfig's defaults are the design-system palette
|
||||
# and _gatelock_ui reads them too (an override drifted once).
|
||||
config = LockConfig(
|
||||
mode="soft" if demo_mode else "hard",
|
||||
app_name="diet_guard",
|
||||
@ -219,8 +214,13 @@ class MealGate(_GateCalendar):
|
||||
self._lock.close()
|
||||
|
||||
def run(self) -> None:
|
||||
"""Run the Tk loop (a hold starting mid-lock closes it), VT-safe."""
|
||||
"""Run the Tk loop (a hold or a meal logged elsewhere closes it), VT-safe."""
|
||||
watch_hold(self.root, self.close)
|
||||
if not self.demo_mode: # a demo owes a synthetic slot: it would self-close
|
||||
arm_credit_watch(
|
||||
self.root, lambda: self._pending, self._reconcile_after_fetch
|
||||
)
|
||||
arm_peer_pull(self)
|
||||
self._lock.run()
|
||||
|
||||
def _wire_events(self) -> None:
|
||||
|
||||
52
diet_guard/_gatelock_credit.py
Normal file
52
diet_guard/_gatelock_credit.py
Normal file
@ -0,0 +1,52 @@
|
||||
"""The open gate window notices a meal that was logged somewhere else.
|
||||
|
||||
Until 2026-11-16 the window's only passive watcher was ``watch_hold``; a meal
|
||||
the phone (or any other process) wrote to the local log while the window was up
|
||||
changed nothing until the user pressed Fetch. This hands the shared
|
||||
``gatelock.watch_credit`` three things diet_guard already has:
|
||||
|
||||
* the file to watch -- the food log ``log_meal`` and every sync merge write;
|
||||
* "is it done?" -- :func:`diet_guard._gate.due_slots`, never a second copy of
|
||||
the rule: done when none of the slots this window still owes is due any more;
|
||||
* the exit -- the window's own reconcile (``_reconcile_after_fetch``), the same
|
||||
path the Fetch button takes, so the status line and unlock delay are identical.
|
||||
|
||||
The credit was already written by whoever logged it. Closing writes nothing.
|
||||
Failure mode: closed -- a log that cannot be read keeps the lock up.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from gatelock import watch_credit
|
||||
|
||||
from diet_guard import _state
|
||||
from diet_guard._gate import due_slots
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
from tkinter import Misc
|
||||
|
||||
__all__ = ["arm_credit_watch"]
|
||||
|
||||
|
||||
def arm_credit_watch(
|
||||
root: Misc,
|
||||
pending: Callable[[], list[int]],
|
||||
on_credit: Callable[[], None],
|
||||
) -> None:
|
||||
"""Close the window once every slot it still owes is covered by the log.
|
||||
|
||||
Args:
|
||||
root: The gate's Tk root.
|
||||
pending: Returns the slots the window still owes. A callable, because
|
||||
the window rebuilds that list as slots are satisfied.
|
||||
on_credit: The window's reconcile/close path.
|
||||
"""
|
||||
|
||||
def _all_covered() -> bool:
|
||||
owed = set(pending())
|
||||
return bool(owed) and owed.isdisjoint(due_slots())
|
||||
|
||||
watch_credit(root, (_state.food_log_path(),), _all_covered, on_credit)
|
||||
@ -63,15 +63,22 @@ class _PullFlows(_GateNutrition):
|
||||
pylint caps the controller chain's depth and every MRO entry counts.
|
||||
"""
|
||||
|
||||
#: Slots still to be filled. Declared on the controller this mixin is
|
||||
#: mixed into; repeated here so mypy can type the reconcile below.
|
||||
#: Slots still to be filled (declared on the controller; typed here).
|
||||
_pending: list[int]
|
||||
|
||||
#: The in-flight sync fetch's queue, or None when none is running.
|
||||
#: Doubles as the poll's own guard: a stray poll after completion finds
|
||||
#: None and stops rather than blocking on an empty queue forever.
|
||||
#: The in-flight sync fetch's queue, or None when none is running. Doubles
|
||||
#: as the poll's guard: a stray poll after completion finds None and stops.
|
||||
_fetch_result: queue.Queue[str | None] | None = None
|
||||
|
||||
@property
|
||||
def fetch_result(self) -> queue.Queue[str | None] | None:
|
||||
"""The in-flight pull, shared with the background timer."""
|
||||
return self._fetch_result
|
||||
|
||||
@fetch_result.setter
|
||||
def fetch_result(self, value: queue.Queue[str | None] | None) -> None:
|
||||
self._fetch_result = value
|
||||
|
||||
#: The in-flight catering fetch's queue, or None when none is running.
|
||||
_delivery_result: queue.Queue[DeliveryResult] | None = None
|
||||
|
||||
@ -79,15 +86,12 @@ class _PullFlows(_GateNutrition):
|
||||
#: time so each still passes through the normal submit path.
|
||||
_delivery_pending: tuple[Dish, ...] = ()
|
||||
|
||||
#: True when the running fetch came from the button rather than the
|
||||
#: window opening. An automatic fetch must not talk over the gate's own
|
||||
#: prompt to report that the caterer had nothing today.
|
||||
#: True when the running fetch came from the button, not the window opening
|
||||
#: (an automatic one must not talk over the gate's own prompt).
|
||||
_delivery_asked: bool = False
|
||||
|
||||
# Supplied by ``_GateMealFlow``, which mixes this class in. Declared so the
|
||||
# contract is explicit and pylint can see it: the dependency runs both ways
|
||||
# (the flows drive the meal form, the form hosts the flows) and the
|
||||
# ancestor cap leaves no room for another chain link.
|
||||
# Supplied by ``_GateMealFlow``, which mixes this class in (the dependency
|
||||
# runs both ways and the ancestor cap leaves no room for another link).
|
||||
_set_status: Callable[..., None]
|
||||
_clear_inputs: Callable[[], None]
|
||||
_apply_reference: Callable[..., None]
|
||||
@ -111,8 +115,7 @@ class _PullFlows(_GateNutrition):
|
||||
return
|
||||
self._delivery_asked = True
|
||||
self._set_status(f"{g.BUSY} {g.DELIVERY}")
|
||||
# Through the module object so the lazy hook resolves it, and so a
|
||||
# test's ``patch.object`` still wins.
|
||||
# Through the module object: the lazy hook, and ``patch.object``.
|
||||
self._delivery_result = start_delivery_fetch(
|
||||
sys.modules[__name__].refresh_delivery,
|
||||
now_local().date(),
|
||||
|
||||
92
diet_guard/_gatelock_peerpull.py
Normal file
92
diet_guard/_gatelock_peerpull.py
Normal file
@ -0,0 +1,92 @@
|
||||
"""The open gate window pulls peer logs on its own, every ~30 s.
|
||||
|
||||
``watch_credit`` (see :mod:`diet_guard._gatelock_credit`) fires on a *local*
|
||||
write to the food log, and until 2026-11-16 nothing on the PC wrote while the
|
||||
window was up: a meal logged on the phone waited for the user to press Fetch.
|
||||
This runs the Fetch button's own narrow pull -- :func:`pull_peer_logs` through
|
||||
:func:`start_fetch`, no new sync client -- on a timer. When a peer has logged
|
||||
something the pull writes the local log, and that write trips the watch.
|
||||
|
||||
* **Off the Tk thread**, a daemon worker and a Tk-side poll, exactly as the
|
||||
button does it.
|
||||
* **One pull at a time, shared with the button.** Both use the window's
|
||||
``fetch_result`` slot: a tick while the button's fetch runs does nothing, and
|
||||
a click while a tick's pull runs is ignored by the button's own guard.
|
||||
* **Silent and never an unlock.** No status line (it would say "nothing new"
|
||||
every 30 s over whatever the user is doing) and no direct close: the watch
|
||||
owns that, on the same ``due_slots`` verdict as every other path.
|
||||
* **Fail closed.** A failed pull is logged and retried at the next interval; the
|
||||
window stays up.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import queue
|
||||
from typing import TYPE_CHECKING, Protocol
|
||||
|
||||
from diet_guard._gatelock_fetch import FETCH_POLL_MS, start_fetch
|
||||
from diet_guard._sync_refresh import pull_peer_logs
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
from tkinter import Misc
|
||||
|
||||
__all__ = ["PEER_PULL_MS", "arm_peer_pull"]
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
|
||||
#: Between the end of one pull and the start of the next. A phone-logged meal
|
||||
#: closes the window within about this long.
|
||||
PEER_PULL_MS = 30_000
|
||||
|
||||
|
||||
class _PullHost(Protocol):
|
||||
"""The slice of the gate window the timer needs."""
|
||||
|
||||
root: Misc
|
||||
#: The shared in-flight slot; None when no pull is running.
|
||||
fetch_result: queue.Queue[str | None] | None
|
||||
|
||||
|
||||
def _poll_closure(host: _PullHost, interval_ms: int) -> Callable[[], None]:
|
||||
"""Build the Tk-side poll that collects a finished pull."""
|
||||
|
||||
def _poll() -> None:
|
||||
result = host.fetch_result
|
||||
if result is None:
|
||||
return
|
||||
try:
|
||||
reason = result.get_nowait()
|
||||
except queue.Empty:
|
||||
host.root.after(FETCH_POLL_MS, _poll)
|
||||
return
|
||||
host.fetch_result = None
|
||||
if reason is not None:
|
||||
_logger.warning("Background peer pull failed, retrying: %s", reason)
|
||||
host.root.after(interval_ms, _tick_closure(host, interval_ms))
|
||||
|
||||
return _poll
|
||||
|
||||
|
||||
def _tick_closure(host: _PullHost, interval_ms: int) -> Callable[[], None]:
|
||||
"""Build the timer callback: start a pull unless one is already running."""
|
||||
|
||||
def _tick() -> None:
|
||||
if host.fetch_result is not None:
|
||||
host.root.after(interval_ms, _tick)
|
||||
return
|
||||
host.fetch_result = start_fetch(pull_peer_logs)
|
||||
host.root.after(FETCH_POLL_MS, _poll_closure(host, interval_ms))
|
||||
|
||||
return _tick
|
||||
|
||||
|
||||
def arm_peer_pull(host: _PullHost, interval_ms: int = PEER_PULL_MS) -> None:
|
||||
"""Start pulling peer logs in the background while the window is up.
|
||||
|
||||
Args:
|
||||
host: The gate window (its Tk root and shared in-flight pull slot).
|
||||
interval_ms: Pause between pulls.
|
||||
"""
|
||||
host.root.after(interval_ms, _tick_closure(host, interval_ms))
|
||||
@ -27,6 +27,8 @@ from diet_guard._constants import FOOD_LOG_FILE
|
||||
from diet_guard._slot_wire import slot_fields
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pathlib import Path
|
||||
|
||||
from diet_guard._estimator import Nutrition
|
||||
|
||||
_logger = logging.getLogger(__name__)
|
||||
@ -194,6 +196,16 @@ def log_meal(
|
||||
return entry
|
||||
|
||||
|
||||
def food_log_path() -> Path:
|
||||
"""The food log's path, resolved through this module's global.
|
||||
|
||||
The one sanctioned way for a sibling to name the log (``FOOD_LOG_FILE`` may
|
||||
only be named here): the test redirect patches this module's constant, so a
|
||||
file watcher asking here watches the file ``log_meal`` really writes.
|
||||
"""
|
||||
return FOOD_LOG_FILE
|
||||
|
||||
|
||||
def load_log() -> DayLog:
|
||||
"""Return the log with only valid, non-deleted entries retained.
|
||||
|
||||
|
||||
@ -158,11 +158,14 @@ def refresh_peer_logs() -> None:
|
||||
return
|
||||
|
||||
seen: dict[str, str] = {}
|
||||
merged, changed = _merge_peer_logs(
|
||||
client, peers, remote_revs, daylog_to_log(read_raw_log()), seen
|
||||
)
|
||||
# Peers merge into an empty log; the local log is read only after the slow
|
||||
# network reads. A union is commutative, so the result is identical, but a
|
||||
# meal logged while the peers downloaded (the open gate now pulls on a
|
||||
# timer) is read here instead of being overwritten by a seconds-old snapshot.
|
||||
peer_log, changed = _merge_peer_logs(client, peers, remote_revs, {}, seen)
|
||||
if not changed:
|
||||
return
|
||||
merged = merge_logs(daylog_to_log(read_raw_log()), peer_log)
|
||||
|
||||
# Re-sign every entry, not just the newly arrived ones: a signature made on
|
||||
# another device is not valid under this device's key, and ``load_log``
|
||||
|
||||
@ -124,6 +124,8 @@ def state_redirects(tmp_path: Path) -> list[_patch[object]]:
|
||||
# entry point (narrow peer-log pull, not the full tick). Without
|
||||
# this every test that reaches `_should_lock` hits the real remote.
|
||||
patch("diet_guard._cli_gate.pull_peer_logs", return_value=None),
|
||||
# The open gate window's 30 s background pull: a third entry point.
|
||||
patch("diet_guard._gatelock_peerpull.pull_peer_logs", return_value=None),
|
||||
# The catering credentials and its cached session cookie. Redirected
|
||||
# for the same reason as `sync_token`: `_test_guard` raises on any
|
||||
# write under the real ~/.config/diet_guard, and a test that logs in
|
||||
|
||||
145
diet_guard/tests/test_gatelock_credit.py
Normal file
145
diet_guard/tests/test_gatelock_credit.py
Normal file
@ -0,0 +1,145 @@
|
||||
"""The open gate window notices a meal logged elsewhere (credit watch).
|
||||
|
||||
2026-11-16: ``watch_hold`` was the gate window's only passive watcher, so a
|
||||
meal the phone (or another process) logged while the window was up changed
|
||||
nothing until the user pressed Fetch. ``arm_credit_watch`` hands the shared
|
||||
``gatelock.watch_credit`` the food log, the existing ``due_slots`` check and
|
||||
the window's existing reconcile/close path.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, time
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from diet_guard import _gatelock_credit, _state
|
||||
from diet_guard._gate import due_slots
|
||||
from diet_guard._gatelock_credit import arm_credit_watch
|
||||
from diet_guard.tests.conftest import _nutrition
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from diet_guard._gatelock import MealGate
|
||||
|
||||
_FIRST, _SECOND, _THIRD = 480, 720, 960
|
||||
|
||||
|
||||
def _evening() -> datetime:
|
||||
"""17:00 local today: the 08:00, 12:00 and 16:00 slots have all elapsed."""
|
||||
return datetime.combine(_state.now_local().date(), time(17, 0)).astimezone()
|
||||
|
||||
|
||||
def _due_at_five_pm() -> tuple[int, ...]:
|
||||
"""The real ``due_slots`` check, frozen at 17:00 so it is deterministic."""
|
||||
return due_slots(_evening())
|
||||
|
||||
|
||||
class TestArming:
|
||||
"""What ``arm_credit_watch`` hands to the shared watcher."""
|
||||
|
||||
def test_watches_the_real_food_log_with_the_reconcile_path(self) -> None:
|
||||
"""The path is the file ``log_meal`` writes; on_credit is passed on."""
|
||||
root, on_credit = MagicMock(), MagicMock()
|
||||
with patch.object(_gatelock_credit, "watch_credit") as watch:
|
||||
arm_credit_watch(root, lambda: [_FIRST], on_credit)
|
||||
args = watch.call_args.args
|
||||
assert args[0] is root
|
||||
assert tuple(args[1]) == (_state.food_log_path(),)
|
||||
assert args[3] is on_credit
|
||||
|
||||
def test_done_means_every_pending_slot_is_covered(self) -> None:
|
||||
"""is_done is True only once no pending slot is still due."""
|
||||
pending = [_FIRST, _SECOND]
|
||||
with patch.object(_gatelock_credit, "watch_credit") as watch:
|
||||
arm_credit_watch(MagicMock(), lambda: pending, MagicMock())
|
||||
is_done = watch.call_args.args[2]
|
||||
with patch.object(_gatelock_credit, "due_slots", return_value=(_FIRST,)):
|
||||
assert is_done() is False
|
||||
with patch.object(_gatelock_credit, "due_slots", return_value=(_SECOND,)):
|
||||
assert is_done() is False
|
||||
with patch.object(_gatelock_credit, "due_slots", return_value=()):
|
||||
assert is_done() is True
|
||||
|
||||
def test_nothing_pending_is_not_a_credit(self) -> None:
|
||||
"""An empty pending list is the window's own state, not a credit."""
|
||||
with patch.object(_gatelock_credit, "watch_credit") as watch:
|
||||
arm_credit_watch(MagicMock(), list, MagicMock())
|
||||
with patch.object(_gatelock_credit, "due_slots", return_value=()):
|
||||
assert watch.call_args.args[2]() is False
|
||||
|
||||
def test_pending_is_read_fresh_each_poll(self) -> None:
|
||||
"""A reconcile that rebuilds the list is seen on the next poll."""
|
||||
holder = {"pending": [_FIRST]}
|
||||
with patch.object(_gatelock_credit, "watch_credit") as watch:
|
||||
arm_credit_watch(MagicMock(), lambda: holder["pending"], MagicMock())
|
||||
is_done = watch.call_args.args[2]
|
||||
with patch.object(_gatelock_credit, "due_slots", return_value=(_FIRST,)):
|
||||
assert is_done() is False
|
||||
holder["pending"] = [_SECOND]
|
||||
assert is_done() is True
|
||||
|
||||
|
||||
class TestWithTheRealLog:
|
||||
"""End to end on the real ``log_meal`` writer and the real watcher."""
|
||||
|
||||
def test_a_meal_written_elsewhere_closes_the_gate(self) -> None:
|
||||
"""Not done while a slot is due; the write that covers it fires once."""
|
||||
root, on_credit = MagicMock(), MagicMock()
|
||||
pending = [_FIRST, _SECOND, _THIRD]
|
||||
with patch.object(_gatelock_credit, "due_slots", _due_at_five_pm):
|
||||
arm_credit_watch(root, lambda: pending, on_credit)
|
||||
|
||||
def poll() -> None:
|
||||
root.after.call_args.args[1]()
|
||||
|
||||
poll() # log absent: asked once, still due
|
||||
on_credit.assert_not_called()
|
||||
_state.log_meal("a", _nutrition(), _FIRST)
|
||||
_state.log_meal("b", _nutrition(), _SECOND)
|
||||
poll() # moved, but the 16:00 slot is still owed
|
||||
on_credit.assert_not_called()
|
||||
_state.log_meal("c", _nutrition(), _THIRD)
|
||||
poll()
|
||||
on_credit.assert_called_once_with()
|
||||
assert root.after.call_count == 3 # armed + two re-arms, none after fire
|
||||
|
||||
|
||||
class TestRunWiring:
|
||||
"""``MealGate.run`` arms the watch and the pull in production, never in demo."""
|
||||
|
||||
def test_production_run_arms_the_credit_watch_and_the_pull(
|
||||
self, gate: MealGate
|
||||
) -> None:
|
||||
"""A real (non-demo) gate watches; on_credit is the reconcile path."""
|
||||
gate.demo_mode = False
|
||||
with (
|
||||
patch.object(gate._lock, "run"),
|
||||
patch("diet_guard._gatelock.watch_hold"),
|
||||
patch("diet_guard._gatelock.arm_credit_watch") as arm,
|
||||
patch("diet_guard._gatelock.arm_peer_pull") as pull,
|
||||
):
|
||||
gate.run()
|
||||
root, pending, on_credit = arm.call_args.args
|
||||
assert root is gate.root
|
||||
assert pending() is gate._pending
|
||||
assert on_credit == gate._reconcile_after_fetch
|
||||
pull.assert_called_once_with(gate)
|
||||
|
||||
def test_demo_run_never_arms_either(self, gate: MealGate) -> None:
|
||||
"""A demo window owes a synthetic slot: it must not close itself."""
|
||||
with (
|
||||
patch.object(gate._lock, "run"),
|
||||
patch("diet_guard._gatelock.watch_hold"),
|
||||
patch("diet_guard._gatelock.arm_credit_watch") as arm,
|
||||
patch("diet_guard._gatelock.arm_peer_pull") as pull,
|
||||
):
|
||||
gate.run()
|
||||
arm.assert_not_called()
|
||||
pull.assert_not_called()
|
||||
|
||||
def test_the_pull_slot_is_the_fetch_buttons_slot(self, gate: MealGate) -> None:
|
||||
"""One in-flight pull for both writers: the public slot is the button's."""
|
||||
assert gate.fetch_result is None
|
||||
marker = MagicMock()
|
||||
gate.fetch_result = marker
|
||||
assert gate._fetch_result is marker
|
||||
113
diet_guard/tests/test_gatelock_peerpull.py
Normal file
113
diet_guard/tests/test_gatelock_peerpull.py
Normal file
@ -0,0 +1,113 @@
|
||||
"""The open gate window pulls peer logs on its own every ~30 s.
|
||||
|
||||
2026-11-16: the credit watch only fires on a *local* write, and nothing on the PC
|
||||
wrote while the window was up, so a meal logged on the phone waited for the user
|
||||
to press Fetch. ``arm_peer_pull`` runs the Fetch button's own narrow pull
|
||||
(``pull_peer_logs``) on a timer; the write it makes trips the watch, which owns
|
||||
the close. So this path is silent and never unlocks anything itself.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import queue
|
||||
from types import SimpleNamespace
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from diet_guard import _gatelock_peerpull
|
||||
from diet_guard._gatelock_fetch import FETCH_POLL_MS
|
||||
from diet_guard._gatelock_peerpull import PEER_PULL_MS, arm_peer_pull
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import pytest
|
||||
|
||||
|
||||
def _host() -> SimpleNamespace:
|
||||
"""A stand-in gate: a recording Tk root and the shared in-flight slot."""
|
||||
root = MagicMock()
|
||||
return SimpleNamespace(
|
||||
root=root, fetch_result=None, _reconcile_after_fetch=MagicMock()
|
||||
)
|
||||
|
||||
|
||||
def _fire(host: SimpleNamespace) -> None:
|
||||
"""Run the callback most recently handed to ``root.after``."""
|
||||
host.root.after.call_args.args[1]()
|
||||
|
||||
|
||||
class TestTick:
|
||||
"""What one interval does."""
|
||||
|
||||
def test_arms_the_first_pull_one_interval_out(self) -> None:
|
||||
host = _host()
|
||||
arm_peer_pull(host)
|
||||
assert host.root.after.call_args.args[0] == PEER_PULL_MS == 30_000
|
||||
|
||||
def test_an_idle_tick_starts_the_narrow_pull_off_thread(self) -> None:
|
||||
host, result = _host(), queue.Queue[str | None](maxsize=1)
|
||||
with patch.object(
|
||||
_gatelock_peerpull, "start_fetch", return_value=result
|
||||
) as start:
|
||||
arm_peer_pull(host)
|
||||
_fire(host)
|
||||
start.assert_called_once_with(_gatelock_peerpull.pull_peer_logs)
|
||||
assert host.fetch_result is result
|
||||
assert host.root.after.call_args.args[0] == FETCH_POLL_MS
|
||||
|
||||
def test_a_tick_during_a_button_fetch_starts_nothing(self) -> None:
|
||||
"""One in-flight pull for both writers: the Fetch button's slot counts."""
|
||||
host = _host()
|
||||
host.fetch_result = busy = queue.Queue[str | None](maxsize=1)
|
||||
with patch.object(_gatelock_peerpull, "start_fetch") as start:
|
||||
arm_peer_pull(host)
|
||||
_fire(host)
|
||||
start.assert_not_called()
|
||||
assert host.fetch_result is busy
|
||||
assert host.root.after.call_args.args[0] == PEER_PULL_MS
|
||||
|
||||
def test_the_poll_waits_while_the_worker_runs(self) -> None:
|
||||
host, result = _host(), queue.Queue[str | None](maxsize=1)
|
||||
with patch.object(_gatelock_peerpull, "start_fetch", return_value=result):
|
||||
arm_peer_pull(host)
|
||||
_fire(host)
|
||||
_fire(host) # worker still running: nothing on the queue
|
||||
assert host.fetch_result is result
|
||||
assert host.root.after.call_args.args[0] == FETCH_POLL_MS
|
||||
|
||||
|
||||
class TestCompletion:
|
||||
"""What a finished pull does -- and, above all, does not do."""
|
||||
|
||||
def _finish(self, reason: str | None) -> tuple[SimpleNamespace, int]:
|
||||
host, result = _host(), queue.Queue[str | None](maxsize=1)
|
||||
with patch.object(_gatelock_peerpull, "start_fetch", return_value=result):
|
||||
arm_peer_pull(host)
|
||||
_fire(host)
|
||||
result.put(reason)
|
||||
_fire(host)
|
||||
return host, host.root.after.call_count
|
||||
|
||||
def test_success_is_silent_frees_the_slot_and_rearms(self) -> None:
|
||||
host, _ = self._finish(None)
|
||||
assert host.fetch_result is None
|
||||
assert host.root.after.call_args.args[0] == PEER_PULL_MS
|
||||
host._reconcile_after_fetch.assert_not_called() # the watch owns the close
|
||||
|
||||
def test_a_failure_is_logged_retried_and_never_unlocks(
|
||||
self, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
with caplog.at_level(logging.WARNING, logger=_gatelock_peerpull.__name__):
|
||||
host, _ = self._finish("sync unavailable (boom)")
|
||||
assert "sync unavailable (boom)" in caplog.text
|
||||
assert host.fetch_result is None
|
||||
assert host.root.after.call_args.args[0] == PEER_PULL_MS
|
||||
host._reconcile_after_fetch.assert_not_called()
|
||||
|
||||
def test_a_stray_poll_with_no_slot_does_nothing(self) -> None:
|
||||
host = _host()
|
||||
arm_peer_pull(host)
|
||||
poll = _gatelock_peerpull._poll_closure(host, PEER_PULL_MS)
|
||||
before = host.root.after.call_count
|
||||
poll()
|
||||
assert host.root.after.call_count == before
|
||||
51
diet_guard/tests/test_sync_refresh_race.py
Normal file
51
diet_guard/tests/test_sync_refresh_race.py
Normal file
@ -0,0 +1,51 @@
|
||||
"""A meal logged while a peer pull is in flight must survive it.
|
||||
|
||||
The gate now pulls on a timer, so a pull's network reads can overlap the user's
|
||||
own "Log & Continue". The merge must therefore read the local log *after* the
|
||||
peers have been fetched, immediately before the write -- not seconds earlier.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import patch
|
||||
|
||||
from diet_guard import _sync_client, _sync_refresh
|
||||
from diet_guard._state import log_meal
|
||||
from diet_guard._state_sync import read_raw_log
|
||||
from diet_guard.tests._sync_fakes import _mock_client, _nutrition, _write_token
|
||||
from diet_guard.tests.test_sync_refresh import _peer_log_text
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from crdt_sync import RemoteStore
|
||||
|
||||
|
||||
def _descs() -> set[str]:
|
||||
return {
|
||||
str(entry.get("desc"))
|
||||
for entries in read_raw_log().values()
|
||||
for entry in entries
|
||||
}
|
||||
|
||||
|
||||
def test_a_meal_logged_during_the_peer_read_is_not_overwritten() -> None:
|
||||
_write_token()
|
||||
text = _peer_log_text()
|
||||
client = _mock_client(
|
||||
devices=("phone",),
|
||||
files={"diet-guard-sync/devices-e2e/phone/food_log.json": text},
|
||||
)
|
||||
real_read = _sync_refresh.read_sealed
|
||||
|
||||
def read_then_user_logs(store: RemoteStore, path: str) -> str | None:
|
||||
got = real_read(store, path)
|
||||
log_meal("typed meanwhile", _nutrition(), 12) # lands mid-pull
|
||||
return got
|
||||
|
||||
with (
|
||||
patch.object(_sync_client, "GitHubSyncClient", return_value=client),
|
||||
patch.object(_sync_refresh, "read_sealed", read_then_user_logs),
|
||||
):
|
||||
_sync_refresh.refresh_peer_logs()
|
||||
|
||||
assert _descs() == {"peer porridge", "typed meanwhile"}
|
||||
Loading…
Reference in New Issue
Block a user