"""Dashboard: status, metrics and model switching. Stdlib only. Serves index.html and a JSON API on cfg["web_port"]. /api/* routes need the API key. """ import hmac import json import re import socket import threading import time import urllib.request from collections import deque from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from .. import hfcache, hw, opencode, paths, service HERE = Path(__file__).resolve().parent SAMPLE_SECONDS = 2 HISTORY_POINTS = 300 # 10 minutes RUNS_SHOWN = 20 # completed requests in the run summary # The sampler's own polling shows up in vLLM's access log every 2s; hide it from the log view. OWN_POLL_RE = re.compile(r'127\.0\.0\.1(:\d+)? - (- \[[^]]*\] )?"GET /(health|metrics|v1/models|llmhost/metrics) ' r'|- INFO - HTTP Request: ') PROGRESS_RE = re.compile(r"\d+(\.\d+)?(it/s|s/it)\]") # A client that hangs up mid-answer leaves mlx_lm writing to a closed socket, and its # ThreadingHTTPServer prints a full traceback for it. That's expected (the proxy logs the # disconnect in one line), so collapse the block instead of letting it bury the log. DASHES_RE = re.compile(r"^-{20,}\s*$") EXC_HEAD_RE = re.compile(r"^Exception occurred during processing of request") DISCONNECT_RE = re.compile(r"^(BrokenPipeError|ConnectionResetError)\b") MAX_TRACE_LINES = 80 def collapse_disconnects(lines): """Replace each mlx_lm traceback that ends in a broken pipe with one line. Any other traceback is left exactly as it is -- those are worth reading in full. socketserver brackets each one with a row of dashes, which is what delimits a block here; a block that never closes (the log was truncated, or is still being written) is emitted unchanged.""" out, block = [], None def flush(decide): nonlocal block if block is None: return if decide and any(DISCONNECT_RE.match(l.split(" - ")[-1].lstrip()) for l in block): out.append(f" [client disconnected mid-answer; {len(block)} lines of traceback hidden]") else: out.extend(block) block = None for l in lines: bare = l.rstrip() if block is None: if DASHES_RE.match(bare) or EXC_HEAD_RE.match(bare): block = [l] else: out.append(l) continue if DASHES_RE.match(bare): block.append(l) flush(True) continue block.append(l) if len(block) > MAX_TRACE_LINES: flush(False) flush(False) return out def http_get(url, key=None, timeout=2): req = urllib.request.Request(url) if key: req.add_header("Authorization", f"Bearer {key}") try: with urllib.request.urlopen(req, timeout=timeout) as r: return r.status, r.read().decode() except Exception: return None, "" def parse_vllm_metrics(text): vals = {} for line in text.splitlines(): m = METRIC_RE.match(line) if not m: continue name, labels, v = m.group(1), m.group(2) or "", m.group(3) if name.endswith(("_created", "_bucket")) or "position=" in labels or "reason=" in labels or "by_source" in name: continue if name == "vllm:engine_sleep_state": continue try: vals[name] = vals.get(name, 0.0) + float(v) except ValueError: pass return { "running": vals.get("vllm:num_requests_running"), "waiting": vals.get("vllm:num_requests_waiting"), "kv": vals.get("vllm:kv_cache_usage_perc"), "gen_total": vals.get("vllm:generation_tokens_total"), "prompt_total": vals.get("vllm:prompt_tokens_total"), "prefix_hits": vals.get("vllm:prefix_cache_hits_total"), "prefix_queries": vals.get("vllm:prefix_cache_queries_total"), "spec_accepted": vals.get("vllm:spec_decode_num_accepted_tokens_total"), "spec_drafted": vals.get("vllm:spec_decode_num_draft_tokens_total"), "preemptions": vals.get("vllm:num_preemptions_total"), "ttft_sum": vals.get("vllm:time_to_first_token_seconds_sum"), "ttft_count": vals.get("vllm:time_to_first_token_seconds_count"), } class Sampler: def __init__(self, cfg, key): self.cfg = cfg self.key = key self.lock = threading.Lock() self.history = deque(maxlen=HISTORY_POINTS) self.prev = None self.state = {} self.action = None self._dl_cache = (0, {}) self.last_ttft = None # (time, seconds) of the latest sample with new first tokens self.runs = deque(maxlen=RUNS_SHOWN) self._seen_runs = set() def reload_cfg(self): self.cfg = paths.load_config() or self.cfg def downloaded(self): t, cache = self._dl_cache if time.time() - t > 30: cache = {m["repo"]: hfcache.is_downloaded(m["repo"]) for m in self.cfg.get("models", [])} self._dl_cache = (time.time(), cache) return cache def loop(self): while True: try: self.sample() except Exception as e: with self.lock: self.state["sampler_error"] = repr(e) time.sleep(SAMPLE_SECONDS) def sample(self): self.reload_cfg() cfg = self.cfg now = time.time() base = f"http://127.0.0.1:{cfg['api_port']}" svc_state, uptime = service.state("model") health, _ = http_get(base + "/health") served, metrics = None, {} if health == 200: st, body = http_get(base + "/v1/models", self.key) if st == 200: try: served = [m["id"] for m in json.loads(body)["data"]] except (ValueError, KeyError): pass if cfg["backend"] == "vllm": st, body = http_get(base + "/metrics") metrics = parse_vllm_metrics(body) if st == 200 else {} else: st, body = http_get(base + "/llmhost/metrics") try: metrics = json.loads(body) if st == 200 else {} except ValueError: metrics = {} active = cfg.get("active") if svc_state in ("inactive", "failed"): phase = "failed" if svc_state == "failed" else "stopped" elif health == 200 and served and active in served: phase = "ready" else: phase = "loading" gen_rate = prompt_rate = ttft = None if metrics.get("gen_total") is not None and self.prev: pt, pm = self.prev dt = now - pt if dt > 0 and pm.get("gen_total") is not None: gen_rate = max(metrics["gen_total"] - pm["gen_total"], 0) / dt prompt_rate = max((metrics.get("prompt_total") or 0) - (pm.get("prompt_total") or 0), 0) / dt # Average time to first token of the requests that got their first token since the # last sample (none: no point, so the chart shows a gap rather than a stale value). dn = (metrics.get("ttft_count") or 0) - (pm.get("ttft_count") or 0) if dn > 0: ttft = max((metrics.get("ttft_sum") or 0) - (pm.get("ttft_sum") or 0), 0) / dn if ttft is not None: self.last_ttft = (now, ttft) self.prev = (now, metrics) if metrics else None gpu = hw.live_stats(cfg["kind"]) kv = metrics.get("kv") point = { "t": now, "gen": gen_rate, "prompt": prompt_rate, "ttft": ttft, "kv": kv * 100 if kv is not None else None, "util": gpu["util"] if gpu else None, "temp": gpu["temp"] if gpu else None, "power": gpu["power"] if gpu else None, } def ratio(a, b): return metrics[a] / metrics[b] if metrics.get(b) else None def run_rates(r): """Split a run into its two phases: time to first token covers the prefill, the rest is generation. Rates over the whole duration would blur the two together.""" dur, ttft = r.get("dur") or 0, r.get("ttft") prompt_tps = (r["prompt"] / ttft) if (ttft and r.get("prompt")) else None gen_window = dur - ttft if (ttft is not None and dur > ttft) else dur gen_tps = (r["gen"] / gen_window) if (gen_window and r.get("gen")) else None return gen_tps, prompt_tps last_log = None if phase in ("loading", "failed"): lines = [l for l in service.logs("model", 20) if l.strip() and not OWN_POLL_RE.search(l)] last_log = lines[-1][-240:] if lines else None dl = self.downloaded() models = [{**m, "downloaded": dl.get(m["repo"], False)} for m in cfg.get("models", [])] with self.lock: self.history.append(point) # Peak KV per run is taken from the sampled history over the run's own window; # the proxy can't do it, since it only learns KV when mlx_lm happens to log it. for r in metrics.get("recent") or []: key = (r.get("start"), r.get("end")) if key in self._seen_runs or r.get("start") is None: continue self._seen_runs.add(key) window = [q["kv"] for q in self.history if q["kv"] is not None and r["start"] <= q["t"] <= r["end"]] gen_tps, prompt_tps = run_rates(r) self.runs.append({ "t": r["end"], "dur": r.get("dur"), "gen": r.get("gen"), "prompt": r.get("prompt"), "ttft": r.get("ttft"), "gen_tps": gen_tps, "prompt_tps": prompt_tps, "kv_peak_pct": max(window) if window else point["kv"], "aborted": bool(r.get("aborted")), }) if len(self._seen_runs) > 4 * RUNS_SHOWN: # The proxy only ever re-offers its own last RECENT_RUNS, so forgetting the # oldest keys can't resurrect a run we already have. self._seen_runs = {(r["t"], r["t"]) for r in self.runs} | { (q.get("start"), q.get("end")) for q in (metrics.get("recent") or [])} if self.action and phase in ("ready", "stopped", "failed") and now - self.action["t"] > 6: self.action = None self.state = { "time": now, "phase": phase, "service": svc_state, "uptime": uptime, "host": socket.gethostname(), "backend": cfg["backend"], "kind": cfg["kind"], "hardware": cfg.get("hardware_name"), "budget_gib": cfg.get("budget_gib"), "active": active, "served_models": served, "models": models, "excluded": cfg.get("excluded", []), "gpu": gpu, "last_log": last_log, "action": self.action, "metrics": { "running": metrics.get("running"), "waiting": metrics.get("waiting"), "kv_pct": point["kv"], "gen_tps": gen_rate, "prompt_tps": prompt_rate, "gen_total": metrics.get("gen_total"), "prompt_total": metrics.get("prompt_total"), "prefix_hit": ratio("prefix_hits", "prefix_queries"), "spec_accept": ratio("spec_accepted", "spec_drafted"), "preemptions": metrics.get("preemptions"), "ttft_last": self.last_ttft[1] if self.last_ttft else None, "ttft_last_t": self.last_ttft[0] if self.last_ttft else None, "ttft_avg": ratio("ttft_sum", "ttft_count"), "ttft_count": metrics.get("ttft_count"), "kv_bytes": metrics.get("kv_bytes"), "kv_seqs": metrics.get("kv_seqs"), "kv_budget_bytes": metrics.get("kv_budget_bytes"), "kv_peak_pct": (metrics["kv_peak_bytes"] / metrics["kv_budget_bytes"] * 100) if metrics.get("kv_peak_bytes") and metrics.get("kv_budget_bytes") else None, }, "runs": list(self.runs)[::-1], } def snapshot(self): with self.lock: s = dict(self.state) s["history"] = list(self.history) return s def control(self, kind, model=None): if kind == "switch": cfg = paths.load_config() cfg["active"] = model paths.save_config(cfg) self.cfg = cfg opencode.sync(cfg) # keep /models' "loaded" marker honest after a dashboard switch fn = service.restart else: fn = {"stop": service.stop, "start": service.start, "restart": service.restart}[kind] with self.lock: self.action = {"kind": kind, "model": model, "t": time.time()} self.history.clear() self.prev = None threading.Thread(target=fn, args=("model",), daemon=True).start() def make_handler(sampler, key): class Handler(BaseHTTPRequestHandler): server_version = "llm-host" def log_message(self, fmt, *args): pass def send_json(self, code, obj): body = json.dumps(obj).encode() self.send_response(code) self.send_header("Content-Type", "application/json") self.send_header("Cache-Control", "no-store") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def authed(self): h = self.headers.get("Authorization", "") tok = h[7:] if h.startswith("Bearer ") else "" if hmac.compare_digest(tok.encode(), key.encode()): return True self.send_json(401, {"error": "unauthorized"}) return False def do_GET(self): path = self.path.split("?", 1)[0] if path in ("/", "/index.html"): body = (HERE / "index.html").read_bytes() self.send_response(200) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Cache-Control", "no-store") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) elif path == "/api/status": if self.authed(): self.send_json(200, sampler.snapshot()) elif path == "/api/logs": if self.authed(): lines = [l for l in service.logs("model", 1500) if not PROGRESS_RE.search(l) and not OWN_POLL_RE.search(l)] self.send_json(200, {"lines": collapse_disconnects(lines)[-80:]}) else: self.send_json(404, {"error": "not found"}) def do_POST(self): path = self.path.split("?", 1)[0] if not self.authed(): return try: n = int(self.headers.get("Content-Length") or 0) data = json.loads(self.rfile.read(n) or b"{}") if n else {} except ValueError: return self.send_json(400, {"error": "bad json"}) if path == "/api/switch": name = str(data.get("model", "")) if name not in {m["name"] for m in sampler.cfg.get("models", [])}: return self.send_json(400, {"error": f"unknown model {name!r}"}) sampler.control("switch", name) return self.send_json(202, {"ok": True, "model": name}) if path in ("/api/stop", "/api/start", "/api/restart"): sampler.control(path.rsplit("/", 1)[1]) return self.send_json(202, {"ok": True}) self.send_json(404, {"error": "not found"}) return Handler def serve(): cfg = paths.load_config() if not cfg: raise SystemExit("not set up; run `llmhost setup`") key = paths.api_key() sampler = Sampler(cfg, key) threading.Thread(target=sampler.loop, daemon=True).start() srv = ThreadingHTTPServer(("0.0.0.0", cfg["web_port"]), make_handler(sampler, key)) print(f"llm-host dashboard on :{cfg['web_port']}", flush=True) srv.serve_forever()