okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aff3a132f
main
1"""An engine update beside a loaded model: the notice, the warning, the clean stop and the start again. 2 3The rule (owner, 11-01): an engine update never starts by itself while a model is loaded, and nothing replaces or removes the engine a running 4model uses. An update that finds a model loaded does one of three things, and never a fourth: 5 6* nobody can be asked (a script, the app without a dialog, a service): it stops BEFORE any download and changes nothing (exit 7), and says 7the two next steps; 8* the person said yes (the question in a terminal, ``--stop-model`` in a script): the new engine is downloaded while the model keeps 9serving, then the model is stopped cleanly, the update is made, and the model is started again with the same settings when the person says so 10(the question in a terminal, ``--start-again`` in a script; otherwise it stays stopped and the way to start it is printed); 11* the person said no: nothing is changed (exit 0). 12 13``ModelGate`` is the one object the update (strata_control/updater.py) calls at its two points: ``consent`` before anything is downloaded, and 14``release`` after the download, right before the first thing is staged or test-started. ``update_with_models`` runs a whole update around it 15and starts the models again afterwards, also when the update failed (the old engine is still in use). 16 17``notice`` is the one quiet line the Terminal shows when the last check found a newer engine. It reads the cached check only (a local 18file) and never touches the network, so showing it breaks no rule. ``refresh_cache`` is the daily check, written but not called by anything: 19adding it to a screen is one line, and waits for the owner's yes (the Terminal learns of a new engine only from a check somebody made). 20""" 21 22from __future__import annotations 23 24import datetime as dt 25import json 26import threading 27from dataclasses import dataclass ,field 28from pathlib import Path 29from typing import Callable 30 31from strata_control import engine_component as ec ,updater 32 33EXIT_BUSY = 7 # a loaded model, nothing was changed (the updater's own code) 34EXIT_NOT_RESTARTED = 8 # the update is done (or failed and the old engine is in use) but a model did not start again 35NEXT_STEP = "`strata update`" 36 37 38# ---------------------------------------------------------------------------------------------------- the notice 39 40def _installed_words (root )-> dict : 41return {"engine" :ec .newest_installed_version (root )} 42 43 44def notice (root = None )-> dict | None : 45"""What the last check found newer, as {"engine": v, "have": {...}, "line": plain sentence}, or None. Local files only.""" 46offers = ec .cached_offers (root ) 47engine = offers .get ("engine" ) 48if not engine : 49return None 50have = _installed_words (root ) 51head = "A new " + f"engine { engine } " + (f" (you have { have [ 'engine' ] } )" if have ["engine" ]else "" )+ " is available" 52return {"engine" :engine ,"have" :have ,"line" :head } 53 54 55def notice_line (root = None ,how :str = f"Update with { NEXT_STEP } ." )-> str | None : 56"""The single quiet line: what is new and the one next step. ``how`` is the screen's own way (the monitor says "Press u or run ...").""" 57found = notice (root ) 58return None if found is None else f" { found [ 'line' ] } . { how } " 59 60 61ATTEMPT_FILE = "notice-attempt.json" 62CHECK_TIMEOUT_S = 5.0 # one read of the feed waits this long at most (twice: the transfer layer tries a web address once more) 63CHECK_ENV = "STRATA_UPDATE_CHECK" # "0" / "off": no daily check (a tester's or a privacy switch; the default is on in the launch monitor only) 64 65 66def _hours_since (text )-> float | None : 67try : 68return (dt .datetime .now (dt .timezone .utc )- dt .datetime .fromisoformat (str (text ))).total_seconds ()/ 3600.0 69except (TypeError ,ValueError ): 70return None 71 72 73def refresh_cache (check :Callable [[],object ],root = None ,* ,max_age_hours :float = 24.0 )-> bool : 74"""The daily check, quiet by design: run ``check()`` (updater.check: it reads the signed feed, writes the cache, downloads no engine) when neither 75the last check nor the last ATTEMPT is younger than ``max_age_hours``. The attempt is written BEFORE the network is touched, so a PC with no 76internet, a blocked DNS, a proxy, a captive portal that answers junk or a connection that never answers is asked once a day and not again until 77tomorrow. Nothing is printed or logged, whatever happens. True when it ran.""" 78import os 79if os .environ .get (CHECK_ENV ,"" ).strip ().lower ()in ("0" ,"off" ,"no" ,"false" ,"never" ): 80return False 81base = Path (root )if root else ec .components_dir () 82try : 83last = json .loads ((base / ec .UPDATE_STATE ).read_text (encoding = "utf-8-sig" )).get ("last_check" , {}).get ("at" ) 84except (OSError ,ValueError ,AttributeError ): 85last = None 86try : 87tried = json .loads ((base / updater .STATE_DIR / ATTEMPT_FILE ).read_text (encoding = "utf-8" )).get ("at" ) 88except (OSError ,ValueError ,AttributeError ): 89tried = None 90for stamp in (last ,tried ): 91age = _hours_since (stamp ) 92if age is not None and age < max_age_hours : 93return False 94try : 95folder = base / updater .STATE_DIR 96folder .mkdir (parents = True ,exist_ok = True ) 97 (folder / ATTEMPT_FILE ).write_text (json .dumps ({"at" :dt .datetime .now (dt .timezone .utc ).isoformat ()}),encoding = "utf-8" ) 98except OSError : 99return False # cannot remember the attempt: do not risk asking again and again 100try : 101check () 102except BaseException :# noqa: BLE001 - quiet: no network, no notice 103return False 104return True 105 106 107def start_daily_check (on_done :Callable [[],None ]| None = None ,root = None ,* ,feed :str | None = None )-> "threading.Thread | None" : 108"""Run the daily check in a thread of its own (a daemon: nothing ever waits for it, and a connection that never answers is simply left behind 109when the program ends). ``on_done`` is called when a check finished well. Used by the launch monitor only.""" 110import threading 111from strata_control import acquisition 112if acquisition .is_forbidden (): 113return None 114 115def work ()-> None : 116try : 117def check (): 118import argparse 119from strata_cli import update_cmd 120from strata_control import signing 121base = Path (root )if root else ec .components_dir () 122ctx = updater .Context (components = base ,source = update_cmd ._feed_source (argparse .Namespace (feed = feed ),base ),trusted = signing .load_trusted_keys (), 123hardware = updater .detect_hardware (),feed_timeout = CHECK_TIMEOUT_S ,serving = lambda : []) 124return updater .check (ctx ) 125if refresh_cache (check ,root )and on_done is not None : 126on_done () 127except BaseException :# noqa: BLE001 - never a message, never a trace 128pass 129thread = threading .Thread (target = work ,name = "strata-daily-check" ,daemon = True ) 130thread .start () 131return thread 132 133 134def monitor_note (root = None )-> str | None : 135"""The short form of the notice for the monitor's one message line.""" 136found = notice (root ) 137if found is None : 138return None 139return f"New engine { found [ 'engine' ] } is available. Press u to update." 140 141 142# ---------------------------------------------------------------------------------------------------- models that are loaded 143 144@dataclass 145class RunningModel : 146profile :str 147name :str 148state :str = "ready" 149port :int | None = None 150kind :str = "launch" # launch (strata launch), profile (the app's or a saved profile), server (a Strata server nobody here started) 151can_stop :bool = True 152choices :dict | None = field (default = None ,repr = False ) 153 154@property 155def label (self )-> str : 156return self .name + (f" (port { self . port } )" if self .port else "" ) 157 158def to_dict (self )-> dict : 159return {"profile" :self .profile ,"name" :self .name ,"port" :self .port ,"kind" :self .kind ,"state" :self .state } 160 161 162def _launch_dir ()-> Path | None : 163try : 164from strata_cli .launch .runner import launch_dir 165return launch_dir () 166except Exception :# noqa: BLE001 167return None 168 169 170def _saved_choices (profile :str )-> dict | None : 171folder = _launch_dir () 172if folder is None or not profile .startswith ("launch-" ): 173return None 174try : 175return json .loads ((folder / f" { profile [ 7 :] } .choices.json" ).read_text (encoding = "utf-8" )) 176except (OSError ,ValueError ): 177return None 178 179 180def running_models (serving :list [dict ]| None = None )-> list [RunningModel ]: 181"""The models that are loaded, named in words a person knows. ``serving`` is updater.serving_now()'s answer (called here when not given).""" 182from strata_control import profiles 183items = updater .serving_now ()if serving is None else serving 184out = [] 185for item in items : 186pid = str (item .get ("profile" ,"" )) 187state = str (item .get ("state" ,"ready" )) 188if not profiles .PROFILE_ID .fullmatch (pid ):# "a running Strata server": the shared lease, held by a process that is not Strata's own launch 189out .append (RunningModel (pid or "a running Strata server" ,pid or "A Strata server" ,state ,None ,"server" ,can_stop = False )) 190continue 191name ,port = pid [7 :]if pid .startswith ("launch-" )else pid ,None 192try : 193prof ,_rev = profiles .load (pid ) 194port = int ((prof .get ("overrides" )or {}).get ("port" )or 0 )or None 195cfg = json .loads (Path (prof ["source_config" ]).read_text (encoding = "utf-8-sig" ))if prof .get ("source_config" )else {} 196name = str (cfg .get ("model_name" )or name ) 197except Exception :# noqa: BLE001 - the name is a nicety 198pass 199out .append (RunningModel (pid ,name ,state ,port ,"launch" if pid .startswith ("launch-" )else "profile" ,True ,_saved_choices (pid ))) 200return out 201 202 203def _names (models :list [RunningModel ])-> str : 204labels = [m .label for m in models ] 205return labels [0 ]if len (labels )== 1 else ", " .join (labels [:- 1 ])+ " and " + labels [- 1 ] 206 207 208def stop_model (model :RunningModel ,timeout :float = 180 )-> None : 209from strata_control import runtime 210runtime .stop (model .profile ,timeout = timeout ) 211try : 212from strata_cli .launch import access 213access .stop_tunnel (model .profile ) 214except Exception :# noqa: BLE001 - no tunnel, or none to stop 215pass 216 217 218def _start_wait (model :RunningModel )-> float : 219try : 220from strata_control import profiles 221prof ,_rev = profiles .load (model .profile ) 222cfg = json .loads (Path (prof ["source_config" ]).read_text (encoding = "utf-8-sig" )) 223return min (1800.0 ,float (cfg .get ("engine_ready_s" )or 900 )+ 60 )# (runtime.start takes 0..1800; a DeepSeek config asks for more) 224except Exception :# noqa: BLE001 225return 960.0 226 227 228def start_model (model :RunningModel )-> tuple [bool ,str ]: 229"""Start the saved profile again: the same run config and overrides, so the same settings. (ok, a plain sentence).""" 230from strata_control import runtime 231cfg_path = None 232try : 233from strata_control import profiles 234cfg_path = Path (profiles .load (model .profile )[0 ]["source_config" ]) 235except Exception :# noqa: BLE001 236pass 237why = "" 238try : 239result = runtime .start (model .profile ,wait = _start_wait (model )) 240if result .get ("ok" ): 241if (model .choices or {}).get ("access" )== "cloudflare" : 242try : 243from strata_cli .launch import access 244access .start_tunnel (model .profile ,int (model .port or 8080 )) 245except Exception :# noqa: BLE001 - the model serves on this computer; the tunnel is said not to be back 246return True ,f" { model . label } is serving again; its Cloudflare tunnel did not open, start it again with `strata launch`." 247return True ,f" { model . label } is serving again with the same settings." 248try : 249from strata_cli .launch .runner import explain_engine_exit 250why = explain_engine_exit (result ,cfg_path )[0 ] 251except Exception :# noqa: BLE001 252why = str (result .get ("error" )or result .get ("next_action" )or result .get ("state" )or "it stopped at its start" ) 253except Exception as exc :# noqa: BLE001 - a refused or failed start is a sentence, never a trace 254why = str (exc ) 255for call in (lambda :runtime .stop (model .profile ,timeout = 30 ),lambda :runtime .cleanup (model .profile )): 256try : 257call () 258except Exception :# noqa: BLE001 - nothing may stay half alive 259pass 260return False ,f" { model . label } did not start again: { why . rstrip ( '.' ) } ." 261 262 263def start_hint (model :RunningModel )-> str : 264"""The way to start a stopped model by hand: the launch line of its saved choices when they can be read, else the command.""" 265if model .choices : 266try : 267from strata_cli .launch import settings as S 268return S .flags_text (S .LaunchSettings .from_dict ({** model .choices ,"name" :model .name })) 269except Exception :# noqa: BLE001 270pass 271return "`strata launch` (the screens start from your saved presets)" 272 273 274# ---------------------------------------------------------------------------------------------------- the gate 275 276class Declined (updater .UpdateError ): 277"""The person said no: nothing was changed. Exit 0.""" 278 279def __init__ (self ,message :str ): 280super ().__init__ (message ,0 ) 281 282 283class ModelGate : 284"""What the updater asks when a model is loaded. ``ask(question, default) -> bool`` is a person (None: nobody can be asked); 285``allow_stop`` is the explicit yes of a script; ``start_again`` the explicit yes to the start-again question of a script. ``say`` shows a 286line; ``emit`` gets one event per step (the app's host reads them from ``strata update --output jsonl``).""" 287 288def __init__ (self ,* ,ask :Callable [[str ,bool ],bool ]| None = None ,say :Callable [[str ],None ]= lambda text :None , 289emit :Callable [[dict ],None ]= lambda event :None ,allow_stop :bool = False ,start_again :bool = False ,settle_s :float = 120.0 , 290stop :Callable [[RunningModel ],None ]| None = None ,start :Callable [[RunningModel ],tuple [bool ,str ]]| None = None ): 291self .ask ,self .say ,self .emit = ask ,say ,emit 292self .allow_stop ,self .start_again ,self .settle_s = allow_stop ,start_again ,settle_s 293self ._stop ,self ._start = stop or stop_model ,start or start_model # (looked up now, so a test or a host can replace them) 294self .consented :dict [str ,RunningModel ]= {} 295self .stopped :list [RunningModel ]= [] 296self .restarts :list [dict ]= [] 297 298# -- before anything is downloaded 299def consent (self ,serving :list [dict ],plan :str )-> None : 300models = running_models (serving ) 301loose = [m for m in models if not m .can_stop ] 302if loose : 303raise updater .UpdateError ( 304f" { _names ( loose ) } is serving, and Strata did not start it from here (a service, `strata serve` or another program), so it cannot be " 305f"stopped for you. Stop it yourself, then run { NEXT_STEP } again. Nothing was changed." ,EXIT_BUSY ) 306names = _names (models ) 307self .emit ({"event" :"models" ,"phase" :"consent" ,"models" : [m .to_dict ()for m in models ],"message" :f" { names } is running" }) 308if not self .allow_stop : 309if self .ask is None : 310raise updater .UpdateError ( 311f" { names } { 'is' if len ( models ) == 1 else 'are' } running, and the update needs " 312f" { 'it' if len ( models ) == 1 else 'them' } stopped, so nothing was changed. To let the update stop " 313f" { 'it' if len ( models ) == 1 else 'them' } : run { NEXT_STEP } again with --stop-model (add --start-again to start " 314f" { 'it' if len ( models ) == 1 else 'them' } again afterwards). Or stop { 'it' if len ( models ) == 1 else 'them' } yourself first " 315f"(`strata launch --stop`)." ,EXIT_BUSY ) 316self .say (f" { names } { 'is' if len ( models ) == 1 else 'are' } running. { plan } The new engine is downloaded while " 317f" { 'it keeps' if len ( models ) == 1 else 'they keep' } serving; then { 'it is' if len ( models ) == 1 else 'they are' } stopped " 318f"(answers in progress end), the engine is updated, and you choose whether to start " 319f" { 'it' if len ( models ) == 1 else 'them' } again with the same settings." ) 320if not self .ask (f"Stop { names } for the update?" ,False ): 321raise Declined ("Nothing was changed. The model keeps running." ) 322for m in models : 323self .consented [m .profile ]= m 324 325# -- after the download, before the first thing is staged or test-started 326def release (self ,serving_now :Callable [[],list [dict ]])-> None : 327serving = serving_now () 328if not serving : 329return 330models = running_models (serving ) 331new = [m for m in models if m .profile not in self .consented ] 332if new :# started after the yes: not covered by it 333names = _names (new ) 334if self .ask is not None and not self .allow_stop : 335self .say (f" { names } started while the update was downloading." ) 336if self .ask (f"Stop { names } too?" ,False ): 337for m in new : 338self .consented [m .profile ]= m 339new = [] 340if new : 341raise updater .UpdateError ( 342f" { names } started while the update was running, and nobody agreed to stop it, so nothing more was changed. " 343f"Stop it, then run { NEXT_STEP } again (the download is kept)." ,EXIT_BUSY ) 344for m in models : 345self .emit ({"event" :"models" ,"phase" :"stopping" ,"models" : [m .to_dict ()],"message" :f"Stopping { m . label } " }) 346self .say (f"Stopping { m . label } (answers in progress end first)..." ) 347try : 348self ._stop (m ) 349except Exception as exc :# noqa: BLE001 350raise updater .UpdateError (f" { m . label } could not be stopped ( { exc } ). Nothing was changed; it may still be running." ,EXIT_BUSY )from None 351if m .profile not in {s .profile for s in self .stopped }: 352self .stopped .append (m ) 353self .emit ({"event" :"models" ,"phase" :"stopped" ,"models" : [m .to_dict ()],"message" :f" { m . label } is stopped" }) 354self ._settle (serving_now ) 355 356def _settle (self ,serving_now :Callable [[],list [dict ]])-> None : 357"""A stopped engine lets go of the card and of the shared lease a moment later (a big DeepSeek model takes a while to unload): wait for that, 358up to ``settle_s``, before the update goes on. Found by the real DeepSeek flow, where the very next check still saw "a running Strata server".""" 359import time 360deadline = time .monotonic ()+ self .settle_s 361while serving_now (): 362if time .monotonic ()>= deadline : 363raise updater .UpdateError ("The model was stopped but its engine has not let go of the graphics card yet, so nothing more was changed. " 364f"Wait a minute and run { NEXT_STEP } again." ,EXIT_BUSY ) 365time .sleep (min (1.0 ,self .settle_s / 10 or 0.1 )) 366 367# -- after the update, whatever happened 368def finish (self ,update_ok :bool ,changed :bool | None = None )-> bool : 369"""Start the stopped models again when the person says so. True when every model that was meant to start did.""" 370everyone = True 371for m in self .stopped : 372if update_ok or changed : 373question = f"Start { m . label } again with the same settings?" 374else : 375question = f"The old engine is unchanged. Start { m . label } again on it?" 376if self .start_again : 377yes = True 378elif self .ask is not None : 379yes = self .ask (question ,True ) 380else : 381yes = False 382if not yes : 383hint = start_hint (m ) 384self .say (f" { m . label } is stopped. Start it when you want with { hint } " ) 385self .restarts .append ({** m .to_dict (),"restarted" :False ,"asked" :self .ask is not None or self .start_again }) 386self .emit ({"event" :"models" ,"phase" :"left-stopped" ,"models" : [m .to_dict ()],"message" :f" { m . label } stays stopped" ,"start" :hint }) 387continue 388self .emit ({"event" :"models" ,"phase" :"restarting" ,"models" : [m .to_dict ()],"message" :f"Starting { m . label } again" }) 389self .say (f"Starting { m . label } again (loading can take a few minutes)..." ) 390ok ,text = self ._start (m ) 391self .say (text ) 392if not ok : 393everyone = False 394self .say (f"The engine is not the problem if this is a one-off: start it with { start_hint ( m ) } " ) 395self .restarts .append ({** m .to_dict (),"restarted" :ok ,"asked" :True ,"message" :text }) 396self .emit ({"event" :"models" ,"phase" :"restarted" if ok else "restart-failed" ,"models" : [m .to_dict ()],"message" :text }) 397return everyone 398 399def report (self )-> dict : 400return {"stopped" : [m .to_dict ()for m in self .stopped ],"restarts" :list (self .restarts )} 401 402 403def update_with_models (ctx :"updater.Context" ,gate :ModelGate ,show :Callable [[dict ],None ]| None = None ,** kwargs )-> dict : 404"""``updater.run_update`` with the gate attached, and the stopped models started again afterwards (also when the update failed or was refused 405after a model had been stopped). Returns run_update's answer plus ``models`` and, if a model did not start again, exit code 8. 406Raises what run_update raises (Busy, Declined, a refused feed) after the models have had their chance to start again.""" 407ctx .gate = gate 408ok ,out ,error ,changed = False ,None ,None ,False 409try : 410out = updater .run_update (ctx ,** kwargs ) 411ok = out ["exit_code" ]== 0 412changed = any (r .get ("changed" )for r in out ["results" ]) 413if show is not None : 414show (out )# what the update did comes before the questions about the models 415except Exception as exc :# noqa: BLE001 - restarted below, then re-raised 416error = exc 417restarted = gate .finish (ok ,changed )if gate .stopped else True 418if error is not None : 419raise error 420out ["models" ]= gate .report () 421if not restarted and out ["exit_code" ]in (0 ,6 ): 422out ["exit_code" ]= EXIT_NOT_RESTARTED if out ["exit_code" ]== 0 else out ["exit_code" ] 423return out 424 425 426def build_context (root = None ,feed :str | None = None ,emit :Callable [[dict ],None ]= lambda event :None )-> "updater.Context" : 427"""The update's context as `strata update` builds it: this computer's hardware, the trusted keys, the feed the person or the install uses.""" 428import argparse 429from strata_cli import update_cmd 430from strata_control import signing 431base = Path (root )if root else ec .components_dir () 432return updater .Context (components = base ,source = update_cmd ._feed_source (argparse .Namespace (feed = feed ),base ),trusted = signing .load_trusted_keys (), 433hardware = updater .detect_hardware (),emit = emit ) 434 435 436def summary (out :dict )-> str : 437"""One plain sentence for what an update did, for a screen that has one line (the monitor).""" 438parts = [] 439for r in out .get ("results" , []): 440name = {"engine" :"Engine" ,"control" :"Control" }.get (r .get ("component" ),str (r .get ("component" ))) 441status = r .get ("status" ) 442if status == "updated" : 443parts .append (f" { name } is now { r . get ( 'installed_after' ) if isinstance ( r . get ( 'installed_after' ), str ) else ( r . get ( 'installed_after' ) or {}). get ( 'version' , 'new' ) } " ) 444elif status == "failed" : 445parts .append (f" { name } was not changed: { str ( r . get ( 'error' , '' )). rstrip ( '.' ) } " ) 446text = "; " .join (parts )or "Nothing needed updating." 447for r in (out .get ("models" )or {}).get ("restarts" , []): 448text += " " + (r .get ("message" )or (f" { r [ 'name' ] } is stopped." if not r .get ("restarted" )else f" { r [ 'name' ] } is serving again." )) 449return text 450 451 452def run_flow (* ,ask ,say ,emit :Callable [[dict ],None ]= lambda event :None ,allow_stop :bool = False ,start_again :bool = False , 453feed :str | None = None ,root = None ,engine :bool = True ,control :bool = True )-> dict : 454"""The whole opt-in update for a screen that cannot print (the monitor) or a host (the app): build the context, attach the gate, run, start the 455models again. Raises what the update raises (Declined, Busy, a refused feed): the caller shows ``str(exc)``.""" 456ctx = build_context (root ,feed ,emit ) 457gate = ModelGate (ask = ask ,say = say ,emit = emit ,allow_stop = allow_stop ,start_again = start_again ) 458return update_with_models (ctx ,gate ,engine = engine ,control = control )