Dashboard: KV cache on MLX, a completed-request table, honest GPU charts

Three gaps, all of them things the dashboard drew but never filled.

KV cache was never reported on MLX: /llmhost/metrics had no "kv" key at all,
so the tile and chart sat empty. mlx_lm has no endpoint for it, but it logs
"Prompt Cache: N sequences, X GB" (decimal GB, n_bytes/1e9) and that stream
already passes through _pump_output, so pick it out there and report a fraction
of --prompt-cache-bytes -- the same shape vLLM's kv already has, so the sampler
needs no backend special-casing. Peak is kept alongside the current value.

GPU temperature and power are root-only on macOS (powermetrics), so hw.live_stats
has always returned None for them on Apple. Two permanently blank charts is worse
than none: hide them and say why when the hardware doesn't report them.

Add a completed-request table above the server log: when each request finished,
its duration, time to first token, prompt and generated tokens, the rate for each
phase, and peak KV during the run. Rates are split at the first token -- prompt
tokens over TTFT, generated tokens over what's left -- since a single rate over
the whole duration blurs prefill into generation. The proxy keeps the last 50 runs;
peak KV is joined in by the sampler, which is the only side that samples KV on a
timer.

Also: close the upstream connection explicitly when a client hangs up mid-answer
rather than leaving it to GC, log that in one line, and collapse mlx_lm's
resulting BrokenPipeError traceback in the log view. Any other traceback is left
verbatim.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Neil Bantoc 2026-11-03 01:28:09 -08:00
parent 2c0818ca2b
commit 944eda06cc
3 changed files with 273 additions and 19 deletions

View file

@ -18,11 +18,56 @@ 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)\]")
METRIC_RE = re.compile(r"^(vllm:[a-z_]+)(\{[^}]*\})?\s+([0-9.eE+-]+|NaN)$")
# 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):
@ -78,6 +123,8 @@ class Sampler:
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
@ -160,6 +207,15 @@ class Sampler:
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)]
@ -170,6 +226,28 @@ class Sampler:
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 = {
@ -190,7 +268,13 @@ class Sampler:
"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):
@ -257,7 +341,7 @@ def make_handler(sampler, key):
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": lines[-80:]})
self.send_json(200, {"lines": collapse_disconnects(lines)[-80:]})
else:
self.send_json(404, {"error": "not found"})