okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
bcf88b738
main
1"""Owner-local receipts for reviewed Desktop calibration operations.""" 2 3from __future__import annotations 4 5import errno 6import json 7import math 8import os 9import stat 10import threading 11import time 12from contextlib import contextmanager 13from pathlib import Path 14 15from strata_control import calibration ,journal ,profiles 16from strata_control .profiles import ProfileError 17from strata_control import posix_owner 18 19 20KINDS = {"measure" :"engine.calibrate.measure" ,"apply" :"engine.calibrate.apply" , 21"rollback" :"engine.calibrate.rollback" } 22STAGES = frozenset ({"preflight" ,"loading" ,"pcie_share" ,"draft_floor" ,"confirmation" , 23"cpu_workers" ,"expert_tier" ,"saving_report" }) 24 25 26#: Windows byte-range locks are mandatory: a locked byte cannot be read through any other handle. The lock 27#: therefore sits far past the marker bytes, so another process can still read who holds the lease. 28WINDOWS_LOCK_OFFSET = 1 << 16 29 30def _directory (profile :str )-> Path : 31return journal ._directory (profile ,create = True ) 32 33 34def _lease_path (profile :str )-> Path : 35return _directory (profile )/ ".calibration-worker.lock" 36 37 38def _open_lease (profile :str ,* ,create :bool )-> int | None : 39flags = os .O_RDWR | (os .O_CREAT if create else 0 )| getattr (os ,"O_NOFOLLOW" ,0 ) 40try : 41descriptor = os .open (_lease_path (profile ),flags ,0o600 ) 42except FileNotFoundError : 43return None 44details = os .fstat (descriptor ) 45if not stat .S_ISREG (details .st_mode )or details .st_nlink != 1 or details .st_size > 32 or \ 46 (os .name == "posix" and 47 (posix_owner .owner_only_wrong (_lease_path (profile ),details ))): 48os .close (descriptor ) 49raise ProfileError (posix_owner .owner_only_text ("calibration worker lease must be owner-only" ,_lease_path (profile )),5 ) 50return descriptor 51 52 53def _try_lock (descriptor :int )-> None : 54if os .name == "nt" : 55import msvcrt 56os .lseek (descriptor ,WINDOWS_LOCK_OFFSET ,os .SEEK_SET ) 57msvcrt .locking (descriptor ,msvcrt .LK_NBLCK ,1 ) 58else : 59import fcntl 60fcntl .flock (descriptor ,fcntl .LOCK_EX | fcntl .LOCK_NB ) 61 62 63def _unlock (descriptor :int )-> None : 64if os .name == "nt" : 65import msvcrt 66os .lseek (descriptor ,WINDOWS_LOCK_OFFSET ,os .SEEK_SET ) 67msvcrt .locking (descriptor ,msvcrt .LK_UNLCK ,1 ) 68else : 69import fcntl 70fcntl .flock (descriptor ,fcntl .LOCK_UN ) 71 72 73@contextmanager 74def _worker_lease (profile :str ,job_id :str ): 75descriptor = _open_lease (profile ,create = True ) 76if descriptor is None : 77raise ProfileError ("calibration worker lease directory is unavailable" ,5 ) 78try : 79try : 80_try_lock (descriptor ) 81except OSError as exc : 82if exc .errno in (errno .EAGAIN ,errno .EACCES )or getattr (exc ,"winerror" ,None )== 33 : 83raise ProfileError ("another calibration worker is running for this profile" ,6 )from None 84raise 85try : 86os .ftruncate (descriptor ,0 ) 87os .lseek (descriptor ,0 ,os .SEEK_SET ) 88if os .write (descriptor ,job_id .encode ("ascii" ))!= 32 : 89raise ProfileError ("cannot record calibration worker identity" ,5 ) 90os .fsync (descriptor ) 91yield 92finally : 93_unlock (descriptor ) 94finally : 95os .close (descriptor ) 96 97 98def _activity (profile :str ,job_id :str )-> str : 99descriptor = _open_lease (profile ,create = False ) 100if descriptor is None : 101return "untracked" 102try : 103try : 104_try_lock (descriptor ) 105except OSError as exc : 106if exc .errno not in (errno .EAGAIN ,errno .EACCES )and getattr (exc ,"winerror" ,None )!= 33 : 107raise 108os .lseek (descriptor ,0 ,os .SEEK_SET ) 109marker = os .read (descriptor ,32 ) 110return "active" if marker == job_id .encode ("ascii" )else "other_active" 111else : 112try : 113os .lseek (descriptor ,0 ,os .SEEK_SET ) 114return "ended" if os .read (descriptor ,32 )== job_id .encode ("ascii" )else "untracked" 115finally : 116_unlock (descriptor ) 117finally : 118os .close (descriptor ) 119 120 121def _cancel_path (profile :str ,job_id :str )-> Path : 122return _directory (profile )/ f" { job_id } .cancel" 123 124 125def _cancel_requested (profile :str ,job_id :str )-> bool : 126path = _cancel_path (profile ,job_id ) 127try : 128details = path .lstat () 129except FileNotFoundError : 130return False 131if not stat .S_ISREG (details .st_mode )or details .st_nlink != 1 or details .st_size != 1 or \ 132 (os .name == "posix" and 133 (posix_owner .owner_only_wrong (path ,details ))): 134raise ProfileError ("calibration cancellation marker is invalid" ,5 ) 135descriptor = os .open (path ,os .O_RDONLY | getattr (os ,"O_NOFOLLOW" ,0 )) 136try : 137current = os .fstat (descriptor ) 138if current .st_ino != details .st_ino or os .read (descriptor ,2 )!= b"1" : 139raise ProfileError ("calibration cancellation marker changed" ,5 ) 140finally : 141os .close (descriptor ) 142return True 143 144 145@contextmanager 146def _cancel_watcher (profile :str ,job_id :str ): 147requested = threading .Event () 148stop = threading .Event () 149 150def watch (): 151while not stop .wait (0.2 ): 152try : 153if _cancel_requested (profile ,job_id ): 154requested .set () 155return 156except (OSError ,ProfileError ): 157requested .set ()# Invalid private state stops the measurement safely. 158return 159 160thread = threading .Thread (target = watch ,name = "strata-calibration-cancel" ,daemon = True ) 161thread .start () 162try : 163yield requested 164finally : 165stop .set () 166thread .join (timeout = 1 ) 167 168 169def _progress_path (profile :str ,job_id :str )-> Path : 170return _directory (profile )/ f" { job_id } .progress.json" 171 172 173def _save_progress (profile :str ,job_id :str ,stage :str ,completed :int ,total :int )-> None : 174if stage not in STAGES or type (completed )is not int or type (total )is not int or \ 175not 0 <= completed <= total <= 1000 : 176raise ProfileError ("calibration progress is invalid" ,5 ) 177value = {"schema_version" :1 ,"job_id" :job_id ,"stage" :stage , 178"completed" :completed ,"total" :total ,"updated_at" :time .time ()} 179profiles ._atomic (_progress_path (profile ,job_id ), 180 (json .dumps (value ,sort_keys = True ,allow_nan = False )+ "\n" ).encode ("utf-8" )) 181 182 183def _load_progress (profile :str ,job_id :str )-> dict | None : 184path = _progress_path (profile ,job_id ) 185try : 186details = path .lstat () 187except FileNotFoundError : 188return None 189if not stat .S_ISREG (details .st_mode )or details .st_nlink != 1 or details .st_size > 1024 or \ 190 (os .name == "posix" and 191 (posix_owner .owner_only_wrong (path ,details ))): 192raise ProfileError (posix_owner .owner_only_text ("calibration progress file must be owner-only" ,path ),5 ) 193try : 194value = json .loads (path .read_text (encoding = "utf-8" )) 195except (OSError ,UnicodeError ,ValueError ): 196raise ProfileError ("calibration progress file is invalid" ,5 )from None 197if not isinstance (value ,dict )or set (value )!= {"schema_version" ,"job_id" ,"stage" , 198"completed" ,"total" ,"updated_at" }or \ 199value ["schema_version" ]!= 1 or value ["job_id" ]!= job_id or \ 200value ["stage" ]not in STAGES or type (value ["completed" ])is not int or \ 201type (value ["total" ])is not int or not 0 <= value ["completed" ]<= value ["total" ]<= 1000 or \ 202type (value ["updated_at" ])not in (int ,float )or not math .isfinite (value ["updated_at" ]): 203raise ProfileError ("calibration progress file is invalid" ,5 ) 204return value 205 206 207def _intent (params :dict )-> dict : 208return {"report_path" :params ["path" ],"exclusive_ack" :True , 209"if_source_sha256" :params ["if_source_sha256" ], 210"if_report_sha256" :params .get ("if_report_sha256" )} 211 212 213def create (profile :str ,action :str ,params :dict )-> dict : 214"""Create a receipt after management has checked every reviewed precondition.""" 215if action not in KINDS or not isinstance (params .get ("job_id" ),str )or \ 216not journal .ID .fullmatch (params ["job_id" ]): 217raise ProfileError ("calibration job ID or action is invalid" ,2 ) 218if _activity (profile ,params ["job_id" ])in ("active" ,"other_active" ): 219raise ProfileError ("another calibration worker is running for this profile" ,6 ) 220record = journal .begin_direct (profile ,KINDS [action ],params ["if_profile_revision" ], 221_intent (params ),operation_id = params ["job_id" ]) 222return {"ok" :True ,"job_id" :record ["operation_id" ],"action" :action , 223"path" :record ["intent" ]["report_path" ]} 224 225 226def _record (profile :str ,job_id :str )-> dict : 227if not isinstance (job_id ,str )or not journal .ID .fullmatch (job_id ): 228raise ProfileError ("calibration job ID must be a 32-character hex value" ,2 ) 229record = journal .load (profile ,job_id ) 230if record .get ("kind" )not in KINDS .values ()or record .get ("origin" )!= "direct" or \ 231"if_source_sha256" not in record ["intent" ]: 232raise ProfileError ("calibration job ID does not identify a Desktop calibration" ,5 ) 233return record 234 235 236def run (profile :str ,action :str ,params :dict ,work )-> tuple [str ,dict ]: 237job_id = params ["job_id" ] 238record = _record (profile ,job_id ) 239if record ["state" ]!= "running" or record ["kind" ]!= KINDS [action ]or \ 240record ["profile_revision" ]!= params ["if_profile_revision" ]or \ 241record ["intent" ]!= _intent (params ): 242raise ProfileError ("calibration job no longer matches its reviewed request" ,6 ) 243with _worker_lease (profile ,job_id ): 244return _run_owned (profile ,action ,job_id ,work ) 245 246 247def _run_owned (profile :str ,action :str ,job_id :str ,work )-> tuple [str ,dict ]: 248try : 249result = work () 250saved = journal .compact_direct_result (KINDS [action ],result ) 251try : 252journal .finish (profile ,job_id ,"succeeded" ,saved ) 253except ProfileError : 254# A recovery read can reconcile a completed measurement first. 255current = _record (profile ,job_id ) 256if current ["state" ]!= "succeeded" or current ["result" ]!= saved : 257raise 258return job_id ,result 259except BaseException as exc : 260if _record (profile ,job_id )["state" ]== "running" : 261unknown = isinstance (exc , (KeyboardInterrupt ,SystemExit ))or \ 262 (isinstance (exc ,ProfileError )and exc .exit_code == 8 ) 263cancelled = (action == "measure" and isinstance (exc ,ProfileError )and 264exc .exit_code == 130 ) 265journal .finish (profile ,job_id ,"completion_unknown" if unknown else "failed" , 266 {"error_type" :type (exc ).__name__ , 267"cancelled" :cancelled , 268"exit_code" :exc .exit_code if isinstance (exc ,ProfileError )else 269130 if unknown else 6 }) 270raise 271 272 273def execute (profile :str ,action :str ,params :dict )-> dict : 274"""Run every preflight inside the receipt, including stale review rejection.""" 275from strata_control import management 276 277def work ()-> dict : 278if action == "measure" : 279try : 280_save_progress (profile ,params ["job_id" ],"preflight" ,0 ,1 ) 281except (OSError ,ProfileError ): 282pass # Progress is supplementary; the reviewed action still runs. 283revision ,digest = management ._calibration_expected_source (profile ,params ) 284if management ._boolean (params ["exclusive_ack" ],"exclusive_ack" )is not True : 285raise ProfileError ("calibration requires exclusive-access acknowledgement" ) 286path = management ._local_report_path (params ["path" ],"calibration report path" ) 287if action == "measure" : 288with _cancel_watcher (profile ,params ["job_id" ])as cancel_event : 289def progress (stage :str ,completed :int ,total :int ): 290try : 291_save_progress (profile ,params ["job_id" ],stage ,completed ,total ) 292except (OSError ,ProfileError ): 293pass 294 295progress ("preflight" ,1 ,1 ) 296report = calibration .measure (profile ,path ,exclusive_ack = True ,say = lambda _ :None , 297expected_profile_revision = revision , 298expected_source_sha256 = digest ,job_id = params ["job_id" ], 299progress = progress ,cancel_event = cancel_event ) 300return {"ok" :True ,"report_path" :str (path ),"report" :report } 301_ ,report = management ._calibration_report (profile ,str (path ),"calibration report path" ) 302expected = management ._optional_revision (params ["if_report_sha256" ],"if_report_sha256" ) 303if expected is None or report ["body_sha256" ]!= expected : 304raise ProfileError ("calibration report changed after review; review again" ,6 ) 305if action == "apply" : 306return {"ok" :True ,"application" :calibration .apply_result ( 307profile ,path ,exclusive_ack = True ,expected_report_sha256 = expected )} 308return {"ok" :True ,"rollback" :calibration .rollback_result ( 309profile ,path ,exclusive_ack = True ,expected_report_sha256 = expected )} 310 311operation_id ,outcome = run (profile ,action ,params ,work ) 312if action == "measure" : 313report = outcome ["report" ] 314return {"ok" :True ,"operation_id" :operation_id ,"path" :params ["path" ], 315"report_id" :report ["report_id" ],"applicable" :report ["applicable" ], 316"settings" :report ["settings" ]} 317return {"ok" :True ,"operation_id" :operation_id , 318"application" if action == "apply" else "rollback" : 319outcome ["application" if action == "apply" else "rollback" ]} 320 321 322def cancel (profile :str ,job_id :str )-> dict : 323"""Request a stop only for the exact active measurement worker.""" 324status (profile ,job_id )# Reconcile a finished report before accepting a new request. 325record = _record (profile ,job_id ) 326if record ["kind" ]!= KINDS ["measure" ]: 327raise ProfileError ("only calibration measurement can be cancelled" ,6 ) 328if record ["state" ]!= "running" or _activity (profile ,job_id )!= "active" : 329raise ProfileError ("the exact calibration measurement is not active" ,6 ) 330path = _cancel_path (profile ,job_id ) 331try : 332descriptor = os .open (path ,os .O_WRONLY | os .O_CREAT | os .O_EXCL | 333getattr (os ,"O_NOFOLLOW" ,0 ),0o600 ) 334except FileExistsError : 335_cancel_requested (profile ,job_id ) 336else : 337try : 338os .write (descriptor ,b"1" ) 339os .fsync (descriptor ) 340finally : 341os .close (descriptor ) 342return {"ok" :True ,"job_id" :job_id ,"state" :"cancel_requested" } 343 344 345def status (profile :str ,job_id :str )-> dict : 346"""Report a bounded receipt; only an exact report may recover measurement success.""" 347record = _record (profile ,job_id ) 348action = next (name for name ,kind in KINDS .items ()if kind == record ["kind" ]) 349path = Path (record ["intent" ]["report_path" ]) 350report = None 351recovered = False 352if action == "measure" and record ["state" ]in ("running" ,"succeeded" ): 353try : 354candidate = calibration .load_report (path ) 355identity = candidate ["identity" ] 356if (candidate .get ("operation_id" )== job_id and 357type (candidate .get ("applicable" ))is bool and 358identity .get ("profile_id" )== profile and 359identity .get ("profile_revision" )== record ["profile_revision" ]and 360identity .get ("source_sha256" )== record ["intent" ]["if_source_sha256" ]): 361report = candidate 362except (ProfileError ,OSError ): 363pass 364if report is not None and record ["state" ]== "running" : 365try : 366journal .finish (profile ,job_id ,"succeeded" , 367 {"ok" :True ,"report_path" :str (path ), 368"report_id" :report ["report_id" ], 369"applicable" :report ["applicable" ]}) 370recovered = True 371except ProfileError : 372pass 373record = _record (profile ,job_id ) 374result = None 375if record ["state" ]== "succeeded" : 376saved = record ["result" ] 377result = {"ok" :True ,"action" :action ,"operation_id" :job_id , 378"report_id" :saved .get ("report_id" )} 379if action == "measure" : 380result .update (path = str (path ),applicable = saved .get ("applicable" ), 381settings = report ["settings" ]if report is not None else {}) 382else : 383result .update (changed = saved .get ("changed" )) 384if action == "apply" : 385result ["application_record" ]= saved .get ("application_record" ) 386else : 387result ["setup_settings_removed" ]= saved .get ("setup_settings_removed" ) 388activity = _activity (profile ,job_id ) 389progress = _load_progress (profile ,job_id )if action == "measure" else None 390cancel_requested = _cancel_requested (profile ,job_id )if action == "measure" else False 391state = record ["state" ] 392if state == "running" : 393state = "running" if activity == "active" else \ 394"launching" if time .time ()- record ["started_at" ]< 10 else "completion_unknown" 395elif state == "failed" and record ["result" ].get ("cancelled" )is True : 396state = "cancelled" 397return {"ok" :True ,"job" : {"job_id" :job_id ,"action" :action ,"state" :state , 398"started_at" :round (record ["started_at" ]* 1000 ), 399"finished_at" :round (record ["finished_at" ]* 1000 )if record ["finished_at" ]is not None else None , 400"result" :result , 401"error" :"Calibration failed; inspect the saved operation and report." if state == "failed" else 402"Calibration completion needs inspection before retrying." if state == "completion_unknown" else None , 403"outcome" :"report_recovered" if recovered else "owner_journal" , 404"activity" :activity ,"progress" :progress ,"cancel_requested" :cancel_requested }}