Files
lucisv/tools/perf/phases_r4.py
T

315 lines
13 KiB
Python

#!/usr/bin/env python3
"""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 <n> 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 session's **last** notification.
Not "when the probe stopped asking, minus a quiet window": the offered load
runs for a fixed window that may end before the session does or long after
it, so both halves are taken into account — the last chatter the send loop
saw, and anything `wait_quiet` sees after it.
"""
entered = time.perf_counter()
more = s.wait_quiet(QUIET)
last = entered + more / 1000.0 if more > 0.0 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)
settle = settled_at(s, quiet_at, origin)
settled_answer = s.request("textDocument/definition", params)[1].get("result")
scans = traces(s)
return {
"sent": sent,
"jitter": jitter,
"settle": settle,
"answers": answers,
"unanswered": unanswered,
"settled_answer": settled_answer,
"scans": scans,
}
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 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["settle"])
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)
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],
"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):
"""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"]
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)"
)
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"
)
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
runs = []
for _ in range(ARGS.tries):
with session("workspace", cold=(cache == "cold"), verbose=True,
storage_name="r4-load") as s:
runs.append(one_session(s, rate, ticks, extra, params))
got = summary(runs)
if not rate:
record(phase="scanload",
row="quiet control, %s cache, %d extra buffer(s)" % (cache, buffers),
fresh_process=True, result_count=0, rate_ms=0,
ms=got["settled_ms"], settled_ms=got["settled_ms"],
publication=got["publication"], open_buffers=buffers + 1,
note=QUIET_NOTE)
return
status, message = cell_status(got)
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 ")