#!/usr/bin/env python3 """The phases take 5 §P0 added: what a command actually costs, what a filtered offer costs, and what a slow offer does to the request behind it. Imported by `bench.py`, which owns the registry and the command line. - `execute` — the rows take 4 never had. An extract or inline offer carries a **command**, not an edit: `codeAction/resolve` on it reaches the ports resolver, which rejects an offer without its data, so take 4's tiny "extract resolve" rows measured a refusal, not an extraction. This phase sends `workspace/executeCommand`, captures the `workspace/applyEdit` the server pushes back, and declines it. The edit is counted and fingerprinted; the corpus is never written. - `offerkinds` — the owner's action-family attribution probe, promoted from a scratch script: seven `context.only` shapes at five cursors, result counts beside every time. - `offerqueue` — the owner's pipelining probe: the pinmux no-offer comment as the leader and an `aes` definition as the follower, leader and follower in their own fields rather than a repeats array that means neither. - [`first_useful_rows`] is not a phase: `bench.py::phase_scan` calls it so the `scan` phase reports scan-settled time and first-useful-answer separately. """ import copy import os import time import schema from harness import ( ARGS, at, code_action_params, counts, doc, fingerprint, phase, pos, record, samples, session, settled, sites, ) #: The `context.only` families the attribution probe walks. `None` asks for #: everything (no `only` key at all); `[]` asks for nothing, and should be the #: cheapest answer the server can give. ONLY_FAMILIES = [ None, [], ["quickfix"], ["refactor.extract"], ["refactor.inline"], ["refactor.rewrite.lucisv.ports"], ["source.organizeImports"], ] #: (label, file, needle, cursor offset) — the five cursors of the owner's #: size/attribution control, smallest file first. OFFER_CURSORS = [ ("tb-comment", sites.TB, "// ", 2), ("aes-reg-instance", sites.AES, "aes_reg_top u_reg (", 0), ("aes-core-comment", sites.AES_CORE, "// ", 2), ("spi-comment", sites.SPI_DEVICE, "// ", 2), ("pinmux-comment", sites.PINMUX_REG_TOP, "// ", 2), ] def open_and_settle(s, relative, quiet=0.6): """Settle the scan, then open the file this row measures.""" settled(s) s.did_open(sites.path(relative)) s.wait_quiet(quiet) s.take_notifications() def shape_of(action): """`edit`, `command` or `data` — how an offer delivers its work. An offer that already carries an `edit` needs nothing more; one with only a `command` is run by `workspace/executeCommand`; one with neither is the lazy shape, completed by `codeAction/resolve`. Take 4 sent the second and third kind to the same place, which is the §P0 bug. """ if not isinstance(action, dict): return "command" # a bare `Command`, not a `CodeAction` if action.get("edit"): return "edit" if action.get("command"): return "command" return "data" def command_of(action): """`{command, arguments}` for `workspace/executeCommand`, or None.""" command = action.get("command") if isinstance(action, dict) else None if isinstance(command, str): # a bare `Command` object return {"command": command, "arguments": action.get("arguments") or []} if isinstance(command, dict): return {"command": command.get("command"), "arguments": command.get("arguments") or []} return None def shown(s): """The `window/showMessage` texts the server has sent since last asked. `extract` and `inline` report their scope warnings this way, and a warning is part of a refactoring's answer — so it joins the fingerprint. A message naming this client's own declined edit is dropped: that is our doing. """ found = [n.get("params", {}).get("message", "") for n in s.take_notifications("window/showMessage")] return [t for t in found if t and schema.CAPTURE_REASON not in t] def execute_once(s, params): """One `workspace/executeCommand`, timed in its two halves. Returns `(compute_ms, deliver_ms, total_ms, message, pushes)`. `compute_ms` runs from the request going out to the server's `workspace/applyEdit` arriving: that instant is the end of the edit computation, which is what a menu click waits for. `deliver_ms` runs from this client's `applied: false` to the command's own response, and is recorded separately because it is bookkeeping, not work. A server that pushed nothing (a refusal, or a client shape that gets the edit as the result) leaves both halves `None` and only `total_ms` stands. """ s.take_applied() rid = s.send("workspace/executeCommand", params) sent = s.pending[rid][1] total_ms, message = s.await_id(rid) pushes = s.take_applied() if not pushes: return None, None, total_ms, message, pushes compute_ms = (pushes[0]["arrived"] - sent) * 1000.0 deliver_ms = total_ms - (pushes[0]["replied"] - sent) * 1000.0 return compute_ms, deliver_ms, total_ms, message, pushes def verdict(statuses, pushed): """The row's status: a capture is a success, a refusal is not a timing.""" failed = next(((s, m) for s, m in statuses if s != "ok"), None) if failed: return failed if not pushed: return "error", "the server pushed no workspace/applyEdit" return "capture", schema.CAPTURE_REASON def execute_row(s, label, action): """`--tries + 1` executions of one command-bearing offer, as one row.""" call = command_of(action) if call is None or not call["command"]: record(phase="execute", row="%s: no command" % label, ms=[0.0], status="error", message="the offer carries no command", result_count=0, client=s.client_shape()) return s.take_notifications() compute, deliver, total, statuses, pushed = [], [], [], [], [] for _ in range(ARGS.tries + 1): one, two, three, message, pushes = execute_once(s, call) if one is not None: compute.append(one) deliver.append(two) total.append(three) statuses.append(schema.status_of(message)) pushed = pushes or pushed warnings = list(dict.fromkeys(shown(s))) # one per distinct text, in order status, text = verdict(statuses, pushed) edit = pushed[0]["edit"] if pushed else {} note = ("ms is executeCommand -> applyEdit: the edit computation. " "applyEdit label %r" % pushed[0]["label"] if pushed else "no edit was pushed, so ms is the whole executeCommand round trip") record(phase="execute", row="%s: %s" % (label, action.get("title")), ms=compute or total, status=status, message=text, result_count=len(pushed), client=s.client_shape(), command=call["command"], arguments=len(call["arguments"]), total_ms=total, deliver_ms=deliver or None, fingerprint=fingerprint(edit, warnings) if pushed else None, warnings=warnings, note=note, **counts(edit)) def execute_sites(): """The two command-bearing sites: the extract selection, the inline point. Both are `sites.py`'s own positions — the selection of `EXTRACT_SELECTION` and the `inline-module` row of `REFACTOR_SITES` — so the cursor this phase runs is the cursor `refactor` offers at. """ relative, first, first_n, last, last_n = sites.EXTRACT_SELECTION start, end = pos(relative, first, first_n), pos(relative, last, last_n) end = {"line": end["line"], "character": end["character"] + len(last)} rows = [("extract-module", relative, {"textDocument": doc(relative), "range": {"start": start, "end": end}, "context": {"diagnostics": []}})] for label, path, needle, occurrence, offset in sites.REFACTOR_SITES: if label != "inline-module": continue rows.append((label, path, code_action_params(path, needle, occurrence, offset))) return rows @phase("execute") def phase_execute(): """§P0 — the extract and inline commands actually run, and their edits. The client says `workspace.applyEdit` and `resourceOperations: create`, so the server takes the branch a real editor takes: the edit is pushed, not returned. Every push is declined with `schema.CAPTURE_REASON`. """ for label, relative, params in execute_sites(): with session("workspace", resolve_support=True, apply_edit=True, create_files=True) as s: open_and_settle(s, relative) offer = samples(s, "textDocument/codeAction", params, ARGS.tries + 1) offered = offer.last.get("result") or [] record(phase="execute", row="%s offer" % label, client=s.client_shape(), file=relative, position=params["range"]["start"], titles=[a.get("title") for a in offered], shapes=[shape_of(a) for a in offered], **offer.row()) for action in offered: if shape_of(action) == "command": execute_row(s, label, action) @phase("offerkinds") def phase_offerkinds(): """§P0 — the `context.only` families at five cursors, four requests each. The owner's scratch attribution probe, promoted: which families a request asks for changes what the server computes, and the result count beside every time says whether a cheaper answer is also a smaller one. """ for label, relative, needle, offset in OFFER_CURSORS: with session("workspace", resolve_support=True) as s: open_and_settle(s, relative) base = code_action_params(relative, needle, offset=offset) for family in ONLY_FAMILIES: params = copy.deepcopy(base) if family is not None: params["context"]["only"] = family got = samples(s, "textDocument/codeAction", params, 4) record(phase="offerkinds", row="%s %s" % (label, family), client=s.client_shape(), file=relative, position=base["range"]["start"], only=family, load=os.getloadavg(), **got.row()) @phase("offerqueue") def phase_offerqueue(): """§P0 — what the pinmux no-offer comment does to the request behind it. Leader and follower go out back to back and are recorded in *separate* fields: take 4's `offer-queue` row put both in `ms`, where a reader could not tell them from repeat trials. """ with session("workspace", resolve_support=True) as s: open_and_settle(s, sites.PINMUX_REG_TOP) leader_params = code_action_params(sites.PINMUX_REG_TOP, "// ", offset=2) follower_params = at(sites.TB, " aes #(", 1, 2) for pipeline in range(1, ARGS.tries + 1): lead = s.send("textDocument/codeAction", leader_params) follow = s.send("textDocument/definition", follower_params) leader_ms, leader_message = s.await_id(lead) follower_ms, follower_message = s.await_id(follow) leader_status, leader_text = schema.status_of(leader_message) follower_status, follower_text = schema.status_of(follower_message) record(phase="offerqueue", row="pinmux comment -> aes definition, pipeline %d" % pipeline, ms=[leader_ms, follower_ms], leader_ms=leader_ms, follower_ms=follower_ms, status=schema.worst([leader_status, follower_status]), message=leader_text or follower_text, result_count=schema.result_count(leader_message), follower_result_count=schema.result_count(follower_message), client=s.client_shape(), note="ms is [leader, follower], not repeats") def first_useful_rows(): """`scan`'s other half: when the first useful answer arrives. A definition goes out immediately after the `didOpen`, while the scan is still running; `first_answer_ms` is when it came back and `settled_ms` is when that session's server went quiet. Each try is a fresh process. These are separate rows from `scan`'s own, because a request served during the scan perturbs the scan: keeping them apart leaves `scan`'s settled series comparable with take 4's, which had nothing in flight. """ for cache in ("cold", "warm"): first, settle, statuses, found = [], [], [], [] for _ in range(ARGS.tries): with session("workspace", cold=(cache == "cold"), storage_name="scan-workspace") as s: s.initialize() started = time.perf_counter() s.did_open(sites.path(sites.TB)) answer_ms, message = s.await_id( s.send("textDocument/definition", at(sites.TB, " aes #(", 1, 2))) first.append(answer_ms) statuses.append(schema.status_of(message)[0]) found.append(schema.result_count(message)) s.wait_quiet(1.5) settle.append((time.perf_counter() - started) * 1000.0 - 1500.0) shape = s.client_shape() status = schema.worst(statuses) record(phase="scan", row="workspace, %s cache, first useful answer" % cache, ms=first, first_answer_ms=first, settled_ms=settle, fresh_process=True, status=status, client=shape, message=None if status == "ok" else "a definition did not answer ok", result_count=found[-1], result_counts=found, note="ms is the definition sent during the scan; a 0 result " "count means the answer arrived before the index could " "give one. settled_ms is that session's own scan, " "perturbed by serving the request")