#!/usr/bin/env python3 # Author: Guoliang Chen, a Senior Digital Design Engineer """The take-5 **review** round's phases for R1a/R1b: `actionprofile`, `ruleablation`. `offerkinds` and `offeredit` say what a code-action menu *costs*; neither says where the milliseconds went. The review's §1 item 1 asks for exactly that split — "trace configuration/waiver loading, dirty-buffer flush, lint execution, fence filtering and action serialization separately on the pinmux case, [for the] first request, unchanged repeat, first request after one-character edit, and navigation queued behind each" — and `--verbose` now logs one `timing: codeaction …` line per request carrying it (`crates/lucisv_server/src/lint_trace.rs`). `actionprofile` issues those four shapes at three cursors and writes every field of that line as a `trace_*` row field, so the tracker quotes numbers and not prose. `ms` remains the wire latency and nothing else (schema 2). `ruleablation` answers the other half of the same question — *which* rules the lint pass spends its milliseconds in on a 42 192-line generated buffer. One `workspace/didChangeConfiguration` per row sets `lucisv.lint.select` to a single rule and the same quickfix-only menu is timed under it. A selection change rescans nothing (`notification.rs::apply_settings`), so the rows are comparable within one warm session. The corpus is not written: a `didChange` is a notification about an in-memory buffer and never reaches disk. """ import os import re import subprocess import time import phases_new import phases_p2 import phases_p4 import schema import sites from harness import ( ARGS, at, code_action_params, phase, record, samples, session, settled, uri as lspclient_uri, ) #: `timing: codeaction ` — the whole line the server logs per request #: that linted anything. TRACE_LINE = re.compile(r"timing: codeaction (.*)$") #: The cursors R1b is profiled at. The first is the review's own headline (a #: no-offer comment in a 42 192-line generated file); the second is the small #: no-offer control; the third the one small-file offer site. Same three #: `phases_p1.EDIT_CURSORS` measures, so the profile rows sit beside the #: latency rows they explain. PROFILE_CURSORS = [ ("pinmux-comment", sites.PINMUX_REG_TOP, "// ", 2), ("tb-comment", sites.TB, "// ", 2), ("aes-reg-instance", sites.AES, "aes_reg_top u_reg (", 0), ] #: The request queued behind each menu — `phases_p0.phase_offerqueue`'s own #: follower, so the queued-definition rows are directly comparable. FOLLOWER = (sites.TB, " aes #(", 1, 2) def traces(s): """Every `codeaction` trace line since the last drain, flattened. `phases_p2.parse_trace` is the parser: `key=value` pairs with `group{…}` flattened under the group's name, which is the shape `lint_trace::Trace` prints. A row whose trace is empty is a row whose server was not `--verbose` or which never linted — the phase says so rather than inventing fields. """ s.drain() found = [m for text in s.log_messages for m in TRACE_LINE.findall(text)] s.log_messages = [] return [phases_p2.parse_trace(one) for one in found] def last_trace(s): """The last traced request of this session, or `{}`.""" found = traces(s) return found[-1] if found else {} def open_verbose(s, relative, quiet=0.8): """Settle the scan, open the file, and start with an empty log.""" settled(s) s.did_open(sites.path(relative)) s.wait_quiet(quiet) s.take_notifications() s.log_messages = [] def profile_row(s, row, relative, params, got, trace, note): """One schema-2 row carrying a request's wire time and its stage split.""" record(phase="actionprofile", row=row, client=s.client_shape(), file=relative, position=params["range"]["start"], load=os.getloadavg(), note=note, **dict(got.row(), **phases_p2.prefixed(trace))) @phase("actionprofile") def phase_actionprofile(): """§R1b — the code-action stage trace, four request shapes per cursor.""" for label, relative, needle, offset in PROFILE_CURSORS: with session("workspace", resolve_support=True, verbose=True, storage_name="actionprofile") as s: open_verbose(s, relative) params = code_action_params(relative, needle, offset=offset) settled_rows(s, label, relative, params) edited_rows(s, label, relative, params) def settled_rows(s, label, relative, params): """The two rows a settled buffer answers: the first menu, then repeats.""" got = samples(s, "textDocument/codeAction", params, 1) profile_row(s, "%s, first codeAction on the settled buffer" % label, relative, params, got, last_trace(s), "the first request of the session at this cursor") got = samples(s, "textDocument/codeAction", params, ARGS.tries) profile_row(s, "%s, repeated codeAction on the unchanged buffer" % label, relative, params, got, last_trace(s), "no didChange between the tries; the trace is the last one") queued_row(s, "%s, definition queued behind the unchanged menu" % label, relative, params) def edited_rows(s, label, relative, params): """The first menu after each `didChange`, and one queued behind it.""" with open(sites.path(relative), encoding="utf-8", errors="replace") as handle: text = handle.read() ms, statuses, counts, trace = [], [], [], {} for version in range(2, 2 + ARGS.tries): s.did_change(sites.path(relative), text + "\n// take5r r1 %d\n" % version, version) got = samples(s, "textDocument/codeAction", params, 1) ms.append(got.ms[0]) statuses.append((got.status, got.message)) counts.append(got.result_count) trace = last_trace(s) or trace status = schema.worst([one for one, _ in statuses]) record(phase="actionprofile", row="%s, first codeAction after a didChange" % label, ms=ms, status=status, message=next((m for one, m in statuses if one != "ok"), None), result_count=counts[-1], result_counts=counts, client=s.client_shape(), file=relative, position=params["range"]["start"], load=os.getloadavg(), note="each try is the first codeAction after its own didChange, so " "the flush group of the trace is that request's Document " "rebuild; the same edit shape phases_p1.offeredit uses", **phases_p2.prefixed(trace)) # The queued case on a buffer that has just changed: the review asks for # navigation queued behind *each* menu, and only this one pays the flush. def edit(pipeline): s.did_change(sites.path(relative), text + "\n// take5r r1 queued %d\n" % pipeline, 10 + pipeline) queued_row(s, "%s, definition queued behind the menu after a didChange" % label, relative, params, change=edit) def queued_row(s, row, relative, params, change=None): """A `codeAction` and a `definition` sent back to back, both traced. `change` is called before every pipeline when the row is about a buffer that has *just* changed: only the first request after an edit pays the flush, so a repeat inside the row would measure the other case. """ follower = at(*FOLLOWER) s.log_messages = [] leaders, followers = [], [] lead_status, follow_status = ("ok", None), ("ok", None) for pipeline in range(ARGS.tries): if change: change(pipeline) s.log_messages = [] lead = s.send("textDocument/codeAction", params) follow = s.send("textDocument/definition", follower) leader_ms, leader_message = s.await_id(lead) follower_ms, follower_message = s.await_id(follow) leaders.append(leader_ms) followers.append(follower_ms) lead_status = schema.status_of(leader_message) follow_status = schema.status_of(follower_message) # Attributed by the line's own `method` field, not by position: a request # that lints nothing logs no line at all, so a definition behind an # already-flushed menu contributes none and the last line in the log is # another `codeAction`. Counting by position made two leaders look like a # leader and a follower. found = traces(s) lead = [one for one in found if one.get("method", "").endswith("codeAction")] follow = [one for one in found if one.get("method", "").endswith("definition")] record(phase="actionprofile", row=row, ms=[leaders[-1], followers[-1]], leader_ms=leaders, follower_ms=followers, status=schema.worst([lead_status[0], follow_status[0]]), message=lead_status[1] or follow_status[1], result_count=len(follow), client=s.client_shape(), file=relative, position=params["range"]["start"], load=os.getloadavg(), note="ms is [leader, follower], not repeats; trace_* is the " "leader's own stage split and follower_trace_* the " "definition's — a definition that linted nothing logs no " "line, and result_count says how many it logged", **dict(phases_p2.prefixed(lead[-1] if lead else {}), **{"follower_%s" % key: value for key, value in phases_p2.prefixed(follow[-1] if follow else {}).items()})) def enabled_rules(): """Every rule the server runs by default over a project, by name. Read from `lucisv check --rules-doc` beside the server under test rather than hard-coded, so the list cannot drift from the registry. `**on**` is a rule a plain check runs; `**on (project)**` is one that also needs a workspace, which the server has. """ binary = os.path.join(os.path.dirname(os.path.abspath(ARGS.server)), "lucisv") out = subprocess.run([binary, "check", "--rules-doc"], check=True, capture_output=True, text=True).stdout rows = re.findall(r"^\| \[`([a-z0-9-]+)`\]\S* \| \w+ \| (\*\*on[^|]*|off) \|", out, re.M) return [name for name, default in rows if default.startswith("**on")] @phase("ruleablation") def phase_ruleablation(): """§R1b — which rules the pinmux quickfix menu's milliseconds are in. One row per default-on rule: `lucisv.lint.select` is set to that rule alone and the same quickfix-only menu is timed. The control row is the unrestricted selection, taken first and last so a drift in the session is visible rather than attributed to a rule. """ rules = enabled_rules() with session("workspace", resolve_support=True, verbose=True, storage_name="ruleablation") as s: open_verbose(s, sites.PINMUX_REG_TOP) params = code_action_params(sites.PINMUX_REG_TOP, "// ", offset=2) params["context"]["only"] = ["quickfix"] ablation_row(s, "control: every default rule (before)", None, params) for name in rules: ablation_row(s, "select %s" % name, [name], params) ablation_row(s, "control: every default rule (after)", None, params) def ablation_row(s, row, select, params): """Push one `lucisv.lint.select`, then time the menu under it.""" lint = {"select": select} if select else {"select": []} s.notify("workspace/didChangeConfiguration", {"settings": {"lucisv": {"lint": lint}}}) s.wait_quiet(0.4) s.take_notifications() s.log_messages = [] got = samples(s, "textDocument/codeAction", params, ARGS.tries) record(phase="ruleablation", row=row, client=s.client_shape(), file=sites.PINMUX_REG_TOP, position=params["range"]["start"], only=params["context"]["only"], load=os.getloadavg(), note="quickfix only, one warm session, selection pushed by " "didChangeConfiguration; a selection change rescans nothing", **dict(got.row(), **phases_p2.prefixed(last_trace(s)))) @phase("snapshotrss") def phase_snapshotrss(): """§R1a — what the lint snapshots cost in memory, at 1, 10 and 100 buffers. The snapshot is one field per open `Document`, holding that document's own violations, so the memory question is "how much does a session with many buffers grow when every one of them has been asked for a quick fix?". Each cell opens `n` RTL files, sends one quickfix-only `codeAction` into every one of them — which is what fills the slot on the reference binary too, minus the keeping — and reads idle RSS a second later. `phases_p4.rtl_files` is the same buffer list the P4 startup cells use, so the 100-buffer row is comparable with the startup memory cell beside it. """ for buffers in (1, 10, 100): idle, peaks, asked = [], [], 0 for _ in range(ARGS.tries): with session("workspace", resolve_support=True, storage_name="snapshotrss") as s: sampler = phases_new.Sampler(s.proc.pid) sampler.start() settled(s) asked = ask_everywhere(s, phases_p4.rtl_files(buffers)) s.wait_quiet(1.0) time.sleep(1.0) idle.append(phases_new.rss_kib(s.proc.pid)) peaks.append(sampler.stop()) shape = s.client_shape() record(phase="snapshotrss", row="idle RSS, %d open buffer(s), each asked for quick fixes" % buffers, units="KiB", rss_kib=idle, peak_rss_kib=peaks, fresh_process=True, result_count=asked, client=shape, load=os.getloadavg(), note="one quickfix-only codeAction per open buffer, so every " "one of them holds a lint snapshot; idle RSS a second " "after the session went quiet, no latency in this row") def ask_everywhere(s, paths): """Open each path and ask it for quick fixes; returns how many answered.""" answered = 0 for path in paths: s.did_open(path) s.wait_quiet(1.0) s.take_notifications() for path in paths: where = {"line": 0, "character": 0} params = {"textDocument": {"uri": lspclient_uri(path)}, "range": {"start": where, "end": where}, "context": {"diagnostics": [], "only": ["quickfix"]}} _, message = s.request("textDocument/codeAction", params) answered += 1 if schema.status_of(message)[0] == "ok" else 0 return answered # Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com