Duration, TTFT and the two new columns use one formatter that grows units only as the value reaches them: 142 ms, 7.52 s, 31.2 s, then 1m 20s, then 1h 02m 06s. Sub-minute values keep their old precision, which is where almost every request lives; a long generation no longer reads as "80.4 s". Prompt sec and Generated sec show the two phases the rates were already computed over, so a row now says where its time went: an 8011-token prompt as 19.3 s of prefill at 415 tok/s, then 6.74 s generating 141 tokens at 20.9. The seconds come from the same split as the rates beside them -- a test asserts tok/s == tokens / seconds for both phases, so the two can't drift apart. A request that didn't stream has no first-token mark and so no split: its prompt seconds read "—" and its whole duration is charged to generation, which the column subtitle now says rather than leaving to be inferred. run_phases/run_row move out of the snapshot closure to module level, so the suite exercises the real row-building instead of a copy of it that had to be kept in step by hand. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
209 lines
12 KiB
Python
209 lines
12 KiB
Python
"""Dashboard tests: KV from mlx_lm's log line, per-run summaries, traceback collapsing."""
|
|
import json
|
|
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, 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 = 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",
|
|
b"2026-11-03 01:15:00,000 - INFO - - user: 3 sequences, 0.17 GB\n",
|
|
b"2026-11-03 01:16:00,000 - INFO - Prompt Cache: 9 sequences, 2.00 GB\n"]:
|
|
m = mlx.CACHE_RE.search(seg)
|
|
if m:
|
|
st.set_kv(int(m.group(1)), float(m.group(2)) * 1e9)
|
|
snap = st.snapshot()
|
|
check("latest size tracked", abs(snap["kv_bytes"] - 2.00e9) < 1, snap["kv_bytes"])
|
|
check("sequences tracked", snap["kv_seqs"] == 9, snap["kv_seqs"])
|
|
check("peak is the max seen, not the last", abs(snap["kv_peak_bytes"] - 4.24e9) < 1, snap["kv_peak_bytes"])
|
|
check("per-role lines ignored", snap["kv_seqs"] != 3, snap["kv_seqs"])
|
|
check("fraction against --prompt-cache-bytes", abs(snap["kv"] - 2.00e9 / (77.27 * 2**30)) < 1e-9, snap["kv"])
|
|
check("budget reported", snap["kv_budget_bytes"] == int(77.27 * 2**30))
|
|
|
|
print("\n2. no budget -> no fraction, but still a size")
|
|
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", proxy.Stats().snapshot()["kv"] is None)
|
|
|
|
print("\n3. run records survive the round trip")
|
|
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(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 {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")
|
|
class S(web.Sampler):
|
|
def __init__(self):
|
|
self.cfg = {"api_port": 1, "web_port": 2, "backend": "mlx", "kind": "apple", "models": [], "active": "m"}
|
|
import threading
|
|
from collections import deque
|
|
self.lock = threading.Lock(); self.history = deque(maxlen=web.HISTORY_POINTS)
|
|
self.prev = None; self.state = {}; self.action = None; self._dl_cache = (0, {})
|
|
self.last_ttft = None; self.runs = deque(maxlen=web.RUNS_SHOWN); self._seen_runs = set()
|
|
|
|
s = S()
|
|
# 10 s run: 2 s prefill for 7667 prompt tokens, 8 s generating 200 tokens
|
|
run = {"start": 100.0, "end": 110.0, "dur": 10.0, "gen": 200, "prompt": 7667, "ttft": 2.0}
|
|
for t, kv in ((99.0, 10.0), (101.0, 40.0), (105.0, 72.5), (109.0, 55.0), (111.0, 90.0)):
|
|
s.history.append({"t": t, "kv": kv, "gen": None, "prompt": None, "ttft": None,
|
|
"util": None, "temp": None, "power": None})
|
|
point = {"t": 111.0, "kv": 90.0}
|
|
|
|
# The merge loop's own bookkeeping, around the real run_row/run_kv_peak it calls.
|
|
def merge(sampler, recent, point):
|
|
for r in recent:
|
|
key = (r.get("start"), r.get("end"))
|
|
if key in sampler._seen_runs or r.get("start") is None: continue
|
|
sampler._seen_runs.add(key)
|
|
window = [q["kv"] for q in sampler.history
|
|
if q["kv"] is not None and r["start"] <= q["t"] <= r["end"]]
|
|
sampler.runs.append(web.run_row(r, max(window) if window else point["kv"]))
|
|
|
|
merge(s, [run], point)
|
|
r = s.runs[-1]
|
|
check("prompt seconds = time to first token", r["prompt_s"] == 2.0, r["prompt_s"])
|
|
check("generated seconds = what's left of the duration", r["gen_s"] == 8.0, r["gen_s"])
|
|
check("the two phases account for the whole run", r["prompt_s"] + r["gen_s"] == r["dur"], r)
|
|
check("prompt tok/s = prompt / ttft", abs(r["prompt_tps"] - 7667 / 2.0) < 1e-6, r["prompt_tps"])
|
|
check("gen tok/s excludes the prefill", abs(r["gen_tps"] - 200 / 8.0) < 1e-6, r["gen_tps"])
|
|
check("each rate matches the seconds shown next to it",
|
|
abs(r["prompt_tps"] - r["prompt"] / r["prompt_s"]) < 1e-9
|
|
and abs(r["gen_tps"] - r["gen"] / r["gen_s"]) < 1e-9, r)
|
|
check("peak KV from the run's own window", r["kv_peak_pct"] == 72.5, r["kv_peak_pct"])
|
|
check("points outside the window ignored", r["kv_peak_pct"] != 90.0)
|
|
merge(s, [run], point)
|
|
check("the same run isn't added twice", len(s.runs) == 1, len(s.runs))
|
|
|
|
print("\n5. degenerate runs don't divide by zero")
|
|
s2 = S()
|
|
merge(s2, [{"start": 1.0, "end": 1.0, "dur": 0.0, "gen": 0, "prompt": 0, "ttft": None}], {"t": 1, "kv": None})
|
|
r2 = s2.runs[-1]
|
|
check("no rates, no crash", r2["gen_tps"] is None and r2["prompt_tps"] is None, r2)
|
|
check("no seconds either, rather than a zero", r2["prompt_s"] is None and r2["gen_s"] is None, r2)
|
|
merge(s2, [{"start": 2.0, "end": 3.0, "dur": 1.0, "gen": 5, "prompt": 9, "ttft": 1.0}], {"t": 3, "kv": None})
|
|
check("ttft == dur -> gen rate falls back to duration", s2.runs[-1]["gen_tps"] == 5.0, s2.runs[-1])
|
|
check("...and the generated seconds say so too", s2.runs[-1]["gen_s"] == 1.0, s2.runs[-1])
|
|
merge(s2, [{"start": 4.0, "end": 6.0, "dur": 2.0, "gen": 8, "prompt": 40, "ttft": None}], {"t": 6, "kv": None})
|
|
nos = s2.runs[-1]
|
|
check("a run that didn't stream has no prompt seconds", nos["prompt_s"] is None, nos)
|
|
check("...no prompt rate to go with them", nos["prompt_tps"] is None, nos)
|
|
check("...and its whole duration counts as generation", nos["gen_s"] == 2.0 and nos["gen_tps"] == 4.0, nos)
|
|
check("no KV history -> current value", s2.runs[-1]["kv_peak_pct"] is None)
|
|
|
|
print("\n6. the broken-pipe traceback you saw collapses to one line")
|
|
REAL = """2026-11-03 00:39:30,482 - INFO - Prompt processing progress: 7667/7667
|
|
----------------------------------------
|
|
Exception occurred during processing of request from ('127.0.0.1', 62589)
|
|
Traceback (most recent call last):
|
|
File "/x/socketserver.py", line 697, in process_request_thread
|
|
self.finish_request(request, client_address)
|
|
File "/x/mlx_lm/server.py", line 1657, in handle_completion
|
|
self.wfile.write(f"data: {json.dumps(resp)}\\n\\n".encode())
|
|
File "/x/socketserver.py", line 845, in write
|
|
self._sock.sendall(b)
|
|
BrokenPipeError: [Errno 32] Broken pipe
|
|
----------------------------------------
|
|
2026-11-03 00:39:31,000 - INFO - Prompt Cache: 10 sequences, 1.58 GB""".splitlines()
|
|
out = web.collapse_disconnects(REAL)
|
|
check("collapsed", len(out) < len(REAL), f"{len(REAL)} -> {len(out)}")
|
|
check("one summary line", sum("client disconnected mid-answer" in l for l in out) == 1, out)
|
|
check("no traceback text left", not any("BrokenPipeError" in l or "socketserver" in l for l in out), out)
|
|
check("surrounding log kept", out[0].endswith("7667/7667") and "Prompt Cache" in out[-1], out)
|
|
|
|
print("\n7. a real traceback is NOT hidden")
|
|
OTHER = """----------------------------------------
|
|
Exception occurred during processing of request from ('127.0.0.1', 1)
|
|
Traceback (most recent call last):
|
|
File "/x/y.py", line 1, in z
|
|
boom()
|
|
ValueError: something actually broke
|
|
----------------------------------------""".splitlines()
|
|
out2 = web.collapse_disconnects(OTHER)
|
|
check("kept verbatim", any("ValueError: something actually broke" in l for l in out2), out2)
|
|
check("nothing claimed to be a disconnect", not any("disconnected" in l for l in out2))
|
|
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)
|