okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
bcf88b738
main
1"""Applying a tuning recommendation: explicit, verified and reversible (checklist T07). 2 3A sweep ends at a report, and a report changes nothing. This module is the separate, deliberate step 4that turns one reviewed recommendation into a change to the active run configuration — and it is 5built around the fact that the most dangerous moment in tuning is the gap between measuring a 6configuration and running it for real. 7 8Four things make that safe, and each exists because of a specific way this goes wrong: 9 101. **Explicit, and only from a completed sweep.** There is no default and no automatic application. 11The job must have reached a terminal state with a recommendation, and the report must still hash 12to what was reviewed — a report edited after review is refused, because the review was of 13different numbers. 14 152. **Identity is re-checked before anything is written.** A recommendation measured against one 16engine or one model says nothing about another. If the engine digest, model digest, backend, 17workload or context has changed since the sweep, the apply is refused *with the reason* rather 18than applied to a configuration it was never measured against. 19 203. **The candidate is verified by running it.** The proposed configuration is started and required 21to produce at least one token before the change is written. A configuration that boots but cannot 22generate is the exact failure a benchmark cannot see, because the benchmark never ran the real 23path. 24 254. **Reversal keeps the previous bytes.** The prior configuration is copied aside by digest before 26the write, and rollback restores those bytes — so "apply" is never a one-way door. 27 28The active profile is untouched until the apply step: exploration and application are separate 29commands with separate leases, and neither can be triggered by the other. 30""" 31 32from __future__import annotations 33 34import hashlib 35import json 36import os 37import shutil 38import tempfile 39import time 40from dataclasses import dataclass 41from pathlib import Path 42from typing import Any ,Callable ,Sequence 43 44from strata_control import user_args 45from strata_control import atomic as _atomic_mod 46 47SCHEMA_VERSION = 1 48 49 50class ApplyError (RuntimeError ): 51"""An apply was refused. The message is the reason, and nothing was written.""" 52 53def __init__ (self ,message :str ,code :int = 6 )-> None : 54super ().__init__ (message ) 55self .code = code 56 57 58def _sha256 (payload :bytes )-> str : 59return hashlib .sha256 (payload ).hexdigest () 60 61 62def _atomic_write (path :Path ,payload :bytes )-> None : 63"""Replace a file's contents in one step, so a crash cannot leave it half-written.""" 64descriptor ,temp = tempfile .mkstemp (prefix = f". { path . name } -" ,suffix = ".tmp" ,dir = path .parent ) 65try : 66with os .fdopen (descriptor ,"wb" )as stream : 67stream .write (payload ) 68stream .flush () 69os .fsync (stream .fileno ()) 70_atomic_mod .replace (temp ,path ) 71finally : 72if os .path .exists (temp ): 73os .unlink (temp ) 74 75 76# --------------------------------------------------------------------------- args and configs 77 78def args_to_argv (args :dict [str ,Any ])-> list [str ]: 79"""The recommendation's flags, as argv. 80 81Order is sorted so the same recommendation always produces the same bytes: an apply that 82reshuffled its own output would produce a different digest each time and break the rollback 83comparison. 84""" 85from strata_control .tuning import flag_argv 86out :list [str ]= [] 87for flag in sorted (args ): 88value = args [flag ] 89if value is None or value is False : 90continue 91if value is True : 92out .append (flag ) 93continue 94out .extend (flag_argv (flag ,value )) 95return out 96 97 98def find_config_files (root :Path ,* ,limit :int = 200 )-> list [Path ]: 99"""Every `strata-*.json` run configuration under `root`. 100 101The project keeps one configuration per installed model, and the naming is the project's own 102(`strata-<model>.json`, as `setup.py` writes them). Anything that does not parse as a JSON object 103with an `args` list is not a run configuration and is ignored rather than guessed at. 104""" 105out :list [Path ]= [] 106for path in sorted (Path (root ).rglob ("strata-*.json" )): 107if len (out )>= limit : 108break 109try : 110data = json .loads (path .read_text (encoding = "utf-8" )) 111except (OSError ,json .JSONDecodeError ): 112continue 113if isinstance (data ,dict )and isinstance (data .get ("args" ),list ): 114out .append (path ) 115return out 116 117 118def apply_args_to_config (config :dict [str ,Any ],argv :Sequence [str ])-> dict [str ,Any ]: 119"""Set a recommendation's flags on a configuration, leaving everything else alone. 120 121The rules are narrow on purpose: 122 123* a flag the configuration already carries has **all** of its occurrences replaced, because a 124half-replaced flag is a configuration that does nothing; 125* a flag it does not carry is appended; 126* no other key is touched, so unknown fields, aliases, `env` and `vision` survive — an apply 127that dropped a user's API token would be worse than no apply at all. 128 129`--flag value` and `--flag=value` are both produced as two argv elements, which the engine's 130parser accepts either way. 131""" 132candidate = json .loads (json .dumps (config ))# deep copy, values are JSON 133existing = list (candidate .get ("args" )or []) 134 135# The recommendation's flags, paired. 136wanted :dict [str ,list [str ]]= {} 137i = 0 138while i < len (argv ): 139flag = argv [i ] 140value = argv [i + 1 ]if i + 1 < len (argv )and not argv [i + 1 ].startswith ("--" )else None 141wanted [flag ]= [flag ]if value is None else [flag ,value ] 142i += 2 if value is not None else 1 143 144# Strip every occurrence of each recommended flag, then append the recommendation once. 145stripped :list [str ]= [] 146i = 0 147while i < len (existing ): 148item = str (existing [i ]) 149if item in wanted : 150i += 2 if (i + 1 < len (existing )and not str (existing [i + 1 ]).startswith ("--" ))else 1 151continue 152stripped .append (existing [i ]) 153i += 1 154 155for flag in sorted (wanted ): 156stripped .extend (wanted [flag ]) 157candidate ["args" ]= stripped 158# The person's own options (user_args, strata_control/user_args.py) are kept, except the flags this recommendation sets: a tuning 159# the person asks for is their newer choice. The hand edits so far are recorded first, so writing "args" here loses none. 160if candidate .get (user_args .WRITTEN_KEY )is not None or candidate .get (user_args .USER_KEY ): 161mine = user_args .capture (config ) 162mine = user_args .flat ([g for g in user_args .groups (mine )if user_args .flag_of (g )not in wanted ]) 163user_args .stamp (candidate ,mine ) 164if user_args .WRITTEN_KEY not in config : 165candidate .pop (user_args .WRITTEN_KEY ,None ) 166return candidate 167 168 169# --------------------------------------------------------------------------- the plan 170 171@dataclass 172class ApplyPlan : 173"""What an apply would do, computed before anything is written.""" 174 175job_id :str 176config_path :Path 177before_args :list [str ] 178after_args :list [str ] 179added :list [str ] 180removed :list [str ] 181before_sha256 :str 182after_sha256 :str 183report_sha256 :str 184reasons :list [str ]# non-empty means it will not apply 185 186@property 187def applicable (self )-> bool : 188return not self .reasons 189 190def to_dict (self )-> dict [str ,Any ]: 191return { 192"job_id" :self .job_id , 193"config_path" :str (self .config_path ), 194"before_args" :self .before_args , 195"after_args" :self .after_args , 196"added" :self .added , 197"removed" :self .removed , 198"before_sha256" :self .before_sha256 , 199"after_sha256" :self .after_sha256 , 200"report_sha256" :self .report_sha256 , 201"applicable" :self .applicable , 202"reasons" :self .reasons , 203 } 204 205 206def _diff (before :Sequence [str ],after :Sequence [str ])-> tuple [list [str ],list [str ]]: 207"""Which flags appeared and which disappeared, as `flag value` strings.""" 208def pairs (items :Sequence [str ])-> dict [str ,str ]: 209out :dict [str ,str ]= {} 210i = 0 211while i < len (items ): 212item = str (items [i ]) 213if item .startswith ("--" )and i + 1 < len (items )and not str (items [i + 1 ]).startswith ("--" ): 214out [item ]= str (items [i + 1 ]) 215i += 2 216else : 217out [item ]= "" 218i += 1 219return out 220 221b ,a = pairs (before ),pairs (after ) 222added = [f" { k } { v } " .strip ()for k ,v in sorted (a .items ())if b .get (k )!= v ] 223removed = [f" { k } { v } " .strip ()for k ,v in sorted (b .items ())if a .get (k )!= v ] 224return added ,removed 225 226 227def review_apply (* ,job :dict [str ,Any ],config_path :Path , 228current_identity :dict [str ,Any ]| None , 229report_sha256 :str | None = None )-> ApplyPlan : 230"""Decide whether this job's recommendation may be applied to this configuration. 231 232Every refusal names what is wrong. An apply that silently proceeded on a stale or incompatible 233report would be the single most damaging thing this module could do, so the checks are exhaustive 234and each one is a reason rather than a bare `False`. 235""" 236reasons :list [str ]= [] 237report = job .get ("report" )or {} 238job_id = str (job .get ("id" )or "" ) 239 240if job .get ("state" )!= "completed" : 241reasons .append (f"the sweep is { job . get ( 'state' ) } , not completed; its result is not final" ) 242if not report .get ("recommendation_available" )or not report .get ("recommendation" ): 243reasons .append ("the sweep recommended no change: " + str (report .get ("reason" )or "no reason recorded" )) 244if report .get ("drift_material" ): 245drift = report .get ("drift" )or {} 246reasons .append ( 247f"the machine drifted by { float ( drift . get ( 'relative' , 0 )) * 100 :+.1f } % during the sweep, " 248"so the comparison does not support a change" ) 249if not config_path .exists (): 250reasons .append (f"no run configuration at { config_path } " ) 251return ApplyPlan (job_id ,config_path , [], [], [], [],"" ,"" ,"" ,reasons ) 252 253source = config_path .read_bytes () 254before = json .loads (source .decode ("utf-8" )) 255before_args = [str (x )for x in (before .get ("args" )or [])] 256 257rec = report .get ("recommendation" )or {} 258argv = args_to_argv (rec .get ("args" )or {}) 259if not argv : 260reasons .append ("the recommendation carries no flags, so there is nothing to apply" ) 261 262candidate = apply_args_to_config (before ,argv ) 263after_args = [str (x )for x in candidate ["args" ]] 264added ,removed = _diff (before_args ,after_args ) 265if not added and not removed : 266reasons .append ("the configuration already carries this recommendation; nothing would change" ) 267 268# The report has to be the one that was reviewed. 269if report_sha256 is not None and report_sha256 != _report_digest (job ): 270reasons .append ("the sweep report changed after review; review it again" ) 271 272# And it has to have been measured on what is installed now. 273if current_identity is not None : 274from strata_control import tune_history 275recorded = report .get ("identity" )or {} 276if not recorded : 277reasons .append ("the sweep recorded no artifact identity, so it cannot be matched to what " 278"is installed now" ) 279else : 280differences = tune_history .incomparable_reasons (recorded ,current_identity ) 281if differences : 282reasons .append ("the sweep was measured against a different configuration: " 283+ ", " .join (differences )) 284 285after_bytes = (json .dumps (candidate ,indent = 1 ,ensure_ascii = False )+ "\n" ).encode ("utf-8" ) 286return ApplyPlan ( 287job_id = job_id ,config_path = config_path ,before_args = before_args ,after_args = after_args , 288added = added ,removed = removed ,before_sha256 = _sha256 (source ),after_sha256 = _sha256 (after_bytes ), 289report_sha256 = _report_digest (job ),reasons = reasons ) 290 291 292def _report_digest (job :dict [str ,Any ])-> str : 293"""A digest of the report, so a review cannot be reused for edited numbers.""" 294body = json .dumps (job .get ("report" )or {},sort_keys = True ,separators = ("," ,":" )) 295return _sha256 (body .encode ("utf-8" )) 296 297 298# --------------------------------------------------------------------------- applying 299 300def _application_dir (root :Path )-> Path : 301d = Path (root )/ "applications" 302d .mkdir (parents = True ,exist_ok = True ) 303return d 304 305 306def apply_recommendation (* ,job :dict [str ,Any ],config_path :Path , 307current_identity :dict [str ,Any ]| None , 308state_dir :Path , 309verify :Callable [[dict [str ,Any ]],int ]| None = None , 310expected_report_sha256 :str | None = None )-> dict [str ,Any ]: 311"""Verify the candidate by running it, then write it — keeping the previous bytes. 312 313`verify` receives the candidate configuration and must return the number of tokens generated. 314A result below 1 is a refusal, not a warning: a configuration that cannot produce a token has not 315been verified, whatever the sweep measured. 316""" 317plan = review_apply (job = job ,config_path = config_path ,current_identity = current_identity , 318report_sha256 = expected_report_sha256 ) 319if not plan .applicable : 320raise ApplyError ("; " .join (plan .reasons )) 321 322before = json .loads (config_path .read_text (encoding = "utf-8" )) 323candidate = apply_args_to_config (before ,args_to_argv ( 324 (job .get ("report" )or {}).get ("recommendation" , {}).get ("args" )or {})) 325 326verified_tokens :int | None = None 327if verify is not None : 328try : 329tokens = verify (candidate ) 330except Exception as exc :# noqa: BLE001 331raise ApplyError ( 332f"the candidate configuration failed verification ( { type ( exc ). __name__ } : { exc } ); " 333"the run configuration is unchanged" )from None 334if type (tokens )is not int or tokens < 1 : 335raise ApplyError ("the candidate configuration generated no tokens; the run " 336"configuration is unchanged" ) 337verified_tokens = int (tokens ) 338 339# Re-read after verification: a user edit during a long verification must not be overwritten. 340if _sha256 (config_path .read_bytes ())!= plan .before_sha256 : 341raise ApplyError ("the run configuration changed during verification; nothing was written" ) 342 343application_id = f" { time . strftime ( '%Y%m%dT%H%M%SZ' , time . gmtime ()) } - { plan . job_id [: 12 ] } " 344directory = _application_dir (state_dir )/ application_id 345if directory .exists (): 346raise ApplyError (f"an application record already exists at { directory } " ) 347directory .mkdir (parents = True ) 348shutil .copy2 (config_path ,directory / "before.json" ) 349 (directory / "candidate.json" ).write_bytes ( 350 (json .dumps (candidate ,indent = 1 ,ensure_ascii = False )+ "\n" ).encode ("utf-8" )) 351 352_atomic_write (config_path , (json .dumps (candidate ,indent = 1 ,ensure_ascii = False )+ "\n" ).encode ("utf-8" )) 353 354record = { 355"schema_version" :SCHEMA_VERSION , 356"kind" :"strata.tuning.application" , 357"application_id" :application_id , 358"job_id" :plan .job_id , 359"applied_at" :time .time (), 360"config_path" :str (config_path ), 361"before_sha256" :plan .before_sha256 , 362"after_sha256" :plan .after_sha256 , 363"report_sha256" :plan .report_sha256 , 364"added" :plan .added , 365"removed" :plan .removed , 366"verified_tokens" :verified_tokens , 367"rolled_back" :False , 368 } 369 (directory / "application.json" ).write_text (json .dumps (record ,indent = 2 )+ "\n" ,encoding = "utf-8" ) 370return {"application" :record ,"directory" :str (directory ),"plan" :plan .to_dict ()} 371 372 373def rollback (* ,application_id :str ,state_dir :Path )-> dict [str ,Any ]: 374"""Restore the configuration that was in place before an apply. 375 376Refuses if the configuration has been edited since the apply, because restoring would then 377discard a deliberate change: the user's edit wins, and the conflict is reported. 378""" 379directory = _application_dir (state_dir )/ application_id 380record_path = directory / "application.json" 381if not record_path .exists (): 382raise ApplyError (f"no application record at { record_path } " ,404 ) 383record = json .loads (record_path .read_text (encoding = "utf-8" )) 384if record .get ("rolled_back" ): 385raise ApplyError ("this application has already been rolled back" ) 386before = directory / "before.json" 387if not before .exists (): 388raise ApplyError (f"the previous configuration was not retained at { before } " ) 389target = Path (record ["config_path" ]) 390if not target .exists (): 391raise ApplyError (f"the run configuration is gone: { target } " ) 392current = _sha256 (target .read_bytes ()) 393if current != record ["after_sha256" ]: 394raise ApplyError ( 395"the run configuration changed after this apply, so restoring would discard a newer " 396"change; nothing was written" ,409 ) 397_atomic_write (target ,before .read_bytes ()) 398record ["rolled_back" ]= True 399record ["rolled_back_at" ]= time .time () 400record_path .write_text (json .dumps (record ,indent = 2 )+ "\n" ,encoding = "utf-8" ) 401return {"application" :record ,"restored" :str (target )}