mirror of
https://github.com/kuhyx/utils.git
synced 2026-11-27 10:49:18 +01:00
gatelock 0.16.2: time stalls on the monotonic clock
Some checks are pending
file length / file-length (push) Waiting to run
gatelock pre-commit / pre-commit (push) Waiting to run
gatelock tests / test (push) Waiting to run
kuhy_credit drift / drift (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
palette drift / palette (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
shared gate tests / gate unit tests (push) Waiting to run
Some checks are pending
file length / file-length (push) Waiting to run
gatelock pre-commit / pre-commit (push) Waiting to run
gatelock tests / test (push) Waiting to run
kuhy_credit drift / drift (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
palette drift / palette (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
shared gate tests / gate unit tests (push) Waiting to run
watch_stalls and SlowWait measured elapsed time with time.time. On 2026-11-25 chrony stepped the wall clock 1.33 s three seconds into a lock, and that read as a 1556 ms tk.mainloop freeze (screen-locker:c890f31a21). Reporter gains a monotonic clock for durations; the wall clock stays for timestamps and ids. The RandR scan on the Tk thread (recovery tick, every event drain) used RRGetScreenResources, a full output re-probe: 57 ms per call on the NVIDIA box. RRGetScreenResourcesCurrent reads the server's state in 0.56 ms; hotplug still updates that state and sends the event. The xrandr fallback uses --current for the same reason. earned-time pin to 0.24.0 (freshness gate). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
e1b15a9449
commit
58b0bbeaf9
@ -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:
|
||||
|
||||
@ -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)
|
||||
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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)
|
||||
|
||||
|
||||
@ -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)
|
||||
|
||||
@ -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:
|
||||
|
||||
@ -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."""
|
||||
|
||||
@ -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
|
||||
|
||||
|
||||
@ -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",
|
||||
]
|
||||
|
||||
Loading…
Reference in New Issue
Block a user