okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aff3a132f
main
1"""The engine of one Qwen4 model shape, as its own component (feed member ``shape_engines``), picked by the model. 2 3An engine is compiled for ONE model geometry (``-DSTRATA_GEOMETRY=...``, cmake/strata_geometry.cmake) and refuses a GGUF of another one at load. The Strata engine is 4built for Flash-Next. A Qwen4 model of a different shape therefore ships with its own engine package, and that package never replaces the Strata engine: 5 6* name: the shape is the compiled geometry's name (``q4_lite``); its component is ``strata-q4-lite``; a feed model of that shape has the family ``qwen4exp_q4_lite``; 7* place: ``<components>/shapes/<shape>/engine/<version>-<platform>-<backend>[-<variant>]/``, beside the Strata engine's ``<components>/engine/`` and never inside it. The 8manifest's id is the shape's component (``strata-q4-lite``) and it carries ``"shape"``, so the Strata engine's scan never reads it and an older Control (which reads only 9``strata-engine``) refuses one that was copied into its engine folder; 10* feed: member ``shape_engines`` (the same entry as ``engine``, plus ``shape``). A Control from before this member ignores it, and ignores the models of those shapes too (their 11family is one it does not know); 12* use: the run config of a model of that shape says ``"exe": "component:strata-q4-lite"``. Every start asks ``engine_component.expand``, which resolves it in the shape's folder 13(checks every file's SHA-256 and the signature, as for the Strata engine). The Strata engine and every model that runs on it are not touched; 14* fetch: setup (the app's Download and the Terminal's launch) fetches the shape's engine through the signed feed when the model is chosen, as it does for DeepSeek's. An explicit 15`strata update` brings an installed shape engine up to date. Starting a model never downloads anything. 16 17Nothing in this module imports anything outside the standard library and ``strata_control`` at load time. 18""" 19from __future__import annotations 20 21import os 22import re 23import shutil 24from pathlib import Path 25from typing import Callable 26 27from strata_control import engine_component as ec 28 29DIR = "shapes" 30FAMILY_PREFIX = "qwen4exp_" 31SHAPE_RE = re .compile (r"[a-z][a-z0-9_]{1,21}[a-z0-9]" )# q4_lite, q4_mid: the geometry header's name (include/strata/core/geometries/<name>.hpp) 32#: component ids that already mean something else; a shape never becomes one of them 33RESERVED = frozenset ({"strata-engine" ,"strata-dsv41" ,"strata-control" ,"strata-vision" ,"strata-device" ,"strata-terminal" ,"strata-app" ,"strata-drafter" }) 34#: The reason, inside WORDS["start_failed"]'s "...did not start correctly ({why})", when a shape engine cannot say its shape (owner, 11-09) 35NO_SHAPE_ANSWER = "it does not say which model shape it was built for" 36KEEP_VERSIONS = 2 # the installed shape engine and the one before it 37#: What a person reads in the lines below where "{model}" stands: the model's title ("Q4 Lite Shape"), not the geometry's name (q4_lite). One switch: False puts the geometry 38#: name back everywhere (the owner decides; `strata components engine` and the JSON always name the shape). 39USE_TITLE = True 40 41# ---- the words a person can see: approved by the owner 11-08 ("A ok"), pinned by tests/terminal/test_shape_engine.py ApprovedWords. {model} is the model's title (see USE_TITLE). 42# Detail (reasons lists, platform-backend, folders) is in the result rows, the JSON and the log, never in these lines. 43WORDS = { 44"checking" :"Checking the engine for {model}\u2026" , 45"fetching" :"{model} needs its own engine. It downloads separately, and the Strata engine stays as it is." , 46"installed" :"Engine for {model} {version} ({backend}) is installed." , 47"ready" :"Engine for {model} {version} ({backend}) is installed." , 48"updated" :"Engine for {model} updated from {old} to {new}." , 49"not_in_feed" :"The update feed has no engine for {model} for this computer." , 50"start_failed" :"The engine for {model} {version} was not installed because it did not start correctly ({why}). The Strata engine is unchanged." , 51"fetch_failed" :"The engine for {model} could not be downloaded: {why}" , 52"newer_failed" :"A newer engine for {model} is available but could not be installed ({why}). Still using {have}." , 53"missing" : ("{model} needs its own engine, which is not installed or does not fit this PC: {reason}. Run `strata launch` again, or Download / repair in the app, " 54"to fetch it. Starting a model never downloads an engine." ), 55"current" :"The engine for {model} is up to date." , 56# setup.py (the [X] / [ok] marks are setup's) 57"setup_failed" :"the engine for {model} could not be installed" , 58"setup_failed_hint" :"See the line above. Nothing was downloaded for the model. Run this again when the update feed has it." , 59"setup_ok" :"engine for {model}: {version} in {folder}" , 60"setup_skip" :"no engine for {model} is installed: the model is downloaded and prepared now; set it up again when the engine can be fetched" , 61"update_label" :"Model engine" , 62} 63 64 65# ---------------------------------------------------------------------------------------------- names 66 67def shown (shape :str ,title :str | None = None )-> str : 68"""The name a person reads for the engine of `shape`: the model's title when there is one (and USE_TITLE), else the shape's name.""" 69return title .strip ()if USE_TITLE and isinstance (title ,str )and title .strip ()else shape 70 71 72def title_from_feed (feed ,shape :str )-> str | None : 73"""The title of the feed's model of `shape` (the first one), for a line of `strata update`, which does not know which model asked.""" 74for model in getattr (feed ,"models" , ())or (): 75if model .shape == shape and model .title : 76return model .title 77return None 78 79 80def valid (shape )-> bool : 81"""Is `shape` a name this Control accepts for a model shape?""" 82return isinstance (shape ,str )and bool (SHAPE_RE .fullmatch (shape ))and "__" not in shape and component_id (shape )not in RESERVED 83 84 85def component_id (shape :str )-> str : 86"""``q4_lite`` -> ``strata-q4-lite``.""" 87return "strata-" + str (shape ).replace ("_" ,"-" ) 88 89 90def shape_of_component (component :str )-> str | None : 91"""``strata-q4-lite`` -> ``q4_lite``; None for anything that is not a shape's component (``strata-engine`` included).""" 92if not isinstance (component ,str )or not component .startswith ("strata-" ): 93return None 94shape = component [len ("strata-" ):].replace ("-" ,"_" ) 95return shape if valid (shape )and component_id (shape )== component else None 96 97 98def family_of (shape :str )-> str : 99"""The feed model family of a shape: ``q4_lite`` -> ``qwen4exp_q4_lite`` (a family older Controls do not know, so they never offer the model).""" 100return FAMILY_PREFIX + shape 101 102 103def shape_of_family (family )-> str | None : 104"""``qwen4exp_q4_lite`` -> ``q4_lite``; None for ``qwen4exp`` and every other family.""" 105if not isinstance (family ,str )or not family .startswith (FAMILY_PREFIX ): 106return None 107shape = family [len (FAMILY_PREFIX ):] 108return shape if valid (shape )else None 109 110 111def reference (shape :str )-> str : 112"""The run config's ``exe`` for a model of this shape: ``component:strata-q4-lite``.""" 113return ec .REFERENCE_PREFIX + component_id (shape ) 114 115 116def exe_name ()-> str : 117return "strata.exe" if os .name == "nt" else "strata" 118 119 120# ---------------------------------------------------------------------------------------------- where, what is installed 121 122def shapes_dir (components :Path | None = None )-> Path : 123return (Path (components )if components else ec .components_dir ())/ DIR 124 125 126def root (shape :str ,components :Path | None = None )-> Path : 127"""The component folder of a shape (it holds ``engine/<package>/``, as the Strata engine's component folder does).""" 128if not valid (shape ): 129raise ValueError (f" { shape !r } is not a model shape name" ) 130return shapes_dir (components )/ shape 131 132 133def installed (shape :str ,components :Path | None = None )-> list [ec .EngineComponent ]: 134"""The engine packages of `shape` that can be read (nothing is hashed), oldest first.""" 135found ,_ = ec .scan (root (shape ,components ),component_id (shape )) 136return sorted (found ,key = lambda item : (ec ._version_key (item .version ),item .root .name )) 137 138 139def installed_shapes (components :Path | None = None )-> list [str ]: 140"""The shapes that have at least one readable engine package here.""" 141try : 142names = sorted (d .name for d in shapes_dir (components ).iterdir ()if d .is_dir ()and valid (d .name )) 143except OSError : 144return [] 145return [name for name in names if installed (name ,components )] 146 147 148def newest_version (shape :str ,components :Path | None = None )-> str | None : 149found = installed (shape ,components ) 150return found [- 1 ].version if found else None 151 152 153def find (shape :str ,components :Path | None = None ,* ,backend :str | None = None ,full :bool = False ,title :str | None = None )-> ec .EngineComponent : 154"""The engine of `shape` for this PC (`ShapeEngineMissing` / `EngineIntegrityError` when there is none that can start).""" 155try : 156return ec .resolve (root (shape ,components ),backend = backend ,full = full ,component_id = component_id (shape )) 157except ec .EngineIntegrityError : 158raise 159except ec .EngineMissing as exc : 160raise ShapeEngineMissing (shape ,exc .reason ,root (shape ,components ),problems = exc .problems ,title = title )from None 161 162 163class ShapeEngineMissing (ec .EngineMissing ): 164"""No usable engine of this model's shape on this PC. Nothing was fetched; the message says how to get it.""" 165 166code = "shape_engine_missing" 167 168def __init__ (self ,shape :str ,reason :str ,where :Path | None = None ,* ,problems :list | None = None ,title :str | None = None ): 169self .shape = shape 170self .reason = reason 171self .root = where 172self .problems = problems or [] 173self .plain_notice = None 174RuntimeError .__init__ (self ,WORDS ["missing" ].format (model = shown (shape ,title ),reason = reason )) 175self .what = f"the engine for { shown ( shape , title ) } " 176self .command = "strata launch" 177 178 179def status (components :Path | None = None )-> list [dict ]: 180"""The shape engines installed here, for `strata components engine` and the app: one row per shape with its packages. Empty when there are none (a PC that 181never had a model of another shape reports exactly what it did before).""" 182rows = [] 183for shape in installed_shapes (components ): 184row = {"shape" :shape ,"component" :component_id (shape ),"installed" : [item .to_dict ()for item in installed (shape ,components )],"usable" :False ,"engine" :None } 185try : 186chosen = find (shape ,components ) 187row ["engine" ],row ["usable" ]= chosen .to_dict (),True 188except ec .EngineMissing as exc : 189row ["notice" ]= str (exc ) 190rows .append (row ) 191return rows 192 193 194# ---------------------------------------------------------------------------------------------- fetching from the signed feed 195 196def _test_start (exe :Path ,timeout :float = 120.0 ,shape :str | None = None )-> tuple [bool ,str ]: 197"""The new engine starts: ``strata --version`` runs, loads its libraries and names itself (it needs no graphics card and no model). The package's own folders go on the 198library path first, as the start path does. With `shape`, ``strata --geometry`` (engine 0.2.13 and later) must name that shape: an engine compiled for another geometry than 199the signed manifest says is refused here, not at its first load, and so is one that cannot answer the flag (NO_SHAPE_ANSWER, owner 11-09).""" 200import subprocess 201env = dict (os .environ ) 202var = "PATH" if os .name == "nt" else "LD_LIBRARY_PATH" 203dirs = [d for d in ec .package_lib_dirs (Path (exe ).parent )if Path (d ).is_dir ()] 204if dirs : 205env [var ]= os .pathsep .join (dirs + ([env [var ]]if env .get (var )else [])) 206try : 207done = subprocess .run ([str (exe ),"--version" ],capture_output = True ,text = True ,errors = "replace" ,timeout = timeout ,cwd = str (Path (exe ).parent ),env = env ) 208except (OSError ,subprocess .SubprocessError )as exc : 209return False ,f"it could not be started ( { exc } )" 210first = ((done .stdout or "" ).strip ().splitlines ()or ["" ])[0 ] 211if done .returncode != 0 or not first .startswith ("strata" ): 212tail = ((done .stderr or "" ).strip ().splitlines ()or [first or f"exit { done . returncode } " ])[- 1 ] 213return False ,tail [:160 ] 214if shape : 215ok ,why = check_geometry (exe ,shape ,env ,timeout ) 216if not ok : 217return False ,why 218return True ,first 219 220 221def check_geometry (exe :Path ,shape :str ,env :dict | None = None ,timeout :float = 60.0 )-> tuple [bool ,str ]: 222"""Does ``strata --geometry`` name `shape`? (True, "") when it does; (False, plain reason) when it names another, or names none: every engine of a model shape is built 223after the flag existed (0.2.13, and the Intel engine since 0.2.14), so one that cannot say its shape is refused (owner, 11-09). The Strata engine is never asked.""" 224import subprocess 225try : 226done = subprocess .run ([str (exe ),"--geometry" ],capture_output = True ,text = True ,errors = "replace" ,timeout = timeout ,cwd = str (Path (exe ).parent ),env = env ) 227except (OSError ,subprocess .SubprocessError ): 228return False ,NO_SHAPE_ANSWER 229named = ((done .stdout or "" ).strip ().splitlines ()or ["" ])[0 ].strip () 230if done .returncode != 0 or not named or named .startswith ("strata" )or " " in named : 231return False ,NO_SHAPE_ANSWER # an engine that does not know the flag (or answers something else) 232if named != shape : 233return False ,f"it was built for a different model shape ( { named } )" 234return True ,"" 235 236 237def choose (feed ,shape :str ,hardware :dict ,title :str | None = None ): 238"""The feed's engine of `shape` that fits this PC: (package, reasons) as ``feed.select_engine``; package None when the feed has none for it.""" 239from strata_control import feed as feedmod 240mine = [p for p in feed .shape_engines if p .shape == shape ] 241if not mine : 242return None , [f"the feed lists no engine for { shown ( shape , title ) } " ] 243return feedmod .select_engine (mine ,hardware ) 244 245 246def _prune (shape_root :Path ,shape :str ,keep_name :str )-> list [str ]: 247"""Keep the newest `KEEP_VERSIONS` packages of the shape; remove the older ones unless a running engine uses them.""" 248from strata_control import folder_use ,longpath 249found ,_ = ec .scan (shape_root ,component_id (shape )) 250ordered = sorted (found ,key = lambda item : (ec ._version_key (item .version ),item .root .name ),reverse = True ) 251removed = [] 252for item in ordered [KEEP_VERSIONS :]: 253if item .root .name == keep_name or folder_use .in_use (item .root ): 254continue 255shutil .rmtree (longpath .long_path (item .root ),ignore_errors = True ) 256removed .append (item .root .name ) 257return removed 258 259 260def update_one (ctx ,feed ,shape :str ,* ,install_missing :bool = True ,title :str | None = None )-> dict : 261"""Bring the engine of `shape` up to the feed's: fetch the newest package that fits this PC (resumable download, archive SHA-256, the manifest hash the signed feed names, 262the package signature, every file's hash, the shape named in the manifest), put it NEXT TO the older ones, start it once (`--version`) and only then keep it. The Strata engine is 263never touched. `install_missing` False: nothing is done for a shape that has no engine installed yet (an explicit `strata update` only updates what is there). 264Returns the result row (``status``: installed, updated, current, none-installed, none-for-this-pc).""" 265from strata_control import feed as feedmod ,longpath ,updater 266comp = component_id (shape ) 267name = shown (shape ,title or title_from_feed (feed ,shape ))# what a person reads; `shape` and `comp` stay the keys 268have = newest_version (shape ,ctx .components ) 269result = {"component" :comp ,"shape" :shape ,"status" :"current" if have else "none-installed" ,"changed" :False ,"installed_before" :have } 270if not have and not install_missing : 271return result 272pkg ,reasons = choose (feed ,shape ,ctx .hardware ,title = name if name != shape else None ) 273if pkg is None : 274result .update (status = "none-for-this-pc" ,note = WORDS ["not_in_feed" ].format (model = name ),reasons = reasons ) 275return result 276if have and feedmod .version_key (pkg .version )<= feedmod .version_key (have ): 277result ["note" ]= WORDS ["current" ].format (model = name ) 278return result 279place = root (shape ,ctx .components ) 280updater ._free_space_check (place ,pkg .size + pkg .installed_bytes ,ctx ,pkg .sha256 ,comp ) 281archive = updater ._download (ctx ,comp ,pkg .url ,pkg .size ,pkg .sha256 ,f"the engine for { name } { pkg . version } " ,feed ) 282stage_root = None 283try : 284try : 285stage_root ,_staged = updater .stage_engine (ctx ,feed ,pkg ,archive ,component_id = comp ) 286except updater .UpdateError as exc : 287if exc .exit_code == 5 : 288archive .unlink (missing_ok = True )# a refused package is not kept for a retry 289raise 290folder = stage_root / "engine" / updater .folder_name (pkg ) 291target = ec .engine_dir (place )/ folder .name 292target .parent .mkdir (parents = True ,exist_ok = True ) 293if target .exists (): 294shutil .rmtree (longpath .long_path (target ),ignore_errors = True ) 295updater ._move_dir (folder ,target ) 296if os .name != "nt" : 297 (target / exe_name ()).chmod (0o755 ) 298ctx .say ("test" ,f"Test-starting the engine for { name } { pkg . version } " ,component = comp ) 299ok ,why = _test_start (target / exe_name (),shape = shape ) 300if not ok : 301shutil .rmtree (longpath .long_path (target ),ignore_errors = True )# (never an older one) 302refused = updater .UpdateError (WORDS ["start_failed" ].format (model = name ,version = pkg .version ,why = why ),6 ) 303refused .refused_why = why # ensure() says the approved line as it is (never inside another line) 304raise refused 305removed = _prune (place ,shape ,target .name ) 306archive .unlink (missing_ok = True ) 307result .update (status = "updated" if have else "installed" ,changed = True ,installed_after = pkg .version ,folder = target .name ,removed = removed , 308note = (WORDS ["updated" ].format (model = name ,old = have ,new = pkg .version )if have 309else WORDS ["installed" ].format (model = name ,version = pkg .version ,backend = pkg .backend ))) 310return result 311finally : 312if stage_root is not None : 313shutil .rmtree (longpath .long_path (stage_root ),ignore_errors = True ) 314 315 316def ensure (shape :str ,source :str ,* ,components :Path | None = None ,hardware :dict | None = None ,emit :Callable [[str ],None ]= cancel = None , 317quiet_when_current :bool = True ,title :str | None = None ,automatic :bool = False )-> Path | None : 318"""The engine of `shape` is installed and up to date, from the signed feed at `source` (a URL or a folder). Returns its program, or None with one plain line through `emit` when 319there is none (not in the feed, nothing for this PC, the feed cannot be read). A newer package is fetched only when the feed can be read; an installed one keeps running when it 320cannot. This is what setup and `strata launch` call when a model of that shape is chosen. `automatic` (`strata launch`): with an engine installed, 321the check for a newer one is a read nobody asked for, so a feed host that refused within the last hours is not asked again (netpolicy rule 4b); 322without one the feed is always read.""" 323from strata_control import acquisition ,feed as feedmod ,signing ,updater 324components = Path (components )if components else ec .components_dir () 325hw = hardware or updater .detect_hardware () 326have = newest_version (shape ,components ) 327name = shown (shape ,title ) 328if not have : 329emit (WORDS ["fetching" ].format (model = name )) 330ctx = updater .Context (components = components ,source = source ,trusted = signing .load_trusted_keys (),hardware = hw ,cancel = cancel , 331feed_timeout = 5.0 if have else 30.0 ,# an installed engine: a launch must not wait long for a feed that is not there 332automatic = bool (automatic and have ), 333emit = lambda event :emit (event ["message" ])if event .get ("event" )== "phase" and event .get ("message" )and event .get ("phase" )!= "feed" else None ) 334try : 335with updater .update_lock (components ): 336state = updater .State (components ) 337try : 338feed = updater .open_feed (ctx ,state ) 339except feedmod .FeedError as exc : 340if have :# offline with an engine installed: the engine runs, nothing to say 341return find (shape ,components ,full = False ,title = title ).exe 342emit (WORDS ["fetch_failed" ].format (model = name ,why = exc )) 343return None 344state .save () 345result = update_one (ctx ,feed ,shape ,title = title ) 346state .save () 347except Exception as exc :# noqa: BLE001 - with an engine installed, a check for a newer one never stops a launch 348if not isinstance (exc , (updater .UpdateError ,feedmod .FeedError ,signing .SignatureError ,acquisition .AcquisitionRefused ,OSError ))and not have : 349raise 350if have : 351if isinstance (exc , (updater .UpdateError ,signing .SignatureError )):# the feed was read and the newer package was refused or did not start: said, the old one runs 352emit (WORDS ["newer_failed" ].format (model = name ,why = getattr (exc ,"refused_why" ,None )or str (exc ).rstrip ("." ),have = have )) 353try : 354return find (shape ,components ,full = False ,title = title ).exe 355except ec .EngineMissing : 356pass 357emit (str (exc )if getattr (exc ,"refused_why" ,None )else WORDS ["fetch_failed" ].format (model = name ,why = str (exc ).rstrip ("." ))) 358return None 359if result ["status" ]== "none-for-this-pc" : 360emit (result ["note" ]) 361return None 362if result .get ("changed" )or not quiet_when_current : 363emit (result .get ("note" )or WORDS ["ready" ].format (model = name ,version = newest_version (shape ,components ),backend = "" )) 364try : 365return find (shape ,components ,full = False ,title = title ).exe 366except ec .EngineMissing as exc : 367emit (str (exc )) 368return None