llm-host/tests/test_proxy.py
Neil Bantoc 9af7f1e545 opencode: offer one model, not a menu where four of five fail
Only one model is loaded at a time, so listing every model that fits gave a
picker with one working entry and four that now answer 404 -- and the entry that
worked changed id on every `llmhost switch`, invalidating any client's saved
default.

Replace the list with a single entry, `default`, which is a name the API itself
answers to: vLLM takes it as a second --served-model-name and still reports the
real slug, being first in the list; the MLX proxy accepts it as an alias. So
`llmhost/default` survives a switch. The local entry is labelled with whatever is
loaded, refreshed by both switch paths; a remote block is pasted once and never
refreshed, so it names no model rather than make a claim that goes stale.

Existing configs point at a specific model, which this provider no longer has and
opencode would reject, so configure() and sync() migrate `<prov>/<model>` to
`<prov>/default`. Other providers' defaults are untouched, and an older remote
block that still lists many models keeps working, including as the fallback when
the local provider is removed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-11-03 02:26:34 -08:00

125 lines
5.2 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 mlx
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) server received
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)
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 = mlx.Stats()
serve(mlx.make_handler(INNER, SERVED, 262144, KEY, stats, aliases=(REPO,)), OUTER)
def post(model, key=KEY, path="/v1/chat/completions"):
body = {"messages": [{"role": "user", "content": "hi"}], "max_tokens": 4}
if model is not None:
body["model"] = model
req = urllib.request.Request(f"http://127.0.0.1:{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:
return r.status, json.loads(r.read() 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)
check("vLLM is told to serve it as a second name",
plan.vllm_args({"name": "m", "context": 1024}, {"repo": "r", "util": 0.9}, 8000, 1)[1:4]
== ["--served-model-name", "m", plan.SERVED_ALIAS],
plan.vllm_args({"name": "m", "context": 1024}, {"repo": "r", "util": 0.9}, 8000, 1)[:5])
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.done(ROOT)