okami.mom/strata

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

Niko1221Portable monitor bundle: carries consoleinfo.py and overview.py (manifest schema 6), the plain Monitor runs when launch is not bundled, smokes accept the Overview's /metrics read, test derives the bundle's import closure3fa1b524d

main
12.1 KiB255 linesraw
1#!/usr/bin/env python3
2"""Exercise one portable Monitor bundle with a local fake server.
3
4Run this on each target OS/Python before release. It checks the client and the
5local bundle lifecycle. --interactive also checks packaged Textual rendering.
6Neither mode exercises the engine or GPU drivers.
7"""
8
9from __future__ import annotations
10
11import argparse
12import hashlib
13import json
14import platform
15import subprocess
16import sys
17import tempfile
18import threading
19import time
20from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
21from pathlib import Path
22
23
24BUILDER = Path(__file__).resolve().parents[1] / "packaging" / "monitor_bundle.py"
25INTERACTIVE_CODE = r'''
26import asyncio
27import io
28import json
29import sys
30
31sys.path.insert(0, sys.argv[1])
32from rich.console import Console
33from textual.widgets import Static
34from strata_cli.client import Endpoint
35from strata_cli.monitor import MonitorApp
36from strata_cli.dashboard import render_dashboard
37from strata_cli.detail_dashboard import render_detail_dashboard
38import strata_cli.monitor as monitor_module
39
40async def main():
41    source = str(monitor_module.__file__).replace("\\", "/")
42    bundle_path = sys.argv[1].replace("\\", "/")
43    if not source.startswith(bundle_path + "/"):
44        raise RuntimeError("interactive Monitor was not imported from the bundle")
45    app = MonitorApp(Endpoint(sys.argv[2]), None, interval=0.5,
46                     theme="dark", color="never", glyphs="ascii")
47    async with app.run_test(size=(110, 30)) as pilot:
48        for _ in range(30):
49            if app.connection_state == "connected":
50                break
51            await pilot.pause(0.1)
52        if app.connection_state != "connected":
53            raise RuntimeError("interactive Monitor did not connect")
54        output = io.StringIO()
55        Console(file=output, width=110, color_system=None).print(
56            app.query_one("#content", Static).content)
57        shown = output.getvalue()
58        if not all(title in shown for title in
59                   ("SERVING", "PERFORMANCE", "BATCHING / PARALLEL",
60                    "HARDWARE", "REQUESTS", "ACTIVITY")):
61            raise RuntimeError("packaged one-screen Overview is incomplete")
62        if (app.latest.get("model") or {}).get("id") != "portable-smoke-model":
63            raise RuntimeError("interactive Monitor showed the wrong model")
64        wide = io.StringIO()
65        Console(file=wide, width=140, color_system=None).print(render_dashboard(
66            app.latest, width=138, height=42, history=app.history,
67            glyphs="ascii", color=False))
68        if not all(title in wide.getvalue() for title in
69                   ("THROUGHPUT", "GPUS", "CONTEXT / BATCHING", "PARALLEL SLOTS", "REQUESTS")):
70            raise RuntimeError("packaged wide visual Overview is incomplete")
71        for view, title in (("serving", "REQUEST FLOW"), ("requests", "IN FLIGHT"),
72                            ("engine", "STAGES / HOST SPAN"), ("hardware", "GPU CARDS"),
73                            ("logs", "RECENT EVENT TIMELINE")):
74            detail = io.StringIO()
75            Console(file=detail, width=140, color_system=None).print(render_detail_dashboard(
76                app.latest, view, width=138, height=42, history=app.history,
77                glyphs="ascii", color=False))
78            if title not in detail.getvalue():
79                raise RuntimeError("packaged visual " + view + " page is incomplete")
80        await pilot.press("q")
81    print(json.dumps({"connected": True, "overview_panels": 6,
82                      "wide_visual": True, "visual_details": 5,
83                      "imported_from_bundle": True, "detached": True}))
84
85asyncio.run(main())
86'''
87
88
89def _run(*argv: str) -> dict:
90    result = subprocess.run([sys.executable, "-I", "-S", *argv],
91                            capture_output=True, text=True, timeout=20, check=False)
92    if result.returncode or result.stderr.strip():
93        raise RuntimeError(f"isolated command failed ({result.returncode}): {result.stderr.strip()}")
94    try:
95        return json.loads(result.stdout)
96    except json.JSONDecodeError as exc:
97        raise RuntimeError("isolated command did not return one JSON record") from exc
98
99
100def _server() -> tuple[ThreadingHTTPServer, list[str], threading.Event]:
101    paths: list[str] = []
102    malformed = threading.Event()
103
104    class TelemetryHandler(BaseHTTPRequestHandler):
105        def do_GET(self) -> None:
106            paths.append("GET " + self.path)
107            if self.path != "/v1/telemetry":
108                self.send_error(404)
109                return
110            body = json.dumps({
111                "schema_version": 1, "sampled_at": time.time(),
112                "instance": {"id": "portable-smoke", "state": "ready"},
113                "model": {"id": "portable-smoke-model", "loaded": True},
114                "work": {"active": 0, "queued": 0, "waiting": 0,
115                         "slots_requested": 1, "slots_effective": 1, "groups": 1,
116                         "slots": [{"slot": 0, "state": "idle", "group": 0}]},
117                "topology": {"mode": "single", "selected_devices": []},
118                "rates": {"output_tokens_server_counter": 0},
119                "devices": [], "quality": {"telemetry": "available"},
120            }).encode() if not malformed.is_set() else b"[" * 100000 + b"0" + b"]" * 100000
121            self.send_response(200)
122            self.send_header("Content-Type", "application/json")
123            self.send_header("Content-Length", str(len(body)))
124            self.end_headers()
125            self.wfile.write(body)
126
127        def _reject(self) -> None:
128            paths.append(self.command + " " + self.path)
129            self.send_error(405)
130
131        do_POST = do_PUT = do_PATCH = do_DELETE = do_HEAD = do_OPTIONS = do_TRACE = _reject
132
133        def log_message(self, *args: object) -> None:
134            pass
135
136    return ThreadingHTTPServer(("127.0.0.1", 0), TelemetryHandler), paths, malformed
137
138
139def _malformed_response(bundle: Path, url: str) -> None:
140    result = subprocess.run([sys.executable, "-I", "-S", str(bundle),
141                             "status", "--url", url, "--json"],
142                            capture_output=True, text=True, timeout=20, check=False)
143    if result.returncode != 3 or result.stderr:
144        raise RuntimeError("deeply nested telemetry escaped the client error boundary")
145    try:
146        response = json.loads(result.stdout)
147    except json.JSONDecodeError as exc:
148        raise RuntimeError("malformed telemetry did not return one JSON error") from exc
149    if (response.get("ok") is not False or
150            (response.get("error") or {}).get("message") != "server returned malformed JSON telemetry"):
151        raise RuntimeError("deeply nested telemetry returned an unexpected error")
152
153
154def _interactive(bundle: Path, url: str) -> dict:
155    result = subprocess.run([sys.executable, "-I", "-c", INTERACTIVE_CODE, str(bundle), url],
156                            capture_output=True, text=True, timeout=20, check=False)
157    if result.returncode:
158        raise RuntimeError(f"packaged interactive Monitor failed ({result.returncode}): "
159                           f"{result.stderr.strip()[-2000:]}")
160    try:
161        report = json.loads(result.stdout)
162    except json.JSONDecodeError as exc:
163        raise RuntimeError("interactive Monitor did not return one JSON record") from exc
164    if report != {"connected": True, "overview_panels": 6, "wide_visual": True,
165                  "visual_details": 5,
166                  "imported_from_bundle": True, "detached": True}:
167        raise RuntimeError("packaged interactive Monitor smoke was incomplete")
168    return report
169
170
171def smoke(bundle: Path, *, interactive: bool = False) -> dict:
172    bundle = bundle.resolve(strict=True)
173    manifest = _run(str(BUILDER), "verify", str(bundle))
174    expected_sha = hashlib.sha256(bundle.read_bytes()).hexdigest()
175    if manifest.get("sha256") != expected_sha:
176        raise RuntimeError("bundle digest changed after verification")
177
178    server, paths, malformed = _server()
179    worker = threading.Thread(target=server.serve_forever, daemon=True)
180    worker.start()
181    try:
182        url = f"http://127.0.0.1:{server.server_port}"
183        one_shot = _run(str(bundle), "monitor", "--url", url, "--once", "--json")
184        if (one_shot.get("ok") is not True or
185                (one_shot.get("snapshot") or {}).get("model", {}).get("id") != "portable-smoke-model"):
186            raise RuntimeError("one-shot monitor returned the wrong model or failed")
187
188        with tempfile.TemporaryDirectory(prefix="strata-portable-smoke-") as scratch:
189            target = Path(scratch) / "monitor"
190            preview = _run(str(BUILDER), "install", str(bundle), "--target", str(target), "--plan")
191            if preview.get("sha256") != expected_sha or preview.get("would_install") is not True:
192                raise RuntimeError("bundle install preview did not bind the candidate digest")
193            installed = _run(str(BUILDER), "install", str(bundle), "--target", str(target),
194                             "--if-candidate-sha256", expected_sha)
195            if installed.get("installed") is not True:
196                raise RuntimeError("bundle install did not complete")
197            installed_bundle = target / bundle.name
198            _run(str(BUILDER), "verify", str(installed_bundle))
199            status = _run(str(installed_bundle), "status", "--url", url, "--json")
200            if (status.get("ok") is not True or
201                    (status.get("snapshot") or {}).get("instance", {}).get("id") != "portable-smoke"):
202                raise RuntimeError("installed client did not reach the fake server")
203            removal = _run(str(BUILDER), "uninstall", "--target", str(target), "--plan")
204            if removal.get("sha256") != expected_sha or removal.get("would_remove") is not True:
205                raise RuntimeError("bundle removal preview did not bind the installed digest")
206            removed = _run(str(BUILDER), "uninstall", "--target", str(target),
207                           "--if-active-sha256", expected_sha)
208            if removed.get("removed") is not True or target.exists():
209                raise RuntimeError("bundle uninstall left an installed directory")
210        malformed.set()
211        _malformed_response(bundle, url)
212        malformed.clear()
213        interactive_report = _interactive(bundle, url) if interactive else None
214    finally:
215        server.shutdown()
216        server.server_close()
217        worker.join(timeout=5)
218
219    if (paths[:2] != ["GET /v1/telemetry", "GET /v1/telemetry"] or
220            any(path not in ("GET /v1/telemetry", "GET /metrics") for path in paths) or     # the interactive Overview also reads /metrics (404 here: it keeps the earlier Overview)
221            (interactive and len(paths) < 4) or (not interactive and len(paths) != 3)):
222        raise RuntimeError(f"unexpected client HTTP operations: {paths}")
223    report = {"schema_version": 1, "scope": "portable_monitor_stdlib_smoke",
224            "bundle_sha256": expected_sha, "python": platform.python_version(),
225            "platform": platform.platform(), "isolated_no_site_packages": True,
226            "one_shot_monitor": True, "installed_status": True,
227            "digest_pinned_install_uninstall": True,
228            "deep_json_error": True,
229            "http_gets": len(paths),
230            "other_http_methods": 0, "passed": True}
231    if interactive_report is not None:
232        report["interactive"] = interactive_report
233    return report
234
235
236def main() -> int:
237    ap = argparse.ArgumentParser(description=__doc__)
238    ap.add_argument("--bundle", type=Path, required=True)
239    ap.add_argument("--report", type=Path, required=True,
240                    help="new absolute JSON report file")
241    ap.add_argument("--interactive", action="store_true",
242                    help="also load the packaged Textual Overview in a headless terminal")
243    args = ap.parse_args()
244    if not args.report.is_absolute() or args.report.exists():
245        ap.error("--report must be a new absolute file path")
246    report = smoke(args.bundle, interactive=args.interactive)
247    with args.report.open("x", encoding="utf-8") as stream:
248        json.dump(report, stream, indent=2, sort_keys=True)
249        stream.write("\n")
250    print(json.dumps({"report": str(args.report), "passed": True}))
251    return 0
252
253
254if __name__ == "__main__":
255    raise SystemExit(main())