okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-022-left: interrupted-move prompt (app + Terminal), deterministic disk test, engine-minimum test reads the tree version1f727f4b5

main
23.7 KiB573 linesraw
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
6  back 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
7  into 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
9  rewritten for every model whose files are all in the new folder.  The data folder in the settings is changed by the caller only
10  when 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
38    def __init__(self, code: str, message: str, details: str = ""):
39        super().__init__(message)
40        self.code = code
41        self.details = details
42
43
44class Stopped(Exception):
45    """The person asked to stop."""
46
47
48@dataclass
49class Entry:
50    rel: str            # path under the data folder, with "/" (models/<tag>/file.gguf)
51    size: int
52    group: 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)."""
59    try:
60        names = sorted(p for p in data.iterdir() if p.is_dir() and p.name.lower() in ITEMS)
61    except OSError:
62        return []
63    return 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."""
68    found: list[Entry] = []
69    for top in _item_dirs(data):
70        for root, _dirs, files in os.walk(top):
71            for name in files:
72                if name.endswith(".part"):
73                    continue
74                path = Path(root) / name
75                try:
76                    size = path.stat().st_size
77                except OSError:
78                    continue
79                rel = path.relative_to(data).as_posix()
80                parts = rel.split("/")
81                kind = parts[0].lower()
82                group = kind if kind == "mtp" or len(parts) < 3 else parts[1].lower()   # a model's GGUF files and its pack are one model
83                found.append(Entry(rel, size, group))
84    found.sort(key=lambda e: (e.group, e.rel))
85    return 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."""
90    out: dict[str, int] = {}
91    for e in entries:
92        out[e.group] = out.get(e.group, 0) + e.size
93    return [{"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)."""
98    p = path
99    while not p.exists() and p.parent != p:
100        p = p.parent
101    return 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."""
106    if os.environ.get("STRATA_MOVE_ALWAYS_COPY") == "1":
107        return False
108    try:
109        return os.stat(_near(a)).st_dev == os.stat(_near(b)).st_dev
110    except OSError:
111        return False
112
113
114def _same(a: Path, b: Path) -> bool:
115    return os.path.normcase(os.path.abspath(a)) == os.path.normcase(os.path.abspath(b))
116
117
118def _inside(child: Path, parent: Path) -> bool:
119    c, p = os.path.normcase(os.path.abspath(child)), os.path.normcase(os.path.abspath(parent))
120    return 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."""
125    try:
126        folder.mkdir(parents=True, exist_ok=True)
127        fd, name = tempfile.mkstemp(prefix=".strata-write-test", dir=folder)
128        os.close(fd)
129        os.remove(name)
130        return None
131    except OSError as e:
132        return 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
140    Returns ``{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),
142    same (nothing to do).  ``choices`` says which of move / keep / empty can be done and why not.
143    """
144    old, new = Path(old), Path(new)
145    free = free or (lambda p: shutil.disk_usage(p).free)
146    entries = inventory(old) if old.is_dir() else []
147    total = sum(e.size for e in entries)
148    result = {"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
151    def refuse(code, message, details=""):
152        result["issue"] = {"code": code, "message": message, "details": details}
153        result["choices"] = {k: {"possible": False, "reason": message} for k in ("move", "keep", "empty")}
154        return result
155
156    if _same(old, new):
157        result["same"] = True
158        return refuse("same", "That is the folder Strata already uses.")
159    if _inside(new, old) or _inside(old, new):
160        return refuse("inside", "Pick a folder outside the current one.")
161    if 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
163        drive = Path(new.anchor) if new.anchor else None
164        if drive is not None and not drive.exists():
165            return refuse("not_found", f"Strata can't find {new}.", f"{drive} does not exist")
166    if write_test:
167        raw = _write_test(new)
168        if raw:
169            return refuse("not_writable", f"Strata can't save files in {new}.", raw)
170    result["same_drive"] = same_drive(old, new)
171    try:
172        result["free_bytes"] = int(free(_near(new)))
173    except OSError:
174        result["free_bytes"] = 0
175    # a same-drive move is a rename: it needs no room
176    needed = 0 if result["same_drive"] else int(total * MARGIN)
177    result["needed_bytes"] = needed
178    can_move = bool(entries) and result["free_bytes"] >= needed
179    reason_move = "" if can_move else ("You have no models to move." if not entries
180                                       else f"Your models need {_gb(needed)}, this drive has {_gb(result['free_bytes'])} free.")
181    result["choices"] = {"move": {"possible": can_move, "reason": reason_move}, "keep": {"possible": True, "reason": ""},
182                         "empty": {"possible": True, "reason": ""}}
183    result["ok"] = True
184    return result
185
186
187def _gb(n: int) -> str:
188    g = n / 1e9
189    return 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:
195    h = hashlib.sha256()
196    with open(path, "rb") as f:
197        while True:
198            if stop():
199                raise Stopped()
200            block = f.read(CHUNK)
201            if not block:
202                break
203            h.update(block)
204            if tick:
205                tick(len(block))
206    return 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."""
211    mark = src.with_name(src.name + ".done")
212    try:
213        m = re.search(r"sha256\s+([0-9a-fA-F]{64})", mark.read_text(encoding="utf-8", errors="replace"))
214    except OSError:
215        return None
216    return m.group(1).lower() if m else None
217
218
219def _disk_full(e: OSError) -> bool:
220    return 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."""
225    part = dst.with_name(dst.name + ".part")
226    dst.parent.mkdir(parents=True, exist_ok=True)
227    h = hashlib.sha256()
228    try:
229        with open(src, "rb") as fin, open(part, "wb") as fout:
230            while True:
231                if stop():
232                    raise Stopped()
233                block = fin.read(CHUNK)
234                if not block:
235                    break
236                h.update(block)
237                fout.write(block)
238                tick(len(block))
239            fout.flush()
240            os.fsync(fout.fileno())
241        if part.stat().st_size != size:
242            raise MoveError("verify", f"The copy of {src.name} has the wrong size.", f"{part.stat().st_size} != {size}")
243        want = h.hexdigest()
244        pinned = _pinned(src)
245        if pinned and pinned != want:
246            raise MoveError("verify", f"{src.name} does not match its saved checksum, so it was not moved.", f"sha256 {want} != pinned {pinned}")
247        got = _sha256_of(part, stop)
248        if got != want:
249            raise MoveError("verify", f"The copy of {src.name} did not match the original.", f"sha256 {got} != {want}")
250        os.replace(part, dst)
251    except OSError as e:
252        _quiet_remove(part)
253        if _disk_full(e):
254            raise 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
255        raise MoveError("io", f"Strata could not copy {src.name}.", f"{type(e).__name__}: {e}") from e
256    except BaseException:
257        _quiet_remove(part)
258        raise
259
260
261def _quiet_remove(path: Path) -> None:
262    try:
263        os.remove(path)
264    except OSError:
265        pass
266
267
268def _read_state(new: Path) -> dict:
269    try:
270        return json.loads((new / STATE_FILE).read_text(encoding="utf-8"))
271    except (OSError, ValueError):
272        return {}
273
274
275def _write_state(new: Path, **fields) -> None:
276    try:
277        tmp = new / (STATE_FILE + ".tmp")
278        tmp.write_text(json.dumps(fields, indent=1), encoding="utf-8")
279        os.replace(tmp, new / STATE_FILE)
280    except OSError:
281        pass
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,
286    so 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:
292    for f in folders:
293        _quiet_remove(Path(f) / STATE_FILE)
294
295
296def _same_path(a, b) -> bool:
297    try:
298        return _same(Path(a), Path(b))
299    except (OSError, ValueError, TypeError):
300        return 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
306    A 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.
307    Returns ``{state, from, to, bytes}`` or None.
308    """
309    data = Path(data)
310    st = _read_state(data)
311    if st.get("state") not in ("running", "stopped", "failed") or not st.get("from") or not st.get("to"):
312        return None
313    if not _same_path(st["from"], data):                       # a pointer left in some other folder is not ours
314        return None
315    if not Path(st["from"]).is_dir():
316        return None
317    pid, token = st.get("pid"), st.get("token")
318    if st["state"] == "running" and isinstance(pid, int) and token and pid != os.getpid():
319        try:
320            from strata_control import procs
321            if procs.start_token(pid) == token:
322                return None
323        except Exception:
324            pass
325    return 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
330    at the old place). Same rule as setup.py repoint_config. Returns whether the file changed."""
331    try:
332        cfg = json.loads(cfg_file.read_text(encoding="utf-8-sig"))
333    except (OSError, ValueError):
334        return False
335
336    def fix(v):
337        if isinstance(v, list):
338            return [fix(x) for x in v]
339        if isinstance(v, dict):
340            return {k: fix(x) for k, x in v.items()}
341        if isinstance(v, str):
342            o = str(old)
343            nv, no = os.path.normcase(v), os.path.normcase(o)
344            if nv.startswith(no + os.sep) or nv.startswith(no + "/"):
345                rest = v[len(o):]
346                if re.split(r"[\\/]", rest.lstrip("\\/"))[0].lower() in ITEMS:
347                    n = str(new) + rest
348                    if Path(n).exists() and not Path(v).exists():
349                        return n
350        return v
351
352    fixed = fix(cfg)
353    if fixed == cfg:
354        return False
355    tmp = cfg_file.with_name(cfg_file.name + ".move-tmp")
356    tmp.write_text(json.dumps(fixed, indent=2) + "\n", encoding="utf-8")
357    os.replace(tmp, cfg_file)
358    return True
359
360
361def config_files(install: Path | None) -> list[Path]:
362    """The ``strata-<model>.json`` run configs of an install folder."""
363    if not install or not Path(install).is_dir():
364        return []
365    return [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."""
370    p = folder
371    while p != stop_at and _inside(p, stop_at):
372        try:
373            p.rmdir()
374        except OSError:
375            return
376        p = p.parent
377
378
379def move(old: Path, new: Path, *, on_progress: Callable[[dict], None] | None = None, cancelled: Callable[[], bool] | None = None,
380         configs: 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    """
385    old, new = Path(old), Path(new)
386    emit = on_progress or (lambda _e: None)
387    stop = cancelled or (lambda: False)
388    p = plan(old, new, write_test=True)
389    if p["issue"]:
390        raise MoveError(p["issue"]["code"], p["issue"]["message"], p["issue"]["details"])
391    entries = inventory(old)
392    total = sum(e.size for e in entries)
393    if not p["choices"]["move"]["possible"] and entries:
394        raise MoveError("disk_full", p["choices"]["move"]["reason"])
395    # unfinished copies of an earlier run are never trusted
396    for top in _item_dirs(new):
397        for root, _d, files in os.walk(top):
398            for name in files:
399                if name.endswith(".part"):
400                    _quiet_remove(Path(root) / name)
401    same = p["same_drive"]
402    todo = {e.group: [] for e in entries}
403    for e in entries:
404        todo[e.group].append(e)
405    left = {g: len(v) for g, v in todo.items()}
406    moved_groups: list[str] = []
407    before = _read_state(old)
408    if not (_same_path(before.get("from", ""), old) and _same_path(before.get("to", ""), new)):
409        before = {}
410    try:
411        from strata_control import procs
412        token = procs.start_token(os.getpid())
413    except Exception:
414        token = None
415    state = {"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)
418    done_bytes = 0
419    files_moved = 0
420    last_emit = [0.0]
421    started = now()
422    seen_inodes: dict[tuple, Path] = {}
423    base_event = lambda **kw: {"event": "progress", "total": total, "same_drive": same, **kw}
424
425    def progress(current: str, group: str, index: int, force: bool = False):
426        t = now()
427        if not force and t - last_emit[0] < 0.25:
428            return
429        last_emit[0] = t
430        rate = done_bytes / max(t - started, 0.001)
431        emit(base_event(done=done_bytes, file=current, group=group, index=index, count=len(entries),
432                        seconds_left=(int((total - done_bytes) / rate) if rate > 0 and not same else 0)))
433
434    def repoint(only_whole: bool = True):
435        for cfg in (configs or []):
436            try:
437                repoint_config(cfg, old, new)
438            except OSError:
439                pass
440
441    try:
442        for index, e in enumerate(entries, 1):
443            if stop():
444                raise Stopped()
445            src, dst = old / e.rel, new / e.rel
446            progress(e.rel, e.group, index, force=True)
447            if not src.exists():
448                done_bytes += e.size
449                left[e.group] -= 1
450            else:
451                if same:
452                    dst.parent.mkdir(parents=True, exist_ok=True)
453                    try:
454                        if dst.exists():
455                            os.remove(dst)
456                        os.replace(src, dst)
457                    except OSError as err:
458                        raise MoveError("io", f"Strata could not move {src.name}.", f"{type(err).__name__}: {err}") from err
459                    done_bytes += e.size
460                else:
461                    ino = None
462                    try:
463                        st = src.stat()
464                        ino = (st.st_dev, st.st_ino) if st.st_nlink > 1 and st.st_ino else None
465                    except OSError:
466                        pass
467                    if 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
469                        try:
470                            dst.parent.mkdir(parents=True, exist_ok=True)
471                            if dst.exists():
472                                os.remove(dst)
473                            os.link(seen_inodes[ino], dst)
474                        except OSError:
475                            _copy_verified(src, dst, e.size, stop, lambda n: None)
476                        done_bytes += e.size
477                    else:
478                        resumed = False
479                        if 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
481                            resumed = _sha256_of(dst, stop) == _sha256_of(src, stop)
482                        if resumed:
483                            done_bytes += e.size
484                        else:
485                            def tick(n, group=e.group, rel=e.rel, idx=index):
486                                nonlocal done_bytes
487                                done_bytes += n
488                                progress(rel, group, idx)
489                            before = done_bytes
490                            try:
491                                _copy_verified(src, dst, e.size, stop, tick)
492                            except BaseException:
493                                done_bytes = before
494                                raise
495                    if ino:
496                        seen_inodes[ino] = dst
497                    try:
498                        os.remove(src)
499                    except OSError as err:
500                        raise 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)
502                files_moved += 1
503                left[e.group] -= 1
504            if left[e.group] == 0:
505                moved_groups.append(e.group)
506                repoint()
507        repoint()
508        state.update(state="done", finished=now())
509        _clear_state(old, new)
510        return {"done": True, "stopped": False, "moved": moved_groups, "remaining": [], "bytes_moved": done_bytes, "total_bytes": total,
511                "files_moved": files_moved, "same_drive": same}
512    except Stopped:
513        repoint()
514        state.update(state="stopped")
515        if files_moved:
516            _save_state(old, new, **state)
517        else:
518            _clear_state(old, new)
519        remaining = [g for g, n in left.items() if n > 0]
520        return {"done": False, "stopped": True, "moved": moved_groups, "remaining": remaining, "bytes_moved": done_bytes, "total_bytes": total,
521                "files_moved": files_moved, "same_drive": same}
522    except MoveError as err:
523        repoint()
524        state.update(state="failed", error=err.code)
525        if files_moved:
526            _save_state(old, new, **state)
527        else:
528            _clear_state(old, new)
529        err.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}
531        raise
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
537    Only 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
538    that 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    """
541    old, new = Path(old), Path(new)
542    st = _read_state(old) or _read_state(new)
543    rels = [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()]
544    removed = restored = bytes_removed = 0
545    for rel in rels:
546        src, dst = old / rel, new / rel
547        _quiet_remove(Path(str(dst) + ".part"))
548        if not dst.exists():
549            continue
550        try:
551            size = dst.stat().st_size
552            if src.exists():
553                os.remove(dst)
554                removed += 1
555                bytes_removed += size
556            else:
557                src.parent.mkdir(parents=True, exist_ok=True)
558                if same_drive(old, new):
559                    os.replace(dst, src)
560                else:
561                    _copy_verified(dst, src, size, lambda: False, lambda n: None)
562                    os.remove(dst)
563                restored += 1
564        except OSError as e:
565            raise MoveError("io", f"Strata could not clean up {dst.name}.", f"{type(e).__name__}: {e}") from e
566        _prune(dst.parent, new)
567    for cfg in (configs or []):
568        try:
569            repoint_config(cfg, new, old)
570        except OSError:
571            pass
572    _clear_state(old, new)
573    return {"removed": removed, "restored": restored, "bytes_removed": bytes_removed}