okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
bcf88b738
main
1"""Reviewed Desktop launch of the same serving benchmark used by the CLI.""" 2 3from __future__import annotations 4 5from strata_control .private_files import private_mkdir as _private_mkdir 6import hashlib 7import errno 8import os 9import re 10import stat 11import time 12from contextlib import contextmanager 13from pathlib import Path 14 15from strata_cli import bench 16from strata_cli .cli import _launch_plan ,_source 17from strata_cli .client import ClientError ,Endpoint 18from strata_control import journal ,profiles ,runtime 19from strata_control .profiles import ProfileError 20from strata_control import posix_owner 21 22 23#: Windows byte-range locks are mandatory: a locked byte cannot be read through any other handle. The lock 24#: therefore sits far past the marker bytes, so another process can still read who holds the lease. 25WINDOWS_LOCK_OFFSET = 1 << 16 26 27def _lease_file (profile :str ,* ,create :bool )-> Path | None : 28if not profiles .PROFILE_ID .fullmatch (profile ): 29raise ProfileError ("benchmark lease needs a saved profile" ) 30directory = profiles .profile_dir () 31if create : 32_private_mkdir (directory ,parents = True ,exist_ok = True ) 33elif not directory .exists (): 34return None 35details = directory .lstat () 36if not stat .S_ISDIR (details .st_mode )or (os .name == "posix" and 37 (posix_owner .owner_only_wrong (directory ,details ))): 38raise ProfileError (posix_owner .owner_only_text ("benchmark lease directory must be owner-only" ,directory ),5 ) 39return directory / f".bench- { profile } .lock" 40 41 42def _lease_descriptor (path :Path ,* ,create :bool )-> int : 43flags = os .O_RDWR | (os .O_CREAT if create else 0 ) 44if hasattr (os ,"O_NOFOLLOW" ): 45flags |= os .O_NOFOLLOW 46descriptor = os .open (path ,flags ,0o600 ) 47details = os .fstat (descriptor ) 48if not stat .S_ISREG (details .st_mode )or details .st_nlink != 1 or details .st_size > 65 or (os .name == "posix" and 49 (posix_owner .owner_only_wrong (path ,details ))): 50os .close (descriptor ) 51raise ProfileError (posix_owner .owner_only_text ("benchmark lease file must be owner-only" ,path ),5 ) 52return descriptor 53 54 55def _lock (descriptor :int ,* ,initialize :bool = False )-> None : 56if initialize and os .fstat (descriptor ).st_size == 0 : 57os .lseek (descriptor ,0 ,os .SEEK_SET ) 58os .write (descriptor ,b"0" ) 59if os .name == "nt" : 60import msvcrt 61os .lseek (descriptor ,WINDOWS_LOCK_OFFSET ,os .SEEK_SET ) 62msvcrt .locking (descriptor ,msvcrt .LK_NBLCK ,1 ) 63else : 64import fcntl 65fcntl .flock (descriptor ,fcntl .LOCK_EX | fcntl .LOCK_NB ) 66 67 68def _unlock (descriptor :int )-> None : 69if os .name == "nt" : 70import msvcrt 71os .lseek (descriptor ,WINDOWS_LOCK_OFFSET ,os .SEEK_SET ) 72msvcrt .locking (descriptor ,msvcrt .LK_UNLCK ,1 ) 73else : 74import fcntl 75fcntl .flock (descriptor ,fcntl .LOCK_UN ) 76 77 78def _path_digest (path :Path )-> bytes : 79return hashlib .sha256 (os .fsencode (os .path .abspath (path ))).hexdigest ().encode ("ascii" ) 80 81 82@contextmanager 83def benchmark_lease (profile :str ,path :Path | None = None ): 84"""Refuse overlapping local runs for one saved profile across host processes.""" 85target = _lease_file (profile ,create = True ) 86descriptor = _lease_descriptor (target ,create = True ) 87try : 88try : 89_lock (descriptor ,initialize = True ) 90except OSError : 91raise ProfileError ("another benchmark is running for this saved profile" ,6 )from None 92try : 93marker = _path_digest (path )if path is not None else b"x" * 64 94os .lseek (descriptor ,1 ,os .SEEK_SET ) 95if os .write (descriptor ,marker )!= len (marker ): 96raise ProfileError ("cannot record benchmark lease identity" ,5 ) 97os .fsync (descriptor ) 98yield 99finally : 100_unlock (descriptor ) 101finally : 102os .close (descriptor ) 103 104 105def benchmark_activity (profile :str ,path :Path )-> str : 106"""Check the exact saved run's lease, without using PID files or stale timestamps.""" 107target = _lease_file (profile ,create = False ) 108if target is None : 109return "untracked" 110try : 111descriptor = _lease_descriptor (target ,create = False ) 112except FileNotFoundError : 113return "untracked" 114try : 115if os .name == "nt" and os .fstat (descriptor ).st_size == 0 : 116return "untracked" 117try : 118_lock (descriptor ) 119except OSError as exc : 120if exc .errno not in (errno .EAGAIN ,errno .EACCES )and getattr (exc ,"winerror" ,None )!= 33 : 121raise ProfileError ("cannot inspect benchmark lease" ,5 )from None 122os .lseek (descriptor ,1 ,os .SEEK_SET ) 123recorded = os .read (descriptor ,65 ) 124if recorded == _path_digest (path ): 125return "active" 126return "other_active" if re .fullmatch (rb"[0-9a-f]{64}" ,recorded )else "untracked" 127else : 128try : 129os .lseek (descriptor ,1 ,os .SEEK_SET ) 130recorded = os .read (descriptor ,65 ) 131return "ended" if recorded == _path_digest (path )else "untracked" 132finally : 133_unlock (descriptor ) 134finally : 135os .close (descriptor ) 136 137 138def request_cancel (profile :str ,path :Path )-> dict : 139"""Request cancellation only for the exact active owner-local benchmark.""" 140directory = path .parent if path .name in ("results.json" ,"progress.json" )else path 141details = directory .lstat () 142if not stat .S_ISDIR (details .st_mode )or (os .name == "posix" and 143 (posix_owner .owner_only_wrong (directory ,details ))): 144raise ProfileError (posix_owner .owner_only_text ("benchmark output directory must be owner-only" ,directory ),5 ) 145if benchmark_activity (profile ,directory )!= "active" : 146raise ProfileError ("the exact benchmark run is not active" ,6 ) 147if bench .progress (directory )["state" ]!= "running" : 148raise ProfileError ("benchmark already saved its final report" ,6 ) 149marker = directory / "cancel.request" 150try : 151descriptor = os .open (marker ,os .O_WRONLY | os .O_CREAT | os .O_EXCL | 152getattr (os ,"O_NOFOLLOW" ,0 ),0o600 ) 153except FileExistsError : 154details = marker .lstat () 155if not stat .S_ISREG (details .st_mode )or details .st_nlink != 1 or details .st_size != 1 or (os .name == "posix" and 156 (posix_owner .owner_only_wrong (marker ,details ))): 157raise ProfileError ("benchmark cancellation marker is invalid" ,5 ) 158else : 159try : 160os .write (descriptor ,b"1" ) 161os .fsync (descriptor ) 162finally : 163os .close (descriptor ) 164current = bench .progress (directory ) 165if current ["state" ]== "report_saved" : 166raise ProfileError ("benchmark already saved its final report" ,6 ) 167return {"ok" :True ,"path" :str (directory / "results.json" ), 168"state" :"cancelled" if current ["state" ]== "cancelled" else "cancel_requested" } 169 170 171def cancel_requested (directory :Path )-> bool : 172"""Read the private marker without treating a stale marker as process liveness.""" 173marker = directory / "cancel.request" 174try : 175details = marker .lstat () 176except FileNotFoundError : 177return False 178if not stat .S_ISREG (details .st_mode )or details .st_nlink != 1 or details .st_size != 1 or (os .name == "posix" and 179 (posix_owner .owner_only_wrong (marker ,details ))): 180raise ProfileError ("benchmark cancellation marker is invalid" ,5 ) 181return True 182 183 184def _settings (profile :str ,params :dict )-> tuple [dict ,dict ,Endpoint ,Endpoint ,Path ]: 185suite ,concurrency ,repeat = params ["suite" ],params ["concurrency" ],params ["repeat" ] 186timeout ,condition = params ["request_timeout" ],params ["condition" ] 187if suite not in bench .SUITES : 188raise ProfileError ("unknown serving benchmark suite" ) 189maximum = 64 if suite == "parallel-overload-v1" else 16 190if (type (concurrency )is not int or not 1 <= concurrency <= maximum or 191type (repeat )is not int or not 1 <= repeat <= 5 or 192type (timeout )not in (int ,float )or not 1 <= timeout <= 600 ): 193raise ProfileError ("benchmark workload settings are outside supported bounds" ) 194if condition is not None and (not isinstance (condition ,str )or 195not re .fullmatch (r"[a-z][a-z0-9_-]{0,39}" ,condition )): 196raise ProfileError ("benchmark condition must be a lowercase name up to 40 characters" ) 197phase_count = sum (1 if kind in ("warmup" ,"recovery" ,"cancel_active" , 198"cancel_queued" ,"cancel_prefill" )else repeat 199for kind in bench .SUITES [suite ]) 200if phase_count * (timeout + 30 )> 1700 : 201raise ProfileError ("benchmark workload exceeds the Desktop job limit; reduce timeout or repeats" ) 202path = Path (params ["path" ]) 203if path .exists ()or path .is_symlink (): 204raise ProfileError ("benchmark output directory already exists" ,2 ) 205if not path .parent .is_dir (): 206raise ProfileError ("benchmark output parent directory does not exist" ,2 ) 207source ,saved ,revision ,cfg = _source (profile ) 208if saved is None or revision is None : 209raise ProfileError ("Desktop benchmark requires a saved profile" ) 210launch ,_ = _launch_plan (profile ) 211host = launch ["effective" ]["host" ] 212host = "127.0.0.1" if host in ("0.0.0.0" ,"::" )else host 213authority = f"[ { host } ]" if ":" in host and not host .startswith ("[" )else host 214url = f"http:// { authority } : { launch [ 'effective' ][ 'port' ] } " 215key = os .environ .get ("STRATA_API_KEY" ) 216endpoint = Endpoint (url ,key ,timeout = 10 ) 217telemetry = Endpoint (url ,os .environ .get ("STRATA_TELEMETRY_KEY" )or key ,timeout = 3 ) 218identity = {"profile" :profile ,"revision" :revision ,"source_config" :str (source ), 219"source_sha256" :hashlib .sha256 (source .read_bytes ()).hexdigest (), 220"model_name" :cfg .get ("model_name" ),"gpu" :cfg .get ("gpu" )} 221return launch ,identity ,endpoint ,telemetry ,path 222 223 224def plan (profile :str ,params :dict )-> dict : 225launch ,identity ,endpoint ,telemetry ,path = _settings (profile ,params ) 226try : 227snapshot = telemetry .snapshot () 228except ClientError as exc : 229raise ProfileError ("benchmark telemetry is unavailable: " + str (exc ),5 )from None 230match = bench ._managed_match (identity ,endpoint .root ,snapshot ) 231if not match ["matched" ]: 232raise ProfileError ("managed benchmark preflight failed: " + match ["reason" ],5 ) 233owner = runtime .status (profile ) 234owner_id = owner .get ("owner_id" ) 235if (owner .get ("state" )!= "ready" or owner .get ("instance_id" )!= match ["instance_id" ]or 236owner .get ("profile_revision" )!= identity ["revision" ]or 237not isinstance (owner_id ,str )or 238not re .fullmatch (r"[0-9a-f]{32}" ,owner_id )): 239raise ProfileError ("benchmark owner identity is unavailable" ,5 ) 240if (snapshot .get ("model" )or {}).get ("loaded" )is not True : 241raise ProfileError ("benchmark needs a loaded model" ,5 ) 242work = snapshot .get ("work" )or {} 243suite ,count ,repeat = params ["suite" ],params ["concurrency" ],params ["repeat" ] 244if suite == "parallel-overload-v1" : 245limit ,deadline = work .get ("admission_limit" ),work .get ("queue_timeout_s" ) 246if (type (limit )is not int or limit < 1 or type (deadline )not in (int ,float )or 247deadline <= 0 or count <= limit ): 248raise ProfileError ("overload benchmark needs configured admission and concurrency above its limit" ,5 ) 249if suite in ("parallel-cancel-v1" ,"parallel-prefill-cancel-v1" ): 250slots = work .get ("slots_effective" ) 251if (type (slots )is not int or not 1 <= slots <= 16 or 252type (work .get ("client_disconnect_cancels" ))is not int ): 253raise ProfileError ("cancellation benchmark needs 1..16 slots and disconnect telemetry" ,5 ) 254if suite == "parallel-cancel-v1" and (count < slots or 255type (work .get ("max_queue" ))is not int or work ["max_queue" ]< 1 or 256type (work .get ("queue_timeout_s" ))not in (int ,float )or 257work ["queue_timeout_s" ]< 2 ): 258raise ProfileError ("cancellation benchmark needs a queue, two-second timeout and all slots" ,5 ) 259if suite == "parallel-prefill-cancel-v1" and (slots < 2 or count < 2 ): 260raise ProfileError ("prefill cancellation needs at least two slots and clients" ,5 ) 261requests = {"serving-smoke" :1 + repeat * (2 + count ), 262"parallel-mixed-v1" :1 + repeat * (2 + 2 * count ), 263"parallel-overload-v1" :2 + repeat * count , 264"parallel-cancel-v1" : (work .get ("slots_effective" )or 0 )+ 4 , 265"parallel-prefill-cancel-v1" :4 }[suite ] 266return {"profile" :profile ,"profile_revision" :identity ["revision" ], 267"source_sha256" :identity ["source_sha256" ],"owner_id" :owner_id , 268"instance_id" :match ["instance_id" ],"endpoint" :endpoint .root , 269"model_id" : (snapshot .get ("model" )or {}).get ("id" ), 270"suite" :suite ,"concurrency" :count ,"repeat" :repeat , 271"request_timeout" :params ["request_timeout" ],"condition" :params ["condition" ], 272"path" :str (path ),"phases" :list (bench .SUITES [suite ]), 273"planned_requests" :requests ,"managed_match" :True , 274"api_credential_env" :"STRATA_API_KEY" ,"telemetry_credential_env" :"STRATA_TELEMETRY_KEY" } 275 276 277def create_job (profile :str ,params :dict )-> dict : 278"""Save a bounded receipt before the Desktop launches its benchmark worker.""" 279job_id = params ["job_id" ] 280intent = {key :value for key ,value in params .items ()if key != "job_id" } 281_settings (profile ,intent ) 282if benchmark_activity (profile ,Path (intent ["path" ]))in ("active" ,"other_active" ): 283raise ProfileError ("another benchmark is running for this saved profile" ,6 ) 284record = journal .begin_direct (profile ,"bench.run" ,intent ["if_profile_revision" ],intent , 285operation_id = job_id ) 286return {"ok" :True ,"job_id" :record ["operation_id" ], 287"path" :str (Path (intent ["path" ])/ "results.json" )} 288 289 290def _job_record (profile :str ,job_id :str )-> dict : 291if not isinstance (job_id ,str )or not journal .ID .fullmatch (job_id ): 292raise ProfileError ("benchmark job ID must be a 32-character hex value" ,2 ) 293record = journal .load (profile ,job_id ) 294if record .get ("kind" )!= "bench.run" or record .get ("origin" )!= "direct" : 295raise ProfileError ("benchmark job ID does not identify a benchmark" ,5 ) 296return record 297 298 299def _receipt_result (path :Path ,report :dict )-> dict : 300return {"ok" :True ,"report_path" :str (path / "results.json" ), 301"run_id" :report ["run_id" ],"instance_id" :report ["instance_id" ], 302"successful" :report ["successful" ],"cancelled" :report .get ("cancelled" ,False )} 303 304 305def _report_matches_job (report :dict ,intent :dict ,profile :str )-> bool : 306identity = report .get ("profile_identity" )or {} 307return (isinstance (identity ,dict )and 308report .get ("suite" )== intent ["suite" ]and 309report .get ("condition" )== intent ["condition" ]and 310report .get ("instance_id" )== intent ["if_instance_id" ]and 311report .get ("planned_phases" )== bench ._planned_phase_kinds (intent ["suite" ],intent ["repeat" ])and 312identity .get ("profile" )== profile and 313identity .get ("revision" )== intent ["if_profile_revision" ]and 314identity .get ("source_sha256" )== intent ["if_source_sha256" ]) 315 316 317def job_status (profile :str ,job_id :str )-> dict : 318"""Recover a Desktop job from its journal, exact lease and private report.""" 319record = _job_record (profile ,job_id ) 320directory = Path (record ["intent" ]["path" ]) 321path = directory / "results.json" 322if directory .exists ()or directory .is_symlink (): 323details = directory .lstat () 324if not stat .S_ISDIR (details .st_mode )or (os .name == "posix" and 325 (posix_owner .owner_only_wrong (directory ,details ))): 326raise ProfileError (posix_owner .owner_only_text ("benchmark output directory must be owner-only" ,directory ),5 ) 327activity = benchmark_activity (profile ,directory ) 328try : 329phase = bench .progress (directory ) 330except ProfileError : 331phase = None 332report = None 333if phase is not None and phase ["state" ]in ("report_saved" ,"cancelled" ): 334candidate = bench .load (directory ) 335if _report_matches_job (candidate ,record ["intent" ],profile ): 336report = candidate 337else : 338phase = None 339if report is not None and record ["state" ]== "running" : 340try : 341journal .finish (profile ,job_id ,"succeeded" ,_receipt_result (directory ,report )) 342except ProfileError : 343pass # The benchmark worker may have finished the same receipt. 344record = _job_record (profile ,job_id ) 345if report is not None : 346state = "cancelled" if report .get ("cancelled" )else "completed" 347result = {"ok" :True ,"path" :str (path ),"successful" :report ["successful" ], 348"cancelled" :report .get ("cancelled" ,False ),"run_id" :report ["run_id" ], 349"instance_id" :report ["instance_id" ],"suite" :report ["suite" ]} 350elif record ["state" ]== "succeeded" and isinstance (record .get ("result" ),dict ): 351saved = record ["result" ] 352state = "cancelled" if saved .get ("cancelled" )else "completed" 353result = {"ok" :True ,"path" :str (path ),"successful" :saved .get ("successful" ), 354"cancelled" :saved .get ("cancelled" ),"run_id" :saved .get ("run_id" ), 355"instance_id" :saved .get ("instance_id" ),"suite" :record ["intent" ]["suite" ]} 356else : 357result = None 358state = ("failed" if record ["state" ]== "failed" else 359"running" if activity == "active" else "completion_unknown" ) 360if (state == "completion_unknown" and record ["state" ]== "running" and phase is None and 361time .time ()- record ["started_at" ]< 10 ): 362state = "launching" 363return {"ok" :True ,"job" : {"job_id" :job_id ,"state" :state , 364"started_at" :round (record ["started_at" ]* 1000 ), 365"finished_at" :round (record ["finished_at" ]* 1000 )if record ["finished_at" ]is not None else None , 366"path" :str (path ),"result" :result , 367"error" : ("Benchmark failed before a complete report was saved." if state == "failed" else 368"Benchmark completion needs inspection at the saved path." 369if state == "completion_unknown" else None ), 370"outcome" :"report_recovered" if report is not None and record ["state" ]!= "succeeded" 371else "owner_journal" ,"progress" :phase , 372"activity" :activity ,"cancel_requested" :cancel_requested (directory )if directory .exists ()else False }} 373 374 375def run (profile :str ,params :dict )-> dict : 376job_id = params .get ("job_id" ) 377if job_id is not None : 378record = _job_record (profile ,job_id ) 379if record ["state" ]!= "running" or record ["intent" ]!= {key :value for key ,value in params .items () 380if key != "job_id" }: 381raise ProfileError ("benchmark job no longer matches its reviewed request" ,6 ) 382try : 383with benchmark_lease (profile ,Path (params ["path" ])): 384planned = plan (profile ,params ) 385for key in ("profile_revision" ,"source_sha256" ,"owner_id" ,"instance_id" ): 386if planned [key ]!= params ["if_" + key ]: 387raise ProfileError ("benchmark target changed after review; review again" ,6 ) 388_ ,identity ,endpoint ,telemetry ,path = _settings (profile ,params ) 389try : 390report = bench .run (endpoint ,telemetry ,path ,suite = params ["suite" ], 391concurrency = params ["concurrency" ],repeat = params ["repeat" ], 392request_timeout = params ["request_timeout" ],condition = params ["condition" ], 393profile_identity = identity ,require_managed_match = True ) 394except ClientError as exc : 395raise ProfileError ("benchmark connection failed: " + str (exc ),exc .exit_code )from None 396if job_id is not None : 397saved_result = _receipt_result (path ,report ) 398try : 399journal .finish (profile ,job_id ,"succeeded" ,saved_result ) 400except ProfileError : 401# A concurrent recovery read may have reconciled this final report. 402recorded = _job_record (profile ,job_id ) 403if recorded ["state" ]!= "succeeded" or recorded ["result" ]!= saved_result : 404raise 405return {"ok" :True ,"path" :str (path / "results.json" ), 406"successful" :report ["successful" ],"summary" :bench .summary (report )} 407except BaseException as exc : 408if job_id is not None and _job_record (profile ,job_id )["state" ]== "running" : 409unknown = isinstance (exc , (KeyboardInterrupt ,SystemExit ))or \ 410 (isinstance (exc ,ProfileError )and exc .exit_code == 8 ) 411journal .finish (profile ,job_id ,"completion_unknown" if unknown else "failed" , 412 {"error_type" :type (exc ).__name__ , 413"exit_code" :exc .exit_code if isinstance (exc ,ProfileError )else 130 if unknown else 6 }) 414raise