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