okami.mom/strata

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

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

main
25.0 KiB458 linesraw
1"""An engine update beside a loaded model: the notice, the warning, the clean stop and the start again.
2
3The rule (owner, 11-01): an engine update never starts by itself while a model is loaded, and nothing replaces or removes the engine a running
4model uses.  An update that finds a model loaded does one of three things, and never a fourth:
5
6* nobody can be asked (a script, the app without a dialog, a service): it stops BEFORE any download and changes nothing (exit 7), and says
7  the two next steps;
8* the person said yes (the question in a terminal, ``--stop-model`` in a script): the new engine is downloaded while the model keeps
9  serving, then the model is stopped cleanly, the update is made, and the model is started again with the same settings when the person says so
10  (the question in a terminal, ``--start-again`` in a script; otherwise it stays stopped and the way to start it is printed);
11* the person said no: nothing is changed (exit 0).
12
13``ModelGate`` is the one object the update (strata_control/updater.py) calls at its two points: ``consent`` before anything is downloaded, and
14``release`` after the download, right before the first thing is staged or test-started.  ``update_with_models`` runs a whole update around it
15and starts the models again afterwards, also when the update failed (the old engine is still in use).
16
17``notice`` is the one quiet line the Terminal shows when the last check found a newer engine.  It reads the cached check only (a local
18file) and never touches the network, so showing it breaks no rule.  ``refresh_cache`` is the daily check, written but not called by anything:
19adding it to a screen is one line, and waits for the owner's yes (the Terminal learns of a new engine only from a check somebody made).
20"""
21
22from __future__ import annotations
23
24import datetime as dt
25import json
26import threading
27from dataclasses import dataclass, field
28from pathlib import Path
29from typing import Callable
30
31from strata_control import engine_component as ec, updater
32
33EXIT_BUSY = 7                                                       # a loaded model, nothing was changed (the updater's own code)
34EXIT_NOT_RESTARTED = 8                                              # the update is done (or failed and the old engine is in use) but a model did not start again
35NEXT_STEP = "`strata update`"
36
37
38# ---------------------------------------------------------------------------------------------------- the notice
39
40def _installed_words(root) -> dict:
41    return {"engine": ec.newest_installed_version(root)}
42
43
44def notice(root=None) -> dict | None:
45    """What the last check found newer, as {"engine": v, "have": {...}, "line": plain sentence}, or None.  Local files only."""
46    offers = ec.cached_offers(root)
47    engine = offers.get("engine")
48    if not engine:
49        return None
50    have = _installed_words(root)
51    head = "A new " + f"engine {engine}" + (f" (you have {have['engine']})" if have["engine"] else "") + " is available"
52    return {"engine": engine, "have": have, "line": head}
53
54
55def notice_line(root=None, how: str = f"Update with {NEXT_STEP}.") -> str | None:
56    """The single quiet line: what is new and the one next step.  ``how`` is the screen's own way (the monitor says "Press u or run ...")."""
57    found = notice(root)
58    return None if found is None else f"{found['line']}. {how}"
59
60
61ATTEMPT_FILE = "notice-attempt.json"
62CHECK_TIMEOUT_S = 5.0                    # one read of the feed waits this long at most (twice: the transfer layer tries a web address once more)
63CHECK_ENV = "STRATA_UPDATE_CHECK"        # "0" / "off": no daily check (a tester's or a privacy switch; the default is on in the launch monitor only)
64
65
66def _hours_since(text) -> float | None:
67    try:
68        return (dt.datetime.now(dt.timezone.utc) - dt.datetime.fromisoformat(str(text))).total_seconds() / 3600.0
69    except (TypeError, ValueError):
70        return None
71
72
73def refresh_cache(check: Callable[[], object], root=None, *, max_age_hours: float = 24.0) -> bool:
74    """The daily check, quiet by design: run ``check()`` (updater.check: it reads the signed feed, writes the cache, downloads no engine) when neither
75    the last check nor the last ATTEMPT is younger than ``max_age_hours``.  The attempt is written BEFORE the network is touched, so a PC with no
76    internet, a blocked DNS, a proxy, a captive portal that answers junk or a connection that never answers is asked once a day and not again until
77    tomorrow.  Nothing is printed or logged, whatever happens.  True when it ran."""
78    import os
79    if os.environ.get(CHECK_ENV, "").strip().lower() in ("0", "off", "no", "false", "never"):
80        return False
81    base = Path(root) if root else ec.components_dir()
82    try:
83        last = json.loads((base / ec.UPDATE_STATE).read_text(encoding="utf-8-sig")).get("last_check", {}).get("at")
84    except (OSError, ValueError, AttributeError):
85        last = None
86    try:
87        tried = json.loads((base / updater.STATE_DIR / ATTEMPT_FILE).read_text(encoding="utf-8")).get("at")
88    except (OSError, ValueError, AttributeError):
89        tried = None
90    for stamp in (last, tried):
91        age = _hours_since(stamp)
92        if age is not None and age < max_age_hours:
93            return False
94    try:
95        folder = base / updater.STATE_DIR
96        folder.mkdir(parents=True, exist_ok=True)
97        (folder / ATTEMPT_FILE).write_text(json.dumps({"at": dt.datetime.now(dt.timezone.utc).isoformat()}), encoding="utf-8")
98    except OSError:
99        return False                                     # cannot remember the attempt: do not risk asking again and again
100    try:
101        check()
102    except BaseException:                                # noqa: BLE001 - quiet: no network, no notice
103        return False
104    return True
105
106
107def start_daily_check(on_done: Callable[[], None] | None = None, root=None, *, feed: str | None = None) -> "threading.Thread | None":
108    """Run the daily check in a thread of its own (a daemon: nothing ever waits for it, and a connection that never answers is simply left behind
109    when the program ends).  ``on_done`` is called when a check finished well.  Used by the launch monitor only."""
110    import threading
111    from strata_control import acquisition
112    if acquisition.is_forbidden():
113        return None
114
115    def work() -> None:
116        try:
117            def check():
118                import argparse
119                from strata_cli import update_cmd
120                from strata_control import signing
121                base = Path(root) if root else ec.components_dir()
122                ctx = updater.Context(components=base, source=update_cmd._feed_source(argparse.Namespace(feed=feed), base), trusted=signing.load_trusted_keys(),
123                                      hardware=updater.detect_hardware(), feed_timeout=CHECK_TIMEOUT_S, serving=lambda: [])
124                return updater.check(ctx)
125            if refresh_cache(check, root) and on_done is not None:
126                on_done()
127        except BaseException:                            # noqa: BLE001 - never a message, never a trace
128            pass
129    thread = threading.Thread(target=work, name="strata-daily-check", daemon=True)
130    thread.start()
131    return thread
132
133
134def monitor_note(root=None) -> str | None:
135    """The short form of the notice for the monitor's one message line."""
136    found = notice(root)
137    if found is None:
138        return None
139    return f"New engine {found['engine']} is available. Press u to update."
140
141
142# ---------------------------------------------------------------------------------------------------- models that are loaded
143
144@dataclass
145class RunningModel:
146    profile: str
147    name: str
148    state: str = "ready"
149    port: int | None = None
150    kind: str = "launch"                 # launch (strata launch), profile (the app's or a saved profile), server (a Strata server nobody here started)
151    can_stop: bool = True
152    choices: dict | None = field(default=None, repr=False)
153
154    @property
155    def label(self) -> str:
156        return self.name + (f" (port {self.port})" if self.port else "")
157
158    def to_dict(self) -> dict:
159        return {"profile": self.profile, "name": self.name, "port": self.port, "kind": self.kind, "state": self.state}
160
161
162def _launch_dir() -> Path | None:
163    try:
164        from strata_cli.launch.runner import launch_dir
165        return launch_dir()
166    except Exception:                                    # noqa: BLE001
167        return None
168
169
170def _saved_choices(profile: str) -> dict | None:
171    folder = _launch_dir()
172    if folder is None or not profile.startswith("launch-"):
173        return None
174    try:
175        return json.loads((folder / f"{profile[7:]}.choices.json").read_text(encoding="utf-8"))
176    except (OSError, ValueError):
177        return None
178
179
180def running_models(serving: list[dict] | None = None) -> list[RunningModel]:
181    """The models that are loaded, named in words a person knows.  ``serving`` is updater.serving_now()'s answer (called here when not given)."""
182    from strata_control import profiles
183    items = updater.serving_now() if serving is None else serving
184    out = []
185    for item in items:
186        pid = str(item.get("profile", ""))
187        state = str(item.get("state", "ready"))
188        if not profiles.PROFILE_ID.fullmatch(pid):       # "a running Strata server": the shared lease, held by a process that is not Strata's own launch
189            out.append(RunningModel(pid or "a running Strata server", pid or "A Strata server", state, None, "server", can_stop=False))
190            continue
191        name, port = pid[7:] if pid.startswith("launch-") else pid, None
192        try:
193            prof, _rev = profiles.load(pid)
194            port = int((prof.get("overrides") or {}).get("port") or 0) or None
195            cfg = json.loads(Path(prof["source_config"]).read_text(encoding="utf-8-sig")) if prof.get("source_config") else {}
196            name = str(cfg.get("model_name") or name)
197        except Exception:                                # noqa: BLE001 - the name is a nicety
198            pass
199        out.append(RunningModel(pid, name, state, port, "launch" if pid.startswith("launch-") else "profile", True, _saved_choices(pid)))
200    return out
201
202
203def _names(models: list[RunningModel]) -> str:
204    labels = [m.label for m in models]
205    return labels[0] if len(labels) == 1 else ", ".join(labels[:-1]) + " and " + labels[-1]
206
207
208def stop_model(model: RunningModel, timeout: float = 180) -> None:
209    from strata_control import runtime
210    runtime.stop(model.profile, timeout=timeout)
211    try:
212        from strata_cli.launch import access
213        access.stop_tunnel(model.profile)
214    except Exception:                                    # noqa: BLE001 - no tunnel, or none to stop
215        pass
216
217
218def _start_wait(model: RunningModel) -> float:
219    try:
220        from strata_control import profiles
221        prof, _rev = profiles.load(model.profile)
222        cfg = json.loads(Path(prof["source_config"]).read_text(encoding="utf-8-sig"))
223        return min(1800.0, float(cfg.get("engine_ready_s") or 900) + 60)          # (runtime.start takes 0..1800; a DeepSeek config asks for more)
224    except Exception:                                    # noqa: BLE001
225        return 960.0
226
227
228def start_model(model: RunningModel) -> tuple[bool, str]:
229    """Start the saved profile again: the same run config and overrides, so the same settings.  (ok, a plain sentence)."""
230    from strata_control import runtime
231    cfg_path = None
232    try:
233        from strata_control import profiles
234        cfg_path = Path(profiles.load(model.profile)[0]["source_config"])
235    except Exception:                                    # noqa: BLE001
236        pass
237    why = ""
238    try:
239        result = runtime.start(model.profile, wait=_start_wait(model))
240        if result.get("ok"):
241            if (model.choices or {}).get("access") == "cloudflare":
242                try:
243                    from strata_cli.launch import access
244                    access.start_tunnel(model.profile, int(model.port or 8080))
245                except Exception:                        # noqa: BLE001 - the model serves on this computer; the tunnel is said not to be back
246                    return True, f"{model.label} is serving again; its Cloudflare tunnel did not open, start it again with `strata launch`."
247            return True, f"{model.label} is serving again with the same settings."
248        try:
249            from strata_cli.launch.runner import explain_engine_exit
250            why = explain_engine_exit(result, cfg_path)[0]
251        except Exception:                                # noqa: BLE001
252            why = str(result.get("error") or result.get("next_action") or result.get("state") or "it stopped at its start")
253    except Exception as exc:                             # noqa: BLE001 - a refused or failed start is a sentence, never a trace
254        why = str(exc)
255    for call in (lambda: runtime.stop(model.profile, timeout=30), lambda: runtime.cleanup(model.profile)):
256        try:
257            call()
258        except Exception:                                # noqa: BLE001 - nothing may stay half alive
259            pass
260    return False, f"{model.label} did not start again: {why.rstrip('.')}."
261
262
263def start_hint(model: RunningModel) -> str:
264    """The way to start a stopped model by hand: the launch line of its saved choices when they can be read, else the command."""
265    if model.choices:
266        try:
267            from strata_cli.launch import settings as S
268            return S.flags_text(S.LaunchSettings.from_dict({**model.choices, "name": model.name}))
269        except Exception:                                # noqa: BLE001
270            pass
271    return "`strata launch` (the screens start from your saved presets)"
272
273
274# ---------------------------------------------------------------------------------------------------- the gate
275
276class Declined(updater.UpdateError):
277    """The person said no: nothing was changed.  Exit 0."""
278
279    def __init__(self, message: str):
280        super().__init__(message, 0)
281
282
283class ModelGate:
284    """What the updater asks when a model is loaded.  ``ask(question, default) -> bool`` is a person (None: nobody can be asked);
285    ``allow_stop`` is the explicit yes of a script; ``start_again`` the explicit yes to the start-again question of a script.  ``say`` shows a
286    line; ``emit`` gets one event per step (the app's host reads them from ``strata update --output jsonl``)."""
287
288    def __init__(self, *, ask: Callable[[str, bool], bool] | None = None, say: Callable[[str], None] = lambda text: None,
289                 emit: Callable[[dict], None] = lambda event: None, allow_stop: bool = False, start_again: bool = False, settle_s: float = 120.0,
290                 stop: Callable[[RunningModel], None] | None = None, start: Callable[[RunningModel], tuple[bool, str]] | None = None):
291        self.ask, self.say, self.emit = ask, say, emit
292        self.allow_stop, self.start_again, self.settle_s = allow_stop, start_again, settle_s
293        self._stop, self._start = stop or stop_model, start or start_model          # (looked up now, so a test or a host can replace them)
294        self.consented: dict[str, RunningModel] = {}
295        self.stopped: list[RunningModel] = []
296        self.restarts: list[dict] = []
297
298    # -- before anything is downloaded
299    def consent(self, serving: list[dict], plan: str) -> None:
300        models = running_models(serving)
301        loose = [m for m in models if not m.can_stop]
302        if loose:
303            raise updater.UpdateError(
304                f"{_names(loose)} is serving, and Strata did not start it from here (a service, `strata serve` or another program), so it cannot be "
305                f"stopped for you. Stop it yourself, then run {NEXT_STEP} again. Nothing was changed.", EXIT_BUSY)
306        names = _names(models)
307        self.emit({"event": "models", "phase": "consent", "models": [m.to_dict() for m in models], "message": f"{names} is running"})
308        if not self.allow_stop:
309            if self.ask is None:
310                raise updater.UpdateError(
311                    f"{names} {'is' if len(models) == 1 else 'are'} running, and the update needs "
312                    f"{'it' if len(models) == 1 else 'them'} stopped, so nothing was changed. To let the update stop "
313                    f"{'it' if len(models) == 1 else 'them'}: run {NEXT_STEP} again with --stop-model (add --start-again to start "
314                    f"{'it' if len(models) == 1 else 'them'} again afterwards). Or stop {'it' if len(models) == 1 else 'them'} yourself first "
315                    f"(`strata launch --stop`).", EXIT_BUSY)
316            self.say(f"{names} {'is' if len(models) == 1 else 'are'} running. {plan} The new engine is downloaded while "
317                     f"{'it keeps' if len(models) == 1 else 'they keep'} serving; then {'it is' if len(models) == 1 else 'they are'} stopped "
318                     f"(answers in progress end), the engine is updated, and you choose whether to start "
319                     f"{'it' if len(models) == 1 else 'them'} again with the same settings.")
320            if not self.ask(f"Stop {names} for the update?", False):
321                raise Declined("Nothing was changed. The model keeps running.")
322        for m in models:
323            self.consented[m.profile] = m
324
325    # -- after the download, before the first thing is staged or test-started
326    def release(self, serving_now: Callable[[], list[dict]]) -> None:
327        serving = serving_now()
328        if not serving:
329            return
330        models = running_models(serving)
331        new = [m for m in models if m.profile not in self.consented]
332        if new:                                          # started after the yes: not covered by it
333            names = _names(new)
334            if self.ask is not None and not self.allow_stop:
335                self.say(f"{names} started while the update was downloading.")
336                if self.ask(f"Stop {names} too?", False):
337                    for m in new:
338                        self.consented[m.profile] = m
339                    new = []
340            if new:
341                raise updater.UpdateError(
342                    f"{names} started while the update was running, and nobody agreed to stop it, so nothing more was changed. "
343                    f"Stop it, then run {NEXT_STEP} again (the download is kept).", EXIT_BUSY)
344        for m in models:
345            self.emit({"event": "models", "phase": "stopping", "models": [m.to_dict()], "message": f"Stopping {m.label}"})
346            self.say(f"Stopping {m.label} (answers in progress end first)...")
347            try:
348                self._stop(m)
349            except Exception as exc:                     # noqa: BLE001
350                raise updater.UpdateError(f"{m.label} could not be stopped ({exc}). Nothing was changed; it may still be running.", EXIT_BUSY) from None
351            if m.profile not in {s.profile for s in self.stopped}:
352                self.stopped.append(m)
353            self.emit({"event": "models", "phase": "stopped", "models": [m.to_dict()], "message": f"{m.label} is stopped"})
354        self._settle(serving_now)
355
356    def _settle(self, serving_now: Callable[[], list[dict]]) -> None:
357        """A stopped engine lets go of the card and of the shared lease a moment later (a big DeepSeek model takes a while to unload): wait for that,
358        up to ``settle_s``, before the update goes on. Found by the real DeepSeek flow, where the very next check still saw "a running Strata server"."""
359        import time
360        deadline = time.monotonic() + self.settle_s
361        while serving_now():
362            if time.monotonic() >= deadline:
363                raise updater.UpdateError("The model was stopped but its engine has not let go of the graphics card yet, so nothing more was changed. "
364                                          f"Wait a minute and run {NEXT_STEP} again.", EXIT_BUSY)
365            time.sleep(min(1.0, self.settle_s / 10 or 0.1))
366
367    # -- after the update, whatever happened
368    def finish(self, update_ok: bool, changed: bool | None = None) -> bool:
369        """Start the stopped models again when the person says so.  True when every model that was meant to start did."""
370        everyone = True
371        for m in self.stopped:
372            if update_ok or changed:
373                question = f"Start {m.label} again with the same settings?"
374            else:
375                question = f"The old engine is unchanged. Start {m.label} again on it?"
376            if self.start_again:
377                yes = True
378            elif self.ask is not None:
379                yes = self.ask(question, True)
380            else:
381                yes = False
382            if not yes:
383                hint = start_hint(m)
384                self.say(f"{m.label} is stopped. Start it when you want with {hint}")
385                self.restarts.append({**m.to_dict(), "restarted": False, "asked": self.ask is not None or self.start_again})
386                self.emit({"event": "models", "phase": "left-stopped", "models": [m.to_dict()], "message": f"{m.label} stays stopped", "start": hint})
387                continue
388            self.emit({"event": "models", "phase": "restarting", "models": [m.to_dict()], "message": f"Starting {m.label} again"})
389            self.say(f"Starting {m.label} again (loading can take a few minutes)...")
390            ok, text = self._start(m)
391            self.say(text)
392            if not ok:
393                everyone = False
394                self.say(f"The engine is not the problem if this is a one-off: start it with {start_hint(m)}")
395            self.restarts.append({**m.to_dict(), "restarted": ok, "asked": True, "message": text})
396            self.emit({"event": "models", "phase": "restarted" if ok else "restart-failed", "models": [m.to_dict()], "message": text})
397        return everyone
398
399    def report(self) -> dict:
400        return {"stopped": [m.to_dict() for m in self.stopped], "restarts": list(self.restarts)}
401
402
403def update_with_models(ctx: "updater.Context", gate: ModelGate, show: Callable[[dict], None] | None = None, **kwargs) -> dict:
404    """``updater.run_update`` with the gate attached, and the stopped models started again afterwards (also when the update failed or was refused
405    after a model had been stopped).  Returns run_update's answer plus ``models`` and, if a model did not start again, exit code 8.
406    Raises what run_update raises (Busy, Declined, a refused feed) after the models have had their chance to start again."""
407    ctx.gate = gate
408    ok, out, error, changed = False, None, None, False
409    try:
410        out = updater.run_update(ctx, **kwargs)
411        ok = out["exit_code"] == 0
412        changed = any(r.get("changed") for r in out["results"])
413        if show is not None:
414            show(out)                                    # what the update did comes before the questions about the models
415    except Exception as exc:                             # noqa: BLE001 - restarted below, then re-raised
416        error = exc
417    restarted = gate.finish(ok, changed) if gate.stopped else True
418    if error is not None:
419        raise error
420    out["models"] = gate.report()
421    if not restarted and out["exit_code"] in (0, 6):
422        out["exit_code"] = EXIT_NOT_RESTARTED if out["exit_code"] == 0 else out["exit_code"]
423    return out
424
425
426def build_context(root=None, feed: str | None = None, emit: Callable[[dict], None] = lambda event: None) -> "updater.Context":
427    """The update's context as `strata update` builds it: this computer's hardware, the trusted keys, the feed the person or the install uses."""
428    import argparse
429    from strata_cli import update_cmd
430    from strata_control import signing
431    base = Path(root) if root else ec.components_dir()
432    return updater.Context(components=base, source=update_cmd._feed_source(argparse.Namespace(feed=feed), base), trusted=signing.load_trusted_keys(),
433                           hardware=updater.detect_hardware(), emit=emit)
434
435
436def summary(out: dict) -> str:
437    """One plain sentence for what an update did, for a screen that has one line (the monitor)."""
438    parts = []
439    for r in out.get("results", []):
440        name = {"engine": "Engine", "control": "Control"}.get(r.get("component"), str(r.get("component")))
441        status = r.get("status")
442        if status == "updated":
443            parts.append(f"{name} is now {r.get('installed_after') if isinstance(r.get('installed_after'), str) else (r.get('installed_after') or {}).get('version', 'new')}")
444        elif status == "failed":
445            parts.append(f"{name} was not changed: {str(r.get('error', '')).rstrip('.')}")
446    text = "; ".join(parts) or "Nothing needed updating."
447    for r in (out.get("models") or {}).get("restarts", []):
448        text += " " + (r.get("message") or (f"{r['name']} is stopped." if not r.get("restarted") else f"{r['name']} is serving again."))
449    return text
450
451
452def run_flow(*, ask, say, emit: Callable[[dict], None] = lambda event: None, allow_stop: bool = False, start_again: bool = False,
453             feed: str | None = None, root=None, engine: bool = True, control: bool = True) -> dict:
454    """The whole opt-in update for a screen that cannot print (the monitor) or a host (the app): build the context, attach the gate, run, start the
455    models again.  Raises what the update raises (Declined, Busy, a refused feed): the caller shows ``str(exc)``."""
456    ctx = build_context(root, feed, emit)
457    gate = ModelGate(ask=ask, say=say, emit=emit, allow_stop=allow_stop, start_again=start_again)
458    return update_with_models(ctx, gate, engine=engine, control=control)