Compare commits

..

4 Commits

Author SHA1 Message Date
cc5075ba53 Cover _tombstoned_ids
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
Tests / lock-popup-safety (push) Waiting to run
release-apk / release (APK) (push) Waiting to run
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018M5gKyYzxWG6QkCaj1wWfk
2026-08-21 13:43:34 +02:00
cdee896d43 Apply sync tombstones across the device union, not per device log
The previous commit dropped tombstoned records while reading each device
log, which was not enough: _merge_device_records unions across devices
keeping the highest HLC, so a record tombstoned on one device and still
live on another was simply absent from one dict and won the merge from
the other -- ingested exactly as before.

Collect tombstoned ids across every device log, then suppress by id
after the union. crdt-sync makes deletion monotonic inside its own merge
for this reason; this reader rolls its own merge, so it has to honour
the same rule itself.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018M5gKyYzxWG6QkCaj1wWfk
2026-08-21 13:38:52 +02:00
590f606856 Honour crdt-sync tombstones when ingesting synced workouts
_records_matching read every record's payload and never checked
record.deleted, so a tombstoned workout was ingested like a live one.
Deleting a workout in the phone app therefore looked like it worked and
came back on the next 15-minute sync, silently re-crediting it.

crdt-sync deletion is monotonic (a tombstone cannot be resurrected by
merging an older, non-deleted copy), so this is the only durable way to
retract a synced workout across devices. Skip tombstoned records and say
so at info, since "this stopped counting" is exactly the kind of thing
that must not happen silently.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018M5gKyYzxWG6QkCaj1wWfk
2026-08-21 13:35:53 +02:00
426b9372be Opt in to preempting a weaker gatelock holder
gatelock just made preempt_weaker_holder opt-in (it defaulted to True,
which let wake_alarm evict this armed lock). screen_locker is the app
that actually needs it: on 2026-08-21 diet_guard held the global grab
from 07:04 to 09:07+ while this locker retried against it, which is the
contention behind the reported lockout.

Production only -- demo mode uses a local grab and never contends.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018M5gKyYzxWG6QkCaj1wWfk
2026-08-21 13:31:57 +02:00
5 changed files with 141 additions and 1 deletions

View File

