diff --git a/gatelock/gatelock/_error_spool.py b/gatelock/gatelock/_error_spool.py index 6bbe47f..228565a 100644 --- a/gatelock/gatelock/_error_spool.py +++ b/gatelock/gatelock/_error_spool.py @@ -84,7 +84,11 @@ class Reporter: version: str | None = None threshold: float = 1.0 still_after: float = 5.0 + #: Wall time: entry timestamps, ids and the rate-limit minutes. clock: Callable[[], float] = time.time + #: Elapsed time for waits. Never the wall clock: chrony stepped it 1.33 s + #: into a fresh lock on 2026-11-25 and that read as a 1.5 s freeze. + monotonic: Callable[[], float] = time.monotonic _guard: _Guard = field(default_factory=_Guard) def __post_init__(self) -> None: @@ -184,7 +188,7 @@ class Reporter: self, operation, route, - self.clock(), + self.monotonic(), f"{int(self.clock() * 1000):x}-{self._guard.serial}", ) @@ -218,7 +222,7 @@ class SlowWait: self._timer.start() def _ms(self) -> int: - return round((self.reporter.clock() - self.started) * 1000) + return round((self.reporter.monotonic() - self.started) * 1000) def _still(self) -> None: if self._ended: diff --git a/gatelock/gatelock/_randr.py b/gatelock/gatelock/_randr.py index 4fe2c40..98f97ca 100644 --- a/gatelock/gatelock/_randr.py +++ b/gatelock/gatelock/_randr.py @@ -42,8 +42,8 @@ if TYPE_CHECKING: output: int class _XRoot(Protocol): - def xrandr_get_screen_resources(self) -> _ScreenResources: - """Mirror ``root.xrandr_get_screen_resources()``.""" + def xrandr_get_screen_resources_current(self) -> _ScreenResources: + """Mirror ``root.xrandr_get_screen_resources_current()``.""" def xrandr_get_output_primary(self) -> _PrimaryReply: """Mirror ``root.xrandr_get_output_primary()``.""" @@ -124,7 +124,10 @@ class RandrBackend: def _scan(self) -> tuple[Output, ...]: """Enumerate outputs via RandR. Raises on any protocol problem.""" root = self._display.screen().root - resources = root.xrandr_get_screen_resources() + # The cached server state, not a full re-probe of every output (53 ms + # vs 0.2 ms on NVIDIA, on the Tk thread every recovery tick). Hotplug + # still lands: the driver updates that state and sends the RandR event. + resources = root.xrandr_get_screen_resources_current() timestamp = resources.config_timestamp primary_id = self._primary_output_id(root) diff --git a/gatelock/gatelock/_xrandr.py b/gatelock/gatelock/_xrandr.py index 66882aa..699f3a7 100644 --- a/gatelock/gatelock/_xrandr.py +++ b/gatelock/gatelock/_xrandr.py @@ -1,5 +1,5 @@ # Copyright (c) 2026 Krzysztof Rudnicki -"""Reading outputs by shelling out to `xrandr --query`. +"""Reading outputs by shelling out to `xrandr --current`. Split from :mod:`gatelock._outputs`, which keeps the value types and the enumerator that picks a source. This is the fallback path: slower than the @@ -77,7 +77,7 @@ def parse_xrandr_query(text: str) -> tuple[Output, ...]: def scan_xrandr() -> tuple[Output, ...] | None: - """Enumerate outputs by shelling out to ``xrandr --query``. + """Enumerate outputs by shelling out to ``xrandr --current``. Returns: The parsed outputs, or None if xrandr is missing, failed, timed out or @@ -89,24 +89,24 @@ def scan_xrandr() -> tuple[Output, ...] | None: return None try: completed = subprocess.run( - [binary, "--query"], + [binary, "--current"], capture_output=True, text=True, timeout=_XRANDR_TIMEOUT_S, check=False, ) except (subprocess.TimeoutExpired, OSError) as exc: - _logger.warning("xrandr --query failed to run: %s", exc) + _logger.warning("xrandr --current failed to run: %s", exc) return None if completed.returncode != 0: _logger.warning( - "xrandr --query exited %d: %s", + "xrandr --current exited %d: %s", completed.returncode, completed.stderr.strip(), ) return None outputs = parse_xrandr_query(completed.stdout) if not outputs: - _logger.warning("xrandr --query produced no parseable output lines") + _logger.warning("xrandr --current produced no parseable output lines") return None return outputs diff --git a/gatelock/gatelock/error_report.py b/gatelock/gatelock/error_report.py index 52dc636..b3044f6 100644 --- a/gatelock/gatelock/error_report.py +++ b/gatelock/gatelock/error_report.py @@ -60,14 +60,16 @@ def watch_stalls(root: tk.Misc, reporter: Reporter) -> None: The operation is ``tk.mainloop``: a blocking call on the Tk thread. """ - last = [reporter.clock()] + # Lateness is monotonic: a wall-clock step (NTP at login) is not a freeze. + last = [reporter.monotonic()] def tick() -> None: - now = reporter.clock() + now = reporter.monotonic() late = round((now - last[0]) * 1000) - STALL_TICK_MS last[0] = now if late > reporter.threshold * 1000: - reporter.slow("tk.mainloop", late, wait_id=f"stall-{int(now * 1000):x}") + stamp = int(reporter.clock() * 1000) + reporter.slow("tk.mainloop", late, wait_id=f"stall-{stamp:x}") with suppress(tk.TclError): # the window is gone: the watch ends root.after(STALL_TICK_MS, tick) diff --git a/gatelock/gatelock/tests/test_error_report.py b/gatelock/gatelock/tests/test_error_report.py index 63e7f28..24f2901 100644 --- a/gatelock/gatelock/tests/test_error_report.py +++ b/gatelock/gatelock/tests/test_error_report.py @@ -34,6 +34,7 @@ def reporter(tmp_path: Path, clock: Clock) -> Reporter: build=5, version="0.3.0", clock=clock, + monotonic=clock, ) @@ -125,6 +126,25 @@ def test_stall_watch_reports_a_frozen_loop( assert entry["durationMs"] == 2500 - error_report.STALL_TICK_MS +def test_stall_watch_ignores_a_wall_clock_step(tmp_path: Path) -> None: + # chrony stepped the wall clock +1.33 s 3 s into a lock (2026-11-25): + # lateness is monotonic time, so the step is not a freeze. + wall, mono = Clock(), Clock() + rep = Reporter(app="tk-app", repo="r", spool=tmp_path, clock=wall, monotonic=mono) + root = MagicMock() + error_report.watch_stalls(root, rep) + tick = root.after.call_args.args[1] + mono.t += 0.1 + wall.t += 1.431 + tick() + assert spool_lines(tmp_path, "tk-app") == [] + mono.t += 2.5 # a real 2.5 s freeze is still reported + wall.t += 2.5 + tick() + (entry,) = spool_lines(tmp_path, "tk-app") + assert entry["durationMs"] == 2500 - error_report.STALL_TICK_MS + + def test_stall_watch_stops_with_the_window(reporter: Reporter, clock: Clock) -> None: root = MagicMock() error_report.watch_stalls(root, reporter) diff --git a/gatelock/gatelock/tests/test_error_spool.py b/gatelock/gatelock/tests/test_error_spool.py index 0809a9f..04f4ef4 100644 --- a/gatelock/gatelock/tests/test_error_spool.py +++ b/gatelock/gatelock/tests/test_error_spool.py @@ -29,6 +29,7 @@ def reporter(tmp_path: Path, clock: Clock) -> Reporter: build=5, version="0.3.0", clock=clock, + monotonic=clock, ) @@ -102,6 +103,20 @@ def test_slow_wait_over_threshold_is_written( assert entry["error"] == "coach.load waited 2000 ms" +def test_slow_wait_measures_monotonic_time(tmp_path: Path) -> None: + wall, mono = Clock(), Clock() + rep = Reporter(app="leetcode-guard", repo="r", spool=tmp_path, clock=wall, monotonic=mono) + with rep.wait("op"): + wall.t += 1.5 # a clock step, not a wait + mono.t += 0.2 + assert spool_lines(tmp_path) == [] + with rep.wait("op"): + mono.t += 1.2 + wall.t -= 3.0 # stepped back: the wait is still 1.2 s + (entry,) = spool_lines(tmp_path) + assert entry["durationMs"] == 1200 + + def test_fast_wait_writes_nothing( reporter: Reporter, tmp_path: Path, clock: Clock ) -> None: diff --git a/gatelock/gatelock/tests/test_outputs.py b/gatelock/gatelock/tests/test_outputs.py index ea7e20c..f5812c1 100644 --- a/gatelock/gatelock/tests/test_outputs.py +++ b/gatelock/gatelock/tests/test_outputs.py @@ -148,7 +148,13 @@ class TestScanXrandr: def test_success(self) -> None: """A clean run parses stdout.""" completed = MagicMock(returncode=0, stdout=XRANDR_REAL, stderr="") - assert self._run(return_value=completed) is not None + with ( + patch("gatelock._xrandr.shutil.which", return_value="/usr/bin/xrandr"), + patch("gatelock._xrandr.subprocess.run", return_value=completed) as run, + ): + assert real_scan_xrandr() is not None + # --current reads the server's state; --query re-probes every output. + assert run.call_args.args[0] == ["/usr/bin/xrandr", "--current"] def test_missing_binary(self) -> None: """xrandr not on PATH degrades rather than raising.""" diff --git a/gatelock/gatelock/tests/test_outputs_randr.py b/gatelock/gatelock/tests/test_outputs_randr.py index 9a40d13..df3b444 100644 --- a/gatelock/gatelock/tests/test_outputs_randr.py +++ b/gatelock/gatelock/tests/test_outputs_randr.py @@ -60,9 +60,11 @@ def _randr_display(*, outputs: dict[int, dict[str, object]]) -> MagicMock: """Build a fake Xlib display exposing ``outputs``.""" display = MagicMock() root = MagicMock() - root.xrandr_get_screen_resources.return_value = _reply( + root.xrandr_get_screen_resources_current.return_value = _reply( config_timestamp=1, outputs=list(outputs) ) + # The full probe re-polls every output (53 ms on NVIDIA, per tick): never. + root.xrandr_get_screen_resources.side_effect = AssertionError("full probe") root.xrandr_get_output_primary.return_value = _reply(output=1) display.screen.return_value.root = root diff --git a/gatelock/pyproject.toml b/gatelock/pyproject.toml index 92e40f0..2d286e6 100644 --- a/gatelock/pyproject.toml +++ b/gatelock/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "gatelock" -version = "0.16.1" +version = "0.16.2" 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 @@ -21,7 +21,7 @@ randr = ["python-xlib==0.33"] # must not refuse to start over a missing dependency, and only the chain's # own CLI imports these (lazily). Pins match book-guard / leetcode-guard. evening = [ - "earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.23.0#subdirectory=earned_time", + "earned-time @ git+https://github.com/kuhyx/utils@earned-time-v0.24.0#subdirectory=earned_time", "freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.4#subdirectory=freedays", "sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.9#subdirectory=sickdays", ]