okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
1f727f4b5
main
1"""Move the model files (models, packs, mtp) from one data folder to another (0.2.2, Settings > Storage > Models folder). 2 3The desktop app and the Terminal both use this: ``strata models move``. Rules, in the order they matter: 4 5* Nothing is deleted until its copy is whole and checked. One file at a time: copy to ``name.part``, compare the size, read the copy 6back and compare its SHA-256 with the original's (and with the pinned SHA-256 in the file's ``.done`` mark when it has one), rename it 7into place, only then remove the original. The extra space needed is never more than the move itself. 8* Stopping is safe. The file in flight is discarded (its ``.part`` is removed), files already moved stay, and the run configs are 9rewritten for every model whose files are all in the new folder. The data folder in the settings is changed by the caller only 10when the whole move is done, so the app is never pointed at an incomplete folder. 11* The same drive is a rename (instant). Another drive is a copy. 12* A crash leaves at worst a model in both folders; ``name.part`` files are never trusted. 13""" 14 15from __future__import annotations 16 17import errno 18import hashlib 19import json 20import os 21import re 22import shutil 23import tempfile 24import time 25from dataclasses import dataclass 26from pathlib import Path 27from typing import Callable 28 29ITEMS = ("models" ,"packs" ,"mtp" ) 30STATE_FILE = "models-move.json" 31MARGIN = 1.05 # room beside the files themselves: 5 % 32CHUNK = 8 * 1024 * 1024 33 34 35class MoveError (Exception ): 36"""A move that stopped for a reason the person can act on. ``code`` is one of: not_found, not_writable, inside, disk_full, verify, busy, io.""" 37 38def __init__ (self ,code :str ,message :str ,details :str = "" ): 39super ().__init__ (message ) 40self .code = code 41self .details = details 42 43 44class Stopped (Exception ): 45"""The person asked to stop.""" 46 47 48@dataclass 49class Entry : 50rel :str # path under the data folder, with "/" (models/<tag>/file.gguf) 51size :int 52group :str # the model it belongs to: "models/<tag>", "packs/<tag>", "mtp" 53 54 55# ----------------------------------------------------------------------------------------------- what is there 56 57def _item_dirs (data :Path )-> list [Path ]: 58"""The models / packs / mtp folders of a data folder (any spelling of the name: ``Models`` and ``models`` are one library).""" 59try : 60names = sorted (p for p in data .iterdir ()if p .is_dir ()and p .name .lower ()in ITEMS ) 61except OSError : 62return [] 63return names 64 65 66def inventory (data :Path )-> list [Entry ]: 67"""Every file Strata keeps in a data folder: nothing else is touched. Unfinished downloads (``.part``) are left where they are.""" 68found :list [Entry ]= [] 69for top in _item_dirs (data ): 70for root ,_dirs ,files in os .walk (top ): 71for name in files : 72if name .endswith (".part" ): 73continue 74path = Path (root )/ name 75try : 76size = path .stat ().st_size 77except OSError : 78continue 79rel = path .relative_to (data ).as_posix () 80parts = rel .split ("/" ) 81kind = parts [0 ].lower () 82group = kind if kind == "mtp" or len (parts )< 3 else parts [1 ].lower ()# a model's GGUF files and its pack are one model 83found .append (Entry (rel ,size ,group )) 84found .sort (key = lambda e : (e .group ,e .rel )) 85return found 86 87 88def groups (entries :list [Entry ])-> list [dict ]: 89"""The models in a list of files, for the person: name (the folder name), bytes.""" 90out :dict [str ,int ]= {} 91for e in entries : 92out [e .group ]= out .get (e .group ,0 )+ e .size 93return [{"group" :g ,"name" :g ,"bytes" :b }for g ,b in out .items ()] 94 95 96def _near (path :Path )-> Path : 97"""The folder that exists and holds ``path`` (or ``path`` itself).""" 98p = path 99while not p .exists ()and p .parent != p : 100p = p .parent 101return p 102 103 104def same_drive (a :Path ,b :Path )-> bool : 105"""Both folders are on one volume (a move is then a rename). STRATA_MOVE_ALWAYS_COPY=1 copies anyway: for testing the copy path on one disk.""" 106if os .environ .get ("STRATA_MOVE_ALWAYS_COPY" )== "1" : 107return False 108try : 109return os .stat (_near (a )).st_dev == os .stat (_near (b )).st_dev 110except OSError : 111return False 112 113 114def _same (a :Path ,b :Path )-> bool : 115return os .path .normcase (os .path .abspath (a ))== os .path .normcase (os .path .abspath (b )) 116 117 118def _inside (child :Path ,parent :Path )-> bool : 119c ,p = os .path .normcase (os .path .abspath (child )),os .path .normcase (os .path .abspath (parent )) 120return c != p and c .startswith (p .rstrip (os .sep )+ os .sep ) 121 122 123def _write_test (folder :Path )-> str | None : 124"""None when files can be written in ``folder`` (made if missing); else the raw refusal.""" 125try : 126folder .mkdir (parents = True ,exist_ok = True ) 127fd ,name = tempfile .mkstemp (prefix = ".strata-write-test" ,dir = folder ) 128os .close (fd ) 129os .remove (name ) 130return None 131except OSError as e : 132return f" { errno . errorcode . get ( e . errno , e . errno ) } : { e . strerror or e } , { e . filename or folder } " 133 134 135# ----------------------------------------------------------------------------------------------- plan 136 137def plan (old :Path ,new :Path ,* ,free = None ,write_test :bool = True )-> dict : 138"""What picking ``new`` for the models folder means, without changing anything. 139 140Returns ``{ok, issue, old, new, same, same_drive, free_bytes, models_bytes, needed_bytes, models, choices}``. ``issue`` is None or 141``{code, message, details}``: not_found (the folder or its drive is gone), not_writable, inside (one folder inside the other), 142same (nothing to do). ``choices`` says which of move / keep / empty can be done and why not. 143""" 144old ,new = Path (old ),Path (new ) 145free = free or (lambda p :shutil .disk_usage (p ).free ) 146entries = inventory (old )if old .is_dir ()else [] 147total = sum (e .size for e in entries ) 148result = {"ok" :False ,"issue" :None ,"old" :str (old ),"new" :str (new ),"same" :False ,"same_drive" :False ,"free_bytes" :0 , 149"models_bytes" :total ,"needed_bytes" :0 ,"models" :groups (entries ),"choices" : {}} 150 151def refuse (code ,message ,details = "" ): 152result ["issue" ]= {"code" :code ,"message" :message ,"details" :details } 153result ["choices" ]= {k : {"possible" :False ,"reason" :message }for k in ("move" ,"keep" ,"empty" )} 154return result 155 156if _same (old ,new ): 157result ["same" ]= True 158return refuse ("same" ,"That is the folder Strata already uses." ) 159if _inside (new ,old )or _inside (old ,new ): 160return refuse ("inside" ,"Pick a folder outside the current one." ) 161if not new .exists (): 162# a folder that will be made is fine when its parent is there; a drive that is not plugged in is not 163drive = Path (new .anchor )if new .anchor else None 164if drive is not None and not drive .exists (): 165return refuse ("not_found" ,f"Strata can't find { new } ." ,f" { drive } does not exist" ) 166if write_test : 167raw = _write_test (new ) 168if raw : 169return refuse ("not_writable" ,f"Strata can't save files in { new } ." ,raw ) 170result ["same_drive" ]= same_drive (old ,new ) 171try : 172result ["free_bytes" ]= int (free (_near (new ))) 173except OSError : 174result ["free_bytes" ]= 0 175# a same-drive move is a rename: it needs no room 176needed = 0 if result ["same_drive" ]else int (total * MARGIN ) 177result ["needed_bytes" ]= needed 178can_move = bool (entries )and result ["free_bytes" ]>= needed 179reason_move = "" if can_move else ("You have no models to move." if not entries 180else f"Your models need { _gb ( needed ) } , this drive has { _gb ( result [ 'free_bytes' ]) } free." ) 181result ["choices" ]= {"move" : {"possible" :can_move ,"reason" :reason_move },"keep" : {"possible" :True ,"reason" :"" }, 182"empty" : {"possible" :True ,"reason" :"" }} 183result ["ok" ]= True 184return result 185 186 187def _gb (n :int )-> str : 188g = n / 1e9 189return f" { g :.0f } GB" if g >= 10 else f" { g :.1f } GB" 190 191 192# ----------------------------------------------------------------------------------------------- the move 193 194def _sha256_of (path :Path ,stop :Callable [[],bool ],tick :Callable [[int ],None ]| None = None )-> str : 195h = hashlib .sha256 () 196with open (path ,"rb" )as f : 197while True : 198if stop (): 199raise Stopped () 200block = f .read (CHUNK ) 201if not block : 202break 203h .update (block ) 204if tick : 205tick (len (block )) 206return h .hexdigest () 207 208 209def _pinned (src :Path )-> str | None : 210"""The SHA-256 a finished download wrote in its ``.done`` mark (setup.py: ``sha256 <hex>``), when there is one.""" 211mark = src .with_name (src .name + ".done" ) 212try : 213m = re .search (r"sha256\s+([0-9a-fA-F]{64})" ,mark .read_text (encoding = "utf-8" ,errors = "replace" )) 214except OSError : 215return None 216return m .group (1 ).lower ()if m else None 217 218 219def _disk_full (e :OSError )-> bool : 220return e .errno in (errno .ENOSPC ,errno .EDQUOT )or getattr (e ,"winerror" ,None )in (112 ,39 ) 221 222 223def _copy_verified (src :Path ,dst :Path ,size :int ,stop :Callable [[],bool ],tick :Callable [[int ],None ])-> None : 224"""Copy src to dst (through dst.part), prove the copy is the same file, rename it into place. The source is left alone.""" 225part = dst .with_name (dst .name + ".part" ) 226dst .parent .mkdir (parents = True ,exist_ok = True ) 227h = hashlib .sha256 () 228try : 229with open (src ,"rb" )as fin ,open (part ,"wb" )as fout : 230while True : 231if stop (): 232raise Stopped () 233block = fin .read (CHUNK ) 234if not block : 235break 236h .update (block ) 237fout .write (block ) 238tick (len (block )) 239fout .flush () 240os .fsync (fout .fileno ()) 241if part .stat ().st_size != size : 242raise MoveError ("verify" ,f"The copy of { src . name } has the wrong size." ,f" { part . stat (). st_size } != { size } " ) 243want = h .hexdigest () 244pinned = _pinned (src ) 245if pinned and pinned != want : 246raise MoveError ("verify" ,f" { src . name } does not match its saved checksum, so it was not moved." ,f"sha256 { want } != pinned { pinned } " ) 247got = _sha256_of (part ,stop ) 248if got != want : 249raise MoveError ("verify" ,f"The copy of { src . name } did not match the original." ,f"sha256 { got } != { want } " ) 250os .replace (part ,dst ) 251except OSError as e : 252_quiet_remove (part ) 253if _disk_full (e ): 254raise MoveError ("disk_full" ,"The drive ran out of space." ,f" { errno . errorcode . get ( e . errno , e . errno ) } : { e . strerror } , { e . filename or dst } " )from e 255raise MoveError ("io" ,f"Strata could not copy { src . name } ." ,f" { type ( e ). __name__ } : { e } " )from e 256except BaseException : 257_quiet_remove (part ) 258raise 259 260 261def _quiet_remove (path :Path )-> None : 262try : 263os .remove (path ) 264except OSError : 265pass 266 267 268def _read_state (new :Path )-> dict : 269try : 270return json .loads ((new / STATE_FILE ).read_text (encoding = "utf-8" )) 271except (OSError ,ValueError ): 272return {} 273 274 275def _write_state (new :Path ,** fields )-> None : 276try : 277tmp = new / (STATE_FILE + ".tmp" ) 278tmp .write_text (json .dumps (fields ,indent = 1 ),encoding = "utf-8" ) 279os .replace (tmp ,new / STATE_FILE ) 280except OSError : 281pass 282 283 284def _save_state (old :Path ,new :Path ,** fields )-> None : 285"""The state goes in the new folder and, as a pointer, in the old one: the old folder stays the data folder until the move is done, 286so that is where the next start looks.""" 287_write_state (new ,** fields ) 288_write_state (old ,** fields ) 289 290 291def _clear_state (* folders :Path )-> None : 292for f in folders : 293_quiet_remove (Path (f )/ STATE_FILE ) 294 295 296def _same_path (a ,b )-> bool : 297try : 298return _same (Path (a ),Path (b )) 299except (OSError ,ValueError ,TypeError ): 300return False 301 302 303def interrupted (data :Path )-> dict | None : 304"""The unfinished move recorded in the data folder (``models-move.json``), for 'A move was interrupted. Finish it or leave it'. 305 306A move that is running right now (its process is alive) is not interrupted. A stopped or failed move that left files in both folders is. 307Returns ``{state, from, to, bytes}`` or None. 308""" 309data = Path (data ) 310st = _read_state (data ) 311if st .get ("state" )not in ("running" ,"stopped" ,"failed" )or not st .get ("from" )or not st .get ("to" ): 312return None 313if not _same_path (st ["from" ],data ):# a pointer left in some other folder is not ours 314return None 315if not Path (st ["from" ]).is_dir (): 316return None 317pid ,token = st .get ("pid" ),st .get ("token" ) 318if st ["state" ]== "running" and isinstance (pid ,int )and token and pid != os .getpid (): 319try : 320from strata_control import procs 321if procs .start_token (pid )== token : 322return None 323except Exception : 324pass 325return st 326 327 328def repoint_config (cfg_file :Path ,old :Path ,new :Path )-> bool : 329"""A run config whose model files moved from ``old`` to ``new`` names them there (each path only when its file is now there and no longer 330at the old place). Same rule as setup.py repoint_config. Returns whether the file changed.""" 331try : 332cfg = json .loads (cfg_file .read_text (encoding = "utf-8-sig" )) 333except (OSError ,ValueError ): 334return False 335 336def fix (v ): 337if isinstance (v ,list ): 338return [fix (x )for x in v ] 339if isinstance (v ,dict ): 340return {k :fix (x )for k ,x in v .items ()} 341if isinstance (v ,str ): 342o = str (old ) 343nv ,no = os .path .normcase (v ),os .path .normcase (o ) 344if nv .startswith (no + os .sep )or nv .startswith (no + "/" ): 345rest = v [len (o ):] 346if re .split (r"[\\/]" ,rest .lstrip ("\\/" ))[0 ].lower ()in ITEMS : 347n = str (new )+ rest 348if Path (n ).exists ()and not Path (v ).exists (): 349return n 350return v 351 352fixed = fix (cfg ) 353if fixed == cfg : 354return False 355tmp = cfg_file .with_name (cfg_file .name + ".move-tmp" ) 356tmp .write_text (json .dumps (fixed ,indent = 2 )+ "\n" ,encoding = "utf-8" ) 357os .replace (tmp ,cfg_file ) 358return True 359 360 361def config_files (install :Path | None )-> list [Path ]: 362"""The ``strata-<model>.json`` run configs of an install folder.""" 363if not install or not Path (install ).is_dir (): 364return [] 365return [p for p in Path (install ).glob ("strata-*.json" )if not p .name .endswith (".shared-settings.json" )] 366 367 368def _prune (folder :Path ,stop_at :Path )-> None : 369"""Remove empty folders from ``folder`` upward, never ``stop_at`` itself.""" 370p = folder 371while p != stop_at and _inside (p ,stop_at ): 372try : 373p .rmdir () 374except OSError : 375return 376p = p .parent 377 378 379def move (old :Path ,new :Path ,* ,on_progress :Callable [[dict ],None ]| None = None ,cancelled :Callable [[],bool ]| None = None , 380configs :list [Path ]| None = None ,now :Callable [[],float ]= time .time )-> dict : 381"""Move the model files from ``old`` to ``new``. Returns the summary; raises MoveError (nothing lost) or Stopped. 382 383``summary = {done: bool, stopped: bool, moved: [group], remaining: [group], bytes_moved, total_bytes, files_moved, same_drive}``. 384""" 385old ,new = Path (old ),Path (new ) 386emit = on_progress or (lambda _e :None ) 387stop = cancelled or (lambda :False ) 388p = plan (old ,new ,write_test = True ) 389if p ["issue" ]: 390raise MoveError (p ["issue" ]["code" ],p ["issue" ]["message" ],p ["issue" ]["details" ]) 391entries = inventory (old ) 392total = sum (e .size for e in entries ) 393if not p ["choices" ]["move" ]["possible" ]and entries : 394raise MoveError ("disk_full" ,p ["choices" ]["move" ]["reason" ]) 395# unfinished copies of an earlier run are never trusted 396for top in _item_dirs (new ): 397for root ,_d ,files in os .walk (top ): 398for name in files : 399if name .endswith (".part" ): 400_quiet_remove (Path (root )/ name ) 401same = p ["same_drive" ] 402todo = {e .group : []for e in entries } 403for e in entries : 404todo [e .group ].append (e ) 405left = {g :len (v )for g ,v in todo .items ()} 406moved_groups :list [str ]= [] 407before = _read_state (old ) 408if not (_same_path (before .get ("from" ,"" ),old )and _same_path (before .get ("to" ,"" ),new )): 409before = {} 410try : 411from strata_control import procs 412token = procs .start_token (os .getpid ()) 413except Exception : 414token = None 415state = {"state" :"running" ,"from" :str (old ),"to" :str (new ),"started" :now (),"bytes" :total ,"pid" :os .getpid (),"token" :token , 416"files" :sorted ({e .rel for e in entries }| set (before .get ("files" )or []))} 417_save_state (old ,new ,** state ) 418done_bytes = 0 419files_moved = 0 420last_emit = [0.0 ] 421started = now () 422seen_inodes :dict [tuple ,Path ]= {} 423base_event = lambda ** kw : {"event" :"progress" ,"total" :total ,"same_drive" :same ,** kw } 424 425def progress (current :str ,group :str ,index :int ,force :bool = False ): 426t = now () 427if not force and t - last_emit [0 ]< 0.25 : 428return 429last_emit [0 ]= t 430rate = done_bytes / max (t - started ,0.001 ) 431emit (base_event (done = done_bytes ,file = current ,group = group ,index = index ,count = len (entries ), 432seconds_left = (int ((total - done_bytes )/ rate )if rate > 0 and not same else 0 ))) 433 434def repoint (only_whole :bool = True ): 435for cfg in (configs or []): 436try : 437repoint_config (cfg ,old ,new ) 438except OSError : 439pass 440 441try : 442for index ,e in enumerate (entries ,1 ): 443if stop (): 444raise Stopped () 445src ,dst = old / e .rel ,new / e .rel 446progress (e .rel ,e .group ,index ,force = True ) 447if not src .exists (): 448done_bytes += e .size 449left [e .group ]-= 1 450else : 451if same : 452dst .parent .mkdir (parents = True ,exist_ok = True ) 453try : 454if dst .exists (): 455os .remove (dst ) 456os .replace (src ,dst ) 457except OSError as err : 458raise MoveError ("io" ,f"Strata could not move { src . name } ." ,f" { type ( err ). __name__ } : { err } " )from err 459done_bytes += e .size 460else : 461ino = None 462try : 463st = src .stat () 464ino = (st .st_dev ,st .st_ino )if st .st_nlink > 1 and st .st_ino else None 465except OSError : 466pass 467if ino and ino in seen_inodes and seen_inodes [ino ].exists (): 468# the same file under two names (a shared pack): one copy, the second name links to it 469try : 470dst .parent .mkdir (parents = True ,exist_ok = True ) 471if dst .exists (): 472os .remove (dst ) 473os .link (seen_inodes [ino ],dst ) 474except OSError : 475_copy_verified (src ,dst ,e .size ,stop ,lambda n :None ) 476done_bytes += e .size 477else : 478resumed = False 479if dst .exists ()and dst .stat ().st_size == e .size : 480# a crash between the rename and the delete: the copy may be whole; prove it before the original goes 481resumed = _sha256_of (dst ,stop )== _sha256_of (src ,stop ) 482if resumed : 483done_bytes += e .size 484else : 485def tick (n ,group = e .group ,rel = e .rel ,idx = index ): 486nonlocal done_bytes 487done_bytes += n 488progress (rel ,group ,idx ) 489before = done_bytes 490try : 491_copy_verified (src ,dst ,e .size ,stop ,tick ) 492except BaseException : 493done_bytes = before 494raise 495if ino : 496seen_inodes [ino ]= dst 497try : 498os .remove (src ) 499except OSError as err : 500raise MoveError ("io" ,f"Strata copied { src . name } but could not remove the old copy." ,f" { type ( err ). __name__ } : { err } " )from err 501_prune (src .parent ,old ) 502files_moved += 1 503left [e .group ]-= 1 504if left [e .group ]== 0 : 505moved_groups .append (e .group ) 506repoint () 507repoint () 508state .update (state = "done" ,finished = now ()) 509_clear_state (old ,new ) 510return {"done" :True ,"stopped" :False ,"moved" :moved_groups ,"remaining" : [],"bytes_moved" :done_bytes ,"total_bytes" :total , 511"files_moved" :files_moved ,"same_drive" :same } 512except Stopped : 513repoint () 514state .update (state = "stopped" ) 515if files_moved : 516_save_state (old ,new ,** state ) 517else : 518_clear_state (old ,new ) 519remaining = [g for g ,n in left .items ()if n > 0 ] 520return {"done" :False ,"stopped" :True ,"moved" :moved_groups ,"remaining" :remaining ,"bytes_moved" :done_bytes ,"total_bytes" :total , 521"files_moved" :files_moved ,"same_drive" :same } 522except MoveError as err : 523repoint () 524state .update (state = "failed" ,error = err .code ) 525if files_moved : 526_save_state (old ,new ,** state ) 527else : 528_clear_state (old ,new ) 529err .summary = {"moved" :moved_groups ,"remaining" : [g for g ,n in left .items ()if n > 0 ],"bytes_moved" :done_bytes ,"total_bytes" :total , 530"files_moved" :files_moved } 531raise 532 533 534def leave (old :Path ,new :Path ,* ,configs :list [Path ]| None = None )-> dict : 535"""'Leave it': give up an unfinished move and keep the old folder as the complete one. 536 537Only the files the move itself listed are touched. A copy in the new folder whose original is still in the old one is removed; a file 538that exists only in the new folder (its original went after a checked copy) is put back in the old folder, so nothing is lost. 539``.part`` files are removed and the run configs point at the old folder again. Returns ``{removed, restored, bytes_removed}``. 540""" 541old ,new = Path (old ),Path (new ) 542st = _read_state (old )or _read_state (new ) 543rels = [r for r in (st .get ("files" )or [])if isinstance (r ,str )and r and ".." not in Path (r ).parts and not Path (r ).is_absolute ()] 544removed = restored = bytes_removed = 0 545for rel in rels : 546src ,dst = old / rel ,new / rel 547_quiet_remove (Path (str (dst )+ ".part" )) 548if not dst .exists (): 549continue 550try : 551size = dst .stat ().st_size 552if src .exists (): 553os .remove (dst ) 554removed += 1 555bytes_removed += size 556else : 557src .parent .mkdir (parents = True ,exist_ok = True ) 558if same_drive (old ,new ): 559os .replace (dst ,src ) 560else : 561_copy_verified (dst ,src ,size ,lambda :False ,lambda n :None ) 562os .remove (dst ) 563restored += 1 564except OSError as e : 565raise MoveError ("io" ,f"Strata could not clean up { dst . name } ." ,f" { type ( e ). __name__ } : { e } " )from e 566_prune (dst .parent ,new ) 567for cfg in (configs or []): 568try : 569repoint_config (cfg ,new ,old ) 570except OSError : 571pass 572_clear_state (old ,new ) 573return {"removed" :removed ,"restored" :restored ,"bytes_removed" :bytes_removed }