Files
lucisv/tools/perf/bench.py
T

437 lines
20 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""The lucisv LSP performance phases — take 3's request table.
python3 tools/perf/bench.py <phase> --server <path> --label <name> \
--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 sites # noqa: E402
from harness import ( # noqa: E402
ARGS, at, code_action_params, doc, phase, pos, record, result_count,
session, settled, tries,
)
import phases_new # noqa: E402,F401 — registers its own 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])
s.did_open(sites.path(sites.TB))
s.wait_quiet(1.5)
s.take_notifications()
ms = tries(s, "$/lucisvNoSuchMethod", {}, 4)
record(phase="baseline", row="transport baseline ($/lucisvNoSuchMethod)", ms=ms)
@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": []}
ms = tries(s, "textDocument/codeAction", params, 4)
server_ms = [t[1] for t in s.take_timings("textDocument/codeAction")]
record(phase="verbose", row=label, ms=ms,
note="verbose" if verbose else "quiet",
server_ms=server_ms)
# =========================================================================
# §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, note=note)
@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)
ms = tries(s, method, params)
_, message = s.request(method, params)
record(phase="scopes", row="%s @ %s" % (name, scope), ms=ms,
n=result_count(message))
ms = tries(s, "workspace/symbol", {"query": "aes"})
_, message = s.request("workspace/symbol", {"query": "aes"})
record(phase="scopes", row="workspace/symbol 'aes' @ %s" % scope, ms=ms,
n=result_count(message))
hint = {"textDocument": doc(sites.TB),
"range": {"start": {"line": 0, "character": 0},
"end": {"line": 9999, "character": 0}}}
ms = tries(s, "textDocument/inlayHint", hint)
_, message = s.request("textDocument/inlayHint", hint)
record(phase="scopes", row="inlayHint @ %s" % scope, ms=ms,
n=result_count(message))
# =========================================================================
# §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)
ms = tries(s, method, params, ARGS.tries + 1)
_, message = s.request(method, params)
record(phase="nav", row=row, ms=ms, n=result_count(message), method=method)
@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 = []
for version in range(2, 2 + ARGS.tries + 1):
s.did_change(sites.path(sites.TB), text + "\n// take4 %d\n" % version, version)
runs.append(s.ms("textDocument/foldingRange", {"textDocument": doc(sites.TB)}))
record(phase="flush", row="didChange flush (foldingRange barrier)", ms=runs)
# =========================================================================
# §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)
ms = tries(s, "textDocument/codeAction", params, ARGS.tries + 1)
_, message = s.request("textDocument/codeAction", params)
record(phase="codeaction",
row="%s (fan-out %d), %s" % (label, fanout, "lazy" if lazy else "eager"),
ms=ms, n=result_count(message),
titles=[a.get("title") for a in (message.get("result") or [])])
with session("workspace", resolve_support=lazy) as s:
settled(s)
params = code_action_params(sites.TB, " // ", 1, 2)
ms = tries(s, "textDocument/codeAction", params, ARGS.tries + 1)
_, message = s.request("textDocument/codeAction", params)
record(phase="codeaction", row="comment line, %s" % ("lazy" if lazy else "eager"),
ms=ms, n=result_count(message))
@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)
ms = tries(s, "textDocument/codeAction", params, ARGS.tries + 1)
_, message = s.request("textDocument/codeAction", params)
offered = message.get("result") or []
record(phase="portaction",
row="aes_wrap.sv offer, %s" % ("lazy" if lazy else "eager"),
ms=ms, n=len(offered),
titles=[a.get("title") for a in offered],
has_edit=[("edit" in a) for a in offered])
if lazy and offered:
resolves = [s.ms("codeAction/resolve", offered[0])
for _ in range(ARGS.tries + 1)]
_, resolved = s.request("codeAction/resolve", offered[0])
edit = (resolved.get("result") or {}).get("edit") or {}
files = edit.get("changes") or {u: 1 for u in
(c.get("textDocument", {}).get("uri")
for c in edit.get("documentChanges") or [])}
record(phase="portaction", row="aes_wrap.sv codeAction/resolve", ms=resolves,
n=len(files), titles=[(resolved.get("result") or {}).get("title")])
# =========================================================================
# §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)
ms = tries(s, "textDocument/prepareRename", where, ARGS.tries + 1)
_, message = s.request("textDocument/prepareRename", where)
record(phase="rename", row="prepareRename on aes", ms=ms,
note=json.dumps(message.get("result")))
params = dict(where, newName="aes_renamed")
ms = tries(s, "textDocument/rename", params, ARGS.tries + 1)
_, message = s.request("textDocument/rename", params)
record(phase="rename", row="rename aes -> aes_renamed", ms=ms,
n=len(phases_new.edited_uris(message)))
@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 = [], []
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]
own.append(s.await_id(lead)[0])
behind.append([(name, s.await_id(rid)[0]) for name, rid in ids])
record(phase="blockers", row=row, ms=own,
note=" | ".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}
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))
s.ms("textDocument/definition", at(relative, "module ", 1, 0))
runs[relative].append((time.perf_counter() - started) * 1000.0)
seconds[relative].append(
s.ms("textDocument/definition", at(relative, "module ", 1, 0)))
s.wait_quiet(0.5)
s.take_notifications()
for relative in sites.WIDEN_FILES:
record(phase="widen",
row="%s @ %s, %s" % (os.path.basename(relative), scope, cache),
ms=runs[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)
@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)}}
ms = tries(s, "textDocument/completion", where, ARGS.tries + 1)
_, message = s.request("textDocument/completion", where)
record(phase="completion", row="completion after %r" % prefix, ms=ms,
n=result_count(message))
@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": []}}
ms = tries(s, "textDocument/codeAction", params, 2)
_, message = s.request("textDocument/codeAction", params)
offered = message.get("result") or []
record(phase="probe", row="%s %s:%s" % (relative, line, character), ms=ms,
n=len(offered), titles=[a.get("title") for a in offered])
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()