okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aff3a132f
main
1"""The signed update feed: what is published, how it is checked, which engine package fits a PC. 2 3One small document, ``strata-feed.json``, with a detached Ed25519 signature ``strata-feed.json.sig`` (the signature covers the 4file's exact bytes, so there is no canonicalisation to get wrong). It lists, for one channel: 5 6* ``app``: the desktop app, in exactly the shape of Tauri's static updater JSON (``version``, ``notes``, ``pub_date``, 7``platforms{<tauri target>: {url, signature}}``), plus ``sha256`` and ``size`` per platform. The Tauri updater plugin 8reads a copy of this member at ``app/latest.json`` and checks the minisign signature itself; 9* ``control``: the runtime component (Control: bundled Python, ``strata_control``, the CLI and server), one archive per platform; 10* ``engine``: the engine packages, one entry per platform / backend / variant, each with ``version``, ``archs``, 11``min_driver``, ``min_runtime``, ``size``, ``sha256`` of the archive, ``manifest_sha256`` of the package's 12``engine-component.json`` (which holds every file's hash) and a URL. 13 14The feed's signature plus those hashes is the whole chain of trust: a package whose archive hash or manifest hash is not the 15one in the signed feed is never installed. Three refusals are tested: a bad signature, a bad hash and a downgrade. The 16downgrade guard has two parts: a feed whose ``sequence`` is lower than the last one this PC accepted is refused (a replayed 17old feed), and a package older than the installed one is never installed by an update. 18 19Nothing here touches the network itself; `strata_control.transfer` does. 20""" 21 22from __future__import annotations 23 24import dataclasses 25import datetime as dt 26import json 27import logging 28import re 29from dataclasses import dataclass ,field 30 31from strata_control import netpolicy ,shape_engine ,signing ,transfer 32from strata_control .targets import BACKEND_MATRIX ,host_platform 33 34SCHEMA_VERSION = 1 35FEED_NAME = "strata-feed.json" 36#: The Linux ARM64 (DGX Spark) Terminal reads this file instead. A Control older than 0.1.53 refuses a feed that names a platform it does not know, so 37#: the linux-aarch64 entries cannot sit in strata-feed.json: that file stays as every released client can read it. Same format, same key. 38AARCH64_FEED_NAME = "strata-feed-linux-aarch64.json" 39SIGNATURE_SUFFIX = ".sig" 40FORMATS = ("tar.gz" ,"tar.xz" ,"zip" ) 41PLATFORMS = ("windows-x86_64" ,"linux-x86_64" ,"linux-aarch64" ,"macos-arm64" ,"macos-x86_64" ) 42#: Tauri's names for the same platforms (no desktop app is built for linux-aarch64: the entry only keeps the name parsable). 43TAURI_TARGETS = {"windows-x86_64" :"windows-x86_64" ,"linux-x86_64" :"linux-x86_64" ,"linux-aarch64" :"linux-aarch64" , 44"macos-arm64" :"darwin-aarch64" ,"macos-x86_64" :"darwin-x86_64" } 45_VERSION = re .compile (r"\d+\.\d+\.\d+(?:\.\d+)?" ) 46_HEX64 = re .compile (r"[0-9a-f]{64}" ) 47_log = logging .getLogger ("strata.feed" ) 48 49 50class FeedError (RuntimeError ): 51"""The feed or something it lists cannot be trusted or used. `exit_code` is the CLI's.""" 52 53def __init__ (self ,message :str ,exit_code :int = 5 ): 54super ().__init__ (message ) 55self .exit_code = exit_code 56 57 58class FeedUnreachable (FeedError ): 59"""The feed's host did not answer, or this computer is offline (strata_control/netpolicy.py's words): a check that runs by itself stays silent.""" 60 61 62class FeedDowngrade (FeedError ): 63"""A feed or a package older than what this PC already has.""" 64# .sequence is the feed's, .accepted the last one this PC took (the updater adds the folder that holds it) 65sequence :int | None = None 66accepted :int | None = None 67 68 69def version_key (value :str )-> tuple [int , ...]: 70if not isinstance (value ,str )or not _VERSION .fullmatch (value ): 71raise FeedError (f" { value !r } is not a version number (expected like 0.1.46 or 0.1.46.1)" ) 72parts = [int (p )for p in value .split ("." )] 73return tuple (parts + [0 ]* (4 - len (parts ))) 74 75 76def app_version_key (value :str )-> tuple [int , ...]: 77"""Compare the INSTALLED app's version: like `version_key`, but a pre-release (0.2.0-beta) is allowed and sorts below the same number without 78the suffix. The feed's own versions stay strict (`version_key`).""" 79base ,dash ,pre = str (value ).partition ("-" ) 80if dash and not re .fullmatch (r"[0-9A-Za-z.]+" ,pre ): 81raise FeedError (f" { value !r } is not a version number (expected like 0.2.0 or 0.2.0-beta)" ) 82return version_key (base )+ (0 if dash else 1 ,) 83 84 85def _need (obj :dict ,key :str ,kind ,where :str ): 86value = obj .get (key ) 87if not isinstance (value ,kind )or isinstance (value ,bool )and kind is int : 88raise FeedError (f"the feed's { where } has no valid { key } " ) 89return value 90 91 92def _hex (value ,where :str )-> str : 93if not isinstance (value ,str )or not _HEX64 .fullmatch (value .lower ()): 94raise FeedError (f"the feed's { where } has no valid sha256" ) 95return value .lower () 96 97 98@dataclass( frozen = True ) 99class EnginePackage : 100version :str 101platform :str 102backend :str 103variant :str 104archs :tuple [str , ...] 105min_driver :dict 106min_runtime :str | None 107build_id :str 108url :str 109format :str 110size :int 111sha256 :str 112manifest_sha256 :str 113installed_bytes :int 114notes :str = "" 115shape :str = "" # the engine of one model shape (feed member ``shape_engines``, strata_control/shape_engine.py): its compiled geometry's name; "" for the others 116 117@property 118def label (self )-> str : 119return f" { self . version } { self . platform } - { self . backend } " + (f"- { self . variant } " if self .variant else "" ) 120 121def to_dict (self )-> dict : 122return {"version" :self .version ,"platform" :self .platform ,"backend" :self .backend ,"variant" :self .variant , 123"archs" :list (self .archs ),"min_driver" :dict (self .min_driver ),"min_runtime" :self .min_runtime , 124"build_id" :self .build_id ,"size" :self .size ,"installed_bytes" :self .installed_bytes , 125"format" :self .format ,"url" :self .url ,"sha256" :self .sha256 ,"manifest_sha256" :self .manifest_sha256 , 126** ({"shape" :self .shape }if self .shape else {})} 127 128 129@dataclass( frozen = True ) 130class DrafterPackage : 131"""A DFlash2 drafter file Strata hosts (feed member ``drafters``): one pinned file, not an archive. ``backends`` are the engine families it was measured on 132(``metal``); ``url`` is relative to the feed (flat release assets) or an https address; ``size`` and ``sha256`` are the file's. The code that fetches it 133pins the same size and SHA-256 (strata_control/drafting.py), so the feed can move the file but never swap its bytes.""" 134name :str 135version :str 136url :str 137size :int 138sha256 :str 139backends :tuple [str , ...] 140base :str = "" 141licence :str = "" 142notes :str = "" 143 144@property 145def label (self )-> str : 146return f"drafter { self . name } { self . version } " 147 148def to_dict (self )-> dict : 149return {"name" :self .name ,"version" :self .version ,"url" :self .url ,"size" :self .size ,"sha256" :self .sha256 , 150"backends" :list (self .backends ),"base" :self .base ,"licence" :self .licence ,"notes" :self .notes } 151 152 153#: Families a ``models`` entry may name that this Control knows how to install (GGUF architectures the engine runs: ``strata --families``). A model of another family 154#: is still listed, as "not available on this engine"; it is never offered to install. 155MODEL_FAMILIES_INSTALLABLE = ("qwen4exp" ,"qwen35moe" ) 156_MODEL_ID = re .compile (r"[a-z0-9][a-z0-9.-]{1,39}" ) 157_MODEL_FAMILY = re .compile (r"[a-z0-9_]{2,32}" ) 158_MODEL_REPO = re .compile (r"[A-Za-z0-9][A-Za-z0-9._-]{0,95}/[A-Za-z0-9][A-Za-z0-9._-]{0,95}" ) 159_MODEL_REVISION = re .compile (r"[0-9a-f]{40}" ) 160_MODEL_QUANT = re .compile (r"[A-Za-z0-9][A-Za-z0-9._-]{0,31}" ) 161MODEL_DRAFTERS = ("mtp" ,"none" ) 162 163 164@dataclass( frozen = True ) 165class ModelFile : 166"""One pinned file of a feed model: ``path`` is its place in the Hugging Face repository (``name`` when it sits at the top), ``size`` and ``sha256`` are its exact bytes.""" 167name :str 168size :int 169sha256 :str 170path :str = "" 171 172@property 173def repo_path (self )-> str : 174return self .path or self .name 175 176def to_dict (self )-> dict : 177out = {"name" :self .name ,"size" :self .size ,"sha256" :self .sha256 } 178if self .path : 179out ["path" ]= self .path 180return out 181 182 183@dataclass( frozen = True ) 184class ModelQuant : 185"""One size of a feed model: the files that make it, and the setup recommendation for it (``ram_gb`` the memory it wants; ``arena_gb`` the experts' share, 0: not given).""" 186name :str 187about :str 188ram_gb :float 189arena_gb :float 190files :tuple [ModelFile , ...] 191 192@property 193def download_bytes (self )-> int : 194return sum (f .size for f in self .files ) 195 196def to_dict (self )-> dict : 197return {"name" :self .name ,"about" :self .about ,"ram_gb" :self .ram_gb ,"arena_gb" :self .arena_gb ,"files" : [f .to_dict ()for f in self .files ]} 198 199 200@dataclass( frozen = True ) 201class FeedModel : 202"""A model Strata lists after the built-in ones (feed member ``models``). Everything setup needs to install it is here and signed: the repository and the pinned revision, 203each file's exact size and SHA-256 (setup checks them after the download, and a wrong file is kept as ``.bad``, exactly as for a built-in model), the engine family, 204the licence and the first engine version that reads it.""" 205id :str 206title :str 207by :str 208about :str 209licence :str 210licence_url :str 211family :str 212repo :str 213revision :str 214quants :tuple [ModelQuant , ...] 215mmproj :ModelFile | None = None 216pictures :bool = False 217drafter :str = "none" 218context :int = 0 219min_engine :str = "" 220kv_bytes_per_token :int = 0 221mtp_drafts :int = 0 222state_gb :float = 0.0 223 224@property 225def label (self )-> str : 226return f"model { self . id } " 227 228@property 229def shape (self )-> str | None : 230"""The model shape whose own engine runs it (``q4_lite``), or None: it runs on the Strata engine.""" 231return shape_engine .shape_of_family (self .family ) 232 233def to_dict (self )-> dict : 234out = {"id" :self .id ,"title" :self .title ,"by" :self .by ,"about" :self .about ,"licence" :self .licence ,"licence_url" :self .licence_url , 235"family" :self .family ,"repo" :self .repo ,"revision" :self .revision ,"quants" : [q .to_dict ()for q in self .quants ], 236"pictures" :self .pictures ,"drafter" :self .drafter ,"context" :self .context ,"min_engine" :self .min_engine } 237if self .mmproj : 238out ["mmproj" ]= self .mmproj .to_dict () 239if self .kv_bytes_per_token : 240out ["kv_bytes_per_token" ]= self .kv_bytes_per_token 241if self .mtp_drafts : 242out ["mtp_drafts" ]= self .mtp_drafts 243if self .state_gb : 244out ["state_gb" ]= self .state_gb 245return out 246 247 248@dataclass( frozen = True ) 249class ControlPackage : 250version :str 251platform :str 252url :str 253format :str 254size :int 255sha256 :str 256installed_bytes :int 257entry :str = "strata.py" 258 259@property 260def label (self )-> str : 261return f"control { self . version } { self . platform } " 262 263 264@dataclass( frozen = True ) 265class AppRelease : 266version :str 267notes :str 268pub_date :str 269platforms :dict # {platform: {"url", "signature", "sha256", "size", "format"?}} 270 271def for_platform (self ,platform :str )-> dict | None : 272return self .platforms .get (platform ) 273 274 275@dataclass 276class Feed : 277sequence :int 278channel :str 279generated_at :str 280expires_at :str | None 281app :AppRelease | None 282control :tuple [ControlPackage , ...] 283engine :tuple [EnginePackage , ...] 284source :str # where it was read from (the base for relative URLs) 285key_id :str # who signed it 286raw :bytes = field (default = b"" ,repr = False ) 287#: entries this Control does not know how to use (a platform, a backend or an archive format added after it was built): left out, one plain line each. 288#: A feed with such an entry is still a feed; only an entry of a kind this Control knows and that is malformed refuses the feed. 289skipped :tuple [str , ...]= () 290#: the DFlash2 drafter files (feed member ``drafters``, DrafterPackage): fetched by setup, `strata drafting fetch` and Load for a set that has one. Older Controls ignore the member. 291drafters :tuple [DrafterPackage , ...]= () 292#: the models Strata lists after the built-in ones (feed member ``models``, FeedModel). An entry that is malformed is left out of this tuple with one plain line in 293#: ``models_dropped`` (and the log); the rest of the feed, and the other models, work. Older Controls ignore the member. 294models :tuple [FeedModel , ...]= () 295models_dropped :tuple [str , ...]= () 296#: the detached signature that went with ``raw`` (fetch fills it for a feed that has models: the cache of the model list keeps both) 297signature :bytes = b"" 298#: the engines of model shapes (feed member ``shape_engines``, EnginePackage with ``shape``): a separate component for each shape, fetched when a model of that shape is 299#: chosen (strata_control/shape_engine.py). Kept out of ``engine`` so that `strata update` never picks one as THE engine. Older Controls ignore the member. 300shape_engines :tuple [EnginePackage , ...]= () 301 302def url (self ,ref :str )-> str : 303return transfer .resolve_ref (transfer .base_of (self .source ),ref ) 304 305 306# ---------------------------------------------------------------------------------------------- parsing 307 308def _time (value ,what :str )-> dt .datetime : 309try : 310parsed = dt .datetime .fromisoformat (str (value ).replace ("Z" ,"+00:00" )) 311except ValueError : 312raise FeedError (f"the feed's { what } is not a timestamp" )from None 313return parsed if parsed .tzinfo else parsed .replace (tzinfo = dt .timezone .utc ) 314 315 316def _skipping (skipped :list | None ,what :str ,reason :str )-> None : 317if skipped is None :# a caller that wants the strict reading 318raise FeedError (f"the update feed lists { what } , { reason } " ) 319skipped .append (f"The update feed lists { what } , { reason } : skipped (a newer Strata may use it)." ) 320 321 322def _engine_package (item :dict ,skipped :list | None = None )-> EnginePackage | None : 323if not isinstance (item ,dict ): 324raise FeedError ("an engine entry in the feed is not an object" ) 325where = f"engine entry { item . get ( 'version' )!r } " 326version = _need (item ,"version" ,str ,where ) 327version_key (version ) 328platform = _need (item ,"platform" ,str ,where ) 329backend = _need (item ,"backend" ,str ,where ) 330label = f" { version } { platform } - { backend } " + (f"- { item [ 'variant' ] } " if item .get ("variant" )else "" ) 331if platform not in PLATFORMS : 332_skipping (skipped ,f"engine { label } " ,f"for a platform this Strata does not know ( { platform } )" ) 333return None 334if backend not in BACKEND_MATRIX : 335_skipping (skipped ,f"engine { label } " ,f"for a backend this Strata does not know ( { backend } )" ) 336return None 337archs = item .get ("archs" ) 338if not isinstance (archs ,list )or not all (isinstance (a ,str )and a for a in archs )or (backend != "cpu" and not archs ): 339raise FeedError (f"the feed's { where } needs a list of archs" ) 340driver = item .get ("min_driver" )or {} 341if not isinstance (driver ,dict )or not all (isinstance (k ,str )and isinstance (v ,str )for k ,v in driver .items ()): 342raise FeedError (f"the feed's { where } has an invalid min_driver" ) 343fmt = _need (item ,"format" ,str ,where ) 344if fmt not in FORMATS : 345_skipping (skipped ,f"engine { label } " ,f"in an archive format this Strata does not know ( { fmt } )" ) 346return None 347size = _need (item ,"size" ,int ,where ) 348installed = _need (item ,"installed_bytes" ,int ,where ) 349if size <= 0 or installed <= 0 : 350raise FeedError (f"the feed's { where } declares a size that cannot be a real file" ) 351runtime = item .get ("min_runtime" ) 352if runtime is not None : 353version_key (runtime ) 354return EnginePackage (version = version ,platform = platform ,backend = backend ,variant = str (item .get ("variant" )or "" ), 355archs = tuple (archs ),min_driver = dict (driver ),min_runtime = runtime , 356build_id = _need (item ,"build_id" ,str ,where ),url = _need (item ,"url" ,str ,where ),format = fmt , 357size = size ,sha256 = _hex (item .get ("sha256" ),where ), 358manifest_sha256 = _hex (item .get ("manifest_sha256" ),where ),installed_bytes = installed , 359notes = str (item .get ("notes" )or "" )) 360 361 362def _shape_engine_package (item :dict ,skipped :list | None = None )-> EnginePackage | None : 363"""An entry of ``shape_engines``: an engine entry that names its model shape. An entry whose shape is not a name this Control accepts is left out like any entry of a kind it 364does not know (a newer Strata may use it).""" 365if not isinstance (item ,dict ): 366raise FeedError ("a shape engine entry in the feed is not an object" ) 367shape = item .get ("shape" ) 368if not shape_engine .valid (shape ): 369_skipping (skipped ,f"an engine for the model shape { shape !r } " ,"a shape name this Strata does not accept" ) 370return None 371pkg = _engine_package (item ,skipped ) 372return dataclasses .replace (pkg ,shape = shape )if pkg is not None else None 373 374 375def _control_package (item :dict ,version :str ,skipped :list | None = None )-> ControlPackage | None : 376where = "control entry" 377platform = _need (item ,"platform" ,str ,where ) 378if platform not in PLATFORMS : 379_skipping (skipped ,f"Control { version } { platform } " ,"for a platform this Strata does not know" ) 380return None 381fmt = _need (item ,"format" ,str ,where ) 382if fmt not in FORMATS : 383_skipping (skipped ,f"Control { version } { platform } " ,f"in an archive format this Strata does not know ( { fmt } )" ) 384return None 385size ,installed = _need (item ,"size" ,int ,where ),_need (item ,"installed_bytes" ,int ,where ) 386if size <= 0 or installed <= 0 : 387raise FeedError ("the feed's control entry declares a size that cannot be a real file" ) 388return ControlPackage (version = version ,platform = platform ,url = _need (item ,"url" ,str ,where ),format = fmt , 389size = size ,sha256 = _hex (item .get ("sha256" ),where ),installed_bytes = installed , 390entry = str (item .get ("entry" )or "strata.py" )) 391 392 393def _drafter_package (item :dict )-> DrafterPackage : 394if not isinstance (item ,dict ): 395raise FeedError ("a drafter entry in the feed is not an object" ) 396where = f"drafter entry { item . get ( 'name' )!r } " 397name = _need (item ,"name" ,str ,where ) 398if "/" in name or "\\" in name or name .startswith ("." ): 399raise FeedError (f"the feed's { where } has a name that is not a plain file name" ) 400size = _need (item ,"size" ,int ,where ) 401if size <= 0 : 402raise FeedError (f"the feed's { where } declares a size that cannot be a real file" ) 403backends = item .get ("backends" ) 404if not isinstance (backends ,list )or not backends or not all (isinstance (b ,str )and b for b in backends ): 405raise FeedError (f"the feed's { where } needs a list of backends" ) 406return DrafterPackage (name = name ,version = str (item .get ("version" )or "" ),url = _need (item ,"url" ,str ,where ),size = size , 407sha256 = _hex (item .get ("sha256" ),where ),backends = tuple (backends ),base = str (item .get ("base" )or "" ), 408licence = str (item .get ("licence" )or "" ),notes = str (item .get ("notes" )or "" )) 409 410 411def _model_text (item :dict ,key :str ,where :str ,* ,limit :int = 400 ,required :bool = True )-> str : 412value = item .get (key ) 413if value is None and not required : 414return "" 415if not isinstance (value ,str )or (required and not value .strip ())or len (value )> limit or any (ord (c )< 32 for c in value ): 416raise FeedError (f" { where } has no valid { key } " ) 417return value .strip () 418 419 420def _model_file (item ,where :str )-> ModelFile : 421if not isinstance (item ,dict ): 422raise FeedError (f" { where } lists a file that is not an object" ) 423name = _need (item ,"name" ,str ,where ) 424if "/" in name or "\\" in name or name .startswith ("." )or not name .lower ().endswith (".gguf" ): 425raise FeedError (f" { where } has a file name that is not a plain .gguf name" ) 426size = _need (item ,"size" ,int ,where ) 427if size <= 0 : 428raise FeedError (f" { where } declares a size that cannot be a real file" ) 429path = item .get ("path" ) 430if path is not None : 431if not isinstance (path ,str )or not path or path .startswith (("/" ,"." ))or "\\" in path or ".." in path .split ("/" )or path .rsplit ("/" ,1 )[- 1 ]!= name : 432raise FeedError (f" { where } has a file path that does not end in the file's name" ) 433return ModelFile (name = name ,size = size ,sha256 = _hex (item .get ("sha256" ),where ),path = path or "" ) 434 435 436def _number (value ,low :float ,high :float )-> bool : 437return isinstance (value , (int ,float ))and not isinstance (value ,bool )and low <= value <= high 438 439 440def _model_entry (item )-> FeedModel : 441"""One ``models`` entry, strictly: any fault raises FeedError (the caller drops that entry and goes on with the next).""" 442if not isinstance (item ,dict ): 443raise FeedError ("a model entry in the feed is not an object" ) 444ident = item .get ("id" ) 445where = f"model entry { ident !r } " 446if not isinstance (ident ,str )or not _MODEL_ID .fullmatch (ident )or ident .endswith (("-" ,"." )): 447raise FeedError (f"the feed's { where } has no valid id" ) 448family = _need (item ,"family" ,str ,where ) 449if not _MODEL_FAMILY .fullmatch (family ): 450raise FeedError (f"the feed's { where } has no valid family" ) 451if family .startswith (shape_engine .FAMILY_PREFIX )and shape_engine .shape_of_family (family )is None : 452raise FeedError (f"the feed's { where } names a model shape that is not a valid name ( { family [ len ( shape_engine . FAMILY_PREFIX ):]!r } )" ) 453repo = _need (item ,"repo" ,str ,where ) 454revision = _need (item ,"revision" ,str ,where ) 455if not _MODEL_REPO .fullmatch (repo )or ".." in repo : 456raise FeedError (f"the feed's { where } has no valid repo" ) 457if not _MODEL_REVISION .fullmatch (revision ): 458raise FeedError (f"the feed's { where } needs the repository's pinned revision (40 hex digits)" ) 459licence_url = _need (item ,"licence_url" ,str ,where ) 460if not licence_url .startswith ("https://" )or any (c .isspace ()for c in licence_url ): 461raise FeedError (f"the feed's { where } needs an https licence_url" ) 462drafter = item .get ("drafter" ,"none" ) 463if drafter not in MODEL_DRAFTERS : 464raise FeedError (f"the feed's { where } has an unknown drafter { drafter !r } " ) 465context = item .get ("context" ,0 ) 466if not isinstance (context ,int )or isinstance (context ,bool )or context < 0 or context > 4194304 : 467raise FeedError (f"the feed's { where } has no valid context" ) 468min_engine = item .get ("min_engine" ,"" ) 469if min_engine : 470version_key (min_engine ) 471pictures = item .get ("pictures" ,False ) 472if not isinstance (pictures ,bool ): 473raise FeedError (f"the feed's { where } has no valid pictures flag" ) 474mmproj = _model_file (item ["mmproj" ],f"the feed's { where } " )if item .get ("mmproj" )is not None else None 475if pictures and mmproj is None : 476raise FeedError (f"the feed's { where } offers pictures but lists no mmproj file" ) 477raw_quants = item .get ("quants" ) 478if not isinstance (raw_quants ,list )or not raw_quants : 479raise FeedError (f"the feed's { where } lists no quants" ) 480quants ,seen_q ,seen_f = [],set (),set () 481for q in raw_quants : 482if not isinstance (q ,dict ): 483raise FeedError (f"the feed's { where } has a quant that is not an object" ) 484qname = q .get ("name" ) 485if not isinstance (qname ,str )or not _MODEL_QUANT .fullmatch (qname )or qname in seen_q : 486raise FeedError (f"the feed's { where } has a quant without a valid, unique name" ) 487seen_q .add (qname ) 488qwhere = f"the feed's { where } quant { qname !r } " 489files = q .get ("files" ) 490if not isinstance (files ,list )or not files : 491raise FeedError (f" { qwhere } lists no files" ) 492parsed = tuple (_model_file (f ,qwhere )for f in files ) 493if len ({f .name for f in parsed })!= len (parsed ): 494raise FeedError (f" { qwhere } lists a file twice" ) 495for f in parsed : 496if f .name in seen_f : 497raise FeedError (f" { qwhere } reuses the file name { f . name !r } of another quant" ) 498seen_f .add (f .name ) 499if not _number (q .get ("ram_gb" ),0.001 ,4096 )or not _number (q .get ("arena_gb" ,0 ),0 ,4096 ): 500raise FeedError (f" { qwhere } has no valid ram_gb or arena_gb" ) 501quants .append (ModelQuant (name = qname ,about = _model_text (q ,"about" ,qwhere ,required = False ),ram_gb = float (q ["ram_gb" ]), 502arena_gb = float (q .get ("arena_gb" ,0 )),files = parsed )) 503if mmproj is not None and mmproj .name in seen_f : 504raise FeedError (f"the feed's { where } uses the mmproj file name for a model file" ) 505kv = item .get ("kv_bytes_per_token" ,0 ) 506drafts = item .get ("mtp_drafts" ,2 if drafter == "mtp" else 0 ) 507state = item .get ("state_gb" ,0 ) 508if not isinstance (kv ,int )or isinstance (kv ,bool )or kv < 0 or not isinstance (drafts ,int )or isinstance (drafts ,bool )or not 0 <= drafts <= 8 \ 509or not _number (state ,0 ,64 ): 510raise FeedError (f"the feed's { where } has an invalid kv_bytes_per_token, mtp_drafts or state_gb" ) 511if family == "qwen35moe" and kv <= 0 : 512raise FeedError (f"the feed's { where } (family qwen35moe) needs kv_bytes_per_token" ) 513here = f"the feed's { where } " 514return FeedModel (id = ident ,title = _model_text (item ,"title" ,here ,limit = 80 ),by = _model_text (item ,"by" ,here ,limit = 160 ), 515about = _model_text (item ,"about" ,here ,limit = 400 ,required = False ), 516licence = _model_text (item ,"licence" ,here ,limit = 120 ),licence_url = licence_url ,family = family ,repo = repo , 517revision = revision ,quants = tuple (quants ),mmproj = mmproj ,pictures = pictures ,drafter = drafter ,context = context ,min_engine = min_engine , 518kv_bytes_per_token = kv ,mtp_drafts = drafts ,state_gb = float (state )) 519 520 521def _models_member (raw )-> tuple [list [FeedModel ],list [str ]]: 522"""The ``models`` member, leniently by entry: (the models that are well-formed, one plain line for each entry left out). A member that is not the 523expected shape is ignored whole, with a line. Nothing here refuses the feed.""" 524dropped :list [str ]= [] 525if raw is None : 526return [],dropped 527if not isinstance (raw ,dict )or not isinstance (raw .get ("packages" ),list ): 528dropped .append ("The update feed's models member is not a list of models: ignored." ) 529_log .warning (dropped [- 1 ]) 530return [],dropped 531out :list [FeedModel ]= [] 532for item in raw ["packages" ]: 533try : 534model = _model_entry (item ) 535except FeedError as exc : 536label = item .get ("id" )if isinstance (item ,dict )else None 537dropped .append (f"The update feed lists a model ( { label !r } ) that is not well-formed, so it is skipped: { exc } " ) 538_log .warning (dropped [- 1 ]) 539continue 540if any (m .id == model .id for m in out ): 541dropped .append (f"The update feed lists the model { model . id !r } twice: the second one is skipped." ) 542_log .warning (dropped [- 1 ]) 543continue 544out .append (model ) 545return out ,dropped 546 547 548def parse (payload :bytes ,* ,source :str ,key_id :str )-> Feed : 549"""The feed document, strictly. Unknown members are ignored; missing or mistyped ones are errors.""" 550try : 551data = json .loads (payload .decode ("utf-8-sig" )) 552except (ValueError ,UnicodeError ): 553raise FeedError ("the update feed is not valid JSON" )from None 554if not isinstance (data ,dict )or data .get ("schema_version" )!= SCHEMA_VERSION : 555raise FeedError ("the update feed has an unsupported schema_version" ) 556sequence = data .get ("sequence" ) 557if type (sequence )is not int or sequence < 0 : 558raise FeedError ("the update feed has no sequence number" ) 559channel = _need (data ,"channel" ,str ,"header" ) 560generated = _need (data ,"generated_at" ,str ,"header" ) 561_time (generated ,"generated_at" ) 562expires = data .get ("expires_at" ) 563if expires is not None : 564_time (expires ,"expires_at" ) 565skipped :list = [] 566app = None 567raw_app = data .get ("app" ) 568if raw_app is not None : 569if not isinstance (raw_app ,dict ): 570raise FeedError ("the feed's app member is not an object" ) 571app_version_key (_need (raw_app ,"version" ,str ,"app entry" )) 572platforms = raw_app .get ("platforms" ) 573if not isinstance (platforms ,dict )or not platforms : 574raise FeedError ("the feed's app entry lists no platforms" ) 575parsed_platforms = {} 576by_tauri = {v :k for k ,v in TAURI_TARGETS .items ()} 577for target ,entry in platforms .items (): 578plat = by_tauri .get (str (target ).split ("-nsis" )[0 ].split ("-msi" )[0 ]) 579if plat is None : 580_skipping (skipped ,f"the app for { target } " ,"a platform this Strata does not know" ) 581continue 582if not isinstance (entry ,dict ): 583raise FeedError (f"the feed's app entry for { target !r } is not an object" ) 584parsed_platforms [plat ]= {"url" :_need (entry ,"url" ,str ,"app entry" ), 585"signature" :_need (entry ,"signature" ,str ,"app entry" ), 586"sha256" :_hex (entry .get ("sha256" ),"app entry" ), 587"size" :_need (entry ,"size" ,int ,"app entry" ),"target" :target } 588app = AppRelease (version = raw_app ["version" ],notes = str (raw_app .get ("notes" )or "" ), 589pub_date = str (raw_app .get ("pub_date" )or "" ),platforms = parsed_platforms ) 590control = [] 591raw_control = data .get ("control" ) 592if raw_control is not None : 593if not isinstance (raw_control ,dict ): 594raise FeedError ("the feed's control member is not an object" ) 595cver = _need (raw_control ,"version" ,str ,"control entry" ) 596version_key (cver ) 597control = [c for c in (_control_package (item ,cver ,skipped )for item in (raw_control .get ("packages" )or []))if c is not None ] 598engine = [] 599raw_engine = data .get ("engine" ) 600if raw_engine is not None : 601if not isinstance (raw_engine ,dict )or not isinstance (raw_engine .get ("packages" ),list ): 602raise FeedError ("the feed's engine member lists no packages" ) 603engine = [e for e in (_engine_package (item ,skipped )for item in raw_engine ["packages" ])if e is not None ] 604seen = set () 605for pkg in engine : 606ident = (pkg .version ,pkg .platform ,pkg .backend ,pkg .variant ) 607if ident in seen : 608raise FeedError (f"the feed lists engine { pkg . label } twice" ) 609seen .add (ident ) 610# (the member "dsv41", the DeepSeek-V4.1 engine packages of Strata 0.2.13 and earlier, may still be in the feed for those versions, frozen; 611# this Control runs no DeepSeek model and does not read it) 612shapes = [] 613raw_shapes = data .get ("shape_engines" ) 614if raw_shapes is not None : 615if not isinstance (raw_shapes ,dict )or not isinstance (raw_shapes .get ("packages" ),list ): 616raise FeedError ("the feed's shape_engines member lists no packages" ) 617shapes = [e for e in (_shape_engine_package (item ,skipped )for item in raw_shapes ["packages" ])if e is not None ] 618seen = set () 619for pkg in shapes : 620ident = (pkg .shape ,pkg .version ,pkg .platform ,pkg .backend ,pkg .variant ) 621if ident in seen : 622raise FeedError (f"the feed lists the engine for { pkg . shape } { pkg . label } twice" ) 623seen .add (ident ) 624drafters = [] 625raw_drafters = data .get ("drafters" ) 626if raw_drafters is not None : 627if not isinstance (raw_drafters ,dict )or not isinstance (raw_drafters .get ("packages" ),list ): 628raise FeedError ("the feed's drafters member lists no packages" ) 629drafters = [_drafter_package (item )for item in raw_drafters ["packages" ]] 630if len ({d .name for d in drafters })!= len (drafters ): 631raise FeedError ("the feed lists a drafter twice" ) 632models ,models_dropped = _models_member (data .get ("models" )) 633return Feed (sequence = sequence ,channel = channel ,generated_at = generated ,expires_at = expires ,app = app , 634control = tuple (control ),engine = tuple (engine ),source = source ,key_id = key_id ,raw = payload , 635skipped = tuple (skipped ),drafters = tuple (drafters ),models = tuple (models ),models_dropped = tuple (models_dropped ),shape_engines = tuple (shapes )) 636 637 638def _expired_words (expires_at :str ,now :dt .datetime ,server_now :dt .datetime | None )-> str : 639"""Expired by this PC's clock. If the update server's own clock says otherwise (or says the PC is far off), the clock is what is wrong.""" 640fix = "Set the date and time right (Windows: Settings, Time & language, Date & time, Set time automatically) and try again." 641if server_now is not None : 642off = abs ((server_now - now ).total_seconds ()) 643if off > 15 * 60 and _time (expires_at ,"expires_at" )>= server_now : 644return (f"your PC clock is wrong: it says { now :%Y-%m-%d %H:%M } (UTC) but the update server says { server_now :%Y-%m-%d %H:%M } , " 645f"so the update feed looks expired. { fix } " ) 646return (f"the update feed expired on { expires_at } by this PC's clock ( { now :%Y-%m-%d } ). If that is not today's date, your PC clock is wrong. " 647f" { fix } Otherwise the update source needs to publish a new feed; nothing was downloaded." ) 648 649 650def verify_and_parse (payload :bytes ,signature_bytes :bytes ,* ,source :str ,trusted :dict [str ,bytes ], 651last_sequence :int | None = None ,channel :str | None = None , 652now :dt .datetime | None = None ,server_now :dt .datetime | None = None )-> Feed : 653"""Check the signature over `payload`, then parse; then the three guards: the channel is the one asked for, the feed has 654not expired, and its sequence is not lower than the last one accepted (a replayed older feed is a downgrade).""" 655if not trusted : 656raise FeedError ("this build trusts no update key (update_keys.json is empty and STRATA_UPDATE_TRUSTED_KEYS is not set), " 657"so no update can be verified; nothing was downloaded" ) 658try : 659signature = json .loads (signature_bytes .decode ("utf-8-sig" )) 660except (ValueError ,UnicodeError ): 661raise FeedError ("the update feed's signature file is not valid" )from None 662try : 663key_id = signing .verify_bytes (trusted ,payload ,signature ) 664except signing .SignatureError as exc : 665raise FeedError (f"the update feed is not trusted: { exc } " )from None 666feed = parse (payload ,source = source ,key_id = key_id ) 667if channel and feed .channel != channel : 668raise FeedError (f"the feed is for the { feed . channel !r } channel, this PC follows { channel !r } " ) 669now = now or dt .datetime .now (dt .timezone .utc ) 670if feed .expires_at and _time (feed .expires_at ,"expires_at" )< now : 671raise FeedError (_expired_words (feed .expires_at ,now ,server_now )) 672if last_sequence is not None and feed .sequence < last_sequence : 673down = FeedDowngrade (f"the update feed is older than the one already accepted (sequence { feed . sequence } < { last_sequence } ); " 674"refusing a replayed feed" ) 675down .sequence ,down .accepted = feed .sequence ,last_sequence 676raise down 677return feed 678 679 680def feed_name (platform :str | None = None )-> str : 681"""The feed file this machine reads from a folder or a release address: ``strata-feed-linux-aarch64.json`` on a Linux ARM64 machine, else 682``strata-feed.json``. A source that names its file (``.../x.json``) is used as given, whatever the machine.""" 683if platform is None : 684try : 685platform = host_platform () 686except Exception :# noqa: BLE001 - an unknown OS reads the common feed 687platform = None 688return AARCH64_FEED_NAME if platform == "linux-aarch64" else FEED_NAME 689 690 691def fetch (source :str ,trusted :dict [str ,bytes ],* ,timeout :float = 30 ,say = None ,automatic :bool = False ,** guards )-> Feed : 692"""Read the feed and its signature from `source` (an https URL, a loopback http URL, a file URL or a folder/file path). `automatic`: a read 693nobody asked for by name (strata_control/netpolicy.py rule 4b: a host that refused within the last hours is not asked again).""" 694if not trusted : 695raise FeedError ("this build trusts no update key (update_keys.json is empty and STRATA_UPDATE_TRUSTED_KEYS is not set), " 696"so no update can be verified; nothing was downloaded" ) 697location = source 698if transfer .kind_of (source )== "path" : 699path = transfer ._local_path (source ) 700if path .is_dir (): 701location = str (path / feed_name ()) 702if not (path / feed_name ()).is_file ()and (path / FEED_NAME ).is_file (): 703location = str (path / FEED_NAME )# a local folder made for the common feed (a test feed, an offline copy) 704elif transfer .kind_of (source )in ("http" ,"https" )and not source .rsplit ("/" ,1 )[- 1 ].endswith (".json" ): 705location = source .rstrip ("/" )+ "/" + feed_name () 706try : 707payload = transfer .read_small (location ,timeout = timeout ,say = say ,automatic = automatic ) 708signature = transfer .read_small (location + SIGNATURE_SUFFIX ,timeout = timeout ,say = say ,automatic = automatic ) 709except transfer .Unreachable as exc : 710f = exc .failure # the network rule (W7 and its two companions): the host, and that nothing installed is lost 711key = {"offline" :"update_offline" ,"again" :"update_again" }.get (f .kind ,"update_no_answer" ) 712raise FeedUnreachable (netpolicy .WORDS [key ].format (host = f .host ,seconds = max (1 ,int (round (f .seconds )))),6 )from None 713except transfer .TransferError as exc : 714raise FeedError (f"the update feed could not be read: { exc } " ,6 )from None 715guards .setdefault ("server_now" ,transfer .server_date ()) 716loaded = verify_and_parse (payload ,signature ,source = location ,trusted = trusted ,** guards ) 717return dataclasses .replace (loaded ,signature = signature )if loaded .models else loaded 718 719 720# ---------------------------------------------------------------------------------------------- hardware and selection 721 722def gfx_covers (archs ,present :list [str ])-> bool : 723"""HIP: the build holds machine code for at least one of the installed AMD GPUs (``gfx1201``). Unknown GPUs: not a refusal.""" 724if not present : 725return True 726return any (a in present for a in archs ) 727 728 729def engine_fit_reasons (pkg :EnginePackage ,hardware :dict )-> list [str ]: 730"""Why `pkg` cannot run on the machine `hardware` describes; empty when it fits. `hardware` is what 731`updater.detect_hardware()` returns: platform, backend, nvidia driver, cuda archs, gfx names, runtime version.""" 732from strata_control import engine_component as ec 733reasons = [] 734if pkg .platform != hardware ["platform" ]: 735reasons .append (f" { pkg . label } is for { pkg . platform } , this PC is { hardware [ 'platform' ] } " ) 736return reasons 737wanted = hardware .get ("backend" )or "cpu" 738if pkg .backend != wanted : 739reasons .append (f" { pkg . label } is a { pkg . backend } engine, this PC needs { wanted } " ) 740return reasons 741runtime = hardware .get ("runtime" ) 742if pkg .min_runtime and runtime and ec ._version_key (runtime )< ec ._version_key (pkg .min_runtime ): 743reasons .append (f" { pkg . label } needs control { pkg . min_runtime } or newer, this is { runtime } " ) 744cuda_archs = tuple (a for a in pkg .archs if a .startswith (("sm_" ,"compute_" ))) 745if pkg .backend == "cuda" and cuda_archs and hardware .get ("cuda_archs" )and not ec .arch_covers (cuda_archs ,hardware ["cuda_archs" ]): 746reasons .append (f" { pkg . label } has code for { ', ' . join ( cuda_archs ) } , this PC's GPU is { ', ' . join ( hardware [ 'cuda_archs' ]) } " ) 747if pkg .backend == "hip" and not gfx_covers (pkg .archs ,hardware .get ("gfx" )or []): 748reasons .append (f" { pkg . label } has code for { ', ' . join ( pkg . archs ) } , this PC's GPU is { ', ' . join ( hardware [ 'gfx' ]) } " ) 749need ,have = pkg .min_driver .get ("nvidia" ),hardware .get ("nvidia_driver" ) 750if pkg .backend == "cuda" and need and have and ec ._version_key (have )< ec ._version_key (need ): 751reasons .append (f" { pkg . label } needs NVIDIA driver { need } or newer, this PC has { have } " ) 752return reasons 753 754 755def select_engine (packages ,hardware :dict )-> tuple [EnginePackage | None ,list [str ]]: 756"""The best package for this PC and, when none fits, every reason. Best = newest version; with equal versions the build 757that needs the newer driver (CUDA 13 beside CUDA 12), as `engine_component.resolve` chooses between installed ones.""" 758from strata_control import engine_component as ec 759fitting ,reasons = [], [] 760for pkg in packages : 761why = engine_fit_reasons (pkg ,hardware ) 762if why : 763reasons .extend (why ) 764else : 765fitting .append (pkg ) 766if not fitting : 767return None ,reasons 768fitting = _settle_hip_variants (fitting ,hardware ,reasons ) 769if not fitting : 770return None ,reasons 771best = max (fitting ,key = lambda p : (version_key (p .version ),ec ._version_key (p .min_driver .get ("nvidia" ,"0" )), 772ec .hip_preference (p .archs )if p .backend == "hip" else 1 , 773ec .arch_native (p .archs ,hardware .get ("cuda_archs" )or [])if p .backend == "cuda" else False )) 774kept = str (hardware .get ("installed_variant" )or "" ) 775if best .backend == "cuda" and kept and best .variant != kept : 776# An update never switches the CUDA build (#3835): a model on the CUDA 12 engine (its card is one CUDA 13 has no code for) must not 777# be given CUDA 13 because ANOTHER card in the PC fits it. The same version of the build that runs here is kept when the feed has it. 778same = [p for p in fitting if p .backend == "cuda" and p .variant == kept and version_key (p .version )== version_key (best .version )] 779if same : 780reasons .append (f"the installed { kept } build is kept; { best . variant } would also fit another card in this PC" ) 781best = same [0 ] 782return best ,reasons 783 784 785def _hip_variants (fitting )-> set [str ]: 786return {p .variant for p in fitting if p .backend == "hip" } 787 788 789def _settle_hip_variants (fitting :list ,hardware :dict ,reasons :list [str ])-> list : 790"""Several HIP builds "fit" only when this PC's gfx is unknown (an empty list fits everything). Version must never decide 791between them: the newest build of the wrong card family would be refused at its test start. Order of evidence: the variant asked 792for, the GPU's name, the variant already installed (an update never switches card family), then give up with a plain reason.""" 793if hardware .get ("backend" )!= "hip" or hardware .get ("gfx" ): 794return fitting 795hip = [p for p in fitting if p .backend == "hip" ] 796if len ({p .variant for p in hip })< 2 : 797return fitting 798from strata_control import engine_component as ec 799chosen ,why = [],"" 800wanted = str (hardware .get ("variant_wanted" )or "" ).lower () 801if wanted : 802chosen = [p for p in hip if p .variant .lower ()== wanted ] 803why = f"the { wanted } build was asked for" 804if not chosen : 805guesses = {g for g in (ec .gfx_from_name (n )for n in hardware .get ("gpu_names" )or [])if g } 806chosen = [p for p in hip if any (a in guesses for a in p .archs )] 807why = f"the GPU name ( { ', ' . join ( hardware . get ( 'gpu_names' ) or []) } ) is a { ', ' . join ( sorted ( guesses )) } " if chosen else "" 808if not chosen and hardware .get ("installed_variant" ): 809chosen = [p for p in hip if p .variant == hardware ["installed_variant" ]] 810why = f"the installed { hardware [ 'installed_variant' ] } build is kept, this PC's AMD card could not be identified" 811if not chosen : 812reasons .append ("Strata cannot tell which AMD build this PC needs (" + ", " .join (sorted (_hip_variants (hip )))+ 813"); the card was not recognised, so nothing was chosen. Name the build with STRATA_ENGINE_BACKEND=hip-<build>" ) 814return [p for p in fitting if p .backend != "hip" ] 815reasons .append (f"several AMD builds fit; chose { chosen [ 0 ]. variant } : { why } " ) 816return [p for p in fitting if p .backend != "hip" or p in chosen ]