"""Offline desktop lifecycle test. Python is a synthetic backend/test runner only.""" import asyncio import json import os from pathlib import Path import secrets import socket import sys import tempfile import uuid def fixture(): from http.server import BaseHTTPRequestHandler, HTTPServer import threading assert "STRATA_NODE_TOKEN" not in os.environ host, port = os.environ["STRATA_WORKER_ENDPOINT"].rsplit(":", 1) class Handler(BaseHTTPRequestHandler): def log_message(self, *_): pass def do_GET(self): body = json.dumps({"status": "ok", "loaded": True, "model": os.environ["STRATA_WORKER_MODEL"]}).encode() self.send_response(200) self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def do_POST(self): self.rfile.read(int(self.headers.get("Content-Length", 0))) body = b'{"id":"fixture_response","status":"completed","output":[]}' self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) # Last-resort bound if the entire test runner is killed. timer = threading.Timer(40, lambda: os._exit(0)) timer.daemon = True timer.start() HTTPServer((host, int(port)), Handler).serve_forever() async def main(): root = Path(__file__).resolve().parents[2] binary = root / "desktop-core/target/debug" / ("strata-desktop.exe" if os.name == "nt" else "strata-desktop") dll = root / "desktop/bin/Debug/net10.0/Strata.Desktop.dll" env = os.environ.copy() env.pop("STRATA_NODE_ENDPOINT", None) env["STRATA_NODE_TOKEN"] = secrets.token_hex(32) node = app = None endpoint = None with socket.socket() as listener: listener.bind(("127.0.0.1", 0)) worker_port = listener.getsockname()[1] with tempfile.TemporaryDirectory(prefix="strata-lifecycle-") as temp: profile = Path(temp) / "profile.json" profile.write_text(json.dumps({ "schema_version": 1, "id": "fixture", "model": "synthetic", "executable": sys.executable, "args": [str(Path(__file__).resolve()), "--fixture"], "endpoint": f"127.0.0.1:{worker_port}", "startup_timeout_ms": 5000, })) async def launch(): process = await asyncio.create_subprocess_exec( str(binary), "node", "--listen", "127.0.0.1:0", "--token-env", "STRATA_NODE_TOKEN", "--worker-profile", str(profile), "--journal", str(Path(temp) / "operations.jsonl"), env=env, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL, ) address = json.loads(await asyncio.wait_for(process.stdout.readline(), 5))["endpoint"] return process, address async def cli(*args): process = await asyncio.create_subprocess_exec( str(binary), "worker", "--node", endpoint.removeprefix("http://"), "--token-env", "STRATA_NODE_TOKEN", *args, env=env, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) stdout, _ = await asyncio.wait_for(process.communicate(), 6) assert process.returncode == 0, "CLI failed" return json.loads(stdout) try: node, endpoint = await launch() env["STRATA_NODE_ENDPOINT"] = endpoint app = await asyncio.create_subprocess_exec( "dotnet", str(dll), "--self-check-worker", env=env, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) stdout, stderr = await asyncio.wait_for(app.communicate(), 30) if app.returncode != 0: raise RuntimeError("Desktop lifecycle failed: " + stderr.decode()[:500]) print(stdout.decode().strip()) operation = str(uuid.uuid4()) await cli("stop", operation) for _ in range(30): result = await cli("operation", operation) if result["status"] == "succeeded": break await asyncio.sleep(.1) assert result["status"] == "succeeded" node.kill() await node.wait() node, endpoint = await launch() assert (await cli("operation", operation))["status"] == "succeeded" assert (await cli("status"))["phase"] == "stopped" assert (await cli("stop", operation))["status"] == "succeeded" print("PASS: durable operation survived real node kill/restart; duplicate returned history without replay.") finally: if app and app.returncode is None: app.kill() await app.wait() if node and node.returncode is None: try: if endpoint: cmd = [str(binary), "worker", "--node", endpoint.removeprefix("http://"), "--token-env", "STRATA_NODE_TOKEN"] child = await asyncio.create_subprocess_exec( *cmd, "stop", str(uuid.uuid4()), env=env, stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL) await asyncio.wait_for(child.wait(), 6) for _ in range(30): child = await asyncio.create_subprocess_exec( *cmd, "status", env=env, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL) data, _ = await asyncio.wait_for(child.communicate(), 6) if child.returncode == 0 and json.loads(data)["phase"] == "stopped": break await asyncio.sleep(.1) finally: if node.returncode is None: node.kill() await node.wait() with socket.socket() as listener: assert listener.connect_ex(("127.0.0.1", worker_port)) != 0, "fixture listener leaked" if __name__ == "__main__": if sys.argv[1:] == ["--fixture"]: fixture() else: asyncio.run(main())