361 lines
14 KiB
Python
361 lines
14 KiB
Python
|
|
"""Behavioral checks for the local Windows process launcher (no remote DB or model calls)."""
|
||
|
|
|
||
|
|
import importlib.util
|
||
|
|
import json
|
||
|
|
import os
|
||
|
|
import socket
|
||
|
|
from pathlib import Path
|
||
|
|
import subprocess
|
||
|
|
import sys
|
||
|
|
import tempfile
|
||
|
|
import threading
|
||
|
|
import time
|
||
|
|
import unittest
|
||
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||
|
|
from http.cookiejar import CookieJar
|
||
|
|
from urllib.request import HTTPCookieProcessor, Request, build_opener
|
||
|
|
|
||
|
|
|
||
|
|
LAUNCHER = Path(__file__).resolve().parents[1] / "local_dev.py"
|
||
|
|
|
||
|
|
|
||
|
|
def load_launcher():
|
||
|
|
spec = importlib.util.spec_from_file_location("cmvr_local_dev", LAUNCHER)
|
||
|
|
module = importlib.util.module_from_spec(spec)
|
||
|
|
sys.modules[spec.name] = module
|
||
|
|
spec.loader.exec_module(module)
|
||
|
|
return module
|
||
|
|
|
||
|
|
|
||
|
|
class LocalDevTests(unittest.TestCase):
|
||
|
|
@classmethod
|
||
|
|
def setUpClass(cls):
|
||
|
|
if not LAUNCHER.exists():
|
||
|
|
raise AssertionError("local launcher has not been implemented")
|
||
|
|
cls.dev = load_launcher()
|
||
|
|
|
||
|
|
def setUp(self):
|
||
|
|
self.temp = tempfile.TemporaryDirectory()
|
||
|
|
self.root = Path(self.temp.name)
|
||
|
|
self.processes = []
|
||
|
|
|
||
|
|
def tearDown(self):
|
||
|
|
if hasattr(self, "test_cleanup"):
|
||
|
|
self.test_cleanup()
|
||
|
|
for process in self.processes:
|
||
|
|
if process.poll() is None:
|
||
|
|
process.terminate()
|
||
|
|
process.wait(timeout=10)
|
||
|
|
self.temp.cleanup()
|
||
|
|
|
||
|
|
def child(self, code="import time; time.sleep(60)"):
|
||
|
|
process = subprocess.Popen(
|
||
|
|
[sys._base_executable, "-c", code],
|
||
|
|
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
|
||
|
|
)
|
||
|
|
self.processes.append(process)
|
||
|
|
return process
|
||
|
|
|
||
|
|
@unittest.skipUnless(os.name == "nt", "Windows process identity")
|
||
|
|
def test_failed_pid_handshake_still_shuts_down_the_started_api(self):
|
||
|
|
# Failure before readiness must still send the API stop marker, even if no interpreter PID arrives.
|
||
|
|
stop_file = self.root / ".local" / "api.stop"
|
||
|
|
identity_file = self.root / ".local" / "api.pid"
|
||
|
|
actual_pid = self.root / "actual.pid"
|
||
|
|
code = (
|
||
|
|
"from pathlib import Path; import time,os; Path(r'"
|
||
|
|
+ str(actual_pid)
|
||
|
|
+ "').write_text(str(os.getpid())); p=Path(r'"
|
||
|
|
+ str(stop_file)
|
||
|
|
+ "'); "
|
||
|
|
+ "exec('while not p.exists(): time.sleep(0.05)')"
|
||
|
|
)
|
||
|
|
|
||
|
|
def cleanup_api():
|
||
|
|
stop_file.touch()
|
||
|
|
if actual_pid.exists():
|
||
|
|
pid = int(actual_pid.read_text())
|
||
|
|
for _ in range(50):
|
||
|
|
if self.dev.process_identity(pid) is None:
|
||
|
|
return
|
||
|
|
time.sleep(0.05)
|
||
|
|
|
||
|
|
self.test_cleanup = cleanup_api
|
||
|
|
services = [
|
||
|
|
self.dev.Service(
|
||
|
|
"api",
|
||
|
|
[sys._base_executable, "-c", code],
|
||
|
|
self.root,
|
||
|
|
"http://127.0.0.1:1",
|
||
|
|
stop_file,
|
||
|
|
identity_file,
|
||
|
|
)
|
||
|
|
]
|
||
|
|
with self.assertRaises(RuntimeError):
|
||
|
|
self.dev.start_services(self.root, services, dict(os.environ), timeout=0.2)
|
||
|
|
state = json.loads((self.root / ".local/dev-processes.json").read_text())
|
||
|
|
self.assertEqual(state["processes"], {})
|
||
|
|
self.assertIsNone(
|
||
|
|
self.dev.process_identity(int(actual_pid.read_text())),
|
||
|
|
"API leaked after a failed PID handshake",
|
||
|
|
)
|
||
|
|
|
||
|
|
@unittest.skipUnless(os.name == "nt", "Windows API wrapper")
|
||
|
|
def test_real_venv_api_with_live_sse_shuts_down_and_completes_lifespan(self):
|
||
|
|
# Exercise the actual venv redirector + uvicorn lifespan on isolated SQLite, with no model/DB network access.
|
||
|
|
with socket.socket() as listener:
|
||
|
|
listener.bind(("127.0.0.1", 0))
|
||
|
|
port = listener.getsockname()[1]
|
||
|
|
local = self.root / ".local"
|
||
|
|
local.mkdir()
|
||
|
|
stop_file, identity_file = local / "api.stop", local / "api.pid"
|
||
|
|
environment = dict(os.environ)
|
||
|
|
environment.update(
|
||
|
|
CMVR_MODE="preview",
|
||
|
|
DATABASE_URL="sqlite+aiosqlite:///" + (self.root / "test.sqlite3").as_posix(),
|
||
|
|
WORKSPACE_ROOT=str(self.root / "workspace"),
|
||
|
|
ADMIN_USERNAME="local-launcher-test",
|
||
|
|
ADMIN_PASSWORD="Local-Launcher-Test-194!",
|
||
|
|
COOKIE_SECURE="false",
|
||
|
|
PUBLIC_ACCESS="false",
|
||
|
|
RUN_COORDINATOR="true",
|
||
|
|
INFERENCE_BASE_URL="",
|
||
|
|
INFERENCE_API_KEY_FILE="",
|
||
|
|
QWEN_BASE_URL="",
|
||
|
|
QWEN_API_KEY="",
|
||
|
|
TTS_BASE_URL="",
|
||
|
|
GPU_STATUS_PATH="",
|
||
|
|
GPU_SCHEDULER_PATH="",
|
||
|
|
)
|
||
|
|
environment["PYTHONUTF8"] = "1"
|
||
|
|
repo = LAUNCHER.parent.parent
|
||
|
|
code = (
|
||
|
|
"import sys;sys.path.insert(0,"
|
||
|
|
+ repr(str(repo))
|
||
|
|
+ ");from scripts.local_dev import serve_api;serve_api("
|
||
|
|
+ repr(str(stop_file))
|
||
|
|
+ ","
|
||
|
|
+ repr(str(identity_file))
|
||
|
|
+ ",port="
|
||
|
|
+ str(port)
|
||
|
|
+ ")"
|
||
|
|
)
|
||
|
|
with (local / "api.log").open("wb") as log:
|
||
|
|
process = subprocess.Popen(
|
||
|
|
[str(repo / "backend/.venv/Scripts/python.exe"), "-c", code],
|
||
|
|
cwd=repo,
|
||
|
|
env=environment,
|
||
|
|
stdout=log,
|
||
|
|
stderr=subprocess.STDOUT,
|
||
|
|
creationflags=subprocess.CREATE_NO_WINDOW,
|
||
|
|
)
|
||
|
|
self.processes.append(process)
|
||
|
|
deadline = time.monotonic() + 15
|
||
|
|
while not identity_file.exists() and process.poll() is None and time.monotonic() < deadline:
|
||
|
|
time.sleep(0.05)
|
||
|
|
self.assertTrue(
|
||
|
|
identity_file.exists(), "real API wrapper failed before reporting its interpreter PID"
|
||
|
|
)
|
||
|
|
record = self.dev.record_process(
|
||
|
|
int(identity_file.read_text()), [sys.executable, "serve-api"], "api"
|
||
|
|
)
|
||
|
|
record["stop_file"] = str(stop_file)
|
||
|
|
status = {"ready": False}
|
||
|
|
while time.monotonic() < deadline and process.poll() is None:
|
||
|
|
status = self.dev.service_status(record, f"http://127.0.0.1:{port}/api/ready", "api")
|
||
|
|
if status["ready"]:
|
||
|
|
break
|
||
|
|
time.sleep(0.1)
|
||
|
|
self.assertTrue(status["ready"], "real API never reached local readiness")
|
||
|
|
self.assertFalse(status["upstream_ready"])
|
||
|
|
# Browser EventSource stays open during stop. Uvicorn must bound the
|
||
|
|
# connection drain, then run normal FastAPI/coordinator lifespan cleanup.
|
||
|
|
browser = build_opener(HTTPCookieProcessor(CookieJar()))
|
||
|
|
credentials = json.dumps(
|
||
|
|
{"username": "local-launcher-test", "password": "Local-Launcher-Test-194!"}
|
||
|
|
).encode()
|
||
|
|
with browser.open(
|
||
|
|
Request(
|
||
|
|
f"http://127.0.0.1:{port}/api/auth/login",
|
||
|
|
data=credentials,
|
||
|
|
headers={"Content-Type": "application/json"},
|
||
|
|
),
|
||
|
|
timeout=5,
|
||
|
|
) as response:
|
||
|
|
self.assertEqual(response.status, 200)
|
||
|
|
events = browser.open(f"http://127.0.0.1:{port}/api/events", timeout=5)
|
||
|
|
self.assertEqual(events.readline(), b": connected\n")
|
||
|
|
self.assertFalse(events.isclosed())
|
||
|
|
started = time.monotonic()
|
||
|
|
try:
|
||
|
|
self.assertTrue(self.dev.stop_owned(record, self.root, timeout=20))
|
||
|
|
self.assertLess(time.monotonic() - started, 20)
|
||
|
|
finally:
|
||
|
|
# The red test releases SSE so the deliberately unfixed server can
|
||
|
|
# finish cleanly too; no unknown process termination is needed.
|
||
|
|
events.close()
|
||
|
|
stop_file.touch()
|
||
|
|
process.wait(timeout=10)
|
||
|
|
self.assertIsNone(self.dev.process_identity(record["pid"]))
|
||
|
|
self.assertEqual(process.returncode, 0)
|
||
|
|
self.assertIn(
|
||
|
|
"Application shutdown complete", (local / "api.log").read_text(encoding="utf-8")
|
||
|
|
)
|
||
|
|
|
||
|
|
def test_env_values_are_literal_and_never_shell_evaluated(self):
|
||
|
|
# Evaluating/interpolating a password would execute code or corrupt its value.
|
||
|
|
path = self.root / ".env.local"
|
||
|
|
path.write_text(
|
||
|
|
"\ufeff# local settings\nMYSQL_PASSWORD='x#$(whoami)`secret`'\nWORKSPACE_ROOT=E:\\workspace\\a b # comment\nEMPTY=\nQUOTED=\"a # b\"\n",
|
||
|
|
encoding="utf-8",
|
||
|
|
)
|
||
|
|
values = self.dev.read_env(path)
|
||
|
|
self.assertEqual(
|
||
|
|
values,
|
||
|
|
{
|
||
|
|
"MYSQL_PASSWORD": "x#$(whoami)`secret`",
|
||
|
|
"WORKSPACE_ROOT": r"E:\workspace\a b",
|
||
|
|
"EMPTY": "",
|
||
|
|
"QUOTED": "a # b",
|
||
|
|
},
|
||
|
|
)
|
||
|
|
|
||
|
|
def test_double_quoted_json_escapes_preserve_private_config_values(self):
|
||
|
|
path = self.root / ".env.local"
|
||
|
|
expected = {"MYSQL_PASSWORD": 'a"b\\c\n秘密', "WORKSPACE_ROOT": r"E:\workspace\a b"}
|
||
|
|
path.write_text(
|
||
|
|
"\n".join(
|
||
|
|
key + "=" + json.dumps(value, ensure_ascii=False) for key, value in expected.items()
|
||
|
|
),
|
||
|
|
encoding="utf-8",
|
||
|
|
)
|
||
|
|
self.assertEqual(self.dev.read_env(path), expected)
|
||
|
|
|
||
|
|
def test_invalid_env_error_does_not_reveal_the_line(self):
|
||
|
|
path = self.root / ".env.local"
|
||
|
|
path.write_text(
|
||
|
|
"MYSQL_PASSWORD=private-password\nthis is another-private-password\n", encoding="utf-8"
|
||
|
|
)
|
||
|
|
with self.assertRaises(ValueError) as raised:
|
||
|
|
self.dev.read_env(path)
|
||
|
|
self.assertIn("2", str(raised.exception))
|
||
|
|
self.assertNotIn("private-password", str(raised.exception))
|
||
|
|
|
||
|
|
@unittest.skipUnless(os.name == "nt", "Windows process identity")
|
||
|
|
def test_stop_refuses_reused_pid_and_leaves_the_live_process_untouched(self):
|
||
|
|
# A PID alone would kill an unrelated process after Windows reused the number.
|
||
|
|
process = self.child()
|
||
|
|
record = self.dev.record_process(process.pid, [sys._base_executable, "-c", "sleep"], "api")
|
||
|
|
record["created"] += 1
|
||
|
|
self.assertFalse(self.dev.stop_owned(record, self.root, timeout=0.1))
|
||
|
|
self.assertIsNone(process.poll())
|
||
|
|
|
||
|
|
@unittest.skipUnless(os.name == "nt", "Windows process identity")
|
||
|
|
def test_stop_terminates_an_owned_process_and_removes_no_other_process(self):
|
||
|
|
owned = self.child()
|
||
|
|
other = self.child()
|
||
|
|
record = self.dev.record_process(
|
||
|
|
owned.pid, [sys._base_executable, "-c", "sleep"], "frontend"
|
||
|
|
)
|
||
|
|
self.assertTrue(self.dev.stop_owned(record, self.root, timeout=0.1))
|
||
|
|
owned.wait(timeout=5)
|
||
|
|
self.assertIsNone(other.poll())
|
||
|
|
|
||
|
|
@unittest.skipUnless(os.name == "nt", "Windows process identity")
|
||
|
|
def test_successful_http_from_unrelated_process_cannot_mask_an_exited_child(self):
|
||
|
|
process = self.child("pass")
|
||
|
|
record = self.dev.record_process(
|
||
|
|
process.pid, [sys._base_executable, "-c", "pass"], "frontend"
|
||
|
|
)
|
||
|
|
process.wait(timeout=5)
|
||
|
|
server, url = self.http_server({"status": "ok"}, 200)
|
||
|
|
self.assertFalse(self.dev.service_status(record, url, "frontend")["running"])
|
||
|
|
self.assertFalse(self.dev.service_status(record, url, "frontend")["ready"])
|
||
|
|
|
||
|
|
def http_server(self, body, code):
|
||
|
|
class Handler(BaseHTTPRequestHandler):
|
||
|
|
def do_GET(self):
|
||
|
|
self.send_response(code)
|
||
|
|
self.send_header("Content-Type", "application/json")
|
||
|
|
self.end_headers()
|
||
|
|
self.wfile.write(json.dumps(body).encode())
|
||
|
|
|
||
|
|
def log_message(self, *args):
|
||
|
|
pass
|
||
|
|
|
||
|
|
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||
|
|
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||
|
|
self.addCleanup(server.server_close)
|
||
|
|
self.addCleanup(server.shutdown)
|
||
|
|
return server, f"http://127.0.0.1:{server.server_port}"
|
||
|
|
|
||
|
|
@unittest.skipUnless(os.name == "nt", "Windows process identity")
|
||
|
|
def test_upstream_outage_is_degraded_but_missing_database_is_not_ready(self):
|
||
|
|
process = self.child()
|
||
|
|
record = self.dev.record_process(process.pid, [sys._base_executable, "-c", "sleep"], "api")
|
||
|
|
_, url = self.http_server(
|
||
|
|
{
|
||
|
|
"status": "not_ready",
|
||
|
|
"checks": {
|
||
|
|
"database": True,
|
||
|
|
"coordinator": True,
|
||
|
|
"accepting": True,
|
||
|
|
"upstream_protocol": False,
|
||
|
|
},
|
||
|
|
},
|
||
|
|
503,
|
||
|
|
)
|
||
|
|
status = self.dev.service_status(record, url, "api")
|
||
|
|
self.assertTrue(status["running"])
|
||
|
|
self.assertTrue(status["ready"])
|
||
|
|
self.assertFalse(status["upstream_ready"])
|
||
|
|
_, broken_url = self.http_server(
|
||
|
|
{
|
||
|
|
"checks": {
|
||
|
|
"database": False,
|
||
|
|
"coordinator": True,
|
||
|
|
"accepting": True,
|
||
|
|
"upstream_protocol": True,
|
||
|
|
}
|
||
|
|
},
|
||
|
|
503,
|
||
|
|
)
|
||
|
|
self.assertFalse(self.dev.service_status(record, broken_url, "api")["ready"])
|
||
|
|
|
||
|
|
@unittest.skipUnless(os.name == "nt", "Windows process identity")
|
||
|
|
def test_start_rolls_back_earlier_children_when_a_later_child_exits(self):
|
||
|
|
# A Vite/config failure must fail start, stop the API we just launched, and retain no stale state.
|
||
|
|
_, url = self.http_server(
|
||
|
|
{
|
||
|
|
"status": "ready",
|
||
|
|
"checks": {
|
||
|
|
"database": True,
|
||
|
|
"coordinator": True,
|
||
|
|
"accepting": True,
|
||
|
|
"upstream_protocol": True,
|
||
|
|
},
|
||
|
|
},
|
||
|
|
200,
|
||
|
|
)
|
||
|
|
services = [
|
||
|
|
self.dev.Service(
|
||
|
|
"api", [sys._base_executable, "-c", "import time; time.sleep(60)"], self.root, url
|
||
|
|
),
|
||
|
|
self.dev.Service(
|
||
|
|
"frontend",
|
||
|
|
[sys._base_executable, "-c", "raise SystemExit(7)"],
|
||
|
|
self.root,
|
||
|
|
"http://127.0.0.1:1",
|
||
|
|
),
|
||
|
|
]
|
||
|
|
with self.assertRaises(RuntimeError):
|
||
|
|
self.dev.start_services(self.root, services, dict(os.environ), timeout=3)
|
||
|
|
state_path = self.root / ".local" / "dev-processes.json"
|
||
|
|
state = json.loads(state_path.read_text()) if state_path.exists() else {"processes": {}}
|
||
|
|
self.assertEqual(state["processes"], {})
|
||
|
|
self.assertTrue((self.root / ".local/logs/frontend.log").exists())
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
unittest.main()
|