okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
40df1f76f
main
1"""The component updater: the one explicit step that downloads and installs engines (and Control, and the app installer). 2 3Everything that fetches software lives behind this module. Starting or serving never imports it (`acquisition.require` 4refuses here when ``STRATA_NO_ACQUIRE`` is set), so a PC that only runs models never reaches the network. 5 6What an engine update does, in order, and what keeps the old engine safe at each point: 7 81. read the signed feed (`feed.py`); a bad signature, an expired feed or an older sequence number ends here; 92. detect the hardware and pick the best package that fits it (`feed.select_engine`); nothing newer, nothing to do; 103. refuse to go on while an engine is serving (wait, or ask); 114. download the archive next to the component folder with resume and progress; the SHA-256 in the signed feed decides; 125. unpack it into a *staging* component folder (``.updates/staging/<id>/engine/<name>``), never into the live ``engine/``; 136. check the package: the manifest is the one the feed named (SHA-256), says what the feed says, carries a valid 14signature, every file matches its recorded hash, and it fits this PC; 157. **test-start** it from the staging folder through the real start path (owner runtime, a saved model, one token); 168. only if that passed, move it into ``engine/`` (a rename), re-resolve to confirm it is the one a start will pick, record the 17previous version for a manual rollback, and mark saved tuning presets for the short re-check. 18 19If any step fails, the live ``engine/`` folder has not changed: the previous engine keeps working, and what failed is 20named. Every older engine stays installed until the person deletes it (Settings > Engine, ``strata components remove``); 21``strata components use`` / ``rollback`` switch between them. 22Models and presets are never read, moved, deleted or downloaded here. 23""" 24 25from __future__import annotations 26 27import contextlib 28import datetime as dt 29import json 30import os 31import re 32import shutil 33import socket 34import subprocess 35import sys 36import tarfile 37import tempfile 38import threading 39import time 40import uuid 41import zipfile 42from dataclasses import dataclass ,field 43from pathlib import Path 44from typing import Callable 45 46from strata_control import acquisition ,components ,engine_component as ec ,feed as feedmod ,folder_use ,longpath ,preset_marks ,signing ,transfer 47from strata_control .targets import host_platform 48from strata_control import atomic as _atomic_mod 49 50STATE_DIR = ".updates" 51STAGE_DIR = ".s" # staging is short on purpose: <components>\.s\<4 hex>\engine\<folder> (see longpath.py) 52SKEW_FREE_BYTES = 1.15 53 54 55def megabytes (n )-> int : 56"""Decimal megabytes (1 MB = 1,000,000 bytes), rounded half up, at least 1: the one figure for an engine's size in the Terminal, the app 57(apps/host/src/lib/format.ts megabytes) and the release page. Both sides are tested on the same numbers.""" 58return max (1 ,int ((n or 0 )/ 1_000_000 + 0.5 )) 59 60 61class UpdateError (RuntimeError ): 62"""An update step stopped. `exit_code` is the CLI's; the old engine is untouched unless the message says otherwise.""" 63 64def __init__ (self ,message :str ,exit_code :int = 6 ): 65super ().__init__ (message ) 66self .exit_code = exit_code 67 68 69LAUNCH_NEXT_STEP = "Stop the model first (`strata launch --stop`), then run `strata update` again. Nothing was changed." 70 71 72class Busy (UpdateError ): 73"""An engine is serving, so nothing was installed or switched.""" 74 75def __init__ (self ,serving :list [dict ]): 76if any (str (item .get ("profile" ,"" )).startswith ("launch-" )for item in serving ): 77super ().__init__ ("Strata's own launch is using the graphics card. " + LAUNCH_NEXT_STEP ,7 ) 78self .serving = serving 79return 80names = ", " .join (item .get ("profile" ,"an engine" )for item in serving )or "an engine" 81super ().__init__ (f" { names } is serving. Stop it (or wait until it is idle) and run the update again; " 82"the update never replaces or tests an engine while one is serving." ,7 ) 83self .serving = serving 84 85 86class TestStartFailed (UpdateError ): 87__test__ = False # not a pytest class 88 89#: reasons that say the graphics card or memory was busy, not that the engine is broken 90BUSY = re .compile (r"timed?[ -]?out|out of memory|\boom\b|not enough (gpu |video |free )?memory|vram|memory allocation|" 91r"cudaerrormemory|device (is )?(busy|in use)|resource busy|no free (gpu|memory)" ,re .I ) 92 93@staticmethod 94def plain (label :str ,reason :str ,busy :bool ,hint :str | None )-> str : 95"""The one text of a failed test start (X01): what did not work in plain words, that nothing was changed, and one next step. The engine's 96own words stay in ``reason`` (the state file, the JSON output and the kept log), never in this sentence.""" 97what = "Control" if label .startswith ("Control" )else "engine" 98head = (f"The new { label } did not start correctly on this computer, so it was not installed. Your current { what } is unchanged." 99if what == "Control" else 100f"The new engine { label } did not start correctly on this computer, so it was not installed. Your current engine is unchanged." ) 101low = reason .lower () 102library = missing_library (reason ) 103if what == "Control" : 104cause = f"It answered `--version` with: { reason . split ( '--version said' , 1 )[ 1 ]. strip () } " if "--version said" in low else \ 105"It did not answer `--version` in time or at all." 106elif library : 107cause = f"The engine needs the system library { library } , and this computer does not have it." 108elif "one-token probe" in low : 109cause = "The engine started but stopped before it answered a test question." 110elif "--version exited" in low or "could not run" in low : 111cause = "The engine program did not run on this computer." 112elif "no installed model" in low : 113cause = "There is no installed model to test the engine with." 114elif low .startswith ("it " ):# Strata's own plain sentences ("it was still loading the model after 10 minutes") 115cause = reason [:1 ].upper ()+ reason [1 :].rstrip ("." )+ "." 116elif busy : 117cause = "The graphics card or memory was in use." 118else : 119cause = "The engine reported a problem while it started." 120if hint is None : 121hint = ("Run `strata update --force` to try again; if it fails again, report it with the log." if not busy and what == "engine" 122else "Run `strata update` again." ) 123return f" { head } { cause } { hint } " 124 125def __init__ (self ,label :str ,reason :str ,* ,busy :bool | None = None ,hint :str | None = None ): 126# busy: True/False says outright whether the card or memory was busy (the wait-expired reasons carry the engine's log tail, which 127# mentions VRAM on every healthy start and must not be read as a busy card, #3683); None reads it from the words of the reason 128self .busy = bool (self .BUSY .search (reason ))if busy is None else busy 129if hint is None and self .busy : 130hint = ("The graphics card or memory looks busy: close programs that use the card (games, video, other models) " 131"and run `strata update` again." ) 132super ().__init__ (self .plain (label ,reason ,self .busy ,hint ),6 ) 133self .label = label 134self .reason = reason 135 136 137#: The loader's own words when a program needs a shared library the system does not have (glibc's ld.so). 138_MISSING_LIBRARY = re .compile (r"error while loading shared libraries:\s*([^\s:]+):\s*cannot open shared object file" ) 139 140#: The package that holds a system library, per Linux family (debian = Debian, Ubuntu, Mint ...; fedora = Fedora, RHEL, Rocky ...; arch = Arch, 141#: Manjaro ...). Only libraries an engine package can need from the system and that a family names differently are listed. Arch: gcc-libs pulls in 142#: libatomic / libgomp / libstdc++ / libgcc both before and after Arch split them into their own packages. 143LIBRARY_PACKAGES = { 144"libatomic.so.1" : {"debian" :"libatomic1" ,"fedora" :"libatomic" ,"arch" :"gcc-libs" }, 145"libgomp.so.1" : {"debian" :"libgomp1" ,"fedora" :"libgomp" ,"arch" :"gcc-libs" }, 146"libstdc++.so.6" : {"debian" :"libstdc++6" ,"fedora" :"libstdc++" ,"arch" :"gcc-libs" }, 147"libgcc_s.so.1" : {"debian" :"libgcc-s1" ,"fedora" :"libgcc" ,"arch" :"gcc-libs" }, 148"libnuma.so.1" : {"debian" :"libnuma1" ,"fedora" :"numactl-libs" ,"arch" :"numactl" }, 149"libz.so.1" : {"debian" :"zlib1g" ,"fedora" :"zlib" ,"arch" :"zlib" }, 150} 151_INSTALL = {"debian" :"sudo apt install {}" ,"fedora" :"sudo dnf install {}" ,"arch" :"sudo pacman -S {}" } 152 153 154def missing_library (text :str | None )-> str | None : 155"""The shared library the loader could not find (``libatomic.so.1``), from a program's output; None when it says no such thing.""" 156found = _MISSING_LIBRARY .search (text or "" ) 157return found .group (1 )if found else None 158 159 160def linux_family (os_release :str = "/etc/os-release" )-> str | None : 161"""debian, fedora or arch for this Linux (from /etc/os-release ID and ID_LIKE), or None when it is none of them or cannot be read.""" 162try : 163text = Path (os_release ).read_text (encoding = "utf-8" ,errors = "replace" ) 164except OSError : 165return None 166words = [] 167for line in text .splitlines (): 168key ,_ ,value = line .partition ("=" ) 169if key .strip ()in ("ID" ,"ID_LIKE" ): 170words += value .strip ().strip ("\"'" ).lower ().split () 171for family ,names in (("debian" , ("debian" ,"ubuntu" )), ("fedora" , ("fedora" ,"rhel" ,"centos" )), ("arch" , ("arch" ,"archlinux" ))): 172if any (w in names for w in words ): 173return family 174return None 175 176 177def library_hint (library :str ,family :str | None = None )-> str : 178"""The one next step for a missing system library: the command that installs its package on this Linux, or the package names when the 179family is not known, then run the update again.""" 180packages = LIBRARY_PACKAGES .get (library ) 181if packages and family in packages : 182return f"Install it with ` { _INSTALL [ family ]. format ( packages [ family ]) } `, then run `strata update` again." 183if packages : 184return (f"Install it with your system's package manager ( { packages [ 'debian' ] } on Debian and Ubuntu, { packages [ 'fedora' ] } on Fedora, " 185f" { packages [ 'arch' ] } on Arch), then run `strata update` again." ) 186return "Install the package that has it with your system's package manager, then run `strata update` again." 187 188 189# ---------------------------------------------------------------------------------------------- state 190 191def updates_dir (root :Path )-> Path : 192return root / STATE_DIR 193 194 195@ contextlib . contextmanager 196def update_lock (root :Path ): 197"""One updater at a time per component folder.""" 198directory = updates_dir (root ) 199directory .mkdir (parents = True ,exist_ok = True ) 200handle = open (directory / "update.lock" ,"a+b" ) 201try : 202if os .name == "nt" : 203import msvcrt 204handle .seek (0 ) 205try : 206msvcrt .locking (handle .fileno (),msvcrt .LK_NBLCK ,1 ) 207except OSError : 208raise UpdateError ("another update is already running for this component folder" ,7 )from None 209else : 210import fcntl 211try : 212fcntl .flock (handle .fileno (),fcntl .LOCK_EX | fcntl .LOCK_NB ) 213except OSError : 214raise UpdateError ("another update is already running for this component folder" ,7 )from None 215yield 216finally : 217try : 218if os .name == "nt" : 219import msvcrt 220handle .seek (0 ) 221msvcrt .locking (handle .fileno (),msvcrt .LK_UNLCK ,1 ) 222except OSError : 223pass 224handle .close () 225 226 227class State : 228"""``<components>/.updates/state.json``: the last accepted feed sequence, which engine is the previous one, a pin set by a 229manual rollback, versions not to offer again. Plain JSON, replaced atomically; a damaged file reads as empty.""" 230 231def __init__ (self ,root :Path ): 232self .path = updates_dir (root )/ "state.json" 233self .data = self ._read () 234 235def _read (self )-> dict : 236try : 237data = json .loads (self .path .read_text (encoding = "utf-8-sig" )) 238if isinstance (data ,dict ): 239return data 240except (OSError ,ValueError ): 241pass 242return {} 243 244def section (self ,name :str )-> dict : 245value = self .data .get (name ) 246if not isinstance (value ,dict ): 247value = self .data [name ]= {} 248return value 249 250def history (self ,entry :dict )-> None : 251log = self .data .setdefault ("history" , []) 252log .append (entry ) 253del log [:- 30 ] 254 255def save (self )-> None : 256self .path .parent .mkdir (parents = True ,exist_ok = True ) 257self .data ["schema_version" ]= 1 258descriptor ,temp = tempfile .mkstemp (prefix = ".state-" ,suffix = ".tmp" ,dir = self .path .parent ) 259try : 260with os .fdopen (descriptor ,"w" ,encoding = "utf-8" )as stream : 261json .dump (self .data ,stream ,indent = 1 ,sort_keys = True ) 262stream .write ("\n" ) 263_atomic_mod .replace (temp ,self .path ) 264finally : 265if os .path .exists (temp ): 266os .unlink (temp ) 267 268 269# ---------------------------------------------------------------------------------------------- hardware 270 271def _gfx_names ()-> list [str ]: 272found :list [str ]= [] 273kfd = Path ("/sys/class/kfd/kfd/topology/nodes" ) 274if kfd .is_dir (): 275for node in sorted (kfd .iterdir ()): 276try : 277text = (node / "properties" ).read_text () 278except OSError : 279continue 280match = re .search (r"^gfx_target_version\s+(\d+)" ,text ,re .MULTILINE ) 281if match and int (match .group (1 ))> 0 : 282value = int (match .group (1 )) 283found .append (f"gfx { value // 10000 } {( value // 100 ) % 100 :x } { value % 100 :x } " ) 284if not found : 285tool = shutil .which ("rocminfo" )if os .name != "nt" else shutil .which ("hipInfo" ) 286if tool : 287try : 288done = subprocess .run ([tool ],capture_output = True ,text = True ,errors = "replace" ,timeout = 10 , 289creationflags = getattr (subprocess ,"CREATE_NO_WINDOW" ,0 )) 290found = sorted (set (re .findall (r"\bgfx[0-9a-f]{3,4}\b" ,done .stdout ))) 291except (OSError ,subprocess .SubprocessError ): 292pass 293if not found and os .name != "nt" : 294try : 295found = ec .hip_archs_from_pci ()# no kfd topology and no rocminfo: the PCI ids of the AMD cards say (an AppImage, a container) 296except Exception :# noqa: BLE001 - detection is best effort 297found = [] 298if not found and os .name == "nt" : 299# a normal Windows PC has no hipInfo (it ships with the HIP SDK): the display adapters' PCI ids / names say which gfx it is 300try : 301found = ec .hip_archs_present () 302except Exception :# noqa: BLE001 - detection is best effort 303found = [] 304return sorted (set (found )) 305 306 307def _amd_card_names ()-> list [str ]: 308if os .name != "nt" : 309return [] 310try : 311return [c ["name" ]for c in ec .windows_amd_cards ()if c .get ("name" )] 312except Exception :# noqa: BLE001 313return [] 314 315 316def detect_hardware (environ = None )-> dict : 317"""What the package choice depends on. Read-only probes of tools that are already installed (nvidia-smi, rocminfo, sysfs); 318``STRATA_ENGINE_BACKEND`` overrides the backend like it does for a start. Anything unreadable is left empty, which the 319selection treats as "cannot tell", never as a refusal.""" 320environ = os .environ if environ is None else environ 321prefer = "" 322family ,prefer = ec .split_backend (environ .get (ec .ENV_BACKEND ,"" )) 323if prefer : 324# "hip-rx9070" is how the feed labels a package; accept it as "the hip family, this variant" 325environ = {** environ ,ec .ENV_BACKEND :family } 326backend ,how = ec .detect_backend (environ ) 327hw = {"platform" :host_platform (),"backend" :backend ,"backend_source" :how ,"runtime" :ec .runtime_version (), 328"nvidia_driver" :None ,"cuda_archs" : [],"gfx" : [],"gpu_names" : [],"variant_wanted" :prefer , 329"makes" :sorted (ec .gpu_makes_present ())} 330if backend == "cuda" : 331hw ["nvidia_driver" ]= ec .nvidia_driver_version () 332hw ["cuda_archs" ]= ec .cuda_archs_present () 333elif backend == "hip" : 334hw ["gfx" ]= _gfx_names () 335hw ["gpu_names" ]= _amd_card_names () 336return hw 337 338 339# ---------------------------------------------------------------------------------------------- serving 340 341def serving_now ()-> list [dict ]: 342"""Engines that are serving: managed instances of the owner runtime and anything holding the shared activity lease 343(`strata serve`, a runtime host). Empty when nothing is. The exclusive lease is only tried, never kept.""" 344from strata_control import profiles ,runtime 345try : 346managed = runtime .active_managed_instances () 347except (profiles .ProfileError ,OSError ): 348managed = [] 349if managed : 350return managed 351try : 352descriptor = runtime .acquire_activity_lease (shared = False ) 353except profiles .ProfileError as exc : 354if "lease" in str (exc ): 355return [{"profile" :"a running Strata server" ,"state" :"serving" }] 356return [] 357except OSError : 358return [] 359try : 360os .close (descriptor ) 361except OSError : 362pass 363return [] 364 365 366def wait_until_idle (check :Callable [[],list [dict ]],* ,wait :float ,emit :Callable ,cancel = None , 367poll :float = 3.0 )-> None : 368"""Return when nothing is serving; raise `Busy` if something still is after `wait` seconds (0 = do not wait).""" 369deadline = time .monotonic ()+ wait 370serving = check () 371while serving : 372if wait <= 0 or time .monotonic ()>= deadline or (cancel is not None and cancel .is_set ()): 373raise Busy (serving ) 374emit ({"event" :"waiting" ,"message" :"An engine is serving; waiting for it to stop before updating." , 375"serving" :serving }) 376time .sleep (poll ) 377serving = check () 378 379 380def idle_gate (ctx :"Context" )-> None : 381"""Called after a download, right before the first thing is staged, test-started or switched: with a gate attached, the models the person agreed to 382stop are stopped here (and a model nobody agreed to stop is refused); then, as always, nothing may still be serving.""" 383gate = getattr (ctx ,"gate" ,None ) 384if gate is not None : 385gate .release (ctx .serving ) 386wait_until_idle (ctx .serving ,wait = ctx .wait ,emit = ctx .emit ,cancel = ctx .cancel ,poll = ctx .poll ) 387 388 389# ---------------------------------------------------------------------------------------------- context 390 391@dataclass 392class Context : 393components :Path 394source :str 395trusted :dict 396hardware :dict 397emit :Callable [[dict ],None ]= lambda event :None 398cancel :threading .Event | None = None 399test_start :Callable | None = None # (stage_root, component, ctx) -> dict; defaults to `default_test_start` 400serving :Callable [[],list [dict ]]= serving_now 401wait :float = 0.0 # seconds to wait for a serving engine to stop 402force :bool = False 403channel :str = "stable" 404app_version :str | None = None 405now :dt .datetime | None = None 406run_config :str | None = None # a run config for the test start (default: an installed model's) 407test_timeout :float = 600.0 408poll :float = 3.0 409environ :dict = field (default_factory = lambda :dict (os .environ )) 410allow_no_model_smoke :bool = True 411state_base :Path | None = None # where tuning/recheck.json goes (default: the per-user state folder) 412feed_timeout :float = 30.0 # seconds a read of the feed may wait (the quiet daily check uses 5) 413automatic :bool = False # a read of the feed nobody asked for by name (netpolicy rule 4b: the refusal note) 414gate :object | None = None # strata_control.engine_update.ModelGate: what to do when a model is loaded (None: refuse before anything is downloaded) 415 416def say (self ,phase :str ,message :str ,** extra )-> None : 417self .emit ({"event" :"phase" ,"phase" :phase ,"message" :message ,** extra }) 418 419 420def require_acquisition (what :str )-> None : 421"""The update path acquires by definition; a process that has forbidden acquiring (a start, a serve) may not run it.""" 422acquisition .require (what ,"`strata update` from a terminal" ) 423 424 425def downgrade_words (sequence ,accepted ,state_file :Path )-> str : 426"""A feed older than the one already accepted (A01b/A05), in plain words: both numbers, the folder that remembers the newer one, and one next step. 427The sentence keeps "older than the one already accepted" so a log search for the old text still finds it.""" 428return (f"this update source is older than the one already accepted on this computer (its sequence is { sequence } , the accepted one is " 429f" { accepted } ; refusing a replayed feed). The newer one is remembered in { state_file . parent } . Use the newest release folder; " 430f"if you really want this older one, delete { state_file } and run this again." ) 431 432 433def open_feed (ctx :Context ,state :State )-> feedmod .Feed : 434require_acquisition ("the update feed" ) 435last = (state .data .get ("feed" )or {}).get ("sequence" ) 436ctx .say ("feed" ,"Reading the signed update feed" ) 437try : 438loaded = feedmod .fetch (ctx .source ,ctx .trusted ,timeout = ctx .feed_timeout ,last_sequence = last ,channel = ctx .channel ,now = ctx .now , 439automatic = ctx .automatic ) 440except feedmod .FeedDowngrade as exc : 441raise feedmod .FeedDowngrade (downgrade_words (exc .sequence ,exc .accepted ,state .path ))from None 442for line in loaded .skipped :# an entry from a newer release that this Control cannot use: said once, never an error 443ctx .say ("feed" ,line ) 444try :# the feed's model list, kept (signature and all) for a PC that is offline later; nothing when the feed has none 445from strata_control import feed_models 446feed_models .remember (loaded ,state .path .parent .parent ) 447except Exception :# noqa: BLE001 - never part of an update 448pass 449info = state .section ("feed" ) 450info .update ({"sequence" :loaded .sequence ,"key_id" :loaded .key_id ,"source" :ctx .source ,"channel" :loaded .channel , 451"checked_at" : (ctx .now or dt .datetime .now (dt .timezone .utc )).isoformat ()}) 452return loaded 453 454 455# ---------------------------------------------------------------------------------------------- archives 456 457def _archive_size (archive :Path ,fmt :str )-> int : 458if fmt == "zip" : 459with zipfile .ZipFile (archive )as zf : 460return sum (info .file_size for info in zf .infolist ()) 461mode = {"tar.gz" :"r:gz" ,"tar.xz" :"r:xz" }[fmt ] 462with tarfile .open (archive ,mode )as tar : 463return sum (m .size for m in tar .getmembers ()if m .isfile ()) 464 465 466def _extract_with_links (archive :Path ,destination :Path ,fmt :str )-> None : 467"""Like `components.safe_extract`, but a relative symbolic link that stays inside `destination` is allowed. A Control bundle's 468Python needs them (libpython, terminfo). Every name is checked before anything is written; hard links, devices, absolute 469links and links that leave the folder are refused.""" 470mode = {"tar.gz" :"r:gz" ,"tar.xz" :"r:xz" }.get (fmt ) 471if mode is None : 472raise components .ComponentError (f"links are only unpacked from tar archives, not { fmt } " ) 473root = destination .resolve () 474with tarfile .open (archive ,mode )as tar : 475members = tar .getmembers () 476for m in members : 477components ._check_member_within (destination ,m .name ) 478if m .isdir ()or m .isfile (): 479continue 480if not m .issym (): 481raise components .UnsafeArchive (f"the archive contains a member that is not a file or a symbolic link ( { m . name !r } )" ) 482link = m .linkname .replace ("\\" ,"/" ) 483if not link or link .startswith ("/" )or re .match (r"^[A-Za-z]:" ,link ): 484raise components .UnsafeArchive (f"the archive has an absolute symbolic link ( { m . name !r } )" ) 485resolved = (destination / m .name ).parent .joinpath (link ).resolve () 486if resolved != root and root not in resolved .parents : 487raise components .UnsafeArchive (f"the symbolic link { m . name !r } leaves the package" ) 488destination .mkdir (parents = True ,exist_ok = True ) 489links = [] 490for m in members : 491target = components ._check_member_within (destination ,m .name ) 492if m .isdir (): 493target .mkdir (parents = True ,exist_ok = True ) 494elif m .isfile (): 495target .parent .mkdir (parents = True ,exist_ok = True ) 496source = tar .extractfile (m ) 497with target .open ("wb" )as out : 498shutil .copyfileobj (source ,out ) 499if m .mode & 0o111 : 500target .chmod (0o755 ) 501else : 502links .append ((target ,m .linkname )) 503for target ,linkname in links : 504target .parent .mkdir (parents = True ,exist_ok = True ) 505os .symlink (linkname ,target ) 506 507 508def extract (archive :Path ,destination :Path ,fmt :str ,installed_bytes :int ,* ,allow_links :bool = False )-> None : 509"""Unpack into a fresh folder. The archive's own total size must not exceed what the signed feed declared, so a package 510cannot grow into a disk-filling bomb; names and links are checked by `components.safe_extract` before anything is written 511(an engine package may not contain links; a Control bundle may contain relative links that stay inside it).""" 512try : 513total = _archive_size (archive ,fmt ) 514except (tarfile .TarError ,zipfile .BadZipFile ,OSError ,EOFError )as exc : 515raise UpdateError (f"the downloaded archive cannot be read ( { type ( exc ). __name__ } )" ,5 )from None 516if total > installed_bytes : 517raise UpdateError (f"the archive holds { total } bytes, the signed feed says the package is { installed_bytes } ; not unpacked" ,5 ) 518destination = longpath .long_path (destination )# extended-length form: a long user name must not stop the unpacking 519if destination .exists (): 520shutil .rmtree (destination ,ignore_errors = True ) 521try : 522if allow_links : 523_extract_with_links (archive ,destination ,fmt ) 524else : 525components .safe_extract (archive ,destination ,fmt = fmt ) 526except components .ComponentError as exc : 527shutil .rmtree (destination ,ignore_errors = True ) 528raise UpdateError (f"the archive was refused: { exc } " ,5 )from None 529except OSError as exc : 530shutil .rmtree (destination ,ignore_errors = True ) 531raise UpdateError (f"the package could not be unpacked: { longpath . describe_oserror ( exc ) } " ,6 )from None 532 533 534def _free_space_check (root :Path ,need :int ,ctx :"Context | None" = None ,sha256 :str = "" ,component :str = "" )-> None : 535"""Stop only when the drive cannot hold the bytes that are still to be written (the package not yet downloaded plus its unpacked 536size). The 1.15 margin is a guess at working room, not a need: below it the update warns and goes on. A resumed download's 537partial file is already on the drive, so it is not counted a second time.""" 538root .mkdir (parents = True ,exist_ok = True ) 539free = shutil .disk_usage (root ).free 540have = 0 541if ctx is not None and sha256 : 542try : 543have = (updates_dir (ctx .components )/ "partial" / f" { sha256 [: 16 ] } .part" ).stat ().st_size 544except OSError : 545have = 0 546real = max (need - have ,0 ) 547drive = root .anchor or str (root ) 548if free < real : 549raise UpdateError (f"not enough free space on { drive } : { free // ( 1 << 20 ) } MiB free, { real // ( 1 << 20 ) } MiB needed. " 550f"Free up some space on { drive } and run the update again" ,6 ) 551if free < real * SKEW_FREE_BYTES and ctx is not None : 552ctx .say ("warn" ,f"Little free space on { drive } : { free // ( 1 << 20 ) } MiB free for about { real // ( 1 << 20 ) } MiB. " 553"The update goes on and should fit; free up space if it stops." ,component = component or "update" ) 554 555 556def _download (ctx :Context ,state_name :str ,url_ref :str ,size :int ,sha256 :str ,label :str ,feed :feedmod .Feed )-> Path : 557work = updates_dir (ctx .components )/ "partial" 558partial = work / f" { sha256 [: 16 ] } .part" 559start = time .monotonic () 560last = {"at" :0.0 ,"pct" :- 1 } 561 562def progress (done :int ,total :int )-> None : 563now = time .monotonic () 564pct = int (done * 100 / total )if total else 0 565if now - last ["at" ]>= 0.25 or pct != last ["pct" ]and pct in (0 ,100 ): 566last ["at" ],last ["pct" ]= now ,pct 567rate = done / max (now - start ,1e-6 ) 568ctx .emit ({"event" :"progress" ,"phase" :"download" ,"component" :state_name ,"label" :label , 569"done" :done ,"total" :total ,"percent" :pct ,"bytes_per_second" :int (rate )}) 570 571ctx .say ("download" ,f"Downloading { label } ( { megabytes ( size ) } MB)" ,component = state_name ) 572try : 573what = label if label .lower ().startswith ("the " )else "the " + label # "the engine 0.1.59 (cuda)", in the network rule's sentences 574return transfer .download (feed .url (url_ref ),partial ,size = size ,sha256 = sha256 ,progress = progress ,cancel = ctx .cancel ,what = what , 575say = lambda line :ctx .say ("download" ,line ,component = state_name )) 576except transfer .Cancelled : 577raise UpdateError ("the update was stopped; the partial download is kept and the next update resumes it" ,130 )from None 578except transfer .ChecksumMismatch as exc : 579raise UpdateError (str (exc ),5 )from None 580except transfer .TransferError as exc : 581raise UpdateError (str (exc ),6 )from None 582 583 584# ---------------------------------------------------------------------------------------------- engine 585 586def folder_name (pkg :feedmod .EnginePackage )-> str : 587return f" { pkg . version } - { pkg . platform } - { pkg . backend } " + (f"- { pkg . variant } " if pkg .variant else "" ) 588 589 590def _manifest_sha (folder :Path )-> str : 591return transfer .sha256_file (folder / ec .MANIFEST ) 592 593 594def installed_engine (root :Path ,hardware :dict )-> tuple [ec .EngineComponent | None ,str | None ]: 595"""(the engine a start would use, why not). A package that fails its integrity check is reported, not hidden.""" 596try : 597return ec .resolve (root ,backend = hardware .get ("backend" ),full = True ,runtime = hardware .get ("runtime" )),None 598except ec .EngineMissing as exc : 599return None ,str (exc ) 600 601 602def _engine_view (component :ec .EngineComponent | None )-> dict | None : 603if component is None : 604return None 605return {"version" :component .version ,"platform" :component .platform ,"backend" :component .backend , 606"variant" :component .variant ,"build_id" :component .build_id ,"folder" :component .root .name , 607"signed" :bool (component .signature )} 608 609 610def decide_engine (feed :feedmod .Feed ,ctx :Context ,state :State )-> dict : 611"""What an update would do for the engine, without downloading anything.""" 612return _choose_engine (feed ,ctx ,state )[0 ] 613 614 615GPU_MAKES = ("cuda" ,"hip" ,"sycl" ) 616 617 618def installed_gpu_makes (root :Path ,platform :str | None )-> set [str ]: 619"""The GPU makes (cuda / hip / sycl) of the engines installed for this platform, whatever their state.""" 620try : 621found ,_ = ec .scan (root ) 622except OSError : 623return set () 624return {item .backend for item in found if item .platform == platform and item .backend in GPU_MAKES } 625 626 627def make_guard (ctx :Context )-> str | None : 628"""Never cross GPU makes (#3688). An update replaces the engine; it does not convert the PC from one make of card to another, 629and a package for the wrong make can only fail its test start. When the engine already installed is for a different make 630than the one detected: 631- if this PC really has a card of the installed make too (the display adapters / PCI vendors say so), the update stays 632on the installed make (a PC with an NVIDIA card and an AMD card keeps the engine it was set up with); 633- otherwise nothing is chosen and the returned sentence says why. 634An explicit ask (``--backend``, ``STRATA_ENGINE_BACKEND``) is the person's decision and passes. Returns None when the update 635may go on.""" 636hw = ctx .hardware 637want = hw .get ("backend" ) 638if want not in GPU_MAKES or hw .get ("backend_source" )in ("environment" ,"requested" ,"installed engine" ,"saved choice" ): 639return None 640have = installed_gpu_makes (ctx .components ,hw .get ("platform" )) 641if not have or want in have : 642return None 643here = set (hw .get ("makes" )or []) 644keep = [make for make in GPU_MAKES if make in have and make in here ] 645if keep : 646ctx .hardware = {** detect_hardware ({** ctx .environ ,ec .ENV_BACKEND :keep [0 ]}),"backend_source" :"installed engine" } 647return None 648mine = " and " .join (ec .MAKE_NAMES [m ]for m in GPU_MAKES if m in have ) 649return (f"The engine installed here is for { mine } cards, but this update would give your PC { ec . MAKE_NAMES [ want ] } one. " 650f"Nothing was changed. If you really changed your graphics card, download the { ec . MAKE_NAMES [ want ] } version " 651f"from { ec . RELEASES_URL } ." ) 652 653 654def _choose_engine (feed :feedmod .Feed ,ctx :Context ,state :State )-> tuple [dict ,feedmod .EnginePackage | None ]: 655refusal = make_guard (ctx ) 656if refusal : 657installed ,_ = installed_engine (ctx .components , {** ctx .hardware ,"backend" :next (iter (sorted (installed_gpu_makes (ctx .components ,ctx .hardware .get ("platform" )))),None )}) 658return {"installed" :_engine_view (installed ),"offered" :None ,"reasons" : [refusal ],"status" :"wrong-make" ,"note" :refusal , 659"download_bytes" :0 ,"previous" :state .section ("engine" ).get ("previous" ),"pinned" :state .section ("engine" ).get ("pinned" ), 660"problem" :None },None 661installed ,missing_reason = installed_engine (ctx .components ,ctx .hardware ) 662sticky = {** ctx .hardware ,"installed_variant" :installed .variant if installed is not None and installed .backend in ("hip" ,"cuda" )else "" } 663offered ,reasons = feedmod .select_engine ([p for p in feed .engine ],sticky ) 664section = state .section ("engine" ) 665report = {"installed" :_engine_view (installed ),"offered" :offered .to_dict ()if offered else None , 666"reasons" :reasons ,"status" :"none-for-this-pc" ,"download_bytes" :0 , 667"previous" :section .get ("previous" ),"pinned" :section .get ("pinned" ), 668"problem" :missing_reason if installed is None and missing_reason and "holds no engine" not in missing_reason else None } 669if offered is None : 670if not feed .engine : 671report ["status" ]= "not-in-feed" 672else : 673hip = [p for p in feed .engine if p .backend == "hip" and p .platform == ctx .hardware .get ("platform" )] 674if hip and ctx .hardware .get ("backend" )== "hip" and ctx .hardware .get ("gfx" )and not any ( 675feedmod .engine_fit_reasons (p ,ctx .hardware )== []for p in hip ): 676# a build for another AMD card family: one plain line instead of the list of reasons 677report ["note" ]= ec .arch_notice (tuple (sorted ({a for p in hip for a in p .archs if a .startswith ("gfx" )})),ctx .hardware ["gfx" ]) 678return report ,None 679report ["download_bytes" ]= offered .size 680if installed is None : 681report ["status" ]= "install" 682return report ,offered 683have ,want = feedmod .version_key (installed .version ),feedmod .version_key (offered .version ) 684if want < have : 685report ["status" ]= "current" 686report ["note" ]= f"the feed offers { offered . version } , older than the installed { installed . version } ; an update never downgrades" 687elif want == have : 688report ["status" ]= "current" 689else : 690report ["status" ]= "available" 691# The offered engine is already installed (the person switched to an older one for a test): the update only makes it the engine in use again, 692# with nothing to download. A version the person switched away from is never hidden from the update (owner, 11-01). 693local = installed_copy (ctx .components ,offered ) 694if report ["status" ]== "available" and local : 695report ["installed_locally" ]= local 696report ["download_bytes" ]= 0 697return report ,offered 698bad = (section .get ("failed" )or {}).get (offered .version ) 699if bad and _failed_mark_is_old (bad ,ctx ): 700bad = None # a failure is held against a version for a day, not for ever 701if report ["status" ]== "available" and not ctx .force : 702if bad and bad .get ("manifest_sha256" )== offered .manifest_sha256 : 703report ["status" ]= "failed-before" 704report ["note" ]= (f" { offered . version } failed its test start on { bad . get ( 'at' , 'an earlier try' ) } ( { bad . get ( 'reason' ) } ); " 705"run `strata update --force` to try it again" ) 706return report ,offered 707 708 709def installed_copy (root :Path ,pkg :feedmod .EnginePackage )-> str | None : 710"""The installed package folder that is byte for byte the feed's ``pkg`` (same name, same manifest hash), or None.""" 711folder = ec .engine_dir (root )/ folder_name (pkg ) 712try : 713if (folder / ec .MANIFEST ).is_file ()and _manifest_sha (folder )== pkg .manifest_sha256 : 714return folder .name 715except OSError : 716pass 717return None 718 719 720def _serving_or_empty (ctx :Context )-> list [dict ]: 721try : 722return ctx .serving () 723except Exception :# noqa: BLE001 - informational only 724return [] 725 726 727def check (ctx :Context )-> dict : 728"""Read the signed feed and say what an update would do for the engine, Control and the app. Downloads nothing but the feed.""" 729with update_lock (ctx .components ): 730state = State (ctx .components ) 731feed = open_feed (ctx ,state ) 732report = {"feed" : {"source" :ctx .source ,"sequence" :feed .sequence ,"channel" :feed .channel ,"key_id" :feed .key_id , 733"generated_at" :feed .generated_at ,"trusted_by" :"test key file" if signing .extra_keys_in_effect (ctx .environ )else "built-in keys" }, 734"engine" :decide_engine (feed ,ctx ,state ),"control" :decide_control (feed ,ctx ,state ), 735"app" :decide_app (feed ,ctx ),"serving" :_serving_or_empty (ctx ),"hardware" :ctx .hardware } 736state .data ["last_check" ]= _last_check (ctx ,report ) 737state .save () 738return report 739 740 741def _last_check (ctx :Context ,report :dict ,control_version :str | None = None )-> dict : 742"""What the feed offers that is newer than what is installed, kept for the notice a start or the app shows without touching the network 743(engine_component.cached_offers). ``control_version``: the Control an update has just installed (the notice belongs to it, not to the one running).""" 744return { 745"at" : (ctx .now or dt .datetime .now (dt .timezone .utc )).isoformat (), 746"engine" :report ["engine" ]["offered" ]["version" ]if report ["engine" ]["status" ]in ("available" ,"install" )and report ["engine" ]["offered" ]else None , 747"app" :report ["app" ]["offered" ]if report ["app" ]["status" ]== "available" else None , 748# the versions this result is for, so a later Control, engine or app change drops the cached notice 749"control" :control_version or ec .runtime_version (),"engine_installed" :ec .newest_installed_version (ctx .components )} 750 751 752def new_stage (root :Path ,prefix :str = "" )-> Path : 753r"""A fresh, short staging folder: ``<components>\.s\<4 hex>``. Old leftovers (a crashed update; the update lock is held, so 754nothing else uses them) are swept first, along with the longer folder older versions used.""" 755base = root / STAGE_DIR 756for old in [base ,updates_dir (root )/ "staging" ]: 757if old .exists (): 758shutil .rmtree (longpath .long_path (old ),ignore_errors = True ) 759while True : 760stage = base / (prefix + uuid .uuid4 ().hex [:4 ]) 761if not stage .exists (): 762return stage 763 764 765def stage_engine (ctx :Context ,feed :feedmod .Feed ,pkg :feedmod .EnginePackage ,archive :Path ,* ,component_id :str = ec .COMPONENT_ID )-> tuple [Path ,ec .EngineComponent ]: 766"""Unpack and check a downloaded engine package in a staging component folder. Returns (staging root, component). `component_id`: the engine of a model shape 767(strata_control/shape_engine.py) is read and checked as its own component, never as the Strata engine.""" 768stage_root = new_stage (ctx .components ) 769folder = stage_root / "engine" / folder_name (pkg ) 770ctx .say ("verify" ,f"Unpacking { pkg . label } " ,component = "engine" ) 771longpath .long_path (folder .parent ).mkdir (parents = True ,exist_ok = True ) 772try : 773extract (archive ,folder ,pkg .format ,pkg .installed_bytes ) 774manifest = folder / ec .MANIFEST 775if not manifest .is_file (): 776raise UpdateError (f"the package has no { ec . MANIFEST } " ,5 ) 777if transfer .sha256_file (manifest )!= pkg .manifest_sha256 : 778raise UpdateError ("the package's manifest is not the one the signed feed names; not installed" ,5 ) 779try : 780component = ec .read_manifest (folder ,component_id ) 781except ec .ComponentProblem as exc : 782raise UpdateError (f"the package manifest is invalid: { exc } " ,5 )from None 783mismatches = [name for name ,a ,b in ( 784 ("version" ,component .version ,pkg .version ), ("platform" ,component .platform ,pkg .platform ), ("shape" ,component .shape ,pkg .shape ), 785 ("backend" ,component .backend ,pkg .backend ), ("variant" ,component .variant ,pkg .variant ), 786 ("build_id" ,component .build_id ,pkg .build_id ), ("archs" ,set (component .archs ),set (pkg .archs )), 787 ("min_driver" ,component .min_driver ,pkg .min_driver ), ("min_runtime" ,component .min_runtime ,pkg .min_runtime )) 788if a != b ] 789if mismatches : 790raise UpdateError (f"the package says something different from the signed feed ( { ', ' . join ( mismatches ) } ); not installed" ,5 ) 791ctx .say ("verify" ,"Checking the package signature and every file" ,component = "engine" ) 792outer = ec ._verifier 793signing .install_component_verifier (ctx .trusted ) 794try : 795ec .verify_signature (component , {** ctx .environ ,ec .ENV_REQUIRE_SIGNED :"1" }) 796ec .verify (component ,full = True ) 797except ec .ComponentProblem as exc : 798raise UpdateError (f"the package failed its check: { exc } " ,5 )from None 799finally : 800ec .register_signature_verifier (outer ) 801why = feedmod .engine_fit_reasons (pkg ,ctx .hardware ) 802if why : 803raise UpdateError ("; " .join (why ),5 ) 804_warn_if_deep (ctx ,ctx .components / "engine" / folder_name (pkg ),max ((len (rel )for rel ,_ ,_ in component .files ),default = 0 )+ 1 ) 805return stage_root ,component 806except BaseException : 807shutil .rmtree (longpath .long_path (stage_root ),ignore_errors = True ) 808raise 809 810 811def discover_run_config (environ = None )-> Path | None : 812"""A saved model's run config for the test start: the one a saved profile uses if its files are all present, otherwise any 813installed model whose files are present. DeepSeek models are left out (strata_control/retired.py: this Strata does not run them). 814None when no model can be used (the first run).""" 815from strata_control import models ,profiles ,retired 816try : 817listed = models .list_installed () 818except Exception :# noqa: BLE001 - discovery is best effort 819return None 820ready = [m for m in listed .get ("models" , [])if m .get ("component_status" )== "present" and m .get ("source_config" ) 821and not retired .config_file_reason (m ["source_config" ])] 822if not ready : 823return None 824try : 825used = {profile .get ("source_config" )for profile in profiles .list_profiles ()if profile .get ("source_config" )} 826except Exception :# noqa: BLE001 827used = set () 828ready .sort (key = lambda m : (m ["source_config" ]not in used ,m ["id" ])) 829return Path (ready [0 ]["source_config" ]) 830 831 832def _free_port ()-> int : 833with socket .socket ()as probe : 834probe .bind (("127.0.0.1" ,0 )) 835return probe .getsockname ()[1 ] 836 837 838@ contextlib . contextmanager 839def _patched_environ (values :dict ): 840old = {key :os .environ .get (key )for key in values } 841os .environ .update (values ) 842try : 843yield 844finally : 845for key ,value in old .items (): 846if value is None : 847os .environ .pop (key ,None ) 848else : 849os .environ [key ]= value 850 851 852def _keep_text (ctx :"Context | None" ,component :ec .EngineComponent ,text :str )-> Path | None : 853"""What the engine printed at its test start, kept as ``.updates/logs/test-start-<version>.log`` (the file `_keep_log` writes for a full test 854start), so a failed update can still be read after the downloaded package is gone. None when there is no context or it cannot be written.""" 855if ctx is None : 856return None 857try : 858target = updates_dir (ctx .components )/ "logs" 859target .mkdir (parents = True ,exist_ok = True ) 860path = target / f"test-start- { component . version } .log" 861path .write_bytes (text .encode ("utf-8" ,errors = "replace" )[- 65536 :]) 862logs = sorted (target .glob ("test-start-*.log" ),key = lambda p :p .stat ().st_mtime ) 863for old in logs [:- 5 ]: 864old .unlink (missing_ok = True ) 865return path 866except OSError : 867return None 868 869 870def binary_smoke (component :ec .EngineComponent ,timeout :float = 60 ,ctx :"Context | None" = None )-> dict : 871"""No model installed yet: the engine must at least load (its libraries resolve, the GPU runtime initialises the loader) and 872report its version. Weaker than a one-token answer, and reported as such. With ``ctx`` a failure keeps the engine's output in 873``.updates/logs`` and says where; a missing system library is named, with the package that has it.""" 874var = "PATH" if os .name == "nt" else ("DYLD_LIBRARY_PATH" if sys .platform == "darwin" else "LD_LIBRARY_PATH" ) 875env = dict (os .environ ) 876env [var ]= os .pathsep .join (ec .package_lib_dirs (component .root ))+ os .pathsep + env .get (var ,"" ) 877command = [str (component .exe ),"--version" ] 878try : 879done = subprocess .run (command ,capture_output = True ,text = True ,errors = "replace" ,timeout = timeout ,env = env , 880cwd = str (component .root ),creationflags = getattr (subprocess ,"CREATE_NO_WINDOW" ,0 )) 881except (OSError ,subprocess .SubprocessError )as exc : 882_keep_text (ctx ,component ,f"$ { ' ' . join ( command ) } \n { type ( exc ). __name__ } : { exc } \n" ) 883raise TestStartFailed (component .version ,f"the engine could not run ( { type ( exc ). __name__ } : { exc } )" )from None 884if done .returncode != 0 : 885text = (done .stderr or "" )+ "\n" + (done .stdout or "" ) 886options = re .findall (r"^\s+--[a-z0-9][a-z0-9-]*" ,text ,re .MULTILINE ) 887if done .returncode == 2 and len (options )>= 5 : 888# an engine built before it answered --version prints its usage (the list of its own options) and exits 2: it loaded, its libraries 889# resolved, the GPU runtime started and its argument parser ran. That is what this test is for; say so, do not fail it. 890return {"mode" :"binary-only" ,"detail" :"no model is installed yet; this engine does not answer --version, but it loaded and listed its options " 891f"( { len ( options ) } of them), so it runs" ,"output" :"" } 892kept = _keep_text (ctx ,component ,f"$ { ' ' . join ( command ) } \nexit code { done . returncode } \n--- stderr\n { done . stderr or '' } \n--- stdout\n { done . stdout or '' } \n" ) 893library = missing_library (text ) 894tail = (done .stderr or done .stdout ).strip ().splitlines ()[- 1 :]or ["no output" ] 895reason = f"--version exited { done . returncode } : { tail [ 0 ][: 200 ] } " 896if library and library not in reason : 897reason += f" (error while loading shared libraries: { library } : cannot open shared object file)" 898where = f" The engine's log from this test is in { kept } ." if kept else "" 899if library : 900raise TestStartFailed (component .version ,reason ,busy = False ,hint = library_hint (library ,linux_family ())+ where ) 901hint = f"Run `strata update --force` to try again; if it fails again, report it with the log: { kept } " if kept else None 902raise TestStartFailed (component .version ,reason ,hint = hint ) 903return {"mode" :"binary-only" ,"detail" :"no model is installed yet, so the engine was run with --version only" , 904"output" :done .stdout .strip ()[:200 ]} 905 906 907def _log_tail (sandbox :Path ,component :ec .EngineComponent )-> str : 908log = sandbox / "engine.log" 909try : 910lines = log .read_text (errors = "replace" ).splitlines ()[- 3 :] 911except OSError : 912return "" 913return " | " + " " .join (lines )[:300 ]if lines else "" 914 915 916def _keep_log (sandbox :Path ,component :ec .EngineComponent ,ctx :Context )-> None : 917"""The engine's log from the test start (the last 64 KiB), kept in ``.updates/logs`` so a failed update can be read afterwards.""" 918log = sandbox / "engine.log" 919try : 920data = log .read_bytes ()[- 65536 :] 921target = updates_dir (ctx .components )/ "logs" 922target .mkdir (parents = True ,exist_ok = True ) 923 (target / f"test-start- { component . version } .log" ).write_bytes (data ) 924logs = sorted (target .glob ("test-start-*.log" ),key = lambda p :p .stat ().st_mtime ) 925for old in logs [:- 5 ]: 926old .unlink (missing_ok = True ) 927except OSError : 928pass 929 930 931_RECORD_LIMIT = 65536 # bytes read from any one kept file 932_RECORDS_KEPT = 3 # failed test starts whose records stay in .updates/logs 933 934 935def _scrub (value ,key :str = "" ): 936"""A kept JSON record without anything that could authorise a request: keys that name a token or a key keep only their first 937characters (enough to see that two records agree), the API key is dropped.""" 938if isinstance (value ,dict ): 939return {k :_scrub (v ,str (k ))for k ,v in value .items ()} 940if isinstance (value ,list ): 941return [_scrub (v ,key )for v in value ] 942low = key .lower () 943if isinstance (value ,str )and value and ("api_key" in low or low in ("key" ,"authorization" )): 944return "<removed>" 945if isinstance (value ,str )and ("token" in low or "secret" in low or low .endswith ("_key" )): 946return value [:8 ]+ "...(rest removed)" 947return value 948 949 950def _keep_records (sandbox :Path ,component :ec .EngineComponent ,ctx :Context )-> None : 951"""A failed test start keeps what the sandbox knew, because the sandbox is deleted right after (#3654): the run config the test used 952(without keys), the host, child and ready records of the runtime (their PIDs show a mismatch), and the host and server logs, next to the 953engine log in ``.updates/logs/test-start-<version>-failed``. The last few failed starts are kept. Best effort: it never hides the failure.""" 954try : 955target = updates_dir (ctx .components )/ "logs" / f"test-start- { component . version } -failed" 956shutil .rmtree (target ,ignore_errors = True ) 957target .mkdir (parents = True ) 958wanted = [sandbox / "run.json" ,sandbox / "engine.log" ] 959wanted += sorted ((sandbox / "runtime" ).glob ("*.json" ))+ sorted ((sandbox / "runtime" ).glob ("*.log" )) 960for source in wanted : 961try : 962if not source .is_file (): 963continue 964data = source .read_bytes ()[- _RECORD_LIMIT :] 965if source .suffix == ".json" : 966try : 967data = (json .dumps (_scrub (json .loads (data .decode ("utf-8-sig" ))),indent = 1 )+ "\n" ).encode ("utf-8" ) 968except ValueError : 969pass # not JSON after all: kept as it is 970 (target / source .name ).write_bytes (data ) 971except OSError : 972continue 973folders = sorted ((d for d in target .parent .glob ("test-start-*-failed" )if d .is_dir ()),key = lambda d :d .stat ().st_mtime ) 974for old in folders [:- _RECORDS_KEPT ]: 975shutil .rmtree (old ,ignore_errors = True ) 976except OSError : 977pass 978 979 980def _warn_if_deep (ctx :Context ,folder :Path ,longest_inside :int )-> None : 981"""Tell the person, in plain words, when the engine will sit too deep for Windows' ordinary path limit and long paths are 982off. The install continues: Strata's own file work uses extended paths; only the engine's own loading may not.""" 983if getattr (ctx ,"_deep_warned" ,False ): 984return 985words = longpath .warning_for (folder ,longest_inside ) 986if words and not longpath .plain_long_paths_work (ctx .components ): 987ctx ._deep_warned = True 988ctx .say ("warn" ,words ,component = "engine" ) 989 990 991def _test_progress (ctx :Context ,component :ec .EngineComponent ): 992"""What the person sees while the staged engine is test-started: a line when the phase changes and one about every 30 seconds, 993so a long load or a stuck probe is never a silent wait (#3683: 10 minutes of nothing, then a timeout).""" 994began = time .monotonic () 995seen = {"phase" :None ,"at" :0.0 } 996words = {"loading" :"is loading the model" , 997"verifying_generation" :"has loaded the model; waiting for it to answer one token" , 998"ready_file_not_matched" :"says it is ready; checking that it is the engine Strata started" } 999 1000def progress (status :dict )-> None : 1001phase = status .get ("phase" )if status .get ("state" )== "starting" else None 1002if phase not in words : 1003return 1004now = time .monotonic () 1005if phase != seen ["phase" ]or now - seen ["at" ]>= 30 : 1006seen ["phase" ],seen ["at" ]= phase ,now 1007ctx .say ("test" ,f"Engine { component . version } { words [ phase ] } ( { int ( now - began ) } s)" ,component = "engine" ) 1008 1009return progress 1010 1011 1012def _test_start_failure (component :ec .EngineComponent ,started :dict ,ctx :Context ,tail :str )-> TestStartFailed : 1013"""The plain reason a test start did not pass, in the words of what the engine was doing when it ran out of time.""" 1014error = started .get ("error" ) 1015minutes = max (1 ,int (min (ctx .test_timeout ,600 )// 60 )) 1016log = updates_dir (ctx .components )/ "logs" / f"test-start- { component . version } .log" 1017if error == "startup_wait_expired" : 1018phase = started .get ("phase" ) 1019kept = f" The engine's log from this test is in { log } ." 1020if phase == "verifying_generation" : 1021return TestStartFailed (component .version ,f"it loaded the model but did not answer one token within { minutes } minutes" , 1022busy = False ,hint = "Nothing was changed. Run `strata update` again; if it happens again, report it with the log." + kept ) 1023if phase == "ready_file_not_matched" : 1024return TestStartFailed (component .version ,f"it reported that it was ready, but Strata could not match it to the engine process it " 1025f"started" ,busy = False , 1026hint = "This looks like a problem in Strata, not in your engine or card. Nothing was changed; report it with the log." + kept ) 1027return TestStartFailed (component .version ,f"it was still loading the model after { minutes } minutes" ,busy = True , 1028hint = "Nothing was changed. A slow disk or a card that other programs are using can do this: close them and run " 1029"`strata update` again." + kept ) 1030reason = f"it did not answer a one-token probe ( { error or started . get ( 'state' ) } ) { tail } " 1031try : 1032library = missing_library (tail )or missing_library (log .read_text (errors = "replace" )) 1033except OSError : 1034library = missing_library (tail ) 1035if library :# the engine program never ran: the system lacks a library it needs 1036if not missing_library (reason ): 1037reason += f" | error while loading shared libraries: { library } : cannot open shared object file" 1038return TestStartFailed (component .version ,reason ,busy = False ,hint = library_hint (library ,linux_family ())+ f" The engine's log from this test is in { log } ." ) 1039# #4692: "report it with the log" named no log. The engine's words stay out of the sentence, but the person is told where the kept log is. 1040hint = (None if TestStartFailed .BUSY .search (reason )else 1041f"Run `strata update --force` to try again; if it fails again, report it with the log: { log } " ) 1042return TestStartFailed (component .version ,reason ,hint = hint ) 1043 1044 1045TEST_CONTEXT = 4096 1046_TEST_DROP_WITH_VALUE = ("--kv-resident" ,"--vision-tokens" ) 1047_TEST_DROP_FLAGS = ("--vision" ,) 1048 1049 1050def light_test_args (args :list )-> list : 1051"""The saved model's engine options made light for the test start (#3842): a short context, no KV kept in VRAM and no picture reader. The 1052test asks whether the NEW engine loads and answers one token, not whether this card holds the model's 262,144-token settings next to the 1053desktop and the running model; a 16 GB card refused good engines with 'out of memory' at the first weight upload.""" 1054out ,i = [],0 1055values = [str (x )for x in args ] 1056while i < len (values ): 1057item = values [i ] 1058nxt = values [i + 1 ]if i + 1 < len (values )else None 1059if item == "--max-context" and nxt is not None : 1060try : 1061out += [item ,str (min (int (nxt ),TEST_CONTEXT ))] 1062except ValueError : 1063out += [item ,nxt ] 1064i += 2 1065elif item in _TEST_DROP_WITH_VALUE and nxt is not None : 1066i += 2 1067elif item in _TEST_DROP_FLAGS : 1068i += 2 if nxt is not None and not nxt .startswith ("--" )else 1 1069else : 1070out .append (item ) 1071i += 1 1072return out 1073 1074 1075def default_test_start (stage_root :Path ,component :ec .EngineComponent ,ctx :Context )-> dict : 1076"""Start the staged engine through the real start path (owner runtime, `component:strata-engine`, a saved model), wait for 1077the one-token generation probe, and stop it. Everything runs in an isolated runtime, profile and component folder, so a 1078user's own instances, profiles and engines are not involved. With no model installed the engine is only run with --version.""" 1079source = Path (ctx .run_config )if ctx .run_config else discover_run_config (ctx .environ ) 1080if source is None : 1081if not ctx .allow_no_model_smoke : 1082raise TestStartFailed (component .version ,"no installed model to test with" ) 1083return binary_smoke (component ,ctx = ctx ) 1084from strata_control import profiles ,runtime 1085sandbox = Path (tempfile .mkdtemp (prefix = "t-" ,dir = stage_root )) 1086try : 1087cfg = json .loads (source .read_text (encoding = "utf-8-sig" )) 1088# paths setup wrote inside a Control folder that is gone (an AppImage's /tmp/.mount_<random>, a moved install): this Control's own files (QAGUI-LIN 0213) 1089from strata_control import control_paths 1090cfg = control_paths .repoint (cfg ) 1091# #5681: paths in a version folder an update removed (components/control/0.1.56/...) are resolved to the current version HERE, while 1092# STRATA_COMPONENTS_DIR is still the real one: under the sandbox's (the stage, which has no control folder) the start's own repair 1093# found no current Control and the test start failed with a ProfileError about the old file 1094from strata_control import cfg_paths 1095cfg ,_moved ,_lost = cfg_paths .resolve_config (cfg ) 1096cfg ["exe" ]= ec .REFERENCE_PREFIX + ec .COMPONENT_ID 1097cfg ["backend" ]= component .backend 1098cfg .pop ("lib_dirs" ,None ) 1099if isinstance (cfg .get ("args" ),list ): 1100cfg ["args" ]= light_test_args (cfg ["args" ]) 1101cfg ["host" ]= "127.0.0.1" 1102cfg ["port" ]= _free_port () 1103cfg ["log" ]= str (sandbox / "engine.log" ) 1104config_path = sandbox / "run.json" 1105config_path .write_text (json .dumps (cfg ,indent = 1 ),encoding = "utf-8" ) 1106env = {"STRATA_COMPONENTS_DIR" :str (stage_root ),"STRATA_PROFILE_DIR" :str (sandbox / "profiles" ), 1107"STRATA_RUNTIME_DIR" :str (sandbox / "runtime" ),"STRATA_NO_ACQUIRE" :"1" , 1108"STRATA_ENGINE_BACKEND" :component .backend } 1109name = "updtest" 1110with _patched_environ (env ): 1111os .environ .pop ("STRATA_API_KEY" ,None ) 1112profiles .create (name ,str (config_path )) 1113started = None 1114try : 1115started = runtime .start (name ,wait = min (ctx .test_timeout ,600 ),shutdown_timeout = 20 , 1116on_status = _test_progress (ctx ,component )) 1117if started .get ("ok" )and started .get ("state" )== "ready" and started .get ("generation_ready" )is not True : 1118# a server that loads its model on the first request is "ready" without having generated anything: 1119# force the load and the one-token probe, because that is what the new engine has to be able to do 1120ctx .say ("test" ,f"Engine { component . version } is up; asking it for one token" ,component = "engine" ) 1121started = {** started ,** runtime .verify (name ,timeout = min (ctx .test_timeout ,600 ),load = True )} 1122if not started .get ("ok" )or started .get ("state" )!= "ready" or started .get ("generation_ready" )is not True : 1123_keep_log (sandbox ,component ,ctx ) 1124_keep_records (sandbox ,component ,ctx ) 1125raise _test_start_failure (component ,started ,ctx ,_log_tail (sandbox ,component )) 1126_keep_log (sandbox ,component ,ctx ) 1127return {"mode" :"full" ,"model" :cfg .get ("model_name" )or source .stem ,"state" :started ["state" ], 1128"generation_ready" :True ,"detail" :"started, answered a one-token probe, stopped" } 1129except TestStartFailed : 1130_keep_log (sandbox ,component ,ctx ) 1131_keep_records (sandbox ,component ,ctx ) 1132raise 1133except Exception as exc :# noqa: BLE001 1134_keep_log (sandbox ,component ,ctx ) 1135_keep_records (sandbox ,component ,ctx ) 1136raise TestStartFailed (component .version ,f" { type ( exc ). __name__ } : { exc } " )from None 1137finally : 1138try : 1139runtime .stop (name ,timeout = 60 ) 1140except Exception :# noqa: BLE001 - stopping a sandbox is best effort 1141pass 1142finally : 1143shutil .rmtree (longpath .long_path (sandbox ),ignore_errors = True ) 1144 1145 1146#: How long a folder rename is retried before the copy is used instead (seconds). A 950 MB engine that was just written is scanned by 1147#: the virus scanner for longer than the old 8 seconds on a slow disk (#4853: unpacked and checked, then "the update didn't finish"). 1148MOVE_PATIENCE_S = 40.0 1149 1150 1151def _move_dir (source :Path ,destination :Path ,* ,patience :float = MOVE_PATIENCE_S ,sleep = time .sleep ,clock = time .monotonic )-> None : 1152"""Put a checked folder where it belongs. A rename is the normal way; on Windows it is refused for as long as any program (the virus 1153scanner, the indexer, Explorer) holds one file inside the folder, so it is retried for `patience` seconds. If it is still refused, 1154the folder is copied instead: a copy needs only to read the files, and the caller checks the copy again (every file's hash is 1155verified when the engine is chosen), so a copy that is wrong is never used.""" 1156last = None 1157deadline = clock ()+ patience 1158attempt = 0 1159while True : 1160try : 1161os .replace (source ,destination ) 1162return 1163except OSError as exc : 1164last = exc 1165if clock ()>= deadline : 1166break 1167attempt += 1 1168sleep (min (0.4 * attempt ,3.0 )) 1169try : 1170shutil .copytree (longpath .long_path (source ),longpath .long_path (destination )) 1171except OSError as exc : 1172shutil .rmtree (longpath .long_path (destination ),ignore_errors = True ) 1173raise UpdateError (f"the new engine could not be moved into place ( { longpath . describe_oserror ( last ) } ); copying it did not work " 1174f"either ( { longpath . describe_oserror ( exc ) } )" ,6 )from None 1175shutil .rmtree (longpath .long_path (source ),ignore_errors = True )# the staging folder is removed again at the end; a held file waits 1176 1177 1178def prune_engines (root :Path ,keep :set [str ])-> list [str ]: 1179removed = [] 1180folder = ec .engine_dir (root ) 1181if not folder .is_dir (): 1182return removed 1183for entry in sorted (folder .iterdir ()): 1184if entry .is_dir ()and not entry .name .startswith ("." )and entry .name not in keep : 1185try : 1186shutil .rmtree (longpath .long_path (entry )) 1187removed .append (entry .name ) 1188except OSError : 1189pass # in use: it goes with the next update 1190return removed 1191 1192 1193def update_engine (ctx :Context ,feed :feedmod .Feed ,state :State )-> dict : 1194"""Install the best engine package for this PC if it is newer than the installed one. See the module docstring.""" 1195decision ,pkg = _choose_engine (feed ,ctx ,state ) 1196status = decision ["status" ] 1197result = {"component" :"engine" ,"status" :status ,"installed_before" :decision ["installed" ],"changed" :False } 1198if status not in ("install" ,"available" )and not (ctx .force and status in ("failed-before" ,"skipped" )): 1199result ["note" ]= decision .get ("note" )or {"current" :"The engine is up to date." , 1200"none-for-this-pc" :"The feed has no engine package for this PC." , 1201"not-in-feed" :"The feed lists no engines." }.get (status ,status ) 1202if status == "none-for-this-pc" : 1203result ["reasons" ]= decision ["reasons" ] 1204return result 1205root = ctx .components 1206local = decision .get ("installed_locally" ) 1207if local : 1208return _switch_to_installed (ctx ,state ,local ,result ) 1209have_makes = installed_gpu_makes (root ,pkg .platform ) 1210if pkg .backend in GPU_MAKES and have_makes and pkg .backend not in have_makes and ctx .hardware .get ("backend_source" )not in ("environment" ,"requested" ,"saved choice" ): 1211raise UpdateError (f"the { pkg . label } engine is for another make of graphics card than the installed one; nothing was staged" ,5 ) 1212_warn_if_deep (ctx ,ec .engine_dir (root )/ folder_name (pkg ),longpath .LONGEST_IN_PACKAGE .get (pkg .backend ,longpath .LONGEST_IN_PACKAGE_DEFAULT )+ 1 ) 1213_free_space_check (root ,pkg .size + pkg .installed_bytes ,ctx ,pkg .sha256 ,"engine" ) 1214archive = _download (ctx ,"engine" ,pkg .url ,pkg .size ,pkg .sha256 ,f"engine { pkg . label } " ,feed ) 1215# busy check after the long download: a model may have been started meanwhile; the verified archive is kept for the retry 1216idle_gate (ctx ) 1217try : 1218stage_root ,staged = stage_engine (ctx ,feed ,pkg ,archive ) 1219except UpdateError as exc : 1220if exc .exit_code == 5 : 1221archive .unlink (missing_ok = True )# a refused package is not kept for a retry 1222raise 1223return _finish_engine_install (ctx ,state ,pkg ,stage_root ,staged ,archive ,result ,delete_archive = True ) 1224 1225 1226def _switch_to_installed (ctx :Context ,state :State ,folder :str ,result :dict )-> dict : 1227"""An update to an engine that is already on this computer: nothing is downloaded; it becomes the engine in use and any pin is cleared.""" 1228from strata_control import engine_library 1229idle_gate (ctx ) 1230ctx .say ("switch" ,"This engine is already on this computer; switching to it" ,component = "engine" ) 1231out = engine_library .use_qwen_unlocked (ctx ,state ,folder ) 1232chosen ,_ = installed_engine (ctx .components ,ctx .hardware ) 1233result .update ({"changed" :out .get ("changed" ,False ),"status" :"updated" if out .get ("changed" )else "current" ,"installed_after" :_engine_view (chosen ), 1234"previous" :state .section ("engine" ).get ("previous" ),"removed" : [],"presets_marked" :bool (out .get ("presets_marked" )),"from_disk" :True }) 1235state .history ({"at" : (ctx .now or dt .datetime .now (dt .timezone .utc )).isoformat (),"action" :"update-engine" ,"from" : (result .get ("installed_before" )or {}).get ("version" ), 1236"to" :chosen .version if chosen else None ,"ok" :True ,"detail" :"already installed" }) 1237state .save () 1238ctx .say ("done" ,f"Engine { chosen . version if chosen else '' } is in use from the next start" ,component = "engine" ) 1239return result 1240 1241 1242def _finish_engine_install (ctx :Context ,state :State ,pkg :feedmod .EnginePackage ,stage_root :Path ,staged :ec .EngineComponent , 1243archive :Path ,result :dict ,* ,delete_archive :bool )-> dict : 1244"""The part of an engine install both ways share (a download from the feed, a file the person chose): test-start the staged engine, 1245switch to it, keep the previous one, remove the staging folder. ``archive`` is only deleted when Strata downloaded it.""" 1246root = ctx .components 1247before_installed ,_ = installed_engine (root ,ctx .hardware ) 1248before_identity = preset_marks .identity_of (before_installed ,_manifest_sha (before_installed .root ))if before_installed else None 1249try : 1250ctx .say ("test" ,f"Test-starting engine { pkg . label } before switching to it" ,component = "engine" ) 1251runner = ctx .test_start or default_test_start 1252try : 1253smoke = runner (stage_root ,staged ,ctx ) 1254except TestStartFailed as exc : 1255try :# a model of Strata's own launch holds the card: one next step, not the engine's words 1256own = [s for s in ctx .serving ()if str (s .get ("profile" ,"" )).startswith ("launch-" )] 1257except Exception :# noqa: BLE001 1258own = [] 1259if own : 1260raise Busy (own )from None 1261section = state .section ("engine" ) 1262at = (ctx .now or dt .datetime .now (dt .timezone .utc )).isoformat () 1263if not exc .busy :# a busy card says nothing about the engine: the next update tries again 1264section .setdefault ("failed" , {})[pkg .version ]= { 1265"manifest_sha256" :pkg .manifest_sha256 ,"reason" :exc .reason [:300 ],"at" :at } 1266state .history ({"at" :at ,"action" :"update-engine" ,"to" :pkg .version , 1267"from" :before_installed .version if before_installed else None ,"ok" :False , 1268"detail" :f"test start failed: { exc . reason [: 200 ] } " }) 1269state .save () 1270raise 1271# last look before the switch: an engine may have started during the test-start 1272idle_gate (ctx ) 1273name = folder_name (pkg ) 1274live = ec .engine_dir (root ) 1275live .mkdir (parents = True ,exist_ok = True ) 1276final = live / name 1277staged_folder = stage_root / "engine" / name 1278if final .exists (): 1279if (final / ec .MANIFEST ).is_file ()and _manifest_sha (final )== pkg .manifest_sha256 : 1280shutil .rmtree (longpath .long_path (staged_folder ),ignore_errors = True )# already installed byte for byte: only the state changes 1281else : 1282final = live / f" { name } - { pkg . manifest_sha256 [: 8 ] } " 1283_move_dir (staged_folder ,final ) 1284else : 1285_move_dir (staged_folder ,final ) 1286ctx .say ("switch" ,f"Switching to engine { pkg . label } " ,component = "engine" ) 1287section = state .section ("engine" ) 1288old_pin = section .pop ("pinned" ,None ) 1289state .save ()# a start reads the pin from the file, so the unpin is written before the check 1290try : 1291chosen = ec .resolve (root ,backend = ctx .hardware .get ("backend" ),full = True ,runtime = ctx .hardware .get ("runtime" )) 1292if chosen .root .name != final .name : 1293raise ec .EngineMissing (f"a start would pick { chosen . root . name } , not { final . name } " ,root ) 1294except ec .EngineMissing as exc : 1295if old_pin : 1296section ["pinned" ]= old_pin 1297state .save () 1298# the rename did not give a working engine: put it back where it cannot be picked 1299shutil .rmtree (longpath .long_path (live / ".rejected" ),ignore_errors = True ) 1300 (live / ".rejected" ).mkdir (parents = True ,exist_ok = True ) 1301if final .exists (): 1302_move_dir (final ,live / ".rejected" / final .name ) 1303raise UpdateError (f"the new engine was not accepted after the switch ( { exc } ); the previous engine is unchanged" ,6 )from None 1304previous = before_installed .root .name if before_installed and before_installed .root .name != final .name else section .get ("previous" ) 1305section ["previous" ]= previous 1306section ["active" ]= final .name 1307section .get ("failed" , {}).pop (pkg .version ,None ) 1308skipped = [v for v in section .get ("skipped" , [])if v != pkg .version ] 1309section ["skipped" ]= skipped 1310after_identity = preset_marks .identity_of (chosen ,pkg .manifest_sha256 ) 1311mark = preset_marks .mark_engine_changed (before_identity ,after_identity ,base = ctx .state_base ) 1312removed :list [str ]= []# every older engine stays until the person deletes it (Settings > Engine, `strata components remove`) 1313state .history ({"at" : (ctx .now or dt .datetime .now (dt .timezone .utc )).isoformat (),"action" :"update-engine" , 1314"from" :before_installed .version if before_installed else None ,"to" :pkg .version ,"ok" :True , 1315"detail" :smoke .get ("mode" )}) 1316state .save () 1317if delete_archive : 1318archive .unlink (missing_ok = True ) 1319result .update ({"changed" :True ,"status" :"updated" ,"installed_after" :_engine_view (chosen ),"test_start" :smoke , 1320"previous" :previous ,"removed" :removed ,"presets_marked" :bool (mark )}) 1321ctx .say ("done" ,f"Engine { pkg . version } is installed and will be used on the next start" ,component = "engine" ) 1322return result 1323finally : 1324shutil .rmtree (longpath .long_path (stage_root ),ignore_errors = True ) 1325 1326 1327def _archive_format (archive :Path )-> str : 1328name = archive .name .lower () 1329for suffix ,fmt in ((".tar.gz" ,"tar.gz" ), (".tgz" ,"tar.gz" ), (".tar.xz" ,"tar.xz" ), (".zip" ,"zip" )): 1330if name .endswith (suffix ): 1331return fmt 1332raise UpdateError ("this is not a Strata engine package (it should be a .tar.gz or .zip file from the release page)" ,5 ) 1333 1334 1335def install_engine_file (ctx :Context ,archive :Path )-> dict : 1336"""Install an engine package the person downloaded themselves (the offline path of the first-run card). No feed and no network: 1337the package must carry the feed key's signature on its manifest, every file must match the manifest, and the package must fit this 1338PC. After that it goes through the same test start and switch as a downloaded one. The file the person chose is left where it is.""" 1339archive = Path (archive ) 1340if not archive .is_file (): 1341raise UpdateError (f" { archive } is not a file" ,5 ) 1342fmt = _archive_format (archive ) 1343state_root = ctx .components 1344with update_lock (state_root ): 1345state = State (state_root ) 1346stage_root = new_stage (state_root ) 1347keep_stage = False 1348try : 1349try : 1350total = _archive_size (archive ,fmt ) 1351except (tarfile .TarError ,zipfile .BadZipFile ,OSError ,EOFError )as exc : 1352raise UpdateError (f"this file cannot be read as a package ( { type ( exc ). __name__ } ); download it again" ,5 )from None 1353_free_space_check (state_root ,total * 2 ,ctx ,"" ,"engine" ) 1354folder = stage_root / "engine" / "incoming" 1355longpath .long_path (folder .parent ).mkdir (parents = True ,exist_ok = True ) 1356ctx .say ("verify" ,"Unpacking the engine file" ,component = "engine" ) 1357extract (archive ,folder ,fmt ,total ) 1358try : 1359component = ec .read_manifest (folder ) 1360except ec .ComponentProblem as exc : 1361raise UpdateError (f"this file is not a Strata engine package: { exc } " ,5 )from None 1362ctx .say ("verify" ,"Checking the package signature and every file" ,component = "engine" ) 1363outer = ec ._verifier 1364signing .install_component_verifier (ctx .trusted ) 1365try : 1366ec .verify_signature (component , {** ctx .environ ,ec .ENV_REQUIRE_SIGNED :"1" }) 1367ec .verify (component ,full = True ) 1368except ec .ComponentProblem as exc : 1369raise UpdateError (f"this file did not pass the security check, so it was not used ( { exc } )" ,5 )from None 1370finally : 1371ec .register_signature_verifier (outer ) 1372pkg = feedmod .EnginePackage ( 1373version = component .version ,platform = component .platform ,backend = component .backend ,variant = component .variant or "" , 1374archs = tuple (component .archs ),min_driver = dict (component .min_driver or {}),min_runtime = component .min_runtime , 1375build_id = component .build_id ,url = "" ,format = fmt ,size = archive .stat ().st_size ,sha256 = transfer .sha256_file (archive ), 1376manifest_sha256 = transfer .sha256_file (folder / ec .MANIFEST ),installed_bytes = total ) 1377why = feedmod .engine_fit_reasons (pkg ,ctx .hardware ) 1378if why : 1379raise UpdateError ("this file is not a Strata engine for this PC: " + "; " .join (why ),5 ) 1380# the staged folder gets the name an installed package has 1381final_stage = stage_root / "engine" / folder_name (pkg ) 1382if final_stage != folder : 1383_move_dir (folder ,final_stage ) 1384staged = ec .read_manifest (final_stage ) 1385before ,_ = installed_engine (state_root ,ctx .hardware ) 1386if before is not None and feedmod .version_key (before .version )> feedmod .version_key (pkg .version )and not ctx .force : 1387return {"component" :"engine" ,"status" :"current" ,"changed" :False ,"installed_before" :_engine_view (before ), 1388"note" :f"Engine { before . version } is already installed and is newer than this file ( { pkg . version } ); nothing was changed." } 1389result = {"component" :"engine" ,"status" :"install" if before is None else "available" , 1390"installed_before" :_engine_view (before ),"changed" :False ,"source" :"file" } 1391keep_stage = True 1392return _finish_engine_install (ctx ,state ,pkg ,stage_root ,staged ,archive ,result ,delete_archive = False ) 1393finally : 1394if not keep_stage : 1395shutil .rmtree (longpath .long_path (stage_root ),ignore_errors = True ) 1396 1397 1398def switch_engine (ctx :Context ,state :State ,name :str ,target :ec .EngineComponent ,* ,unpin_if_automatic :bool = False , 1399what :str = "engine" )-> dict : 1400"""Make the installed package folder ``name`` the engine a start uses. Nothing is downloaded or removed; the package was verified by the 1401caller. A pin makes the package the one a start picks even though a newer one is installed. With ``unpin_if_automatic`` the pin is dropped 1402when the package is what a start picks anyway (the newest one), so the engine follows updates again. One writer of the pin and of the 1403previous / skipped bookkeeping: `strata components rollback` and `use_engine` (Settings > Engine, `strata components use`) both come here.""" 1404section = state .section ("engine" ) 1405current ,_ = installed_engine (ctx .components ,ctx .hardware ) 1406leaving = current .root .name if current else None 1407before_identity = preset_marks .identity_of (current ,_manifest_sha (current .root ))if current else None 1408old_pin = section .get ("pinned" ) 1409automatic = False 1410if unpin_if_automatic : 1411section .pop ("pinned" ,None ) 1412state .save () 1413try : 1414picked = ec .resolve (ctx .components ,backend = ctx .hardware .get ("backend" ),full = True ,runtime = ctx .hardware .get ("runtime" )) 1415automatic = picked .root .name == name 1416except ec .EngineMissing : 1417automatic = False 1418if not automatic : 1419section ["pinned" ]= name 1420state .save ()# a start reads the pin from the file, so it is written before it is checked 1421try : 1422chosen = ec .resolve (ctx .components ,backend = ctx .hardware .get ("backend" ),full = True ,runtime = ctx .hardware .get ("runtime" )) 1423if chosen .root .name != name : 1424raise ec .EngineMissing (f"a start would pick { chosen . root . name } " ,ctx .components ) 1425except ec .EngineMissing as exc : 1426if old_pin : 1427section ["pinned" ]= old_pin 1428else : 1429section .pop ("pinned" ,None ) 1430state .save () 1431raise UpdateError (f"the { what } does not fit this PC any more: { exc } " ,5 )from None 1432forward = bool (current )and feedmod .version_key (target .version )> feedmod .version_key (current .version ) 1433if forward : 1434# going to the newer engine: it is no longer one the person left, so a later update may offer it 1435section ["skipped" ]= [v for v in section .get ("skipped" , [])if v != target .version ] 1436elif current and current .version != target .version : 1437skip = section .setdefault ("skipped" , []) 1438if current .version not in skip : 1439skip .append (current .version ) 1440section ["previous" ]= leaving 1441section ["active" ]= name 1442mark = preset_marks .mark_engine_changed (before_identity ,preset_marks .identity_of (chosen ,_manifest_sha (chosen .root )),base = ctx .state_base ) 1443state .history ({"at" : (ctx .now or dt .datetime .now (dt .timezone .utc )).isoformat (),"action" :"rollback-engine" if what != "engine" else "use-engine" , 1444"from" :current .version if current else None ,"to" :target .version ,"ok" :True }) 1445state .save () 1446return {"component" :"engine" ,"status" :"rolled-forward" if forward else "rolled-back" ,"from" :current .version if current else None , 1447"to" :target .version ,"folder" :name ,"presets_marked" :bool (mark ),"automatic" :automatic } 1448 1449 1450def rollback_engine (ctx :Context )-> dict : 1451"""Return to the previous engine version, which the last switch or update left. Nothing is downloaded. A pin makes the older 1452package the one a start picks even though a newer one is installed; the next successful update clears it.""" 1453with update_lock (ctx .components ): 1454state = State (ctx .components ) 1455section = state .section ("engine" ) 1456previous = section .get ("previous" ) 1457if not previous : 1458raise UpdateError ("there is no previous engine to return to (the last update kept none, or none has happened)" ,2 ) 1459folder = ec .engine_dir (ctx .components )/ previous 1460wait_until_idle (ctx .serving ,wait = ctx .wait ,emit = ctx .emit ,cancel = ctx .cancel ,poll = ctx .poll ) 1461try : 1462target = ec .read_manifest (folder ) 1463signing .ensure_component_verifier () 1464ec .verify (target ,full = True ) 1465except (ec .ComponentProblem ,OSError )as exc : 1466raise UpdateError (f"the previous engine ( { previous } ) can no longer be used: { exc } " ,5 )from None 1467current ,_ = installed_engine (ctx .components ,ctx .hardware ) 1468if current is not None and current .root .name == previous : 1469# an earlier rollback is still in force (S3: the text said "0.1.45.3 -> 0.1.45.3"): there is nothing to leave behind 1470raise UpdateError (f"the engine is already the previous one ( { current . version } ); there is nothing older to return to. " 1471"Run `strata update --force` to try the newer version again." ,2 ) 1472return switch_engine (ctx ,state ,previous ,target ,what = "previous engine" ) 1473 1474 1475# ---------------------------------------------------------------------------------------------- control 1476 1477def control_dir (root :Path )-> Path : 1478return root / "control" 1479 1480 1481def active_control (root :Path )-> dict | None : 1482try : 1483data = json .loads ((control_dir (root )/ "active.json" ).read_text (encoding = "utf-8-sig" )) 1484return data if isinstance (data ,dict )and data .get ("version" )and data .get ("folder" )else None 1485except (OSError ,ValueError ): 1486return None 1487 1488 1489def source_tree_version (root :Path | None = None )-> str | None : 1490"""The version of a source checkout (it has no VERSION file): the project version in its CMakeLists.txt, the same rule `strata --version` uses. 1491Used only to PRINT what a checkout runs (`update --check` said `Control ?: available`); the decision to stage a Control copy does not use it.""" 1492root = root or Path (__file__ ).resolve ().parents [1 ] 1493try : 1494found = re .search (r"^\s*project\([^)]*?VERSION\s+([0-9]+(?:\.[0-9]+)+)" , (root / "CMakeLists.txt" ).read_text (encoding = "utf-8" ,errors = "replace" ),re .MULTILINE ) 1495except OSError : 1496return None 1497return found .group (1 )if found else None 1498 1499 1500def decide_control (feed :feedmod .Feed ,ctx :Context ,state :State )-> dict : 1501here = ctx .hardware ["platform" ] 1502pkg = next ((p for p in feed .control if p .platform == here ),None ) 1503installed = (active_control (ctx .components )or {}).get ("version" )or ec .runtime_version () 1504report = {"installed" :installed ,"offered" :pkg .version if pkg else None ,"status" :"not-in-feed" ,"download_bytes" :0 } 1505if pkg is None : 1506return report 1507report ["download_bytes" ]= pkg .size 1508if not installed : 1509report ["status" ]= "available" 1510else : 1511have ,want = feedmod .version_key (installed ),feedmod .version_key (pkg .version ) 1512report ["status" ]= "available" if want > have else "current" 1513return report 1514 1515 1516CONTROL_VERSION_TIMEOUTS = (240 ,360 )# seconds: antivirus scans a fresh python.exe on its first run, which can take minutes 1517 1518 1519def _control_version (interpreter :str ,entry :Path ,stage :Path ,ctx :Context ,version :str ): 1520"""Run `--version` of the staged Control; once more, with more time, when the first try timed out, failed to start or said nothing.""" 1521last_error = None 1522done = None 1523for attempt ,timeout in enumerate (CONTROL_VERSION_TIMEOUTS ): 1524try : 1525done = subprocess .run ([interpreter ,str (entry ),"--version" ],capture_output = True ,text = True ,errors = "replace" ,timeout = timeout ,cwd = str (stage ), 1526env = {** ctx .environ ,"PYTHONNOUSERSITE" :"1" ,"STRATA_NO_ACQUIRE" :"1" ,"STRATA_HANDOVER" :"1" }, 1527creationflags = getattr (subprocess ,"CREATE_NO_WINDOW" ,0 )) 1528last_error = None 1529if done .returncode == 0 and version in done .stdout : 1530return done 1531except (OSError ,subprocess .SubprocessError )as exc : 1532last_error = exc 1533if attempt + 1 < len (CONTROL_VERSION_TIMEOUTS ): 1534ctx .say ("test" ,f"Control { version } did not answer yet (a virus scanner may be checking it); trying once more" ,component = "control" ) 1535if last_error is not None : 1536raise TestStartFailed (f"Control { version } " ,f" { type ( last_error ). __name__ } : { last_error } " )from None 1537return done 1538 1539 1540def _failed_mark_is_old (mark :dict ,ctx :Context ,hours :float = 24.0 )-> bool : 1541try : 1542then = dt .datetime .fromisoformat (str (mark .get ("at" ))) 1543if then .tzinfo is None : 1544then = then .replace (tzinfo = dt .timezone .utc ) 1545return (ctx .now or dt .datetime .now (dt .timezone .utc ))- then > dt .timedelta (hours = hours ) 1546except (TypeError ,ValueError ): 1547return False 1548 1549 1550def update_control (ctx :Context ,feed :feedmod .Feed ,state :State )-> dict : 1551"""Stage a newer Control bundle beside the running one, run it once (`--version`), and only then point the app and the 1552terminal at it (``components/control/active.json``). The running Control is never modified.""" 1553decision = decide_control (feed ,ctx ,state ) 1554result = {"component" :"control" ,"status" :decision ["status" ],"changed" :False ,"installed_before" :decision ["installed" ]} 1555if decision ["status" ]!= "available" : 1556return result 1557pkg = next (p for p in feed .control if p .platform == ctx .hardware ["platform" ]) 1558root = ctx .components 1559_free_space_check (root ,pkg .size + pkg .installed_bytes ,ctx ,pkg .sha256 ,"control" ) 1560archive = _download (ctx ,"control" ,pkg .url ,pkg .size ,pkg .sha256 ,f"Control { pkg . version } " ,feed ) 1561idle_gate (ctx )# a new Control never takes over beside a model that is loaded without the person's yes 1562stage = new_stage (root ,"c" ) 1563try : 1564ctx .say ("verify" ,f"Unpacking Control { pkg . version } " ,component = "control" ) 1565extract (archive ,stage ,pkg .format ,pkg .installed_bytes ,allow_links = pkg .format != "zip" ) 1566entry = stage / pkg .entry 1567if not entry .is_file (): 1568raise UpdateError (f"the Control package has no { pkg . entry } " ,5 ) 1569python = stage / "python" / ("python.exe" if os .name == "nt" else "bin/python3" ) 1570interpreter = str (python )if python .is_file ()else sys .executable 1571ctx .say ("test" ,f"Test-starting Control { pkg . version } " ,component = "control" ) 1572done = _control_version (interpreter ,entry ,stage ,ctx ,pkg .version ) 1573if done .returncode != 0 or pkg .version not in done .stdout : 1574raise TestStartFailed (f"Control { pkg . version } " ,f"--version said { done . stdout . strip ()[: 120 ]!r } (exit { done . returncode } )" ) 1575final = control_dir (root )/ pkg .version 1576control_dir (root ).mkdir (parents = True ,exist_ok = True ) 1577if final .exists (): 1578shutil .rmtree (longpath .long_path (final ),ignore_errors = True ) 1579_move_dir (stage ,final ) 1580section = state .section ("control" ) 1581previous = active_control (root ) 1582section ["previous" ]= previous 1583pointer = control_dir (root )/ "active.json" 1584temp = pointer .with_suffix (".tmp" ) 1585temp .write_text (json .dumps ({"version" :pkg .version ,"folder" :pkg .version ,"sha256" :pkg .sha256 }),encoding = "utf-8" ) 1586_atomic_mod .replace (temp ,pointer ) 1587keep = {pkg .version }| ({previous ["folder" ]}if previous else set ()) 1588for entry_dir in control_dir (root ).iterdir (): 1589if entry_dir .is_dir ()and entry_dir .name not in keep and not folder_use .in_use (entry_dir ):# (never the Control a running server runs from) 1590shutil .rmtree (longpath .long_path (entry_dir ),ignore_errors = True ) 1591state .history ({"at" : (ctx .now or dt .datetime .now (dt .timezone .utc )).isoformat (),"action" :"update-control" , 1592"from" :decision ["installed" ],"to" :pkg .version ,"ok" :True }) 1593archive .unlink (missing_ok = True ) 1594result .update ({"changed" :True ,"status" :"updated" ,"installed_after" :pkg .version , 1595"note" :"the Terminal hands over to it from the next command; the app uses it from its next start" }) 1596return result 1597finally : 1598shutil .rmtree (longpath .long_path (stage ),ignore_errors = True ) 1599 1600 1601# ---------------------------------------------------------------------------------------------- app 1602 1603def app_public_key (environ = None )-> str | None : 1604environ = os .environ if environ is None else environ 1605explicit = environ .get ("STRATA_APP_UPDATE_PUBKEY" ) 1606if explicit : 1607return explicit 1608try : 1609data = json .loads (signing .BUILTIN_KEYS .read_text (encoding = "utf-8-sig" )) 1610value = data .get ("app_minisign_public" ) 1611return value if isinstance (value ,str )and value else None 1612except (OSError ,ValueError ): 1613return None 1614 1615 1616def decide_app (feed :feedmod .Feed ,ctx :Context )-> dict : 1617report = {"installed" :ctx .app_version ,"offered" :None ,"status" :"not-in-feed" ,"notes" :"" ,"download_bytes" :0 } 1618if feed .app is None : 1619return report 1620entry = feed .app .for_platform (ctx .hardware ["platform" ]) 1621if entry is None : 1622report ["status" ]= "none-for-this-pc" 1623return report 1624report .update ({"offered" :feed .app .version ,"notes" :feed .app .notes ,"download_bytes" :entry ["size" ]}) 1625if not ctx .app_version : 1626report ["status" ]= "unknown-installed" 1627else : 1628report ["status" ]= "available" if feedmod .app_version_key (feed .app .version )> feedmod .app_version_key (ctx .app_version )else "current" 1629return report 1630 1631 1632def update_app (ctx :Context ,feed :feedmod .Feed )-> dict : 1633"""The Terminal's share of an app update: download the installer, check its SHA-256 (signed feed) and its minisign signature 1634(the key the app trusts), and leave it in ``.updates/app``. The Desktop app installs itself through Tauri's updater; a 1635terminal only fetches and verifies, because installing an app is the platform installer's job.""" 1636decision = decide_app (feed ,ctx ) 1637result = {"component" :"app" ,"status" :decision ["status" ],"changed" :False ,"installed_before" :decision ["installed" ]} 1638if decision ["status" ]not in ("available" ,"unknown-installed" ): 1639return result 1640entry = feed .app .for_platform (ctx .hardware ["platform" ]) 1641key = app_public_key (ctx .environ ) 1642if not key : 1643raise UpdateError ("this build has no app update key (update_keys.json app_minisign_public); the app installer cannot be verified, so it was not downloaded" ,5 ) 1644root = ctx .components 1645_free_space_check (root ,entry ["size" ],ctx ,entry ["sha256" ],"app" ) 1646archive = _download (ctx ,"app" ,entry ["url" ],entry ["size" ],entry ["sha256" ],f"Strata app { feed . app . version } " ,feed ) 1647 1648def chunks (): 1649with archive .open ("rb" )as stream : 1650yield from iter (lambda :stream .read (1 << 20 ),b"" ) 1651try : 1652signing .minisign_verify (key ,entry ["signature" ],chunks ()) 1653except signing .SignatureError as exc : 1654archive .unlink (missing_ok = True ) 1655raise UpdateError (f"the app installer failed its signature check: { exc } ; it was deleted" ,5 )from None 1656target_dir = updates_dir (root )/ "app" 1657target_dir .mkdir (parents = True ,exist_ok = True ) 1658name = Path (transfer .resolve_ref (transfer .base_of (feed .source ),entry ["url" ]).replace ("\\" ,"/" )).name or f"strata-app- { feed . app . version } " 1659target = target_dir / name 1660_atomic_mod .replace (archive ,target ) 1661result .update ({"changed" :True ,"status" :"downloaded" ,"installed_after" :None ,"version" :feed .app .version ,"path" :str (target ), 1662"note" :"Verified. Run the installer to finish; models and settings are kept." }) 1663return result 1664 1665 1666# ---------------------------------------------------------------------------------------------- the one command 1667 1668def _installed_before (name :str ,ctx :Context ): 1669"""What was installed when a step failed, for the report: the engine's view, Control's version, or nothing.""" 1670try : 1671if name == "engine" : 1672return _engine_view (installed_engine (ctx .components ,ctx .hardware )[0 ]) 1673if name == "control" : 1674return (active_control (ctx .components )or {}).get ("version" )or ec .runtime_version () 1675except Exception :# noqa: BLE001 - reporting only 1676pass 1677return None 1678 1679 1680def pending_changes (feed :feedmod .Feed ,ctx :Context ,state :State ,* ,engine :bool = True ,control :bool = True )-> list [str ]: 1681"""What this update would install or switch, in words, from the feed alone (nothing is downloaded). Empty: nothing to do.""" 1682out = [] 1683if engine : 1684decision = decide_engine (feed ,ctx ,state ) 1685if decision ["status" ]in ("install" ,"available" )or (ctx .force and decision ["status" ]in ("failed-before" ,"skipped" )): 1686offered = (decision .get ("offered" )or {}).get ("version" ) 1687have = (decision .get ("installed" )or {}).get ("version" ) 1688out .append (f"engine { have } -> { offered } " if have else f"engine { offered } " ) 1689if control : 1690decision = decide_control (feed ,ctx ,state ) 1691if decision ["status" ]== "available" : 1692out .append (f"Control { decision [ 'installed' ] } -> { decision [ 'offered' ] } " ) 1693return out 1694 1695 1696def _model_check (ctx :Context ,feed :feedmod .Feed ,state :State ,* ,engine :bool ,control :bool )-> None : 1697"""Before anything is downloaded: with a model loaded and something to install, either wait for it to stop (--wait), ask (a gate), or refuse. 1698An update never starts by itself beside a loaded model, and never half-runs (the engine refused while Control moves on).""" 1699changes = pending_changes (feed ,ctx ,state ,engine = engine ,control = control ) 1700if not changes : 1701return 1702if ctx .wait : 1703wait_until_idle (ctx .serving ,wait = ctx .wait ,emit = ctx .emit ,cancel = ctx .cancel ,poll = ctx .poll ) 1704serving = ctx .serving () 1705if not serving : 1706return 1707gate = getattr (ctx ,"gate" ,None ) 1708if gate is None : 1709raise Busy (serving ) 1710gate .consent (serving ,"It would update the " + " and the " .join (changes )+ "." ) 1711 1712 1713def _shape_steps (ctx :Context ,feed :feedmod .Feed ,engine :bool )-> list : 1714"""One step for each model-shape engine installed here (strata_control/shape_engine.py): the explicit update brings it up to the feed's, beside the older one; the Strata engine is 1715not touched. A PC that never installed one has no such step.""" 1716if not engine : 1717return [] 1718from strata_control import shape_engine 1719return [(shape_engine .component_id (shape ), (lambda shape = shape :shape_engine .update_one (ctx ,feed ,shape ,install_missing = False ))) 1720for shape in shape_engine .installed_shapes (ctx .components )] 1721 1722 1723def run_update (ctx :Context ,* ,engine :bool = True ,control :bool = True ,app :bool = False )-> dict : 1724"""`strata update`: the feed once, then the engine, Control and (if asked) the app installer, each reported separately. 1725A component that fails does not undo one that succeeded; the exit code is the worst one.""" 1726require_acquisition ("the update" ) 1727results ,failure = [],None 1728with update_lock (ctx .components ): 1729state = State (ctx .components ) 1730feed = open_feed (ctx ,state ) 1731state .save () 1732_model_check (ctx ,feed ,state ,engine = engine ,control = control ) 1733steps = ([("engine" ,lambda :update_engine (ctx ,feed ,state ))]if engine else [])+ \ 1734_shape_steps (ctx ,feed ,engine )+ \ 1735 ([("control" ,lambda :update_control (ctx ,feed ,state ))]if control else [])+ \ 1736 ([("app" ,lambda :update_app (ctx ,feed ))]if app else []) 1737for name ,step in steps : 1738try : 1739results .append (step ()) 1740except UpdateError as exc : 1741results .append ({"component" :name ,"status" :"failed" ,"changed" :False ,"error" :str (exc ),"exit_code" :exc .exit_code , 1742"installed_before" :_installed_before (name ,ctx )}) 1743failure = failure or exc 1744if any (r .get ("component" )== "engine" and r .get ("status" )== "updated" for r in results ): 1745state .data .get ("last_check" , {}).pop ("engine" ,None ) 1746try :# the feed was read for this update: what it offers that is still newer is kept for the app's one card 1747now_control = next ((r .get ("installed_after" )for r in results if r .get ("component" )== "control" and r .get ("status" )== "updated" ),None ) 1748state .data ["last_check" ]= _last_check (ctx , {"engine" :decide_engine (feed ,ctx ,state ),"app" :decide_app (feed ,ctx )},now_control ) 1749except Exception :# noqa: BLE001 - only a hint for the app 1750pass 1751state .save () 1752return {"feed" : {"source" :ctx .source ,"sequence" :feed .sequence ,"channel" :feed .channel ,"key_id" :feed .key_id }, 1753"results" :results ,"exit_code" :failure .exit_code if failure else 0 }