Debian Codegraph @

scripts/catalog_lag.py

raw
1 """Run Harlequin against a real database and report event-loop lag on exit.
2
3 Event-loop lag is what "the catalog is hanging" actually means: every millisecond
4 the loop is blocked is a millisecond of unrendered keystrokes and scrolling.
5
6 Usage:
7 uv run python scripts/catalog_lag.py --adapter postgres "postgresql://..."
8 uv run python scripts/catalog_lag.py --profile my-big-mysql
9
10 Browse the catalog as you normally would -- expand big schemas, scroll fast --
11 then quit with ctrl+q. Anything over ~100ms at p95 is visible jank.
12 """
13
14 from __future__ import annotations
15
16 import asyncio
17 import sys
18 import time
19
20 from harlequin.app import Harlequin
21
22 SAMPLE_INTERVAL = 0.05
23
24
25 class Heartbeat:
26 """Sample how late a fixed-interval timer actually fires."""
27
28 def __init__(self) -> None:
29 self.lags: list[float] = []
30
31 async def run(self) -> None:
32 while True:
33 start = time.monotonic()
34 await asyncio.sleep(SAMPLE_INTERVAL)
35 self.lags.append(time.monotonic() - start - SAMPLE_INTERVAL)
36
37 def report(self) -> str:
38 if not self.lags:
39 return "no samples collected"
40 lags = sorted(self.lags)
41
42 def pct(p: float) -> float:
43 return lags[min(int(len(lags) * p), len(lags) - 1)] * 1000
44
45 over_100ms = sum(1 for lag in lags if lag > 0.1)
46 return (
47 f"\nevent-loop lag over {len(lags)} samples "
48 f"({len(lags) * SAMPLE_INTERVAL:.0f}s of use):\n"
49 f" p50 {pct(0.50):6.1f} ms\n"
50 f" p95 {pct(0.95):6.1f} ms\n"
51 f" p99 {pct(0.99):6.1f} ms\n"
52 f" max {lags[-1] * 1000:6.1f} ms\n"
53 f" {over_100ms} samples ({over_100ms / len(lags):.1%}) over 100ms\n"
54 )
55
56
57 def main() -> None:
58 heartbeat = Heartbeat()
59 original_on_mount = Harlequin.on_mount
60
61 async def on_mount(self: Harlequin) -> None:
62 asyncio.create_task(heartbeat.run())
63 await original_on_mount(self)
64
65 Harlequin.on_mount = on_mount # type: ignore[method-assign]
66
67 from harlequin.cli import harlequin
68
69 try:
70 # `harlequin` is a click command; the decorator hides `.main` from mypy
71 harlequin.main(sys.argv[1:], standalone_mode=False) # type: ignore[attr-defined]
72 finally:
73 print(heartbeat.report(), file=sys.stderr)
74
75
76 if __name__ == "__main__":
77 main()