okami.mom/strata

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

Niko1221merge f-split into f-split-s6326e39118

main
18.5 KiB361 linesraw
1#!/usr/bin/env python3
2"""The installed Windows app, closed every way, with a stub engine: nothing may be left running.
3
4    python apps/desktop/scripts/app-close-matrix.py --install <folder the installer wrote> [--scenarios all] [--report out.json]
5
6For each case it starts the REAL installed `strata-desktop.exe` (its window opens), loads a stub engine through the host's API
7(profile + `runtime start` under Control's owner runtime, exactly the app's path), records every process of the tree (the app,
8the host, Control, the owner host, the server, the engine), ends the app one way, and asserts:
9  * no process of the tree is left, the engine's port is free, the runtime lease can be taken again;
10  * the engine got the clean stop where the way of closing allows one (normal close, window X);
11  * the next load of the same slot works (a lost owner's state is cleaned, not a blocker).
12It also proves a second launch focuses the open window and starts nothing, and that one app runs two engines and closes both.
13Everything per-user lives under a scratch folder; the stub engine is a script. No real engine ever runs.
14"""
15from __future__ import annotations
16
17import argparse
18import ctypes
19import json
20import os
21import subprocess
22import sys
23import tempfile
24import time
25import urllib.error
26import urllib.request
27from ctypes import wintypes
28from pathlib import Path
29
30ROOT = Path(__file__).resolve().parents[3]
31sys.path.insert(0, str(ROOT))
32
33import psutil  # noqa: E402
34
35from strata_control import procs, runtime  # noqa: E402
36from tests.terminal.lifecycle_matrix import install_fake_engine, port_open  # noqa: E402
37
38if os.name != "nt":
39    raise SystemExit("this matrix drives the Windows installer's app")
40
41user32 = ctypes.WinDLL("user32", use_last_error=True)
42WM_CLOSE = 0x0010
43
44
45def main_window(pid: int) -> int | None:
46    found = []
47
48    @ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
49    def visit(hwnd, _):
50        owner = wintypes.DWORD()
51        user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner))
52        if owner.value == pid and user32.IsWindowVisible(hwnd):
53            buf = ctypes.create_unicode_buffer(256)
54            user32.GetWindowTextW(hwnd, buf, 256)
55            if buf.value.strip() == "Strata":
56                found.append(hwnd)
57        return True
58    user32.EnumWindows(visit, 0)
59    return found[0] if found else None
60
61
62class Scratch:
63    def __init__(self, root: Path, install: Path):
64        self.root, self.install = root, install
65        self.components = root / "components"
66        self.models = root / "models"
67        self.mark = root / "mark"
68        for d in (self.components, self.models, self.mark, root / "local", root / "home", root / "appdata", root / "webview"):
69            d.mkdir(parents=True, exist_ok=True)
70        install_fake_engine(self.components)
71        from tools.strata_tokenizer import BYTE_TO_UNICODE
72        tok = self.models / "tokenizer"
73        tok.mkdir()
74        tokens = [BYTE_TO_UNICODE[i] for i in range(256)] + ["ab", "<|im_start|>", "<|im_end|>", "<|endoftext|>"]
75        (tok / "vocab.json").write_text(json.dumps({t: i for i, t in enumerate(tokens)}))
76        (tok / "merges.txt").write_text("a b")
77        (tok / "token_type.json").write_text(json.dumps([0] * 257 + [3, 3, 3]))
78        for name in ("stub", "stub2"):
79            (self.models / f"strata-{name}.json").write_text(json.dumps({
80                "exe": "component:strata-engine", "backend": "cuda", "tokenizer": str(tok), "args": [], "cwd": str(root),
81                "model_name": name, "host": "127.0.0.1", "port": 0}))
82        self.env = {**os.environ, "STRATA_COMPONENTS_DIR": str(self.components), "STRATA_PROFILE_DIR": str(root / "profiles"),
83                    "STRATA_RUNTIME_DIR": str(root / "runtime"), "STRATA_INSTALL_DIR": str(self.models),
84                    "STRATA_MODELS_DIR": str(root / "models-unused"), "STRATA_ENGINE_BACKEND": "cuda",
85                    "STRATA_HOME": str(root / "home"), "APPDATA": str(root / "appdata"), "LOCALAPPDATA": str(root / "local"),
86                    "WEBVIEW2_USER_DATA_FOLDER": str(root / "webview"), "FAKE_ENGINE_MARK": str(self.mark),
87                    "FAKE_ENGINE_SLOW_STEPS": "0", "PYTHONDONTWRITEBYTECODE": "1"}
88        self.env.pop("STRATA_API_KEY", None)
89        for key in ("STRATA_COMPONENTS_DIR", "STRATA_PROFILE_DIR", "STRATA_RUNTIME_DIR", "LOCALAPPDATA", "STRATA_ENGINE_BACKEND",
90                    "STRATA_NO_ACQUIRE", "FAKE_ENGINE_MARK"):
91            os.environ[key] = self.env.get(key, "1")          # this process reads the same runtime and records folders
92
93
94class App:
95    def __init__(self, scratch: Scratch):
96        self.s = scratch
97        self.proc = subprocess.Popen([str(scratch.install / "strata-desktop.exe")], cwd=scratch.install, env=scratch.env,
98                                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
99        self.base = None
100
101    def host(self):
102        for child in psutil.Process(self.proc.pid).children(recursive=True):
103            if child.name().lower() == "node.exe":
104                return child
105        return None
106
107    def wait_up(self, seconds=90):
108        deadline = time.monotonic() + seconds
109        while time.monotonic() < deadline:
110            if self.proc.poll() is not None:
111                raise RuntimeError(f"the app exited with {self.proc.returncode}")
112            try:
113                host = self.host()
114                if host:
115                    for c in host.net_connections(kind="tcp"):
116                        if c.status == "LISTEN" and c.laddr.ip == "127.0.0.1":
117                            base = f"http://127.0.0.1:{c.laddr.port}"
118                            try:
119                                if urllib.request.urlopen(base + "/api/health", timeout=2).status == 200 and main_window(self.proc.pid):
120                                    self.base = base
121                                    return
122                            except OSError:
123                                pass
124            except psutil.Error:
125                pass
126            time.sleep(0.5)
127        raise RuntimeError("the app did not come up")
128
129    def call(self, path, method="GET", body=None):
130        req = urllib.request.Request(self.base + path, method=method, data=None if body is None else json.dumps(body).encode(),
131                                     headers={"content-type": "application/json"})
132        try:
133            with urllib.request.urlopen(req, timeout=120) as r:
134                return json.loads(r.read() or b"null")
135        except urllib.error.HTTPError as exc:
136            raise RuntimeError(f"{method} {path} -> {exc.code} {exc.read()[:300]!r}") from None
137
138    def load(self, model, multiple=False):
139        self.call("/api/native?refresh=1")
140        started = self.call("/api/native/operations", "POST", {"kind": "load", "args": {"model": model, **({"multiple": True} if multiple else {})}})
141        deadline = time.monotonic() + 180
142        while time.monotonic() < deadline:
143            state = self.call("/api/native")
144            job = next((j for j in state["jobs"] if j["id"] == started["id"]), None)
145            if job and job["state"] != "running":
146                if job["state"] != "done":
147                    raise RuntimeError(f"load {model}: {job['state']} {job.get('error')}")
148                return state
149            time.sleep(0.3)
150        raise RuntimeError("load did not finish")
151
152
153def tree_of(app: App, slots=("app-1",)) -> tuple[list[procs.Ident], list[int]]:
154    idents, ports = [], []
155    members = [psutil.Process(app.proc.pid), *psutil.Process(app.proc.pid).children(recursive=True)]
156    pids = {p.pid for p in members}
157    for slot in slots:
158        state = runtime._read_state(slot)
159        if state:
160            pids.add(state["host_pid"])
161    for r in procs.records():
162        if r.get("profile") in slots:                 # the app's own slots; a Terminal service is not part of the app's tree
163            pids.add(r["pid"])
164    for pid in pids:
165        token = procs.start_token(pid)
166        if token:
167            idents.append(procs.Ident(pid, token, tuple(procs.command_line(pid) or [])))
168    return idents, ports
169
170
171def survivors(idents):
172    return [f"{i.pid} {' '.join(i.cmd)[:80]}" for i in idents if procs.start_token(i.pid) == i.token]
173
174
175def wait_gone(idents, seconds):
176    deadline = time.monotonic() + seconds
177    left = survivors(idents)
178    while left and time.monotonic() < deadline:
179        time.sleep(0.25)
180        left = survivors(idents)
181    return left
182
183
184def lease_free() -> bool:
185    try:
186        fd = runtime.acquire_activity_lease(shared=False)
187    except Exception:  # noqa: BLE001
188        return False
189    runtime._unlock_file(fd)
190    os.close(fd)
191    return True
192
193
194def control(scratch: Scratch, *argv: str, timeout: int = 300) -> dict:
195    py = scratch.install / "control" / "python" / "python.exe"
196    out = subprocess.run([str(py), str(scratch.install / "control" / "strata.py"), *argv, "--output", "json"],
197                         env={**scratch.env, "PYTHONNOUSERSITE": "1", "STRATA_NO_ACQUIRE": "1"},
198                         capture_output=True, text=True, timeout=timeout)
199    try:
200        return json.loads(out.stdout)
201    except ValueError:
202        return {"ok": False, "raw": out.stdout[-300:] + out.stderr[-300:]}
203
204
205def stop_cli(scratch: Scratch, slot: str) -> dict:
206    py = scratch.install / "control" / "python" / "python.exe"
207    out = subprocess.run([str(py), str(scratch.install / "control" / "strata.py"), "runtime", "stop", "--profile", slot, "--wait", "30",
208                          "--output", "json"], env={**scratch.env, "PYTHONNOUSERSITE": "1", "STRATA_NO_ACQUIRE": "1"},
209                         capture_output=True, text=True, timeout=120)
210    try:
211        return json.loads(out.stdout)
212    except ValueError:
213        return {"state": "?", "raw": out.stdout[-200:] + out.stderr[-200:]}
214
215
216def case(name: str, install: Path, how: str) -> dict:
217    with tempfile.TemporaryDirectory(prefix="strata-app-matrix-", ignore_cleanup_errors=True) as tmp:
218        saved = dict(os.environ)
219        scratch = Scratch(Path(tmp), install)
220        app = App(scratch)
221        problems, note = [], ""
222        try:
223            app.wait_up()
224            slots = ("app-1", "app-2") if how == "two-engines" else ("app-1",)
225            terminal = None
226            if how == "window-x-terminal-engine":
227                # an engine the Terminal started (its own profile, no tie to the app) must survive the app's close
228                control(scratch, "profile", "create", "terminal-1", "--from-config", str(scratch.models / "strata-stub2.json"))
229                terminal = control(scratch, "runtime", "start", "--profile", "terminal-1", "--wait", "60")
230                if terminal.get("state") != "ready":
231                    raise RuntimeError(f"the Terminal's service did not start: {terminal}")
232                terminal_pids = {r["pid"] for r in procs.records(profile="terminal-1")} | {runtime._read_state("terminal-1")["host_pid"]}
233            state = app.load("stub")
234            if how == "two-engines":
235                state = app.load("stub2", multiple=True)
236            engine_ports = [i["port"] for i in state["instances"]]
237            idents, _ = tree_of(app, slots)
238            kinds = sorted({("engine" if "engine" in " ".join(i.cmd) else "server" if "serve.server" in " ".join(i.cmd) else
239                             "owner" if "strata_control.runtime" in " ".join(i.cmd) else "app" if "strata-desktop" in i.cmd[0].lower()
240                             else "host" if "node" in i.cmd[0].lower() else "other") for i in idents})
241            note = f"tree {len(idents)} processes: {', '.join(kinds)}; engine ports {engine_ports}"
242            t0 = time.monotonic()
243            if how == "normal-close":
244                subprocess.run(["taskkill", "/PID", str(app.proc.pid)], capture_output=True)
245            elif how in ("window-x", "two-engines", "window-x-terminal-engine"):
246                hwnd = main_window(app.proc.pid)
247                if not hwnd:
248                    raise RuntimeError("no main window")
249                user32.PostMessageW(hwnd, WM_CLOSE, 0, 0)
250            elif how == "kill-app":
251                subprocess.run(["taskkill", "/F", "/PID", str(app.proc.pid)], capture_output=True)
252            elif how == "host-crash":
253                host = app.host()
254                subprocess.run(["taskkill", "/F", "/PID", str(host.pid)], capture_output=True)
255            elif how == "second-launch":
256                second = subprocess.Popen([str(install / "strata-desktop.exe")], cwd=install, env=scratch.env,
257                                          stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
258                try:
259                    code = second.wait(timeout=30)
260                except subprocess.TimeoutExpired:
261                    second.kill()
262                    problems.append("the second launch did not exit")
263                    code = None
264                time.sleep(2)
265                hosts = [p for p in psutil.process_iter(["name", "pid"]) if p.info["name"].lower() == "node.exe"
266                         and (p.parent() and p.parent().pid == app.proc.pid)]
267                apps = [p for p in psutil.process_iter(["name"]) if p.info["name"].lower() == "strata-desktop.exe"]
268                if app.proc.poll() is not None:
269                    problems.append("the first app went away")
270                if len(apps) != 1:
271                    problems.append(f"{len(apps)} app processes (want 1)")
272                if len(hosts) != 1:
273                    problems.append(f"{len(hosts)} hosts under the first app (want 1)")
274                after, _ = tree_of(app, slots)
275                new = [i for i in after if i.pid not in {x.pid for x in idents}]
276                if new:
277                    problems.append(f"the second launch started: {[' '.join(i.cmd)[:60] for i in new]}")
278                note += f"; second launch exit code {code}, app processes {len(apps)}, hosts {len(hosts)}"
279                subprocess.run(["taskkill", "/PID", str(app.proc.pid)], capture_output=True)
280            if how == "host-crash":
281                # the shell and its window stay (nothing here restarts a dead host); the host, Control's owner, the server and
282                # the engine must not
283                idents = [i for i in idents if any(k in " ".join(i.cmd) for k in ("strata_control.runtime", "serve.server", "engine", "node.exe"))]
284            left = wait_gone(idents, 90)
285            if left:
286                problems.append(f"processes left: {left}")
287            for port in engine_ports:
288                deadline = time.monotonic() + 10
289                while port_open(port) and time.monotonic() < deadline:
290                    time.sleep(0.2)
291                if port_open(port):
292                    problems.append(f"engine port {port} still open")
293            if terminal is None and not lease_free():
294                problems.append("lease still held")
295            marks = sorted(p.name for p in scratch.mark.iterdir())
296            if terminal is not None:
297                status = control(scratch, "runtime", "status", "--profile", "terminal-1")
298                alive_pids = [p for p in terminal_pids if procs.start_token(p)]
299                if status.get("state") != "ready" or len(alive_pids) != len(terminal_pids):
300                    problems.append(f"closing the app disturbed the Terminal's service: {status.get('state')}, alive {alive_pids} of {sorted(terminal_pids)}")
301                note += f"; the Terminal's service is {status.get('state')} after the app closed"
302                stopped = control(scratch, "runtime", "stop", "--profile", "terminal-1", "--wait", "30")
303                if stopped.get("state") != "stopped" or [p for p in terminal_pids if procs.start_token(p)]:
304                    problems.append(f"the Terminal's service did not stop on request: {stopped}")
305                time.sleep(1)
306                if not lease_free():
307                    problems.append("lease still held after the Terminal's service stopped")
308            if how in ("normal-close", "window-x", "two-engines", "second-launch", "window-x-terminal-engine") and not ({"quit", "eof"} & set(marks)):
309                problems.append(f"the engine was not stopped the clean way (marks {marks})")
310            seconds = round(time.monotonic() - t0, 1)
311            if how == "host-crash":
312                subprocess.run(["taskkill", "/PID", str(app.proc.pid)], capture_output=True)
313                note += "; the app shell stays open after a host crash (by design today)"
314            # the slot must be usable again: stopping a lost owner's slot cleans its state; nothing blocks the next load
315            for slot in slots:
316                res = stop_cli(scratch, slot)
317                already = "not managed or is stopped" in json.dumps(res)       # nothing was left to stop: the clean outcome
318                if res.get("state") not in ("stopped",) and not already:
319                    problems.append(f"runtime stop {slot} after the close: {res}")
320                if runtime._read_state(slot) is not None:
321                    problems.append(f"state of {slot} left behind")
322            return {"name": f"app-{how}", "ok": not problems, "problems": problems, "seconds": seconds, "marks": marks, "note": note}
323        except Exception as exc:  # noqa: BLE001
324            return {"name": f"app-{how}", "ok": False, "problems": [f"{type(exc).__name__}: {exc}"] + problems, "note": note}
325        finally:
326            for p in psutil.process_iter(["name", "exe"]):
327                try:
328                    if (p.info["exe"] or "").lower().startswith(str(install).lower()):
329                        p.kill()
330                except psutil.Error:
331                    pass
332            for r in procs.records():
333                try:
334                    psutil.Process(r["pid"]).kill()
335                except psutil.Error:
336                    pass
337            os.environ.clear(); os.environ.update(saved)
338
339
340SCENARIOS = ["normal-close", "window-x", "window-x-terminal-engine", "kill-app", "host-crash", "second-launch", "two-engines"]
341
342
343def main() -> int:
344    ap = argparse.ArgumentParser()
345    ap.add_argument("--install", required=True)
346    ap.add_argument("--scenarios", default="all")
347    ap.add_argument("--report")
348    a = ap.parse_args()
349    names = SCENARIOS if a.scenarios == "all" else a.scenarios.split(",")
350    results = []
351    for how in names:
352        r = case(how, Path(a.install), how)
353        results.append(r)
354        print(("PASS " if r["ok"] else "FAIL ") + r["name"], r.get("seconds", ""), r.get("problems") or "", r.get("note", ""), flush=True)
355    if a.report:
356        Path(a.report).write_text(json.dumps({"platform": "windows", "engine": "fake", "results": results}, indent=1), encoding="utf-8")
357    return 0 if all(r["ok"] for r in results) else 1
358
359
360if __name__ == "__main__":
361    raise SystemExit(main())