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>
This commit is contained in:
neil 2026-11-03 13:03:52 -08:00
parent 1121c3f908
commit 8879db44a0
12 changed files with 886 additions and 493 deletions

View file

@ -8,14 +8,14 @@ import harness
ROOT = harness.setup()
from llmhost import paths
from llmhost.backends import mlx
from llmhost.backends import mlx, proxy
from llmhost.web import server as web
harness.guard(paths, ROOT)
check = harness.Checks()
print("\n1. KV is picked out of mlx_lm's log line")
st = mlx.Stats()
st = proxy.Stats()
st.kv_budget = int(77.27 * 2**30)
for seg in [b"2026-11-03 01:13:31,176 - INFO - Prompt Cache: 10 sequences, 1.58 GB\n",
b"2026-11-03 01:14:32,794 - INFO - Prompt Cache: 12 sequences, 4.24 GB\n",
@ -33,20 +33,20 @@ check("fraction against --prompt-cache-bytes", abs(snap["kv"] - 2.00e9 / (77.27
check("budget reported", snap["kv_budget_bytes"] == int(77.27 * 2**30))
print("\n2. no budget -> no fraction, but still a size")
st2 = mlx.Stats(); st2.set_kv(4, 1.5e9)
st2 = proxy.Stats(); st2.set_kv(4, 1.5e9)
check("kv is None", st2.snapshot()["kv"] is None)
check("kv_bytes still there", st2.snapshot()["kv_bytes"] == 1.5e9)
check("fresh Stats reports nothing", mlx.Stats().snapshot()["kv"] is None)
check("fresh Stats reports nothing", proxy.Stats().snapshot()["kv"] is None)
print("\n3. run records survive the round trip")
st3 = mlx.Stats()
st3 = proxy.Stats()
st3.add_run({"start": 100.0, "end": 110.0, "dur": 10.0, "gen": 200, "prompt": 7667,
"ttft": 2.0, "aborted": False})
check("recent carries the run", len(st3.snapshot()["recent"]) == 1)
for i in range(mlx.RECENT_RUNS + 10):
for i in range(proxy.RECENT_RUNS + 10):
st3.add_run({"start": float(i), "end": float(i) + 1, "dur": 1.0, "gen": 1, "prompt": 1,
"ttft": 0.1, "aborted": False})
check(f"bounded to {mlx.RECENT_RUNS}", len(st3.snapshot()["recent"]) == mlx.RECENT_RUNS,
check(f"bounded to {proxy.RECENT_RUNS}", len(st3.snapshot()["recent"]) == proxy.RECENT_RUNS,
len(st3.snapshot()["recent"]))
print("\n4. the sampler splits a run into prefill and generation")
@ -142,4 +142,68 @@ check("nothing claimed to be a disconnect", not any("disconnected" in l for l in
check("ordinary lines pass through", web.collapse_disconnects(["a", "b"]) == ["a", "b"])
check("empty input", web.collapse_disconnects([]) == [])
print("\n8. vLLM's /metrics is parsed (lines captured from vLLM 0.33 on an RTX PRO 6000)")
VLLM_METRICS = """# HELP vllm:num_requests_running Number of requests in model execution batches.
vllm:num_requests_running{engine="0",model_name="qwen3.8-27b"} 2.0
vllm:num_requests_waiting{engine="0",model_name="qwen3.8-27b"} 1.0
vllm:num_requests_waiting_by_reason{engine="0",model_name="qwen3.8-27b",reason="capacity"} 5.0
vllm:kv_cache_usage_perc{engine="0",model_name="qwen3.8-27b"} 0.25
vllm:prefix_cache_queries_total{engine="0",model_name="qwen3.8-27b"} 57.0
vllm:prefix_cache_hits_total{engine="0",model_name="qwen3.8-27b"} 0.0
vllm:num_preemptions_total{engine="0",model_name="qwen3.8-27b"} 0.0
vllm:prompt_tokens_total{engine="0",model_name="qwen3.8-27b"} 57.0
vllm:generation_tokens_total{engine="0",model_name="qwen3.8-27b"} 37.0
vllm:time_to_first_token_seconds_bucket{engine="0",le="0.1",model_name="qwen3.8-27b"} 1.0
vllm:time_to_first_token_seconds_count{engine="0",model_name="qwen3.8-27b"} 1.0
vllm:time_to_first_token_seconds_sum{engine="0",model_name="qwen3.8-27b"} 0.03685879707336426
vllm:time_to_first_token_seconds_created{engine="0",model_name="qwen3.8-27b"} 1793704000.0"""
vm = web.parse_vllm_metrics(VLLM_METRICS)
check("running / waiting", vm["running"] == 2.0 and vm["waiting"] == 1.0, vm)
check("waiting_by_reason not added into waiting", vm["waiting"] == 1.0, vm["waiting"])
check("kv usage", vm["kv"] == 0.25, vm["kv"])
check("token totals", vm["prompt_total"] == 57.0 and vm["gen_total"] == 37.0, vm)
check("ttft sum and count, buckets and _created skipped",
vm["ttft_count"] == 1.0 and abs(vm["ttft_sum"] - 0.0369) < 1e-3, vm)
check("empty body", web.parse_vllm_metrics("")["kv"] is None)
check.section("9. Statistics reset rebases the counters; Requests clear empties the table")
smp = web.Sampler(harness.config(), "k")
raw = {"gen_total": 1000.0, "prompt_total": 5000.0, "ttft_sum": 4.0, "ttft_count": 8.0,
"prefix_hits": 300.0, "prefix_queries": 1000.0, "kv": 0.2, "running": 1}
check("before a reset: as reported", smp.since_reset(raw) == raw)
smp.prev = (0, raw)
smp.history.append({"t": 0, "kv": 20.0})
smp.reset_stats()
check("charts emptied", len(smp.history) == 0)
check("reset time recorded", smp.stats_since is not None)
later = dict(raw, gen_total=1040.0, prompt_total=5100.0, ttft_sum=4.5, ttft_count=9.0,
prefix_hits=350.0, prefix_queries=1100.0)
sh = smp.since_reset(later)
check("counters count from the reset", sh["gen_total"] == 40 and sh["prompt_total"] == 100, sh)
check("averages are of what came after", sh["ttft_sum"] / sh["ttft_count"] == 0.5 and
sh["prefix_hits"] / sh["prefix_queries"] == 0.5, sh)
check("live values untouched", sh["kv"] == 0.2 and sh["running"] == 1, sh)
check("the reported metrics aren't modified", later["gen_total"] == 1040.0)
restarted = dict(raw, gen_total=12.0, prompt_total=30.0, ttft_sum=0.1, ttft_count=1.0,
prefix_hits=0.0, prefix_queries=30.0)
check("a server restart after the reset: its own counters already start later",
smp.since_reset(restarted)["gen_total"] == 12.0, smp.since_reset(restarted))
smp.history.extend([{"t": 1, "kv": 5.0}, {"t": 2, "kv": 9.0}, {"t": 3, "kv": None}])
check("peak KV since the reset comes from the samples",
smp.kv_peak_pct({"kv_peak_bytes": 8e9, "kv_budget_bytes": 1e10}) == 9.0)
smp.runs.extend([{"t": 1}, {"t": 2}])
smp._seen_runs.update({(1, 1), (2, 2)})
smp.clear_runs()
check("requests cleared", len(smp.runs) == 0)
check("cleared requests stay seen (they don't come back)", {(1, 1), (2, 2)} <= smp._seen_runs)
check.section("10. a run's peak KV comes from samples in its window, or not at all")
hist = [{"t": 10, "kv": 4.0}, {"t": 12, "kv": 7.5}, {"t": 14, "kv": 3.0}, {"t": 16, "kv": None}]
check("max over the window", web.run_kv_peak(hist, {"start": 9, "end": 15}, 15, 0.0) == 7.5)
check("a short run just finished: the reading right after it",
web.run_kv_peak(hist, {"start": 16.2, "end": 16.9}, 17.0, 2.5) == 2.5)
check("a run picked up long after (dashboard restarted): unknown, not 0%",
web.run_kv_peak([], {"start": 100, "end": 400}, 900, 0.0) is None)
check.done(ROOT)

View file

@ -296,4 +296,31 @@ reset({"provider": {"mymac": opencode.local_block(CFG)}, "model": "mymac/qwen3-c
opencode.sync(dict(CFG, active="qwen3-coder"))
check("migrated under a renamed provider too", load()["model"] == "mymac/default", load().get("model"))
check.section("23. opencode-config's default points at an entry its block has")
import argparse, io, contextlib
cli._service_check = lambda: CFG
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
cli.cmd_opencode(argparse.Namespace(host="popos.local", provider=None, json=True))
snip = json.loads(buf.getvalue())
prov_id, block = next(iter(snip["provider"].items()))
check("provider named after the host", prov_id == "llmhost-popos", prov_id)
check("model is <provider>/<an entry in the block>",
snip["model"].partition("/")[0] == prov_id and snip["model"].partition("/")[2] in block["models"],
(snip["model"], list(block["models"])))
check.section("24. the block offers only the effort levels the loaded model accepts")
check("qwen3.8: hide high, add xhigh",
opencode.effort_variants(("low", "medium", "xhigh")) == {"high": {"disabled": True},
"xhigh": {"reasoningEffort": "xhigh"}},
opencode.effort_variants(("low", "medium", "xhigh")))
check("no levels: hide opencode's whole menu",
opencode.effort_variants(()) == {l: {"disabled": True} for l in ("low", "medium", "high")})
q = opencode.provider_block(dict(CFG, active="qwen3.8-27b"), "popos.local", "k", "popos.local")
ent = q["models"]["default"]
check("qwen3.8 block (not downloaded: catalog levels)",
ent.get("variants") == {"high": {"disabled": True}, "xhigh": {"reasoningEffort": "xhigh"}}, ent)
nr = opencode.provider_block(dict(CFG, active="qwen3-coder"), "popos.local", "k", "popos.local")
check("a non-reasoning model gets no variants", "variants" not in nr["models"]["default"], nr["models"]["default"])
check.done(ROOT)

View file

@ -9,14 +9,15 @@ import harness
ROOT = harness.setup()
from llmhost import paths
from llmhost.backends import mlx
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) server received
seen = [] # bodies the inner (fake mlx_lm / vLLM) server received
auths = [] # the Authorization header each of them came with
check = harness.Checks()
@ -28,6 +29,21 @@ class Inner(BaseHTTPRequestHandler):
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"}}],
@ -46,20 +62,21 @@ def serve(handler, port):
INNER, OUTER = 18231, 18232
serve(Inner, INNER)
stats = mlx.Stats()
serve(mlx.make_handler(INNER, SERVED, 262144, KEY, stats, aliases=(REPO,)), OUTER)
stats = proxy.Stats()
serve(proxy.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}
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:{OUTER}{path}", data=json.dumps(body).encode(),
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:
return r.status, json.loads(r.read() or b"{}")
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, {}
@ -89,10 +106,12 @@ 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])
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")
@ -122,4 +141,56 @@ 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)