okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
049ae1c67
main
1"""Explicit measure, review and apply steps around Strata's existing calibration. 2 3The current suite measures decode speed. It is not a four-GPU serving benchmark. 4Its report binds a candidate to the run config, engine binary and observed local 5hardware; applying it is a separate operation with a backup and smoke generation. 6""" 7 8from __future__import annotations 9 10from strata_control .private_files import private_mkdir as _private_mkdir 11import copy 12import hashlib 13import json 14import math 15import os 16import re 17import socket 18import stat 19import tempfile 20import threading 21import time 22import uuid 23from contextlib import contextmanager 24from pathlib import Path 25 26from strata_control import profiles 27from strata_control .doctor import inspect as inspect_components 28from strata_control .profiles import ProfileError 29from strata_control import atomic as _atomic_mod 30from strata_control import posix_owner 31 32 33SUITE = "legacy-decode-v1" 34MAX_REPORT_BYTES = 2 * 1024 * 1024 35MAX_APPLICATION_BYTES = 8 * 1024 36MAX_AGE_SECONDS = 30 * 24 * 3600 37ALLOWED_SETTINGS = {"--pcie-frac" ,"--spec-min-p" ,"--pool-workers" , 38"--adapt-every" ,"--adapt-swaps" ,"--adapt-decay" } 39 40 41def _full_folder (name :str ): 42"""`setup` and `tools.calibrate` belong to a full Strata folder; the Terminal archive carries neither (it never 43installs or builds). Use them when they are importable, or when STRATA_INSTALL_DIR names a folder that has both; 44otherwise refuse in words instead of a traceback.""" 45import importlib 46import sys 47try : 48return importlib .import_module (name ) 49except ImportError : 50pass 51raw = os .environ .get ("STRATA_INSTALL_DIR" ) 52if raw : 53folder = Path (raw ).expanduser () 54if (folder / "setup.py" ).is_file ()and (folder / "tools" / "calibrate.py" ).is_file (): 55if str (folder )not in sys .path : 56sys .path .append (str (folder )) 57try : 58return importlib .import_module (name ) 59except ImportError : 60pass 61raise ProfileError ( 62"engine calibrate needs a full Strata folder (setup.py and tools/calibrate.py); this terminal archive has " 63"neither. Set STRATA_INSTALL_DIR to such a folder, or use `strata tune run --mode api` to tune from the " 64"archive" ,5 )from None 65 66 67def _tools_available ()-> bool : 68"""False in the Terminal archive without STRATA_INSTALL_DIR: `--measure` would be refused (see `_full_folder`).""" 69import importlib .util 70try : 71if importlib .util .find_spec ("setup" )and importlib .util .find_spec ("tools.calibrate" ): 72return True 73except (ImportError ,ValueError ): 74pass 75raw = os .environ .get ("STRATA_INSTALL_DIR" ) 76if raw : 77folder = Path (raw ).expanduser () 78return (folder / "setup.py" ).is_file ()and (folder / "tools" / "calibrate.py" ).is_file () 79return False 80 81 82def _digest (path :Path )-> str : 83result = hashlib .sha256 () 84with path .open ("rb" )as stream : 85for block in iter (lambda :stream .read (1024 * 1024 ),b"" ): 86result .update (block ) 87return result .hexdigest () 88 89 90def _target (ref :str )-> tuple [Path ,dict | None ,str | None ,dict ]: 91path ,profile ,revision = profiles .resolve (ref ) 92return path ,profile ,revision ,profiles .read_run_config (path ) 93 94 95def preview (ref :str )-> dict : 96"""Inspect a proposed decode sweep without starting the engine or writing files.""" 97path ,profile ,revision ,cfg = _target (ref ) 98components = inspect_components (path ,profile_id = profile ["id" ]if profile else None ) 99source_bytes = path .read_bytes () 100if json .loads (source_bytes .decode ("utf-8-sig" ))!= cfg : 101raise ProfileError ("run config changed during calibration preview; retry" ,6 ) 102return {"profile" :profile ["id" ]if profile else None ,"profile_revision" :revision , 103"source_config" :str (path ),"source_sha256" :hashlib .sha256 (source_bytes ).hexdigest (), 104"model_name" :cfg .get ("model_name" ),"backend" :cfg .get ("backend" )or "unverified" , 105"devices_selected" :cfg .get ("gpu" ),"tool" :"tools/calibrate.py" , 106"tool_available" :_tools_available (), 107"estimated_minutes" : [15 ,30 ],"requires_exclusive_engine" :True , 108"settings_measured" : ["--pcie-frac" ,"--spec-min-p" ,"--pool-workers" , 109"--adapt-every" ,"--adapt-swaps" ,"--adapt-decay" ], 110"component_preflight" :components ,"hardware_identity" :"unverified_until_measurement" , 111"would_start_engine" :False ,"would_write_config" :False } 112 113 114def _resolved (raw :str ,cfg :dict ,path :Path )-> Path : 115from strata_control import engine_component 116if engine_component .is_reference (raw ): 117return Path (engine_component .expand (raw ,cfg )) 118value = Path (raw ).expanduser () 119if value .is_absolute (): 120return value 121cwd = cfg .get ("cwd" ) 122return (Path (cwd )if isinstance (cwd ,str )and cwd else path .parent )/ value 123 124 125def _runtime_cfg (cfg :dict ,profile :dict | None )-> dict : 126"""Apply the saved engine concurrency settings without changing setup's config.""" 127effective = copy .deepcopy (cfg ) 128if profile is None : 129return effective 130overrides = profile ["overrides" ] 131if "parallel" in overrides : 132if any (flag in effective ["args" ]for flag in ("--batch" ,"--slots" )): 133raise ProfileError ("parallel profile override conflicts with engine args" ) 134effective ["parallel" ]= overrides ["parallel" ] 135if "batch_groups" in overrides : 136if "--batch-groups" in effective ["args" ]: 137raise ProfileError ("batch_groups profile override conflicts with engine args" ) 138effective ["args" ]+= ["--batch-groups" ,str (overrides ["batch_groups" ])] 139return effective 140 141 142def _hardware_key (cfg :dict )-> str : 143return _full_folder ("setup" ).hardware_key (cfg ) 144 145 146def _identity (path :Path ,cfg :dict ,profile :dict | None ,revision :str | None )-> dict : 147cal = _full_folder ("tools.calibrate" ) 148engine = _resolved (cfg ["exe" ],cfg ,path ) 149components = inspect_components (path ,profile_id = profile ["id" ]if profile else None ) 150if not components ["ok" ]: 151raise ProfileError ("required engine/model components are missing; run strata doctor --profile first" ,5 ) 152files = [] 153for item in components ["components" ]: 154if item .get ("required" )and item .get ("kind" )== "file" and item .get ("name" )!= "engine" : 155file_path = Path (item ["path" ]) 156try : 157details = file_path .stat () 158except OSError : 159raise ProfileError (f"component changed during calibration: { item [ 'name' ] } " ,5 )from None 160files .append ({"name" :item ["name" ],"path" :str (file_path ), 161"size" :details .st_size ,"modified_ns" :details .st_mtime_ns }) 162return {"source_sha256" :_digest (path ),"engine_sha256" :_digest (engine ), 163"suite_sha256" :_digest (Path (cal .__file__ )),"hardware_key" :_hardware_key (cfg ), 164"model_name" :cfg .get ("model_name" ),"backend" :cfg .get ("backend" ),"gpu" :cfg .get ("gpu" ), 165"profile_id" :profile ["id" ]if profile else None ,"profile_revision" :revision , 166"required_file_metadata" :files ,"model_integrity" :"metadata_only_unverified" } 167 168 169def _validate_settings (settings :object )-> dict [str ,str ]: 170if not isinstance (settings ,dict )or set (settings )- ALLOWED_SETTINGS : 171raise ProfileError ("calibration report has unsupported settings" ,5 ) 172out = {} 173for flag ,raw in settings .items (): 174if not isinstance (raw ,str )or len (raw )> 32 : 175raise ProfileError (f"calibration setting { flag } must be a short string" ,5 ) 176try : 177number = float (raw ) 178except ValueError : 179raise ProfileError (f"calibration setting { flag } must be numeric" ,5 )from None 180if not number == number or number in (float ("inf" ),float ("-inf" )): 181raise ProfileError (f"calibration setting { flag } must be finite" ,5 ) 182if flag in ("--pcie-frac" ,"--spec-min-p" ,"--adapt-decay" ): 183if not 0 <= number <= 1 : 184raise ProfileError (f"calibration setting { flag } must be in 0..1" ,5 ) 185else : 186if not raw .isdecimal ()or not 1 <= int (raw )<= 8192 : 187raise ProfileError (f"calibration setting { flag } must be a positive whole number" ,5 ) 188out [flag ]= raw 189return out 190 191 192def _port_active (cfg :dict )-> bool : 193port = cfg .get ("port" ,8095 ) 194if type (port )is not int or not 1 <= port <= 65535 : 195return False 196host = cfg .get ("host" )or "127.0.0.1" 197address = "127.0.0.1" if host in ("0.0.0.0" ,"::" ,"localhost" )else host 198try : 199with socket .create_connection ((address ,port ),timeout = 0.2 ): 200return True 201except OSError : 202return False 203 204 205def _exclusive_preflight (cfg :dict ,profile :dict | None = None )-> None : 206endpoints = [cfg ] 207overrides = profile ["overrides" ]if profile else {} 208if "host" in overrides or "port" in overrides : 209endpoints .append ({** cfg ,** {key :overrides [key ]for key in ("host" ,"port" )if key in overrides }}) 210if any (_port_active (endpoint )for endpoint in endpoints ): 211raise ProfileError ("a server is listening on this profile's port; stop it before calibration" ,6 ) 212 213 214@contextmanager 215def _managed_exclusive (): 216"""Keep new owner hosts out for the full calibration engine action.""" 217if os .name not in ("posix" ,"nt" ): 218yield 219return 220from strata_control import runtime 221lease = runtime .acquire_activity_lease (shared = False ) 222try : 223active = runtime .active_managed_instances () 224if active : 225raise ProfileError ("stop managed Strata runtime instances before calibration: " + 226", " .join (item ["profile" ]for item in active ),6 ) 227yield 228finally : 229os .close (lease ) 230 231 232def _write_new (path :Path ,payload :bytes )-> None : 233if not path .parent .is_dir (): 234raise ProfileError ("report output directory does not exist" ,5 ) 235descriptor = os .open (path ,os .O_WRONLY | os .O_CREAT | os .O_EXCL ,0o600 ) 236try : 237with os .fdopen (descriptor ,"wb" )as stream : 238stream .write (payload ) 239stream .flush () 240os .fsync (stream .fileno ()) 241except BaseException : 242path .unlink (missing_ok = True ) 243raise 244 245 246def _report_bytes (report :dict )-> bytes : 247try : 248payload = (json .dumps (report ,ensure_ascii = False ,sort_keys = True ,indent = 2 ,allow_nan = False )+ "\n" ).encode ("utf-8" ) 249except (TypeError ,ValueError ): 250raise ProfileError ("calibration returned an invalid report" ,6 )from None 251if len (payload )> MAX_REPORT_BYTES : 252raise ProfileError ("calibration report exceeds 2 MiB" ,6 ) 253return payload 254 255 256def _body_sha256 (report :dict )-> str : 257body = {key :value for key ,value in report .items ()if key != "body_sha256" } 258try : 259encoded = json .dumps (body ,ensure_ascii = False ,sort_keys = True ,separators = ("," ,":" ), 260allow_nan = False ).encode ("utf-8" ) 261except (TypeError ,ValueError ): 262raise ProfileError ("calibration report has invalid values" ,5 )from None 263return hashlib .sha256 (encoded ).hexdigest () 264 265 266def _lock_name (path :Path )-> str : 267return "cal" + hashlib .sha256 (str (path .resolve ()).encode ("utf-8" )).hexdigest ()[:24 ] 268 269 270def measure (ref :str ,output :Path ,* ,exclusive_ack :bool = False ,say = runner = None , 271expected_profile_revision :str | None = None , 272expected_source_sha256 :str | None = None ,job_id :str | None = None , 273progress = None ,cancel_event = None )-> dict : 274"""Run the existing decode sweep, leaving the run config unchanged.""" 275if not exclusive_ack : 276raise ProfileError ("calibration measure requires an exclusive-access acknowledgement" ) 277path ,profile ,revision ,cfg = _target (ref ) 278with profiles ._lock (_lock_name (path )),_managed_exclusive (): 279current_path ,profile ,revision ,cfg = _target (ref ) 280if current_path != path or (expected_profile_revision is not None and 281revision != expected_profile_revision )or \ 282 (expected_source_sha256 is not None and 283_digest (current_path )!= expected_source_sha256 ): 284raise ProfileError ("calibration source changed after review; review again" ,6 ) 285return _measure_locked (ref ,path ,profile ,revision ,cfg ,output ,say = say ,runner = runner , 286job_id = job_id ,progress = progress ,cancel_event = cancel_event ) 287 288 289def _measure_locked (ref :str ,path :Path ,profile :dict | None ,revision :str | None ,cfg :dict , 290output :Path ,* ,say ,runner ,job_id :str | None = None , 291progress = None ,cancel_event = None )-> dict : 292_exclusive_preflight (cfg ,profile ) 293if output .exists ()or output .is_symlink (): 294raise ProfileError ("calibration report path already exists" ,2 ) 295if not output .parent .is_dir ():# before the 19 minute sweep, not after it (#3187) 296raise ProfileError ("report output directory does not exist" ,5 ) 297identity = _identity (path ,cfg ,profile ,revision ) 298cal = _full_folder ("tools.calibrate" ) 299execute = runner or cal .run 300runner_cfg = _runtime_cfg (cfg ,profile ) 301runner_cfg ["exe" ]= str (_resolved (cfg ["exe" ],cfg ,path )) 302runner_cfg ["tokenizer" ]= str (_resolved (cfg ["tokenizer" ],cfg ,path )) 303try : 304if cancel_event is not None and cancel_event .is_set (): 305raise cal .CalibrationCancelled ("calibration cancelled" ) 306result = (execute (runner_cfg ,say = say )if progress is None and cancel_event is None else 307execute (runner_cfg ,say = say ,progress = progress ,cancel_event = cancel_event )) 308except cal .CalibrationCancelled : 309raise ProfileError ("calibration cancelled by operator; config unchanged" ,130 )from None 310except (KeyboardInterrupt ,SystemExit ): 311raise 312except Exception as exc : 313raise ProfileError (f"calibration measurement failed ( { type ( exc ). __name__ } ); config unchanged" ,6 )from None 314if not isinstance (result ,dict )or not isinstance (result .get ("report" ),dict ): 315raise ProfileError ("calibration returned no measurement report" ,6 ) 316settings = _validate_settings (result .get ("settings" )) 317try : 318end_path ,end_profile ,end_revision ,end_cfg = _target (ref ) 319unchanged = path == end_path and identity == _identity (end_path ,end_cfg ,end_profile ,end_revision ) 320except ProfileError : 321unchanged = False 322report = {"schema_version" :1 ,"kind" :"strata.engine.calibration" ,"suite" :SUITE , 323"report_id" :uuid .uuid4 ().hex ,"created_at" :time .time (),"source_config" :str (path ), 324"identity" :identity ,"applicable" :unchanged ,"settings" :settings , 325"measurements" :result ["report" ]} 326if job_id is not None : 327if not re .fullmatch (r"[0-9a-f]{32}" ,job_id ): 328raise ProfileError ("calibration job ID is invalid" ,5 ) 329report ["operation_id" ]= job_id 330report ["body_sha256" ]= _body_sha256 (report ) 331if progress is not None : 332progress ("saving_report" ,0 ,1 ) 333_write_new (output ,_report_bytes (report )) 334if progress is not None : 335progress ("saving_report" ,1 ,1 ) 336return report 337 338 339def load_report (path :Path )-> dict : 340try : 341if not stat .S_ISREG (path .lstat ().st_mode )or path .stat ().st_size > MAX_REPORT_BYTES : 342raise ProfileError ("calibration report must be a regular file under 2 MiB" ,5 ) 343report = json .loads (path .read_text (encoding = "utf-8" )) 344except (OSError ,UnicodeError ,ValueError )as exc : 345if isinstance (exc ,ProfileError ): 346raise 347raise ProfileError (f"cannot read calibration report ( { type ( exc ). __name__ } )" ,5 )from None 348if not isinstance (report ,dict )or type (report .get ("schema_version" ))is not int or \ 349report ["schema_version" ]!= 1 or \ 350report .get ("kind" )!= "strata.engine.calibration" or report .get ("suite" )!= SUITE or \ 351not isinstance (report .get ("identity" ),dict )or not isinstance (report .get ("measurements" ),dict )or \ 352not isinstance (report .get ("source_config" ),str )or \ 353type (report .get ("created_at" ))not in (int ,float )or \ 354not math .isfinite (report ["created_at" ])or \ 355not re .fullmatch (r"[0-9a-f]{32}" ,str (report .get ("report_id" ,"" ))): 356raise ProfileError ("unsupported calibration report" ,5 ) 357_validate_settings (report .get ("settings" )) 358if report .get ("body_sha256" )!= _body_sha256 (report ): 359raise ProfileError ("calibration report contents changed after measurement" ,5 ) 360return report 361 362 363def review (ref :str ,report_path :Path )-> dict : 364path ,profile ,revision ,cfg = _target (ref ) 365report = load_report (report_path ) 366cal = _full_folder ("tools.calibrate" ) 367reasons = [] 368if report ["source_config" ]!= str (path ): 369reasons .append ("source_config_mismatch" ) 370if report .get ("applicable" )is not True : 371reasons .append ("measurement_became_stale" ) 372age = time .time ()- report ["created_at" ] 373if age < - 300 or age > MAX_AGE_SECONDS : 374reasons .append ("report_expired" ) 375try : 376now = _identity (path ,cfg ,profile ,revision ) 377if now != report ["identity" ]: 378reasons .append ("source_engine_model_or_hardware_changed" ) 379except ProfileError as exc : 380reasons .append (f"identity_unavailable: { exc . exit_code } " ) 381after = cal .apply (cfg ["args" ],report ["settings" ]) 382return {"schema_version" :1 ,"report_id" :report .get ("report_id" ),"profile" :profile ["id" ]if profile else None , 383"source_config" :str (path ),"applicable" :not reasons ,"reasons" :reasons , 384"settings" :report ["settings" ],"before_args" :cfg ["args" ],"after_args" :after , 385"measurements" :report ["measurements" ],"model_integrity" :"metadata_only_unverified" } 386 387 388def _smoke (cfg :dict ,source_path :Path )-> int : 389"""Start the candidate and require at least one generated token before writing it.""" 390import strata_tokenizer as st 391from serve .server import StrataEngine ,child_env ,engine_args 392cal = _full_folder ("tools.calibrate" ) 393tokdir = _resolved (cfg ["tokenizer" ],cfg ,source_path ) 394vocab = json .loads ((tokdir / "vocab.json" ).read_text (encoding = "utf-8" )) 395tokens = [None ]* len (vocab ) 396for token ,index in vocab .items (): 397tokens [index ]= token 398tok = st .Tokenizer (tokens , (tokdir / "merges.txt" ).read_text (encoding = "utf-8" ).split ("\n" ), 399json .loads ((tokdir / "token_type.json" ).read_text (encoding = "utf-8" ))) 400engine = StrataEngine (str (_resolved (cfg ["exe" ],cfg ,source_path )),engine_args (cfg ), 401cwd = cfg .get ("cwd" ),log = cfg .get ("log" ),env = child_env (cfg )) 402try : 403ids = cal .chat_ids (tok ,"Say OK." ) 404count = sum (token is not None for token in engine .generate (ids ,16 , {"temperature" :0 },threading .Event ())) 405if count < 1 : 406raise ProfileError ("candidate engine produced no tokens in smoke generation" ,6 ) 407return count 408finally : 409cal .close (engine ) 410 411 412def _replace_bytes (path :Path ,payload :bytes )-> None : 413descriptor ,temp = tempfile .mkstemp (prefix = f". { path . name } -" ,suffix = ".tmp" ,dir = path .parent ) 414try : 415with os .fdopen (descriptor ,"wb" )as stream : 416stream .write (payload ) 417stream .flush () 418os .fsync (stream .fileno ()) 419_atomic_mod .replace (temp ,path ) 420finally : 421if os .path .exists (temp ): 422os .unlink (temp ) 423 424 425def _settings_candidate (hardware_key :str ,result :dict )-> tuple [Path ,bytes | None ,bytes ]: 426"""Prepare setup's remembered calibration without accepting a corrupt store.""" 427target = _full_folder ("setup" ).settings_path () 428try : 429previous = target .read_bytes () 430settings = json .loads (previous .decode ("utf-8" )) 431if not isinstance (settings ,dict ): 432raise ValueError 433except FileNotFoundError : 434previous ,settings = None , {} 435except (OSError ,UnicodeError ,ValueError ): 436raise ProfileError ("setup settings could not be read safely; config unchanged" ,5 )from None 437if previous is not None and len (previous )> MAX_REPORT_BYTES : 438raise ProfileError ("setup settings exceed the calibration rollback size limit; config unchanged" ,5 ) 439cal = settings .get ("calibration" ) 440if cal is None : 441cal = {} 442settings ["calibration" ]= cal 443if not isinstance (cal ,dict ): 444raise ProfileError ("setup calibration store is invalid; config unchanged" ,5 ) 445cal [hardware_key ]= {"settings" :result ["settings" ],"tok_s" :result ["measurements" ].get ("tok_s" ), 446"date" :time .strftime ("%Y-%m-%d" )} 447try : 448proposed = (json .dumps (settings ,indent = 1 ,ensure_ascii = False ,allow_nan = False )+ "\n" ).encode ("utf-8" ) 449except (TypeError ,ValueError ): 450raise ProfileError ("setup settings cannot be serialized; config unchanged" ,5 )from None 451if len (proposed )> MAX_REPORT_BYTES : 452raise ProfileError ("updated setup settings exceed the calibration rollback size limit; config unchanged" ,5 ) 453return target ,previous ,proposed 454 455 456def _backup_directory (path :Path ,* ,create :bool = False )-> Path : 457directory = path .parent / ".strata-calibration-backups" 458try : 459if create : 460_private_mkdir (directory ,exist_ok = True ) 461details = directory .lstat () 462except FileNotFoundError : 463raise ProfileError ("calibration backup directory is missing" ,5 )from None 464except OSError as exc : 465raise ProfileError (f"cannot access calibration backup directory ( { type ( exc ). __name__ } )" ,5 )from None 466if not stat .S_ISDIR (details .st_mode )or (os .name == "posix" and 467 (posix_owner .owner_only_wrong (directory ,details ))): 468raise ProfileError (posix_owner .owner_only_text ("calibration backup directory must be owner-only and not a symlink" ,directory ),5 ) 469return directory 470 471 472def _application_paths (path :Path ,report_id :str ,* ,create :bool = False )-> tuple [Path ,Path ,Path ]: 473directory = _backup_directory (path ,create = create ) 474return (directory / f" { path . stem } - { report_id } .json" , 475directory / f"settings- { report_id } .json" , 476directory / f" { path . stem } - { report_id } .apply.json" ) 477 478 479def _sha256 (payload :bytes | None )-> str | None : 480return hashlib .sha256 (payload ).hexdigest ()if payload is not None else None 481 482 483def _load_application (path :Path ,report :dict )-> dict : 484backup ,settings_backup ,manifest = _application_paths (path ,report ["report_id" ]) 485try : 486details = manifest .lstat () 487if not stat .S_ISREG (details .st_mode )or details .st_size > MAX_APPLICATION_BYTES or \ 488 (os .name == "posix" and (posix_owner .owner_only_wrong (manifest ,details ))): 489raise ProfileError (posix_owner .owner_only_text ("calibration application record is not an owner-only regular file" ,manifest ),5 ) 490data = json .loads (manifest .read_text (encoding = "utf-8" )) 491except FileNotFoundError : 492raise ProfileError ("calibration application record was not found" ,5 )from None 493except (OSError ,ValueError ,UnicodeError )as exc : 494if isinstance (exc ,ProfileError ): 495raise 496raise ProfileError (f"cannot read calibration application record ( { type ( exc ). __name__ } )" ,5 )from None 497expected_keys = {"schema_version" ,"kind" ,"report_id" ,"report_body_sha256" ,"source_config" , 498"profile_revision" ,"before_config_sha256" ,"after_config_sha256" , 499"settings_path" ,"before_settings_sha256" ,"after_settings_sha256" } 500if not isinstance (data ,dict )or set (data )!= expected_keys or \ 501type (data .get ("schema_version" ))is not int or data ["schema_version" ]!= 1 or \ 502data .get ("kind" )!= "strata.engine.calibration.application" or \ 503data .get ("report_id" )!= report ["report_id" ]or \ 504data .get ("report_body_sha256" )!= report ["body_sha256" ]or \ 505data .get ("source_config" )!= str (path )or \ 506data .get ("profile_revision" )!= report ["identity" ].get ("profile_revision" )or \ 507not isinstance (data .get ("settings_path" ),str )or \ 508not Path (data ["settings_path" ]).is_absolute ()or \ 509not (data .get ("before_settings_sha256" )is None or 510isinstance (data ["before_settings_sha256" ],str )and 511re .fullmatch (r"[0-9a-f]{64}" ,data ["before_settings_sha256" ]))or \ 512not isinstance (data .get ("after_settings_sha256" ),str )or \ 513not re .fullmatch (r"[0-9a-f]{64}" ,data ["after_settings_sha256" ])or \ 514not all (isinstance (data .get (key ),str )and re .fullmatch (r"[0-9a-f]{64}" ,data [key ]) 515for key in ("before_config_sha256" ,"after_config_sha256" ))or \ 516data ["before_config_sha256" ]!= report ["identity" ].get ("source_sha256" ): 517raise ProfileError ("calibration application record has an unsupported shape" ,5 ) 518try : 519if data ["settings_path" ]!= str (_full_folder ("setup" ).settings_path ()): 520raise ProfileError ("setup settings path changed since calibration apply" ,5 ) 521except (OSError ,ValueError ): 522raise ProfileError ("setup settings path is unavailable" ,5 )from None 523return {** data ,"backup" :backup ,"settings_backup" :settings_backup ,"manifest" :manifest } 524 525 526def apply_result (ref :str ,report_path :Path ,* ,exclusive_ack :bool = False ,smoke = None , 527expected_report_sha256 :str | None = None )-> dict : 528"""Apply a reviewed result after a candidate smoke test; retain prior config.""" 529if not exclusive_ack : 530raise ProfileError ("calibration apply requires an exclusive-access acknowledgement" ) 531path ,profile ,revision ,cfg = _target (ref ) 532with profiles ._lock (_lock_name (path )),_managed_exclusive (): 533return _apply_locked (ref ,path ,profile ,revision ,cfg ,report_path ,smoke = smoke , 534expected_report_sha256 = expected_report_sha256 ) 535 536 537def _apply_locked (ref :str ,path :Path ,profile :dict | None ,revision :str | None ,cfg :dict , 538report_path :Path ,* ,smoke ,expected_report_sha256 :str | None )-> dict : 539_exclusive_preflight (cfg ,profile ) 540if expected_report_sha256 is not None and \ 541load_report (report_path )["body_sha256" ]!= expected_report_sha256 : 542raise ProfileError ("calibration report changed after review; review again" ,6 ) 543preview = review (ref ,report_path ) 544if not preview ["applicable" ]: 545raise ProfileError ("calibration report is stale: " + ", " .join (preview ["reasons" ]),6 ) 546report = load_report (report_path ) 547if expected_report_sha256 is not None and report ["body_sha256" ]!= expected_report_sha256 : 548raise ProfileError ("calibration report changed after review; review again" ,6 ) 549settings_path ,previous_settings ,new_settings = _settings_candidate (report ["identity" ]["hardware_key" ],report ) 550source = path .read_bytes () 551if hashlib .sha256 (source ).hexdigest ()!= report ["identity" ]["source_sha256" ]: 552raise ProfileError ("run config changed before calibration apply" ,6 ) 553candidate = copy .deepcopy (cfg ) 554candidate ["args" ]= preview ["after_args" ] 555from strata_control import arg_layers 556arg_layers .record_calibration (candidate ,cfg ,report ["settings" ])# the origin is kept: a launch puts these over Auto again (#5132) 557smoke_candidate = _runtime_cfg (candidate ,profile ) 558candidate_bytes = (json .dumps (candidate ,indent = 1 ,ensure_ascii = False )+ "\n" ).encode ("utf-8" ) 559if len (source )> MAX_REPORT_BYTES or len (candidate_bytes )> MAX_REPORT_BYTES : 560raise ProfileError ("run config exceeds the calibration rollback size limit; config unchanged" ,5 ) 561try : 562token_count = smoke (smoke_candidate )if smoke else _smoke (smoke_candidate ,path ) 563except ProfileError : 564raise 565except Exception as exc : 566raise ProfileError (f"candidate smoke generation failed ( { type ( exc ). __name__ } ); config unchanged" ,6 )from None 567if type (token_count )is not int or token_count < 1 : 568raise ProfileError ("candidate smoke generation produced no tokens; config unchanged" ,6 ) 569if path .read_bytes ()!= source : 570raise ProfileError ("run config changed during smoke generation; config unchanged" ,6 ) 571end_path ,end_profile ,end_revision ,end_cfg = _target (ref ) 572if end_path != path or _identity (end_path ,end_cfg ,end_profile ,end_revision )!= report ["identity" ]: 573raise ProfileError ("engine, model or hardware changed during smoke generation; config unchanged" ,6 ) 574_private_mkdir (settings_path .parent ,parents = True ,exist_ok = True ) 575current_settings = settings_path .read_bytes ()if settings_path .exists ()else None 576if current_settings != previous_settings : 577raise ProfileError ("setup settings changed during calibration; config unchanged" ,6 ) 578backup ,settings_backup_path ,manifest = _application_paths (path ,report ["report_id" ],create = True ) 579if any (item .exists ()or item .is_symlink ()for item in (backup ,settings_backup_path ,manifest )): 580raise ProfileError ("calibration result already has application records; measure again" ,6 ) 581application = {"schema_version" :1 ,"kind" :"strata.engine.calibration.application" , 582"report_id" :report ["report_id" ],"report_body_sha256" :report ["body_sha256" ], 583"source_config" :str (path ),"profile_revision" :revision , 584"before_config_sha256" :_sha256 (source ),"after_config_sha256" :_sha256 (candidate_bytes ), 585"settings_path" :str (settings_path ), 586"before_settings_sha256" :_sha256 (previous_settings ), 587"after_settings_sha256" :_sha256 (new_settings )} 588settings_backup = settings_backup_path if previous_settings is not None else None 589written = [] 590try : 591_write_new (backup ,source ) 592written .append (backup ) 593if settings_backup is not None : 594_write_new (settings_backup ,previous_settings ) 595written .append (settings_backup ) 596_write_new (manifest ,_report_bytes (application )) 597written .append (manifest ) 598except (OSError ,ProfileError )as exc : 599for item in written : 600item .unlink (missing_ok = True ) 601raise ProfileError (f"cannot save calibration rollback evidence ( { type ( exc ). __name__ } ); config unchanged" ,6 )from None 602try : 603if candidate_bytes != source : 604_replace_bytes (path ,candidate_bytes ) 605_replace_bytes (settings_path ,new_settings ) 606except Exception as exc : 607# Restore both stores if either write failed; backups remain for manual recovery. 608failed = False 609try : 610_replace_bytes (path ,source ) 611except OSError : 612failed = True 613try : 614if previous_settings is None : 615settings_path .unlink (missing_ok = True ) 616else : 617_replace_bytes (settings_path ,previous_settings ) 618except OSError : 619failed = True 620if failed : 621raise ProfileError (f"calibration apply failed ( { type ( exc ). __name__ } ); restore from { backup } " ,6 )from None 622raise ProfileError (f"calibration apply failed ( { type ( exc ). __name__ } ); config restored" ,6 )from None 623return {"changed" :candidate_bytes != source ,"report_id" :report .get ("report_id" ),"source_config" :str (path ), 624"backup" :str (backup ),"settings_backup" :str (settings_backup )if settings_backup else None , 625"application_record" :str (manifest ), 626"previous_sha256" :hashlib .sha256 (source ).hexdigest (), 627"current_sha256" :hashlib .sha256 (candidate_bytes ).hexdigest (),"smoke_output_tokens" :token_count , 628"setup_settings_persisted" :True } 629 630 631def _saved_bytes (path :Path ,* ,required :bool = True ,owner_only :bool = False )-> bytes | None : 632try : 633details = path .lstat () 634except FileNotFoundError : 635if not required : 636return None 637raise ProfileError ("calibration rollback file is missing" ,5 )from None 638if not stat .S_ISREG (details .st_mode )or details .st_size > MAX_REPORT_BYTES or \ 639 (owner_only and os .name == "posix" and 640 (posix_owner .owner_only_wrong (path ,details ))): 641raise ProfileError (posix_owner .owner_only_text ("calibration rollback file must be a regular owner-only file under 2 MiB" ,path ),5 ) 642try : 643return path .read_bytes () 644except OSError as exc : 645raise ProfileError (f"cannot read calibration rollback file ( { type ( exc ). __name__ } )" ,5 )from None 646 647 648def review_rollback (ref :str ,report_path :Path )-> dict : 649"""Preview an exact rollback without touching engine or settings.""" 650path ,profile ,revision ,cfg = _target (ref ) 651report = load_report (report_path ) 652application = _load_application (path ,report ) 653reasons :list [str ]= [] 654if report ["source_config" ]!= str (path ): 655reasons .append ("source_config_mismatch" ) 656before_config = _saved_bytes (application ["backup" ],owner_only = True ) 657if _sha256 (before_config )!= application ["before_config_sha256" ]: 658reasons .append ("config_backup_changed" ) 659settings_backup = _saved_bytes (application ["settings_backup" ],required = False ,owner_only = True ) 660if _sha256 (settings_backup )!= application ["before_settings_sha256" ]: 661reasons .append ("settings_backup_changed" ) 662current_config = _saved_bytes (path ) 663if _sha256 (current_config )!= application ["after_config_sha256" ]: 664reasons .append ("run_config_changed_after_apply" ) 665current_settings = _saved_bytes (Path (application ["settings_path" ]),required = False ) 666if _sha256 (current_settings )!= application ["after_settings_sha256" ]: 667reasons .append ("setup_settings_changed_after_apply" ) 668try : 669identity = _identity (path ,cfg ,profile ,revision ) 670expected = {** report ["identity" ],"source_sha256" :application ["after_config_sha256" ]} 671if identity != expected : 672reasons .append ("engine_model_hardware_or_profile_changed" ) 673except ProfileError as exc : 674reasons .append (f"identity_unavailable: { exc . exit_code } " ) 675if _port_active (cfg ): 676reasons .append ("profile_port_is_active" ) 677return {"schema_version" :1 ,"report_id" :report ["report_id" ], 678"profile" :profile ["id" ]if profile else None ,"source_config" :str (path ), 679"applicable" :not reasons ,"reasons" :reasons , 680"config_would_change" :application ["before_config_sha256" ]!= application ["after_config_sha256" ], 681"setup_settings_would_be_removed" :application ["before_settings_sha256" ]is None , 682"backup" :str (application ["backup" ]),"application_record" :str (application ["manifest" ]), 683"model_integrity" :"metadata_only_unverified" } 684 685 686def rollback_result (ref :str ,report_path :Path ,* ,exclusive_ack :bool = False ,smoke = None , 687expected_report_sha256 :str | None = None )-> dict : 688"""Smoke-test and restore the prior config/settings only if the applied state is still exact.""" 689if not exclusive_ack : 690raise ProfileError ("calibration rollback requires an exclusive-access acknowledgement" ) 691path ,profile ,revision ,cfg = _target (ref ) 692with profiles ._lock (_lock_name (path )),_managed_exclusive (): 693_exclusive_preflight (cfg ,profile ) 694if expected_report_sha256 is not None and \ 695load_report (report_path )["body_sha256" ]!= expected_report_sha256 : 696raise ProfileError ("calibration report changed after review; review again" ,6 ) 697preview = review_rollback (ref ,report_path ) 698if not preview ["applicable" ]: 699raise ProfileError ("calibration rollback is stale: " + ", " .join (preview ["reasons" ]),6 ) 700report = load_report (report_path ) 701if expected_report_sha256 is not None and report ["body_sha256" ]!= expected_report_sha256 : 702raise ProfileError ("calibration report changed after review; review again" ,6 ) 703application = _load_application (path ,report ) 704before_config = _saved_bytes (application ["backup" ],owner_only = True ) 705before_settings = _saved_bytes (application ["settings_backup" ],required = False ,owner_only = True ) 706current_config = _saved_bytes (path ) 707settings_path = Path (application ["settings_path" ]) 708current_settings = _saved_bytes (settings_path ,required = False ) 709candidate = profiles .read_run_config (application ["backup" ]) 710smoke_candidate = _runtime_cfg (candidate ,profile ) 711try : 712token_count = smoke (smoke_candidate )if smoke else _smoke (smoke_candidate ,path ) 713except ProfileError : 714raise 715except Exception as exc : 716raise ProfileError (f"rollback smoke generation failed ( { type ( exc ). __name__ } ); config unchanged" ,6 )from None 717if type (token_count )is not int or token_count < 1 : 718raise ProfileError ("rollback smoke generation produced no tokens; config unchanged" ,6 ) 719repeated = review_rollback (ref ,report_path ) 720if not repeated ["applicable" ]or _saved_bytes (path )!= current_config or \ 721_saved_bytes (settings_path ,required = False )!= current_settings : 722raise ProfileError ("config or setup settings changed during rollback smoke; config unchanged" ,6 ) 723try : 724if before_config != current_config : 725_replace_bytes (path ,before_config ) 726if before_settings is None : 727settings_path .unlink (missing_ok = True ) 728elif before_settings != current_settings : 729_replace_bytes (settings_path ,before_settings ) 730except Exception as exc : 731failed = False 732try : 733_replace_bytes (path ,current_config ) 734except OSError : 735failed = True 736try : 737if current_settings is None : 738settings_path .unlink (missing_ok = True ) 739else : 740_replace_bytes (settings_path ,current_settings ) 741except OSError : 742failed = True 743if failed : 744raise ProfileError (f"calibration rollback failed ( { type ( exc ). __name__ } ); " 745f"manual recovery may be needed from { application [ 'backup' ] } " ,6 )from None 746raise ProfileError (f"calibration rollback failed ( { type ( exc ). __name__ } ); applied state restored" ,6 )from None 747return {"changed" :before_config != current_config or before_settings != current_settings , 748"report_id" :report ["report_id" ],"source_config" :str (path ), 749"restored_config_sha256" :_sha256 (before_config ), 750"setup_settings_removed" :before_settings is None , 751"smoke_output_tokens" :token_count ,"backup" :str (application ["backup" ])}