Debian Codegraph @

scripts/cold_start.py

raw
1 """Measure what an import costs before anyone has done any work.
2
3 Cold start is the budget the headless CLI has to live inside, and it is spent
4 almost entirely on imports: the modules a front end touches on its way to a
5 connection, not the query. This reports the wall time and the module count for
6 each step, so a regression points at the import that caused it.
7
8 Usage:
9 uv run python scripts/cold_start.py
10 uv run python scripts/cold_start.py --runs 10
11 uv run python scripts/cold_start.py --json # for CI job summaries
12
13 The numbers are informational. The blocking guards are the import-linter
14 contracts in pyproject.toml and tests/unit_tests/test_import_hygiene.py, which
15 fail identically on every machine; a wall clock on a shared CI runner does not.
16 """
17
18 from __future__ import annotations
19
20 import argparse
21 import json
22 import subprocess
23 import sys
24 import time
25
26 # (label, statement). Ordered cheapest to dearest, which is also roughly the
27 # order a headless invocation touches them.
28 #
29 # The first three are the warm-session client's whole graph, and the budget
30 # they live inside is the tightest here: a round trip to a session is about a
31 # millisecond, so what a caller waits for is these. Everything below `click` is
32 # already more than the feature costs.
33 STEPS: list[tuple[str, str]] = [
34 ("interpreter only", "pass"),
35 ("harlequin", "import harlequin"),
36 ("hsql session", "import harlequin.hsql.session"),
37 ("hsql client", "import harlequin.hsql.client"),
38 ("click", "import click"),
39 ("harlequin.statements", "import harlequin.statements"),
40 ("harlequin.catalog", "import harlequin.catalog"),
41 ("harlequin.options", "import harlequin.options"),
42 ("harlequin.config", "import harlequin.config"),
43 ("harlequin.plugins", "import harlequin.plugins"),
44 (
45 "fastdatatable backend",
46 "from textual_fastdatatable.backend import create_backend",
47 ),
48 ("harlequin.query", "import harlequin.query"),
49 ("harlequin.layout", "import harlequin.layout"),
50 ("harlequin.export", "import harlequin.export"),
51 ("harlequin.hsql.cli", "import harlequin.hsql.cli"),
52 ("harlequin_sqlite", "import harlequin_sqlite"),
53 ("harlequin_duckdb", "import harlequin_duckdb"),
54 ("harlequin.cli", "import harlequin.cli"),
55 ("the TUI", "from harlequin import Harlequin"),
56 ]
57
58 PROBE = """
59 {statement}
60 import sys
61 print(len(sys.modules), "textual" in sys.modules, sep=",")
62 """
63
64
65 def measure(statement: str, runs: int) -> tuple[float, int, bool]:
66 """Returns (best milliseconds, module count, whether Textual was imported).
67
68 The best of N, not the mean: we want the floor the import costs, and a
69 shared runner only ever adds noise on top of it.
70 """
71 best = float("inf")
72 modules = 0
73 imported_textual = False
74 for _ in range(runs):
75 start = time.perf_counter()
76 proc = subprocess.run(
77 [sys.executable, "-c", PROBE.format(statement=statement)],
78 capture_output=True,
79 text=True,
80 check=True,
81 )
82 best = min(best, (time.perf_counter() - start) * 1000)
83 count, textual = proc.stdout.strip().split(",")
84 modules = int(count)
85 imported_textual = textual == "True"
86 return best, modules, imported_textual
87
88
89 def main() -> int:
90 parser = argparse.ArgumentParser(description=__doc__)
91 parser.add_argument(
92 "--runs", type=int, default=5, help="iterations per step (best wins)"
93 )
94 parser.add_argument(
95 "--json", action="store_true", help="emit JSON instead of a table"
96 )
97 args = parser.parse_args()
98
99 results = []
100 for label, statement in STEPS:
101 elapsed, modules, textual = measure(statement, args.runs)
102 results.append(
103 {
104 "step": label,
105 "statement": statement,
106 "ms": round(elapsed, 1),
107 "modules": modules,
108 "textual": textual,
109 }
110 )
111
112 if args.json:
113 print(json.dumps(results, indent=2))
114 return 0
115
116 print(f"{'step':<24}{'ms':>8}{'modules':>10} textual")
117 print("-" * 52)
118 for row in results:
119 flag = "yes" if row["textual"] else "no"
120 print(f"{row['step']:<24}{row['ms']:>8}{row['modules']:>10} {flag}")
121 return 0
122
123
124 if __name__ == "__main__":
125 raise SystemExit(main())