These grew one bug at a time in a scratch directory and were about to be thrown away, having caught four real regressions between them. Move them in as they are -- plain scripts, stdlib only, no test dependency -- behind a shared harness and `python3 tests/run.py`. The harness exists mostly for its guard. A suite testing the purge path once sandboxed LLMHOST_CONFIG but not LLMHOST_HOME and deleted a live install's data directory; BIN_DIR and SHIM have no env override at all, coming straight off Path.home(). So the harness repoints those into the sandbox and then asserts that every path llmhost could write or delete is inside it, aborting the run if not -- verified by pointing it at a real path and watching it refuse. The model plan the opencode suite needs is now a fixture rather than a file read out of someone's home directory; it carries no key (the key lives in its own file) and its machine-specific fields are pinned. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
145 lines
7.3 KiB
Python
145 lines
7.3 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
|
|
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.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 = mlx.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)
|
|
|
|
print("\n3. run records survive the round trip")
|
|
st3 = mlx.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):
|
|
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,
|
|
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}
|
|
gen_tps, prompt_tps = (None, None)
|
|
|
|
# exercise the real merge code by calling the block through a tiny shim
|
|
def merge(sampler, recent, point):
|
|
metrics = {"recent": recent}
|
|
def run_rates(r):
|
|
dur, ttft = r.get("dur") or 0, r.get("ttft")
|
|
p = (r["prompt"] / ttft) if (ttft and r.get("prompt")) else None
|
|
w = dur - ttft if (ttft is not None and dur > ttft) else dur
|
|
g = (r["gen"] / w) if (w and r.get("gen")) else None
|
|
return g, p
|
|
for r in metrics["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"]]
|
|
g, p = run_rates(r)
|
|
sampler.runs.append({"t": r["end"], "dur": r.get("dur"), "gen": r.get("gen"),
|
|
"prompt": r.get("prompt"), "ttft": r.get("ttft"),
|
|
"gen_tps": g, "prompt_tps": p,
|
|
"kv_peak_pct": max(window) if window else point["kv"],
|
|
"aborted": bool(r.get("aborted"))})
|
|
|
|
merge(s, [run], point)
|
|
r = s.runs[-1]
|
|
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("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)
|
|
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("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([]) == [])
|
|
|
|
check.done(ROOT)
|