okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6e1085c1d
main
1#!/usr/bin/env python3 2"""Replay frozen requests against an already configured, running Strata server. 3 4No launch, restart, model selection, or configuration changes are performed. 5Set STRATA_BENCHMARK_API_KEY if the server needs a bearer token. 6""" 7import argparse 8from datetime import datetime ,timezone 9import gzip 10import hashlib 11import http .client 12import json 13import math 14import os 15from pathlib import Path 16import re 17import socket 18import sys 19import threading 20import time 21from urllib .parse import urlsplit 22 23ROOT = Path (__file__ ).resolve ().parent 24SECRET = os .environ .get ("STRATA_BENCHMARK_API_KEY" ,"" ) 25 26 27def sha (data ): 28return hashlib .sha256 (data ).hexdigest () 29 30 31def utc (): 32return datetime .now (timezone .utc ).isoformat () 33 34 35def error_text (error ): 36text = str (error ) 37return text .replace (SECRET ,"[redacted]" )if SECRET else text 38 39 40def save (path ,value ): 41path .write_text (json .dumps (value ,ensure_ascii = False ,indent = 2 )+ "\n" ,encoding = "utf-8" ) 42 43 44class Client : 45def __init__ (self ,url ,timeout ): 46parsed = urlsplit (url ) 47if (parsed .scheme not in ("http" ,"https" )or not parsed .hostname 48or parsed .username or parsed .password or parsed .query or parsed .fragment 49or parsed .path not in ("" ,"/" )): 50raise ValueError ("--url must be an http(s) origin without credentials, path, query, or fragment" ) 51self .origin ,self .timeout = url .rstrip ("/" ),timeout 52self .host ,self .port = parsed .hostname ,parsed .port 53self .connection_type = http .client .HTTPSConnection if parsed .scheme == "https" else http .client .HTTPConnection 54 55def connection (self ,timeout = None ): 56return self .connection_type (self .host ,self .port ,timeout = timeout or self .timeout ) 57 58def headers (self ,streaming = False ): 59headers = {"Content-Type" :"application/json" } 60if streaming : 61headers ["Accept" ]= "text/event-stream" 62if SECRET : 63headers ["Authorization" ]= "Bearer " + SECRET 64return headers 65 66def json_request (self ,method ,path ,body = None ,timeout = None ): 67connection = self .connection (timeout ) 68try : 69connection .request (method ,path ,body = body ,headers = self .headers ()) 70response = connection .getresponse () 71payload = response .read () 72if response .status != 200 : 73raise ValueError (f" { method } { path } : HTTP { response . status } : { payload [: 4096 ]!r } " ) 74value = json .loads (payload ) 75if not isinstance (value ,dict )or "error" in value : 76raise ValueError (f" { method } { path } : invalid/API error response: { value !r } " ) 77return value 78finally : 79connection .close () 80 81def served_state (self ): 82state = {} 83for path in ("/v1/status" ,"/health" ): 84try : 85state [path ]= {"response" :self .json_request ("GET" ,path ,timeout = min (5 ,self .timeout ))} 86except Exception as error : 87state [path ]= {"error" :error_text (error )} 88return state 89 90def stream (self ,body ,directory ,row ): 91started = time .monotonic () 92connection = self .connection () 93network_socket ,timed_out = [],threading .Event () 94 95def expire (): 96timed_out .set () 97current = network_socket [0 ]if network_socket else connection .sock 98if current is not None : 99try : 100current .shutdown (socket .SHUT_RDWR ) 101except OSError : 102pass 103 104timer = threading .Timer (self .timeout ,expire ) 105timer .daemon = True 106timer .start () 107done ,data = False , [] 108content ,reasoning ,calls = [], [], {} 109row .update (content = "" ,reasoning_content = "" ,tool_calls = [],usage = {},timings = {}, 110finish_reason = None ,client_ttft_s = None ,sse_chunks = 0 ) 111 112def consume (payload ,parsed_log ): 113nonlocal done 114elapsed = time .monotonic ()- started 115if payload == "[DONE]" : 116done = True 117parsed_log .write (json .dumps ({"elapsed_s" :elapsed ,"done" :True })+ "\n" ) 118return 119chunk = json .loads (payload ) 120parsed_log .write (json .dumps ({"elapsed_s" :elapsed ,"chunk" :chunk },ensure_ascii = False )+ "\n" ) 121parsed_log .flush () 122if not isinstance (chunk ,dict )or "error" in chunk : 123raise ValueError (f"Invalid/API error SSE chunk: { chunk !r } " ) 124row ["sse_chunks" ]+= 1 125if "id" in chunk : 126row ["completion_id" ]= chunk ["id" ] 127for key in ("usage" ,"timings" ): 128if key in chunk : 129if not isinstance (chunk [key ],dict ): 130raise ValueError (f"SSE { key } must be an object" ) 131row [key ]= chunk [key ] 132choices = chunk .get ("choices" , []) 133if not isinstance (choices ,list ): 134raise ValueError ("SSE choices must be a list" ) 135for choice in choices : 136if not isinstance (choice ,dict )or choice .get ("index" ,0 )!= 0 : 137raise ValueError ("Replay supports a single completion (index 0)" ) 138if choice .get ("finish_reason" )is not None : 139row ["finish_reason" ]= choice ["finish_reason" ] 140delta = choice .get ("delta" , {}) 141if not isinstance (delta ,dict ): 142raise ValueError ("SSE delta must be an object" ) 143nonempty = False 144for key ,target in (("content" ,content ), ("reasoning_content" ,reasoning )): 145value = delta .get (key ) 146if value is not None and not isinstance (value ,str ): 147raise ValueError (f"Non-string { key } delta" ) 148if value : 149target .append (value ) 150nonempty = True 151deltas = delta .get ("tool_calls" , []) 152if not isinstance (deltas ,list ): 153raise ValueError ("SSE tool_calls must be a list" ) 154for call in deltas : 155if not isinstance (call ,dict ): 156raise ValueError ("SSE tool call must be an object" ) 157index = call .get ("index" ,0 ) 158if type (index )is not int or index < 0 : 159raise ValueError ("Invalid tool-call index" ) 160current = calls .setdefault (index , {"id" :"" ,"type" :"function" ,"function" : {"name" :"" ,"arguments" :"" }}) 161function = call .get ("function" , {}) 162if not isinstance (function ,dict ): 163raise ValueError ("SSE tool-call function must be an object" ) 164for key in ("id" ,"type" ): 165if call .get (key ): 166if not isinstance (call [key ],str ): 167raise ValueError (f"Non-string tool-call { key } " ) 168current [key ]= call [key ] 169nonempty = True 170for key in ("name" ,"arguments" ): 171if function .get (key ): 172if not isinstance (function [key ],str ): 173raise ValueError (f"Non-string function { key } " ) 174current ["function" ][key ]+= function [key ] 175nonempty = True 176if nonempty and row ["client_ttft_s" ]is None : 177row ["client_ttft_s" ]= elapsed 178 179try : 180connection .request ("POST" ,"/v1/chat/completions" ,body = body ,headers = self .headers (streaming = True )) 181if connection .sock is not None : 182network_socket .append (connection .sock ) 183response = connection .getresponse () 184row ["http_status" ]= response .status 185if response .status != 200 : 186payload = response .read (4096 ) 187 (directory / "http-error.bin" ).write_bytes (payload ) 188raise ValueError (f"POST /v1/chat/completions: HTTP { response . status } : { payload !r } " ) 189if not response .getheader ("Content-Type" ,"" ).lower ().startswith ("text/event-stream" ): 190payload = response .read (4096 ) 191 (directory / "http-error.bin" ).write_bytes (payload ) 192raise ValueError (f"Expected text/event-stream, got { payload !r } " ) 193with (directory / "response.sse" ).open ("wb" )as raw , (directory / "stream.jsonl" ).open ("w" ,encoding = "utf-8" )as parsed : 194while not done : 195remaining = self .timeout - (time .monotonic ()- started ) 196if timed_out .is_set ()or remaining <= 0 : 197raise TimeoutError ("Absolute request timeout exceeded" ) 198if network_socket : 199network_socket [0 ].settimeout (remaining ) 200line = response .readline (2 * 1024 * 1024 + 1 ) 201if not line : 202if data : 203consume ("\n" .join (data ),parsed ) 204break 205raw .write (line ) 206raw .flush () 207if len (line )> 2 * 1024 * 1024 : 208raise ValueError ("SSE line exceeds 2 MiB" ) 209text = line .decode ("utf-8" ).rstrip ("\r\n" ) 210if not text : 211if data : 212consume ("\n" .join (data ),parsed ) 213data = [] 214elif not text .startswith (":" ): 215field ,separator ,value = text .partition (":" ) 216if separator and value .startswith (" " ): 217value = value [1 :] 218if field == "data" : 219data .append (value ) 220if timed_out .is_set (): 221raise TimeoutError ("Absolute request timeout exceeded" ) 222if not done or row ["finish_reason" ]is None or not row ["usage" ]: 223raise ValueError ("Incomplete SSE: [DONE], finish reason, and usage are required" ) 224except Exception : 225if timed_out .is_set (): 226raise TimeoutError ("Absolute request timeout exceeded" )from None 227raise 228finally : 229timer .cancel () 230connection .close () 231row .update (content = "" .join (content ),reasoning_content = "" .join (reasoning ), 232tool_calls = [calls [index ]for index in sorted (calls )], 233client_total_s = time .monotonic ()- started ) 234 235 236def frozen (entry ): 237path = (ROOT / entry ["path" ]).resolve () 238if not path .is_relative_to (ROOT )or path .suffix != ".gz" : 239raise ValueError ("Frozen request path must be a .gz file inside the report" ) 240body = gzip .decompress (path .read_bytes ()) 241if sha (body )!= entry ["request_sha256" ]: 242raise ValueError ("Frozen request SHA-256 mismatch: " + str (entry ["id" ])) 243request = json .loads (body ) 244if not isinstance (request ,dict )or request .get ("stream" )is not True : 245raise ValueError ("Frozen request must be a streaming JSON object" ) 246return body ,request 247 248 249def rates (row ): 250timings = row ["timings" ] 251row ["reused_prompt_tokens" ]= timings .get ("cache_n" ) 252row ["fresh_prompt_tokens" ]= timings .get ("prompt_n" ) 253for target ,count ,elapsed in (("engine_prefill_tok_s" ,"prompt_n" ,"prompt_ms" ), 254 ("engine_decode_tok_s" ,"predicted_n" ,"predicted_ms" )): 255n ,ms = timings .get (count ),timings .get (elapsed ) 256row [target ]= n * 1000 / ms if type (n )in (int ,float )and type (ms )in (int ,float )and n >= 0 and ms > 0 else None 257 258 259def eligibility (entry ,request ,row ): 260reasons ,expected = [],entry ["expected_prompt_tokens" ] 261if row ["usage" ].get ("prompt_tokens" )!= expected : 262reasons .append ("usage prompt_tokens differs from frozen expectation" ) 263reused ,fresh = row .get ("reused_prompt_tokens" ),row .get ("fresh_prompt_tokens" ) 264if type (reused )is not int or type (fresh )is not int or fresh + reused != expected : 265reasons .append ("timings prompt_n + cache_n differs from frozen expectation" ) 266measured = entry ["role" ]== "measured" 267if entry ["suite" ]== "decode" : 268if measured and (type (reused )is not int or reused / expected < .999 ): 269reasons .append ("decode reused less than 99.9% of the frozen prefix" ) 270elif entry ["role" ]!= "continuation" and reused != 0 : 271reasons .append ("fresh request unexpectedly reused prompt tokens" ) 272if measured : 273generated = entry .get ("expected_completion_tokens" ,512 ) 274if row ["finish_reason" ]!= "length" or row ["usage" ].get ("completion_tokens" )!= generated or row ["timings" ].get ("predicted_n" )!= generated : 275reasons .append ("measured completion did not consume the exact fixed decode budget" ) 276if row .get ("engine_prefill_tok_s" )is None or row .get ("engine_decode_tok_s" )is None : 277reasons .append ("engine throughput timings are unavailable or invalid" ) 278if entry ["suite" ]== "disk" : 279if row ["finish_reason" ]!= "stop" : 280reasons .append ("disk request did not finish at EOS" ) 281previous = entry .get ("previous_prefix_tokens" ) 282if entry ["role" ]== "continuation" and previous is not None : 283ratio = reused / previous if type (reused )is int and previous > 0 else None 284row ["previous_prefix_reuse_fraction" ]= ratio 285if ratio is None or ratio < .99 : 286reasons .append ("disk continuation reused less than 99% of the previous prefix" ) 287if "expected_needles" in entry : 288try : 289actual = json .loads (row ["content" ]) 290except ValueError : 291actual = None 292row ["needle_grade" ]= {"expected" :entry ["expected_needles" ],"actual" :actual , 293"passed" :actual == entry ["expected_needles" ]} 294if not row ["needle_grade" ]["passed" ]: 295reasons .append ("disk answer differs from the eight frozen needle values" ) 296return reasons 297 298 299def selected (entries ,args ): 300rows = [entry for entry in entries if entry ["suite" ]== args .suite ] 301if args .suite == "disk" : 302rows = [entry for entry in rows if entry ["role" ]== args .disk_phase 303and (args .depth is None or entry ["depth" ]== args .depth ) 304and (args .round is None or entry ["round" ]== args .round )] 305elif args .suite == "decode" : 306rows = [entry for entry in rows if args .round is None or entry ["round" ]== args .round ] 307else : 308warmups = [entry for entry in rows if entry ["role" ]== "warmup" ] 309measured = [entry for entry in rows if entry ["role" ]== "measured" 310and (args .round is None or entry ["round" ]== args .round )] 311rows = warmups + measured if measured else [] 312if not rows : 313raise ValueError ("No requests match the selected suite/round/depth/phase" ) 314return rows 315 316 317def main (): 318parser = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 319parser .add_argument ("--url" ,default = "http://127.0.0.1:18089" ) 320parser .add_argument ("--suite" ,choices = ("confirmation" ,"screen" ,"decode" ,"disk" )) 321parser .add_argument ("--round" ,type = int ) 322parser .add_argument ("--depth" ,type = int ,help = "Disk suite depth filter" ) 323parser .add_argument ("--disk-phase" ,choices = ("initial" ,"continuation" ),default = "initial" ) 324parser .add_argument ("--out" ,type = Path ,required = True ,help = "New output directory; never overwritten" ) 325parser .add_argument ("--timeout" ,type = float ,default = 120 ,help = "Per-request seconds, at least 1 (1M initial needs a larger value)" ) 326parser .add_argument ("--slot-action" ,choices = ("save" ,"restore" ),help = "Only perform this native slot action; no replay or restart" ) 327parser .add_argument ("--slot-filename" ,help = "Explicit safe regular-file basename inside the server's configured slot-save directory" ) 328args = parser .parse_args () 329if args .out .exists (): 330parser .error ("--out must be a new directory" ) 331args .out .mkdir (parents = True ) 332run = {"started_at_utc" :utc (),"harness_sha256" :sha (Path (__file__ ).read_bytes ()), 333"url" :args .url ,"suite" :args .suite ,"round" :args .round ,"depth" :args .depth , 334"disk_phase" :args .disk_phase ,"timeout_s" :args .timeout ,"results" : [],"status" :"running" } 335try : 336if not math .isfinite (args .timeout )or args .timeout < 1 : 337raise ValueError ("--timeout must be finite and at least 1 second" ) 338client = Client (args .url ,args .timeout ) 339if args .slot_action : 340name = args .slot_filename or "" 341if not re .fullmatch (r"[A-Za-z0-9][A-Za-z0-9_.-]{0,254}" ,name )or ".." in name : 342raise ValueError ("--slot-filename must be an explicit safe regular-file basename" ) 343run ["served_before" ]= client .served_state () 344started = time .monotonic () 345action = {"action" :args .slot_action ,"filename" :name ,"status" :"running" } 346run ["slot_action" ]= action 347try : 348action ["response" ]= client .json_request ("POST" ,"/slots/0?action=" + args .slot_action , 349json .dumps ({"filename" :name }).encode ()) 350action ["status" ]= "completed" 351except Exception as error : 352action .update (status = "failed" ,error = error_text (error )) 353raise 354finally : 355action ["client_total_s" ]= time .monotonic ()- started 356run ["served_after" ]= client .served_state () 357else : 358if not args .suite or args .slot_filename : 359raise ValueError ("Use --suite for replay, or --slot-action with --slot-filename" ) 360index_path = ROOT / "requests/index.json" 361index_bytes = index_path .read_bytes () 362run ["index_sha256" ]= sha (index_bytes ) 363entries = selected (json .loads (index_bytes )["requests" ],args ) 364# Preflight every chosen file before sending even the warmup. 365for entry in entries : 366frozen (entry ) 367for ordinal ,entry in enumerate (entries ): 368directory = args .out / (f" { ordinal :03d } -" + re .sub (r"[^A-Za-z0-9_.-]" ,"_" ,str (entry ["id" ]))[:100 ]) 369directory .mkdir () 370row = {"request" :entry ,"harness_sha256" :run ["harness_sha256" ], 371"started_at_utc" :utc (),"status" :"running" ,"eligible" :False , 372"served_before" :client .served_state ()} 373run ["results" ].append (row ) 374try : 375body ,request = frozen (entry ) 376client .stream (body ,directory ,row ) 377rates (row ) 378reasons = eligibility (entry ,request ,row ) 379row .update (status = "completed" ,eligible =not reasons ,ineligible_reasons = reasons ) 380except Exception as error : 381row .update (status = "failed" ,error = error_text (error ),eligible = False ) 382finally : 383row .update (finished_at_utc = utc (),served_after = client .served_state ()) 384save (directory / "result.json" ,row ) 385save (args .out / "run.json" ,run ) 386f" { entry [ 'id' ] } : { row [ 'status' ] } , eligible= { row [ 'eligible' ] } " ,flush = True ) 387if row ["status" ]== "failed" : 388break 389if any (not row ["eligible" ]for row in run ["results" ]): 390raise ValueError ("One or more replay requests failed or were ineligible; inspect actual outputs" ) 391run ["status" ]= "completed" 392except Exception as error : 393run .update (status = "failed" ,error = error_text (error )) 394run ["error" ],file = sys .stderr ) 395finally : 396run ["finished_at_utc" ]= utc () 397save (args .out / "run.json" ,run ) 398return 0 if run ["status" ]== "completed" else 1 399 400 401if __name__ == "__main__" : 402sys .exit (main ())