okami.mom/strata

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

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
6.9 KiB159 linesraw
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
12  current 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
14  line 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:
35    head = str(name).split("-")[0]
36    return tuple(int(x) for x in head.split(".") if x.isdigit()), str(name)
37
38
39def _kind_of(name: str) -> str:
40    return str(name).split("-", 1)[1] if "-" in str(name) else ""
41
42
43def _newest(folder: Path, kind: str | None = None) -> Path | None:
44    try:
45        found = [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)]
46    except OSError:
47        return None
48    return max(found, key=lambda d: _key(d.name), default=None)
49
50
51def _active_control(control: Path) -> Path | None:
52    try:
53        data = json.loads((control / "active.json").read_text(encoding="utf-8-sig"))
54        folder = control / str(data["folder"])
55        if folder.is_dir():
56            return folder
57    except (OSError, ValueError, KeyError, TypeError):
58        pass
59    return _newest(control)
60
61
62def _components() -> Path:
63    from strata_control import engine_component as ec
64    return 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)."""
70    if not isinstance(value, str) or len(value) < 8 or "\n" in value:
71        return None
72    m = _COMPONENT.match(value)
73    if not m:
74        return None
75    old = Path(m["head"] + m["kind"] + os.sep + m["ver"])
76    if old.exists() or not _VERSION.match(m["ver"]):
77        return None
78    root = _components() / m["kind"]
79    current = _active_control(root) if m["kind"] == "control" else _newest(root, _kind_of(m["ver"]))
80    rest = m["rest"].lstrip("\\/")
81    if current is None:
82        return value, False
83    new = current / rest if rest else current
84    return (str(new), True) if new.exists() else (value, False)
85
86
87def _walk(obj, found: list, lost: list, key: str = ""):
88    if isinstance(obj, str):
89        if key in SKIP_KEYS:
90            return obj
91        res = resolve_path(obj)
92        if res is None:
93            return obj
94        (found if res[1] else lost).append((obj, res[0]))
95        return res[0]
96    if isinstance(obj, list):
97        out, skip = [], False
98        for item in obj:
99            out.append(item if skip else _walk(item, found, lost, key))
100            skip = isinstance(item, str) and item in SKIP_FLAGS
101        return out
102    if isinstance(obj, dict):
103        return {k: _walk(v, found, lost, str(k)) for k, v in obj.items()}
104    return 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])."""
109    found: list = []
110    lost: list = []
111    return _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."""
116    from strata_control import profiles
117    out = []
118    try:
119        for p in profiles.list_profiles():
120            if isinstance(p.get("source_config"), str):
121                out.append(Path(p["source_config"]))
122    except Exception:                                    # noqa: BLE001 - informational
123        pass
124    return 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).
129    Returns (one plain line for each file changed, one plain line for each path that exists nowhere).  Never raises."""
130    notes: list[str] = []
131    problems: list[str] = []
132    seen = set()
133    for c in configs:
134        c = Path(c)
135        if c in seen:
136            continue
137        seen.add(c)
138        try:
139            cfg = json.loads(c.read_text(encoding="utf-8-sig"))
140        except (OSError, ValueError):
141            continue
142        if not isinstance(cfg, dict):
143            continue
144        from strata_control import retired
145        if retired.config_reason(cfg) or retired.config_file_reason(c):
146            continue                                     # a DeepSeek config is never written: this Strata does not run it (retired.py)
147        new, found, lost = resolve_config(cfg)
148        for old, _ in lost:
149            problems.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")
150        if not found:
151            continue
152        try:
153            from strata_control import profiles
154            profiles._atomic(c, json.dumps(new, indent=2).encode("utf-8"))
155        except (OSError, ValueError):
156            continue
157        notes.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.")
159    return notes, problems