@ -55,11 +55,38 @@ def _session_records(log_json: str) -> dict[str, tuple[dict, Hlc]]:
return _records_matching(log_json, _is_session_payload)
def _tombstoned_ids(log_json: str) -> set[str]:
"""Return the ids this device log marks deleted.
Collected separately from :func:`_records_matching` because suppression has
to be applied across the whole device union, not per file: one device
tombstoning a record while another still holds it live must delete it, and
a per-file skip would just let the live copy win the merge.
Raises the same decode errors as :func:`_records_matching`.
"""
raw = json.loads(log_json)
if not isinstance(raw, dict):
msg = f"top-level sync payload is not a JSON object: {raw!r}"
raise TypeError(msg)
return {
record.id
for record in (Record.from_dict(data) for data in raw.values())
if record.deleted
}
def _records_matching(
log_json: str, predicate: Callable[[object], bool]
) -> dict[str, tuple[dict, Hlc]]:
"""Return ``{record_id: (payload, hlc)}`` for payloads passing ``predicate``.
Tombstoned records are skipped. crdt-sync deletion is monotonic -- a
tombstone can never be resurrected by merging an older, non-deleted copy --
so ``deleted`` is the only way a workout removed on one device can stop
counting on another. Without this check, deleting a workout in the phone
app looked like it worked and then the next 15-minute sync re-ingested it.
Raises:
TypeError: If the top-level JSON isn't an object or a record's shape
doesn't match what :meth:`Record.from_dict` expects.
@ -73,6 +100,13 @@ def _records_matching(
result: dict[str, tuple[dict, Hlc]] = {}
for data in raw.values():
record = Record.from_dict(data)
if record.deleted:
_logger.info(
"Sync record %s is tombstoned — skipping it, so a workout "
"deleted on another device stops counting here too",
record.id,
)
continue
field = record.fields.get(_PAYLOAD_FIELD)
if field is None:
continue

View File

@ -36,6 +36,7 @@ from screen_locker._sync_records import (
_manual_records,
_records_matching,
_session_records,
_tombstoned_ids,
)
from screen_locker._sync_retry import with_sync_retry
@ -115,6 +116,7 @@ def _merge_device_records(
return {}
merged: dict[str, tuple[dict, Hlc]] = {}
tombstoned: set[str] = set()
for device in devices:
path = f"{_DEVICES_PREFIX}/{device}/log.json"
try:
@ -132,6 +134,7 @@ def _merge_device_records(
continue
try:
records = extract(text)
tombstoned |= _tombstoned_ids(text)
except (ValueError, KeyError, TypeError) as exc:
_logger.warning("Corrupt sync data at %s: %s", path, exc)
continue
@ -140,6 +143,19 @@ def _merge_device_records(
if existing is None or existing[1] < hlc:
merged[rid] = (payload, hlc)
# Applied after the union, not per device: one device deleting a record
# while another still holds it live must delete it. crdt-sync's own merge
# makes deletion monotonic for exactly this reason, and this reader rolls
# its own merge, so it has to honour the same rule itself.
for rid in tombstoned & merged.keys():
_logger.info(
"Synced record %s is tombstoned on another device — dropping it, "
"so a deleted %s stops counting here too",
rid,
what,
)
del merged[rid]
return merged

View File

@ -156,6 +156,12 @@ class ScreenLocker(
mode="hard",
grab="local" if demo_mode else "global",
disable_vt=not demo_mode,
# Opt in: a weaker holder (diet_guard, leetcode_guard) that already
# owns the grab must stand down rather than block enforcement
# forever -- the 2026-08-21 lockout was diet_guard holding it for
# hours. Safe in this direction only; gatelock never signals a
# holder that outranks us, so wake_alarm can still take the screen.
preempt_weaker_holder=not demo_mode,
)
# Built before setup(), which calls build_surface per live output.
self.container = FrameGroup([])

View File

@ -12,7 +12,7 @@ import json
from crdt_sync import Hlc, Record
import pytest
from screen_locker import _workout_sync
from screen_locker import _sync_records, _workout_sync
from screen_locker.tests._workout_sync_fixtures import (
_manual_payload,
_manual_record_dict,
@ -155,3 +155,25 @@ class TestManualRecords:
"""Raises type error when top level is not an object."""
with pytest.raises(TypeError, match="not a JSON object"):
_workout_sync._manual_records(json.dumps([1, 2, 3]))
class TestTombstonedIds:
"""TombstonedIds."""
def test_returns_only_the_deleted_ids(self) -> None:
"""Returns only the deleted ids."""
hlc = Hlc(wall_time_ms=1, counter=0, node_id="phone")
live = Record(id="live", fields={"payload": ({"a": 1}, hlc)})
gone = Record(
id="gone",
fields={"payload": ({"a": 1}, hlc)},
deleted=True,
deleted_hlc=hlc,
)
log = {"x": live.to_dict(), "y": gone.to_dict()}
assert _sync_records._tombstoned_ids(json.dumps(log)) == {"gone"}
def test_raises_type_error_when_top_level_is_not_an_object(self) -> None:
"""Raises type error when top level is not an object."""
with pytest.raises(TypeError, match="not a JSON object"):
_sync_records._tombstoned_ids(json.dumps([1, 2, 3]))

View File

@ -11,6 +11,8 @@ from unittest.mock import MagicMock, patch
from crdt_sync import (
GitHubSyncError,
Hlc,
Record,
)
from screen_locker import _sync_client, _workout_sync
@ -53,6 +55,66 @@ class TestPullAllManualRecords:
result = _workout_sync.pull_all_manual_records()
assert sorted(rid for rid, _ in result) == ["manual:a", "manual:b"]
def test_skips_a_tombstoned_record(self) -> None:
"""A workout deleted on another device must stop counting here.
crdt-sync deletion is monotonic, so the tombstone is the only durable
way to retract a synced workout. Ingesting it anyway made a delete in
the phone app look like it worked and then silently come back on the
next 15-minute sync.
"""
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
hlc = Hlc(wall_time_ms=1000, counter=0, node_id="phone")
tombstoned = Record(
id="manual:gone",
fields={"payload": (_manual_payload(), hlc)},
deleted=True,
deleted_hlc=hlc,
).to_dict()
client = _multi_device_client(
{
"phone": json.dumps(
{
"a": _manual_record_dict("manual:kept", _manual_payload()),
"b": tombstoned,
}
),
}
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
result = _workout_sync.pull_all_manual_records()
assert [rid for rid, _ in result] == ["manual:kept"]
def test_a_tombstone_on_one_device_beats_a_live_copy_on_another(self) -> None:
"""Suppression must apply across the union, not per device log.
The per-file skip alone was not enough: the tombstone was merely
absent from one device's dict while the live copy won the merge from
the other, so the record was ingested exactly as before.
"""
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")
hlc = Hlc(wall_time_ms=1000, counter=0, node_id="phone")
tombstoned = Record(
id="manual:dup",
fields={"payload": (_manual_payload(), hlc)},
deleted=True,
deleted_hlc=hlc,
).to_dict()
client = _multi_device_client(
{
"phone": json.dumps({"x": tombstoned}),
"pc": json.dumps(
{
"y": _manual_record_dict("manual:dup", _manual_payload()),
"z": _manual_record_dict("manual:keep", _manual_payload()),
}
),
}
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
result = _workout_sync.pull_all_manual_records()
assert [rid for rid, _ in result] == ["manual:keep"]
def test_skips_missing_and_corrupt_device_logs(self) -> None:
"""Skips missing and corrupt device logs."""
_workout_sync.SYNC_TOKEN_FILE.write_text("tok")