#!/usr/bin/env python3 # Author: Guoliang Chen, a Senior Digital Design Engineer """Review round §R4: what a startup scan costs while requests keep arriving. Imported by `bench.py`, which owns the registry and the command line. `scanserve` (`phases_p4.py`) sends the next definition 200 ms **after the previous response**, so a server that answers faster is asked more often and its session-completion time is not comparable between two binaries. The review (`docs/performance_take5_review.md` §4, "Startup throughput and responsiveness must be judged separately") asks for the controlled form instead: a **fixed arrival rate**, the same offered load whatever the server does with it. `scanload` is that probe. - **The clock, not the answers.** A definition goes out every `rate` ms of wall time counted from the session's own start, whether or not the previous one has been answered. Requests pipeline; a server that stalls accumulates them, which is the queue latency this is here to see. - **Every request's own wait.** `Session.poll_answers` stamps a response where the reader thread parses it, so a request answered while the probe is busy sending the next one is not charged for the probe's poll interval. - **The publication split beside it.** The session runs `--verbose`, so the server's own `timing: scan stages/counts` lines give `publishes`, `published` and the four `publish_*` stages (`docs/features/perf5-p4/README.md`) for the very session whose latencies are in the row. - **A quiet control in the same series.** The same cells with no requests at all, so a settle time that moved can be told apart from a settle time that moved *because requests arrived*. Buffer counts are **extra** buffers: the cursor's own file (`sites.TB`) is always open, because the definition is asked in it. So "0" is one open buffer and "100" is 101, which is the same convention `scanprofile` uses. """ import os import statistics import time from harness import ARGS, at, phase, record, session, sites from phases_p4 import QUIET, rtl_files, scan_chatter, traces #: Arrival rates, in milliseconds between two definitions. RATES = (100, 250) #: Extra open buffers per cell, beside the cursor's own. BUFFERS = (0, 1, 10, 100) #: How long the probe keeps offering, per cache state, in milliseconds. #: #: **A fixed window, not "until the scan goes quiet".** The first draft stopped #: sending when the server stopped saying things, which made the offered load a #: function of the server — a faster binary was asked fewer times, which is the #: very confound `scanserve` has and this phase exists to remove. The window is #: instead long enough to cover the *reference's* whole loaded session (cold #: 5.9-9.2 s, warm 2.0-3.4 s measured at `eb54042`), so both binaries are asked #: exactly the same number of times and a binary that finishes sooner shows it #: as requests answered **after** settle rather than as requests never sent. WINDOW_MS = {"cold": 9000, "warm": 3500} #: A request still in flight after the scan settled is waited for this long. DRAIN_TIMEOUT = 60.0 #: The four `publish_*` stages, in the order `ScanTrace::stage_line` writes. PUBLISH_STAGES = ("publish_absorb", "publish_candidates", "publish_includes", "publish_overlay") def open_buffers(s, extra): """Open the cursor's own file and `extra` more. Returns the start instant.""" started = time.perf_counter() s.did_open(sites.path(sites.TB)) for path in extra: s.did_open(path if os.path.isabs(path) else sites.path(path)) return started def take_answers(s, answers, origin): """Move every response that has arrived into `answers`, timestamped.""" for rid, _method, elapsed, arrived, message in s.poll_answers(): answers.append({ "rid": rid, "ms": elapsed, "at": (arrived - origin) * 1000.0, "result": message.get("result"), }) def offer(s, rate_ms, ticks, params, origin, answers): """Send `ticks` definitions, one every `rate_ms`, and watch for silence. The tick is counted from `t0` in whole periods rather than accumulated from the last send, so a slow iteration cannot make the offered load drift; the largest gap between a tick's due instant and its write is reported as `tick_jitter_ms`, which is how a reader checks the arrival discipline the row claims. **The count is fixed**, so what the server does with a request cannot change how many it is asked. Returns `(sent, jitter_ms, quiet_at)` — `quiet_at` being the last instant the *scan* said anything. """ t0 = time.perf_counter() sent, jitter = 0, 0.0 seen, quiet_at = scan_chatter(s), t0 while sent < ticks: now = time.perf_counter() due = t0 + sent * rate_ms / 1000.0 if now >= due: s.send("textDocument/definition", params) jitter = max(jitter, (time.perf_counter() - due) * 1000.0) sent += 1 take_answers(s, answers, origin) chatter = scan_chatter(s) if chatter != seen: seen, quiet_at = chatter, now time.sleep(0.002) return sent, jitter, quiet_at def drain_answers(s, answers, origin): """Wait, bounded, for the requests still in flight when the scan ended.""" deadline = time.time() + DRAIN_TIMEOUT while s.pending and time.time() < deadline: take_answers(s, answers, origin) time.sleep(0.002) take_answers(s, answers, origin) return len(s.pending) def settled_at(s, quiet_at, origin): """Milliseconds from `origin` to the moment the **scan** ended. The scan's own event and nothing else (review finding F3). The old form took the last notification of any kind after the request window, and a `--verbose` server logs one line per request — so a probe that offered load for 3.5 s recorded a 3.4 s "settle" for a scan that ended at 1.77 s, and then classified every response as mid-scan. `Session.scan_completed_at` is stamped by the reader thread on the indexing bar's own `end`, which no request can move. The fallback is for a session that saw no such event at all — and "nothing more arrived" is asked by counting notifications, never by testing a clock delta for exact zero. """ if s.scan_completed_at is not None: return (s.scan_completed_at - origin) * 1000.0 entered = time.perf_counter() before = len(s.notifications) more = s.wait_quiet(QUIET) s.drain() last = entered + more / 1000.0 if len(s.notifications) > before else quiet_at return (last - origin) * 1000.0 def one_session(s, rate_ms, ticks, extra, params): """One fresh session under a fixed offered load. Returns its measurements.""" s.initialize() origin = open_buffers(s, extra) answers = [] sent, jitter, quiet_at = offer(s, rate_ms, ticks, params, origin, answers) unanswered = drain_answers(s, answers, origin) # One measurement under two names: `settled_ms` is the row field every # earlier series carries, and it now holds what it always claimed to — # when this session's scan ended. settle = settled_at(s, quiet_at, origin) settled_answer = s.request("textDocument/definition", params)[1].get("result") return { "sent": sent, "jitter": jitter, "settle": settle, "scan_completed_ms": settle, "scan_ends": len(s.progress_ends), "answers": answers, "unanswered": unanswered, "settled_answer": settled_answer, "scans": traces(s), } def publication(scans): """The first whole scan's publication counts and per-stage milliseconds.""" if not scans: return {} stages = scans[0].get("stages") or {} counts = scans[0].get("counts") or {} out = {stage: stages.get(stage, 0.0) for stage in PUBLISH_STAGES} out["publish_total"] = sum(out.values()) out["publishes"] = counts.get("publishes", 0) out["published"] = counts.get("published", 0) out["first_publish"] = counts.get("first_publish", 0.0) out["scan_total"] = stages.get("total", 0.0) return out def counts_of(run): """One session's first traced scan's `counts`, or nothing.""" scans = run.get("scans") or [] return (scans[0].get("counts") if scans else None) or {} def summary(runs): """Every session's rows folded into the one the cell records.""" latencies = sorted(a["ms"] for run in runs for a in run["answers"]) inside = sorted(a["ms"] for run in runs for a in run["answers"] if a["at"] <= run["scan_completed_ms"]) mid = len(inside) mismatched = sum(1 for run in runs for a in run["answers"] if a["result"] and a["result"] != run["settled_answer"]) unsettled = sum(1 for run in runs for a in run["answers"] if a["result"] != run["settled_answer"]) answered = len(latencies) # Per **timed trial**, never per cell: a cell whose first trial is the one # that filled the store is exactly what finding F2 was about, and one # number for the cell would hide it again. cache_hits = [counts_of(run).get("hits", 0) for run in runs] cache_misses = [counts_of(run).get("misses", 0) for run in runs] return { "ms": latencies, "latency_median_ms": statistics.median(latencies) if latencies else 0.0, "latency_max_ms": max(latencies) if latencies else 0.0, "mid_scan_median_ms": statistics.median(inside) if inside else 0.0, "mid_scan_max_ms": max(inside) if inside else 0.0, "requests_sent": [run["sent"] for run in runs], "requests_answered": answered, "mid_scan_answers": mid, "after_settle_answers": answered - mid, "unanswered_requests": sum(run["unanswered"] for run in runs), "mismatched_answers": mismatched, "unsettled_answers": unsettled, "settled_ms": [run["settle"] for run in runs], "scan_completed_ms": [run["scan_completed_ms"] for run in runs], "scan_ends": [run["scan_ends"] for run in runs], "cache_hits": cache_hits, "cache_misses": cache_misses, "tick_jitter_ms": max((run["jitter"] for run in runs), default=0.0), "publication": [publication(run["scans"]) for run in runs], } def cell_status(got, cache=None): """A cell is a finding when an answer disagreed or a request went missing.""" if not got["ms"]: return "error", "no request was answered at all" if got["mismatched_answers"]: return "error", "%d mid-scan answers disagreed with the settled index" % ( got["mismatched_answers"]) if got["unanswered_requests"]: return "error", "%d requests were never answered" % got["unanswered_requests"] # Finding F2: a warm label is a claim about the store, so it is checked # rather than asserted. A trial that parsed everything read nothing from # the store, and a cell that quotes it beside three warm ones is the # measurement error the review found, not a slow server. if cache == "warm" and any(hits == 0 for hits in got.get("cache_hits", [])): return "error", ("a warm trial found nothing in the store: hits %r, misses %r" % (got.get("cache_hits"), got.get("cache_misses"))) return "ok", None NOTE = ( "ms is every request's own wait, sorted, across all tries; the arrival " "rate is wall-clock and independent of the responses (`tick_jitter_ms` is " "the largest slip); `publication` is each try's first traced scan — the " "four publish_* stages, the publish count and the files published; " "`mismatched_answers` is the coherence contract of " "docs/features/index-scope/README.md, `unsettled_answers` the review §2 " "gate (every answer, empty ones included, equal to the settled one); " "`scan_completed_ms` (and `settled_ms`, the same measurement) is the " "server's own end-of-scan event, so `mid_scan_*` counts responses that " "really did arrive inside the scan; `cache_hits`/`cache_misses` are per " "timed trial, and a warm cell whose trial found nothing in the store is a " "finding rather than a number (F2/F3)" ) QUIET_NOTE = ( "the control: the same cell with no requests at all, so a settle time " "that moved can be told from one that moved because requests arrived. " "ms is the session's completion time, not a request latency" ) #: Where every `scanload` session's index store lives, under `--storage`. STORE = "r4-load" def prime(extra): """Fill the store, untimed, before a warm cell measures anything. Finding F2: `Session.__enter__` *creates* the storage directory, which is not the same as filling it, so a `scanload` run pointed at a fresh `--storage` measured a cold first trial under a warm label (0 hits and 3 974 misses, 1 684 ms of parsing, against 3 974 hits and none on the next). This is the missing half: one whole session over the same scope and the same buffers, its time thrown away, so every timed trial afterwards reads a store that has all of it. Not a substitute for the check — `cell_status` still refuses a warm cell whose trials found nothing in the store, because a store that exists is not evidence that it is complete. """ with session("workspace", cold=False, verbose=True, storage_name=STORE) as s: s.initialize() open_buffers(s, extra) s.wait_quiet(QUIET) def load_cell(cache, buffers, rate, params, where=""): """One cell: `--tries` fresh sessions under the same fixed offered load.""" extra = rtl_files(buffers) ticks = WINDOW_MS[cache] // rate if rate else 0 store = os.path.join(ARGS.storage, STORE) if cache == "warm" and not (os.path.isdir(store) and os.listdir(store)): prime(extra) runs = [] for _ in range(ARGS.tries): with session("workspace", cold=(cache == "cold"), verbose=True, storage_name=STORE) as s: runs.append(one_session(s, rate, ticks, extra, params)) got = summary(runs) if not rate: # `ms` is the settle time here, and `settled_ms` is already in `got`. record(phase="scanload", row="quiet control, %s cache, %d extra buffer(s)" % (cache, buffers), fresh_process=True, result_count=0, rate_ms=0, open_buffers=buffers + 1, note=QUIET_NOTE, **dict(got, ms=got["settled_ms"])) return status, message = cell_status(got, cache) got["ms"] = got["ms"] or [0.0] record(phase="scanload", row="%sdefinition every %d ms, %s cache, %d extra buffer(s)" % (where, rate, cache, buffers), fresh_process=True, status=status, message=message, result_count=got["requests_answered"], requests_offered=ticks, rate_ms=rate, open_buffers=buffers + 1, note=NOTE, **got) def every_cell(cache): """Both rates and the quiet control at every buffer count, for one cache.""" params = at(sites.TB, " aes #(", 1, 2) for buffers in BUFFERS: for rate in RATES: load_cell(cache, buffers, rate, params) load_cell(cache, buffers, 0, params) @phase("scanload") def phase_scanload(): """A definition every N ms of wall clock, for the whole **warm** scan. Warm and cold are two phases rather than one because a cold cell under this load is a 10-second session and eight of them do not fit inside the 1 800-second guard every perf command runs under. Splitting the *run* is the answer to that; raising the guard is not (`tools/guard.sh`). """ every_cell("warm") @phase("scanloadcold") def phase_scanloadcold(): """[`phase_scanload`] with the index store deleted before every session.""" every_cell("cold") @phase("scanloadprobe") def phase_scanloadprobe(): """One warm cell only — the fast loop for checking the probe itself.""" load_cell("warm", 1, 100, at(sites.TB, " aes #(", 1, 2)) @phase("scanloadcross") def phase_scanloadcross(): """The same fixed load at a cursor the open buffer's own folder cannot answer. `scanload`'s cursor names a module in `hw/ip/aes/rtl`, which the head walks first — so it is non-empty from the first publish and the empty-answer rule never fires on it. This one names an interface declared in `hw/dv/sv/tl_agent`, which the head does not hold: in the reference it is answered `[]` at the head publish and only becomes right once the scan has reached that folder. It is what the rule costs (a longer wait for those requests) and what it buys (`unsettled_answers`, which is the review's own gate), measured rather than argued. """ params = at(sites.TB, "tl_if tl_if (", 1, 0) for cache in ("cold", "warm"): for buffers in (0, 10): load_cell(cache, buffers, 100, params, where="cross-folder ") # Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com