okami.mom/strata

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

Niko1221Merge f-022-refusals: environmental refusals repair or warn instead of blocking (audit items 1-4, 6, 8-10, 12-15)bcf88b738

main
73.2 KiB1308 linesraw
1"""Explicit, local-file serving benchmark with privacy-safe evidence.
2
3This measures the API as a client sees it. Engine batching and GPU readings are
4sampled from telemetry; missing signals stay unknown. It does not tune a model.
5"""
6
7from __future__ import annotations
8
9try:
10    from strata_control.private_files import private_mkdir as _private_mkdir
11except ImportError:                                     # a thin bundle (monitor only) ships without strata_control
12    def _private_mkdir(path, *, parents=False, exist_ok=True):
13        path.mkdir(mode=0o700, parents=parents, exist_ok=exist_ok)
14        return path
15import hashlib
16import http.client
17import json
18import math
19import os
20import re
21import socket
22import stat
23import statistics
24import threading
25import time
26import urllib.error
27import urllib.request
28import uuid
29from contextlib import contextmanager, nullcontext
30from concurrent.futures import ThreadPoolExecutor, as_completed
31from datetime import datetime, timezone
32from pathlib import Path
33
34from strata_cli.client import ClientError, Endpoint, _NoRedirect
35from strata_control.profiles import ProfileError
36from strata_control import atomic as _atomic_mod
37from strata_control import posix_owner
38
39
40SCHEMA = 1
41MAX_EVENT_BYTES = 256 * 1024
42MAX_RESPONSE_BYTES = 8 * 1024 * 1024
43MAX_REPORT_BYTES = 4 * 1024 * 1024
44MAX_SAMPLES_PER_PHASE = 500
45SHORT_PROMPT = "Answer in one sentence: what does a GPU do during model inference?"
46LONG_PROMPT = ("Explain how a serving system handles simultaneous short and long requests, "
47               "including queue admission, prefill, decode slots, batching and cancellation. " * 12)
48CANCEL_PROMPT = ("Cancellation benchmark: write a detailed explanation of batching and parallel inference "
49                 "with at least 200 words. Discuss admission, prompt reading, decoding and recovery.")
50SUITES = {"serving-smoke": ("warmup", "serial", "mixed"),
51          "parallel-mixed-v1": ("warmup", "serial", "mixed", "mixed"),
52          "parallel-overload-v1": ("warmup", "overload", "recovery"),
53          "parallel-cancel-v1": ("warmup", "cancel_active", "cancel_queued", "recovery"),
54          "parallel-prefill-cancel-v1": ("warmup", "cancel_prefill", "recovery")}
55
56
57class OperatorCancellation:
58    """Stop benchmark-owned streams after an owner-local cancel request appears."""
59
60    def __init__(self, directory: Path):
61        self.path = directory / "cancel.request"
62        self.event = threading.Event()
63        self._stop = threading.Event()
64        self._lock = threading.Lock()
65        self._sockets: set[socket.socket] = set()
66        self._watcher = threading.Thread(target=self._watch, daemon=True)
67
68    def _watch(self) -> None:
69        while not self._stop.wait(0.1):
70            if self.path.exists():
71                self.cancel()
72                return
73
74    def cancel(self) -> None:
75        with self._lock:
76            self.event.set()
77            sockets = tuple(self._sockets)
78        for owned in sockets:
79            try:
80                owned.shutdown(socket.SHUT_RDWR)
81            except OSError:
82                pass
83
84    @contextmanager
85    def track(self, response):
86        # urllib's HTTPResponse owns the socket while reading its buffered stream.
87        stream = getattr(response, "fp", None)
88        raw = getattr(stream, "raw", None)
89        owned = getattr(raw, "_sock", None)
90        if not isinstance(owned, socket.socket):
91            owned = None
92        if owned is not None:
93            with self._lock:
94                self._sockets.add(owned)
95                cancelled = self.event.is_set()
96            if cancelled:
97                try:
98                    owned.shutdown(socket.SHUT_RDWR)
99                except OSError:
100                    pass
101        try:
102            yield
103        finally:
104            if owned is not None:
105                with self._lock:
106                    self._sockets.discard(owned)
107
108    def __enter__(self):
109        self._watcher.start()
110        return self
111
112    def __exit__(self, *_):
113        self._stop.set()
114        self._watcher.join(timeout=1)
115
116
117def _planned_phase_kinds(suite: str, repeat: int) -> list[str]:
118    single = {"warmup", "recovery", "cancel_active", "cancel_queued", "cancel_prefill"}
119    return [kind for kind in SUITES[suite]
120            for _ in range(1 if kind in single else repeat)]
121
122
123def _utc_now() -> str:
124    return datetime.now(timezone.utc).isoformat(timespec="seconds")
125
126
127def _percentile(values: list[float], fraction: float) -> float | None:
128    if not values:
129        return None
130    ordered = sorted(values)
131    return round(ordered[max(0, math.ceil(len(ordered) * fraction) - 1)], 4)
132
133
134def _sample(snapshot: dict) -> dict:
135    work = snapshot.get("work") or {}
136    rates = snapshot.get("rates") or {}
137    return {"at": time.time(), "instance_id": (snapshot.get("instance") or {}).get("id"),
138            "active": work.get("active"), "queued": work.get("queued"),
139            "waiting": work.get("waiting"), "occupied_slots": work.get("occupied_slots"),
140            "slots_effective": work.get("slots_effective"), "groups": work.get("groups"),
141            "admission_reserved": work.get("admission_reserved"),
142            "admission_rejected": work.get("admission_rejected"),
143            "admission_limit": work.get("admission_limit"), "max_queue": work.get("max_queue"),
144            "queue_timeout_s": work.get("queue_timeout_s"), "queue_timeouts": work.get("queue_timeouts"),
145            "client_disconnect_cancels": work.get("client_disconnect_cancels"),
146            "answer_tok_s": rates.get("answer_tok_s"),
147            "devices": [{"index": d.get("index"), "mem_used": d.get("mem_used"),
148                         "mem_total": d.get("mem_total"), "util": d.get("util")}
149                        for d in snapshot.get("devices", [])[:16]]}
150
151
152def _environment(snapshot: dict) -> dict:
153    """Bounded reported setup for comparisons, not a hardware attestation."""
154    work = snapshot.get("work") or {}
155    model = snapshot.get("model") or {}
156    topology = snapshot.get("topology") or {}
157    devices = []
158    for row in snapshot.get("devices", [])[:16]:
159        if not isinstance(row, dict):
160            continue
161        name = row.get("name")
162        devices.append({"index": row.get("index"),
163                        "name": name[:120] if isinstance(name, str) and name.isprintable() else None,
164                        "mem_total": row.get("mem_total")})
165    return {"model_context": model.get("context"),
166            "slots_effective": work.get("slots_effective"), "groups": work.get("groups"),
167            "max_queue": work.get("max_queue"), "queue_timeout_s": work.get("queue_timeout_s"),
168            "selected_devices": (topology.get("selected_devices") or [])[:16],
169            "stages": (topology.get("stages") or [])[:16], "devices": devices,
170            "source": "server_telemetry; driver, engine binary and model artifact hashes not attested"}
171
172
173def _managed_match(profile_identity: dict, endpoint_root: str, snapshot: dict) -> dict:
174    """Check a local owner host without persisting its control token or launch MAC."""
175    from strata_control import runtime
176
177    name, revision = profile_identity.get("profile"), profile_identity.get("revision")
178    if not isinstance(name, str) or not re.fullmatch(r"[a-z][a-z0-9_-]{0,63}", name) or \
179            not isinstance(revision, str) or not re.fullmatch(r"[0-9a-f]{16}", revision):
180        return {"matched": False, "reason": "saved_profile_required"}
181    try:
182        owner = runtime.status(name)
183        plan = runtime.plan_restart(name)
184    except (OSError, ProfileError, ValueError):
185        return {"matched": False, "reason": "owner_unavailable"}
186    instance = (snapshot.get("instance") or {}).get("id")
187    if (not owner.get("ok") or owner.get("state") != "ready" or
188            owner.get("launch_attested") is not True or owner.get("api_identity_verified") is not True or
189            owner.get("generation_ready") is not True):
190        return {"matched": False, "reason": "owner_not_verified"}
191    if (not plan.get("ok") or plan.get("changed") is not False):
192        return {"matched": False, "reason": "profile_or_source_changed"}
193    if (not isinstance(instance, str) or owner.get("instance_id") != instance or
194            plan.get("current_instance_id") != instance):
195        return {"matched": False, "reason": "instance_mismatch"}
196    if (owner.get("profile_revision") != revision or
197            plan.get("current_profile_revision") != revision or
198            plan.get("candidate_profile_revision") != revision):
199        return {"matched": False, "reason": "profile_revision_mismatch"}
200    if owner.get("api_url") != endpoint_root:
201        return {"matched": False, "reason": "endpoint_mismatch"}
202    return {"matched": True, "reason": "managed_launch_checked", "instance_id": instance,
203            "profile_revision": revision}
204
205
206def _event_result(event: dict, first_ns: int | None,
207                  completion_tokens: int | None) -> tuple[int | None, int | None, str | None]:
208    if "error" in event:
209        error = event["error"]
210        code = (error.get("code") or error.get("type")) if isinstance(error, dict) else "stream_error"
211        return first_ns, completion_tokens, str(code)[:80]
212    choices = event.get("choices")
213    if isinstance(choices, list) and choices and isinstance(choices[0], dict):
214        delta = choices[0].get("delta")
215        if isinstance(delta, dict) and any(delta.get(key) for key in ("content", "reasoning_content", "tool_calls")):
216            first_ns = first_ns or time.monotonic_ns()
217    usage = event.get("usage")
218    if isinstance(usage, dict) and type(usage.get("completion_tokens")) is int:
219        completion_tokens = usage["completion_tokens"]
220    return first_ns, completion_tokens, None
221
222
223def _request(root: str, credential: str | None, prompt: str, max_tokens: int,
224             timeout: float, label: str, start_gate: threading.Event | None = None,
225             operator: OperatorCancellation | None = None) -> dict:
226    """Send one streamed request. Save measurements, never prompt or answer text."""
227    payload = {"messages": [{"role": "user", "content": prompt}],
228               "stream": True, "max_tokens": max_tokens, "temperature": 0}
229    headers = {"Content-Type": "application/json", "Accept": "text/event-stream",
230               "User-Agent": "Strata-Bench/0.1"}
231    if credential:
232        headers["Authorization"] = "Bearer " + credential
233    request = urllib.request.Request(root + "/v1/chat/completions",
234                                     data=json.dumps(payload).encode("utf-8"), headers=headers, method="POST")
235    if start_gate is not None:
236        start_gate.wait()
237    start_ns = time.monotonic_ns()
238    first_ns = None
239    tokens = None
240    received = 0
241    done = False
242    status = None
243    error = None
244    try:
245        if operator is not None and operator.event.is_set():
246            raise InterruptedError("operator cancelled")
247        with urllib.request.build_opener(_NoRedirect).open(request, timeout=timeout) as response:
248            with operator.track(response) if operator is not None else nullcontext():
249                status = response.status
250                if "text/event-stream" not in response.headers.get("Content-Type", ""):
251                    raise ValueError("response was not an event stream")
252                while True:
253                    line = response.readline(MAX_EVENT_BYTES + 1)
254                    if not line:
255                        break
256                    received += len(line)
257                    if len(line) > MAX_EVENT_BYTES or received > MAX_RESPONSE_BYTES:
258                        raise ValueError("stream exceeded the benchmark size limit")
259                    if not line.startswith(b"data: "):
260                        continue
261                    data = line[6:].strip()
262                    if data == b"[DONE]":
263                        done = True
264                        break
265                    event = json.loads(data)
266                    if not isinstance(event, dict):
267                        raise ValueError("stream event was not an object")
268                    first_ns, tokens, error = _event_result(event, first_ns, tokens)
269                    if error:
270                        break
271                if not done and not error:
272                    error = "stream_ended_without_done"
273    except urllib.error.HTTPError as exc:
274        status = exc.code
275        error = "authentication_failed" if status in (401, 403) else f"http_{status}"
276        if status == 429:
277            try:
278                raw = exc.read(4097)
279                if len(raw) <= 4096:
280                    body = json.loads(raw)
281                    code = (body.get("error") or {}).get("code")
282                    if code in ("admission_full", "queue_wait_timeout"):
283                        error = code
284            except (OSError, ValueError, AttributeError):
285                pass
286        exc.close()
287    except (urllib.error.URLError, TimeoutError, socket.timeout, OSError, http.client.HTTPException) as exc:
288        error = "connection_" + type(exc).__name__
289    except (UnicodeError, ValueError) as exc:
290        error = "invalid_stream_" + type(exc).__name__
291    if operator is not None and operator.event.is_set():
292        error = "operator_cancelled"
293        done = False
294    end_ns = time.monotonic_ns()
295    result = {"label": label, "prompt_sha256": hashlib.sha256(prompt.encode("utf-8")).hexdigest(),
296            "prompt_characters": len(prompt), "max_tokens": max_tokens,
297            "status": status, "ok": status == 200 and done and error is None,
298            "error_code": error, "latency_s": round((end_ns - start_ns) / 1e9, 4),
299            "ttft_s": round((first_ns - start_ns) / 1e9, 4) if first_ns else None,
300            "completion_tokens": tokens}
301    if start_gate is not None:
302        result["_launch_ns"] = start_ns
303    return result
304
305
306def _cancellable_request(root: str, credential: str | None, prompt: str, timeout: float,
307                         first_content: bool, opened: threading.Event,
308                         ready_to_close: threading.Event, close_now: threading.Event,
309                         result: dict, operator: OperatorCancellation | None = None) -> None:
310    """Hold one streamed client socket until the benchmark deliberately closes it."""
311    payload = {"messages": [{"role": "user", "content": prompt}],
312               "stream": True, "max_tokens": 512, "temperature": 0}
313    headers = {"Content-Type": "application/json", "Accept": "text/event-stream",
314               "User-Agent": "Strata-Bench/0.1"}
315    if credential:
316        headers["Authorization"] = "Bearer " + credential
317    request = urllib.request.Request(root + "/v1/chat/completions",
318                                     data=json.dumps(payload).encode("utf-8"), headers=headers, method="POST")
319    started = time.monotonic_ns()
320    result.update({"label": "cancel_target", "prompt_sha256": hashlib.sha256(prompt.encode()).hexdigest(),
321                   "prompt_characters": len(prompt), "max_tokens": 512, "status": None,
322                   "client_closed": False, "first_content_seen": False, "error_code": None})
323    try:
324        if operator is not None and operator.event.is_set():
325            raise InterruptedError("operator cancelled")
326        with urllib.request.build_opener(_NoRedirect).open(request, timeout=timeout) as response:
327            with operator.track(response) if operator is not None else nullcontext():
328                result["status"] = response.status
329                opened.set()
330                if "text/event-stream" not in response.headers.get("Content-Type", ""):
331                    result["error_code"] = "not_event_stream"
332                    return
333                if first_content:
334                    received = 0
335                    while received <= MAX_RESPONSE_BYTES:
336                        line = response.readline(MAX_EVENT_BYTES + 1)
337                        if not line:
338                            result["error_code"] = "ended_before_cancel"
339                            return
340                        received += len(line)
341                        if len(line) > MAX_EVENT_BYTES:
342                            result["error_code"] = "stream_too_large"
343                            return
344                        if line.startswith(b"data: "):
345                            data = line[6:].strip()
346                            if data == b"[DONE]":
347                                result["error_code"] = "ended_before_cancel"
348                                return
349                            event = json.loads(data)
350                            first_ns, _, error = _event_result(event, None, None)
351                            if error:
352                                result["error_code"] = error
353                                return
354                            if first_ns is not None:
355                                result["first_content_seen"] = True
356                                break
357                    if not result["first_content_seen"]:
358                        result["error_code"] = "stream_too_large"
359                        return
360                ready_to_close.set()
361                if not close_now.wait(timeout):
362                    result["error_code"] = "client_close_signal_timeout"
363                    return
364                result["client_closed"] = True
365    except urllib.error.HTTPError as error:
366        result["status"] = error.code
367        result["error_code"] = "authentication_failed" if error.code in (401, 403) else f"http_{error.code}"
368        error.close()
369    except (urllib.error.URLError, TimeoutError, socket.timeout, OSError,
370            http.client.HTTPException, UnicodeError, ValueError, TypeError, AttributeError) as error:
371        result["error_code"] = type(error).__name__[:80]
372    finally:
373        if operator is not None and operator.event.is_set():
374            result["error_code"] = "operator_cancelled"
375        opened.set()
376        ready_to_close.set()
377        result["latency_s"] = round((time.monotonic_ns() - started) / 1e9, 4)
378
379
380def _cancel_phase(endpoint: Endpoint, telemetry: Endpoint, *, kind: str,
381                  slots: int, timeout: float,
382                  operator: OperatorCancellation | None = None) -> dict:
383    samples: list[dict] = []
384    sample_errors = 0
385    samples_omitted = 0
386    peaks: dict[str, int | float] = {}
387    beginning = time.monotonic()
388
389    def capture() -> dict | None:
390        nonlocal sample_errors, samples_omitted
391        try:
392            snapshot = telemetry.snapshot()
393        except (ClientError, ValueError):
394            sample_errors += 1
395            return None
396        row = _sample(snapshot)
397        for key in ("active", "queued", "waiting", "occupied_slots", "groups"):
398            value = row.get(key)
399            if type(value) in (int, float):
400                peaks[key] = max(peaks.get(key, value), value)
401        if len(samples) < 120:
402            samples.append(row)
403        else:
404            samples_omitted += 1
405        return snapshot
406
407    def until(check, seconds: float) -> dict | None:
408        deadline = time.monotonic() + seconds
409        while time.monotonic() < deadline:
410            if operator is not None and operator.event.is_set():
411                return None
412            snapshot = capture()
413            if snapshot is not None and check(snapshot):
414                return snapshot
415            time.sleep(0.05)
416        return None
417
418    def wait_signal(signal: threading.Event, seconds: float) -> None:
419        deadline = time.monotonic() + seconds
420        while not signal.is_set() and time.monotonic() < deadline:
421            if operator is not None and operator.event.is_set():
422                return
423            signal.wait(min(0.2, max(0, deadline - time.monotonic())))
424
425    before = capture()
426    if before is None:
427        raise ProfileError("cancellation benchmark could not read telemetry", 5)
428    work_before = before.get("work") or {}
429    before_ids = {row.get("id") for row in work_before.get("requests") or []}
430    base_cancel = work_before.get("client_disconnect_cancels")
431    base_timeout = work_before.get("queue_timeouts")
432    if type(base_cancel) is not int or type(base_timeout) is not int:
433        raise ProfileError("cancellation benchmark lost required telemetry counters", 5)
434    opened, ready_to_close, close_now = threading.Event(), threading.Event(), threading.Event()
435    target: dict = {}
436    companion_rows: list[dict] = []
437    seen_state = False
438    observed_cancel = False
439    settled = False
440    target_id = None
441    companion_ok = True
442    worker = None
443    companions = None
444    companions_needed = slots if kind == "cancel_queued" else 1 if kind == "cancel_prefill" else 0
445    prompt_read_seen = False
446    try:
447        if companions_needed:
448            companions = ThreadPoolExecutor(max_workers=companions_needed)
449            futures = [companions.submit(_request, endpoint.root, endpoint.credential,
450                                         CANCEL_PROMPT, 512, timeout, "companion", None, operator)
451                       for _ in range(companions_needed)]
452            running = until(lambda snap: sum(row.get("state") not in ("queued", "waiting")
453                                             for row in (snap.get("work") or {}).get("requests") or []
454                                             if row.get("id") not in before_ids) >= companions_needed,
455                            min(timeout, 20))
456            if running is None:
457                target["error_code"] = "companion_slots_not_active"
458            else:
459                before_ids = {row.get("id") for row in (running.get("work") or {}).get("requests") or []}
460        if "error_code" not in target:
461            worker = threading.Thread(target=_cancellable_request,
462                                      args=(endpoint.root, endpoint.credential,
463                                            SHORT_PROMPT if kind == "cancel_queued" else
464                                            LONG_PROMPT if kind == "cancel_prefill" else CANCEL_PROMPT,
465                                            timeout, kind == "cancel_active",
466                                            opened, ready_to_close, close_now, target, operator), daemon=True)
467            worker.start()
468            wait_signal(opened, min(timeout, 20))
469            wait_signal(ready_to_close, min(timeout, 20))
470            desired = ({"queued", "waiting"} if kind == "cancel_queued" else
471                       {"reading"} if kind == "cancel_prefill" else None)
472            found = until(lambda snap: any(row.get("id") not in before_ids and
473                                           (desired is None or row.get("state") in desired) and
474                                           (kind != "cancel_prefill" or
475                                            type(row.get("prompt_read")) is int and
476                                            type(row.get("prompt_tokens")) is int and
477                                            0 < row["prompt_read"] < row["prompt_tokens"])
478                                           for row in (snap.get("work") or {}).get("requests") or []),
479                          min(timeout, 5.0))
480            if found is not None:
481                row = next(row for row in (found.get("work") or {}).get("requests") or []
482                           if row.get("id") not in before_ids and
483                           (desired is None or row.get("state") in desired) and
484                           (kind != "cancel_prefill" or
485                            type(row.get("prompt_read")) is int and
486                            type(row.get("prompt_tokens")) is int and
487                            0 < row["prompt_read"] < row["prompt_tokens"]))
488                target_id = row["id"]
489                target["request_id"] = target_id
490                seen_state = True
491                if kind == "cancel_prefill":
492                    target["prompt_read_at_close"] = row["prompt_read"]
493                    target["prompt_tokens_at_close"] = row["prompt_tokens"]
494                    prompt_read_seen = True
495            close_now.set()
496            worker.join(timeout=min(timeout, 10))
497            observed = until(lambda snap: type((snap.get("work") or {}).get("client_disconnect_cancels")) is int
498                             and (snap["work"]["client_disconnect_cancels"] >= base_cancel + 1)
499                             and (target_id is None or all(row.get("id") != target_id
500                                                           for row in snap["work"].get("requests") or [])), 10.0)
501            observed_cancel = observed is not None
502        if companions is not None:
503            for future in as_completed(futures):
504                companion_rows.append(future.result())
505            companion_ok = all(row["ok"] for row in companion_rows)
506        settled = until(lambda snap: (snap.get("work") or {}).get("admission_reserved") == 0 and
507                        (snap.get("work") or {}).get("active") == 0 and
508                        (snap.get("work") or {}).get("occupied_slots") in (0, None), 10.0) is not None
509    finally:
510        close_now.set()
511        if worker is not None:
512            worker.join(timeout=1)
513        if companions is not None:
514            companions.shutdown(wait=True)
515    after = capture() or {}
516    work_after = after.get("work") or {}
517    cancel_delta = (work_after.get("client_disconnect_cancels") - base_cancel
518                    if type(work_after.get("client_disconnect_cancels")) is int and type(base_cancel) is int
519                    else None)
520    timeout_delta = (work_after.get("queue_timeouts") - base_timeout
521                     if type(work_after.get("queue_timeouts")) is int and type(base_timeout) is int else None)
522    passed = (seen_state and (kind != "cancel_prefill" or prompt_read_seen) and
523              target.get("client_closed") is True and observed_cancel and settled and
524              companion_ok and timeout_delta == 0 and target.get("error_code") is None and
525              (kind != "cancel_active" or target.get("first_content_seen")))
526    elapsed = time.monotonic() - beginning
527    return {"kind": kind, "requested": 1 + companions_needed,
528            "client_workers": 1 + companions_needed, "passed": passed,
529            "duration_s": round(elapsed, 4), "requests": [target, *companion_rows],
530            "telemetry_samples": samples, "telemetry_sample_errors": sample_errors,
531            "telemetry_samples_omitted": samples_omitted,
532            "summary": {"successful": sum(row["ok"] for row in companion_rows),
533                        "failed": 0 if passed else 1, "expected_overload": 0,
534                        "target_state_seen": seen_state, "client_closed": target.get("client_closed") is True,
535                        "prompt_read_seen": prompt_read_seen,
536                        "first_content_seen": target.get("first_content_seen") is True,
537                        "client_disconnect_delta": cancel_delta, "queue_timeouts_delta": timeout_delta,
538                        "companion_successful": sum(row["ok"] for row in companion_rows),
539                        "settled": settled,
540                        "p50_latency_s": _percentile([row["latency_s"] for row in companion_rows if row["ok"]], 0.5),
541                        "p95_latency_s": _percentile([row["latency_s"] for row in companion_rows if row["ok"]], 0.95),
542                        "p50_ttft_s": None, "p95_ttft_s": None, "output_tokens": None, "output_tok_s": None,
543                        "peak_active": peaks.get("active"), "peak_queued": peaks.get("queued"),
544                        "peak_waiting": peaks.get("waiting"),
545                        "peak_occupied_slots": peaks.get("occupied_slots"), "peak_groups": peaks.get("groups"),
546                        "peak_admission_rejected": None}}
547
548
549def _phase(endpoint: Endpoint, telemetry: Endpoint, *, kind: str, count: int,
550           concurrency: int, timeout: float,
551           operator: OperatorCancellation | None = None) -> dict:
552    samples = []
553    sample_errors = 0
554    samples_omitted = 0
555    sample_cap = min(MAX_SAMPLES_PER_PHASE, 120) if kind == "overload" else MAX_SAMPLES_PER_PHASE
556    peaks = {}
557    first_sample = None
558    last_sample = None
559    stop = threading.Event()
560
561    def record(snapshot):
562        nonlocal samples_omitted, first_sample, last_sample
563        sample = _sample(snapshot)
564        if first_sample is None:
565            first_sample = sample
566        last_sample = sample
567        for key in ("active", "queued", "waiting", "occupied_slots", "groups", "admission_rejected"):
568            value = sample.get(key)
569            if type(value) in (int, float):
570                peaks[key] = max(peaks.get(key, value), value)
571        if len(samples) < sample_cap:
572            samples.append(sample)
573        else:
574            samples_omitted += 1
575
576    def poll():
577        nonlocal sample_errors
578        while not stop.is_set() and (operator is None or not operator.event.is_set()):
579            try:
580                record(telemetry.snapshot())
581            except (ClientError, ValueError):
582                sample_errors += 1
583            stop.wait(0.15)
584
585    try:
586        record(telemetry.snapshot())
587    except (ClientError, ValueError):
588        sample_errors += 1
589    worker = threading.Thread(target=poll, daemon=True)
590    worker.start()
591    start = time.monotonic()
592    requests = []
593    try:
594        with ThreadPoolExecutor(max_workers=concurrency) as pool:
595            futures = []
596            start_gate = threading.Event() if kind == "overload" else None
597            try:
598                for index in range(count):
599                    long = kind in ("mixed", "overload") and index % 2 == 1
600                    prompt = LONG_PROMPT if long else SHORT_PROMPT
601                    limit = 256 if kind == "overload" else 96 if long else 32
602                    futures.append(pool.submit(_request, endpoint.root, endpoint.credential,
603                                               prompt, limit, timeout, "long" if long else "short",
604                                               start_gate, operator))
605            finally:
606                if start_gate is not None:
607                    start_gate.set()
608            for future in as_completed(futures):
609                requests.append(future.result())
610    finally:
611        stop.set()
612        worker.join(timeout=min(telemetry.timeout + 1, 31))
613    elapsed = time.monotonic() - start
614    try:
615        record(telemetry.snapshot())
616    except (ClientError, ValueError):
617        sample_errors += 1
618    launches = [row["_launch_ns"] for row in requests if "_launch_ns" in row]
619    if launches:
620        for row in requests:
621            # The monotonic clock has meaning only inside this run; expose phase-relative offsets.
622            row["launch_offset_s"] = round((row.pop("_launch_ns") / 1e9) - start, 4)
623    launch_spread = round((max(launches) - min(launches)) / 1e9, 4) if launches else None
624    latencies = [r["latency_s"] for r in requests if r["ok"]]
625    ttfts = [r["ttft_s"] for r in requests if r["ok"] and r["ttft_s"] is not None]
626    tokens = [r["completion_tokens"] for r in requests if r["ok"]]
627    token_count_complete = (bool(tokens) and all(type(value) is int for value in tokens) and
628                            (kind == "overload" or len(tokens) == len(requests)))
629    output_tokens = sum(tokens) if token_count_complete else None
630    rejected = sum(r["error_code"] == "admission_full" for r in requests)
631    timed_out_count = sum(r["error_code"] == "queue_wait_timeout" for r in requests)
632    expected_overload = rejected + timed_out_count
633    unexpected_failures = sum(not r["ok"] and r["error_code"] not in
634                              ("admission_full", "queue_wait_timeout") for r in requests)
635    passed = (sum(bool(r["ok"]) for r in requests) > 0 and expected_overload > 0 and
636              unexpected_failures == 0) if kind == "overload" else all(r["ok"] for r in requests)
637    def counter_delta(key):
638        if (first_sample is None or last_sample is None or
639                first_sample.get("instance_id") != last_sample.get("instance_id") or
640                type(first_sample.get(key)) is not int or type(last_sample.get(key)) is not int):
641            return None
642        return last_sample[key] - first_sample[key] if last_sample[key] >= first_sample[key] else None
643    return {"kind": kind, "requested": count, "client_workers": concurrency,
644            "passed": passed,
645            "duration_s": round(elapsed, 4), "requests": requests, "telemetry_samples": samples,
646            "telemetry_sample_errors": sample_errors, "telemetry_samples_omitted": samples_omitted,
647            "summary": {"successful": sum(bool(r["ok"]) for r in requests),
648                        "launch_spread_s": launch_spread,
649                        "failed": unexpected_failures if kind == "overload" else sum(not r["ok"] for r in requests),
650                        "expected_overload": expected_overload if kind == "overload" else 0,
651                        "admission_full": rejected if kind == "overload" else 0,
652                        "queue_wait_timeout": timed_out_count if kind == "overload" else 0,
653                        "admission_rejected_delta": counter_delta("admission_rejected"),
654                        "queue_timeouts_delta": counter_delta("queue_timeouts"),
655                        "p50_latency_s": _percentile(latencies, 0.5),
656                        "p95_latency_s": _percentile(latencies, 0.95),
657                        "p50_ttft_s": _percentile(ttfts, 0.5),
658                        "p95_ttft_s": _percentile(ttfts, 0.95),
659                        "output_tokens": output_tokens,
660                        "output_tok_s": round(output_tokens / elapsed, 3)
661                        if output_tokens is not None and elapsed > 0 else None,
662                        "peak_active": peaks.get("active"), "peak_queued": peaks.get("queued"),
663                        "peak_waiting": peaks.get("waiting"),
664                        "peak_occupied_slots": peaks.get("occupied_slots"), "peak_groups": peaks.get("groups"),
665                        "peak_admission_rejected": peaks.get("admission_rejected")}}
666
667
668def _write_new(path: Path, data: bytes) -> None:
669    descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
670    try:
671        with os.fdopen(descriptor, "wb") as stream:
672            stream.write(data)
673            stream.flush()
674            os.fsync(stream.fileno())
675    except BaseException:
676        path.unlink(missing_ok=True)
677        raise
678
679
680def _progress_write(path: Path, record: dict, *, first: bool = False) -> None:
681    encoded = (json.dumps(record, ensure_ascii=False, sort_keys=True, allow_nan=False) + "\n").encode("utf-8")
682    if len(encoded) > 4096:
683        raise ProfileError("benchmark progress record exceeded 4 KiB", 6)
684    if first:
685        _write_new(path, encoded)
686        return
687    temporary = path.with_name(".progress-" + uuid.uuid4().hex + ".tmp")
688    try:
689        _write_new(temporary, encoded)
690        _atomic_mod.replace(temporary, path)
691    finally:
692        temporary.unlink(missing_ok=True)
693
694
695def progress(path: Path) -> dict:
696    """Read only bounded phase evidence; a running record does not prove liveness."""
697    target = (path / "progress.json" if path.is_dir() else
698              path.with_name("progress.json") if path.name == "results.json" else path)
699    try:
700        details = target.lstat()
701        if not stat.S_ISREG(details.st_mode) or details.st_size > 4096 or \
702                (os.name == "posix" and (posix_owner.owner_only_wrong(target, details))):
703            raise ProfileError(posix_owner.owner_only_text("benchmark progress must be an owner-only regular file under 4 KiB", target), 5)
704        record = json.loads(target.read_text(encoding="utf-8"))
705    except (OSError, UnicodeError, ValueError) as exc:
706        if isinstance(exc, ProfileError):
707            raise
708        raise ProfileError("cannot read benchmark progress", 5) from None
709    phases = record.get("planned_phases") if isinstance(record, dict) else None
710    if (not isinstance(record, dict) or set(record) != {"schema_version", "kind", "suite", "instance_id",
711                                                "started_at", "updated_at", "state", "planned_phases",
712                                                "completed_phases", "current_phase", "last_completed",
713                                                "successful"} or
714            type(record.get("schema_version")) is not int or record["schema_version"] != 1 or
715            record.get("kind") != "strata.serving.benchmark.progress" or
716            record.get("suite") not in SUITES or not re.fullmatch(r"[0-9a-f]{32}", str(record.get("instance_id"))) or
717            not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\+00:00",
718                             str(record.get("started_at"))) or
719            not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\+00:00",
720                             str(record.get("updated_at"))) or
721            record.get("state") not in ("running", "report_saved", "cancelled") or
722            not isinstance(phases, list) or not 1 <= len(phases) <= 21 or
723            any(phase not in ("warmup", "serial", "mixed", "overload", "recovery",
724                              "cancel_active", "cancel_queued", "cancel_prefill") for phase in phases) or
725            type(record.get("completed_phases")) is not int or
726            not 0 <= record["completed_phases"] <= len(phases) or
727            record.get("current_phase") not in (None, *phases) or
728            record.get("last_completed") not in (None, *phases) or
729            (record["state"] == "running" and record.get("successful") is not None) or
730            (record["state"] in ("report_saved", "cancelled") and type(record.get("successful")) is not bool) or
731            (record["state"] == "cancelled" and record.get("successful") is not False)):
732        raise ProfileError("benchmark progress has an unsupported shape", 5)
733    if record["state"] in ("report_saved", "cancelled"):
734        report = load(target.parent)
735        if (report["suite"] != record["suite"] or report["instance_id"] != record["instance_id"] or
736                report["successful"] != record["successful"] or
737                report.get("planned_phases") != record["planned_phases"] or
738                len(report["phases"]) != record["completed_phases"] or
739                bool(report.get("cancelled")) != (record["state"] == "cancelled")):
740            raise ProfileError("benchmark progress and report do not match", 5)
741    return record
742
743
744def run(endpoint: Endpoint, telemetry: Endpoint, out: Path, *, suite: str = "serving-smoke",
745        concurrency: int = 4, repeat: int = 1, request_timeout: float = 120,
746        profile_identity: dict | None = None, condition: str | None = None,
747        require_managed_match: bool = False) -> dict:
748    if suite not in SUITES:
749        raise ProfileError("unknown serving benchmark suite")
750    maximum = 64 if suite == "parallel-overload-v1" else 16
751    if not 1 <= concurrency <= maximum or not 1 <= repeat <= 5 or not 1 <= request_timeout <= 600:
752        raise ProfileError(f"concurrency must be 1..{maximum}, repeat 1..5 and request timeout 1..600 seconds")
753    if condition is not None and not re.fullmatch(r"[a-z][a-z0-9_-]{0,39}", condition):
754        raise ProfileError("benchmark condition must be a lowercase name up to 40 characters")
755    if out.exists() or out.is_symlink():
756        raise ProfileError("benchmark output directory already exists", 2)
757    before = telemetry.snapshot()
758    instance = (before.get("instance") or {}).get("id")
759    if not instance or (before.get("model") or {}).get("loaded") is not True:
760        raise ProfileError("benchmark needs a loaded Strata instance with versioned telemetry", 5)
761    managed_before = None
762    if require_managed_match:
763        managed_before = _managed_match(profile_identity or {}, endpoint.root, before)
764        if not managed_before["matched"]:
765            raise ProfileError("managed benchmark preflight failed: " + managed_before["reason"], 5)
766    if suite == "parallel-overload-v1":
767        work = before.get("work") or {}
768        limit = work.get("admission_limit")
769        deadline = work.get("queue_timeout_s")
770        if (type(limit) is not int or limit < 1 or type(deadline) not in (int, float) or
771                not math.isfinite(deadline) or deadline <= 0):
772            raise ProfileError("overload suite requires a server with max_queue and queue_timeout configured", 5)
773        if concurrency <= limit:
774            raise ProfileError(f"overload concurrency must exceed the admission limit ({limit})", 2)
775    slots = None
776    if suite in ("parallel-cancel-v1", "parallel-prefill-cancel-v1"):
777        work = before.get("work") or {}
778        slots = work.get("slots_effective")
779        if (type(slots) is not int or not 1 <= slots <= 16 or
780                type(work.get("client_disconnect_cancels")) is not int):
781            raise ProfileError("cancellation suite requires 1..16 effective slots and disconnect telemetry", 5)
782        if suite == "parallel-cancel-v1":
783            if (type(work.get("max_queue")) is not int or work["max_queue"] < 1 or
784                    type(work.get("queue_timeout_s")) not in (int, float) or
785                    not math.isfinite(work["queue_timeout_s"]) or work["queue_timeout_s"] < 2):
786                raise ProfileError("cancellation suite requires max_queue >= 1 and "
787                                   "queue_timeout >= 2 seconds", 5)
788            if concurrency < slots:
789                raise ProfileError(f"cancellation concurrency must cover all {slots} effective slots", 2)
790        elif slots < 2 or concurrency < 2:
791            raise ProfileError("prefill cancellation suite requires at least two effective slots and concurrency >= 2", 5)
792    _private_mkdir(out, parents=False, exist_ok=False)
793    phases = []
794    started = _utc_now()
795    planned_phases = _planned_phase_kinds(suite, repeat)
796    progress_record = {"schema_version": 1, "kind": "strata.serving.benchmark.progress",
797                       "suite": suite, "instance_id": instance, "started_at": started,
798                       "updated_at": started, "state": "running", "planned_phases": planned_phases,
799                       "completed_phases": 0, "current_phase": None,
800                       "last_completed": None, "successful": None}
801    progress_path = out / "progress.json"
802    _progress_write(progress_path, progress_record, first=True)
803
804    def mark(*, current: str | None = None, completed: str | None = None) -> None:
805        if completed is not None:
806            progress_record["completed_phases"] = len(phases)
807            progress_record["last_completed"] = completed
808        progress_record["current_phase"] = current
809        progress_record["updated_at"] = _utc_now()
810        _progress_write(progress_path, progress_record)
811
812    operator = OperatorCancellation(out)
813    with operator:
814        try:
815            for kind in SUITES[suite]:
816                if operator.event.is_set():
817                    break
818                if kind in ("cancel_active", "cancel_queued", "cancel_prefill"):
819                    mark(current=kind)
820                    phase = _cancel_phase(endpoint, telemetry, kind=kind, slots=slots,
821                                          timeout=request_timeout, operator=operator)
822                    if operator.event.is_set():
823                        break
824                    phases.append(phase)
825                    mark(completed=kind)
826                    continue
827                for _ in range(1 if kind in ("warmup", "recovery") else repeat):
828                    if operator.event.is_set():
829                        break
830                    mark(current=kind)
831                    count = 1 if kind in ("warmup", "recovery") else 2 if kind == "serial" else concurrency
832                    workers = concurrency if kind in ("mixed", "overload") else 1
833                    phase = _phase(endpoint, telemetry, kind=kind, count=count,
834                                   concurrency=workers, timeout=request_timeout, operator=operator)
835                    if operator.event.is_set():
836                        break
837                    phases.append(phase)
838                    mark(completed=kind)
839                    if not phases[-1]["passed"] and kind != "overload":
840                        break
841                if operator.event.is_set() or (phases and not phases[-1]["passed"] and kind != "overload"):
842                    break
843        finally:
844            try:
845                after = telemetry.snapshot()
846            except (ClientError, ValueError):
847                after = {}
848            cancelled = operator.event.is_set() or operator.path.exists()
849            success = (not cancelled and len(phases) == len(planned_phases)
850                       and all(p["passed"] for p in phases)
851                       and (after.get("instance") or {}).get("id") == instance)
852            managed_after = (_managed_match(profile_identity or {}, endpoint.root, after)
853                             if require_managed_match else None)
854            if require_managed_match and (not managed_after["matched"] or
855                                          managed_after.get("instance_id") != managed_before.get("instance_id")):
856                success = False
857            report = {"schema_version": SCHEMA, "kind": "strata.serving.benchmark",
858                      "run_id": uuid.uuid4().hex, "suite": suite, "started_at": started,
859                      "finished_at": _utc_now(), "server_root": endpoint.root,
860                      "condition": condition, "environment": _environment(before),
861                      "profile_identity": profile_identity,
862                      "profile_running_match": "managed_launch_checked" if require_managed_match and success else "unverified",
863                      "profile_running_check": {"before": managed_before, "after": managed_after}
864                      if require_managed_match else None,
865                      "instance_id": instance, "model_id": (before.get("model") or {}).get("id"),
866                      "planned_phases": planned_phases,
867                      "before": _sample(before), "after": _sample(after), "phases": phases,
868                      "successful": success, "cancelled": cancelled,
869                      "limitations": ["client-observed timings; no synchronized backend clock",
870                                      "missing telemetry samples are not zero",
871                                      "no engine batch-window or stage mapping measurement",
872                                      "condition is operator-supplied; monitor attachment is not verified",
873                                      "environment fields come from server telemetry, not hardware attestation",
874                                      "managed launch is checked only at the beginning and end; post-start changes are not continuously verified"
875                                      if require_managed_match else
876                                      "selected local profile is not authenticated as the running instance's config",
877                                      "driver and model artifact hashes not verified by this suite"] +
878                                     (["client-disconnect cancellation is inferred from a server counter and "
879                                       "request disappearance; run without unrelated clients"]
880                                      if suite in ("parallel-cancel-v1", "parallel-prefill-cancel-v1") else [])}
881            encoded = (json.dumps(report, ensure_ascii=False, indent=2, allow_nan=False) + "\n").encode("utf-8")
882            if len(encoded) > MAX_REPORT_BYTES:
883                raise ProfileError("benchmark report exceeded 4 MiB", 6)
884            _write_new(out / "results.json", encoded)
885            progress_record.update({"state": "cancelled" if cancelled else "report_saved", "successful": success,
886                                    "current_phase": None, "updated_at": _utc_now()})
887            _progress_write(progress_path, progress_record)
888    return report
889
890
891def load(path: Path) -> dict:
892    target = path / "results.json" if path.is_dir() else path
893    try:
894        if not stat.S_ISREG(target.lstat().st_mode) or target.stat().st_size > MAX_REPORT_BYTES:
895            raise ProfileError("benchmark report must be a regular file under 4 MiB", 5)
896        result = json.loads(target.read_text(encoding="utf-8"))
897    except (OSError, UnicodeError, ValueError) as exc:
898        if isinstance(exc, ProfileError):
899            raise
900        raise ProfileError("cannot read benchmark report", 5) from None
901    planned = result.get("planned_phases") if isinstance(result, dict) else None
902    if not isinstance(result, dict) or type(result.get("schema_version")) is not int or \
903            result.get("schema_version") != SCHEMA or result.get("kind") != "strata.serving.benchmark" or \
904            not isinstance(result.get("phases"), list) or len(result["phases"]) > 21 or \
905            not re.fullmatch(r"[0-9a-f]{32}", str(result.get("run_id", ""))) or \
906            not isinstance(result.get("suite"), str) or result["suite"] not in SUITES or \
907            (result.get("condition") is not None and
908             (not isinstance(result["condition"], str) or
909              not re.fullmatch(r"[a-z][a-z0-9_-]{0,39}", result["condition"]))) or \
910            not re.fullmatch(r"[0-9a-f]{32}", str(result.get("instance_id", ""))) or \
911            type(result.get("successful")) is not bool or \
912            ("cancelled" in result and type(result["cancelled"]) is not bool) or \
913            (result.get("cancelled") is True and result["successful"] is not False) or \
914            (result.get("model_id") is not None and
915             (not isinstance(result["model_id"], str) or len(result["model_id"]) > 120 or
916              not result["model_id"].isprintable())) or \
917            not all(isinstance(phase, dict) and isinstance(phase.get("summary"), dict) and
918                    phase.get("kind") in ("warmup", "serial", "mixed", "overload", "recovery",
919                                          "cancel_active", "cancel_queued", "cancel_prefill") and
920                    type(phase.get("requested")) is int and
921                    type(phase.get("client_workers")) is int and
922                    type(phase["summary"].get("successful")) is int and
923                    type(phase["summary"].get("failed")) is int and
924                    ("passed" not in phase or type(phase["passed"]) is bool) and
925                    (phase.get("kind") not in ("overload", "cancel_active", "cancel_queued", "cancel_prefill") or
926                     type(phase.get("passed")) is bool) and
927                    (phase.get("kind") not in ("cancel_active", "cancel_queued", "cancel_prefill") or
928                     ("client_disconnect_delta" in phase["summary"] and
929                      (phase["summary"]["client_disconnect_delta"] is None or
930                       type(phase["summary"]["client_disconnect_delta"]) is int) and
931                      type(phase["summary"].get("target_state_seen")) is bool and
932                      (phase.get("kind") != "cancel_prefill" or
933                       type(phase["summary"].get("prompt_read_seen")) is bool) and
934                      type(phase["summary"].get("settled")) is bool)) and
935                    all(key in phase["summary"] for key in ("p95_latency_s", "output_tok_s",
936                                                            "peak_occupied_slots"))
937                    for phase in result["phases"]):
938        raise ProfileError("unsupported benchmark report", 5)
939    kinds = [phase["kind"] for phase in result["phases"]]
940    valid_plans = [_planned_phase_kinds(result["suite"], repeat) for repeat in range(1, 6)]
941    if (planned is not None and
942            (not isinstance(planned, list) or planned not in valid_plans or
943             kinds != planned[:len(kinds)] or
944             (result["successful"] and len(kinds) != len(planned)))) or \
945            (result["successful"] and
946             (kinds not in valid_plans or any(phase.get("passed") is False
947                                              for phase in result["phases"]))):
948        raise ProfileError("unsupported benchmark report", 5)
949    return result
950
951
952def summary(report: dict) -> dict:
953    fields = ("successful", "failed", "expected_overload", "admission_full", "queue_wait_timeout",
954              "launch_spread_s",
955              "admission_rejected_delta",
956              "queue_timeouts_delta", "client_disconnect_delta", "target_state_seen", "client_closed",
957              "first_content_seen", "companion_successful", "settled",
958              "p50_latency_s", "p95_latency_s", "p50_ttft_s", "p95_ttft_s",
959              "output_tokens", "output_tok_s", "peak_active", "peak_queued", "peak_waiting",
960              "peak_occupied_slots", "peak_groups", "peak_admission_rejected")
961    rows = []
962    for phase in report["phases"]:
963        rows.append({"kind": phase["kind"], "requested": phase["requested"],
964                     "passed": phase.get("passed", phase["summary"]["failed"] == 0),
965                     "client_workers": phase["client_workers"],
966                     **{key: phase["summary"].get(key) for key in fields}})
967    return {"run_id": report["run_id"], "suite": report["suite"],
968            "condition": report.get("condition"),
969            "profile_running_match": report.get("profile_running_match", "unverified"),
970            "instance_id": report["instance_id"], "model_id": report["model_id"],
971            "successful": report["successful"], "cancelled": report.get("cancelled", False),
972            "phases": rows,
973            "planned_phase_count": len(report["planned_phases"])
974            if isinstance(report.get("planned_phases"), list) else None,
975            "completed_phase_count": len(rows)}
976
977
978def _workload_signature(phase: dict) -> tuple:
979    rows = phase.get("requests")
980    if not isinstance(rows, list) or len(rows) > 64:
981        raise ProfileError("benchmark comparison needs bounded request evidence", 5)
982    signatures = []
983    for row in rows:
984        if not isinstance(row, dict) or not re.fullmatch(r"[0-9a-f]{64}", str(row.get("prompt_sha256", ""))) or \
985                type(row.get("max_tokens")) is not int or not 1 <= row["max_tokens"] <= 65536 or \
986                not isinstance(row.get("label"), str) or not re.fullmatch(r"[a-z_]{1,40}", row["label"]):
987            raise ProfileError("benchmark comparison needs valid request fingerprints", 5)
988        signatures.append((row["prompt_sha256"], row["max_tokens"], row["label"]))
989    return (phase["kind"], phase["requested"], phase["client_workers"], tuple(sorted(signatures)))
990
991
992def _metric(value: object) -> float | None:
993    if type(value) not in (int, float) or not 0 <= value <= 1e9:
994        return None
995    return float(value) if math.isfinite(value) else None
996
997
998def _change(baseline: object, candidate: object) -> dict:
999    old, new = _metric(baseline), _metric(candidate)
1000    return {"baseline": old, "candidate": new,
1001            "delta": round(new - old, 4) if old is not None and new is not None else None,
1002            "delta_percent": round(100 * (new / old - 1), 2)
1003            if old is not None and new is not None and old > 0 else None}
1004
1005
1006def compare(baseline: dict, candidate: dict) -> dict:
1007    """Compare two saved runs without claiming hardware or monitor-state attestation."""
1008    if not baseline["successful"] or not candidate["successful"]:
1009        raise ProfileError("benchmark comparison requires two successful runs", 5)
1010    if baseline["run_id"] == candidate["run_id"]:
1011        raise ProfileError("benchmark comparison needs two distinct runs", 2)
1012    if (baseline["suite"] != candidate["suite"] or baseline["model_id"] != candidate["model_id"] or
1013            not baseline["model_id"]):
1014        raise ProfileError("benchmark suite and model ID must match", 5)
1015    old_phases, new_phases = baseline["phases"], candidate["phases"]
1016    if len(old_phases) != len(new_phases) or not old_phases:
1017        raise ProfileError("benchmark phase counts differ", 5)
1018    if any(_workload_signature(old) != _workload_signature(new)
1019           for old, new in zip(old_phases, new_phases)):
1020        raise ProfileError("benchmark request workload or concurrency differs", 5)
1021
1022    warnings = []
1023    old_profile = baseline.get("profile_identity")
1024    new_profile = candidate.get("profile_identity")
1025    old_profile = old_profile if isinstance(old_profile, dict) else {}
1026    new_profile = new_profile if isinstance(new_profile, dict) else {}
1027    old_digest, new_digest = old_profile.get("source_sha256"), new_profile.get("source_sha256")
1028    if old_digest and new_digest:
1029        if old_digest != new_digest:
1030            raise ProfileError("benchmark source config digests differ", 5)
1031    else:
1032        warnings.append("source config identity missing from one or both reports")
1033    if (baseline.get("profile_running_match") != "managed_launch_checked" or
1034            candidate.get("profile_running_match") != "managed_launch_checked"):
1035        warnings.append("source config was not attested as the running server config")
1036
1037    old_env = baseline.get("environment")
1038    new_env = candidate.get("environment")
1039    old_env = old_env if isinstance(old_env, dict) else {}
1040    new_env = new_env if isinstance(new_env, dict) else {}
1041    for key in ("model_context", "slots_effective", "groups", "max_queue", "queue_timeout_s",
1042                "selected_devices", "stages", "devices"):
1043        old, new = old_env.get(key), new_env.get(key)
1044        if old is None or new is None or old == [] or new == []:
1045            warnings.append(f"{key} identity is unavailable in one or both reports")
1046        elif old != new:
1047            raise ProfileError(f"benchmark reported environment differs: {key}", 5)
1048    warnings.append("driver, engine binary, model artifact and monitor attachment are not attested by these reports")
1049
1050    metric_keys = ("p95_ttft_s", "p95_latency_s", "output_tok_s", "admission_full",
1051                   "queue_wait_timeout", "admission_rejected_delta", "queue_timeouts_delta",
1052                   "client_disconnect_delta", "companion_successful", "launch_spread_s",
1053                   "peak_waiting", "peak_queued")
1054    phases = []
1055    for index, (old, new) in enumerate(zip(old_phases, new_phases)):
1056        phases.append({"index": index, "kind": old["kind"], "requested": old["requested"],
1057                       "client_workers": old["client_workers"],
1058                       "duration_s": _change(old.get("duration_s"), new.get("duration_s")),
1059                       "metrics": {key: _change(old["summary"].get(key), new["summary"].get(key))
1060                                   for key in metric_keys}})
1061    primary_kind = next((kind for kind in ("mixed", "overload", "serial", "cancel_prefill",
1062                                           "cancel_active", "cancel_queued", "recovery")
1063                         if any(phase["kind"] == kind for phase in phases)), phases[0]["kind"])
1064    primary = [phase for phase in phases if phase["kind"] == primary_kind]
1065    if len(primary) < 3:
1066        warnings.append("fewer than three measured primary phases; repeat the workload for qualification")
1067    medians = {}
1068    for key in ("p95_ttft_s", "p95_latency_s", "output_tok_s"):
1069        old_values = [phase["metrics"][key]["baseline"] for phase in primary]
1070        new_values = [phase["metrics"][key]["candidate"] for phase in primary]
1071        medians[key] = _change(statistics.median(old_values) if all(x is not None for x in old_values) else None,
1072                               statistics.median(new_values) if all(x is not None for x in new_values) else None)
1073    return {"schema_version": 1, "kind": "strata.serving.benchmark_comparison",
1074            "suite": baseline["suite"], "model_id": baseline["model_id"],
1075            "baseline": {"run_id": baseline["run_id"], "condition": baseline.get("condition"),
1076                         "profile_running_match": baseline.get("profile_running_match", "unverified")},
1077            "candidate": {"run_id": candidate["run_id"], "condition": candidate.get("condition"),
1078                          "profile_running_match": candidate.get("profile_running_match", "unverified")},
1079            "workload_match": True, "qualification": "provisional",
1080            "primary_kind": primary_kind, "primary_phases": len(primary),
1081            "median_primary_metrics": medians, "phases": phases, "warnings": warnings}
1082
1083
1084def format_comparison(value: dict) -> str:
1085    def pair(metric: dict) -> str:
1086        return (f"{metric['baseline']:g} -> {metric['candidate']:g}"
1087                if metric["baseline"] is not None and metric["candidate"] is not None else "unavailable")
1088
1089    lines = [f"{value['suite']} - provisional comparison ({value['primary_phases']} "
1090             f"{value['primary_kind']} phases)",
1091             f"Baseline {value['baseline']['condition'] or value['baseline']['run_id']}  "
1092             f"Candidate {value['candidate']['condition'] or value['candidate']['run_id']}",
1093             f"Managed launch: baseline {value['baseline']['profile_running_match']}, "
1094             f"candidate {value['candidate']['profile_running_match']}"]
1095    for label, key in (("p95 TTFT", "p95_ttft_s"), ("p95 latency", "p95_latency_s"),
1096                       ("output throughput", "output_tok_s")):
1097        metric = value["median_primary_metrics"][key]
1098        if metric["baseline"] is None or metric["candidate"] is None:
1099            lines.append(f"{label}: unavailable")
1100        else:
1101            unit = " tok/s" if key == "output_tok_s" else " s"
1102            change = (f"{metric['delta_percent']:+.2f}%" if metric["delta_percent"] is not None
1103                      else "percent unavailable")
1104            lines.append(f"{label}: {metric['baseline']:.4f}{unit} -> "
1105                         f"{metric['candidate']:.4f}{unit} ({change})")
1106    for phase in value["phases"]:
1107        metrics = phase["metrics"]
1108        if phase["kind"] == "overload":
1109            lines.append(f"overload {phase['index']}: admission full {pair(metrics['admission_full'])}, "
1110                         f"queue timeout {pair(metrics['queue_wait_timeout'])}, "
1111                         f"duration {pair(phase['duration_s'])} s")
1112        elif phase["kind"].startswith("cancel_"):
1113            lines.append(f"{phase['kind']}: disconnects {pair(metrics['client_disconnect_delta'])}, "
1114                         f"companions {pair(metrics['companion_successful'])}, "
1115                         f"duration {pair(phase['duration_s'])} s")
1116    lines.extend(f"Note: {warning}" for warning in value["warnings"])
1117    return "\n".join(lines)
1118
1119
1120def format_summary(value: dict) -> str:
1121    def shown(value):
1122        return "--" if value is None else value
1123
1124    condition = f" [{value['condition']}]" if value.get("condition") else ""
1125    outcome = "cancelled" if value.get("cancelled") else "passed" if value["successful"] else "failed"
1126    lines = [f"{value['suite']}{condition} - {outcome}",
1127             f"Instance {value['instance_id']}  Model {value['model_id']}",
1128             f"Config match {value.get('profile_running_match', 'unverified')}"]
1129    for phase in value["phases"]:
1130        if phase["kind"] in ("cancel_active", "cancel_queued"):
1131            lines.append(f"{phase['kind']}: {'passed' if phase['passed'] else 'failed'}  "
1132                         f"companions {shown(phase.get('companion_successful'))}")
1133        else:
1134            lines.append(f"{phase['kind']}: {phase['successful']}/{phase['requested']} requests  "
1135                         f"p95 TTFT {shown(phase.get('p95_ttft_s'))} s  "
1136                         f"p95 latency {shown(phase.get('p95_latency_s'))} s  "
1137                         f"output {shown(phase.get('output_tok_s'))} tok/s")
1138        if phase["kind"] == "overload":
1139            lines.append(f"  launch spread {shown(phase.get('launch_spread_s'))} s  "
1140                         f"rejected {shown(phase.get('admission_full'))}  "
1141                         f"timed out {shown(phase.get('queue_wait_timeout'))}  "
1142                         f"unexpected failures {shown(phase.get('failed'))}  "
1143                         f"rejected delta {shown(phase.get('admission_rejected_delta'))}  "
1144                         f"timeout delta {shown(phase.get('queue_timeouts_delta'))}")
1145        if phase["kind"] in ("cancel_active", "cancel_queued"):
1146            lines.append(f"  target seen {shown(phase.get('target_state_seen'))}  "
1147                         f"client closed {shown(phase.get('client_closed'))}  "
1148                         f"disconnect delta {shown(phase.get('client_disconnect_delta'))}  "
1149                         f"companions completed {shown(phase.get('companion_successful'))}  "
1150                         f"settled {shown(phase.get('settled'))}")
1151        lines.append(f"  peak active {shown(phase.get('peak_active'))}  "
1152                     f"occupied {shown(phase.get('peak_occupied_slots'))}  "
1153                     f"engine waiting {shown(phase.get('peak_waiting'))}  "
1154                     f"queued {shown(phase.get('peak_queued'))}  groups {shown(phase.get('peak_groups'))}")
1155    return "\n".join(lines)
1156
1157
1158def _md_cell(value: object, *, limit: int = 120) -> str:
1159    """Bound an untrusted report label before placing it in a Markdown cell."""
1160    if value is None:
1161        return "unavailable"
1162    raw = str(value)
1163    raw = " ".join(part for part in raw.split() if part)
1164    raw = "".join(char for char in raw[:limit] if char.isprintable())
1165    for char in ("\\", "|", "*", "_", "[", "]", "<", ">", "`"):
1166        raw = raw.replace(char, "\\" + char)
1167    return raw or "unavailable"
1168
1169
1170def _md_number(value: object, *, digits: int = 3) -> str:
1171    measured = _metric(value)
1172    if measured is None:
1173        return "unavailable"
1174    return str(int(measured)) if measured.is_integer() else f"{measured:.{digits}f}"
1175
1176
1177def _md_time(value: object) -> str:
1178    return value if isinstance(value, str) and len(value) <= 40 and re.fullmatch(
1179        r"[0-9TZ:+.\-]+", value) else "unavailable"
1180
1181
1182def markdown_report(report: dict) -> str:
1183    """Render a shareable, bounded summary without endpoint, paths or request text."""
1184    compact = summary(report)
1185    incomplete = (compact["planned_phase_count"] is not None and
1186                  compact["completed_phase_count"] < compact["planned_phase_count"])
1187    result_label = ("Cancelled" if compact["cancelled"] else "Passed" if compact["successful"]
1188                    else "Incomplete" if incomplete else "Failed")
1189    rows = ["# Strata serving benchmark", "",
1190            "This report summarizes client-observed requests and server-reported telemetry. "
1191            "It is not a hardware or model-quality qualification.", "",
1192            "| Run | Value |", "| --- | --- |",
1193            f"| Result | {result_label} |",
1194            f"| Phases | {compact['completed_phase_count']} of {compact['planned_phase_count'] if compact['planned_phase_count'] is not None else 'unavailable'} |",
1195            f"| Suite | {_md_cell(compact['suite'])} |",
1196            f"| Run ID | {_md_cell(compact['run_id'])} |",
1197            f"| Started (UTC) | {_md_time(report.get('started_at'))} |",
1198            f"| Finished (UTC) | {_md_time(report.get('finished_at'))} |",
1199            f"| Operator condition | {_md_cell(compact.get('condition'))} |",
1200            f"| Model ID | {_md_cell(compact.get('model_id'))} |",
1201            f"| Instance ID | {_md_cell(compact.get('instance_id'))} |",
1202            f"| Managed launch check | {_md_cell(compact.get('profile_running_match'))} |",
1203            "", "## Measured phases", "",
1204            "| Phase | Clients | Succeeded | Failed | p95 TTFT (s) | p95 latency (s) | Output (tok/s) | Peak active | Peak queued | Peak slots | Peak groups | Result |",
1205            "| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | --- |"]
1206    for phase in compact["phases"][:21]:
1207        rows.append("| " + " | ".join((
1208            _md_cell(phase.get("kind")), _md_number(phase.get("client_workers")),
1209            _md_number(phase.get("successful")), _md_number(phase.get("failed")),
1210            _md_number(phase.get("p95_ttft_s")), _md_number(phase.get("p95_latency_s")),
1211            _md_number(phase.get("output_tok_s")), _md_number(phase.get("peak_active")),
1212            _md_number(phase.get("peak_queued")), _md_number(phase.get("peak_occupied_slots")),
1213            _md_number(phase.get("peak_groups")), "Passed" if phase.get("passed") else "Failed",
1214        )) + " |")
1215    exceptional = [phase for phase in compact["phases"] if phase.get("kind") in
1216                   ("overload", "cancel_active", "cancel_queued", "cancel_prefill")]
1217    if exceptional:
1218        rows += ["", "## Admission and cancellation observations", "",
1219                 "| Phase | Expected overload | Admission full | Queue timeout | Disconnect delta | Companion completed | Settled |",
1220                 "| --- | ---: | ---: | ---: | ---: | ---: | --- |"]
1221        for phase in exceptional:
1222            rows.append("| " + " | ".join((
1223                _md_cell(phase.get("kind")), _md_number(phase.get("expected_overload")),
1224                _md_number(phase.get("admission_full")), _md_number(phase.get("queue_wait_timeout")),
1225                _md_number(phase.get("client_disconnect_delta")),
1226                _md_number(phase.get("companion_successful")),
1227                "Yes" if phase.get("settled") is True else
1228                "No" if phase.get("settled") is False else "unavailable",
1229            )) + " |")
1230    environment = report.get("environment")
1231    environment = environment if isinstance(environment, dict) else {}
1232    selected = environment.get("selected_devices")
1233    selected = ", ".join(_md_number(item) for item in selected[:16]) if isinstance(selected, list) else "unavailable"
1234    rows += ["", "## Server-reported environment", "",
1235             "| Field | Value |", "| --- | --- |",
1236             f"| Context tokens | {_md_number(environment.get('model_context'))} |",
1237             f"| Effective slots | {_md_number(environment.get('slots_effective'))} |",
1238             f"| Pipeline groups | {_md_number(environment.get('groups'))} |",
1239             f"| Maximum queue | {_md_number(environment.get('max_queue'))} |",
1240             f"| Selected device indices | {selected or 'unavailable'} |"]
1241    devices = environment.get("devices")
1242    if isinstance(devices, list):
1243        for device in devices[:16]:
1244            if isinstance(device, dict):
1245                rows.append(f"| Reported device {_md_number(device.get('index'))} | "
1246                            f"{_md_cell(device.get('name'))} |")
1247    rows += ["", "## Measurement limits", "",
1248             "- Missing readings appear as `unavailable`; they are not zero.",
1249             "- The condition label is operator supplied. Monitor attachment is not verified.",
1250             "- Device names and serving configuration come from server telemetry. Driver, topology, "
1251             "engine binary and model artifact hashes are not attested here.",
1252             "- A managed launch check, when present, covers the beginning and end of the run only.",
1253             "- Timings are observed by the client. This report does not measure GPU kernel occupancy "
1254             "or independently synchronize backend clocks.", ""]
1255    return "\n".join(rows)
1256
1257
1258def markdown_comparison(comparison: dict) -> str:
1259    """Render the workload-checked comparison with provisional status visible."""
1260    rows = ["# Strata serving benchmark comparison", "",
1261            "**Provisional comparison.** The saved runs passed workload checks; environment "
1262            "and monitor attachment still need independent qualification.", "",
1263            "| Run | Baseline | Candidate |", "| --- | --- | --- |",
1264            f"| Suite | {_md_cell(comparison.get('suite'))} | {_md_cell(comparison.get('suite'))} |",
1265            f"| Model ID | {_md_cell(comparison.get('model_id'))} | {_md_cell(comparison.get('model_id'))} |",
1266            f"| Run ID | {_md_cell(comparison['baseline'].get('run_id'))} | {_md_cell(comparison['candidate'].get('run_id'))} |",
1267            f"| Operator condition | {_md_cell(comparison['baseline'].get('condition'))} | {_md_cell(comparison['candidate'].get('condition'))} |",
1268            f"| Managed launch check | {_md_cell(comparison['baseline'].get('profile_running_match'))} | {_md_cell(comparison['candidate'].get('profile_running_match'))} |",
1269            "", f"Primary phase: {_md_cell(comparison.get('primary_kind'))} "
1270            f"({_md_number(comparison.get('primary_phases'))} measured phase(s)).", "",
1271            "| Median primary metric | Baseline | Candidate | Change |",
1272            "| --- | ---: | ---: | ---: |"]
1273    for label, key, unit in (("p95 TTFT", "p95_ttft_s", "s"),
1274                             ("p95 latency", "p95_latency_s", "s"),
1275                             ("Output throughput", "output_tok_s", "tok/s")):
1276        metric = comparison["median_primary_metrics"][key]
1277        change = metric.get("delta_percent")
1278        change_text = (f"{change:+.2f}%" if type(change) in (int, float) and
1279                       math.isfinite(change) and abs(change) <= 1e9 else "unavailable")
1280        rows.append(f"| {label} ({unit}) | {_md_number(metric.get('baseline'))} | "
1281                    f"{_md_number(metric.get('candidate'))} | {change_text} |")
1282    rows += ["", "## Per-phase results", "",
1283             "| Phase | Clients | Baseline p95 TTFT (s) | Candidate p95 TTFT (s) | Baseline output (tok/s) | Candidate output (tok/s) |",
1284             "| --- | ---: | ---: | ---: | ---: | ---: |"]
1285    for phase in comparison["phases"][:21]:
1286        metrics = phase["metrics"]
1287        rows.append("| " + " | ".join((
1288            _md_cell(phase.get("kind")), _md_number(phase.get("client_workers")),
1289            _md_number(metrics["p95_ttft_s"].get("baseline")),
1290            _md_number(metrics["p95_ttft_s"].get("candidate")),
1291            _md_number(metrics["output_tok_s"].get("baseline")),
1292            _md_number(metrics["output_tok_s"].get("candidate")),
1293        )) + " |")
1294    rows += ["", "## Comparison limits", ""]
1295    rows.extend(f"- {_md_cell(warning, limit=240)}" for warning in comparison.get("warnings", [])[:32])
1296    rows += ["- A percentage change describes the observed result; it does not by itself "
1297             "establish an improvement or hardware qualification.", ""]
1298    return "\n".join(rows)
1299
1300
1301def write_markdown(path: Path, content: str) -> None:
1302    """Create a shareable report file without replacing an earlier result."""
1303    encoded = content.encode("utf-8")
1304    if len(encoded) > 64 * 1024:
1305        raise ProfileError("Markdown benchmark report exceeded 64 KiB", 6)
1306    if path.exists() or path.is_symlink():
1307        raise ProfileError("Markdown output file already exists", 2)
1308    _write_new(path, encoded)