llm-host/tests/test_proxy.py
neil 8879db44a0 Proxy in front of vLLM too; dashboard reset/clear; opencode effort variants
- Move the MLX proxy into backends/proxy.py and run it on both backends:
  public port 1134 is the proxy, the model server listens on 127.0.0.1:1135.
  On vLLM this brings the reasoning chooser, the "default" alias and the
  per-request table. Effort levels the model lacks map to the nearest it has
  (high -> xhigh on qwen3.8); vLLM's own key is sent upstream; streamed runs
  are counted from the usage chunk (MTP packs several tokens per chunk).
- Dashboard: restore METRIC_RE (vLLM page stuck on "loading"); Statistics
  header with Reset, Requests header with Clear; drop the TTFT chart; rename
  token columns; Peak KV shows "-" when no samples cover a run.
- opencode: config snippet's model points at <provider>/default, and
  reasoning models get variants built from the levels the template accepts.
- README: proxy on both platforms; NVIDIA checklist split into verified / open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:03:52 -08:00

196 lines
9.4 KiB
Python

"""Proxy tests: the model name a client asks for must be honoured or refused, never ignored."""
import json, threading, urllib.error, urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import harness
ROOT = harness.setup()
from llmhost import paths
from llmhost.backends import proxy
harness.guard(paths, ROOT)
SERVED = "ornith-1.5-9b"
REPO = "ornith-ai/Ornith-1.5-9B-MLX-6bit"
KEY = "sk-test-key"
seen = [] # bodies the inner (fake mlx_lm / vLLM) server received
auths = [] # the Authorization header each of them came with
check = harness.Checks()
class Inner(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *a): pass
def do_POST(self):
n = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(n) if n else b""
try: seen.append(json.loads(raw or b"{}"))
except ValueError: seen.append(None)
auths.append(self.headers.get("Authorization"))
if seen[-1] and seen[-1].get("stream"):
# vLLM with speculative decoding: one chunk can carry several tokens, so only
# the closing usage chunk has the true count.
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.end_headers()
for text in ("Hello", " there, how", " are you"):
self.wfile.write(b"data: " + json.dumps({"choices": [{"index": 0, "delta": {"content": text}}]}).encode() + b"\n\n")
self.wfile.write(b"data: " + json.dumps({"choices": [], "usage": {
"prompt_tokens": 30, "completion_tokens": 7, "total_tokens": 37,
"prompt_tokens_details": {"cached_tokens": 20}}}).encode() + b"\n\n")
self.wfile.write(b"data: [DONE]\n\n")
self.close_connection = True
return
body = json.dumps({"id": "x", "object": "chat.completion", "model": "default_model",
"created": 0, "choices": [{"index": 0, "finish_reason": "stop",
"message": {"role": "assistant", "content": "pong"}}],
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}}).encode()
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)
def serve(handler, port):
srv = ThreadingHTTPServer(("127.0.0.1", port), handler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv
INNER, OUTER = 18231, 18232
serve(Inner, INNER)
stats = proxy.Stats()
serve(proxy.make_handler(INNER, SERVED, 262144, KEY, stats, aliases=(REPO,)), OUTER)
def post(model, key=KEY, path="/v1/chat/completions", port=None, raw_reply=False, **extra):
body = {"messages": [{"role": "user", "content": "hi"}], "max_tokens": 4, **extra}
if model is not None:
body["model"] = model
req = urllib.request.Request(f"http://127.0.0.1:{port or OUTER}{path}", data=json.dumps(body).encode(),
headers={"Content-Type": "application/json",
"Authorization": f"Bearer {key}"}, method="POST")
try:
with urllib.request.urlopen(req, timeout=20) as r:
data = r.read()
return r.status, (data if raw_reply else json.loads(data or b"{}"))
except urllib.error.HTTPError as e:
try: return e.code, json.loads(e.read() or b"{}")
except ValueError: return e.code, {}
print("\n1. the loaded model is accepted")
seen.clear()
code, body = post(SERVED)
check("200", code == 200, code)
check("answered", body.get("choices", [{}])[0].get("message", {}).get("content") == "pong", body)
check("forwarded as default_model (mlx_lm must not try to load by name)",
seen and seen[-1].get("model") == "default_model", seen[-1] if seen else None)
print("\n2. the repo id is accepted as an alias")
check("200", post(REPO)[0] == 200)
print("\n3. case differences are accepted")
check("200", post(SERVED.upper())[0] == 200)
print("\n4. no model named -> the loaded one")
check("200 when absent", post(None)[0] == 200)
check("200 when empty", post("")[0] == 200)
check("200 when blank", post(" ")[0] == 200)
check.section("4b. the stable alias always means whatever is loaded")
from llmhost import plan
check("alias accepted", post(plan.SERVED_ALIAS)[0] == 200, post(plan.SERVED_ALIAS)[0])
check("alias is 'default'", plan.SERVED_ALIAS == "default")
seen.clear()
post(plan.SERVED_ALIAS)
check("still forwarded as default_model", seen and seen[-1].get("model") == "default_model", seen[-1] if seen else None)
va = plan.vllm_args({"name": "m", "context": 1024}, {"repo": "r", "util": 0.9}, 8001, 1)
check("vLLM serves one name; the proxy owns the alias",
va[1:3] == ["--served-model-name", "m"] and plan.SERVED_ALIAS not in va, va[:5])
check("vLLM listens on localhost only, behind the proxy",
va[va.index("--host") + 1] == "127.0.0.1" and va[va.index("--port") + 1] == "8001", va)
check("vLLM reports cached prompt tokens", "--enable-prompt-tokens-details" in va, va)
print("\n5. a model that ISN'T loaded is refused, not silently answered")
code, body = post("qwen3.8-27b")
check("404", code == 404, code)
err = body.get("error") or {}
check("code=model_not_found", err.get("code") == "model_not_found", err)
check("param=model", err.get("param") == "model", err)
check("names the model asked for", "qwen3.8-27b" in err.get("message", ""), err)
check("names the loaded model", SERVED in err.get("message", ""), err)
check("says how to load it", "llmhost switch" in err.get("message", ""), err)
seen.clear()
post("qwen3.8-27b")
check("never reached the model server", seen == [], seen)
print("\n6. unknown junk is refused too")
check("404", post("../etc/passwd")[0] == 404)
check("404", post("gpt-4")[0] == 404)
print("\n7. auth still comes first")
code, body = post("qwen3.8-27b", key="sk-wrong")
check("401, not 404 (key checked before the model)", code == 401, code)
print("\n8. /v1/models still advertises the served name")
req = urllib.request.Request(f"http://127.0.0.1:{OUTER}/v1/models",
headers={"Authorization": f"Bearer {KEY}"})
with urllib.request.urlopen(req, timeout=10) as r:
d = json.loads(r.read())
check("advertises the loaded model", [m["id"] for m in d["data"]] == [SERVED], d)
check.section("9. in front of vLLM: its model name and its own key are sent upstream")
VOUTER = 18233
vstats = proxy.Stats()
vstats.ready = True
serve(proxy.make_handler(INNER, "qwen3.8-27b", 262144, KEY, vstats, aliases=("Qwen/Qwen3.8-27B-FP8",),
upstream_model="qwen3.8-27b", upstream_key="sk-inner",
effort_levels=("low", "medium", "xhigh"),
reasoning=lambda: {"reasoning_effort": "low"}), VOUTER)
seen.clear(); auths.clear()
check("alias accepted", post(plan.SERVED_ALIAS, port=VOUTER)[0] == 200)
check("forwarded under vLLM's served name", seen[-1].get("model") == "qwen3.8-27b", seen[-1])
check("inner key sent, not the client's", auths[-1] == "Bearer sk-inner", auths[-1])
check("other models still refused", post("ornith-1.5-9b", port=VOUTER)[0] == 404)
check.section("10. effort levels the model lacks are mapped to the nearest it has")
for asked, sent in (("high", "xhigh"), ("medium", "medium"), ("xhigh", "xhigh"),
("minimal", "low"), ("max", "xhigh")):
seen.clear()
post(None, port=VOUTER, reasoning_effort=asked)
check(f"top-level {asked} -> {sent}", seen[-1].get("reasoning_effort") == sent, seen[-1])
seen.clear()
post(None, port=VOUTER, chat_template_kwargs={"reasoning_effort": "high"})
check("inside chat_template_kwargs too", seen[-1]["chat_template_kwargs"].get("reasoning_effort") == "xhigh",
seen[-1].get("chat_template_kwargs"))
seen.clear()
post(None, port=VOUTER, reasoning_effort="bogus")
check("an unknown word is left for the server to reject", seen[-1].get("reasoning_effort") == "bogus", seen[-1])
seen.clear()
post(None, port=VOUTER)
check("dashboard setting applied when the client sets none",
seen[-1].get("chat_template_kwargs") == {"reasoning_effort": "low"}, seen[-1])
seen.clear()
post(None, port=VOUTER, reasoning_effort="xhigh")
check("a client's own top-level level wins over the dashboard's",
"reasoning_effort" not in (seen[-1].get("chat_template_kwargs") or {})
and seen[-1].get("reasoning_effort") == "xhigh", seen[-1])
check("mapping only where a model has levels",
[plan.nearest_effort("high", ()), plan.nearest_effort("high", ("low", "high"))] == [None, "high"])
check("a tie goes to the higher level", plan.nearest_effort("high", ("medium", "xhigh")) == "xhigh")
check.section("11. a streamed run is counted from its usage chunk, and recorded")
before = vstats.snapshot()
code, data = post(None, port=VOUTER, raw_reply=True, stream=True)
after = vstats.snapshot()
check("200", code == 200, code)
check("usage chunk hidden from a client that didn't ask for it", b'"usage"' not in data, data[-200:])
check("generated tokens from usage (3 chunks, 7 tokens)", after["gen_total"] - before["gen_total"] == 7,
after["gen_total"] - before["gen_total"])
run = after["recent"][-1]
check("run recorded with its uncached prompt tokens", run["gen"] == 7 and run["prompt"] == 10, run)
check("time to first token recorded", run["ttft"] is not None, run)
check.done(ROOT)