#58: the discovery walk runs in 512-entry slices with requests drained between them (lucisv_core ResumableWalk, state/walking.rs); identities are read in one pass at landing. Proved equal to the one-shot walk. #64: the 40k rescan timing split is not reproducible; the store is kept across rescans, compaction streams, candidates are cheaper (-12% on 40k, answers and store byte-identical). Files topo #71-#74. Co-Authored-By: Claude Mythos 5.2 <[email protected]>
258 lines
11 KiB
Python
258 lines
11 KiB
Python
# Author: Guoliang Chen, a Senior Digital Design Engineer
|
||
|
||
"""The rescan after a delete, on a big tree, with the server's own breakdown.
|
||
|
||
TODO §71 wave 8 left open: *the 40 000-file rescan after a delete takes either
|
||
12.3 s or 14.5–15.5 s*. The harness that saw it (`fast-actions`' `ab41.py`,
|
||
`b3.py`) lived in a scratch directory and is gone. This is the same loop,
|
||
kept, with every rescan's `--verbose` stage, count and memory lines parsed
|
||
into the row, so a slow rescan can be told from a fast one stage by stage:
|
||
|
||
tools/guard.sh -m 8 -t 1200 -- python3 tools/perf/rescan.py \
|
||
--server target/release/lucisv-server --tree "$SCRATCH/ot10" \
|
||
--storage "$SCRATCH/store" --out "$SCRATCH/rescan.jsonl" \
|
||
--label after --mode busy --runs 5
|
||
|
||
One session per invocation: initialize at workspace scope, open
|
||
`c0/ip/aes/rtl/aes_cipher_core.sv`, wait for the startup scan, then `--runs`
|
||
times: delete the previous probe file (a `didChangeWatchedFiles` *Deleted*,
|
||
which the server answers with a one-file update), create a new one (*Created*,
|
||
which owes a whole rescan) and wait for that rescan to finish. `--mode idle`
|
||
waits for the delete's update before sending the create; `--mode busy` sends
|
||
the create 50 ms after the delete, while the server is still inside it —
|
||
the two rows of the fast-actions table.
|
||
|
||
The probe files are written into `--tree`, which must be a scratch copy
|
||
(`bigtree.py`), never the corpus. `--trigger settings` writes nothing at all
|
||
— each rescan is a settings push alternating a no-op exclude — so it is the
|
||
form to run on the read-only corpus itself (`--open` names the buffer,
|
||
relative to `--tree`). `--probe` sends a `documentSymbol` on the open buffer
|
||
5 ms after each trigger and records how long it waited: what a rescan holds
|
||
a buffer-local request for (topo §2.9-58). Python 3 standard library only.
|
||
"""
|
||
|
||
import argparse
|
||
import json
|
||
import os
|
||
import re
|
||
import resource
|
||
import subprocess
|
||
import sys
|
||
import threading
|
||
import time
|
||
|
||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||
|
||
from lspclient import Session, uri # noqa: E402
|
||
|
||
OPEN = os.path.join("c0", "ip", "aes", "rtl", "aes_cipher_core.sv")
|
||
STAGE = re.compile(r"timing: scan (\d+) (stages|counts|memory) \((\w+)[^)]*\): (.*)")
|
||
PAIR = re.compile(r"(\w+)=([0-9.]+)")
|
||
FINISHED = "timing: scan finished:"
|
||
|
||
|
||
class Rss:
|
||
"""The server's resident set, sampled every 100 ms by `ps` on a thread.
|
||
|
||
The guard sums the whole tree and kills it at 8 GB; this says how close
|
||
each rescan came, and when in the rescan the peak was.
|
||
"""
|
||
|
||
def __init__(self, pid):
|
||
self.pid = pid
|
||
self.samples = [] # (perf_counter, kib)
|
||
self.stopped = False
|
||
self.thread = threading.Thread(target=self.run, daemon=True)
|
||
self.thread.start()
|
||
|
||
def run(self):
|
||
while not self.stopped:
|
||
out = subprocess.run(["ps", "-o", "rss=", "-p", str(self.pid)],
|
||
capture_output=True, text=True).stdout.strip()
|
||
if out:
|
||
self.samples.append((time.perf_counter(), int(out)))
|
||
time.sleep(0.1)
|
||
|
||
def between(self, start, end):
|
||
"""(peak KiB, KiB at `start`, KiB at `end`) over one window."""
|
||
inside = [kib for at, kib in self.samples if start <= at <= end]
|
||
before = [kib for at, kib in self.samples if at <= start]
|
||
after = [kib for at, kib in self.samples if at >= end]
|
||
first = before[-1] if before else (inside[0] if inside else 0)
|
||
last = after[0] if after else (inside[-1] if inside else 0)
|
||
return (max(inside) if inside else 0), first, last
|
||
|
||
|
||
def watched(s, path, kind):
|
||
"""One `didChangeWatchedFiles` naming `path` (1 created, 3 deleted)."""
|
||
s.notify("workspace/didChangeWatchedFiles", {"changes": [{"uri": uri(path), "type": kind}]})
|
||
|
||
|
||
def wait_log(s, start, predicate, timeout=600.0):
|
||
"""Block until a log line from index `start` on satisfies `predicate`."""
|
||
deadline = time.time() + timeout
|
||
while time.time() < deadline:
|
||
s.drain()
|
||
for at in range(start, len(s.log_messages)):
|
||
if predicate(s.log_messages[at]):
|
||
return at, time.perf_counter()
|
||
time.sleep(0.002)
|
||
raise TimeoutError("no matching log line")
|
||
|
||
|
||
def finished(s, start):
|
||
"""Wait for the next whole scan to finish and for its three trace lines.
|
||
|
||
The `stages`/`counts`/`memory` lines follow `scan finished`, and taking
|
||
the window before they land would credit this rescan with the previous
|
||
one's breakdown. Returns (index of the finished line, its instant, the
|
||
lines of this rescan).
|
||
"""
|
||
at, done = wait_log(s, start, lambda t: t.startswith(FINISHED))
|
||
last, _ = wait_log(s, at, lambda t: "memory (whole" in t)
|
||
return at, done, s.log_messages[start:last + 1]
|
||
|
||
|
||
def trace_of(lines):
|
||
"""The stage/count/memory fields of the last whole scan in `lines`."""
|
||
row = {}
|
||
for text in lines:
|
||
found = STAGE.search(text)
|
||
if not found or found.group(3) != "whole":
|
||
continue
|
||
for key, value in PAIR.findall(found.group(4)):
|
||
row["%s_%s" % (found.group(2), key)] = float(value)
|
||
return row
|
||
|
||
|
||
def probe_symbols(s, path):
|
||
"""A `documentSymbol` on `path` sent 5 ms from now; returns its id."""
|
||
time.sleep(0.005)
|
||
return s.send("textDocument/documentSymbol", {"textDocument": {"uri": uri(path)}})
|
||
|
||
|
||
def probe_wait(s, rid):
|
||
"""How long the probe waited: sent to the instant the reader thread
|
||
parsed its answer — not to whenever this script got round to asking."""
|
||
sent = s.pending[rid][1]
|
||
deadline = time.time() + 600
|
||
with s._cond:
|
||
while rid not in s._arrived and time.time() < deadline:
|
||
s._cond.wait(0.05)
|
||
arrived = s._arrived.get(rid, time.perf_counter())
|
||
s.await_id(rid)
|
||
return (arrived - sent) * 1000.0
|
||
|
||
|
||
def settings_rescan(s, k, rss, opened, probe):
|
||
"""A settings push that owes a whole rescan and changes nothing else."""
|
||
s.drain()
|
||
start = len(s.log_messages)
|
||
s.scope = {"index": {"scope": "workspace"}, "exclude": ["zz_no_such_%d" % (k % 2)]}
|
||
sent = time.perf_counter()
|
||
s.notify("workspace/didChangeConfiguration", {"settings": {"lucisv": s.scope}})
|
||
rid = probe_symbols(s, opened) if probe else None
|
||
at, done, lines = finished(s, start)
|
||
row = {"k": k, "wall_ms": (done - sent) * 1000.0, "mode": "settings"}
|
||
if rid is not None:
|
||
row["probe_ms"] = probe_wait(s, rid)
|
||
s.drain()
|
||
time.sleep(0.25)
|
||
row["rss_peak_kib"], row["rss_before_kib"], row["rss_after_kib"] = rss.between(sent, done)
|
||
server_ms = re.search(r"in ([0-9.]+) ?(ms|s)\b", s.log_messages[at])
|
||
if server_ms:
|
||
scale = 1000.0 if server_ms.group(2) == "s" else 1.0
|
||
row["server_ms"] = float(server_ms.group(1)) * scale
|
||
row.update(trace_of(lines))
|
||
return row
|
||
|
||
|
||
def one_rescan(s, tree, k, mode, rss, gap, opened, asked):
|
||
"""Delete probe k-1 (if any), create probe k, time the rescan it owes."""
|
||
probe = os.path.join(tree, "c0", "zz_probe_%d.sv" % k)
|
||
previous = os.path.join(tree, "c0", "zz_probe_%d.sv" % (k - 1))
|
||
s.drain()
|
||
start = len(s.log_messages)
|
||
deleted_at = None
|
||
if os.path.exists(previous):
|
||
os.remove(previous)
|
||
deleted_at = time.perf_counter()
|
||
watched(s, previous, 3)
|
||
if mode == "idle":
|
||
wait_log(s, start, lambda t: "reindex_one(" in t or t.startswith(FINISHED))
|
||
elif gap > 0:
|
||
time.sleep(gap)
|
||
with open(probe, "w", encoding="utf-8") as handle:
|
||
handle.write("module zz_probe_%d;\nendmodule\n" % k)
|
||
sent = time.perf_counter()
|
||
watched(s, probe, 1)
|
||
rid = probe_symbols(s, opened) if asked else None
|
||
at, done, lines = finished(s, start)
|
||
server_ms = re.search(r"in ([0-9.]+) ?(ms|s)\b", s.log_messages[at])
|
||
row = {"k": k, "wall_ms": (done - sent) * 1000.0, "mode": mode, "gap": gap}
|
||
if rid is not None:
|
||
row["probe_ms"] = probe_wait(s, rid)
|
||
time.sleep(0.25)
|
||
row["rss_peak_kib"], row["rss_before_kib"], row["rss_after_kib"] = rss.between(sent, done)
|
||
if deleted_at is not None:
|
||
row["since_delete_ms"] = (done - deleted_at) * 1000.0
|
||
if server_ms:
|
||
scale = 1000.0 if server_ms.group(2) == "s" else 1.0
|
||
row["server_ms"] = float(server_ms.group(1)) * scale
|
||
row.update(trace_of(lines))
|
||
row["reindex_one"] = [t for t in lines if "reindex_one(" in t]
|
||
return row
|
||
|
||
|
||
def main():
|
||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||
parser.add_argument("--server", required=True)
|
||
parser.add_argument("--tree", required=True)
|
||
parser.add_argument("--storage", required=True)
|
||
parser.add_argument("--out", required=True)
|
||
parser.add_argument("--label", required=True)
|
||
parser.add_argument("--mode", choices=("idle", "busy"), default="busy")
|
||
parser.add_argument("--runs", type=int, default=5)
|
||
parser.add_argument("--first", type=int, default=0, help="first probe number")
|
||
parser.add_argument("--gap", type=float, default=0.05,
|
||
help="busy mode: seconds between the delete and the create")
|
||
parser.add_argument("--trigger", choices=("create", "settings"), default="create")
|
||
parser.add_argument("--open", default=OPEN, help="the buffer to open, under --tree")
|
||
parser.add_argument("--probe", action="store_true",
|
||
help="time a documentSymbol sent 5 ms after each trigger")
|
||
args = parser.parse_args()
|
||
tree = os.path.abspath(args.tree)
|
||
with Session(args.server, tree, args.storage, scope={"index": {"scope": "workspace"}},
|
||
verbose=True) as s:
|
||
rss = Rss(s.proc.pid)
|
||
s.initialize()
|
||
opened = os.path.join(tree, args.open)
|
||
s.did_open(opened)
|
||
wait_log(s, 0, lambda t: t.startswith(FINISHED))
|
||
s.wait_quiet(1.0)
|
||
for k in range(args.first, args.first + args.runs):
|
||
if args.trigger == "settings":
|
||
row = settings_rescan(s, k, rss, opened, args.probe)
|
||
else:
|
||
row = one_rescan(s, tree, k, args.mode, rss, args.gap, opened, args.probe)
|
||
row.update({"label": args.label, "pid_load": os.getloadavg()[0]})
|
||
with open(args.out, "a", encoding="utf-8") as handle:
|
||
handle.write(json.dumps(row) + "\n")
|
||
print("%s %s k=%d server=%.0f wall=%.0f probe=%.1f rss %.0f -> peak %.0f -> %.0f MB" % (
|
||
args.label, row["mode"], k, row.get("server_ms", -1), row["wall_ms"],
|
||
row.get("probe_ms", -1),
|
||
row["rss_before_kib"] / 1024, row["rss_peak_kib"] / 1024,
|
||
row["rss_after_kib"] / 1024), flush=True)
|
||
rss.stopped = True
|
||
last = os.path.join(tree, "c0", "zz_probe_%d.sv" % (args.first + args.runs - 1))
|
||
if args.trigger == "create" and os.path.exists(last):
|
||
os.remove(last)
|
||
usage = resource.getrusage(resource.RUSAGE_CHILDREN)
|
||
print("children maxrss %.0f MB" % (usage.ru_maxrss / 1048576.0))
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|
||
|
||
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|