"""Server + wire-format test (CPU, random tiny checkpoint around the real tokenizer; seconds): - verdin.server in-process: every question type, invalid requests (422), an over-cap state (422 "too many tokens"), 24 concurrent clients (dynamic batching) giving the same numbers as one-at-a-time, /v1/models; - the Decision Index kit's own http engine + response validator (third_party/decision-index), unchanged; - JevBench's own typesafe adapter (third_party/jevbench), unchanged. (These two run when the kits are importable, from PYTHONPATH or third_party/ next to verdin/; skipped otherwise.) python -m verdin.tests.test_server --tokenizer tokenizer.json [--model DIR] --model runs the same checks against a real checkpoint instead (e.g. on a GPU host). """ import argparse import json import socket import sys import tempfile import threading import time import urllib.error import urllib.request from pathlib import Path ROOT = Path(__file__).resolve().parents[2] REQS = [ {"state": "The parcel arrived on 2026-03-02, two weeks after the order on 2026-02-16; the mug inside was broken.", "questions": {"damaged": {"type": "noul", "instructions": "Was anything damaged?"}, "team": {"type": "choice", "instructions": "Route it.", "criteria": {"billing": "refunds", "shipping": None, "other": ""}}, "severity": {"type": "score", "instructions": "How severe?", "criteria": ["minor", "moderate", "major"]}}}, {"state": {"user": "ana", "events": [{"t": "login"}, {"t": "export", "rows": 120000}]}, "questions": {"risky": {"type": "noul", "instructions": "Is this an unusual data export?", "criteria": {"true": "unusual", "false": "routine"}}}}, {"state": ["a", "b", {"c": [1, 2.5, True, None]}], "model": "client-name", "questions": {"pick": {"type": "choice", "instructions": {"task": "pick", "hint": "first letter"}, "criteria": {"a": None, "b": None}}}}, {"state": "", "questions": {"only": {"type": "choice", "instructions": "One option.", "criteria": {"x": "the only one"}}}}, ] def post(url, body, raw=None): data = raw if raw is not None else json.dumps(body).encode() req = urllib.request.Request(url + "/v1/systemone", data=data, headers={"Content-Type": "application/json"}, method="POST") try: with urllib.request.urlopen(req, timeout=600) as r: return r.status, json.loads(r.read()) except urllib.error.HTTPError as e: return e.code, json.loads(e.read()) def free_port(): s = socket.socket(); s.bind(("127.0.0.1", 0)); p = s.getsockname()[1]; s.close() return p def start(model, extra=()): from verdin.server import main port = free_port() threading.Thread(target=main, args=(["--model", str(model), "--port", str(port), "--no-warmup", *extra],), daemon=True).start() url = f"http://127.0.0.1:{port}" for _ in range(600): try: urllib.request.urlopen(url + "/health", timeout=2); return url except Exception: # noqa: BLE001 time.sleep(0.5) raise RuntimeError("server did not start") def check_answer(q, a): assert a["type"] == q["type"], (q, a) if q["type"] == "noul": assert 0 <= a["noul"] <= 1 else: p = a["probabilities"] keys = list(q["criteria"]) if q["type"] == "choice" else [str(i) for i in range(len(q["criteria"]))] assert list(p) == keys and abs(sum(p.values()) - 1) < 1e-9, a if q["type"] == "choice": assert a["choice"] == max(p, key=p.get) else: assert abs(a["score"] - sum(i * v for i, v in enumerate(p.values()))) < 1e-9 and set(a["legend"]) == set(keys) def run(url): # 1. every question type single = [] for body in REQS: code, out = post(url, body) assert code == 200, out assert set(out["answers"]) == set(body["questions"]) and out["usage"]["input_tokens"] > 0 assert out["model"] == body.get("model", out["model"]) for k, q in body["questions"].items(): check_answer(q, out["answers"][k]) single.append(out["answers"]) print(" question types / answers: OK") # 2. invalid and over-cap bad = [({"state": "x", "questions": {}}, "questions"), ({"questions": {"a": {"type": "noul", "instructions": "x"}}}, "state"), ({"state": "x", "questions": {"a": {"type": "rank", "instructions": "x", "criteria": ["a", "b"]}}}, "type"), ({"state": "x", "questions": {"a": {"type": "choice", "instructions": "x", "criteria": {}}}}, "criteria"), ({"state": "x", "questions": {"a": {"type": "score", "instructions": "x", "criteria": ["one"]}}}, "score")] for body, word in bad: code, out = post(url, body) assert code == 422 and word in out["error"] and "too many tokens" not in out["error"], (code, out) code, out = post(url, None, raw=b"{not json") assert code == 422 and "JSON" in out["error"] big = {"state": "lorem ipsum dolor " * 30000, "questions": {"a": {"type": "noul", "instructions": "x"}}} code, out = post(url, big) print(f" over-cap: {code} {out.get('error', '')[:80]}") return single, code, out def concurrency(url, single, n_threads=24): results, errors = {}, [] def worker(t): try: for j in range(4): i = (t + j) % len(REQS) code, out = post(url, REQS[i]) assert code == 200, out results[(t, j)] = (i, out["answers"]) except Exception as e: # noqa: BLE001 errors.append(repr(e)) ths = [threading.Thread(target=worker, args=(t,)) for t in range(n_threads)] [t.start() for t in ths]; [t.join() for t in ths] assert not errors, errors[:3] worst = 0.0 for i, ans in results.values(): for k, a in ans.items(): b = single[i][k] if a["type"] == "noul": worst = max(worst, abs(a["noul"] - b["noul"])) else: worst = max(worst, max(abs(a["probabilities"][x] - b["probabilities"][x]) for x in a["probabilities"])) with urllib.request.urlopen(url + "/v1/models") as r: models = json.loads(r.read()) srv = models["data"][0]["server"] print(f" {len(results)} concurrent requests: max |dp| vs one-at-a-time {worst:.1e}; batches {srv['batches']}, " f"largest batch {srv['max_batch_seen']}") return worst def di_and_jevbench(url): sys.path.insert(0, str(ROOT / "third_party" / "decision-index")) sys.path.insert(0, str(ROOT / "third_party" / "jevbench")) ok = [] try: from decision_index.engines.base import Unsupported, validate from decision_index.engines.http import HttpSystemOne except ImportError as e: print(f" Decision Index kit not importable here ({e}); skipped") else: eng = HttpSystemOne(base_url=url, model="verdin-test") for body in REQS: qs = {k: q for k, q in body["questions"].items() if q["type"] in ("choice", "noul")} if not qs: continue resp, raw = eng(body["state"], qs) validate(qs, resp) try: eng("lorem ipsum " * 40000, {"a": {"type": "noul", "instructions": "x"}}) raise AssertionError("over-cap request was not refused") except Unsupported: pass eng.close(); ok.append("decision-index http engine + validate (incl. Unsupported on over-cap)") try: from jevbench.adapters.typesafe import TypeSafeAdapter from jevbench.tasks import Task except ImportError as e: print(f" JevBench not importable here ({e}); skipped") else: ad = TypeSafeAdapter(endpoint=url, model="verdin-test", key_env=None) tasks = [Task("t1", "x", "The mug was broken.", {"type": "noul", "instructions": "Damaged?"}, ["yes", "no"], "yes", "public"), Task("t2", "x", "Refund please.", {"type": "choice", "instructions": "Team?", "criteria": {"billing": None, "tech": None}}, ["billing", "tech"], "billing", "public"), Task("t3", "x", "Severe outage.", {"type": "score", "instructions": "Severity?", "criteria": ["low", "mid", "high"]}, ["0", "1", "2"], "2", "public")] for t in tasks: r = ad.run(t) assert r.ok, (t.id, r.error) assert abs(sum(r.probs.values()) - 1) < 1e-6 ok.append("jevbench typesafe adapter (noul / choice / score)") for x in ok: print(f" {x}: OK") def main(): ap = argparse.ArgumentParser() ap.add_argument("--tokenizer", help="tokenizer.json for the random tiny checkpoint") ap.add_argument("--model", help="test this checkpoint instead of a random tiny one") ap.add_argument("--server-args", default="", help="extra verdin.server flags") ap.add_argument("--url", help="test an already running server instead (e.g. http://host:port)") a = ap.parse_args() sys.path.insert(0, str(ROOT)) if a.url: url = a.url.rstrip("/") else: if a.model: model = a.model else: from verdin.tests.make_tiny import make_tiny_checkpoint model = make_tiny_checkpoint(Path(tempfile.mkdtemp(prefix="verdin-tiny-")), a.tokenizer) url = start(model, a.server_args.split()) single, code, out = run(url) assert code == 422 and "too many tokens" in out["error"], (code, out) worst = concurrency(url, single) # batched vs one-at-a-time: ~1e-7 in fp32 (CPU tests); on a GPU in bf16 the GEMM shapes change with the batch # composition, so the last bits move (4e-3 max |dp| seen on an RTX 4090): allow 2e-2 when serving bf16 on CUDA info = json.loads(urllib.request.urlopen(url + "/v1/models", timeout=30).read()) bf16_gpu = "bfloat16" in json.dumps(info) and "cuda" in json.dumps(info) assert worst < (2e-2 if bf16_gpu else 1e-4), worst di_and_jevbench(url) print("server tests: OK") if __name__ == "__main__": main()