Round 10: resumable discovery walk and faster whole rescans (#58, #64)

#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]>
This commit is contained in:
Guoliang ChenandClaude Mythos 5.2 committed 2026-11-26 19:29:02 -08:00
1 parent dc54b23572
commit 36733e2c7c
29 files changed
+3520 -126

No files matched your search

+102
View File
@@ -0,0 +1,102 @@
# Author: Guoliang Chen, a Senior Digital Design Engineer
"""Build the replicated OpenTitan tree the 40 000-file rescan is measured on.
`docs/features/fast-actions/README.md` measured its 20k / 40k rows on copies
of OpenTitan `hw/` replicated 5 / 10 times under `c0/ ... c9/`, every module,
package, interface, program and class name declared anywhere prefixed `cK_`
in copy K, so that the copies do not collapse into one set of duplicate
definitions. That generator (`gen.py`) lived in a scratch directory and is
gone; this is its replacement, kept here so the tree can be rebuilt.
python3 tools/perf/bigtree.py --opentitan ~/repo/opentitan --copies 10 \
--out "$SCRATCH/ot10"
Python 3 standard library only. **The corpus is only read**: every byte goes
to `--out`, which must not be inside the corpus or the repository, and which
is refused when it already exists (delete it yourself, so a typo cannot
delete anything else). Files whose text is not UTF-8 are copied as bytes.
"""
import argparse
import os
import re
import sys
EXTENSIONS = (".sv", ".v", ".svh", ".vh")
DECL = re.compile(
r"^\s*(?:virtual\s+)?(?:module|macromodule|package|interface|program|class)"
r"\s+(?:automatic\s+|static\s+)?([A-Za-z_][A-Za-z0-9_$]*)",
re.MULTILINE,
)
IDENT = re.compile(r"\b[A-Za-z_][A-Za-z0-9_]*\b")
def sources(hw):
"""Every source file under `hw`, as paths relative to it, sorted."""
found = []
for base, dirs, files in os.walk(hw):
dirs.sort()
for name in sorted(files):
if name.endswith(EXTENSIONS):
found.append(os.path.relpath(os.path.join(base, name), hw))
return found
def declared_names(hw, files):
"""Every unit name any file declares — what each copy prefixes."""
names = set()
for rel in files:
with open(os.path.join(hw, rel), "rb") as handle:
text = handle.read().decode("utf-8", "replace")
names.update(DECL.findall(text))
return names
def renamed(text, names, prefix):
"""`text` with every whole-word use of a declared name prefixed."""
return IDENT.sub(lambda m: prefix + m.group(0) if m.group(0) in names else m.group(0), text)
def write_copy(hw, files, names, out, k):
prefix = "c%d_" % k
for rel in files:
target = os.path.join(out, "c%d" % k, rel)
os.makedirs(os.path.dirname(target), exist_ok=True)
with open(os.path.join(hw, rel), "rb") as handle:
raw = handle.read()
try:
data = renamed(raw.decode("utf-8"), names, prefix).encode("utf-8")
except UnicodeDecodeError:
data = raw
with open(target, "wb") as handle:
handle.write(data)
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--opentitan", required=True)
parser.add_argument("--copies", type=int, default=10)
parser.add_argument("--out", required=True)
args = parser.parse_args()
hw = os.path.realpath(os.path.join(args.opentitan, "hw"))
out = os.path.realpath(args.out)
here = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", ".."))
for forbidden in (os.path.realpath(args.opentitan), here):
if out == forbidden or out.startswith(forbidden + os.sep):
sys.exit("bigtree: --out must be outside %s" % forbidden)
if os.path.exists(out):
sys.exit("bigtree: %s exists; remove it first" % out)
files = sources(hw)
names = declared_names(hw, files)
print("bigtree: %d files, %d declared names, %d copies" % (len(files), len(names), args.copies))
for k in range(args.copies):
write_copy(hw, files, names, out, k)
print("bigtree: copy %d written" % k, flush=True)
print("bigtree: %d files under %s" % (len(files) * args.copies, out))
if __name__ == "__main__":
main()
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
+257
View File
@@ -0,0 +1,257 @@
# 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
+137
View File
@@ -0,0 +1,137 @@
# Author: Guoliang Chen, a Senior Digital Design Engineer
"""What a session answers before and after its rescans, as hashes to diff
between two `lucisv-server` binaries — the differential behind
`docs/features/server-scaling-r10/README.md`.
tools/guard.sh -m 8 -t 1200 -- python3 tools/perf/rescan_diff.py \
--server target/release/lucisv-server --tree ~/repo/opentitan/hw \
--open ip/aes/rtl/aes_cipher_core.sv --storage "$SCRATCH/diff-new" \
--rescans 2 > "$SCRATCH/new.txt"
One cold session at workspace scope (`--storage` is emptied first): the
startup scan, then `--rescans` whole rescans, each a settings push alternating
an exclude that names nothing — so every rescan reads the same tree and writes
nothing into it, and the corpus stays read-only. After the startup scan and
after every rescan it prints one line per answer — workspace symbols, the
module hierarchy, the open buffer's outline and every definition, hover and
reference answer at a few cursors — with the SHA-256 of the answer's JSON;
at the end the SHA-256 and size of the index store file. `--storage` is
emptied only when it is absent, empty or a lucisv store; anything else is
refused. Two binaries that
agree print the same lines. Python 3 standard library only.
"""
import argparse
import hashlib
import json
import os
import re
import shutil
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from lspclient import Session, uri # noqa: E402
from rescan import FINISHED, finished, wait_log # noqa: E402
QUERIES = ["aes", "prim_", "tl_", "u", "reg"]
def digest(value):
return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()[:16]
def cursors(path, count=8):
"""Up to `count` (line, character) positions on names worth asking about
in `path`: package references, instance names, ports and signals with an
underscore, the first of each, never inside a comment."""
wanted = re.compile(r"\b(?:\w+_pkg|u_\w+|\w+_[io]|\w+_q|\w+_d)\b")
found, seen = [], set()
with open(path, encoding="utf-8", errors="replace") as handle:
for line_no, line in enumerate(handle):
code = line.split("//", 1)[0]
for match in wanted.finditer(code):
if match.group(0) in seen:
continue
seen.add(match.group(0))
found.append((line_no, match.start() + 1))
if len(found) >= count:
return found
return found
def answers(s, opened, step):
"""Print one line per answer, `step` naming when it was asked."""
asked = [("workspace/symbol", {"query": q}) for q in QUERIES]
asked.append(("lucisv/moduleHierarchy", {}))
asked.append(("textDocument/documentSymbol", {"textDocument": {"uri": uri(opened)}}))
for line, character in cursors(opened):
for method in ("textDocument/definition", "textDocument/hover",
"textDocument/references"):
params = {"textDocument": {"uri": uri(opened)},
"position": {"line": line, "character": character},
"context": {"includeDeclaration": True}}
asked.append((method, params))
for method, params in asked:
_, message = s.request(method, params)
result = message.get("result", message.get("error"))
where = params.get("query", params.get("position", ""))
print("%s %s %s %s" % (step, method, json.dumps(where, sort_keys=True), digest(result)))
def clear_store(path):
"""Empty `path` for a cold session — only when it is absent, empty, or
holds nothing but what a lucisv index store writes (`index-cache`, its
`.gitignore`, a leftover `index-cache.<pid>.tmp`). Anything else is a
mistyped path and is refused rather than deleted."""
if not os.path.exists(path):
return
if not os.path.isdir(path):
sys.exit("rescan_diff: --storage %s is not a directory; refusing to delete it" % path)
names = os.listdir(path)
store = lambda n: n in ("index-cache", ".gitignore") or (
n.startswith("index-cache.") and n.endswith(".tmp"))
strangers = [n for n in names if not store(n)]
if strangers:
sys.exit("rescan_diff: --storage %s holds %s, not a lucisv store; refusing to delete it"
% (path, ", ".join(sorted(strangers)[:5])))
shutil.rmtree(path)
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--server", required=True)
parser.add_argument("--tree", required=True)
parser.add_argument("--open", required=True)
parser.add_argument("--storage", required=True)
parser.add_argument("--rescans", type=int, default=2)
args = parser.parse_args()
tree = os.path.abspath(args.tree)
clear_store(args.storage)
opened = os.path.join(tree, args.open)
with Session(args.server, tree, args.storage, scope={"index": {"scope": "workspace"}},
verbose=True) as s:
s.initialize()
s.did_open(opened)
wait_log(s, 0, lambda t: t.startswith(FINISHED))
s.wait_quiet(1.0)
answers(s, opened, "startup")
for k in range(args.rescans):
s.drain()
start = len(s.log_messages)
s.scope = {"index": {"scope": "workspace"}, "exclude": ["zz_no_such_%d" % (k % 2)]}
s.notify("workspace/didChangeConfiguration", {"settings": {"lucisv": s.scope}})
finished(s, start)
s.wait_quiet(0.5)
answers(s, opened, "rescan%d" % k)
store = os.path.join(args.storage, "index-cache")
with open(store, "rb") as handle:
data = handle.read()
print("store %d %s" % (len(data), hashlib.sha256(data).hexdigest()))
if __name__ == "__main__":
main()
# Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com