okami.mom/strata

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

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

main
22.1 KiB368 linesraw
1"""The engine of one Qwen4 model shape, as its own component (feed member ``shape_engines``), picked by the model.
2
3An engine is compiled for ONE model geometry (``-DSTRATA_GEOMETRY=...``, cmake/strata_geometry.cmake) and refuses a GGUF of another one at load. The Strata engine is
4built for Flash-Next. A Qwen4 model of a different shape therefore ships with its own engine package, and that package never replaces the Strata engine:
5
6* name: the shape is the compiled geometry's name (``q4_lite``); its component is ``strata-q4-lite``; a feed model of that shape has the family ``qwen4exp_q4_lite``;
7* place: ``<components>/shapes/<shape>/engine/<version>-<platform>-<backend>[-<variant>]/``, beside the Strata engine's ``<components>/engine/`` and never inside it. The
8  manifest's id is the shape's component (``strata-q4-lite``) and it carries ``"shape"``, so the Strata engine's scan never reads it and an older Control (which reads only
9  ``strata-engine``) refuses one that was copied into its engine folder;
10* feed: member ``shape_engines`` (the same entry as ``engine``, plus ``shape``). A Control from before this member ignores it, and ignores the models of those shapes too (their
11  family is one it does not know);
12* use: the run config of a model of that shape says ``"exe": "component:strata-q4-lite"``. Every start asks ``engine_component.expand``, which resolves it in the shape's folder
13  (checks every file's SHA-256 and the signature, as for the Strata engine). The Strata engine and every model that runs on it are not touched;
14* fetch: setup (the app's Download and the Terminal's launch) fetches the shape's engine through the signed feed when the model is chosen, as it does for DeepSeek's. An explicit
15  `strata update` brings an installed shape engine up to date. Starting a model never downloads anything.
16
17Nothing in this module imports anything outside the standard library and ``strata_control`` at load time.
18"""
19from __future__ import annotations
20
21import os
22import re
23import shutil
24from pathlib import Path
25from typing import Callable
26
27from strata_control import engine_component as ec
28
29DIR = "shapes"
30FAMILY_PREFIX = "qwen4exp_"
31SHAPE_RE = re.compile(r"[a-z][a-z0-9_]{1,21}[a-z0-9]")                    # q4_lite, q4_mid: the geometry header's name (include/strata/core/geometries/<name>.hpp)
32#: component ids that already mean something else; a shape never becomes one of them
33RESERVED = frozenset({"strata-engine", "strata-dsv41", "strata-control", "strata-vision", "strata-device", "strata-terminal", "strata-app", "strata-drafter"})
34#: The reason, inside WORDS["start_failed"]'s "...did not start correctly ({why})", when a shape engine cannot say its shape (owner, 11-09)
35NO_SHAPE_ANSWER = "it does not say which model shape it was built for"
36KEEP_VERSIONS = 2                                                           # the installed shape engine and the one before it
37#: What a person reads in the lines below where "{model}" stands: the model's title ("Q4 Lite Shape"), not the geometry's name (q4_lite). One switch: False puts the geometry
38#: name back everywhere (the owner decides; `strata components engine` and the JSON always name the shape).
39USE_TITLE = True
40
41# ---- the words a person can see: approved by the owner 11-08 ("A ok"), pinned by tests/terminal/test_shape_engine.py ApprovedWords. {model} is the model's title (see USE_TITLE).
42# Detail (reasons lists, platform-backend, folders) is in the result rows, the JSON and the log, never in these lines.
43WORDS = {
44    "checking": "Checking the engine for {model}\u2026",
45    "fetching": "{model} needs its own engine. It downloads separately, and the Strata engine stays as it is.",
46    "installed": "Engine for {model} {version} ({backend}) is installed.",
47    "ready": "Engine for {model} {version} ({backend}) is installed.",
48    "updated": "Engine for {model} updated from {old} to {new}.",
49    "not_in_feed": "The update feed has no engine for {model} for this computer.",
50    "start_failed": "The engine for {model} {version} was not installed because it did not start correctly ({why}). The Strata engine is unchanged.",
51    "fetch_failed": "The engine for {model} could not be downloaded: {why}",
52    "newer_failed": "A newer engine for {model} is available but could not be installed ({why}). Still using {have}.",
53    "missing": ("{model} needs its own engine, which is not installed or does not fit this PC: {reason}. Run `strata launch` again, or Download / repair in the app, "
54                "to fetch it. Starting a model never downloads an engine."),
55    "current": "The engine for {model} is up to date.",
56    # setup.py (the [X] / [ok] marks are setup's)
57    "setup_failed": "the engine for {model} could not be installed",
58    "setup_failed_hint": "See the line above. Nothing was downloaded for the model. Run this again when the update feed has it.",
59    "setup_ok": "engine for {model}: {version} in {folder}",
60    "setup_skip": "no engine for {model} is installed: the model is downloaded and prepared now; set it up again when the engine can be fetched",
61    "update_label": "Model engine",
62}
63
64
65# ---------------------------------------------------------------------------------------------- names
66
67def shown(shape: str, title: str | None = None) -> str:
68    """The name a person reads for the engine of `shape`: the model's title when there is one (and USE_TITLE), else the shape's name."""
69    return title.strip() if USE_TITLE and isinstance(title, str) and title.strip() else shape
70
71
72def title_from_feed(feed, shape: str) -> str | None:
73    """The title of the feed's model of `shape` (the first one), for a line of `strata update`, which does not know which model asked."""
74    for model in getattr(feed, "models", ()) or ():
75        if model.shape == shape and model.title:
76            return model.title
77    return None
78
79
80def valid(shape) -> bool:
81    """Is `shape` a name this Control accepts for a model shape?"""
82    return isinstance(shape, str) and bool(SHAPE_RE.fullmatch(shape)) and "__" not in shape and component_id(shape) not in RESERVED
83
84
85def component_id(shape: str) -> str:
86    """``q4_lite`` -> ``strata-q4-lite``."""
87    return "strata-" + str(shape).replace("_", "-")
88
89
90def shape_of_component(component: str) -> str | None:
91    """``strata-q4-lite`` -> ``q4_lite``; None for anything that is not a shape's component (``strata-engine`` included)."""
92    if not isinstance(component, str) or not component.startswith("strata-"):
93        return None
94    shape = component[len("strata-"):].replace("-", "_")
95    return shape if valid(shape) and component_id(shape) == component else None
96
97
98def family_of(shape: str) -> str:
99    """The feed model family of a shape: ``q4_lite`` -> ``qwen4exp_q4_lite`` (a family older Controls do not know, so they never offer the model)."""
100    return FAMILY_PREFIX + shape
101
102
103def shape_of_family(family) -> str | None:
104    """``qwen4exp_q4_lite`` -> ``q4_lite``; None for ``qwen4exp`` and every other family."""
105    if not isinstance(family, str) or not family.startswith(FAMILY_PREFIX):
106        return None
107    shape = family[len(FAMILY_PREFIX):]
108    return shape if valid(shape) else None
109
110
111def reference(shape: str) -> str:
112    """The run config's ``exe`` for a model of this shape: ``component:strata-q4-lite``."""
113    return ec.REFERENCE_PREFIX + component_id(shape)
114
115
116def exe_name() -> str:
117    return "strata.exe" if os.name == "nt" else "strata"
118
119
120# ---------------------------------------------------------------------------------------------- where, what is installed
121
122def shapes_dir(components: Path | None = None) -> Path:
123    return (Path(components) if components else ec.components_dir()) / DIR
124
125
126def root(shape: str, components: Path | None = None) -> Path:
127    """The component folder of a shape (it holds ``engine/<package>/``, as the Strata engine's component folder does)."""
128    if not valid(shape):
129        raise ValueError(f"{shape!r} is not a model shape name")
130    return shapes_dir(components) / shape
131
132
133def installed(shape: str, components: Path | None = None) -> list[ec.EngineComponent]:
134    """The engine packages of `shape` that can be read (nothing is hashed), oldest first."""
135    found, _ = ec.scan(root(shape, components), component_id(shape))
136    return sorted(found, key=lambda item: (ec._version_key(item.version), item.root.name))
137
138
139def installed_shapes(components: Path | None = None) -> list[str]:
140    """The shapes that have at least one readable engine package here."""
141    try:
142        names = sorted(d.name for d in shapes_dir(components).iterdir() if d.is_dir() and valid(d.name))
143    except OSError:
144        return []
145    return [name for name in names if installed(name, components)]
146
147
148def newest_version(shape: str, components: Path | None = None) -> str | None:
149    found = installed(shape, components)
150    return found[-1].version if found else None
151
152
153def find(shape: str, components: Path | None = None, *, backend: str | None = None, full: bool = False, title: str | None = None) -> ec.EngineComponent:
154    """The engine of `shape` for this PC (`ShapeEngineMissing` / `EngineIntegrityError` when there is none that can start)."""
155    try:
156        return ec.resolve(root(shape, components), backend=backend, full=full, component_id=component_id(shape))
157    except ec.EngineIntegrityError:
158        raise
159    except ec.EngineMissing as exc:
160        raise ShapeEngineMissing(shape, exc.reason, root(shape, components), problems=exc.problems, title=title) from None
161
162
163class ShapeEngineMissing(ec.EngineMissing):
164    """No usable engine of this model's shape on this PC. Nothing was fetched; the message says how to get it."""
165
166    code = "shape_engine_missing"
167
168    def __init__(self, shape: str, reason: str, where: Path | None = None, *, problems: list | None = None, title: str | None = None):
169        self.shape = shape
170        self.reason = reason
171        self.root = where
172        self.problems = problems or []
173        self.plain_notice = None
174        RuntimeError.__init__(self, WORDS["missing"].format(model=shown(shape, title), reason=reason))
175        self.what = f"the engine for {shown(shape, title)}"
176        self.command = "strata launch"
177
178
179def status(components: Path | None = None) -> list[dict]:
180    """The shape engines installed here, for `strata components engine` and the app: one row per shape with its packages. Empty when there are none (a PC that
181    never had a model of another shape reports exactly what it did before)."""
182    rows = []
183    for shape in installed_shapes(components):
184        row = {"shape": shape, "component": component_id(shape), "installed": [item.to_dict() for item in installed(shape, components)], "usable": False, "engine": None}
185        try:
186            chosen = find(shape, components)
187            row["engine"], row["usable"] = chosen.to_dict(), True
188        except ec.EngineMissing as exc:
189            row["notice"] = str(exc)
190        rows.append(row)
191    return rows
192
193
194# ---------------------------------------------------------------------------------------------- fetching from the signed feed
195
196def _test_start(exe: Path, timeout: float = 120.0, shape: str | None = None) -> tuple[bool, str]:
197    """The new engine starts: ``strata --version`` runs, loads its libraries and names itself (it needs no graphics card and no model). The package's own folders go on the
198    library path first, as the start path does. With `shape`, ``strata --geometry`` (engine 0.2.13 and later) must name that shape: an engine compiled for another geometry than
199    the signed manifest says is refused here, not at its first load, and so is one that cannot answer the flag (NO_SHAPE_ANSWER, owner 11-09)."""
200    import subprocess
201    env = dict(os.environ)
202    var = "PATH" if os.name == "nt" else "LD_LIBRARY_PATH"
203    dirs = [d for d in ec.package_lib_dirs(Path(exe).parent) if Path(d).is_dir()]
204    if dirs:
205        env[var] = os.pathsep.join(dirs + ([env[var]] if env.get(var) else []))
206    try:
207        done = subprocess.run([str(exe), "--version"], capture_output=True, text=True, errors="replace", timeout=timeout, cwd=str(Path(exe).parent), env=env)
208    except (OSError, subprocess.SubprocessError) as exc:
209        return False, f"it could not be started ({exc})"
210    first = ((done.stdout or "").strip().splitlines() or [""])[0]
211    if done.returncode != 0 or not first.startswith("strata"):
212        tail = ((done.stderr or "").strip().splitlines() or [first or f"exit {done.returncode}"])[-1]
213        return False, tail[:160]
214    if shape:
215        ok, why = check_geometry(exe, shape, env, timeout)
216        if not ok:
217            return False, why
218    return True, first
219
220
221def check_geometry(exe: Path, shape: str, env: dict | None = None, timeout: float = 60.0) -> tuple[bool, str]:
222    """Does ``strata --geometry`` name `shape`? (True, "") when it does; (False, plain reason) when it names another, or names none: every engine of a model shape is built
223    after the flag existed (0.2.13, and the Intel engine since 0.2.14), so one that cannot say its shape is refused (owner, 11-09). The Strata engine is never asked."""
224    import subprocess
225    try:
226        done = subprocess.run([str(exe), "--geometry"], capture_output=True, text=True, errors="replace", timeout=timeout, cwd=str(Path(exe).parent), env=env)
227    except (OSError, subprocess.SubprocessError):
228        return False, NO_SHAPE_ANSWER
229    named = ((done.stdout or "").strip().splitlines() or [""])[0].strip()
230    if done.returncode != 0 or not named or named.startswith("strata") or " " in named:
231        return False, NO_SHAPE_ANSWER                     # an engine that does not know the flag (or answers something else)
232    if named != shape:
233        return False, f"it was built for a different model shape ({named})"
234    return True, ""
235
236
237def choose(feed, shape: str, hardware: dict, title: str | None = None):
238    """The feed's engine of `shape` that fits this PC: (package, reasons) as ``feed.select_engine``; package None when the feed has none for it."""
239    from strata_control import feed as feedmod
240    mine = [p for p in feed.shape_engines if p.shape == shape]
241    if not mine:
242        return None, [f"the feed lists no engine for {shown(shape, title)}"]
243    return feedmod.select_engine(mine, hardware)
244
245
246def _prune(shape_root: Path, shape: str, keep_name: str) -> list[str]:
247    """Keep the newest `KEEP_VERSIONS` packages of the shape; remove the older ones unless a running engine uses them."""
248    from strata_control import folder_use, longpath
249    found, _ = ec.scan(shape_root, component_id(shape))
250    ordered = sorted(found, key=lambda item: (ec._version_key(item.version), item.root.name), reverse=True)
251    removed = []
252    for item in ordered[KEEP_VERSIONS:]:
253        if item.root.name == keep_name or folder_use.in_use(item.root):
254            continue
255        shutil.rmtree(longpath.long_path(item.root), ignore_errors=True)
256        removed.append(item.root.name)
257    return removed
258
259
260def update_one(ctx, feed, shape: str, *, install_missing: bool = True, title: str | None = None) -> dict:
261    """Bring the engine of `shape` up to the feed's: fetch the newest package that fits this PC (resumable download, archive SHA-256, the manifest hash the signed feed names,
262    the package signature, every file's hash, the shape named in the manifest), put it NEXT TO the older ones, start it once (`--version`) and only then keep it. The Strata engine is
263    never touched. `install_missing` False: nothing is done for a shape that has no engine installed yet (an explicit `strata update` only updates what is there).
264    Returns the result row (``status``: installed, updated, current, none-installed, none-for-this-pc)."""
265    from strata_control import feed as feedmod, longpath, updater
266    comp = component_id(shape)
267    name = shown(shape, title or title_from_feed(feed, shape))                   # what a person reads; `shape` and `comp` stay the keys
268    have = newest_version(shape, ctx.components)
269    result = {"component": comp, "shape": shape, "status": "current" if have else "none-installed", "changed": False, "installed_before": have}
270    if not have and not install_missing:
271        return result
272    pkg, reasons = choose(feed, shape, ctx.hardware, title=name if name != shape else None)
273    if pkg is None:
274        result.update(status="none-for-this-pc", note=WORDS["not_in_feed"].format(model=name), reasons=reasons)
275        return result
276    if have and feedmod.version_key(pkg.version) <= feedmod.version_key(have):
277        result["note"] = WORDS["current"].format(model=name)
278        return result
279    place = root(shape, ctx.components)
280    updater._free_space_check(place, pkg.size + pkg.installed_bytes, ctx, pkg.sha256, comp)
281    archive = updater._download(ctx, comp, pkg.url, pkg.size, pkg.sha256, f"the engine for {name} {pkg.version}", feed)
282    stage_root = None
283    try:
284        try:
285            stage_root, _staged = updater.stage_engine(ctx, feed, pkg, archive, component_id=comp)
286        except updater.UpdateError as exc:
287            if exc.exit_code == 5:
288                archive.unlink(missing_ok=True)                 # a refused package is not kept for a retry
289            raise
290        folder = stage_root / "engine" / updater.folder_name(pkg)
291        target = ec.engine_dir(place) / folder.name
292        target.parent.mkdir(parents=True, exist_ok=True)
293        if target.exists():
294            shutil.rmtree(longpath.long_path(target), ignore_errors=True)
295        updater._move_dir(folder, target)
296        if os.name != "nt":
297            (target / exe_name()).chmod(0o755)
298        ctx.say("test", f"Test-starting the engine for {name} {pkg.version}", component=comp)
299        ok, why = _test_start(target / exe_name(), shape=shape)
300        if not ok:
301            shutil.rmtree(longpath.long_path(target), ignore_errors=True)         # (never an older one)
302            refused = updater.UpdateError(WORDS["start_failed"].format(model=name, version=pkg.version, why=why), 6)
303            refused.refused_why = why                              # ensure() says the approved line as it is (never inside another line)
304            raise refused
305        removed = _prune(place, shape, target.name)
306        archive.unlink(missing_ok=True)
307        result.update(status="updated" if have else "installed", changed=True, installed_after=pkg.version, folder=target.name, removed=removed,
308                      note=(WORDS["updated"].format(model=name, old=have, new=pkg.version) if have
309                            else WORDS["installed"].format(model=name, version=pkg.version, backend=pkg.backend)))
310        return result
311    finally:
312        if stage_root is not None:
313            shutil.rmtree(longpath.long_path(stage_root), ignore_errors=True)
314
315
316def ensure(shape: str, source: str, *, components: Path | None = None, hardware: dict | None = None, emit: Callable[[str], None] = print, cancel=None,
317           quiet_when_current: bool = True, title: str | None = None, automatic: bool = False) -> Path | None:
318    """The engine of `shape` is installed and up to date, from the signed feed at `source` (a URL or a folder). Returns its program, or None with one plain line through `emit` when
319    there is none (not in the feed, nothing for this PC, the feed cannot be read). A newer package is fetched only when the feed can be read; an installed one keeps running when it
320    cannot. This is what setup and `strata launch` call when a model of that shape is chosen.  `automatic` (`strata launch`): with an engine installed,
321    the check for a newer one is a read nobody asked for, so a feed host that refused within the last hours is not asked again (netpolicy rule 4b);
322    without one the feed is always read."""
323    from strata_control import acquisition, feed as feedmod, signing, updater
324    components = Path(components) if components else ec.components_dir()
325    hw = hardware or updater.detect_hardware()
326    have = newest_version(shape, components)
327    name = shown(shape, title)
328    if not have:
329        emit(WORDS["fetching"].format(model=name))
330    ctx = updater.Context(components=components, source=source, trusted=signing.load_trusted_keys(), hardware=hw, cancel=cancel,
331                          feed_timeout=5.0 if have else 30.0,           # an installed engine: a launch must not wait long for a feed that is not there
332                          automatic=bool(automatic and have),
333                          emit=lambda event: emit(event["message"]) if event.get("event") == "phase" and event.get("message") and event.get("phase") != "feed" else None)
334    try:
335        with updater.update_lock(components):
336            state = updater.State(components)
337            try:
338                feed = updater.open_feed(ctx, state)
339            except feedmod.FeedError as exc:
340                if have:                                          # offline with an engine installed: the engine runs, nothing to say
341                    return find(shape, components, full=False, title=title).exe
342                emit(WORDS["fetch_failed"].format(model=name, why=exc))
343                return None
344            state.save()
345            result = update_one(ctx, feed, shape, title=title)
346            state.save()
347    except Exception as exc:                                      # noqa: BLE001 - with an engine installed, a check for a newer one never stops a launch
348        if not isinstance(exc, (updater.UpdateError, feedmod.FeedError, signing.SignatureError, acquisition.AcquisitionRefused, OSError)) and not have:
349            raise
350        if have:
351            if isinstance(exc, (updater.UpdateError, signing.SignatureError)):         # the feed was read and the newer package was refused or did not start: said, the old one runs
352                emit(WORDS["newer_failed"].format(model=name, why=getattr(exc, "refused_why", None) or str(exc).rstrip("."), have=have))
353            try:
354                return find(shape, components, full=False, title=title).exe
355            except ec.EngineMissing:
356                pass
357        emit(str(exc) if getattr(exc, "refused_why", None) else WORDS["fetch_failed"].format(model=name, why=str(exc).rstrip(".")))
358        return None
359    if result["status"] == "none-for-this-pc":
360        emit(result["note"])
361        return None
362    if result.get("changed") or not quiet_when_current:
363        emit(result.get("note") or WORDS["ready"].format(model=name, version=newest_version(shape, components), backend=""))
364    try:
365        return find(shape, components, full=False, title=title).exe
366    except ec.EngineMissing as exc:
367        emit(str(exc))
368        return None