diet-guard/diet_guard/tests/test_sync_device_id.py
Krzysztof kuhy Rudnicki e23f7ac3b4
Some checks are pending
pre-commit / pre-commit (push) Waiting to run
Tests / test (3.10) (push) Waiting to run
Tests / test (3.11) (push) Waiting to run
Tests / test (3.12) (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
Push under a persisted per-install uuid, not a fixed role id
diet_guard pushed as "pc" (Python), "phone" (Android) and "desktop" (web).
A role constant collides the moment a second machine takes the same role,
and after a reinstall the new install inherits the previous one's CRDT
identity -- the same reasoning home_inventory already records for choosing a
uuid. Both halves now mint a uuid once and persist it: the PC in
~/.local/share/diet_guard/.device_id, the app under SharedPreferences
'crdt.nodeId' (the key todo and home_inventory already use).

The old constant survives as the legacy id and is passed to sync_log /
syncLog, so devices/<legacy>/ is skipped as this device's own. Without that
every tick would re-download and re-merge this device's own pre-migration
log as though a peer had written it -- idempotent under LWW, but hundreds of
KB, 96 times a day. It drops to None once that path is reclaimed; a test
covers both states, including a negative control proving the skip is the
legacy id's doing.

All four documents move together (food_log, food_bank, food_bank_manual,
budget), and the hist:<date> fields riding on the budget record are
untouched -- merge_record unions field names, so they relay through
unchanged.

The resolver lives in its own module (_device.py / sync_device_id.dart)
because _sync_merge needs it for HLC stamping too and importing _sync there
would be a cycle. Dart resolves it asynchronously at startup, before
LogStorageService.init(); currentSyncDeviceId falls back to the compile-time
role constant until then, so a too-early Hlc stamp gets a valid id rather
than crashing.

conftest redirects the new id file in the same change that introduces it --
without that a test mints a uuid into the real state dir and this machine's
live sync identity is decided by whichever test ran first. Verified by
checking ~/.local/share/diet_guard/ before and after: untouched.

Verified live, not just against mocks: the sync timer ran mid-change and
migrated this machine to f8f46da6. All 358 food_log records and all 100
food_bank records are present under the new path (0 missing vs devices/pc/),
and the new log's HLCs carry only its own id -- confirming it did not
re-merge the old path as a peer.

Python: 687 tests, 100% branch coverage. App: 518 tests, analyzer clean.
Pins bumped to crdt-sync-v0.6.0 / crdt_sync_dart-v0.7.0 (pyproject,
requirements.txt, .pre-commit-config.yaml, pubspec), and the new library is
installed into /usr/bin/python's user site-packages so the production timer
does not ImportError on its next tick.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GZH89WEqAjuJT8WZdqc7AP
2026-08-09 17:18:42 +02:00

65 lines
2.5 KiB
Python

"""Tests for this machine's persisted sync device id.
Split out of ``test_sync.py`` to keep it under the repo's 500-line cap.
Covers the migration from the fixed ``"pc"`` role constant to a per-install
uuid -- specifically that the old path is still recognised as this device's
own, so its pre-migration log is not re-merged as a peer's.
"""
from __future__ import annotations
from unittest.mock import MagicMock
from crdt_sync import DeviceIdentity, SyncState
from diet_guard import _sync
from diet_guard._device import device_id, device_identity
def _mock_client(*, devices: tuple[str, ...] = ()) -> MagicMock:
"""Build a mock sync client that lists ``devices`` and holds no files."""
client = MagicMock()
client.list_directory.return_value = list(devices)
client.get_file_text.side_effect = lambda _path: None
del client.get_string_map
return client
class TestPullSkipsOwnLegacyPath:
"""The uuid migration leaves this device's old 'pc' log behind."""
def test_skips_the_devices_own_legacy_id(self) -> None:
"""devices/pc/ is this machine's own history, not a peer's.
Without the legacy id in the skip set, every tick would download and
re-merge the log this machine pushed before it migrated -- idempotent
under LWW, but hundreds of KB of pure waste, 96 times a day.
"""
client = _mock_client(devices=("pc", "phone"))
state = SyncState(pushed_rev=None, peer_revs={})
seen: dict[str, str] = {}
_sync._pull_remote_logs(client, {}, state, seen, device_identity())
fetched = [call.args[0] for call in client.get_file_text.call_args_list]
assert "diet-guard-sync/devices/pc/food_log.json" not in fetched
assert "diet-guard-sync/devices/phone/food_log.json" in fetched
def test_pulls_the_legacy_path_once_it_is_disowned(self) -> None:
"""Negative control: with no legacy id, devices/pc/ IS a peer.
Proves the skip above is the legacy id's doing, not an artifact of
the fixture -- and documents what happens after the old path is
reclaimed and SYNC_LEGACY_DEVICE_ID drops to None.
"""
client = _mock_client(devices=("pc",))
state = SyncState(pushed_rev=None, peer_revs={})
seen: dict[str, str] = {}
_sync._pull_remote_logs(
client, {}, state, seen, DeviceIdentity(device_id=device_id())
)
fetched = [call.args[0] for call in client.get_file_text.call_args_list]
assert "diet-guard-sync/devices/pc/food_log.json" in fetched