okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aff3a132f
main
1"""Paths in a saved run config that name a version folder of Strata's own components, and what to do when an update has removed that folder. 2 3Setup writes absolute paths into the run config: ``cwd`` and ``--expert-profile`` into the Control bundle that ran it 4(``<components>/control/<version>/...``), the picture reader and library folders into an engine package 5(``<components>/engine/<version>-<platform>-<backend>/...``). An update puts the new version 6beside the old one and removes the versions older than the one before, so the second update after a model was set up deleted the folders its config 7names: the model showed as "not installed" and a start failed (#4891; "Qwen breaks each time Strata is updated"). 8 9One resolver, used by both sides: 10 11* ``resolve_config(cfg)`` (pure; ``profiles.read_run_config`` calls it, so the doctor, the model list, the launch plan and the runtime host see the 12current folders without a file being written); 13* ``repair(configs)`` (runtime.start calls it for the profile being started and every saved profile): the same, written once into the file, one plain 14line for each file it changed. 15 16Only paths in Strata's own folders are touched (``components/control``, ``components/engine``), and only when the version folder they 17name is GONE; a path the person typed themselves, a model or pack folder, or a version folder that still exists is left exactly as it is. A path whose 18file is nowhere in the current version either is not guessed: ``unresolved`` names it. 19""" 20from __future__import annotations 21 22import json 23import os 24import re 25from pathlib import Path 26 27_SEP = r"[\\/]" 28_COMPONENT = re .compile (rf"^(?P<head>.*? { _SEP } components { _SEP } )(?P<kind>control|engine) { _SEP } (?P<ver>[^\\/]+)(?P<rest>(?: { _SEP } .*)?)$" ,re .S ) 29_VERSION = re .compile (r"^\d+(?:\.\d+)+" ) 30SKIP_KEYS = ("log" ,)# paths the engine writes, not reads 31SKIP_FLAGS = ("--expert-profile-save" ,) 32 33 34def _key (name :str )-> tuple : 35head = str (name ).split ("-" )[0 ] 36return tuple (int (x )for x in head .split ("." )if x .isdigit ()),str (name ) 37 38 39def _kind_of (name :str )-> str : 40return str (name ).split ("-" ,1 )[1 ]if "-" in str (name )else "" 41 42 43def _newest (folder :Path ,kind :str | None = None )-> Path | None : 44try : 45found = [d for d in folder .iterdir ()if d .is_dir ()and _VERSION .match (d .name )and (kind is None or _kind_of (d .name )== kind )] 46except OSError : 47return None 48return max (found ,key = lambda d :_key (d .name ),default = None ) 49 50 51def _active_control (control :Path )-> Path | None : 52try : 53data = json .loads ((control / "active.json" ).read_text (encoding = "utf-8-sig" )) 54folder = control / str (data ["folder" ]) 55if folder .is_dir (): 56return folder 57except (OSError ,ValueError ,KeyError ,TypeError ): 58pass 59return _newest (control ) 60 61 62def _components ()-> Path : 63from strata_control import engine_component as ec 64return ec .components_dir () 65 66 67def resolve_path (value :str )-> tuple [str ,bool ]| None : 68"""For a string that names a file in a version folder of Strata's own that is gone: (the same file in the current version, True) when it is there, 69(value, False) when it is nowhere; None when the string is not such a path or its version folder still exists (nothing to do).""" 70if not isinstance (value ,str )or len (value )< 8 or "\n" in value : 71return None 72m = _COMPONENT .match (value ) 73if not m : 74return None 75old = Path (m ["head" ]+ m ["kind" ]+ os .sep + m ["ver" ]) 76if old .exists ()or not _VERSION .match (m ["ver" ]): 77return None 78root = _components ()/ m ["kind" ] 79current = _active_control (root )if m ["kind" ]== "control" else _newest (root ,_kind_of (m ["ver" ])) 80rest = m ["rest" ].lstrip ("\\/" ) 81if current is None : 82return value ,False 83new = current / rest if rest else current 84return (str (new ),True )if new .exists ()else (value ,False ) 85 86 87def _walk (obj ,found :list ,lost :list ,key :str = "" ): 88if isinstance (obj ,str ): 89if key in SKIP_KEYS : 90return obj 91res = resolve_path (obj ) 92if res is None : 93return obj 94 (found if res [1 ]else lost ).append ((obj ,res [0 ])) 95return res [0 ] 96if isinstance (obj ,list ): 97out ,skip = [],False 98for item in obj : 99out .append (item if skip else _walk (item ,found ,lost ,key )) 100skip = isinstance (item ,str )and item in SKIP_FLAGS 101return out 102if isinstance (obj ,dict ): 103return {k :_walk (v ,found ,lost ,str (k ))for k ,v in obj .items ()} 104return obj 105 106 107def resolve_config (cfg :dict )-> tuple [dict ,list ,list ]: 108"""(the config with every path of a removed version folder pointed at the current one, [(old, new)], [(old, "") that exist nowhere]).""" 109found :list = [] 110lost :list = [] 111return _walk (cfg ,found ,lost ),found , [(old ,"" )for old ,_ in lost ] 112 113 114def saved_configs ()-> list [Path ]: 115"""The run config of every saved profile (app-1, app-2, launch-...): the files a start reads.""" 116from strata_control import profiles 117out = [] 118try : 119for p in profiles .list_profiles (): 120if isinstance (p .get ("source_config" ),str ): 121out .append (Path (p ["source_config" ])) 122except Exception :# noqa: BLE001 - informational 123pass 124return out 125 126 127def repair (configs )-> tuple [list [str ],list [str ]]: 128"""For a START: every run config in `configs` is resolved and, when a path changed, written once (atomically, nothing else changed). 129Returns (one plain line for each file changed, one plain line for each path that exists nowhere). Never raises.""" 130notes :list [str ]= [] 131problems :list [str ]= [] 132seen = set () 133for c in configs : 134c = Path (c ) 135if c in seen : 136continue 137seen .add (c ) 138try : 139cfg = json .loads (c .read_text (encoding = "utf-8-sig" )) 140except (OSError ,ValueError ): 141continue 142if not isinstance (cfg ,dict ): 143continue 144from strata_control import retired 145if retired .config_reason (cfg )or retired .config_file_reason (c ): 146continue # a DeepSeek config is never written: this Strata does not run it (retired.py) 147new ,found ,lost = resolve_config (cfg ) 148for old ,_ in lost : 149problems .append (f" { c . name } : { old } was removed by an update and no file of that name is in the current version; run setup again for this model" ) 150if not found : 151continue 152try : 153from strata_control import profiles 154profiles ._atomic (c ,json .dumps (new ,indent = 2 ).encode ("utf-8" )) 155except (OSError ,ValueError ): 156continue 157notes .append (f" { c . name } : { len ( found ) } path { 's' if len ( found ) != 1 else '' } named folders of an earlier Strata version that an update removed (" 158+ ", " .join (sorted ({Path (o ).name or o for o ,_ in found })[:3 ])+ "); they now name the current version." ) 159return notes ,problems