Files

184 lines
6.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""What every phase shares: the registry, the session factory, the recorder.
`bench.py` owns the command line and the take-3 table's phases; `phases_new.py`
owns the phases for what 0.44–0.49 added. Both import from here, so the run's
configuration lives in exactly one place.
`ARGS` is a `Namespace` that is *mutated* by [`configure`], never rebound, so
`from harness import ARGS` in another module keeps seeing the live values.
Every row [`record`] writes is schema 2 (`schema.py`): units, status, result
count, client shape and fresh-process flag are in the row, not in prose.
Phases call [`samples`], never `Session.ms`, because `ms` throws the response
away and a request that *failed* would be recorded as a fast success.
"""
import argparse
import json
import os
import time
import schema as rowschema
import sites
from lspclient import Session, find_position, summarize, uri # noqa: F401
from schema import ( # noqa: F401 — the phases' record helpers
counts, edit_of, fingerprint, result_count,
)
PHASES = {}
#: The run's configuration. Filled by `configure()`; never reassigned.
ARGS = argparse.Namespace(
server=None, label=None, opentitan=None, storage=None, out=None,
tries=3, probe="",
)
def configure(parsed):
"""Adopt a parsed command line, and point `sites` at the corpus."""
for key, value in vars(parsed).items():
setattr(ARGS, key, value)
ARGS.opentitan = os.path.abspath(ARGS.opentitan)
ARGS.out = os.path.abspath(ARGS.out)
sites.ROOT = ARGS.opentitan
os.makedirs(ARGS.storage, exist_ok=True)
def phase(name):
"""Register a phase under the name `bench.py <name>` runs."""
def register(fn):
PHASES[name] = fn
return fn
return register
def record(**fields):
"""Append one schema-2 row to results.jsonl and echo a readable line.
`units`, `status` and `fresh_process` are stamped when a phase does not
say otherwise; a status outside `schema.STATUSES`, or a failing status
with nothing to say, is a bug in the phase and raises here rather than
reaching a document. `units="ms"` means the `ms` list is latency and
nothing else — memory and size rows pass their own units and their own
fields (`rss_kib`, `store_kib`), never `ms`.
"""
fields.setdefault("ts", time.strftime("%Y-%m-%dT%H:%M:%S"))
fields.setdefault("label", ARGS.label)
fields.setdefault("schema", rowschema.SCHEMA)
fields.setdefault("units", "ms")
fields.setdefault("status", "ok")
fields.setdefault("fresh_process", False)
if fields["status"] not in rowschema.STATUSES:
raise ValueError("status %r is not one of %r" % (fields["status"],
rowschema.STATUSES))
if fields["status"] != "ok" and not fields.get("message"):
raise ValueError("a %r row must carry its message" % fields["status"])
if fields["units"] == "ms" and "ms" not in fields:
raise ValueError("row %r says ms but carries none" % fields.get("row"))
with open(ARGS.out, "a", encoding="utf-8") as handle:
handle.write(json.dumps(fields) + "\n")
ms = fields.get("ms")
shown = " ".join("%.3f" % v for v in ms) if ms else ""
tail = fields.get("note") or ""
if fields["status"] != "ok":
tail = "[%s] %s %s" % (fields["status"], fields.get("message", ""), tail)
print("%-11s %-52s %s %s" % (fields["phase"], fields.get("row", ""), shown,
tail), flush=True)
def session(scope="workspace", cold=False, resolve_support=True, verbose=False,
storage_name=None, apply_edit=False, create_files=False):
"""A session at one scope, its index store under `--storage/<name>`.
Never the default store: the corpus must not be written near, and cache
warmth has to be controllable per cell. `apply_edit` makes the session
capture and decline a pushed `workspace/applyEdit` (the execute phase);
`create_files` lets an extraction answer with a new file.
"""
store = os.path.join(ARGS.storage, storage_name or scope)
return Session(
server=ARGS.server,
root=sites.ROOT,
storage=store,
scope=sites.SCOPES[scope],
resolve_support=resolve_support,
verbose=verbose,
cold=cold,
apply_edit=apply_edit,
create_files=create_files,
)
def settled(s, open_file=sites.TB):
"""Initialize, open a buffer, and wait for the scan to go quiet."""
s.initialize()
s.did_open(sites.path(open_file))
s.wait_quiet(1.5)
s.take_notifications()
return s
class Samples:
"""`n` identical requests: their times, their status, the last answer."""
def __init__(self, ms, statuses, messages):
self.ms = ms
self.statuses = statuses
self.messages = messages
self.status = rowschema.worst([s for s, _ in statuses])
self.message = next((m for s, m in statuses if s != "ok"), None)
self.last = messages[-1] if messages else {}
self.result_count = rowschema.result_count(self.last)
def row(self):
"""The schema-2 fields every request row carries."""
fields = {"ms": self.ms, "status": self.status,
"result_count": self.result_count}
if self.message:
fields["message"] = self.message
return fields
def samples(s, method, params, n=None, extra=0):
"""`n` (+ `extra`) identical requests, keeping every response.
`Session.ms` discards the answer, so a request the server *rejected* was
recorded as a fast success (take 5 §P0). This keeps each response, so the
row can say `status=error` with the server's own message.
"""
n = (n or ARGS.tries) + extra
ms, statuses, messages = [], [], []
for _ in range(n):
elapsed, message = s.request(method, params)
ms.append(elapsed)
statuses.append(rowschema.status_of(message))
messages.append(message)
return Samples(ms, statuses, messages)
def pos(relative, needle, occurrence=1, offset=0):
"""0-based `{line, character}` of a token, resolved from the file text."""
line, character = find_position(sites.path(relative), needle, occurrence, offset)
return {"line": line, "character": character}
def doc(relative):
return {"uri": uri(sites.path(relative))}
def at(relative, needle, occurrence=1, offset=0):
"""A position request's params at a token."""
return {"textDocument": doc(relative), "position": pos(relative, needle, occurrence, offset)}
def code_action_params(relative, needle, occurrence=1, offset=0):
"""A zero-width `textDocument/codeAction` range at a token."""
where = pos(relative, needle, occurrence, offset)
return {
"textDocument": doc(relative),
"range": {"start": where, "end": where},
"context": {"diagnostics": []},
}