Files
alzeo/tests/test_proxy_engine_gone.py

212 lines
9.8 KiB
Python

"""What a client reads when no engine answers (v6.63).
With no lane at all it read "It is stopped, restarting or still loading (about 9 on a DGX Spark)", to send
again "once GET http://127.0.0.1:30000/health answers 200", an address of its own machine, with a
Retry-After for what only the box's owner brings back: opencode 2.3.2 wrote it again every 30 s, the OpenAI
SDK waited 60 s before it showed it (2026-11-30). And what the engine had said in a 503 was dropped."""
import http.server
import importlib.util
import json
import os
import sys
import threading
import time
import unittest
import urllib.error
import urllib.request
from pathlib import Path
from types import SimpleNamespace
sys.path.insert(0, str(Path(__file__).resolve().parent))
import localports # noqa: E402
REPO = Path(__file__).resolve().parents[1]
KEY = "k3y-of-this-test-0123456789"
UNITS = ("qwen38-sglang.service", "qwen38-flash.service")
class Engine(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
says = (503, b"", "application/json")
def log_message(self, *a):
pass
def answer(self):
self.rfile.read(int(self.headers.get("Content-Length") or 0))
status, body, ctype = self.says
self.send_response(status)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
do_GET = do_POST = answer
def load(upstream):
os.environ.update(UPSTREAM=upstream, CLIENT_IO_S="5", PROMPT_CEILING_TOKENS="0", PROXY_HOLD_UNITS="",
QWEN38_UPSTREAM_API_KEY=KEY)
os.environ.pop("QWEN38_CLIENT_KEYS_FILE", None)
spec = importlib.util.spec_from_file_location(f"kp_gone_{time.time_ns()}", REPO / "keepalive-proxy.py")
mod = importlib.util.module_from_spec(spec)
sys.argv = ["keepalive-proxy.py"]
spec.loader.exec_module(mod)
mod.journal = []
mod.log = mod.journal.append
mod._api_key = lambda: KEY # never the key of the box that runs the suite, nor its absence
for name in ("image_lane_serving", "video_lane_serving", "transcribe_lane_serving"):
setattr(mod, name, lambda: None)
return mod
class Base(unittest.TestCase):
@classmethod
def setUpClass(cls):
saved = dict(os.environ)
cls.addClassCleanup(lambda: (os.environ.clear(), os.environ.update(saved)))
cls.engine = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Engine)
cls.engine.daemon_threads = True
threading.Thread(target=cls.engine.serve_forever, daemon=True).start()
cls.addClassCleanup(cls.engine.server_close)
cls.addClassCleanup(cls.engine.shutdown)
cls.nobody = f"127.0.0.1:{localports.held(SimpleNamespace(addCleanup=cls.addClassCleanup))}"
def serve(self, upstream):
mod = load(f"http://{upstream}")
srv = mod.Server(("127.0.0.1", 0), mod.H)
threading.Thread(target=srv.serve_forever, daemon=True).start()
self.addCleanup(srv.server_close)
self.addCleanup(srv.shutdown)
self.at = f"http://127.0.0.1:{srv.server_address[1]}"
return mod
def ask(self, path="/v1/chat/completions", body=b'{"model": "m", "messages": []}'):
req = urllib.request.Request(self.at + path, data=body, headers={"Authorization": f"Bearer {KEY}",
"Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=60) as r:
return r.status, r.headers, r.read()
except urllib.error.HTTPError as e:
return e.code, e.headers, e.read()
def systemd(states, jobs=""):
"""subprocess.run as systemctl answers it: the units' states, and the jobs."""
def run(argv, **k):
if states is None:
raise FileNotFoundError("systemctl")
return SimpleNamespace(returncode=0, stdout=jobs if "list-jobs" in argv else "\n\n".join(states) + "\n")
return run
class NoLane(Base):
def reading(self, states, jobs=""):
mod = self.serve(self.nobody)
mod.HOLD_UNITS = UNITS
mod.HOLD_MAX_S = 0 # nothing is held: what is said is what is tested
mod.subprocess = SimpleNamespace(run=systemd(states, jobs))
status, head, raw = self.ask()
self.assertEqual(status, 503)
return json.loads(raw)["error"]["message"], head.get("Retry-After")
def test_none_serves_and_none_comes(self):
msg, retry = self.reading(("inactive", "failed"))
self.assertIn("No lane serves on this box: start one in the cockpit, Lanes", msg)
self.assertNotIn("switch-model.sh", msg, "which starts nothing")
self.assertIsNone(retry, "no wait brings it back")
def test_one_is_on_its_way(self):
for states, jobs in ((("activating", "inactive"), ""), (("active", "inactive"), ""),
(("deactivating", "inactive"), "12 qwen38-sglang.service restart running\n")):
msg, retry = self.reading(states, jobs)
self.assertIn("qwen38-sglang.service is starting, loading or restarting", msg)
self.assertNotIn("No lane serves", msg)
self.assertEqual(retry, "30")
def test_systemd_does_not_say(self):
msg, retry = self.reading(None)
self.assertIn("stopped, restarting or still loading", msg)
self.assertEqual(retry, "30")
def test_another_kind_of_lane_holds_the_gpu(self):
mod = load(f"http://{self.nobody}")
mod.HOLD_UNITS = UNITS
mod.subprocess = SimpleNamespace(run=systemd(("inactive", "inactive")))
for name, words in (("image_lane_serving", "serving images"), ("video_lane_serving", "serving video"),
("transcribe_lane_serving", "transcribing speech")):
with self.subTest(name=name):
setattr(mod, name, lambda: "qwen38-image.service")
said, retry = mod.engine_gone()
self.assertIn(words, said)
self.assertIsNone(retry)
setattr(mod, name, lambda: None)
def test_the_engine_s_address_and_python_s_dressing_stay_here(self):
mod = self.serve(self.nobody)
# no unit of the box that runs the suite is read, and nothing is held
mod.HOLD_UNITS, mod.HOLD_MAX_S = UNITS, 0
mod.subprocess = SimpleNamespace(run=systemd(("inactive", "inactive")))
for path, body in (("/v1/chat/completions", b'{"model": "m", "messages": []}'), ("/v1/models", None), ("/health", None),
("/v1/messages", b'{"model": "m", "messages": []}'),
("/v1/systemone", b'{"state": "s", "model": "jev-latest", "questions": '
b'{"a": {"type": "noul", "instructions": "x?"}}}')):
with self.subTest(path=path):
status, _, raw = self.ask(path, body)
self.assertEqual(status, 503, raw)
for text in (self.nobody.encode(), b"urlopen", b"Errno"):
self.assertNotIn(text, raw)
self.assertIn(b"Connection refused", raw)
self.assertIn(b"once GET /health on this address answers 200", raw)
self.assertTrue([ln for ln in mod.journal if ln == "engine unreachable: Connection refused"], mod.journal)
def test_a_path_of_the_box_stays_here(self):
mod = self.serve(self.nobody)
mod.HOLD_UNITS, mod.HOLD_MAX_S = UNITS, 0
mod.subprocess = SimpleNamespace(run=systemd(("inactive", "inactive")))
def missing():
raise FileNotFoundError(2, "No such file or directory", "/home/someone/.config/qwen38/api-key")
mod._api_key = missing
status, _, raw = self.ask("/v1/systemone", b'{"state": "s", "model": "jev-latest", "questions": '
b'{"a": {"type": "noul", "instructions": "x?"}}}')
self.assertEqual(status, 503, raw)
self.assertNotIn(b"/home/someone", raw)
self.assertIn(b"No such file or directory", raw)
class WhatTheEngineSaid(Base):
def said(self, body, ctype="application/json", path="/v1/chat/completions"):
Engine.says = (503, body, ctype)
mod = self.serve(f"127.0.0.1:{self.engine.server_port}")
status, head, raw = self.ask(path, None if path == "/v1/models" else b'{"model": "m", "messages": []}')
self.assertEqual(status, 503)
self.assertNotIn(KEY.encode(), raw)
self.assertNotIn(KEY, "\n".join(mod.journal))
return json.loads(raw)["error"]["message"]
def test_its_words_are_given(self):
for body, words in ((b'{"error": {"code": 503, "message": "Loading model", "type": "unavailable_error"}}', "Loading model"),
(b'{"object": "error", "message": "The request queue is full.", "code": 503}', "The request queue is full."),
(b'{"error": "paused"}', "paused"), (b'{"detail": "busy"}', "busy"), (b"overloaded\n now", "overloaded now")):
for path in ("/v1/chat/completions", "/v1/models"):
msg = self.said(body, path=path)
self.assertIn(f'it answered HTTP 503: "{words}"', msg)
self.assertNotIn("as it does while starting", msg)
def test_an_empty_answer_and_a_page_say_nothing(self):
for body, ctype in ((b"", "application/json"), (b"<html><h1>503 nginx</h1></html>", "text/html"), (b"{}", "application/json")):
msg = self.said(body, ctype)
self.assertIn("it answered HTTP 503, as it does while starting or shutting down", msg)
self.assertNotIn("nginx", msg)
def test_its_secrets_are_masked_and_its_length_bounded(self):
msg = self.said(json.dumps({"error": {"message": f"args: --api-key {KEY} and {KEY} " + "x" * 5000}}).encode())
self.assertIn("<masked>", msg)
self.assertLess(len(msg), 1200)
if __name__ == "__main__":
unittest.main()