okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge commit 'b8d604d28' into f-clean-1ab0fc432ed

main
76.9 KiB1326 linesraw
1"""`strata bench run` for the standard benchmark protocol (docs/BENCHMARK_PROTOCOL.md).
2
3The runner sends the frozen requests of bench/prompts/standard-v1 to a Strata server through streaming chat completions, in the
4protocol's order, and writes a `strata-standard-benchmark` result that other people's results can be compared with:
5
6    warm-up (1, excluded)  ->  performance (short, prompt-4k, prompt-16k, three times)  ->  sanity (I1-I4, R1-R4, T1-T4)
7    ->  optional concurrency (four short requests released together, three rounds)
8
9Speeds are the engine's own timings (the `timings` of the last stream chunk); first-token times are the client's monotonic clock. A value
10that cannot be read stays `None` with a reason in `missing`; nothing is estimated from chunks, characters or words. Prompts, answers and
11timings are saved without home folders, host names, private addresses or keys.
12"""
13
14from __future__ import annotations
15
16import contextlib
17import hashlib
18import http.client
19import json
20import math
21import os
22import re
23import socket
24import statistics
25import subprocess
26import sys
27import threading
28import time
29import urllib.parse
30import uuid
31from concurrent.futures import ThreadPoolExecutor
32from datetime import datetime, timezone
33from pathlib import Path
34
35from strata_cli import bench_facts as facts
36from strata_cli.bench import _private_mkdir, _write_new
37from strata_control.profiles import ProfileError
38
39FORMAT = "strata-standard-benchmark"
40SCHEMA_VERSION = 1
41PROTOCOL_ID = "strata-qwen38-thinking-v1-draft.1"
42PROFILE = "qwen3.8-flash-next-thinking"
43SUITE = "standard-v1"
44#: The model-card revision the profile was defined from. The owner has not pinned one yet, so every result says so.
45MODEL_CARD_REVISION: str | None = None
46MODEL_CARD_URL = "https://huggingface.co/Qwen/Qwen3.8-Flash-Next"
47
48REQUEST_TIMEOUT_S = 1800.0
49#: Prompt tokens the cache may report beyond the longest prefix a request shares with the rest of the bundle before the
50#: user payload counts as reused. The slack covers token merges at the boundary.
51REUSE_SLACK_TOKENS = 8
52LENGTH_TOLERANCE = 0.02
53
54SAMPLING = {"temperature": 1.0, "top_p": 0.95, "top_k": 20, "min_p": 0.0, "presence_penalty": 0.0,
55            "repetition_penalty": 1.0, "reasoning_effort": "xhigh"}
56TEMPLATE_KWARGS = {"enable_thinking": True, "preserve_thinking": True}
57PHASES = ("warmup", "performance", "sanity", "concurrency")
58PLANNED = {"warmup": 1, "performance": 9, "sanity": 12, "concurrency": 12}
59PERFORMANCE_CASES = ("short", "prompt-4k", "prompt-16k")
60METRICS = (("prompt_tps", "tokens/s"), ("decode_tps", "tokens/s"), ("ttft_s", "s"),
61           ("first_answer_s", "s"), ("total_s", "s"))
62HEX64 = re.compile(r"^[0-9a-f]{64}$")
63
64
65class CorpusError(ProfileError):
66    pass
67
68
69def _now() -> str:
70    return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
71
72
73def _number(value) -> float | None:
74    if isinstance(value, bool) or not isinstance(value, (int, float)):
75        return None
76    return float(value) if math.isfinite(value) and value >= 0 else None
77
78
79def _count(value) -> int | None:
80    if isinstance(value, bool) or not isinstance(value, int) or value < 0:
81        if isinstance(value, float) and value.is_integer() and value >= 0 and math.isfinite(value):
82            return int(value)
83        return None
84    return value
85
86
87# ------------------------------------------------------------------------------------------------------------ the fixtures
88class Corpus:
89    def __init__(self, sha256: str, specs: list[dict], build: dict, manifest: bytes, directory: Path):
90        self.sha256, self.specs, self.build, self.manifest, self.directory = sha256, specs, build, manifest, directory
91
92
93def corpus_dir() -> Path:
94    return Path(__file__).resolve().parents[1] / "bench" / "prompts" / SUITE
95
96
97def load_corpus(directory: Path | None = None) -> Corpus:
98    """Read the fixture bundle and check every file against its manifest. Any difference is an error: the run would not be the protocol's."""
99    root = Path(directory) if directory else corpus_dir()
100    try:
101        manifest = (root / "MANIFEST.sha256").read_bytes()
102        lines = manifest.decode("utf-8").splitlines()
103    except (OSError, UnicodeError):
104        raise CorpusError("the standard benchmark fixtures are missing (bench/prompts/standard-v1/MANIFEST.sha256)", 5) from None
105    entries: dict[str, str] = {}
106    for line in lines:
107        digest, _, name = line.partition("  ")
108        if not HEX64.match(digest) or not name or name.startswith(("/", "\\")) or ".." in Path(name).parts:
109            raise CorpusError("the fixture manifest is malformed", 5)
110        entries[name] = digest
111    for name, digest in entries.items():
112        try:
113            data = (root / name).read_bytes()
114        except OSError:
115            raise CorpusError(f"fixture file missing: {name}", 5) from None
116        if hashlib.sha256(data).hexdigest() != digest:
117            raise CorpusError(f"fixture file changed: {name} (line endings converted? bench/prompts is hashed byte for byte)", 5)
118    extra = {p.relative_to(root).as_posix() for p in (root / "requests").glob("*.json")} - set(entries)
119    if extra:
120        raise CorpusError(f"fixture file not in the manifest: {sorted(extra)[0]}", 5)
121    try:
122        build = json.loads((root / "build.json").read_text(encoding="utf-8"))
123        specs = [json.loads((root / "requests" / f"{row['id']}.json").read_text(encoding="utf-8")) for row in build["requests"]]
124    except (OSError, ValueError, KeyError, TypeError):
125        raise CorpusError("the fixture bundle is unreadable", 5) from None
126    counts = {p: sum(1 for s in specs if s.get("phase") == p) for p in PHASES}
127    if counts != PLANNED or len({s["id"] for s in specs}) != len(specs) or build.get("protocol_id") != PROTOCOL_ID:
128        raise CorpusError("the fixture bundle does not match this protocol", 5)
129    return Corpus(hashlib.sha256(manifest).hexdigest(), specs, build, manifest, root)
130
131
132# ------------------------------------------------------------------------------------------------------------ HTTP
133class Target:
134    def __init__(self, root: str, key: str | None):
135        parts = urllib.parse.urlsplit(root)
136        self.scheme, self.host = parts.scheme, parts.hostname or ""
137        self.port = parts.port or (443 if parts.scheme == "https" else 80)
138        self.key = key
139        self.root = root.rstrip("/")
140
141    @property
142    def loopback(self) -> bool:
143        return self.host in facts.LOOPBACK
144
145    def connection(self, timeout: float) -> http.client.HTTPConnection:
146        cls = http.client.HTTPSConnection if self.scheme == "https" else http.client.HTTPConnection
147        return cls(self.host, self.port, timeout=timeout)
148
149    def headers(self, extra: dict | None = None) -> dict:
150        out = {"User-Agent": "Strata-Bench/1", "Accept": "application/json", "Connection": "close", **(extra or {})}
151        if self.key:
152            out["Authorization"] = "Bearer " + self.key
153        return out
154
155    def get(self, path: str, timeout: float = 10) -> dict | None:
156        conn = self.connection(timeout)
157        try:
158            conn.request("GET", path, headers=self.headers())
159            response = conn.getresponse()
160            body = response.read(8 << 20)
161            if response.status != 200:
162                return None
163            value = json.loads(body)
164            return value if isinstance(value, dict) else None
165        except (OSError, http.client.HTTPException, ValueError):
166            return None
167        finally:
168            conn.close()
169
170
171def payload_of(spec: dict, model: str | None) -> dict:
172    """The request body: the protocol's sampling and thinking settings, every one explicit, plus the fixture's messages and tools."""
173    body = {"model": model or "strata", "messages": spec["messages"], "stream": True,
174            "stream_options": {"include_usage": True}, "max_tokens": spec["max_output_tokens"], "seed": spec["seed"],
175            **SAMPLING, "reasoning_budget_tokens": 0, "chat_template_kwargs": dict(TEMPLATE_KWARGS)}
176    if spec.get("tools"):
177        body["tools"] = spec["tools"]
178        body["tool_choice"] = spec.get("tool_choice") or "auto"
179    return body
180
181
182def stream_chat(target: Target, spec: dict, model: str | None, *, timeout_s: float,
183                gate: threading.Event | None = None) -> dict:
184    """Send one streamed request and keep what the client saw, with monotonic offsets from the moment of dispatch."""
185    body = json.dumps(payload_of(spec, model)).encode("utf-8")
186    raw: dict = {"http_status": None, "error": None, "finish_reason": None, "usage": None, "timings": None,
187                 "events": [], "reasoning": [], "content": [], "tool_calls": {}, "done": False,
188                 "timed_out": False, "interrupted": False}
189    if gate is not None:
190        gate.wait()
191    raw["t0"] = start = time.monotonic_ns()
192    conn = target.connection(timeout_s)
193
194    def expire():
195        raw["timed_out"] = True
196        sock = getattr(conn, "sock", None)
197        if sock is not None:
198            try:
199                sock.shutdown(socket.SHUT_RDWR)
200            except OSError:
201                pass
202            try:
203                sock.close()
204            except OSError:
205                pass
206    timer = threading.Timer(timeout_s, expire)
207    timer.daemon = True
208    timer.start()
209
210    def offset() -> float:
211        return round((time.monotonic_ns() - start) / 1e9, 6)
212
213    def mark(kind: str) -> None:
214        raw["events"].append([offset(), kind])
215
216    try:
217        conn.request("POST", "/v1/chat/completions", body,
218                     target.headers({"Content-Type": "application/json", "Accept": "text/event-stream"}))
219        response = conn.getresponse()
220        raw["http_status"] = response.status
221        if response.status != 200:
222            text = response.read(4096).decode("utf-8", "replace")
223            raw["error"] = {"kind": f"http_{response.status}", "message": text.strip()[:300] or f"HTTP {response.status}"}
224        else:
225            while True:
226                line = response.readline(1 << 20)
227                if not line:
228                    break
229                if not line.startswith(b"data:"):
230                    continue
231                data = line[5:].strip()
232                if data == b"[DONE]":
233                    raw["done"] = True
234                    break
235                try:
236                    event = json.loads(data)
237                except ValueError:
238                    raw["error"] = {"kind": "malformed_stream", "message": "a stream event was not JSON"}
239                    break
240                if not isinstance(event, dict):
241                    raw["error"] = {"kind": "malformed_stream", "message": "a stream event was not an object"}
242                    break
243                if "error" in event:
244                    err = event["error"]
245                    kind = (err.get("code") or err.get("type")) if isinstance(err, dict) else None
246                    raw["error"] = {"kind": str(kind or "stream_error")[:60],
247                                    "message": str(err.get("message") if isinstance(err, dict) else err)[:300]}
248                    break
249                if isinstance(event.get("usage"), dict):
250                    raw["usage"] = event["usage"]
251                if isinstance(event.get("timings"), dict):
252                    raw["timings"] = event["timings"]
253                for choice in event.get("choices") or []:
254                    if not isinstance(choice, dict):
255                        continue
256                    delta = choice.get("delta") if isinstance(choice.get("delta"), dict) else {}
257                    reasoning, text = delta.get("reasoning_content"), delta.get("content")
258                    if isinstance(reasoning, str) and reasoning:
259                        raw["reasoning"].append(reasoning)
260                        mark("reasoning")
261                    if isinstance(text, str) and text:
262                        raw["content"].append(text)
263                        mark("answer")
264                    calls = delta.get("tool_calls")
265                    if isinstance(calls, list):
266                        qualifies = False
267                        for call in calls:
268                            if not isinstance(call, dict):
269                                continue
270                            slot = raw["tool_calls"].setdefault(call.get("index", len(raw["tool_calls"])),
271                                                                {"id": "", "name": "", "arguments": ""})
272                            function = call.get("function") if isinstance(call.get("function"), dict) else {}
273                            for field, value in (("id", call.get("id")), ("name", function.get("name")),
274                                                 ("arguments", function.get("arguments"))):
275                                if isinstance(value, str) and value:
276                                    slot[field] += value
277                                    qualifies = True
278                        if qualifies:
279                            mark("tool_call")
280                    if choice.get("finish_reason"):
281                        raw["finish_reason"] = str(choice["finish_reason"])
282            if raw["error"] is None:
283                if not raw["done"]:
284                    raw["error"] = {"kind": "malformed_stream", "message": "the stream ended without [DONE]"}
285                elif raw["finish_reason"] is None:
286                    raw["error"] = {"kind": "malformed_stream", "message": "the stream carried no finish_reason"}
287    except KeyboardInterrupt:
288        raw["interrupted"] = True
289        raw["error"] = {"kind": "cancelled", "message": "cancelled by the operator"}
290    except (OSError, http.client.HTTPException, ValueError) as exc:
291        if raw["timed_out"] or isinstance(exc, TimeoutError):   # the socket's own timeout can fire just before the timer does (Windows)
292            raw["error"] = {"kind": "timeout", "message": f"no complete answer within {timeout_s:g} seconds"}
293        else:
294            raw["error"] = {"kind": "connection_" + type(exc).__name__, "message": str(exc)[:200] or type(exc).__name__}
295    finally:
296        timer.cancel()
297        try:
298            conn.close()
299        except OSError:
300            pass
301    if raw["timed_out"] and raw["error"] is None:
302        raw["error"] = {"kind": "timeout", "message": f"no complete answer within {timeout_s:g} seconds"}
303    raw["t_end"] = time.monotonic_ns()
304    return raw
305
306
307# ------------------------------------------------------------------------------------------------------------ scoring
308def strict_json(text: str):
309    """One complete JSON value: no duplicate keys, no NaN or Infinity, no prose or fence around it."""
310    def pairs(items):
311        out = {}
312        for key, value in items:
313            if key in out:
314                raise ValueError(f"duplicate key {key!r}")
315            out[key] = value
316        return out
317
318    def constant(name):
319        raise ValueError(f"{name} is not JSON")
320    return json.loads(text.strip(" \t\r\n\x0b\x0c"), object_pairs_hook=pairs, parse_constant=constant)
321
322
323def same_json(a, b) -> bool:
324    """Equal values of equal JSON types (true is not 1, 3 is not 3.0); object key order does not matter."""
325    if isinstance(a, bool) or isinstance(b, bool):
326        return isinstance(a, bool) and isinstance(b, bool) and a == b
327    if isinstance(a, dict) and isinstance(b, dict):
328        return a.keys() == b.keys() and all(same_json(a[k], b[k]) for k in a)
329    if isinstance(a, list) and isinstance(b, list):
330        return len(a) == len(b) and all(same_json(x, y) for x, y in zip(a, b))
331    return type(a) is type(b) and a == b
332
333
334def evaluate(spec: dict, status: str, answer: str, calls: list[dict]) -> dict:
335    expected = spec["expected"]
336    category = spec["category"]
337
338    def verdict(passed: bool, reason: str) -> dict:
339        return {"category": category, "passed": passed, "reason": reason}
340    if status != "completed":
341        return verdict(False, {"truncated": "the output cap was reached before the answer was complete",
342                               "failed": "the request failed", "skipped": "the request was skipped"}[status])
343    kind = expected["kind"]
344    if kind == "tool_call":
345        if len(calls) != 1:
346            return verdict(False, f"expected one structured tool call, got {len(calls)}")
347        call = calls[0]
348        if call["name"] != expected["name"]:
349            return verdict(False, f"wrong function {call['name']!r}")
350        try:
351            arguments = strict_json(call["arguments"] or "{}")
352        except ValueError as exc:
353            return verdict(False, f"the tool arguments are not strict JSON ({exc})")
354        if not isinstance(arguments, dict) or not same_json(arguments, expected["arguments"]):
355            return verdict(False, "the tool arguments differ from the expected values")
356        return verdict(True, "the expected tool call")
357    if kind == "text":
358        text = answer.strip(" \t\r\n\x0b\x0c")
359        return verdict(text == expected["value"],
360                       "the exact expected text" if text == expected["value"] else "the answer text differs from the expected text")
361    try:
362        value = strict_json(answer)
363    except ValueError as exc:
364        return verdict(False, f"the answer is not one strict JSON value ({exc})")
365    return verdict(same_json(value, expected["value"]),
366                   "the expected JSON value" if same_json(value, expected["value"]) else "the JSON value differs from the expected value")
367
368
369# ------------------------------------------------------------------------------------------------------------ one request
370def _round(value: float | None) -> float | None:
371    return None if value is None else round(value, 6)
372
373
374def record_of(spec: dict, raw: dict, meta: dict, why: facts.Why | None = None) -> tuple[dict, dict, dict]:
375    """-> (the report's request record, evidence for outputs.jsonl, extras for the report's `extensions`)."""
376    usage = raw["usage"] if isinstance(raw.get("usage"), dict) else {}
377    timings = raw["timings"] if isinstance(raw.get("timings"), dict) else {}
378    details = usage.get("prompt_tokens_details") if isinstance(usage.get("prompt_tokens_details"), dict) else {}
379    error = raw["error"]
380    finish = raw["finish_reason"]
381    if error is not None:
382        status = "failed"
383    elif finish == "length":
384        status = "truncated"
385    elif finish in ("stop", "tool_calls"):
386        status = "completed"
387    else:
388        status = "failed"
389        error = {"kind": "unexpected_finish_reason", "message": f"finish_reason {finish!r}"}
390    t0 = raw["t0"]
391    events = raw["events"]
392    first = events[0] if events else None
393    answer = next((e for e in events if e[1] in ("answer", "tool_call")), None)
394
395    input_tokens, output_tokens = _count(usage.get("prompt_tokens")), _count(usage.get("completion_tokens"))
396    cached, cached_source = _count(details.get("cached_tokens")), "usage.prompt_tokens_details.cached_tokens"
397    if cached is None:
398        cached, cached_source = _count(timings.get("cache_n")), "timings.cache_n"
399    read, read_source = _count(timings.get("prompt_n")), "timings.prompt_n"
400    if read is None and input_tokens is not None and cached is not None and cached <= input_tokens:
401        read, read_source = input_tokens - cached, "derived: usage.prompt_tokens - cached tokens"
402    prompt_s = _number(timings.get("prompt_ms"))
403    prompt_s = prompt_s / 1000 if prompt_s is not None else None
404    decode_s = _number(timings.get("predicted_ms"))
405    decode_s = decode_s / 1000 if decode_s is not None else None
406    rate, predicted_n = _number(timings.get("predicted_per_second")), _count(timings.get("predicted_n"))
407    decode_tokens, decode_source, note = None, None, None
408    if rate is not None and decode_s:
409        implied = round(rate * decode_s)
410        # the engine rounds its rate to 0.1 tokens/s, so the implied count is good to about 0.05 * decode_s tokens
411        if predicted_n is not None and abs(predicted_n - implied) <= 0.05 * decode_s + 1:
412            decode_tokens, decode_source = predicted_n, "timings.predicted_n (agrees with timings.predicted_per_second x predicted_ms)"
413        else:
414            decode_tokens = implied
415            decode_source = "derived: timings.predicted_per_second x timings.predicted_ms / 1000 (the count the engine's rate used)"
416            if predicted_n is not None:
417                note = (f"timings.predicted_n is {predicted_n} but the engine's decode rate and time imply {implied} tokens; "
418                        "the implied count is used because it is the one the rate was computed from")
419    elif predicted_n is not None:
420        decode_tokens, decode_source = predicted_n, "timings.predicted_n (no decode rate to check it against)"
421    if note is None and output_tokens is not None and decode_tokens is not None and output_tokens != decode_tokens:
422        note = (f"API usage.completion_tokens is {output_tokens}; the engine's decode count is {decode_tokens}. The engine count "
423                "feeds decode_tps; the API count feeds the concurrent aggregate")
424    prompt_tps = read / prompt_s if read and prompt_s else None
425    decode_tps = decode_tokens / decode_s if decode_tokens and decode_s else None
426
427    text = "".join(raw["content"])
428    calls = [raw["tool_calls"][k] for k in sorted(raw["tool_calls"], key=lambda k: (not isinstance(k, int), k))]
429    ttft, first_answer = (first[0] if first else None), (answer[0] if answer else None)
430    total = round((raw["t_end"] - t0) / 1e9, 6)
431    kind_names = {"reasoning": "reasoning", "answer": "answer", "tool_call": "tool_call"}
432    record = {
433        "id": spec["id"], "phase": spec["phase"], "case_id": spec["case_id"], "repetition": spec["repetition"],
434        "seed": spec["seed"], "max_output_tokens": spec["max_output_tokens"], "concurrency": spec["concurrency"],
435        "round": spec["round"], "status": status, "finish_reason": finish,
436        "error": None if status in ("completed", "truncated") else error,
437        "tokens": {"input_tokens": input_tokens, "cached_tokens": cached, "read_tokens": read,
438                   "output_tokens": output_tokens, "decode_tokens": decode_tokens},
439        "timings": {"prompt_s": _round(prompt_s), "decode_s": _round(decode_s), "ttft_s": _round(ttft),
440                    "first_answer_s": _round(first_answer), "total_s": total},
441        "metrics": {"prompt_tps": _round(prompt_tps), "decode_tps": _round(decode_tps)},
442        "sources": {"input_tokens": "usage.prompt_tokens of the final stream chunk" if input_tokens is not None else None,
443                    "cached_tokens": cached_source if cached is not None else None,
444                    "read_tokens": read_source if read is not None else None,
445                    "output_tokens": "usage.completion_tokens of the final stream chunk" if output_tokens is not None else None,
446                    "decode_tokens": decode_source,
447                    "engine_timings": ("timings.prompt_ms, timings.predicted_ms, timings.predicted_per_second of the final stream "
448                                       "chunk (raw values in outputs.jsonl)") if timings else None,
449                    "client_timings": ("client monotonic clock from dispatch; event offsets in outputs.jsonl")},
450        "first_delta_kind": kind_names.get(first[1]) if first else None,
451        "token_accounting_note": note, "evaluation": None}
452    if spec["phase"] == "sanity":
453        record["evaluation"] = evaluate(spec, status, text, [c for c in calls if c["name"] or c["arguments"]])
454    reuse_limit = meta["max_shared_prefix_tokens"] + REUSE_SLACK_TOKENS
455    extras = {"max_shared_prefix_tokens": meta["max_shared_prefix_tokens"],
456              "frozen_input_tokens": meta["input_tokens"],
457              "unexpected_payload_reuse": bool(cached is not None and cached > reuse_limit),
458              "length_outside_tolerance": bool(spec.get("target_input_tokens") and input_tokens is not None and
459                                               abs(input_tokens - spec["target_input_tokens"]) >
460                                               LENGTH_TOLERANCE * spec["target_input_tokens"])}
461    evidence = {"request_id": spec["id"], "phase": spec["phase"], "case_id": spec["case_id"],
462                "request": {k: v for k, v in payload_of(spec, None).items() if k not in ("messages", "tools", "model")},
463                "messages": spec["messages"], "tools": spec.get("tools"),
464                "final_answer": text, "reasoning": "".join(raw["reasoning"]),
465                "tool_calls": [{"id": c["id"], "name": c["name"], "arguments": c["arguments"]} for c in calls],
466                "finish_reason": finish, "usage": raw.get("usage"), "timings": raw.get("timings"), "error": error,
467                "http_status": raw["http_status"], "dispatch_offset_s": 0.0, "end_offset_s": total,
468                "first_delta": {"offset_s": first[0], "kind": first[1]} if first else None,
469                "first_answer_offset_s": first_answer, "client_events": events}
470    return record, evidence, extras
471
472
473def skipped_record(spec: dict, reason: str) -> tuple[dict, dict, dict]:
474    record = {"id": spec["id"], "phase": spec["phase"], "case_id": spec["case_id"], "repetition": spec["repetition"],
475              "seed": spec["seed"], "max_output_tokens": spec["max_output_tokens"], "concurrency": spec["concurrency"],
476              "round": spec["round"], "status": "skipped", "finish_reason": None,
477              "error": {"kind": "skipped", "message": reason},
478              "tokens": {k: None for k in ("input_tokens", "cached_tokens", "read_tokens", "output_tokens", "decode_tokens")},
479              "timings": {k: None for k in ("prompt_s", "decode_s", "ttft_s", "first_answer_s", "total_s")},
480              "metrics": {"prompt_tps": None, "decode_tps": None},
481              "sources": {k: None for k in ("input_tokens", "cached_tokens", "read_tokens", "output_tokens", "decode_tokens",
482                                            "engine_timings", "client_timings")},
483              "first_delta_kind": None, "token_accounting_note": None, "evaluation": None}
484    if spec["phase"] == "sanity":
485        record["evaluation"] = {"category": spec["category"], "passed": False, "reason": "the request was skipped: " + reason}
486    return record, {"request_id": spec["id"], "skipped": reason}, {"unexpected_payload_reuse": False,
487                                                                     "length_outside_tolerance": False}
488
489
490# ------------------------------------------------------------------------------------------------------------ the run
491class Collector:
492    """Runs the scheduled requests in order and keeps their records."""
493
494    def __init__(self, target: Target, corpus: Corpus, model: str | None, log, timeout_s: float):
495        self.target, self.corpus, self.model, self.log, self.timeout_s = target, corpus, model, log, timeout_s
496        self.meta = {row["id"]: row for row in corpus.build["requests"]}
497        self.results: dict[str, tuple[dict, dict, dict]] = {}
498        self.abort: str | None = None
499        self.number = 0
500        self.total = sum(PLANNED[p] for p in ("warmup", "performance", "sanity"))
501
502    def finish(self, spec: dict, raw: dict) -> dict:
503        result = record_of(spec, raw, self.meta[spec["id"]])
504        self.results[spec["id"]] = result
505        return result[0]
506
507    def alive(self) -> bool:
508        health = self.target.get("/health", timeout=5)
509        return bool(health and health.get("service") == "strata")
510
511    def one(self, spec: dict) -> None:
512        if self.abort:
513            self.results[spec["id"]] = skipped_record(spec, self.abort)
514            return
515        self.number += 1
516        self.log(f"[{self.number}/{self.total}] {spec['id']} (up to {spec['max_output_tokens']} tokens)")
517        raw = stream_chat(self.target, spec, self.model, timeout_s=self.timeout_s)
518        record = self.finish(spec, raw)
519        timing = record["timings"]
520        speed = record["metrics"]
521        self.log(f"    {record['status']}: prompt {speed['prompt_tps'] or 'n/a'} tok/s, decode {speed['decode_tps'] or 'n/a'} tok/s, "
522                 f"first token {timing['ttft_s'] if timing['ttft_s'] is not None else 'n/a'} s"
523                 + (f"; {record['error']['kind']}" if record["error"] else ""))
524        if raw["interrupted"]:
525            self.abort = "the operator cancelled the run"
526        elif record["status"] == "failed":
527            if spec["phase"] == "warmup":
528                self.abort = f"the warm-up request failed ({record['error']['kind']}); the measured stages were not run"
529            elif not self.alive():
530                self.abort = f"the server stopped answering after {spec['id']} ({record['error']['kind']})"
531
532    def concurrent_round(self, specs: list[dict]) -> dict:
533        gate = threading.Event()
534        raws: dict[str, dict] = {}
535
536        def work(spec):
537            raws[spec["id"]] = stream_chat(self.target, spec, self.model, timeout_s=self.timeout_s, gate=gate)
538        with ThreadPoolExecutor(max_workers=len(specs)) as pool:
539            futures = [pool.submit(work, spec) for spec in specs]
540            time.sleep(0.05)
541            gate.set()
542            for future in futures:
543                future.result()
544        records = [self.finish(spec, raws[spec["id"]]) for spec in specs]
545        start = min(raws[s["id"]]["t0"] for s in specs)
546        end = max(raws[s["id"]]["t_end"] for s in specs)
547        wall = round((end - start) / 1e9, 6)
548        counted = [r for r in records if r["status"] in ("completed", "truncated")]
549        outputs = [r["tokens"]["output_tokens"] for r in counted]
550        total = sum(outputs) if outputs and all(o is not None for o in outputs) else None
551        failed = sum(r["status"] == "failed" for r in records)
552        self.log(f"    round {specs[0]['round']}: {len(counted)} completed or capped, {failed} failed, {wall} s")
553        if any(raws[s["id"]]["interrupted"] for s in specs):
554            self.abort = "the operator cancelled the run"
555        return {"round": specs[0]["round"], "request_ids": [s["id"] for s in specs], "wall_s": wall,
556                "output_tokens": total, "aggregate_tps": _round(total / wall) if total is not None and wall > 0 else None,
557                "failed": failed}
558
559
560def summaries_of(records: list[dict], extras: dict, phase: str, cases: tuple[str, ...], concurrency: int) -> list[dict]:
561    rows = []
562    for case in cases:
563        group = [r for r in records if r["phase"] == phase and r["case_id"] == case]
564        for metric, unit in METRICS:
565            included, excluded, values = [], [], []
566            for r in group:
567                reason = None
568                if r["status"] == "skipped":
569                    reason = "skipped: " + r["error"]["message"]
570                elif r["status"] == "failed":
571                    reason = "failed: " + r["error"]["kind"]
572                elif extras[r["id"]]["unexpected_payload_reuse"]:
573                    reason = (f"unexpected cache reuse: {r['tokens']['cached_tokens']} cached tokens exceed the "
574                              f"{extras[r['id']]['max_shared_prefix_tokens']}-token shared template prefix")
575                else:
576                    value = r["metrics"].get(metric) if metric in ("prompt_tps", "decode_tps") else r["timings"].get(metric)
577                    if value is None:
578                        reason = f"{metric} is not available for this request"
579                    else:
580                        values.append(value)
581                        included.append(r["id"])
582                if reason:
583                    excluded.append({"request_id": r["id"], "reason": reason})
584            rows.append({"phase": phase, "case_id": case, "concurrency": concurrency, "metric": metric, "unit": unit,
585                         "median": _round(statistics.median(values)) if values else None,
586                         "min": _round(min(values)) if values else None, "max": _round(max(values)) if values else None,
587                         "n": len(values), "included_request_ids": included, "excluded": excluded})
588    return rows
589
590
591def counts_of(records: list[dict], phase: str, planned: int) -> dict:
592    rows = [r for r in records if r["phase"] == phase]
593    tally = {s: sum(r["status"] == s for r in rows) for s in ("completed", "truncated", "failed", "skipped")}
594    attempted = tally["completed"] + tally["truncated"] + tally["failed"]
595    return {"planned": planned, "attempted": attempted, **tally}
596
597
598def quality_of(records: list[dict]) -> dict:
599    sanity = [r for r in records if r["phase"] == "sanity"]
600    cats = {name: {"passed": sum(r["evaluation"]["passed"] for r in sanity if r["evaluation"]["category"] == name),
601                   "total": 4} for name in ("instruction", "retrieval", "tool_call")}
602    return {"passed": sum(c["passed"] for c in cats.values()), "total": 12, "categories": cats}
603
604
605def scan_nulls(value, path: str = ""):
606    if value is None:
607        yield path
608    elif isinstance(value, dict):
609        for key, item in value.items():
610            if path == "" and key in ("missing", "extensions"):
611                continue
612            yield from scan_nulls(item, path + facts.pointer(key))
613    elif isinstance(value, list):
614        for index, item in enumerate(value):
615            yield from scan_nulls(item, path + facts.pointer(index))
616
617
618def default_reason(doc: dict, pointer: str) -> str:
619    parts = [p.replace("~1", "/").replace("~0", "~") for p in pointer.split("/")[1:]]
620    if parts[0] == "requests" and len(parts) >= 3:
621        record = doc["requests"][int(parts[1])]
622        field = ".".join(parts[2:])
623        if record["status"] == "skipped":
624            return "not measured: the request was skipped (" + record["error"]["message"] + ")"
625        if field == "error":
626            return "none: the request ended normally"
627        if field == "round":
628            return "not applicable outside the concurrency stage"
629        if field == "evaluation":
630            return "not applicable outside the sanity stage"
631        if field == "token_accounting_note":
632            return "none: the API and engine counts agree or only one exists"
633        if field == "finish_reason":
634            return "the server sent no finish_reason"
635        if field == "first_delta_kind":
636            return "no nonempty reasoning, answer or tool-call delta arrived"
637        if field in ("timings.ttft_s", "timings.first_answer_s"):
638            return ("no nonempty delta arrived" if field == "timings.ttft_s"
639                    else "no answer text or tool call arrived (reasoning alone does not count)")
640        if field.startswith("metrics."):
641            return ("the rate needs a nonzero freshly read count (or generated count) and an engine duration, and one is missing or zero")
642        if field.startswith("sources."):
643            return "no source: the value was not reported"
644        if record["status"] == "failed":
645            return f"the request failed ({record['error']['kind']}) before this value was reported"
646        return "the server's response did not include this value (usage or timings)"
647    if parts[0] == "summaries" and len(parts) >= 3:
648        row = doc["summaries"][int(parts[1])]
649        return f"no valid samples of {row['metric']} for {row['case_id']} ({len(row['excluded'])} excluded)"
650    if parts[0] == "concurrency_rounds":
651        return "an included request has no output token count, or the round wall time is zero"
652    if parts[0] == "run" and parts[1] == "optional_duration_s":
653        return "the optional concurrency stage was not selected or did not run"
654    if parts[0] == "protocol" and parts[1] == "model_card_revision":
655        return "the profile's model-card revision is not pinned yet (protocol draft)"
656    return "not available"
657
658
659def _start_wait(target: Target, proc, timeout_s: float, log, log_path: Path | None) -> bool:
660    began, announced = time.monotonic(), 0.0
661    while time.monotonic() - began < timeout_s:
662        if proc is not None and proc.poll() is not None:
663            return False
664        health = target.get("/health", timeout=5)
665        if health and health.get("service") == "strata" and health.get("loaded"):
666            return True
667        if time.monotonic() - announced > 30:
668            log(f"waiting for the model to load ({int(time.monotonic() - began)} s) ...")
669            announced = time.monotonic()
670        time.sleep(2)
671    return False
672
673
674def start_engine(ref: str, target: Target, log_path: Path, log, timeout_s: float):
675    """Start `strata serve --profile REF` as a child of this run. -> the process."""
676    root = Path(__file__).resolve().parents[1]
677    command = [sys.executable, str(root / "strata.py"), "serve", "--profile", ref, "--quiet"]
678    handle = open(log_path, "wb")
679    kwargs = {}
680    if os.name == "nt":
681        kwargs["creationflags"] = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
682    else:
683        kwargs["start_new_session"] = True
684    proc = subprocess.Popen(command, cwd=str(root), stdout=handle, stderr=subprocess.STDOUT, **kwargs)
685    proc._strata_log = handle                              # closed by stop_engine
686    if os.name == "nt":
687        # Windows has no process group to signal: the engine tree is put in a job object this run owns, which ends every process in it in one call
688        # and cannot be refused for a single member (a per-process taskkill was "Access is denied" on a tree this very user started, #4260)
689        from serve import winjob
690        proc._strata_job = winjob.contain(proc)
691    log("starting the engine (the model load is not part of the benchmark time) ...")
692    try:
693        ready = _start_wait(target, proc, timeout_s, log, log_path)
694    except BaseException:                                  # Ctrl+C (or a SIGTERM turned into one) while the model loads: the caller never gets `proc`, so end it here
695        stop_engine(proc)
696        raise
697    if not ready:
698        stuck = stop_engine(proc)
699        tail = ""
700        try:
701            tail = log_path.read_text(encoding="utf-8", errors="replace")[-600:]
702        except OSError:
703            pass
704        raise ProfileError("the engine did not become ready" + (": " + tail.strip().splitlines()[-1] if tail.strip() else "") +
705                           ("; and it could not be stopped (" + stuck + "): it may still hold the port" if stuck else ""), 6)
706    return proc
707
708
709def engine_log_since(console_log: Path, run_log: Path | None, offset: int) -> Path:
710    """The log to keep with a result when the runner started the engine. `strata serve --quiet` prints nothing, so the
711    console capture is empty; the engine's own lines are in the run config's `log` file, from `offset` (its size before
712    the start). Falls back to the console capture when there is no such file or nothing new in it."""
713    try:
714        if run_log is not None and run_log.is_file() and run_log.stat().st_size > offset:
715            with run_log.open("rb") as stream:
716                stream.seek(offset)
717                data = stream.read()
718            if data.strip():
719                merged = console_log.with_name("engine-run.log")
720                merged.write_bytes(data)
721                return merged
722    except OSError:
723        pass
724    return console_log
725
726
727@contextlib.contextmanager
728def term_is_interrupt():
729    """While a run owns an engine it started, SIGTERM (and Ctrl+Break on Windows) end the run the way Ctrl+C does: the `finally` that stops the engine
730    runs. Without this a plain `kill` (a service stop, a script's timeout, the app's Stop) ended only the runner and left the server and the engine
731    holding the port and the GPU. Main thread only; the earlier handlers come back afterwards."""
732    import signal
733    if threading.current_thread() is not threading.main_thread():
734        yield
735        return
736
737    def handler(signum, frame):
738        raise KeyboardInterrupt
739
740    saved = []
741    for name in ("SIGTERM", "SIGBREAK"):
742        number = getattr(signal, name, None)
743        if number is None:
744            continue
745        try:
746            saved.append((number, signal.signal(number, handler)))
747        except (ValueError, OSError):
748            pass
749    try:
750        yield
751    finally:
752        for number, old in saved:
753            try:
754                signal.signal(number, old)
755            except (ValueError, OSError, TypeError):
756                pass
757
758
759def stop_engine(proc) -> str | None:
760    """Stop only the process this run started. -> None when it is gone, else a plain sentence on why it may still be running
761    (a failed taskkill / signal, or a process that outlives the wait): the caller must not report a normal finish then, because
762    a process that is still alive can hold the server's port and the GPU (#3438)."""
763    if proc is None:
764        return None
765    problem = None
766    try:
767        if proc.poll() is None:
768            if os.name == "nt":
769                # 1. the job this run put the engine in (ends the whole tree at once); 2. taskkill of the tree; 3. the process itself.
770                # The next step runs only when the one before left the process running, and a refusal is reported only if all of them fail.
771                if getattr(proc, "_strata_job", False):
772                    from serve import winjob
773                    winjob.terminate()
774                    try:
775                        proc.wait(10)
776                    except subprocess.TimeoutExpired:
777                        pass
778                if proc.poll() is None:
779                    try:
780                        done = subprocess.run(["taskkill", "/PID", str(proc.pid), "/T", "/F"], capture_output=True, timeout=60)
781                        if done.returncode != 0 and proc.poll() is None:
782                            said = (done.stderr or done.stdout or b"").decode("utf-8", errors="replace").strip()
783                            problem = f"taskkill for process {proc.pid} failed (exit {done.returncode}){': ' + said[:200] if said else ''}"
784                    except subprocess.TimeoutExpired:
785                        problem = f"taskkill for process {proc.pid} did not finish in 60 s"
786                    except OSError as error:
787                        problem = f"taskkill could not run for process {proc.pid}: {error}"
788                if proc.poll() is None:
789                    try:
790                        proc.kill()                          # this run's own child, by the handle it holds
791                    except OSError:
792                        pass
793            else:
794                import signal
795                try:
796                    os.killpg(proc.pid, signal.SIGTERM)
797                except OSError:
798                    proc.terminate()
799                try:
800                    proc.wait(90)
801                except subprocess.TimeoutExpired:
802                    try:
803                        os.killpg(proc.pid, signal.SIGKILL)
804                    except OSError:
805                        proc.kill()
806            try:
807                proc.wait(30)
808            except subprocess.TimeoutExpired:
809                pass
810            if proc.poll() is None:
811                problem = (problem + "; " if problem else "") + f"process {proc.pid} is still running 30 s after it was told to stop"
812            else:
813                problem = None                               # it is gone: an earlier refusal that a later step got around is not news
814    finally:
815        handle = getattr(proc, "_strata_log", None)
816        if handle is not None:
817            handle.close()
818    return problem
819
820
821def slug(text: str, limit: int = 40) -> str:
822    cleaned = re.sub(r"(?i)\b(nvidia|geforce|amd|radeon|intel|graphics|corporation)\b", " ", text or "")
823    return re.sub(r"[^a-z0-9]+", "-", cleaned.lower()).strip("-")[:limit].strip("-") or "unknown"
824
825
826def run(target: Target, out: Path | None, *, out_root: Path | None = None, optional_concurrency: bool = False,
827        corpus: Corpus | None = None, declared: dict | None = None, plan: dict | None = None,
828        engine_log: Path | None = None, engine_run_log: tuple[Path | None, int] | None = None, command: str = "strata bench run --suite standard-v1",
829        log=lambda message: None, timeout_s: float = REQUEST_TIMEOUT_S, started_engine: bool = False,
830        hash_model: bool = True) -> tuple[dict, Path]:
831    """Run the protocol against `target` and write the report into the new directory `out` (or a new folder named
832    <date>-standard-<gpu>-<run id> under `out_root`). -> (the result, the folder)."""
833    declared = {"track": "custom", "track_notes": "no notes given by the operator", **(declared or {})}
834    if declared["track"] not in ("default", "custom"):
835        raise ProfileError("--track must be default or custom", 2)
836    corpus = corpus or load_corpus()
837    if out is not None and (out.exists() or out.is_symlink()):
838        raise ProfileError("benchmark output directory already exists", 2)
839    if out is None and out_root is None:
840        raise ProfileError("benchmark needs an output directory", 2)
841    health = target.get("/health", timeout=10)
842    if not health or health.get("service") != "strata":
843        raise ProfileError("no Strata server answers at that address", 5)
844    if health.get("loaded") is not True:
845        raise ProfileError("the server has no model loaded; the benchmark needs a loaded model", 5)
846    props = target.get("/props", timeout=15)
847    status = target.get("/v1/status", timeout=15) or {}
848    if props is None:
849        raise ProfileError("the server did not answer /props (an API key may be needed: STRATA_API_KEY)", 5)
850    redact = facts.redactor(target.key or "")
851    why = facts.Why()
852    reasons_nonconforming: list[str] = []
853    if not target.loopback:
854        reasons_nonconforming.append("the server is not on loopback: standard latency is measured over loopback")
855
856    served_model = props.get("model_alias") or status.get("model")
857    prior = ((status.get("activity") or {}).get("requests"))
858    # the server's own view of its hardware and build
859    machine = target.get("/metrics", timeout=20) or {}
860    static = machine.get("hardware_static") or {}
861    served_gpu = ((status.get("machine") or {}).get("gpu") or {}).get("name") or static.get("gpu_name")
862    engine_version = ((machine.get("engine") or {}).get("version") or status.get("engine")
863                      or (str(props.get("build_info", "")).replace("Strata ", "") or None))
864
865    plan = plan or {}
866    options = facts.parse_options(plan["engine_argv"]) if plan.get("engine_argv") else None
867    model_paths = [str(props.get("model_path") or "")] + [str(v) for v in (plan.get("engine_argv") or [])]
868    files = facts.model_files_from([p for p in model_paths if p]) if hash_model else []
869    model_dir = files[0].parent if files else None
870    selected = facts.gpu_selection(plan.get("config"), plan.get("engine_argv"))
871    template_text = props.get("chat_template") if isinstance(props.get("chat_template"), str) else None
872
873    hardware_block, machine_facts = facts.hardware(why, selected=selected, served_gpu=served_gpu, model_dir=model_dir,
874                                                   declared_background=list(declared.get("background") or []))
875    software_block = facts.software(why, machine_facts, engine_version=engine_version,
876                                    build_options=declared.get("build_options"),
877                                    engine_build=facts.engine_build_runtime(plan.get("engine_exe")))
878    model_block = facts.model(why, props=props, status=status, files=files, declared=declared, log=log)
879    template_ref = {"path": "provenance/chat_template.jinja", "sha256": facts.sha256_text(template_text)} if template_text else None
880    configuration_block, other_options = facts.configuration(
881        why, options=options, env=(plan.get("config") or {}).get("env") if isinstance(plan.get("config"), dict) else None,
882        props=props, declared=declared,
883        sampling={"sampling": SAMPLING, "chat_template_kwargs": TEMPLATE_KWARGS}, template_ref=template_ref)
884
885    if software_block["strata_commit"] is None:
886        reasons_nonconforming.append("the Strata commit is unknown (not a git checkout and no COMMIT file)")
887    if not model_block["files"]:
888        reasons_nonconforming.append("no model file could be hashed")
889    if template_ref is None:
890        reasons_nonconforming.append("the effective chat template could not be read from the server")
891    if props.get("is_sleeping"):
892        reasons_nonconforming.append("the server reported its model as sleeping")
893
894    run_id = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + "-" + uuid.uuid4().hex[:8]
895    if out is None:
896        names = "-plus-".join(slug(g["name"], 30) for g in hardware_block["gpus"]) or "cpu"
897        out = out_root / (datetime.now(timezone.utc).strftime("%Y-%m-%d") + "-standard-" + names[:60].strip("-") + "-" + run_id[-8:])
898        out_root.mkdir(parents=True, exist_ok=True)
899    _private_mkdir(out, parents=False, exist_ok=False)
900    started_at = _now()
901    collector = Collector(target, corpus, served_model, log, timeout_s)
902    by_phase = {p: [s for s in corpus.specs if s["phase"] == p] for p in PHASES}
903    required_start = time.monotonic()
904    interrupted = False
905    try:
906        for phase in ("warmup", "performance", "sanity"):
907            for spec in by_phase[phase]:
908                collector.one(spec)
909        required_duration = round(time.monotonic() - required_start, 3)
910        optional_duration = None
911        rounds: list[dict] = []
912        if optional_concurrency:
913            optional_start = time.monotonic()
914            specs = by_phase["concurrency"]
915            for round_no in (1, 2, 3):
916                group = [s for s in specs if s["round"] == round_no]
917                if collector.abort:
918                    for spec in group:
919                        collector.results[spec["id"]] = skipped_record(spec, collector.abort)
920                    rounds.append({"round": round_no, "request_ids": [s["id"] for s in group], "wall_s": None,
921                                   "output_tokens": None, "aggregate_tps": None, "failed": 0})
922                    continue
923                log(f"concurrency round {round_no}/3: four requests released together")
924                rounds.append(collector.concurrent_round(group))
925                if not collector.abort and any(collector.results[s["id"]][0]["status"] == "failed" for s in group) \
926                        and not collector.alive():
927                    collector.abort = "the server stopped answering during the concurrency stage"
928            optional_duration = round(time.monotonic() - optional_start, 3)
929    except KeyboardInterrupt:
930        interrupted = True
931        required_duration = round(time.monotonic() - required_start, 3)
932        optional_duration, rounds = None, []
933        collector.abort = "the operator cancelled the run"
934        for spec in corpus.specs:
935            if spec["id"] not in collector.results and (spec["phase"] != "concurrency" or optional_concurrency):
936                collector.results[spec["id"]] = skipped_record(spec, collector.abort)
937    for spec in corpus.specs:                              # a stage that never started is skipped, not missing
938        if spec["id"] not in collector.results and (spec["phase"] != "concurrency" or optional_concurrency):
939            collector.results[spec["id"]] = skipped_record(spec, collector.abort or "not run")
940
941    selected_specs = [s for s in corpus.specs if s["id"] in collector.results]
942    records = [collector.results[s["id"]][0] for s in selected_specs]
943    evidence = [collector.results[s["id"]][1] for s in selected_specs]
944    extras = {s["id"]: collector.results[s["id"]][2] for s in selected_specs}
945
946    for r in records:
947        if r["phase"] == "performance" and extras[r["id"]]["unexpected_payload_reuse"]:
948            reasons_nonconforming.append(f"unexpected reuse of the user payload in {r['id']}")
949        if extras[r["id"]]["length_outside_tolerance"]:
950            reasons_nonconforming.append(f"{r['id']} measured {r['tokens']['input_tokens']} prompt tokens, outside 2% of its target")
951        if r["status"] == "failed" and r["error"]["kind"] in ("http_400", "http_422"):
952            reasons_nonconforming.append(f"the server refused the protocol's required settings in {r['id']} ({r['error']['kind']})")
953    skipped_required = any(r["status"] == "skipped" for r in records if r["phase"] != "concurrency")
954    skipped_optional = any(r["status"] == "skipped" for r in records if r["phase"] == "concurrency")
955    run_status = ("nonconforming" if reasons_nonconforming else
956                  "partial" if skipped_required or interrupted else "complete")
957    reasons_nonconforming = list(dict.fromkeys(reasons_nonconforming))
958
959    # the artifacts first, so the report can hash their final bytes
960    artifacts: list[dict] = []
961
962    def put(kind: str, relative: str, data: bytes) -> None:
963        path = out / relative
964        path.parent.mkdir(parents=True, exist_ok=True)
965        _write_new(path, data)
966        artifacts.append({"kind": kind, "path": relative, "sha256": hashlib.sha256(data).hexdigest()})
967    lines = [json.dumps(facts.redact_object(row, redact), ensure_ascii=False, allow_nan=False) for row in evidence]
968    put("outputs", "outputs.jsonl", ("\n".join(lines) + "\n").encode("utf-8"))
969    config_doc = facts.redact_object({"engine_options": options, "other_engine_options": other_options,
970                                      "server_defaults": (props.get("default_generation_settings") or {}).get("params"),
971                                      "total_slots": props.get("total_slots"), "context": configuration_block["context_tokens"],
972                                      "source": "effective engine arguments of the profile" if options is not None
973                                      else "the server was already running; its engine options are not exposed"}, redact)
974    put("config", "config.json", (json.dumps(config_doc, ensure_ascii=False, indent=2, allow_nan=False) + "\n").encode("utf-8"))
975    if engine_log is not None and engine_run_log is not None:
976        engine_log = engine_log_since(engine_log, *engine_run_log)
977    if engine_log is not None and engine_log.is_file():
978        text = engine_log.read_text(encoding="utf-8", errors="replace")[-2_000_000:]
979        put("engine_log", "engine.log", redact(text).encode("utf-8"))
980    if template_text:
981        put("provenance", "provenance/chat_template.jinja", template_text.encode("utf-8"))
982    put("provenance", "provenance/corpus-manifest.sha256", corpus.manifest)
983    put("provenance", "provenance/corpus-build.json", (corpus.directory / "build.json").read_bytes())
984
985    summaries = summaries_of(records, extras, "performance", PERFORMANCE_CASES, 1)
986    if optional_concurrency:
987        summaries += summaries_of(records, extras, "concurrency", ("short-burst",), 4)
988    doc = {
989        "format": FORMAT, "schema_version": SCHEMA_VERSION,
990        "protocol": {"id": PROTOCOL_ID, "git_commit": software_block["runner_commit"], "profile": PROFILE,
991                     "corpus_sha256": corpus.sha256, "model_card_revision": MODEL_CARD_REVISION},
992        "run": {"id": run_id, "started_at": started_at, "status": run_status, "required_duration_s": required_duration,
993                "optional_duration_s": optional_duration, "optional_concurrency": bool(optional_concurrency),
994                "command": command},
995        "hardware": hardware_block, "software": software_block, "model": model_block,
996        "configuration": configuration_block,
997        "request_counts": {p: counts_of(records, p, PLANNED[p] if p != "concurrency" or optional_concurrency else 0)
998                           for p in PHASES},
999        "requests": records, "summaries": summaries, "concurrency_rounds": rounds if optional_concurrency else [],
1000        "quality": quality_of(records), "artifacts": artifacts, "missing": {},
1001        "extensions": {"suite": SUITE, "runner": "strata_cli.bench_standard",
1002                       "status_reasons": reasons_nonconforming or (
1003                           [collector.abort] if collector.abort else []),
1004                       "started_engine": started_engine,
1005                       "server_requests_before_run": prior if isinstance(prior, int) else None,
1006                       "other_engine_options": other_options,
1007                       "request_checks": {rid: v for rid, v in extras.items()},
1008                       "optional_stage_skipped": skipped_optional,
1009                       "api_key_sent": bool(target.key)}}
1010    doc = facts.redact_document(doc, redact)      # results.json gets what the README and the other files get (#4484)
1011    if doc["run"]["optional_duration_s"] is None:
1012        why.add("/run/optional_duration_s", "the optional concurrency stage was not selected" if not optional_concurrency
1013                else "the optional concurrency stage did not run")
1014    for pointer_text in scan_nulls(doc):
1015        doc["missing"][pointer_text] = why.get(pointer_text) or default_reason(doc, pointer_text)
1016    problems = validate(doc)
1017    if problems:
1018        raise ProfileError("the benchmark report failed its own validation: " + problems[0], 6)
1019    encoded = (json.dumps(doc, ensure_ascii=False, indent=2, allow_nan=False) + "\n").encode("utf-8")
1020    _write_new(out / "results.json", encoded)
1021    _write_new(out / "README.md", report_markdown(doc, redact).encode("utf-8"))
1022    return doc, out
1023
1024
1025# ------------------------------------------------------------------------------------------------------------ validation
1026def validate(doc: dict) -> list[str]:
1027    """A strict check of the result contract: shape, types, count identities, null reasons and summaries rebuilt from the requests."""
1028    bad: list[str] = []
1029
1030    def need(condition: bool, message: str) -> None:
1031        if not condition:
1032            bad.append(message)
1033
1034    if not isinstance(doc, dict):
1035        return ["the result is not an object"]
1036    need(doc.get("format") == FORMAT and doc.get("schema_version") == SCHEMA_VERSION, "unknown format or schema version")
1037    required = ("protocol", "run", "hardware", "software", "model", "configuration", "request_counts", "requests", "summaries",
1038                "concurrency_rounds", "quality", "artifacts", "missing")
1039    for key in required:
1040        need(key in doc, f"missing top-level field {key}")
1041    if bad:
1042        return bad
1043    allowed = {"format", "schema_version", *required, "extensions"}
1044    need(set(doc) <= allowed, "unknown top-level fields must be under extensions")
1045    protocol, run_block = doc["protocol"], doc["run"]
1046    need(all(k in protocol for k in ("id", "git_commit", "profile", "corpus_sha256", "model_card_revision")), "protocol fields")
1047    need(isinstance(protocol.get("corpus_sha256"), str) and bool(HEX64.match(protocol["corpus_sha256"])), "corpus_sha256 is not a SHA-256")
1048    for field in ("id", "started_at", "status", "required_duration_s", "optional_duration_s", "optional_concurrency", "command"):
1049        need(field in run_block, f"run.{field} missing")
1050    need(run_block.get("status") in ("complete", "partial", "nonconforming"), "run.status")
1051    need(bool(re.fullmatch(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ", str(run_block.get("started_at")))), "run.started_at is not UTC ISO 8601")
1052    for field in ("gpus", "cpu", "ram_bytes", "storage", "background_workloads"):
1053        need(field in doc["hardware"], f"hardware.{field} missing")
1054    for gpu in doc["hardware"].get("gpus") or []:
1055        need(gpu.get("memory_kind") in ("dedicated", "shared"), "gpu memory_kind")
1056        need(isinstance(gpu.get("device_index"), int), "gpu device_index")
1057    for field in ("os", "drivers", "runtime", "strata_commit", "engine_version", "build_kind", "runner_commit", "build_options"):
1058        need(field in doc["software"], f"software.{field} missing")
1059    need(doc["software"].get("build_kind") in ("release", "source"), "software.build_kind")
1060    for field in ("id", "revision", "source_revision", "quantization", "files", "tokenizer_revision", "custom_pack"):
1061        need(field in doc["model"], f"model.{field} missing")
1062    for entry in doc["model"].get("files") or []:
1063        need(bool(HEX64.match(str(entry.get("sha256")))) and "/" not in str(entry.get("path")) and "\\" not in str(entry.get("path")),
1064             "model file entry")
1065    cfg = doc["configuration"]
1066    for field in ("track", "track_notes", "context_tokens", "server_capacity", "kv_cache", "expert_cache", "offloading", "prefill",
1067                  "mtp", "calibration", "experimental_options", "template", "sampling", "chat_template_kwargs"):
1068        need(field in cfg, f"configuration.{field} missing")
1069    need(cfg.get("track") in ("default", "custom"), "configuration.track")
1070    need(all(k in cfg.get("sampling", {}) for k in SAMPLING), "configuration.sampling")
1071
1072    records = doc["requests"]
1073    ids = [r.get("id") for r in records]
1074    need(len(set(ids)) == len(ids), "duplicate request ids")
1075    need(len(records) in (22, 34), "the requests array has neither 22 nor 34 records")
1076    sanity_ids = {f"sanity-{n}" for n in ("I1", "I2", "I3", "I4", "R1", "R2", "R3", "R4", "T1", "T2", "T3", "T4")}
1077    need(sanity_ids <= set(ids), "a sanity case is missing")
1078    for r in records:
1079        need(r.get("status") in ("completed", "truncated", "failed", "skipped"), f"{r.get('id')}: status")
1080        need(r.get("phase") in PHASES, f"{r.get('id')}: phase")
1081        if r.get("status") in ("completed", "truncated"):
1082            need(r.get("error") is None, f"{r.get('id')}: error on a finished request")
1083        else:
1084            need(isinstance(r.get("error"), dict) and "kind" in r["error"] and "message" in r["error"], f"{r.get('id')}: error object")
1085        for group, keys in (("tokens", ("input_tokens", "cached_tokens", "read_tokens", "output_tokens", "decode_tokens")),
1086                            ("timings", ("prompt_s", "decode_s", "ttft_s", "first_answer_s", "total_s")),
1087                            ("metrics", ("prompt_tps", "decode_tps")),
1088                            ("sources", ("input_tokens", "cached_tokens", "read_tokens", "output_tokens", "decode_tokens",
1089                                         "engine_timings", "client_timings"))):
1090            need(isinstance(r.get(group), dict) and all(k in r[group] for k in keys), f"{r.get('id')}: {group}")
1091        for k, v in (r.get("tokens") or {}).items():
1092            need(v is None or (isinstance(v, int) and not isinstance(v, bool) and v >= 0), f"{r.get('id')}: tokens.{k}")
1093        for group in ("timings", "metrics"):
1094            for k, v in (r.get(group) or {}).items():
1095                need(v is None or (isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v) and v >= 0),
1096                     f"{r.get('id')}: {group}.{k}")
1097        if r.get("phase") == "sanity":
1098            need(isinstance(r.get("evaluation"), dict) and isinstance(r["evaluation"].get("passed"), bool), f"{r.get('id')}: evaluation")
1099        else:
1100            need(r.get("evaluation") is None, f"{r.get('id')}: evaluation outside sanity")
1101        need((r.get("round") is not None) == (r.get("phase") == "concurrency"), f"{r.get('id')}: round")
1102    counts = doc["request_counts"]
1103    for phase in PHASES:
1104        rows = [r for r in records if r.get("phase") == phase]
1105        c = counts.get(phase) or {}
1106        need(c.get("attempted") == c.get("completed", 0) + c.get("truncated", 0) + c.get("failed", 0), f"{phase}: attempted identity")
1107        need(c.get("planned") == c.get("attempted", 0) + c.get("skipped", 0), f"{phase}: planned identity")
1108        need(len(rows) == c.get("planned"), f"{phase}: record count")
1109    need(doc["quality"] == quality_of(records) if len(records) >= 22 else False, "quality does not match the sanity verdicts")
1110    need(isinstance(run_block.get("optional_concurrency"), bool), "run.optional_concurrency")
1111    need((counts["concurrency"]["planned"] == 12) == bool(run_block.get("optional_concurrency")), "concurrency count")
1112
1113    extras = {k: v for k, v in (doc.get("extensions") or {}).get("request_checks", {}).items()}
1114    if extras:
1115        rebuilt = summaries_of(records, extras, "performance", PERFORMANCE_CASES, 1)
1116        if run_block.get("optional_concurrency"):
1117            rebuilt += summaries_of(records, extras, "concurrency", ("short-burst",), 4)
1118        need(rebuilt == doc["summaries"], "summaries cannot be rebuilt from the request records")
1119    for row in doc["summaries"]:
1120        need(row["n"] == len(row["included_request_ids"]), "summary n")
1121        if row["n"] == 0:
1122            need(row["median"] is None and row["min"] is None and row["max"] is None, "empty summary must be null")
1123    for artifact in doc["artifacts"]:
1124        need(artifact.get("kind") in ("config", "engine_log", "outputs", "provenance") and bool(HEX64.match(str(artifact.get("sha256"))))
1125             and not str(artifact.get("path")).startswith(("/", "\\")) and ".." not in Path(str(artifact.get("path"))).parts
1126             and not re.match(r"^[A-Za-z]:", str(artifact.get("path"))), "artifact entry")
1127    nulls = set(scan_nulls(doc))
1128    need(nulls == set(doc["missing"]), "missing must list exactly the null values: "
1129         f"{sorted(nulls ^ set(doc['missing']))[:3]}")
1130    need(all(isinstance(v, str) and v for v in doc["missing"].values()), "every missing entry needs a reason")
1131    try:
1132        json.dumps(doc, allow_nan=False)
1133    except ValueError:
1134        bad.append("the result contains NaN or infinity")
1135    return bad
1136
1137
1138# ------------------------------------------------------------------------------------------------------------ reading it out
1139def _span(row: dict | None, digits: int = 1) -> str:
1140    if not row or row["n"] == 0:
1141        return "not measured"
1142    return f"{row['median']:.{digits}f} ({row['min']:.{digits}f}-{row['max']:.{digits}f}) n={row['n']}"
1143
1144
1145def _find(doc: dict, phase: str, case: str, metric: str) -> dict | None:
1146    return next((s for s in doc["summaries"] if s["phase"] == phase and s["case_id"] == case and s["metric"] == metric), None)
1147
1148
1149def _minutes(seconds: float | None) -> str:
1150    if seconds is None:
1151        return "not measured"
1152    return f"{int(seconds // 60)} min {int(seconds % 60)} s"
1153
1154
1155SHORT_PROMPT_NOTE = ("short is a prompt of about 80 tokens: its prompt rate is dominated by the fixed cost of a request, so it is not "
1156                     "shown; read prompt speed from prompt-4k and prompt-16k")
1157CAP_NOTE = ("Capped = requests that reached the 512-token cap, reasoning and answer together. A capped request's total time is the "
1158            "time to the cap, not to an answer, and it has no first-answer time when it was still reasoning")
1159
1160
1161def capped(doc: dict, phase: str, case: str) -> str:
1162    """'k/n': how many of the case's measured requests stopped at the output cap."""
1163    rows = [r for r in doc["requests"] if r["phase"] == phase and r["case_id"] == case]
1164    return f"{sum(1 for r in rows if r['status'] == 'truncated')}/{len(rows)}"
1165
1166
1167def prompt_cell(doc: dict, phase: str, case: str, digits: int = 1) -> str:
1168    return "n/a" if case == "short" else _span(_find(doc, phase, case, "prompt_tps"), digits)
1169
1170
1171def table_lines(doc: dict, phase: str, cases: tuple[str, ...]) -> list[str]:
1172    head = ["Case", "Prompt tok/s", "Decode tok/s", "TTFT s", "Total s", "Capped"]
1173    rows = [head]
1174    for case in cases:
1175        rows.append([case, prompt_cell(doc, phase, case), _span(_find(doc, phase, case, "decode_tps")),
1176                     _span(_find(doc, phase, case, "ttft_s"), 2), _span(_find(doc, phase, case, "total_s"), 1),
1177                     capped(doc, phase, case)])
1178    widths = [max(len(r[i]) for r in rows) for i in range(len(head))]
1179    return (["  " + "  ".join(cell.ljust(widths[i]) for i, cell in enumerate(row)).rstrip() for row in rows]
1180            + ["  " + SHORT_PROMPT_NOTE + ".", "  " + CAP_NOTE + "."])
1181
1182
1183def format_plain(doc: dict) -> str:
1184    """The summary printed at the end of a run: what ran, how fast, what passed, what to be careful about."""
1185    hw, sw, run_block = doc["hardware"], doc["software"], doc["run"]
1186    gpu = ", ".join(g["name"] for g in hw["gpus"]) or "no GPU found"
1187    counts = doc["request_counts"]
1188    done = sum(counts[p]["completed"] + counts[p]["truncated"] for p in ("performance", "sanity"))
1189    quality = doc["quality"]
1190    lines = [f"Strata standard benchmark ({doc['protocol']['id']})",
1191             f"Status: {run_block['status']}. {done} of 21 required requests finished, "
1192             f"{sum(counts[p]['failed'] for p in PHASES)} failed, {sum(counts[p]['skipped'] for p in PHASES)} skipped. "
1193             f"Time after the model loaded: {_minutes(run_block['required_duration_s'])}.",
1194             f"Machine: {gpu}; {hw['cpu'] or 'CPU not read'}; "
1195             f"{round(hw['ram_bytes'] / 2 ** 30) if hw['ram_bytes'] else 'unknown'} GB RAM; {sw['os']['name']} {sw['os']['version']}.",
1196             f"Model: {doc['model']['id'] or 'unknown'}, {doc['model']['quantization'] or 'quantization not read'}, "
1197             f"context {doc['configuration']['context_tokens'] or 'unknown'}; engine {sw['engine_version'] or 'unknown'}; "
1198             f"track {doc['configuration']['track']}.", "",
1199             "Speed (median, min-max, n; the engine's own prompt and decode timings, the client's first-token time):"]
1200    lines += table_lines(doc, "performance", PERFORMANCE_CASES)
1201    lines += ["", f"Sanity checks: {quality['passed']} of 12 passed "
1202              f"(instruction {quality['categories']['instruction']['passed']}/4, retrieval "
1203              f"{quality['categories']['retrieval']['passed']}/4, tool calls {quality['categories']['tool_call']['passed']}/4)."]
1204    failed = [r["evaluation"] and f"{r['case_id']}: {r['evaluation']['reason']}" for r in doc["requests"]
1205              if r["phase"] == "sanity" and not r["evaluation"]["passed"]]
1206    lines += ["  Not passed: " + "; ".join(failed)] if failed else []
1207    if doc["run"]["optional_concurrency"]:
1208        rounds = [r["aggregate_tps"] for r in doc["concurrency_rounds"] if r["aggregate_tps"] is not None]
1209        lines += ["", "Four requests at once (server capacity "
1210                  f"{doc['configuration']['server_capacity'] or 'unknown'}): "
1211                  + (", ".join(f"{v:.1f}" for v in rounds) + " tok/s in total per round" if rounds else "no round finished")]
1212    reasons = doc["extensions"]["status_reasons"]
1213    if run_block["status"] != "complete" and reasons:
1214        lines += ["", "Why this is not a complete standard result:"] + [f"  - {r}" for r in reasons]
1215    failures = [f"{r['id']}: {r['error']['kind']}" for r in doc["requests"] if r["status"] == "failed"]
1216    if failures:
1217        lines += ["", "Failed requests: " + "; ".join(failures)]
1218    return "\n".join(lines)
1219
1220
1221def report_markdown(doc: dict, redact=lambda text: text) -> str:
1222    hw, sw, run_block, model, cfg = doc["hardware"], doc["software"], doc["run"], doc["model"], doc["configuration"]
1223    counts = doc["request_counts"]
1224    quality = doc["quality"]
1225    gpu = "; ".join(("%s (%.1f GiB %s)" % (g["name"], g["memory_bytes"] / 2 ** 30, g["memory_kind"])) if g["memory_bytes"]
1226                    else g["name"] for g in hw["gpus"]) or "not measured"
1227    nm = "not measured"
1228    ram = "%.1f GiB" % (hw["ram_bytes"] / 2 ** 30) if hw["ram_bytes"] else nm
1229    storage = ", ".join("%s %s (%s)" % (s["kind"], s["model"], s["bus"]) for s in hw["storage"]) if hw["storage"] else nm
1230    drivers = ", ".join("%s %s" % (d["name"], d["version"]) for d in sw["drivers"]) if sw["drivers"] else nm
1231    runtime = ", ".join("%s %s" % (d["name"], d["version"]) for d in sw["runtime"]) if sw["runtime"] else nm
1232    lines = [
1233        "# Strata standard benchmark: %s" % (", ".join(g["name"] for g in hw["gpus"]) or "unknown GPU"), "",
1234        "Protocol `%s` (draft), run `%s`, started %s. **Status: %s.**" % (doc["protocol"]["id"], run_block["id"],
1235                                                                         run_block["started_at"], run_block["status"]), "",
1236        "Written by `strata bench run`. The machine-readable result is [results.json](results.json); every request, its raw usage "
1237        "and timings and the client event offsets are in [outputs.jsonl](outputs.jsonl).", ""]
1238    reasons = doc["extensions"]["status_reasons"]
1239    if run_block["status"] != "complete":
1240        lines += ["This run is not a complete standard result:", ""] + ["- " + r for r in reasons] + [""]
1241    lines += [
1242        "## Hardware and software", "",
1243        "- GPU: " + gpu,
1244        "- CPU: %s; RAM: %s" % (hw["cpu"] or nm, ram),
1245        "- Storage of the model files: " + storage,
1246        "- OS: %s %s; drivers: %s; runtime: %s" % (sw["os"]["name"], sw["os"]["version"], drivers, runtime),
1247        "- Strata commit: `%s`; engine %s; %s build" % (sw["strata_commit"] or nm, sw["engine_version"] or nm, sw["build_kind"]),
1248        "- Background work: " + ("; ".join(hw["background_workloads"]) if hw["background_workloads"] else nm), "",
1249        "## Model and configuration", "",
1250        f"- Model: {model['id'] or nm}; quantization {model['quantization'] or nm}; revision {model['revision'] or nm}; "
1251        f"source revision {model['source_revision'] or nm}",
1252        f"- Files: " + ("; ".join(f"`{f['path']}` `{f['sha256'][:16]}...`" for f in model['files']) if model['files'] else nm),
1253        f"- Track: **{cfg['track']}** ({cfg['track_notes']})",
1254        f"- Context {cfg['context_tokens'] or nm} tokens; server capacity {cfg['server_capacity'] or nm} slot(s)",
1255        f"- Sampling: " + ", ".join(f"{k} {v}" for k, v in cfg["sampling"].items()) + "; thinking on, preserved",
1256        f"- Engine options: `config.json`; chat template: `provenance/chat_template.jinja`", "",
1257        "## Method", "",
1258        f"The frozen requests of `bench/prompts/standard-v1` (corpus `{doc['protocol']['corpus_sha256'][:16]}...`) were sent over "
1259        "loopback HTTP, streaming, one at a time, in this order: 1 warm-up (excluded), 3 repetitions of the short, 4K and 16K prompts, "
1260        "and the twelve sanity checks. Prompt and decode speed are the engine's own `timings`; time to first token is the client's "
1261        "monotonic clock from dispatch to the first nonempty reasoning, answer or tool-call delta. No request was retried. "
1262        f"Time after the model loaded: {_minutes(run_block['required_duration_s'])}.", "",
1263        "## Results", ""]
1264    lines += ["| Case | Prompt tok/s | Decode tok/s | TTFT s | First answer s | Total s | Capped |", "| --- | --- | --- | --- | --- | --- | --- |"]
1265    for case in PERFORMANCE_CASES:
1266        lines.append(f"| {case} | " + prompt_cell(doc, "performance", case) + " | " + " | ".join(
1267            _span(_find(doc, "performance", case, m), d) for m, d in (("decode_tps", 1), ("ttft_s", 2),
1268                                                                      ("first_answer_s", 2), ("total_s", 1)))
1269            + f" | {capped(doc, 'performance', case)} |")
1270    lines += ["", "Cells are median (min-max) n=samples. " + SHORT_PROMPT_NOTE[0].upper() + SHORT_PROMPT_NOTE[1:] + ". " + CAP_NOTE + ".", "",
1271              "| Phase | Planned | Completed | Truncated | Failed | Skipped |", "| --- | ---: | ---: | ---: | ---: | ---: |"]
1272    for phase in PHASES:
1273        c = counts[phase]
1274        lines.append(f"| {phase} | {c['planned']} | {c['completed']} | {c['truncated']} | {c['failed']} | {c['skipped']} |")
1275    lines += ["", f"Sanity checks: **{quality['passed']} of 12**.", "", "| Case | Result | Reason |", "| --- | --- | --- |"]
1276    for r in doc["requests"]:
1277        if r["phase"] == "sanity":
1278            lines.append(f"| {r['case_id']} | {'pass' if r['evaluation']['passed'] else 'fail'} | {r['evaluation']['reason']} |")
1279    if run_block["optional_concurrency"]:
1280        lines += ["", "Concurrency rounds (four requests released together):", "",
1281                  "| Round | Wall s | Output tokens | Aggregate tok/s | Failed |", "| ---: | ---: | ---: | ---: | ---: |"]
1282        for r in doc["concurrency_rounds"]:
1283            lines.append(f"| {r['round']} | {r['wall_s']} | {r['output_tokens']} | {r['aggregate_tps']} | {r['failed']} |")
1284    failures = [r for r in doc["requests"] if r["status"] == "failed"]
1285    lines += ["", "## Failures, exclusions and limitations", ""]
1286    lines += [f"- {r['id']} failed: {r['error']['kind']} ({r['error']['message']})" for r in failures] or ["- No request failed."]
1287    excluded = {(e["request_id"], e["reason"]) for s in doc["summaries"] for e in s["excluded"]}
1288    lines += [f"- Excluded from speed summaries: {rid}: {reason}" for rid, reason in sorted(excluded)]
1289    lines += ["- Prompt-prefix reuse is the shared template prefix only; the cache was not emptied between requests, and the expert "
1290              "cache stays warm and evolves. These are not cold-model measurements.",
1291              "- Output caps include reasoning; a request that reaches its cap is `truncated` and fails its sanity check.",
1292              "- The runner cannot see other programs on the machine, the repeat-stop and loop-recovery switches of the server, or "
1293              "the quantization repository's revision; see `missing` in results.json for every value it could not read.",
1294              f"- The server had answered {doc['extensions']['server_requests_before_run']} request(s) before this run."
1295              if doc["extensions"]["server_requests_before_run"] else
1296              ("- The server had answered no request before this run (a freshly loaded engine)."
1297               if doc["extensions"]["server_requests_before_run"] == 0 else
1298               "- The runner could not tell whether the server was freshly loaded."), ""]
1299    return redact("\n".join(lines))
1300
1301
1302def load(path: Path) -> dict:
1303    """Read a saved standard result and validate it. A result in another format or schema version is refused, never merged."""
1304    target = path / "results.json" if path.is_dir() else path
1305    try:
1306        if target.stat().st_size > 64 << 20:
1307            raise ProfileError("benchmark result is larger than 64 MiB", 5)
1308        doc = json.loads(target.read_text(encoding="utf-8"))
1309    except (OSError, UnicodeError, ValueError):
1310        raise ProfileError("cannot read the benchmark result", 5) from None
1311    problems = validate(doc)
1312    if problems:
1313        raise ProfileError("not a valid standard benchmark result: " + problems[0], 5)
1314    return doc
1315
1316
1317def load_if_standard(path: Path) -> dict | None:
1318    """The validated result at `path` when it is a standard benchmark result; None when it is another kind of report."""
1319    target = path / "results.json" if path.is_dir() else path
1320    try:
1321        head = json.loads(target.read_text(encoding="utf-8"))
1322    except (OSError, UnicodeError, ValueError):
1323        return None
1324    if not isinstance(head, dict) or head.get("format") != FORMAT:
1325        return None
1326    return load(path)