Add tests/: four suites, a runner, and a sandbox that can't escape
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>
This commit is contained in:
parent
ba7bd76af6
commit
51c2880a2e
8 changed files with 852 additions and 0 deletions
19
README.md
19
README.md
|
|
@ -166,6 +166,25 @@ These avoid problems that come up on a fresh desktop install without sudo:
|
||||||
- Kernel builds are limited to one compile job per ~12 GB of RAM (unlimited builds can exhaust memory).
|
- Kernel builds are limited to one compile job per ~12 GB of RAM (unlimited builds can exhaust memory).
|
||||||
- `loginctl enable-linger` keeps the services running when you're logged out (and starts them at boot).
|
- `loginctl enable-linger` keeps the services running when you're logged out (and starts them at boot).
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
Stdlib only, no test dependencies, and nothing touches a real install — every suite redirects
|
||||||
|
`LLMHOST_HOME`, `LLMHOST_CONFIG` and `XDG_*` into a temp dir, and `tests/harness.py` aborts the
|
||||||
|
run if any path llmhost could write to resolves outside it.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 tests/run.py # every suite
|
||||||
|
python3 tests/run.py proxy # just the ones matching "proxy"
|
||||||
|
python3 tests/test_opencode.py # or run one directly
|
||||||
|
```
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| `tests/test_opencode.py` | provider naming and ownership, removal, the credential cache |
|
||||||
|
| `tests/test_proxy.py` | the API refusing a model that isn't loaded, against a fake `mlx_lm` |
|
||||||
|
| `tests/test_dashboard.py` | KV parsing, per-run summaries, log collapsing |
|
||||||
|
| `tests/test_reasoning.py` | effort options matching the real chat templates |
|
||||||
|
|
||||||
## Files
|
## Files
|
||||||
|
|
||||||
| Path | |
|
| Path | |
|
||||||
|
|
|
||||||
92
tests/fixtures/config.json
vendored
Normal file
92
tests/fixtures/config.json
vendored
Normal file
|
|
@ -0,0 +1,92 @@
|
||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"kind": "apple",
|
||||||
|
"backend": "mlx",
|
||||||
|
"hardware_name": "Apple M-series, 128 GB unified memory",
|
||||||
|
"budget_gib": 96.0,
|
||||||
|
"tp": 1,
|
||||||
|
"prefer": "balanced",
|
||||||
|
"api_port": 1134,
|
||||||
|
"web_port": 11340,
|
||||||
|
"max_jobs": 10,
|
||||||
|
"models": [
|
||||||
|
{
|
||||||
|
"name": "qwen3.8-27b",
|
||||||
|
"title": "Qwen3.8 27B",
|
||||||
|
"about": "Dense 27B, hybrid attention, strong general coding and tool use.",
|
||||||
|
"context": 262144,
|
||||||
|
"reasoning": true,
|
||||||
|
"format": "mlx-6bit",
|
||||||
|
"repo": "lmstudio-community/Qwen3.8-27B-MLX-6bit",
|
||||||
|
"weights_gib": 21.2,
|
||||||
|
"util": 1.0,
|
||||||
|
"est_context": 262144,
|
||||||
|
"mtp": false,
|
||||||
|
"free_gib": 71.34,
|
||||||
|
"prompt_cache_gib": 52.74
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "ornith-1.5-35b",
|
||||||
|
"title": "Ornith 1.5 35B A3B",
|
||||||
|
"about": "35B mixture-of-experts with 3B active: very fast.",
|
||||||
|
"context": 262144,
|
||||||
|
"reasoning": true,
|
||||||
|
"format": "mlx-6bit",
|
||||||
|
"repo": "ornith-ai/Ornith-1.5-35B-A3B-MLX-6bit",
|
||||||
|
"weights_gib": 26.3,
|
||||||
|
"util": 1.0,
|
||||||
|
"est_context": 262144,
|
||||||
|
"mtp": false,
|
||||||
|
"free_gib": 66.21,
|
||||||
|
"prompt_cache_gib": 60.91
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "qwen3-coder",
|
||||||
|
"title": "Qwen3 Coder 30B A3B",
|
||||||
|
"about": "Coding-tuned mixture-of-experts, no reasoning phase.",
|
||||||
|
"context": 262144,
|
||||||
|
"reasoning": false,
|
||||||
|
"format": "mlx-6bit",
|
||||||
|
"repo": "lmstudio-community/Qwen3-Coder-30B-A3B-Instruct-MLX-6bit",
|
||||||
|
"weights_gib": 23.1,
|
||||||
|
"util": 1.0,
|
||||||
|
"est_context": 262144,
|
||||||
|
"mtp": false,
|
||||||
|
"free_gib": 69.44,
|
||||||
|
"prompt_cache_gib": 45.44
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "ornith-1.5-122b",
|
||||||
|
"title": "Ornith 1.5 122B",
|
||||||
|
"about": "Largest option; needs ~80 GB of GPU memory even at 4-bit.",
|
||||||
|
"context": 262144,
|
||||||
|
"reasoning": true,
|
||||||
|
"format": "mlx-4bit",
|
||||||
|
"repo": "ornith-ai/Ornith-1.5-122B-MLX-4bit",
|
||||||
|
"weights_gib": 64.8,
|
||||||
|
"util": 1.0,
|
||||||
|
"est_context": 262144,
|
||||||
|
"mtp": false,
|
||||||
|
"free_gib": 26.88,
|
||||||
|
"prompt_cache_gib": 20.28
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "ornith-1.5-9b",
|
||||||
|
"title": "Ornith 1.5 9B",
|
||||||
|
"about": "Small dense model for 16 GB Macs and 12-16 GB GPUs; noticeably weaker at multi-step agentic work.",
|
||||||
|
"context": 262144,
|
||||||
|
"reasoning": true,
|
||||||
|
"format": "mlx-6bit",
|
||||||
|
"repo": "ornith-ai/Ornith-1.5-9B-MLX-6bit",
|
||||||
|
"weights_gib": 6.8,
|
||||||
|
"util": 1.0,
|
||||||
|
"est_context": 262144,
|
||||||
|
"mtp": false,
|
||||||
|
"free_gib": 86.07,
|
||||||
|
"prompt_cache_gib": 77.27
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"excluded": [],
|
||||||
|
"active": "ornith-1.5-9b",
|
||||||
|
"mlx": {}
|
||||||
|
}
|
||||||
76
tests/harness.py
Normal file
76
tests/harness.py
Normal file
|
|
@ -0,0 +1,76 @@
|
||||||
|
"""Shared bits for the suites: repo-relative imports, a sandbox, and a check() counter.
|
||||||
|
|
||||||
|
Each suite is a plain script: run it directly, or run them all with `python3 tests/run.py`.
|
||||||
|
Stdlib only, like the rest of llm-host.
|
||||||
|
|
||||||
|
Every suite sandboxes LLMHOST_HOME / LLMHOST_CONFIG / XDG_* before importing llmhost, so
|
||||||
|
nothing touches a real install. setup() asserts that, because a suite that forgot
|
||||||
|
LLMHOST_HOME once deleted a live install's data directory.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
REPO = Path(__file__).resolve().parents[1]
|
||||||
|
FIXTURES = Path(__file__).resolve().parent / "fixtures"
|
||||||
|
|
||||||
|
|
||||||
|
def setup():
|
||||||
|
"""Point every path llmhost writes to at a fresh temp dir. Returns its root."""
|
||||||
|
root = tempfile.mkdtemp(prefix="llmhost-test-")
|
||||||
|
os.environ["LLMHOST_HOME"] = root + "/.local/share/llm-host"
|
||||||
|
os.environ["LLMHOST_CONFIG"] = root + "/.config/llm-host"
|
||||||
|
os.environ["XDG_CONFIG_HOME"] = root + "/.config"
|
||||||
|
os.environ["XDG_DATA_HOME"] = root + "/.local/share"
|
||||||
|
sys.path.insert(0, str(REPO))
|
||||||
|
return root
|
||||||
|
|
||||||
|
|
||||||
|
def guard(paths, root):
|
||||||
|
"""Move the paths no env var covers into the sandbox, then abort unless everything
|
||||||
|
llmhost could write or delete is inside it.
|
||||||
|
|
||||||
|
LLMHOST_HOME and LLMHOST_CONFIG redirect most of it, but BIN_DIR/SHIM come off
|
||||||
|
Path.home() with no override, so they are repointed here -- once, for every suite,
|
||||||
|
rather than per test. The assertion is the real safety net: a suite that forgot
|
||||||
|
LLMHOST_HOME once deleted a live install's data directory."""
|
||||||
|
paths.BIN_DIR = Path(root) / ".local/bin"
|
||||||
|
paths.SHIM = paths.BIN_DIR / "llmhost"
|
||||||
|
paths.LOG_DIR = Path(root) / "logs"
|
||||||
|
for name in ("DATA", "CONFIG_DIR", "CONFIG_FILE", "KEY_FILE", "BIN_DIR", "SHIM", "LOG_DIR"):
|
||||||
|
value = str(getattr(paths, name))
|
||||||
|
if not value.startswith(root):
|
||||||
|
sys.exit(f"ABORT: paths.{name} = {value} is outside the sandbox {root}")
|
||||||
|
|
||||||
|
|
||||||
|
def config():
|
||||||
|
"""The planned-models fixture: a real `llmhost setup` result, machine bits pinned."""
|
||||||
|
return json.loads((FIXTURES / "config.json").read_text())
|
||||||
|
|
||||||
|
|
||||||
|
class Checks:
|
||||||
|
def __init__(self):
|
||||||
|
self.failed = []
|
||||||
|
self.passed = 0
|
||||||
|
|
||||||
|
def __call__(self, label, cond, extra=""):
|
||||||
|
if cond:
|
||||||
|
self.passed += 1
|
||||||
|
print(" ok " + label)
|
||||||
|
else:
|
||||||
|
self.failed.append(label)
|
||||||
|
print(" FAIL " + label + ((" <- " + str(extra)) if extra else ""))
|
||||||
|
return bool(cond)
|
||||||
|
|
||||||
|
def section(self, title):
|
||||||
|
print("\n" + title)
|
||||||
|
|
||||||
|
def done(self, root=None):
|
||||||
|
if root:
|
||||||
|
shutil.rmtree(root, ignore_errors=True)
|
||||||
|
print("\n" + (f"ALL PASS ({self.passed} checks)" if not self.failed
|
||||||
|
else f"{len(self.failed)} FAILURES of {self.passed + len(self.failed)}: {self.failed}"))
|
||||||
|
sys.exit(1 if self.failed else 0)
|
||||||
45
tests/run.py
Executable file
45
tests/run.py
Executable file
|
|
@ -0,0 +1,45 @@
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Run every suite in tests/ and summarise. Exits nonzero if any failed.
|
||||||
|
|
||||||
|
python3 tests/run.py all suites
|
||||||
|
python3 tests/run.py proxy just the ones whose name contains "proxy"
|
||||||
|
"""
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
HERE = Path(__file__).resolve().parent
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv):
|
||||||
|
picks = argv[1:]
|
||||||
|
suites = sorted(p for p in HERE.glob("test_*.py")
|
||||||
|
if not picks or any(a in p.stem for a in picks))
|
||||||
|
if not suites:
|
||||||
|
print("no suites matched", picks)
|
||||||
|
return 1
|
||||||
|
width = max(len(p.stem) for p in suites)
|
||||||
|
results, total = [], 0
|
||||||
|
for p in suites:
|
||||||
|
r = subprocess.run([sys.executable, str(p)], capture_output=True, text=True)
|
||||||
|
tail = [l for l in r.stdout.splitlines() if l.strip()]
|
||||||
|
summary = tail[-1] if tail else "(no output)"
|
||||||
|
ok = r.returncode == 0
|
||||||
|
count = 0
|
||||||
|
for word in summary.replace("(", " ").replace(")", " ").split():
|
||||||
|
if word.isdigit():
|
||||||
|
count = int(word)
|
||||||
|
break
|
||||||
|
total += count if ok else 0
|
||||||
|
print(f" {p.stem:<{width}} {'PASS' if ok else 'FAIL'} {summary}")
|
||||||
|
if not ok:
|
||||||
|
print("\n".join(" " + l for l in r.stdout.splitlines() if "FAIL" in l))
|
||||||
|
if r.stderr.strip():
|
||||||
|
print(" stderr: " + r.stderr.strip().splitlines()[-1])
|
||||||
|
results.append(ok)
|
||||||
|
print(f"\n{sum(results)}/{len(results)} suites passed, {total} checks")
|
||||||
|
return 0 if all(results) else 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main(sys.argv))
|
||||||
145
tests/test_dashboard.py
Normal file
145
tests/test_dashboard.py
Normal file
|
|
@ -0,0 +1,145 @@
|
||||||
|
"""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)
|
||||||
271
tests/test_opencode.py
Normal file
271
tests/test_opencode.py
Normal file
|
|
@ -0,0 +1,271 @@
|
||||||
|
"""opencode integration: provider naming, ownership, removal, the credential cache."""
|
||||||
|
import json, os, shutil, pathlib
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||||
|
import harness
|
||||||
|
|
||||||
|
ROOT = harness.setup()
|
||||||
|
from llmhost import opencode, paths
|
||||||
|
|
||||||
|
harness.guard(paths, ROOT)
|
||||||
|
CFG = harness.config()
|
||||||
|
OC = opencode.config_file()
|
||||||
|
check = harness.Checks()
|
||||||
|
|
||||||
|
def reset(data=None):
|
||||||
|
shutil.rmtree(OC.parent, ignore_errors=True)
|
||||||
|
if data is not None:
|
||||||
|
OC.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
OC.write_text(json.dumps(data, indent=2))
|
||||||
|
|
||||||
|
def load():
|
||||||
|
return json.loads(OC.read_text())
|
||||||
|
|
||||||
|
def remote(host, prov=None):
|
||||||
|
prov = prov or opencode.remote_provider(host)
|
||||||
|
return prov, opencode.provider_block(CFG, host, opencode.remote_key_file(prov), host)
|
||||||
|
|
||||||
|
print("\n1. fresh install")
|
||||||
|
reset()
|
||||||
|
st, path, prov, authcl = opencode.configure(CFG)
|
||||||
|
d = load()
|
||||||
|
check("status added", st == "added", st)
|
||||||
|
check("id is llmhost", prov == "llmhost", prov)
|
||||||
|
check('name is "LLMHost (Local)"', d["provider"]["llmhost"]["name"] == "LLMHost (Local)", d["provider"]["llmhost"]["name"])
|
||||||
|
check("baseURL localhost", d["provider"]["llmhost"]["options"]["baseURL"] == "http://localhost:1134/v1")
|
||||||
|
check("apiKey -> llm-host key file", str(paths.KEY_FILE) in d["provider"]["llmhost"]["options"]["apiKey"])
|
||||||
|
check("model set", d["model"] == "llmhost/ornith-1.5-9b", d.get("model"))
|
||||||
|
mods = d["provider"]["llmhost"]["models"]
|
||||||
|
check("model keyed by slug", "qwen3.8-27b" in mods, list(mods))
|
||||||
|
check("label = title + slug", mods["qwen3.8-27b"]["name"] == "Qwen3.8 27B \u00b7 qwen3.8-27b (Local)", mods["qwen3.8-27b"]["name"])
|
||||||
|
check("active model marked loaded", mods[CFG["active"]]["name"].endswith("(Local, loaded)"), mods[CFG["active"]]["name"])
|
||||||
|
check("only the active one is marked",
|
||||||
|
sum(v["name"].endswith(", loaded)") for v in mods.values()) == 1,
|
||||||
|
[v["name"] for v in mods.values()])
|
||||||
|
check("slug searchable for every model", all(k in v["name"] for k, v in mods.items()))
|
||||||
|
|
||||||
|
print("\n2. local + remote side by side")
|
||||||
|
rp, rb = remote("popos.local")
|
||||||
|
reset({"provider": {rp: rb}, "model": f"{rp}/qwen3.8-27b"})
|
||||||
|
st, path, prov, authcl = opencode.configure(CFG)
|
||||||
|
d = load()
|
||||||
|
check("remote id is llmhost-popos", rp == "llmhost-popos", rp)
|
||||||
|
check('remote name is "LLMHost (popos.local)"', rb["name"] == "LLMHost (popos.local)", rb["name"])
|
||||||
|
check("remote model label", rb["models"]["qwen3.8-27b"]["name"] == "Qwen3.8 27B \u00b7 qwen3.8-27b (popos.local)", rb["models"]["qwen3.8-27b"]["name"])
|
||||||
|
check("remote block is NOT marked loaded", not any(", loaded)" in v["name"] for v in rb["models"].values()),
|
||||||
|
[v["name"] for v in rb["models"].values()])
|
||||||
|
check("local added alongside", sorted(d["provider"]) == ["llmhost", "llmhost-popos"], sorted(d["provider"]))
|
||||||
|
check("remote untouched", d["provider"][rp] == rb)
|
||||||
|
check("existing model kept", d["model"] == f"{rp}/qwen3.8-27b", d["model"])
|
||||||
|
|
||||||
|
print("\n3. a REMOTE block squatting on the `llmhost` id (gap 1)")
|
||||||
|
_, rb2 = remote("popos.local", prov="llmhost")
|
||||||
|
reset({"provider": {"llmhost": rb2}})
|
||||||
|
st, path, prov, authcl = opencode.configure(CFG)
|
||||||
|
d = load()
|
||||||
|
check("did not reuse `llmhost`", prov == "llmhost-local", prov)
|
||||||
|
check("remote block intact", d["provider"]["llmhost"] == rb2)
|
||||||
|
check("local under llmhost-local", d["provider"]["llmhost-local"]["options"]["baseURL"] == "http://localhost:1134/v1")
|
||||||
|
|
||||||
|
print("\n4. user renamed the local provider (gap 2)")
|
||||||
|
reset({"provider": {"mymac": opencode.local_block(CFG)}, "model": "mymac/ornith-1.5-9b"})
|
||||||
|
st, path, prov, authcl = opencode.configure(CFG)
|
||||||
|
d = load()
|
||||||
|
check("recognised under new name", prov == "mymac", prov)
|
||||||
|
check("no duplicate added", list(d["provider"]) == ["mymac"], list(d["provider"]))
|
||||||
|
check("status unchanged", st == "unchanged", st)
|
||||||
|
|
||||||
|
print("\n5. uninstall: remove local, keep remote, repoint model")
|
||||||
|
rp, rb = remote("popos.local")
|
||||||
|
reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}, "model": "llmhost/ornith-1.5-9b"})
|
||||||
|
st, path, removed, new_model = opencode.remove(local=True)
|
||||||
|
d = load()
|
||||||
|
check("status removed", st == "removed", st)
|
||||||
|
check("removed only local", removed == ["llmhost"], removed)
|
||||||
|
check("remote survives", list(d["provider"]) == [rp], list(d["provider"]))
|
||||||
|
first = CFG["models"][0]["name"]
|
||||||
|
check("model repointed to remote's first (plan-order) model",
|
||||||
|
new_model == f"{rp}/{first}" and d["model"] == new_model, (new_model, d.get("model")))
|
||||||
|
|
||||||
|
print("\n6. uninstall must NOT glob llmhost*")
|
||||||
|
reset({"provider": {rp: rb}, "model": f"{rp}/qwen3.8-27b"})
|
||||||
|
st, path, removed, new_model = opencode.remove(local=True)
|
||||||
|
check("nothing matched", st == "none" and removed == [], (st, removed))
|
||||||
|
check("remote still there", list(load()["provider"]) == [rp])
|
||||||
|
|
||||||
|
print("\n7. retiring a remote server (gap 3)")
|
||||||
|
reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}, "model": f"{rp}/qwen3.8-27b"})
|
||||||
|
st, path, removed, new_model = opencode.remove(local=False, host="popos.local")
|
||||||
|
d = load()
|
||||||
|
check("removed the remote", removed == [rp], removed)
|
||||||
|
check("local survives", list(d["provider"]) == ["llmhost"], list(d["provider"]))
|
||||||
|
check("model repointed to local", d["model"].startswith("llmhost/"), d.get("model"))
|
||||||
|
reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}})
|
||||||
|
st, path, removed, _ = opencode.remove(local=False, host="popos")
|
||||||
|
check("short hostname also matches", removed == [rp], removed)
|
||||||
|
|
||||||
|
print("\n8. --all drops the model key when nothing is left")
|
||||||
|
reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}, "model": "llmhost/ornith-1.5-9b"})
|
||||||
|
st, path, removed, new_model = opencode.remove(local=False, every=True)
|
||||||
|
d = load()
|
||||||
|
check("both removed", sorted(removed) == ["llmhost", rp], removed)
|
||||||
|
check("model key dropped", "model" not in d and new_model is None, d)
|
||||||
|
check("provider key dropped", "provider" not in d, d)
|
||||||
|
|
||||||
|
print("\n9. foreign providers are never touched")
|
||||||
|
foreign = {"npm": "@ai-sdk/openai-compatible", "name": "vLLM (popos)",
|
||||||
|
"options": {"baseURL": "http://popos.local:1134/v1", "apiKey": "{file:~/.config/opencode/popos-vllm.key}"},
|
||||||
|
"models": {"x": {"name": "x"}}}
|
||||||
|
reset({"provider": {"popos-vllm": foreign, "llmhost": opencode.local_block(CFG)}, "model": "popos-vllm/x"})
|
||||||
|
st, path, removed, new_model = opencode.remove(local=True)
|
||||||
|
d = load()
|
||||||
|
check("only ours removed", removed == ["llmhost"], removed)
|
||||||
|
check("foreign intact", d["provider"]["popos-vllm"] == foreign)
|
||||||
|
check("foreign model untouched", d["model"] == "popos-vllm/x", d.get("model"))
|
||||||
|
st, path, removed, _ = opencode.remove(local=False, every=True)
|
||||||
|
check("--all skips foreign", removed == [], removed)
|
||||||
|
|
||||||
|
print("\n10. .jsonc with comments is left alone")
|
||||||
|
shutil.rmtree(OC.parent, ignore_errors=True)
|
||||||
|
OC.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
j = OC.parent / "opencode.jsonc"
|
||||||
|
orig = '{\n // mine\n "provider": {}\n}\n'
|
||||||
|
j.write_text(orig)
|
||||||
|
st, path, prov, authcl = opencode.configure(CFG)
|
||||||
|
check("configure reports has-comments", st == "has-comments", st)
|
||||||
|
check("file unchanged", j.read_text() == orig)
|
||||||
|
st, path, removed, _ = opencode.remove(local=True)
|
||||||
|
check("remove reports has-comments", st == "has-comments", st)
|
||||||
|
check("file still unchanged", j.read_text() == orig)
|
||||||
|
check("snippet has the new name", '"LLMHost (Local)"' in opencode.snippet(CFG))
|
||||||
|
|
||||||
|
print("\n11. unparsable JSON is left alone")
|
||||||
|
reset(); OC.parent.mkdir(parents=True, exist_ok=True); OC.write_text("{ broken")
|
||||||
|
st, path, prov, authcl = opencode.configure(CFG)
|
||||||
|
check("configure reports unparsable", st == "unparsable", st)
|
||||||
|
check("file unchanged", OC.read_text() == "{ broken")
|
||||||
|
|
||||||
|
print("\n12. missing/garbage blocks don't crash the fingerprint")
|
||||||
|
reset({"provider": {"a": None, "b": "nope", "c": {}, "d": {"options": {}}}})
|
||||||
|
check("no crash, nothing ours", opencode.local_ids(load()["provider"]) == [])
|
||||||
|
st, path, prov, authcl = opencode.configure(CFG)
|
||||||
|
check("still installs", prov == "llmhost" and st == "added", (prov, st))
|
||||||
|
|
||||||
|
print("\n13. --host must not take a foreign provider on the same host (regression)")
|
||||||
|
rp, rb = remote("popos.local")
|
||||||
|
reset({"provider": {rp: rb, "popos-vllm": foreign, "llmhost": opencode.local_block(CFG)},
|
||||||
|
"model": "popos-vllm/x"})
|
||||||
|
st, path, removed, new_model = opencode.remove(local=False, host="popos.local")
|
||||||
|
d = load()
|
||||||
|
check("removed only ours", removed == [rp], removed)
|
||||||
|
check("foreign on same host survives", "popos-vllm" in d["provider"])
|
||||||
|
check("local survives", "llmhost" in d["provider"])
|
||||||
|
check("foreign model untouched", d["model"] == "popos-vllm/x", d.get("model"))
|
||||||
|
|
||||||
|
print("\n14. a stale cached key is cleared on configure")
|
||||||
|
def put_auth(d, mode=0o600):
|
||||||
|
f = opencode.auth_file(); f.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
fd = os.open(f, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode)
|
||||||
|
with os.fdopen(fd, "w") as fh: json.dump(d, fh)
|
||||||
|
return f
|
||||||
|
|
||||||
|
def get_auth():
|
||||||
|
return json.loads(opencode.auth_file().read_text())
|
||||||
|
|
||||||
|
reset()
|
||||||
|
af = put_auth({"llmhost": {"type": "api", "key": "sk-STALE"}, "anthropic": {"type": "oauth", "t": 1}})
|
||||||
|
st, path, prov, authcl = opencode.configure(CFG)
|
||||||
|
a = get_auth()
|
||||||
|
check("reported clearing the cache", authcl is True, authcl)
|
||||||
|
check("stale llmhost entry gone", "llmhost" not in a, a)
|
||||||
|
check("other providers' creds untouched", a.get("anthropic") == {"type": "oauth", "t": 1}, a)
|
||||||
|
check("file mode preserved (0600)", oct(af.stat().st_mode & 0o777) == "0o600", oct(af.stat().st_mode & 0o777))
|
||||||
|
|
||||||
|
print("\n15. nothing cached -> nothing reported, no file created")
|
||||||
|
reset(); opencode.auth_file().unlink(missing_ok=True)
|
||||||
|
st, path, prov, authcl = opencode.configure(CFG)
|
||||||
|
check("no clear reported", authcl is False, authcl)
|
||||||
|
check("no auth.json invented", not opencode.auth_file().exists())
|
||||||
|
reset(); put_auth({"other": {"type": "api", "key": "x"}})
|
||||||
|
st, path, prov, authcl = opencode.configure(CFG)
|
||||||
|
check("untouched when we have no entry", authcl is False and get_auth() == {"other": {"type": "api", "key": "x"}})
|
||||||
|
|
||||||
|
print("\n16. an unreadable auth store is left alone, not repaired")
|
||||||
|
reset()
|
||||||
|
f = opencode.auth_file(); f.parent.mkdir(parents=True, exist_ok=True); f.write_text("{ not json")
|
||||||
|
st, path, prov, authcl = opencode.configure(CFG)
|
||||||
|
check("no crash", st == "added", st)
|
||||||
|
check("left verbatim", f.read_text() == "{ not json")
|
||||||
|
check("reported nothing cleared", authcl is False, authcl)
|
||||||
|
|
||||||
|
print("\n17. remove() takes the cached key with the provider")
|
||||||
|
reset({"provider": {"llmhost": opencode.local_block(CFG), "llmhost-popos": remote("popos.local")[1]}})
|
||||||
|
put_auth({"llmhost": {"type": "api", "key": "sk-A"}, "llmhost-popos": {"type": "api", "key": "sk-B"}})
|
||||||
|
st, path, removed, _ = opencode.remove(local=True)
|
||||||
|
a = get_auth()
|
||||||
|
check("local cred cleared", "llmhost" not in a, a)
|
||||||
|
check("remote cred kept", a.get("llmhost-popos") == {"type": "api", "key": "sk-B"}, a)
|
||||||
|
|
||||||
|
print("\n18. purge --keep-key keeps the API key through a purge")
|
||||||
|
from llmhost import cli
|
||||||
|
cli_shim = pathlib.Path(ROOT) / "bin/llmhost"
|
||||||
|
cli_shim.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
paths.SHIM = cli_shim # never touch the real launcher from a test
|
||||||
|
|
||||||
|
for name in ("DATA", "CONFIG_DIR", "KEY_FILE", "SHIM"):
|
||||||
|
val = str(getattr(paths, name))
|
||||||
|
if not val.startswith(ROOT):
|
||||||
|
sys.exit(f"ABORT: paths.{name} = {val} is outside the sandbox {ROOT}; "
|
||||||
|
"purge() would delete a real install")
|
||||||
|
|
||||||
|
def seed():
|
||||||
|
paths.CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
paths.DATA.mkdir(parents=True, exist_ok=True)
|
||||||
|
(paths.DATA / "venv-mlx").mkdir(exist_ok=True)
|
||||||
|
key = paths.api_key(create=True)
|
||||||
|
paths.save_config({"active": "x"})
|
||||||
|
cli_shim.write_text("#!/bin/sh\n")
|
||||||
|
return key
|
||||||
|
|
||||||
|
key = seed()
|
||||||
|
kept = cli.purge(keep_key=True)
|
||||||
|
check("reported the kept path", kept == paths.KEY_FILE, kept)
|
||||||
|
check("key file survives", paths.KEY_FILE.exists())
|
||||||
|
check("key value unchanged", paths.KEY_FILE.read_text().strip() == key.strip(), paths.KEY_FILE.read_text())
|
||||||
|
check("key mode is 0600", oct(paths.KEY_FILE.stat().st_mode & 0o777) == "0o600", oct(paths.KEY_FILE.stat().st_mode & 0o777))
|
||||||
|
check("config.json gone", not paths.CONFIG_FILE.exists())
|
||||||
|
check("data dir gone", not paths.DATA.exists())
|
||||||
|
check("launcher gone", not cli_shim.exists())
|
||||||
|
check("a reinstall would reuse it", paths.api_key(create=True).strip() == key.strip())
|
||||||
|
|
||||||
|
print("\n19. purge without --keep-key removes everything")
|
||||||
|
key2 = seed()
|
||||||
|
kept = cli.purge(keep_key=False)
|
||||||
|
check("reported nothing kept", kept is None, kept)
|
||||||
|
check("key file gone", not paths.KEY_FILE.exists())
|
||||||
|
check("config dir gone", not paths.CONFIG_DIR.exists())
|
||||||
|
check("a reinstall mints a different key", paths.api_key(create=True).strip() != key2.strip())
|
||||||
|
|
||||||
|
print("\n20. sync() refreshes an existing block after a switch")
|
||||||
|
reset({"provider": {"llmhost": opencode.local_block(CFG)}, "model": "llmhost/" + CFG["active"]})
|
||||||
|
switched = dict(CFG, active="qwen3-coder")
|
||||||
|
prov = opencode.sync(switched)
|
||||||
|
mods = load()["provider"]["llmhost"]["models"]
|
||||||
|
check("reported the provider", prov == "llmhost", prov)
|
||||||
|
check("new model marked loaded", mods["qwen3-coder"]["name"].endswith("(Local, loaded)"), mods["qwen3-coder"]["name"])
|
||||||
|
check("old one unmarked", not mods[CFG["active"]]["name"].endswith(", loaded)"), mods[CFG["active"]]["name"])
|
||||||
|
check("idempotent", opencode.sync(switched) is None)
|
||||||
|
|
||||||
|
print("\n21. sync() never wires opencode up on its own")
|
||||||
|
reset()
|
||||||
|
check("no config file -> no-op", opencode.sync(CFG) is None)
|
||||||
|
check("still no config file", not opencode.config_file().exists())
|
||||||
|
reset({"provider": {"popos-vllm": foreign}, "model": "popos-vllm/x"})
|
||||||
|
check("no local block -> no-op", opencode.sync(CFG) is None)
|
||||||
|
check("foreign provider untouched", load()["provider"] == {"popos-vllm": foreign})
|
||||||
|
reset({"provider": {"mymac": opencode.local_block(CFG)}})
|
||||||
|
check("finds a renamed local block", opencode.sync(dict(CFG, active="qwen3-coder")) == "mymac")
|
||||||
|
|
||||||
|
check.done(ROOT)
|
||||||
113
tests/test_proxy.py
Normal file
113
tests/test_proxy.py
Normal file
|
|
@ -0,0 +1,113 @@
|
||||||
|
"""Proxy tests: the model name a client asks for must be honoured or refused, never ignored."""
|
||||||
|
import json, threading, urllib.error, urllib.request
|
||||||
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
|
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
|
||||||
|
|
||||||
|
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
|
||||||
|
check = harness.Checks()
|
||||||
|
|
||||||
|
|
||||||
|
class Inner(BaseHTTPRequestHandler):
|
||||||
|
protocol_version = "HTTP/1.1"
|
||||||
|
def log_message(self, *a): pass
|
||||||
|
def do_POST(self):
|
||||||
|
n = int(self.headers.get("Content-Length") or 0)
|
||||||
|
raw = self.rfile.read(n) if n else b""
|
||||||
|
try: seen.append(json.loads(raw or b"{}"))
|
||||||
|
except ValueError: seen.append(None)
|
||||||
|
body = json.dumps({"id": "x", "object": "chat.completion", "model": "default_model",
|
||||||
|
"created": 0, "choices": [{"index": 0, "finish_reason": "stop",
|
||||||
|
"message": {"role": "assistant", "content": "pong"}}],
|
||||||
|
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}}).encode()
|
||||||
|
self.send_response(200)
|
||||||
|
self.send_header("Content-Type", "application/json")
|
||||||
|
self.send_header("Content-Length", str(len(body)))
|
||||||
|
self.end_headers(); self.wfile.write(body)
|
||||||
|
|
||||||
|
|
||||||
|
def serve(handler, port):
|
||||||
|
srv = ThreadingHTTPServer(("127.0.0.1", port), handler)
|
||||||
|
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||||
|
return srv
|
||||||
|
|
||||||
|
|
||||||
|
INNER, OUTER = 18231, 18232
|
||||||
|
serve(Inner, INNER)
|
||||||
|
stats = mlx.Stats()
|
||||||
|
serve(mlx.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}
|
||||||
|
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(),
|
||||||
|
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"{}")
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
try: return e.code, json.loads(e.read() or b"{}")
|
||||||
|
except ValueError: return e.code, {}
|
||||||
|
|
||||||
|
|
||||||
|
print("\n1. the loaded model is accepted")
|
||||||
|
seen.clear()
|
||||||
|
code, body = post(SERVED)
|
||||||
|
check("200", code == 200, code)
|
||||||
|
check("answered", body.get("choices", [{}])[0].get("message", {}).get("content") == "pong", body)
|
||||||
|
check("forwarded as default_model (mlx_lm must not try to load by name)",
|
||||||
|
seen and seen[-1].get("model") == "default_model", seen[-1] if seen else None)
|
||||||
|
|
||||||
|
print("\n2. the repo id is accepted as an alias")
|
||||||
|
check("200", post(REPO)[0] == 200)
|
||||||
|
print("\n3. case differences are accepted")
|
||||||
|
check("200", post(SERVED.upper())[0] == 200)
|
||||||
|
print("\n4. no model named -> the loaded one")
|
||||||
|
check("200 when absent", post(None)[0] == 200)
|
||||||
|
check("200 when empty", post("")[0] == 200)
|
||||||
|
check("200 when blank", post(" ")[0] == 200)
|
||||||
|
|
||||||
|
print("\n5. a model that ISN'T loaded is refused, not silently answered")
|
||||||
|
code, body = post("qwen3.8-27b")
|
||||||
|
check("404", code == 404, code)
|
||||||
|
err = body.get("error") or {}
|
||||||
|
check("code=model_not_found", err.get("code") == "model_not_found", err)
|
||||||
|
check("param=model", err.get("param") == "model", err)
|
||||||
|
check("names the model asked for", "qwen3.8-27b" in err.get("message", ""), err)
|
||||||
|
check("names the loaded model", SERVED in err.get("message", ""), err)
|
||||||
|
check("says how to load it", "llmhost switch" in err.get("message", ""), err)
|
||||||
|
seen.clear()
|
||||||
|
post("qwen3.8-27b")
|
||||||
|
check("never reached the model server", seen == [], seen)
|
||||||
|
|
||||||
|
print("\n6. unknown junk is refused too")
|
||||||
|
check("404", post("../etc/passwd")[0] == 404)
|
||||||
|
check("404", post("gpt-4")[0] == 404)
|
||||||
|
|
||||||
|
print("\n7. auth still comes first")
|
||||||
|
code, body = post("qwen3.8-27b", key="sk-wrong")
|
||||||
|
check("401, not 404 (key checked before the model)", code == 401, code)
|
||||||
|
|
||||||
|
print("\n8. /v1/models still advertises the served name")
|
||||||
|
req = urllib.request.Request(f"http://127.0.0.1:{OUTER}/v1/models",
|
||||||
|
headers={"Authorization": f"Bearer {KEY}"})
|
||||||
|
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.done(ROOT)
|
||||||
91
tests/test_reasoning.py
Normal file
91
tests/test_reasoning.py
Normal file
|
|
@ -0,0 +1,91 @@
|
||||||
|
"""Reasoning-effort tests: options must match what the template really accepts, and a
|
||||||
|
client's own chat_template_kwargs must always win over the server default."""
|
||||||
|
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, plan
|
||||||
|
|
||||||
|
harness.guard(paths, ROOT)
|
||||||
|
check = harness.Checks()
|
||||||
|
|
||||||
|
BOTH = {"thinking": True, "effort": True}
|
||||||
|
THINK = {"thinking": True, "effort": False}
|
||||||
|
NONE = {"thinking": False, "effort": False}
|
||||||
|
QWEN = {"name": "qwen3.8-27b", "reasoning": True,
|
||||||
|
"effort": {"levels": ["low", "medium", "xhigh"], "default": "xhigh"}}
|
||||||
|
ORNITH = {"name": "ornith-1.5-9b", "reasoning": True}
|
||||||
|
CODER = {"name": "qwen3-coder", "reasoning": False}
|
||||||
|
|
||||||
|
print("\n1. options follow the template, not the catalog alone")
|
||||||
|
vals = lambda e, c: [v for v, _ in plan.reasoning_options(e, None, c)]
|
||||||
|
check("full set when the template reads both", vals(QWEN, BOTH) == ["default", "xhigh", "medium", "low", "off"], vals(QWEN, BOTH))
|
||||||
|
check("most effort first", vals(QWEN, BOTH)[1] == "xhigh", vals(QWEN, BOTH))
|
||||||
|
check("levels dropped if the template ignores them", vals(QWEN, THINK) == ["default", "off"], vals(QWEN, THINK))
|
||||||
|
check("nothing at all if it reads neither", vals(QWEN, NONE) == [], vals(QWEN, NONE))
|
||||||
|
check("thinking-only model gets on/off", vals(ORNITH, THINK) == ["default", "off"], vals(ORNITH, THINK))
|
||||||
|
check("no levels invented for it", "low" not in vals(ORNITH, BOTH), vals(ORNITH, BOTH))
|
||||||
|
check("non-reasoning model gets no control", vals(CODER, BOTH) == [], vals(CODER, BOTH))
|
||||||
|
check("a lone 'default' is not a choice", vals({"name": "x", "reasoning": True}, NONE) == [])
|
||||||
|
labels = dict(plan.reasoning_options(QWEN, None, BOTH))
|
||||||
|
check("xhigh reads as a word", labels["xhigh"] == "Extra high", labels)
|
||||||
|
|
||||||
|
print("\n2. kwargs are only ever what the template accepts")
|
||||||
|
kw = lambda v, e, c: plan.reasoning_kwargs(v, e, c)
|
||||||
|
check("default sends nothing", kw("default", QWEN, BOTH) == {})
|
||||||
|
check("None sends nothing", kw(None, QWEN, BOTH) == {})
|
||||||
|
check("off -> enable_thinking false", kw("off", QWEN, BOTH) == {"enable_thinking": False})
|
||||||
|
check("level -> reasoning_effort", kw("low", QWEN, BOTH) == {"reasoning_effort": "low"})
|
||||||
|
check("xhigh passes through", kw("xhigh", QWEN, BOTH) == {"reasoning_effort": "xhigh"})
|
||||||
|
check("a level the catalog doesn't list is refused", kw("high", QWEN, BOTH) == {}, kw("high", QWEN, BOTH))
|
||||||
|
check("...which is the value that would make the template raise", "high" not in QWEN["effort"]["levels"])
|
||||||
|
check("a level the template can't read is refused", kw("low", QWEN, THINK) == {}, kw("low", QWEN, THINK))
|
||||||
|
check("off refused when thinking isn't readable", kw("off", QWEN, {"thinking": False, "effort": True}) == {})
|
||||||
|
check("nothing for a non-reasoning model", kw("low", CODER, BOTH) == {})
|
||||||
|
check("garbage is ignored, not forwarded", kw("../etc", QWEN, BOTH) == {})
|
||||||
|
|
||||||
|
print("\n3. the real catalog entry matches the real template")
|
||||||
|
from llmhost import hfcache, paths
|
||||||
|
cat = {m["name"]: m for m in paths.load_catalog()["models"]}
|
||||||
|
q = cat["qwen3.8-27b"]
|
||||||
|
check("qwen3.8-27b declares levels", (q.get("effort") or {}).get("levels") == ["low", "medium", "xhigh"], q.get("effort"))
|
||||||
|
tmpl = hfcache.chat_template("lmstudio-community/Qwen3.8-27B-MLX-6bit")
|
||||||
|
if tmpl:
|
||||||
|
for lvl in q["effort"]["levels"]:
|
||||||
|
check(f"template accepts {lvl!r}", f"'{lvl}'" in tmpl or f'"{lvl}"' in tmpl)
|
||||||
|
check("template has no 'high' level", "'high'" not in tmpl.replace("'xhigh'", ""))
|
||||||
|
else:
|
||||||
|
print(" skip (template not on disk)")
|
||||||
|
check("no other catalog model claims levels",
|
||||||
|
[m for m in cat.values() if m.get("effort") and m["name"] != "qwen3.8-27b"] == [])
|
||||||
|
|
||||||
|
print("\n4. a client's own kwargs win over the server default")
|
||||||
|
def inject(server_kw, client_body):
|
||||||
|
"""The precedence rule from the proxy, which mirrors mlx_lm's own."""
|
||||||
|
if not server_kw:
|
||||||
|
return client_body.get("chat_template_kwargs")
|
||||||
|
mine = dict(server_kw)
|
||||||
|
theirs = client_body.get("chat_template_kwargs")
|
||||||
|
if isinstance(theirs, dict):
|
||||||
|
mine.update(theirs)
|
||||||
|
return mine
|
||||||
|
|
||||||
|
check("server default applied when client says nothing",
|
||||||
|
inject({"reasoning_effort": "low"}, {}) == {"reasoning_effort": "low"})
|
||||||
|
check("client overrides the same key",
|
||||||
|
inject({"reasoning_effort": "low"}, {"chat_template_kwargs": {"reasoning_effort": "xhigh"}})
|
||||||
|
== {"reasoning_effort": "xhigh"})
|
||||||
|
check("client's other keys survive alongside",
|
||||||
|
inject({"reasoning_effort": "low"}, {"chat_template_kwargs": {"enable_thinking": False}})
|
||||||
|
== {"reasoning_effort": "low", "enable_thinking": False})
|
||||||
|
check("no server default -> body untouched", inject({}, {}) is None)
|
||||||
|
check("no server default -> client kwargs preserved",
|
||||||
|
inject({}, {"chat_template_kwargs": {"enable_thinking": False}}) == {"enable_thinking": False})
|
||||||
|
check("a non-dict from the client isn't merged into",
|
||||||
|
inject({"reasoning_effort": "low"}, {"chat_template_kwargs": "nope"}) == {"reasoning_effort": "low"})
|
||||||
|
|
||||||
|
check.done(ROOT)
|
||||||
Loading…
Add table
Add a link
Reference in a new issue