#!/usr/bin/env python3 """The lucisv LSP performance phases — take 3's request table. python3 tools/perf/bench.py --server --label \ --opentitan DIR --storage DIR --out results.jsonl [--tries N] Every phase opens its own `lucisv-server` sessions, times requests on the wire with `time.perf_counter`, and appends one JSON object per row to `results.jsonl`. Nothing is ever written into the corpus: the index cache is directed at `--storage`, and every edit a request returns (`rename`, `codeAction/resolve`) is discarded. This file holds the phases that reproduce `docs/performance_take3.md`'s tables; `phases_new.py` holds the phases for what 0.44–0.49 added, and `harness.py` holds what both share. Run every invocation under `tools/guard.sh -m 8 -t 1800 --`; see `tools/perf/README.md`. """ import argparse import json import os import sys import time sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import harness # noqa: E402 import schema # noqa: E402 import sites # noqa: E402 from harness import ( # noqa: E402 ARGS, at, code_action_params, counts, doc, edit_of, fingerprint, phase, pos, record, samples, session, settled, ) import phases_new # noqa: E402,F401 — registers its own phases import phases_p0 # noqa: E402,F401 — registers take 5 §P0's phases import phases_p1 # noqa: E402,F401 — registers take 5 §P1's phases import phases_p2 # noqa: E402,F401 — registers take 5 §P2's phases # ========================================================================= # §0 — the transport baseline and the `--verbose` cross-check # ========================================================================= @phase("baseline") def phase_baseline(): with session("workspace") as s: init = s.initialize() record(phase="baseline", row="initialize", ms=[init], result_count=1, client=s.client_shape(), fresh_process=True) s.did_open(sites.path(sites.TB)) s.wait_quiet(1.5) s.take_notifications() got = samples(s, "$/lucisvNoSuchMethod", {}, 4) # The floor is an unknown method: the server rejects it without doing # any work, which is the whole point of the row. The rejection is # recorded honestly as an error *and* named in `expected_status`, so # the row stays quotable while a row that failed by accident does not. record(phase="baseline", row="transport baseline ($/lucisvNoSuchMethod)", client=s.client_shape(), expected_status="error", note="an unknown method, rejected without work — by design", **got.row()) @phase("verbose") def phase_verbose(): """The wire beside the server's own `timing:` line, three shapes (§0).""" shapes = [ ("prim_flop_2sync (128), eager", False, sites.AON_TIMER, "prim_flop_2sync #(", 2), ("prim_flop_2sync (128), lazy", True, sites.AON_TIMER, "prim_flop_2sync #(", 2), ("aes (6), eager", False, sites.TB, " aes #(", 2), ("comment line", True, sites.TB, "// ", 2), ] for label, lazy, relative, needle, offset in shapes: for verbose in (False, True): with session("workspace", resolve_support=lazy, verbose=verbose) as s: settled(s) s.did_open(sites.path(relative)) s.wait_quiet(0.6) s.take_notifications() s.take_timings() params = at(relative, needle, 1, offset) params["range"] = {"start": params.pop("position"), "end": None} params["range"]["end"] = params["range"]["start"] params["context"] = {"diagnostics": []} got = samples(s, "textDocument/codeAction", params, 4) server_ms = [t[1] for t in s.take_timings("textDocument/codeAction")] record(phase="verbose", row=label, note="verbose" if verbose else "quiet", server_ms=server_ms, client=s.client_shape(), **got.row()) # ========================================================================= # §4 — startup and scan, per scope config and cache state # ========================================================================= @phase("scan") def phase_scan(): """§4 — one cell per (scope, cache state), `--tries` runs each. "Cold" wipes the `storagePath` directory immediately before each run; "warm" leaves the previous run's store in place. The barrier is 1.5 s of silence after the `didOpen`, not the `$/progress` `end`, because the end report is followed by more indexing chatter. """ for scope in ("default", "empty-index", "depth0", "workspace"): for cache in ("cold", "warm"): runs, note = [], "" for _ in range(ARGS.tries): cold = cache == "cold" with session(scope, cold=cold, storage_name="scan-" + scope) as s: s.initialize() started = time.perf_counter() s.did_open(sites.path(sites.TB)) s.wait_quiet(1.5) runs.append((time.perf_counter() - started) * 1000.0 - 1500.0) ends = [ n["params"]["value"].get("message", "") for n in s.notifications if n["method"] == "$/progress" and n["params"]["value"].get("kind") == "end" ] note = " | ".join(ends[-2:]) record(phase="scan", row="%s, %s cache" % (scope, cache), ms=runs, settled_ms=runs, fresh_process=True, result_count=len(runs), note=note + " | nothing in flight during the scan") # The other half of §P0's split: when the *first useful answer* arrives, # measured in its own fresh sessions so the settled series above stays # comparable with take 4's. phases_p0.first_useful_rows() @phase("scopes") def phase_scopes(): """§4b — what each scope answers at the `aes` instantiation in `tb.sv`.""" asks = [ ("definition", "textDocument/definition", {}), ("typeDefinition", "textDocument/typeDefinition", {}), ("hover", "textDocument/hover", {}), ("references", "textDocument/references", {"context": {"includeDeclaration": True}}), ("documentHighlight", "textDocument/documentHighlight", {}), ("signatureHelp", "textDocument/signatureHelp", {}), ] for scope in ("default", "depth0", "workspace"): with session(scope, storage_name="scopes-" + scope) as s: settled(s) for name, method, extra in asks: params = dict(at(sites.TB, " aes #(", 1, 2)) params.update(extra) got = samples(s, method, params) record(phase="scopes", row="%s @ %s" % (name, scope), client=s.client_shape(), **got.row()) got = samples(s, "workspace/symbol", {"query": "aes"}) record(phase="scopes", row="workspace/symbol 'aes' @ %s" % scope, client=s.client_shape(), **got.row()) hint = {"textDocument": doc(sites.TB), "range": {"start": {"line": 0, "character": 0}, "end": {"line": 9999, "character": 0}}} got = samples(s, "textDocument/inlayHint", hint) record(phase="scopes", row="inlayHint @ %s" % scope, client=s.client_shape(), **got.row()) # ========================================================================= # §2 — the navigation table at workspace scope # ========================================================================= @phase("nav") def phase_nav(): rows = [ ("definition on aes", "textDocument/definition", at(sites.TB, " aes #(", 1, 2)), ("hover on aes", "textDocument/hover", at(sites.TB, " aes #(", 1, 2)), ("typeDefinition on aes", "textDocument/typeDefinition", at(sites.TB, " aes #(", 1, 2)), ("documentHighlight", "textDocument/documentHighlight", at(sites.TB, " aes #(", 1, 2)), ("references on aes", "textDocument/references", dict(at(sites.TB, " aes #(", 1, 2), context={"includeDeclaration": True})), ("references on .clk_i", "textDocument/references", dict(at(sites.TB, " .clk_i", 1, 5), context={"includeDeclaration": True})), ("signatureHelp in the port list", "textDocument/signatureHelp", at(sites.TB, " .clk_i", 1, 22)), ("documentSymbol", "textDocument/documentSymbol", {"textDocument": doc(sites.TB)}), ("foldingRange", "textDocument/foldingRange", {"textDocument": doc(sites.TB)}), ("codeLens", "textDocument/codeLens", {"textDocument": doc(sites.TB)}), ("documentLink", "textDocument/documentLink", {"textDocument": doc(sites.TB)}), ("selectionRange", "textDocument/selectionRange", {"textDocument": doc(sites.TB), "positions": [pos(sites.TB, " aes #(", 1, 2)]}), ("semanticTokens/full", "textDocument/semanticTokens/full", {"textDocument": doc(sites.TB)}), ("inlayHint (whole file)", "textDocument/inlayHint", {"textDocument": doc(sites.TB), "range": {"start": {"line": 0, "character": 0}, "end": {"line": 9999, "character": 0}}}), ("diagnostic (pull)", "textDocument/diagnostic", {"textDocument": doc(sites.TB)}), ("workspace/symbol 'aes'", "workspace/symbol", {"query": "aes"}), ] for row, method, params in rows: with session("workspace") as s: settled(s) got = samples(s, method, params, ARGS.tries + 1) record(phase="nav", row=row, method=method, client=s.client_shape(), **got.row()) @phase("flush") def phase_flush(): """The `didChange` flush, measured with a `foldingRange` barrier.""" with session("workspace") as s: settled(s) text = open(sites.path(sites.TB), encoding="utf-8", errors="replace").read() runs, statuses, last = [], [], {} for version in range(2, 2 + ARGS.tries + 1): s.did_change(sites.path(sites.TB), text + "\n// take4 %d\n" % version, version) got = samples(s, "textDocument/foldingRange", {"textDocument": doc(sites.TB)}, 1) runs.append(got.ms[0]) statuses.append(got.status) last = got.last status = schema.worst(statuses) record(phase="flush", row="didChange flush (foldingRange barrier)", ms=runs, status=status, message=None if status == "ok" else "a barrier failed", result_count=schema.result_count(last), client=s.client_shape()) # ========================================================================= # §6 — codeAction, offer and resolve # ========================================================================= @phase("codeaction") def phase_codeaction(): for lazy in (True, False): for label, relative, needle, occurrence, fanout, offset in sites.FANOUT_CURSORS: with session("workspace", resolve_support=lazy) as s: settled(s) if relative != sites.TB: s.did_open(sites.path(relative)) s.wait_quiet(0.6) s.take_notifications() params = code_action_params(relative, needle, occurrence, offset) got = samples(s, "textDocument/codeAction", params, ARGS.tries + 1) offered = got.last.get("result") or [] record(phase="codeaction", row="%s (fan-out %d), %s" % (label, fanout, "lazy" if lazy else "eager"), titles=[a.get("title") for a in offered], shapes=[phases_p0.shape_of(a) for a in offered], client=s.client_shape(), file=relative, position=params["range"]["start"], **got.row()) with session("workspace", resolve_support=lazy) as s: settled(s) params = code_action_params(sites.TB, " // ", 1, 2) got = samples(s, "textDocument/codeAction", params, ARGS.tries + 1) record(phase="codeaction", row="comment line, %s" % ("lazy" if lazy else "eager"), client=s.client_shape(), file=sites.TB, position=params["range"]["start"], **got.row()) @phase("portaction") def phase_portaction(): """The one opentitan cursor that offers a port refactoring: offer + resolve.""" for lazy in (True, False): with session("workspace", resolve_support=lazy) as s: settled(s) s.did_open(sites.path(sites.AES_WRAP)) s.wait_quiet(0.6) s.take_notifications() params = code_action_params(sites.AES_WRAP, " aes #(", 1, 2) got = samples(s, "textDocument/codeAction", params, ARGS.tries + 1) offered = got.last.get("result") or [] record(phase="portaction", row="aes_wrap.sv offer, %s" % ("lazy" if lazy else "eager"), titles=[a.get("title") for a in offered], shapes=[phases_p0.shape_of(a) for a in offered], client=s.client_shape(), **got.row()) if lazy and offered: phases_new.resolve_rows(s, "portaction", "aes_wrap.sv", offered[:1]) # ========================================================================= # §6c / §49 — rename, and the hierarchical tail # ========================================================================= @phase("rename") def phase_rename(): with session("workspace") as s: settled(s) where = at(sites.TB, " aes #(", 1, 2) got = samples(s, "textDocument/prepareRename", where, ARGS.tries + 1) record(phase="rename", row="prepareRename on aes", client=s.client_shape(), note=json.dumps(got.last.get("result")), **got.row()) params = dict(where, newName="aes_renamed") got = samples(s, "textDocument/rename", params, ARGS.tries + 1) edit = edit_of(got.last) record(phase="rename", row="rename aes -> aes_renamed", client=s.client_shape(), fingerprint=fingerprint(edit), titles=sorted(os.path.basename(u) for u in phases_new.edited_uris(got.last)), **dict(got.row(), **counts(edit))) @phase("blockers") def phase_blockers(): leaders = [ ("codeAction on the aes token", "textDocument/codeAction", lambda: code_action_params(sites.TB, " aes #(", 1, 2)), ("prepareRename on aes", "textDocument/prepareRename", lambda: at(sites.TB, " aes #(", 1, 2)), ("rename on aes", "textDocument/rename", lambda: dict(at(sites.TB, " aes #(", 1, 2), newName="aes_renamed")), ("workspace/symbol 'aes'", "workspace/symbol", lambda: {"query": "aes"}), ] followers = [ ("definition", "textDocument/definition", lambda: at(sites.TB, " aes #(", 1, 2)), ("hover", "textDocument/hover", lambda: at(sites.TB, " aes #(", 1, 2)), ("documentSymbol", "textDocument/documentSymbol", lambda: {"textDocument": doc(sites.TB)}), ] for row, method, make in leaders: own, behind, statuses = [], [], [] follower_ms = {name: [] for name, _, _ in followers} for _ in range(ARGS.tries): with session("workspace") as s: settled(s) lead = s.send(method, make()) ids = [(name, s.send(m, mk())) for name, m, mk in followers] leader_ms, leader_message = s.await_id(lead) own.append(leader_ms) statuses.append(schema.status_of(leader_message)[0]) one = [] for name, rid in ids: elapsed, message = s.await_id(rid) one.append((name, elapsed)) follower_ms[name].append(elapsed) statuses.append(schema.status_of(message)[0]) behind.append(one) shape = s.client_shape() status = schema.worst(statuses) record(phase="blockers", row=row, ms=own, leader_ms=own, follower_ms=follower_ms, fresh_process=True, status=status, message=None if status == "ok" else "a pipelined request failed", result_count=len(own), client=shape, note="ms is the leader; each follower has its own field. " + " | ".join("; ".join("%s %.2f" % (n, v) for n, v in one) for one in behind)) # ========================================================================= # §5 / §46 — the didOpen widen, and the didOpen delay # ========================================================================= @phase("widen") def phase_widen(): """§5 — a `didOpen` that may widen the scope, then the request behind it. One session per (scope, cache, try): the widen is a once-per-session event, so a second try inside the same session would measure nothing. """ for scope in ("depth0", "default"): for cache in ("cold", "warm"): runs = {relative: [] for relative in sites.WIDEN_FILES} seconds = {relative: [] for relative in sites.WIDEN_FILES} statuses = {relative: [] for relative in sites.WIDEN_FILES} for _ in range(ARGS.tries): with session(scope, cold=(cache == "cold"), storage_name="widen-" + scope) as s: settled(s) for relative in sites.WIDEN_FILES: started = time.perf_counter() s.did_open(sites.path(relative)) first = samples(s, "textDocument/definition", at(relative, "module ", 1, 0), 1) runs[relative].append((time.perf_counter() - started) * 1000.0) second = samples(s, "textDocument/definition", at(relative, "module ", 1, 0), 1) seconds[relative].append(second.ms[0]) statuses[relative].extend([first.status, second.status]) s.wait_quiet(0.5) s.take_notifications() shape = s.client_shape() for relative in sites.WIDEN_FILES: status = schema.worst(statuses[relative]) record(phase="widen", row="%s @ %s, %s" % (os.path.basename(relative), scope, cache), ms=runs[relative], fresh_process=True, status=status, message=None if status == "ok" else "a definition failed", result_count=len(runs[relative]), client=shape, second_definition_ms=seconds[relative], note="second definition " + " / ".join( "%.2f" % v for v in seconds[relative])) # ========================================================================= # diagnostics, completion, hierarchy, RSS # ========================================================================= @phase("diagnostics") def phase_diagnostics(): with session("workspace") as s: settled(s) text = open(sites.path(sites.TB), encoding="utf-8", errors="replace").read() runs = [] for version in range(2, 2 + ARGS.tries + 1): s.take_notifications() started = time.perf_counter() s.did_change(sites.path(sites.TB), text + "\n// take4 %d\n" % version, version) while True: s.drain() if any(n["method"] == "textDocument/publishDiagnostics" for n in s.notifications): break if time.perf_counter() - started > 30: raise TimeoutError("no diagnostics published") time.sleep(0.001) runs.append((time.perf_counter() - started) * 1000.0) record(phase="diagnostics", row="publish after didChange (incl. ~150 ms debounce)", ms=runs, result_count=len(runs), client=s.client_shape(), note="a notification barrier, not a request round trip") @phase("completion") def phase_completion(): with session("workspace") as s: settled(s) text = open(sites.path(sites.TB), encoding="utf-8", errors="replace").read() base = text.rstrip("\n") for version, prefix in enumerate(sites.COMPLETION_PREFIXES, start=2): body = base + "\n" + prefix + "\n" s.did_change(sites.path(sites.TB), body, version) where = {"textDocument": doc(sites.TB), "position": {"line": body.count("\n") - 1, "character": len(prefix)}} got = samples(s, "textDocument/completion", where, ARGS.tries + 1) record(phase="completion", row="completion after %r" % prefix, client=s.client_shape(), **got.row()) @phase("probe") def phase_probe(): """Ad-hoc: what does a cursor offer? `--probe FILE:LINE:CHAR` (0-based).""" relative, line, character = ARGS.probe.rsplit(":", 2) where = {"line": int(line), "character": int(character)} with session("workspace", resolve_support=True) as s: settled(s) s.did_open(sites.path(relative)) s.wait_quiet(0.8) s.take_notifications() params = {"textDocument": doc(relative), "range": {"start": where, "end": where}, "context": {"diagnostics": []}} got = samples(s, "textDocument/codeAction", params, 2) offered = got.last.get("result") or [] record(phase="probe", row="%s %s:%s" % (relative, line, character), titles=[a.get("title") for a in offered], shapes=[phases_p0.shape_of(a) for a in offered], client=s.client_shape(), **got.row()) def main(): parser = argparse.ArgumentParser() parser.add_argument("phase", choices=sorted(harness.PHASES)) parser.add_argument("--server", required=True) parser.add_argument("--label", required=True) parser.add_argument("--opentitan", default=sites.ROOT) parser.add_argument("--storage", required=True) parser.add_argument("--out", required=True) parser.add_argument("--tries", type=int, default=3) parser.add_argument("--probe", default="", help="for the `probe` phase: FILE:LINE:CHAR, 0-based") harness.configure(parser.parse_args()) harness.PHASES[ARGS.phase]() if __name__ == "__main__": main()