264 lines
12 KiB
Python
264 lines
12 KiB
Python
#!/usr/bin/env python3
|
||
"""The phases for what 0.44–0.49 added: the new offer sites, §49's
|
||
hierarchical surface, §46's `didOpen` fix on the wire, `lucisv/moduleHierarchy`
|
||
and the index's cost on disk and in memory.
|
||
|
||
Imported by `bench.py`, which owns the registry and the command line; nothing
|
||
here is run directly. Split out of `bench.py` so each file stays inside
|
||
CLAUDE.md's size rule and each has one sentence: `bench.py` is the take-3
|
||
table, this is what changed since it.
|
||
"""
|
||
|
||
import json
|
||
import os
|
||
import subprocess
|
||
import threading
|
||
import time
|
||
|
||
import phases_p0
|
||
import schema
|
||
from harness import (
|
||
ARGS, Session, at, code_action_params, counts, doc, edit_of, fingerprint,
|
||
phase, pos, record, samples, session, settled, sites,
|
||
)
|
||
|
||
|
||
def resolve_rows(s, phase_name, label, offered):
|
||
"""Resolve the offers that need resolving; route the rest to their phase.
|
||
|
||
Take 4 sent every offer without an `edit` to `codeAction/resolve`,
|
||
including the extract and inline offers, which carry only a **command**.
|
||
Dispatch handed those to the ports resolver, which rejects an offer
|
||
without its data — so their tiny times measured a refusal. Now a
|
||
command-bearing offer is recorded as belonging to the `execute` phase and
|
||
is not timed here.
|
||
"""
|
||
for action in offered:
|
||
shape = phases_p0.shape_of(action)
|
||
if shape == "edit":
|
||
edit = action.get("edit") or {}
|
||
record(phase=phase_name, row="%s offer carries its edit: %s" % (
|
||
label, action.get("title")),
|
||
ms=[0.0], result_count=1, client=s.client_shape(),
|
||
fingerprint=fingerprint(edit), note="no resolve needed",
|
||
**counts(edit))
|
||
continue
|
||
if shape == "command":
|
||
call = phases_p0.command_of(action) or {}
|
||
record(phase=phase_name, row="%s offer is a command: %s" % (
|
||
label, action.get("title")),
|
||
ms=[0.0], result_count=1, client=s.client_shape(),
|
||
command=call.get("command"),
|
||
note="timed by the `execute` phase, not by resolve")
|
||
continue
|
||
got = samples(s, "codeAction/resolve", action, ARGS.tries + 1)
|
||
edit = edit_of(got.last)
|
||
record(phase=phase_name, row="%s resolve: %s" % (label, action.get("title")),
|
||
client=s.client_shape(), fingerprint=fingerprint(edit),
|
||
**dict(got.row(), **counts(edit)))
|
||
|
||
|
||
@phase("refactor")
|
||
def phase_refactor():
|
||
"""The offer sites 0.44–0.49 added: what is offered, and what it costs."""
|
||
for label, relative, needle, occurrence, offset in sites.REFACTOR_SITES:
|
||
with session("workspace", resolve_support=True) as s:
|
||
phases_p0.open_and_settle(s, relative)
|
||
params = code_action_params(relative, needle, occurrence, offset)
|
||
offer = samples(s, "textDocument/codeAction", params, ARGS.tries + 1)
|
||
offered = offer.last.get("result") or []
|
||
record(phase="refactor", row="%s offer" % label,
|
||
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"], **offer.row())
|
||
resolve_rows(s, "refactor", label, offered)
|
||
# `extract module` is a selection, not a point.
|
||
relative, first, first_n, last, last_n = sites.EXTRACT_SELECTION
|
||
start = pos(relative, first, first_n)
|
||
end = pos(relative, last, last_n)
|
||
end = {"line": end["line"], "character": end["character"] + len(last)}
|
||
with session("workspace", resolve_support=True) as s:
|
||
phases_p0.open_and_settle(s, relative)
|
||
params = {"textDocument": doc(relative),
|
||
"range": {"start": start, "end": end},
|
||
"context": {"diagnostics": []}}
|
||
offer = samples(s, "textDocument/codeAction", params, ARGS.tries + 1)
|
||
offered = offer.last.get("result") or []
|
||
record(phase="refactor", row="extract-module offer (selection)",
|
||
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=start,
|
||
note="selection %d:%d-%d:%d" % (
|
||
start["line"], start["character"], end["line"], end["character"]),
|
||
**offer.row())
|
||
resolve_rows(s, "refactor", "extract-module", offered)
|
||
|
||
|
||
@phase("tailrename")
|
||
def phase_tailrename():
|
||
"""§49 — a net renamed at its declaration, named through an instance tail."""
|
||
relative, needle, occurrence, offset = sites.TAIL_RENAME
|
||
with session("workspace") as s:
|
||
settled(s)
|
||
s.did_open(sites.path(relative))
|
||
s.did_open(sites.path(sites.TAIL_TAIL_FILE))
|
||
s.wait_quiet(0.8)
|
||
s.take_notifications()
|
||
where = at(relative, needle, occurrence, offset)
|
||
record(phase="tailrename", row="tail rename cursor", ms=[0.0],
|
||
result_count=0, note=json.dumps(where["position"]), file=relative)
|
||
params = dict(where, newName="state_q_x")
|
||
got = samples(s, "textDocument/rename", params, ARGS.tries + 1)
|
||
edit = edit_of(got.last)
|
||
uris = edited_uris(got.last)
|
||
tail = os.path.basename(sites.TAIL_TAIL_FILE)
|
||
record(phase="tailrename",
|
||
row="rename state_q (tail through u_entropy_src_main_sm)",
|
||
client=s.client_shape(), fingerprint=fingerprint(edit),
|
||
note="tail edited" if any(tail in u for u in uris) else "TAIL NOT EDITED",
|
||
titles=sorted(os.path.basename(u) for u in uris),
|
||
**dict(got.row(), **counts(edit)))
|
||
|
||
def edited_uris(message):
|
||
"""The URIs a `WorkspaceEdit` touches, whichever shape it came in."""
|
||
edit = message.get("result") or {}
|
||
if not isinstance(edit, dict):
|
||
return []
|
||
if edit.get("changes"):
|
||
return list(edit["changes"].keys())
|
||
return [c.get("textDocument", {}).get("uri", "")
|
||
for c in edit.get("documentChanges") or []]
|
||
|
||
|
||
@phase("didopen")
|
||
def phase_didopen():
|
||
"""§46 — `didOpen` → the request behind it, workspace scope, warm store."""
|
||
for relative in sites.DIDOPEN_FILES:
|
||
runs, seconds, statuses, last = [], [], [], {}
|
||
for _ in range(ARGS.tries):
|
||
with session("workspace") as s:
|
||
settled(s)
|
||
started = time.perf_counter()
|
||
s.did_open(sites.path(relative))
|
||
first = samples(s, "textDocument/definition",
|
||
at(relative, "module ", 1, 0), 1)
|
||
runs.append((time.perf_counter() - started) * 1000.0)
|
||
second = samples(s, "textDocument/definition",
|
||
at(relative, "module ", 1, 0), 1)
|
||
seconds.append(second.ms[0])
|
||
statuses.extend([first.status, second.status])
|
||
last, shape = second.last, s.client_shape()
|
||
lines = sum(1 for _ in open(sites.path(relative), encoding="utf-8", errors="replace"))
|
||
status = schema.worst(statuses)
|
||
record(phase="didopen", row="didOpen %s -> definition" % os.path.basename(relative),
|
||
ms=runs, n=lines, lines=lines, fresh_process=True, status=status,
|
||
message=None if status == "ok" else "a definition did not answer ok",
|
||
result_count=schema.result_count(last), client=shape,
|
||
second_definition_ms=seconds,
|
||
note="each try is a fresh server; second definition " + " / ".join(
|
||
"%.2f" % v for v in seconds))
|
||
|
||
|
||
@phase("tailcompletion")
|
||
def phase_tailcompletion():
|
||
"""Completion after `u_x.` on an instance head (§49's surface)."""
|
||
relative, needle, occurrence, offset = sites.TAIL_HEAD_COMPLETION
|
||
with session("workspace") as s:
|
||
settled(s)
|
||
s.did_open(sites.path(relative))
|
||
s.wait_quiet(0.8)
|
||
s.take_notifications()
|
||
where = at(relative, needle, occurrence, offset)
|
||
got = samples(s, "textDocument/completion", where, ARGS.tries + 1)
|
||
items = (got.last.get("result") or {})
|
||
items = items.get("items", items) if isinstance(items, dict) else items
|
||
record(phase="tailcompletion",
|
||
row="completion after an instance head + '.' (%s)" % os.path.basename(
|
||
sites.path(relative)),
|
||
client=s.client_shape(),
|
||
titles=[i.get("label") for i in (items or [])[:8]], **got.row())
|
||
|
||
|
||
@phase("hierarchy")
|
||
def phase_hierarchy():
|
||
with session("workspace") as s:
|
||
settled(s)
|
||
got = samples(s, "lucisv/moduleHierarchy", {}, ARGS.tries + 1)
|
||
result = got.last.get("result") or {}
|
||
record(phase="hierarchy", row="lucisv/moduleHierarchy",
|
||
client=s.client_shape(), payload_bytes=len(json.dumps(result)),
|
||
note="modules %d, files %d, schema %s" % (
|
||
len(result.get("modules") or []), len(result.get("files") or []),
|
||
result.get("schemaVersion")), **got.row())
|
||
|
||
|
||
def rss_kib(pid):
|
||
"""One `ps -o rss=` reading in KiB, or 0 once the process is gone."""
|
||
out = subprocess.run(["ps", "-o", "rss=", "-p", str(pid)],
|
||
capture_output=True, text=True).stdout.strip()
|
||
return float(out) if out else 0.0
|
||
|
||
|
||
class Sampler(threading.Thread):
|
||
"""`ps -o rss=` every 50 ms, so a scan's *peak* is seen, not just its end.
|
||
|
||
`/usr/bin/time -l` would give a kernel-reported maximum, but it would have
|
||
to wrap the server, and the session's guard already owns that slot; a
|
||
50 ms poll is the honest approximation and the row says which it is.
|
||
"""
|
||
|
||
def __init__(self, pid, interval=0.05):
|
||
super().__init__(daemon=True)
|
||
self.pid, self.interval, self.peak = pid, interval, 0.0
|
||
self.stopping = threading.Event()
|
||
|
||
def run(self):
|
||
while not self.stopping.is_set():
|
||
self.peak = max(self.peak, rss_kib(self.pid))
|
||
self.stopping.wait(self.interval)
|
||
|
||
def stop(self):
|
||
self.stopping.set()
|
||
self.join(timeout=2.0)
|
||
return self.peak
|
||
|
||
|
||
@phase("rss")
|
||
def phase_rss():
|
||
"""Idle and peak server RSS after the workspace scan, and the store size.
|
||
|
||
Take 4 put idle RSS in a field called `ms`, where it was neither a latency
|
||
nor a peak (take 5 §P0). Here idle RSS is `rss_kib`, the sampled maximum
|
||
is `peak_rss_kib`, the store is `store_kib`, `units` says `KiB`, and there
|
||
is no `ms` field at all.
|
||
|
||
Idle is `ps -o rss=` on the server's own pid a second after the scan
|
||
settles — the resident set of a server that has finished indexing and is
|
||
doing nothing. Peak is the largest of the same reading taken every 50 ms
|
||
from `initialize` to that moment, so the scan's own high-water mark is in
|
||
the row rather than inferred.
|
||
"""
|
||
store = os.path.join(ARGS.storage, "rss")
|
||
for cache in ("cold", "warm"):
|
||
idle, peaks, size = [], [], "0"
|
||
for _ in range(ARGS.tries):
|
||
s = Session(server=ARGS.server, root=sites.ROOT, storage=store,
|
||
scope=sites.SCOPES["workspace"], cold=(cache == "cold"))
|
||
with s:
|
||
sampler = Sampler(s.proc.pid)
|
||
sampler.start()
|
||
settled(s)
|
||
time.sleep(1.0)
|
||
idle.append(rss_kib(s.proc.pid))
|
||
peaks.append(sampler.stop())
|
||
size = subprocess.run(["du", "-sk", store], capture_output=True,
|
||
text=True).stdout.split()[0]
|
||
record(phase="rss", row="server RSS after workspace scan, %s cache" % cache,
|
||
units="KiB", rss_kib=idle, peak_rss_kib=peaks, store_kib=int(size),
|
||
fresh_process=True, result_count=len(idle), client=s.client_shape(),
|
||
note="idle RSS a second after the scan settled; peak from "
|
||
"`ps -o rss=` sampled at 50 ms; no latency in this row")
|
||
|
||
|