Files

292 lines
14 KiB
Python

#!/usr/bin/env python3
"""Take 5 §P4a: where a startup goes, read off the server's own trace.
Imported by `bench.py`, which owns the registry and the command line.
The server built for §P4a says, at the end of every scan and only under
`--verbose`, three `timing: scan <n> …` lines — stages in ms, counts, and the
sizes the scan left resident (`docs/features/perf5-p4/README.md`). This module
runs the scans the plan named, parses those lines, and writes one schema-2 row
per (cell, scan). Nothing here changes the server; it reads what the server
says about itself.
- `scanprofile` — the workspace scope cold and warm, the default scope, depth
0, and 1 / 10 / 100 open buffers. Every cell is `--tries` fresh processes.
A session at a non-default scope pays **two** scans: the startup scan runs
at the default settings, and the configured scope arrives afterwards and
asks for another. They are separate rows because they are separate scans.
- `scanwait` — the first useful answer during a scan, cold and warm, with the
trace of the very session that answered it beside the latency. This is the
§P0 finding (cold 84 ms, warm 206 ms) with the breakdown that explains it.
- `scanserve` — a definition every 200 ms for as long as the scan runs: the
latency distribution of requests that arrive mid-scan, and whether any of
them saw a table the settled index disagrees with.
"""
import os
import re
import time
import schema
from harness import (
ARGS, at, phase, record, session, sites,
)
#: One trace line: `timing: scan <n> <kind> (<shape>, …): a=1 b=2 …`.
TRACE_LINE = re.compile(r"^timing: scan (\d+) (stages|counts|memory) \(([a-z]+)[,)]")
#: `timing: scan finished: N file(s) (S skipped, C from cache) in X ms`.
FINISHED = re.compile(r"^timing: scan finished: (\d+) files? \((\d+) skipped, (\d+) from cache\)")
#: How long to let a scan run before giving up on it going quiet.
QUIET = 1.5
def fields(line):
"""Every `key=value` on a trace line, values as numbers where they are."""
out = {}
for token in line.split(":", 2)[-1].split():
if "=" not in token:
continue
key, value = token.split("=", 1)
try:
out[key] = float(value) if "." in value else int(value)
except ValueError:
out[key] = value
return out
def traces(s):
"""The scans a session traced, in order, as dicts keyed by scan number.
Each entry is `{"n", "kind", "stages", "counts", "memory"}`. A scan whose
three lines did not all arrive is still reported, with the halves it has —
a missing half is a finding, not something to hide.
"""
s.drain()
found = {}
for text in s.log_messages:
seen = TRACE_LINE.match(text)
if not seen:
continue
number, kind, shape = int(seen.group(1)), seen.group(2), seen.group(3)
entry = found.setdefault(number, {"n": number, "kind": shape})
entry[kind] = fields(text)
return [found[n] for n in sorted(found)]
def config_wait_ms(s):
"""How long the client took to answer `workspace/configuration`."""
for text in s.log_messages:
if text.startswith("timing: configuration answered in "):
return float(text.rsplit(" ", 2)[-2])
return None
def stage_row(phase_name, row, cell, scans, settled, extra=None):
"""One row per traced scan, plus the settled wall time of the session."""
for scan in scans:
stages = scan.get("stages") or {}
counts = scan.get("counts") or {}
memory = scan.get("memory") or {}
missing = [k for k in ("stages", "counts", "memory") if not scan.get(k)]
record(
phase=phase_name,
row="%s, scan %d (%s)" % (row, scan["n"], scan["kind"]),
ms=[stages.get("total", 0.0)],
settled_ms=settled,
stages=stages, counts=counts, memory=memory,
fresh_process=True,
result_count=counts.get("read", 0),
status="ok" if not missing else "error",
message=None if not missing else "no %s line" % "/".join(missing),
note=cell + ("" if not extra else " | " + extra),
)
def settle(s, open_files=(), first=sites.TB):
"""Open `first` (and any extra buffers), then wait for the scan to end.
Returns the milliseconds from the `didOpen` to the last notification, with
the quiet window taken back off — the same barrier `bench.py::phase_scan`
uses, so the numbers are comparable with the settled series.
"""
started = time.perf_counter()
s.did_open(sites.path(first))
for relative in open_files:
s.did_open(relative if os.path.isabs(relative) else sites.path(relative))
s.wait_quiet(QUIET)
return (time.perf_counter() - started) * 1000.0 - QUIET * 1000.0
def rtl_files(count):
"""`count` opentitan RTL files, in a stable order, for the buffer cells."""
found = []
for folder in ("hw/ip/aes/rtl", "hw/ip/kmac/rtl", "hw/ip/spi_device/rtl",
"hw/ip/entropy_src/rtl", "hw/ip/otbn/rtl", "hw/ip/hmac/rtl",
"hw/ip/flash_ctrl/rtl", "hw/ip/keymgr/rtl", "hw/ip/rv_dm/rtl",
"hw/ip/usbdev/rtl", "hw/ip/i2c/rtl", "hw/ip/spi_host/rtl"):
directory = sites.path(folder)
if not os.path.isdir(directory):
continue
for name in sorted(os.listdir(directory)):
if name.endswith(".sv") and len(found) < count:
found.append(os.path.join(directory, name))
return found
@phase("scanprofile")
def phase_scanprofile():
"""The startup breakdown, one cell per (scope, cache state, buffers)."""
cells = [
("workspace, cold cache", "workspace", True, 0),
("workspace, warm cache", "workspace", False, 0),
("default scope, cold cache", "default", True, 0),
("default scope, warm cache", "default", False, 0),
("depth0, cold cache", "depth0", True, 0),
("depth0, warm cache", "depth0", False, 0),
("workspace warm, 1 open buffer", "workspace", False, 1),
("workspace warm, 10 open buffers", "workspace", False, 10),
("workspace warm, 100 open buffers", "workspace", False, 100),
]
for label, scope, cold, buffers in cells:
settled, per_try, waits = [], [], []
opened = rtl_files(buffers)
for _ in range(ARGS.tries):
with session(scope, cold=cold, verbose=True,
storage_name="p4-" + scope) as s:
s.initialize()
settled.append(settle(s, opened))
per_try.append(traces(s))
waits.append(config_wait_ms(s))
# The scans line up across tries (the same scope resolves the same
# way), so a scan's row carries the first try's fields and every try's
# settled time. A try that traced a different number of scans is a
# finding, and the note says so.
shapes = {len(t) for t in per_try}
extra = "config wait %s ms | %d open buffer(s)" % (
"/".join("%.2f" % w if w is not None else "-" for w in waits), buffers)
if len(shapes) != 1:
extra += " | tries traced %s scans" % sorted(shapes)
stage_row("scanprofile", label, label, per_try[0], settled, extra)
@phase("scanwait")
def phase_scanwait():
"""The first useful answer during a scan, with that session's own trace.
§P0 measured the latency and could not explain it: cold 84 ms, warm 206.
Here the definition goes out exactly as it did there, and the trace of the
very session that answered it is in the row beside it.
"""
for cache in ("cold", "warm"):
first, settled, found, statuses, per_try, waits = [], [], [], [], [], []
for _ in range(ARGS.tries):
with session("workspace", cold=(cache == "cold"), verbose=True,
storage_name="p4-wait") as s:
s.initialize()
started = time.perf_counter()
s.did_open(sites.path(sites.TB))
answer_ms, message = s.await_id(
s.send("textDocument/definition", at(sites.TB, " aes #(", 1, 2)))
first.append(answer_ms)
statuses.append(schema.status_of(message)[0])
found.append(schema.result_count(message))
s.wait_quiet(QUIET)
settled.append((time.perf_counter() - started) * 1000.0 - QUIET * 1000.0)
per_try.append(traces(s))
waits.append(config_wait_ms(s))
shape = s.client_shape()
status = schema.worst(statuses)
record(phase="scanwait", row="workspace, %s cache, first useful answer" % cache,
ms=first, first_answer_ms=first, settled_ms=settled,
fresh_process=True, status=status, client=shape,
message=None if status == "ok" else "a definition did not answer ok",
result_count=found[-1], result_counts=found,
config_wait_ms=[w for w in waits if w is not None],
scans=[{"n": t["n"], "kind": t["kind"],
"first_publish": (t.get("counts") or {}).get("first_publish"),
"publishes": (t.get("counts") or {}).get("publishes"),
"total": (t.get("stages") or {}).get("total")}
for t in per_try[0]],
note="ms is the definition sent during the scan; `scans` is the "
"first try's trace, so the answer can be placed inside it")
stage_row("scanwait", "workspace, %s cache, answering" % cache,
"the session that answered the first request", per_try[0], settled)
def scan_chatter(s):
"""How many notifications a *scan* has sent — the busy signal.
`window/logMessage` is excluded: a `--verbose` server logs one per
request, so a loop that counted it would be listening to itself.
"""
s.drain()
return sum(1 for n in s.notifications
if n["method"] in ("$/progress", "textDocument/publishDiagnostics"))
@phase("scanserve")
def phase_scanserve():
"""A definition every 200 ms for as long as the scan runs.
Three questions: what those requests cost while the index is being built,
whether any of them saw a table the finished index disagrees with, and how
many were not yet the settled answer at all.
**Two counters, because they are two contracts.** `mismatched_answers` is
the coherence contract of `docs/features/index-scope/README.md`: a mid-scan
answer may be *empty* — the file it would name has not been reached — but
it may never name somewhere else than the settled index does. That is the
number the 0.51.0 baseline cells were taken with and the one they stay
comparable against. `unsettled_answers` is the review §2 gate (TODO §61.3):
every answer, empty ones included, equal to the settled one. An empty
interim answer is coherent and useless, and the gate is about useful.
"""
for cache in ("cold", "warm"):
during, results, mismatched, settled = [], [], 0, []
unsettled = 0
for _ in range(ARGS.tries):
with session("workspace", cold=(cache == "cold"), verbose=True,
storage_name="p4-serve") as s:
s.initialize()
started = time.perf_counter()
s.did_open(sites.path(sites.TB))
params = at(sites.TB, " aes #(", 1, 2)
seen = []
# As long as the *scan* is still saying things, keep asking.
# The busy test counts `$/progress` and `publishDiagnostics`
# only: under `--verbose` the server logs a line per request,
# so counting every notification would count this loop's own
# noise and never stop.
while True:
before = scan_chatter(s)
elapsed, message = s.request("textDocument/definition", params)
during.append(elapsed)
seen.append(message.get("result"))
time.sleep(0.2)
if scan_chatter(s) == before and (
time.perf_counter() - started) > 1.0:
break
s.wait_quiet(QUIET)
settled.append((time.perf_counter() - started) * 1000.0 - QUIET * 1000.0)
settled_answer = s.request("textDocument/definition", params)[1].get("result")
results.append(len(seen))
mismatched += sum(1 for answer in seen
if answer and answer != settled_answer)
unsettled += sum(1 for answer in seen if answer != settled_answer)
during.sort()
record(phase="scanserve", row="definition every 200 ms during a %s scan" % cache,
ms=during, fresh_process=True, result_count=len(during),
requests_per_session=results, mismatched_answers=mismatched,
unsettled_answers=unsettled, settled_ms=settled,
status="ok" if mismatched == 0 else "error",
message=None if mismatched == 0 else
"%d mid-scan answers disagreed with the settled index" % mismatched,
note="ms is every mid-scan definition, sorted, across all tries; "
"`mismatched_answers` counts non-empty answers that named "
"somewhere the settled index does not — the coherence "
"contract of docs/features/index-scope/README.md; "
"`unsettled_answers` counts every answer that was not the "
"settled one, empty ones included — the review §2 gate")