okami.mom/strata

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

Niko1221Merge f-0250-tui into f-0243-rel0c53372a0

main
11.6 KiB247 linesraw
1#!/usr/bin/env python3
2"""Smoke-test a terminal archive in a clean environment.
3
4    python packaging/smoke_terminal.py release/artifacts/strata-terminal-0.1.45-windows-x86_64.zip [--json out.json]
5
6The archive is extracted into a fresh folder whose name has a space in it (so a moved or awkward path is part of
7the test), and every command runs with a PATH that holds no Python (Windows: System32 only; POSIX: a folder with
8dirname/readlink/cat and nothing else), no PYTHON* variables, a private user profile, and a dead HTTP proxy so that
9anything reaching for the internet fails loudly. It then checks, through the bundled launcher:
10
11    strata --version              must name the interpreter inside the extracted folder
12    strata doctor                 read-only inventory
13    strata profile list           saved profiles (none in a clean profile)
14    strata serve --engine mock    the server on the scripted engine: /health, /v1/models and a chat answer
15    strata install               must refuse (no installer in the archive) with exit 5, not fetch anything
16
17The script is one foreground run: the mock server it starts is a child that is stopped (whole tree) before it exits.
18"""
19
20from __future__ import annotations
21
22import argparse
23import json
24import os
25import shutil
26import socket
27import subprocess
28import sys
29import tarfile
30import tempfile
31import time
32import urllib.request
33import zipfile
34from pathlib import Path
35
36
37def free_port() -> int:
38    with socket.socket() as s:
39        s.bind(("127.0.0.1", 0))
40        return s.getsockname()[1]
41
42
43def extract(archive: Path, dest: Path) -> Path:
44    if archive.suffix == ".zip":
45        with zipfile.ZipFile(archive) as zf:
46            zf.extractall(dest)
47    else:
48        with tarfile.open(archive) as tf:
49            tf.extractall(dest)
50    roots = [p for p in dest.iterdir() if p.is_dir()]
51    if len(roots) != 1:
52        raise SystemExit(f"expected one folder in the archive, found {[p.name for p in roots]}")
53    return roots[0]
54
55
56def clean_env(sandbox: Path) -> tuple[dict, list[str]]:
57    home = sandbox / "home"
58    home.mkdir(parents=True, exist_ok=True)
59    if os.name == "nt":
60        system32 = str(Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32")
61        env = {"PATH": system32, "SystemRoot": os.environ.get("SystemRoot", r"C:\Windows"),
62               "SystemDrive": os.environ.get("SystemDrive", "C:"), "COMSPEC": os.environ.get("COMSPEC", ""),
63               "TEMP": str(sandbox / "tmp"), "TMP": str(sandbox / "tmp"), "USERPROFILE": str(home),
64               "APPDATA": str(home / "AppData" / "Roaming"), "LOCALAPPDATA": str(home / "AppData" / "Local"),
65               "HOMEDRIVE": "C:", "HOMEPATH": str(home)[2:], "PATHEXT": ".COM;.EXE;.BAT;.CMD"}
66        shell = ["cmd", "/c"]
67    else:
68        minimal = sandbox / "minbin"
69        minimal.mkdir(parents=True, exist_ok=True)
70        for tool in ("dirname", "readlink", "cat", "uname", "basename"):
71            found = shutil.which(tool)
72            if found and not (minimal / tool).exists():
73                (minimal / tool).symlink_to(found)
74        env = {"PATH": str(minimal), "HOME": str(home), "TMPDIR": str(sandbox / "tmp"),
75               "XDG_CONFIG_HOME": str(home / ".config"), "LANG": "C.UTF-8"}
76        shell = []
77    (sandbox / "tmp").mkdir(parents=True, exist_ok=True)
78    # anything that reaches for the internet fails loudly; the loopback server is unaffected
79    env.update({"HTTP_PROXY": "http://127.0.0.1:9", "HTTPS_PROXY": "http://127.0.0.1:9",
80                "NO_PROXY": "127.0.0.1,localhost", "PIP_NO_INDEX": "1"})
81    return env, shell
82
83
84def launcher(root: Path) -> list[str]:
85    return [str(root / "bin" / "strata.cmd")] if os.name == "nt" else [str(root / "bin" / "strata")]
86
87
88def as_command(args: list[str]):
89    """What to hand to subprocess. A .cmd launcher in a folder with a space needs cmd's /s rule (strip only the outer
90    pair of quotes), the way a user's shell does it."""
91    if os.name != "nt":
92        return args
93    return 'cmd.exe /d /s /c "' + subprocess.list2cmdline(args) + '"'
94
95
96def run(cmd: list[str], env: dict, cwd: Path, timeout: int = 120) -> dict:
97    t = time.time()
98    r = subprocess.run(as_command(cmd), env=env, cwd=str(cwd), capture_output=True, text=True, timeout=timeout)
99    return {"cmd": " ".join(cmd), "rc": r.returncode, "seconds": round(time.time() - t, 2),
100            "stdout": r.stdout, "stderr": r.stderr}
101
102
103def inside_archive(root: Path, text: str) -> bool:
104    """The interpreter the launcher reported is the one in the extracted folder (8.3 and long forms of a path both)."""
105    tail = (root.name + os.sep + ("python" + os.sep + "python.exe" if os.name == "nt" else "python/bin/python3")).lower()
106    return tail in text.lower().replace("/", os.sep)
107
108
109def kill_tree(proc: subprocess.Popen) -> None:
110    if proc.poll() is not None:
111        return
112    if os.name == "nt":
113        subprocess.run(["taskkill", "/T", "/F", "/PID", str(proc.pid)], capture_output=True)
114    else:
115        proc.terminate()
116    try:
117        proc.wait(timeout=20)
118    except subprocess.TimeoutExpired:
119        proc.kill()
120
121
122def http(url: str, body: dict | None = None, timeout: float = 20) -> tuple[int, str]:
123    # the dead proxy is for the child processes; this client talks to loopback directly
124    opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
125    req = urllib.request.Request(url, data=json.dumps(body).encode() if body is not None else None,
126                                 headers={"Content-Type": "application/json"})
127    with opener.open(req, timeout=timeout) as resp:
128        return resp.status, resp.read().decode("utf-8", "replace")
129
130
131def main() -> int:
132    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
133    ap.add_argument("archive")
134    ap.add_argument("--json", help="write the full results here")
135    ap.add_argument("--keep", action="store_true", help="keep the extracted folder")
136    a = ap.parse_args()
137    archive = Path(a.archive).resolve()
138    sandbox = Path(tempfile.mkdtemp(prefix="strata smoke "))
139    results: dict = {"archive": archive.name, "sandbox_has_space": " " in str(sandbox), "checks": {}}
140    ok = True
141    proc = None
142    try:
143        root = extract(archive, sandbox / "extract")
144        env, _ = clean_env(sandbox)
145        results["root"] = str(root)
146        strata = launcher(root)
147
148        # no other Python can be found from this environment
149        if os.name == "nt":
150            found = {"rc": 1, "stdout": "", "stderr": ""}
151            for name in ("python", "py", "python3"):
152                w = subprocess.run(["where", name], env=env, capture_output=True, text=True)
153                if w.returncode == 0 and w.stdout.strip():
154                    found = {"rc": 0, "stdout": w.stdout, "stderr": ""}
155        else:
156            found = {"rc": 1, "stdout": "", "stderr": ""}
157            for name in ("python", "python3", "py"):
158                if shutil.which(name, path=env["PATH"]):
159                    found = {"rc": 0, "stdout": name, "stderr": ""}
160        results["other_python_on_path"] = found["rc"] == 0 and bool(found["stdout"].strip())
161        ok &= not results["other_python_on_path"]
162
163        def check(name: str, cond: bool, **info) -> None:
164            nonlocal ok
165            results["checks"][name] = {"ok": bool(cond), **info}
166            ok &= bool(cond)
167            print(("PASS " if cond else "FAIL ") + name)
168
169        r = run([*strata, "--version"], env, root)
170        inside = inside_archive(root, r["stdout"])
171        check("version", r["rc"] == 0 and r["stdout"].startswith("strata ") and inside,
172              rc=r["rc"], output=r["stdout"].strip(), interpreter_inside_archive=inside)
173
174        if os.name == "nt":
175            ps = Path(env["SystemRoot"]) / "System32" / "WindowsPowerShell" / "v1.0" / "powershell.exe"
176            r = run([str(ps), "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(root / "bin" / "strata.ps1"),
177                     "--version"], env, root)
178            check("version (strata.ps1)", r["rc"] == 0 and inside_archive(root, r["stdout"]),
179                  rc=r["rc"], output=r["stdout"].strip(), stderr=r["stderr"].strip()[:200])
180
181        r = run([*strata, "doctor"], env, root)
182        check("doctor", r["rc"] == 0, rc=r["rc"], output=r["stdout"].strip()[:600])
183
184        r = run([*strata, "profile", "list"], env, root)
185        check("profile list", r["rc"] == 0, rc=r["rc"], output=r["stdout"].strip()[:300])
186
187        r = run([*strata, "install"], env, root)
188        # since 0.2.4 the Terminal carries setup.py: with no keyboard it stops at the first question, in plain words and with a non-zero code
189        # (an older Terminal without the installer answers rc 5 "no installer")
190        stopped = r["rc"] not in (0, None) and ("no installer" in r["stderr"] or "setup stopped" in (r["stdout"] + r["stderr"]).lower())
191        check("install stops without a keyboard (or without an installer)", stopped, rc=r["rc"], stderr=r["stderr"].strip()[:300],
192              output=r["stdout"].strip()[-300:])
193
194        # serve on the mock engine: a fake run config (the mock never loads it), a free port, a chat answer
195        cfg_dir = sandbox / "cfg"
196        cfg_dir.mkdir()
197        (cfg_dir / "engine.exe").write_bytes(b"not an engine")
198        (cfg_dir / "tokenizer.json").write_text("{}", encoding="utf-8")
199        cfg = cfg_dir / "strata-mock.json"
200        cfg.write_text(json.dumps({"exe": str(cfg_dir / "engine.exe"), "tokenizer": str(cfg_dir / "tokenizer.json"),
201                                   "args": [], "model_name": "mock"}), encoding="utf-8")
202        port = free_port()
203        log = sandbox / "serve.log"
204        with log.open("wb") as lf:
205            proc = subprocess.Popen(as_command([*strata, "serve", "--profile", str(cfg), "--engine", "mock",
206                                                "--port", str(port), "--host", "127.0.0.1"]),
207                                    env=env, cwd=str(root), stdout=lf, stderr=subprocess.STDOUT,
208                                    stdin=subprocess.DEVNULL)
209        health = None
210        deadline = time.time() + 60
211        while time.time() < deadline and proc.poll() is None:
212            try:
213                status, body = http(f"http://127.0.0.1:{port}/health", timeout=3)
214                if status == 200:
215                    health = body
216                    break
217            except OSError:
218                time.sleep(0.5)
219        check("serve: /health", health is not None, port=port, body=(health or "")[:200],
220              exited=proc.poll(), log=log.read_text(errors="replace")[-600:] if health is None else "")
221        if health is not None:
222            status, models = http(f"http://127.0.0.1:{port}/v1/models")
223            check("serve: /v1/models", status == 200, body=models[:200])
224            status, chat = http(f"http://127.0.0.1:{port}/v1/chat/completions",
225                                {"model": "mock", "messages": [{"role": "user", "content": "hello"}],
226                                 "max_tokens": 16})
227            text = ""
228            try:
229                msg = json.loads(chat)["choices"][0]["message"]
230                text = (msg.get("content") or "") + (msg.get("reasoning_content") or "")
231            except (ValueError, KeyError, IndexError, TypeError):
232                pass
233            check("serve: chat answer", status == 200 and bool(text.strip()), answer=text[:200], body=chat[:400])
234    finally:
235        if proc is not None:
236            kill_tree(proc)
237        if not a.keep:
238            shutil.rmtree(sandbox, ignore_errors=True)
239    results["ok"] = ok
240    if a.json:
241        Path(a.json).write_text(json.dumps(results, indent=2), encoding="utf-8")
242    print("SMOKE " + ("OK" if ok else "FAILED"))
243    return 0 if ok else 1
244
245
246if __name__ == "__main__":
247    sys.exit(main())