diff --git a/gatelock/README.md b/gatelock/README.md index b643c5f..abf7fb5 100644 --- a/gatelock/README.md +++ b/gatelock/README.md @@ -78,6 +78,15 @@ that is stood down but not done (`build_corner_strip`, `CornerStrip`, `StripContent`, `corner_rect`, `corner_geometry`). It never grabs input; its tick ends when the owner's `supply` returns `None`. +`gatelock.watch_credit(root, paths, is_done, on_credit, poll_ms=3000)` lets an +open lock window notice a credit that landed while it was up (a workout or meal +logged elsewhere). One `stat` per path per poll on the Tk `after` loop; the +owner's `is_done()` runs only on the first poll and when a path's (mtime, size, +inode) changed; True calls `on_credit` (the window's normal close) and stops. +A raising `is_done`/`on_credit` or an unreadable path is logged and retried +(fail closed). Pass `poll_ms` of 3000 or less: an open window should notice +inside ~10 s. Generalises screen-locker's `_credit_watch`. + `gatelock.night_lockdown.evening_lockdown_today` answers "has tonight's evening night-lockdown already happened?" from night-lockdown's `/var/lib/night-lockdown/locked_at_epoch` (local date today, local time diff --git a/gatelock/gatelock/__init__.py b/gatelock/gatelock/__init__.py index 1e9cc3d..64f564c 100644 --- a/gatelock/gatelock/__init__.py +++ b/gatelock/gatelock/__init__.py @@ -17,6 +17,7 @@ from gatelock._arbiter import ( from gatelock._claimfile import held_grabs from gatelock._claims import ArbiterVerdict, Claim, default_runtime_dir, grab_strength from gatelock._config import GrabPolicy, LockConfig, SpaceStep, TypeRole +from gatelock._credit_watch import CREDIT_POLL_MS, watch_credit from gatelock._detect import OutputChangeDetector from gatelock._escape import ( EscapeDraft, @@ -72,6 +73,7 @@ from gatelock.widgets import ( ) __all__ = [ + "CREDIT_POLL_MS", "DEFAULT_WRAP", "QUEUE_DEADLINE_SECONDS", "QUEUE_HEARTBEAT_SECONDS", @@ -137,4 +139,5 @@ __all__ = [ "stronger_claims", "wait_for_turn", "wait_for_x_server", + "watch_credit", ] diff --git a/gatelock/gatelock/_credit_watch.py b/gatelock/gatelock/_credit_watch.py new file mode 100644 index 0000000..a6733e7 --- /dev/null +++ b/gatelock/gatelock/_credit_watch.py @@ -0,0 +1,122 @@ +# Copyright (c) 2026 Krzysztof Rudnicki +"""An open lock window notices a credit that landed while it was up. + +Born in screen-locker (2026-11-16): the window opened at 07:55, a workout was +credited at 07:59 by a separate daemon, and the open window never noticed -- +the startup ladder reads the log once. This is the shared form of that fix, so +every gate that earns its way down can take itself down the same way. + +Event-driven on the Tk ``after`` loop, no thread, no dependency. Each poll is +one ``stat`` per watched file; the owner's "is it done today?" verdict (which +may parse and HMAC-check the log) runs only when a file's (mtime, size, inode) +moved, plus once on the first poll. The credit itself was already written by +whoever earned it, so ``on_credit`` writes nothing: it only takes the window +down through the owner's normal close path. + +Failure modes, chosen out loud: **fail closed**. A file that cannot be stat'ed +or a verdict that raises is logged and retried at the next poll; the lock stays +up. Only a verdict of True ever lifts it. +""" + +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING, Final + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + from pathlib import Path + from tkinter import Misc + +__all__ = ["CREDIT_POLL_MS", "watch_credit"] + +_logger: Final = logging.getLogger(__name__) + +# Well inside the 10 s an open window may take to notice a credit. +CREDIT_POLL_MS: Final = 3_000 + +_Signature = tuple[tuple[int, ...], ...] +# Never equals a real signature, so the first poll always asks. +_UNSEEN: Final[_Signature] = ((-1,),) +_ABSENT: Final[tuple[int, ...]] = () +# What a verdict or close path may raise on a bad read; anything else is a bug +# and should surface, not be swallowed by a watcher. +_CHECK_ERRORS: Final = (OSError, ValueError, TypeError, LookupError, RuntimeError) + + +def _signature(paths: Sequence[Path], poll_ms: int) -> _Signature | None: + """(mtime_ns, size, inode) per path: ``()`` if absent, None if unreadable.""" + parts: list[tuple[int, ...]] = [] + for path in paths: + try: + stat = path.stat() + except FileNotFoundError: + # A file nobody has written yet is normal, not a fault. + parts.append(_ABSENT) + continue + except OSError as exc: + _logger.warning( + "Could not stat %s while the lock is up (%s) -- keeping the " + "lock and trying again in %d s", + path, + exc, + poll_ms // 1000, + ) + return None + parts.append((stat.st_mtime_ns, stat.st_size, stat.st_ino)) + return tuple(parts) + + +def watch_credit( + root: Misc, + paths: Sequence[Path], + is_done: Callable[[], bool], + on_credit: Callable[[], None], + poll_ms: int = CREDIT_POLL_MS, +) -> None: + """Hand a credit that landed while the window is up to ``on_credit``. + + Args: + root: The Tk root whose ``after`` loop drives the polling. + paths: Files whose change can mean a credit landed (the log the owner + reads). Absent files are fine; they count as "not there yet". + is_done: The owner's own "is today satisfied?" check. Called on the + first poll and whenever a watched file changed, never otherwise. + on_credit: Called once when ``is_done`` returns True; should close the + window through its normal path. The watch stops re-arming then. + poll_ms: Interval between polls. + + Raises: + ValueError: ``paths`` is empty or ``poll_ms`` is not positive. + + An ``is_done`` or ``on_credit`` that raises an OSError, ValueError, + TypeError, LookupError or RuntimeError is logged and retried at the + next poll: one bad read must not end the only thing watching. + """ + if not paths: + msg = "watch_credit needs at least one path to watch (paths is empty)" + raise ValueError(msg) + if poll_ms <= 0: + msg = f"poll_ms must be positive, got {poll_ms}" + raise ValueError(msg) + seen = _UNSEEN + + def _tick() -> None: + nonlocal seen + sig = _signature(paths, poll_ms) + if sig is not None and sig != seen: + seen = sig + try: + if is_done(): + on_credit() + return + except _CHECK_ERRORS: + _logger.exception( + "Credit check failed while the lock is up -- keeping the " + "lock and trying again in %d s", + poll_ms // 1000, + ) + seen = _UNSEEN + root.after(poll_ms, _tick) + + root.after(poll_ms, _tick) diff --git a/gatelock/gatelock/tests/test_credit_watch.py b/gatelock/gatelock/tests/test_credit_watch.py new file mode 100644 index 0000000..ae51042 --- /dev/null +++ b/gatelock/gatelock/tests/test_credit_watch.py @@ -0,0 +1,229 @@ +# Copyright (c) 2026 Krzysztof Rudnicki +"""``watch_credit``: a credit that lands while a lock window is up is noticed. + +Driven by hand on a ``MagicMock`` root: ``root.after`` records the next poll, +the test runs it, so no display and no real clock are involved. +""" + +from __future__ import annotations + +import logging +import os +from pathlib import Path +from typing import TYPE_CHECKING +from unittest.mock import MagicMock, patch + +import pytest + +import gatelock +from gatelock import CREDIT_POLL_MS, watch_credit + +if TYPE_CHECKING: + from collections.abc import Callable + + +def _arm( + paths: list[Path], + *, + done: list[bool] | None = None, + poll_ms: int | None = None, +) -> tuple[MagicMock, MagicMock, MagicMock, Callable[[], None]]: + """Arm a watch; return (root, is_done, on_credit, run-next-poll).""" + root = MagicMock() + verdicts = iter(done if done is not None else [False] * 50) + is_done = MagicMock(side_effect=lambda: next(verdicts)) + on_credit = MagicMock() + if poll_ms is None: + watch_credit(root, paths, is_done, on_credit) + else: + watch_credit(root, paths, is_done, on_credit, poll_ms=poll_ms) + + def poll() -> None: + """Run the callback the last ``root.after`` call scheduled.""" + root.after.call_args.args[1]() + + return root, is_done, on_credit, poll + + +class TestArming: + """What arming does before the first poll.""" + + def test_exported_from_the_package(self) -> None: + """The helper is public API, like the other gatelock helpers.""" + assert "watch_credit" in gatelock.__all__ + assert "CREDIT_POLL_MS" in gatelock.__all__ + + def test_first_poll_is_scheduled_at_the_default_rate(self, tmp_path: Path) -> None: + """Nothing is read at arm time; the first poll is one interval away.""" + root, is_done, on_credit, _ = _arm([tmp_path / "log.json"]) + root.after.assert_called_once() + assert root.after.call_args.args[0] == CREDIT_POLL_MS == 3_000 + is_done.assert_not_called() + on_credit.assert_not_called() + + def test_custom_poll_rate(self, tmp_path: Path) -> None: + """``poll_ms`` sets the interval of every poll.""" + root, _, _, poll = _arm([tmp_path / "log.json"], poll_ms=500) + assert root.after.call_args.args[0] == 500 + poll() + assert root.after.call_args.args[0] == 500 + + def test_no_paths_is_refused(self) -> None: + """A watch with nothing to stat could never see a change.""" + with pytest.raises(ValueError, match="paths"): + watch_credit(MagicMock(), [], MagicMock(), MagicMock()) + + @pytest.mark.parametrize("poll_ms", [0, -5]) + def test_non_positive_poll_is_refused(self, tmp_path: Path, poll_ms: int) -> None: + """A zero interval would spin the Tk loop.""" + with pytest.raises(ValueError, match="poll_ms"): + watch_credit( + MagicMock(), + [tmp_path / "a"], + MagicMock(), + MagicMock(), + poll_ms=poll_ms, + ) + + +class TestPolling: + """One stat per path per poll; the verdict only when a file moved.""" + + def test_first_poll_asks_even_when_the_file_is_absent(self, tmp_path: Path) -> None: + """A credit may land between startup and arming: ask once up front.""" + root, is_done, on_credit, poll = _arm([tmp_path / "log.json"]) + poll() + is_done.assert_called_once_with() + on_credit.assert_not_called() + assert root.after.call_count == 2 + + def test_unchanged_file_is_not_asked_again(self, tmp_path: Path) -> None: + """Steady state costs one stat per poll and no parse.""" + log = tmp_path / "log.json" + log.write_text("{}") + _, is_done, _, poll = _arm([log]) + for _ in range(5): + poll() + assert is_done.call_count == 1 + + def test_a_changed_file_is_asked_again(self, tmp_path: Path) -> None: + """A write moves (mtime, size, inode): the verdict is re-read.""" + log = tmp_path / "log.json" + log.write_text("{}") + _, is_done, _, poll = _arm([log]) + poll() + log.write_text('{"meal": 1}') + poll() + assert is_done.call_count == 2 + + def test_a_replaced_file_is_asked_again(self, tmp_path: Path) -> None: + """An atomic replace of equal size and mtime still changes the inode.""" + log = tmp_path / "log.json" + log.write_text("aaaa") + stamp = log.stat().st_mtime_ns + _, is_done, _, poll = _arm([log]) + poll() + replacement = tmp_path / "log.json.tmp" + replacement.write_text("bbbb") + os.utime(replacement, ns=(stamp, stamp)) + replacement.replace(log) + poll() + assert is_done.call_count == 2 + + def test_a_file_appearing_is_asked_again(self, tmp_path: Path) -> None: + """Absent -> present is a change.""" + log = tmp_path / "log.json" + _, is_done, _, poll = _arm([log]) + poll() + log.write_text("{}") + poll() + assert is_done.call_count == 2 + + def test_any_watched_path_counts(self, tmp_path: Path) -> None: + """A change in the second file triggers the check too.""" + first, second = tmp_path / "a.json", tmp_path / "b.json" + first.write_text("{}") + second.write_text("{}") + _, is_done, _, poll = _arm([first, second]) + poll() + second.write_text('{"x": 1}') + poll() + assert is_done.call_count == 2 + + +class TestCredit: + """What happens when the verdict flips.""" + + def test_credit_fires_once_and_stops_polling(self, tmp_path: Path) -> None: + """``on_credit`` runs, and the watch does not re-arm behind it.""" + log = tmp_path / "log.json" + root, _, on_credit, poll = _arm([log], done=[True]) + poll() + on_credit.assert_called_once_with() + assert root.after.call_count == 1 + + def test_credit_after_a_later_write(self, tmp_path: Path) -> None: + """Not done at the first poll, done once the file is rewritten.""" + log = tmp_path / "log.json" + log.write_text("{}") + root, _, on_credit, poll = _arm([log], done=[False, True]) + poll() + on_credit.assert_not_called() + log.write_text('{"meal": 1}') + poll() + on_credit.assert_called_once_with() + assert root.after.call_count == 2 + + +class TestFailures: + """One bad read must not end the only thing watching; none is silent.""" + + def test_is_done_error_is_logged_and_retried( + self, tmp_path: Path, caplog: pytest.LogCaptureFixture + ) -> None: + """A raising check logs, re-arms and asks again without a file change.""" + log = tmp_path / "log.json" + log.write_text("{}") + root = MagicMock() + is_done = MagicMock(side_effect=[ValueError("bad row"), True]) + on_credit = MagicMock() + watch_credit(root, [log], is_done, on_credit) + with caplog.at_level(logging.WARNING, logger="gatelock._credit_watch"): + root.after.call_args.args[1]() + assert "bad row" in caplog.text + assert root.after.call_count == 2 + root.after.call_args.args[1]() + on_credit.assert_called_once_with() + + def test_on_credit_error_is_logged_and_retried( + self, tmp_path: Path, caplog: pytest.LogCaptureFixture + ) -> None: + """A close path that raised leaves the window up: keep watching.""" + log = tmp_path / "log.json" + root = MagicMock() + on_credit = MagicMock(side_effect=[RuntimeError("close failed"), None]) + watch_credit(root, [log], MagicMock(return_value=True), on_credit) + with caplog.at_level(logging.WARNING, logger="gatelock._credit_watch"): + root.after.call_args.args[1]() + assert "close failed" in caplog.text + assert root.after.call_count == 2 + root.after.call_args.args[1]() + assert on_credit.call_count == 2 + + def test_stat_error_keeps_the_lock_and_retries( + self, tmp_path: Path, caplog: pytest.LogCaptureFixture + ) -> None: + """An unreadable file is "could not check": logged, never "done".""" + log = tmp_path / "log.json" + log.write_text("{}") + _, is_done, on_credit, poll = _arm([log], done=[True]) + with ( + patch.object(Path, "stat", side_effect=PermissionError("denied")), + caplog.at_level(logging.WARNING, logger="gatelock._credit_watch"), + ): + poll() + assert "denied" in caplog.text + is_done.assert_not_called() + on_credit.assert_not_called() + poll() + on_credit.assert_called_once_with() diff --git a/gatelock/pyproject.toml b/gatelock/pyproject.toml index 124c5a7..684ba3e 100644 --- a/gatelock/pyproject.toml +++ b/gatelock/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "gatelock" -version = "0.13.0" +version = "0.14.0" description = "Shared per-output lock-window + HMAC log-integrity backend for blocking-overlay apps" requires-python = ">=3.14" dependencies = [] # pure stdlib — tkinter is bundled with Python