omega-helix
This project has not described itself yet.
Brought by drakestapleton
omega-helix / tests / test_serve_scaling.py
| 1 | #!/usr/bin/env python3 |
| 2 | """ |
| 3 | Workstream 3 regression suite for native/serve.om: |
| 4 | - Continuous-batching multi-slot concurrency (zero spurious 503s, true saturation 503) |
| 5 | - Shared-trunk KV prefix caching across base, single strands, and spclip S=2 strands |
| 6 | with bit-exact cold/offline parity, TTFT speedup, collision rejection, and LRU eviction |
| 7 | - 8K-32K long-context serving, generous default output limits (>= 4096), clean 400 refusal |
| 8 | - OpenAI feature preservation & disconnect cleanup |
| 9 | - Live GB10 GPU gserve concurrency & 8K verification (when OLLM_GB10_LIVE=1) |
| 10 | """ |
| 11 | |
| 12 | from __future__ import annotations |
| 13 | |
| 14 | import http.client |
| 15 | import json |
| 16 | import os |
| 17 | from pathlib import Path |
| 18 | import platform |
| 19 | import shutil |
| 20 | import socket |
| 21 | import subprocess |
| 22 | import sys |
| 23 | import tempfile |
| 24 | import threading |
| 25 | import time |
| 26 | |
| 27 | ROOT = Path(__file__).resolve().parent.parent |
| 28 | RESERVED_PORTS = {3080, 18090, 18091, 18097, 18098} |
| 29 | |
| 30 | |
| 31 | def _pick_safe_port() -> int: |
| 32 | env_port = os.environ.get("OLLM_SERVE_PORT", "").strip() |
| 33 | if env_port: |
| 34 | p = int(env_port) |
| 35 | if p in RESERVED_PORTS: |
| 36 | raise RuntimeError(f"Refusing reserved Spark port {p}") |
| 37 | return p |
| 38 | for _ in range(64): |
| 39 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 40 | try: |
| 41 | s.bind(("127.0.0.1", 0)) |
| 42 | port = s.getsockname()[1] |
| 43 | finally: |
| 44 | s.close() |
| 45 | if port not in RESERVED_PORTS: |
| 46 | return port |
| 47 | raise RuntimeError("Could not allocate safe ephemeral port") |
| 48 | |
| 49 | |
| 50 | def _wait_port_free(port: int, timeout: float = 5.0) -> None: |
| 51 | deadline = time.monotonic() + timeout |
| 52 | while time.monotonic() < deadline: |
| 53 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 54 | try: |
| 55 | s.settimeout(0.2) |
| 56 | if s.connect_ex(("127.0.0.1", port)) != 0: |
| 57 | return |
| 58 | finally: |
| 59 | s.close() |
| 60 | time.sleep(0.05) |
| 61 | |
| 62 | |
| 63 | def _run_cmd(cmd: list[str], cwd: Path | None = None, env: dict[str, str] | None = None, timeout: float = 120.0) -> subprocess.CompletedProcess[str]: |
| 64 | merged = os.environ.copy() |
| 65 | if env: |
| 66 | merged.update(env) |
| 67 | return subprocess.run( |
| 68 | cmd, |
| 69 | cwd=str(cwd or ROOT), |
| 70 | env=merged, |
| 71 | stdout=subprocess.PIPE, |
| 72 | stderr=subprocess.PIPE, |
| 73 | text=True, |
| 74 | encoding="utf-8", |
| 75 | errors="replace", |
| 76 | timeout=timeout, |
| 77 | ) |
| 78 | |
| 79 | |
| 80 | def _find_omc() -> str: |
| 81 | if os.environ.get("OMC"): |
| 82 | return os.environ["OMC"] |
| 83 | local = Path.home() / ".local" / "bin" / "omc" |
| 84 | if local.exists(): |
| 85 | return str(local) |
| 86 | spark_canon = Path.home() / "canon" / "omega-mv" / "seed" / "out" / "omc" |
| 87 | if spark_canon.exists(): |
| 88 | return str(spark_canon) |
| 89 | found = shutil.which("omc") |
| 90 | if found: |
| 91 | return found |
| 92 | raise RuntimeError("Could not locate omc compiler") |
| 93 | |
| 94 | |
| 95 | class ManagedServer: |
| 96 | def __init__(self, args: list[str], port: int) -> None: |
| 97 | self.args = args |
| 98 | self.port = port |
| 99 | self.proc: subprocess.Popen[str] | None = None |
| 100 | self.lines: list[str] = [] |
| 101 | self.stderr_lines: list[str] = [] |
| 102 | self._t_out: threading.Thread | None = None |
| 103 | self._t_err: threading.Thread | None = None |
| 104 | self._ready = threading.Event() |
| 105 | self._failed = False |
| 106 | |
| 107 | def __enter__(self) -> "ManagedServer": |
| 108 | _wait_port_free(self.port) |
| 109 | self.proc = subprocess.Popen( |
| 110 | self.args, |
| 111 | cwd=str(ROOT), |
| 112 | stdout=subprocess.PIPE, |
| 113 | stderr=subprocess.PIPE, |
| 114 | text=True, |
| 115 | encoding="utf-8", |
| 116 | errors="replace", |
| 117 | bufsize=1, |
| 118 | ) |
| 119 | |
| 120 | def read_out() -> None: |
| 121 | assert self.proc is not None and self.proc.stdout is not None |
| 122 | try: |
| 123 | for line in self.proc.stdout: |
| 124 | s = line.rstrip("\r\n") |
| 125 | self.lines.append(s) |
| 126 | if s.startswith("PORT "): |
| 127 | self._ready.set() |
| 128 | finally: |
| 129 | self._ready.set() |
| 130 | |
| 131 | def read_err() -> None: |
| 132 | assert self.proc is not None and self.proc.stderr is not None |
| 133 | for line in self.proc.stderr: |
| 134 | self.stderr_lines.append(line.rstrip("\r\n")) |
| 135 | |
| 136 | self._t_out = threading.Thread(target=read_out, daemon=True) |
| 137 | self._t_err = threading.Thread(target=read_err, daemon=True) |
| 138 | self._t_out.start() |
| 139 | self._t_err.start() |
| 140 | |
| 141 | if not self._ready.wait(timeout=45.0): |
| 142 | self.close() |
| 143 | raise RuntimeError(f"Server startup timeout: out={self.lines} err={self.stderr_lines}") |
| 144 | if self.proc.poll() is not None and not any(l.startswith("PORT ") for l in self.lines): |
| 145 | rc = self.proc.returncode |
| 146 | self.close() |
| 147 | raise RuntimeError(f"Server exited early rc={rc}: out={self.lines} err={self.stderr_lines}") |
| 148 | return self |
| 149 | |
| 150 | def assert_alive(self) -> None: |
| 151 | assert self.proc is not None |
| 152 | rc = self.proc.poll() |
| 153 | if rc is not None: |
| 154 | raise RuntimeError(f"Server crashed unexpectedly with rc={rc}: out={self.lines[-10:]} err={self.stderr_lines[-10:]}") |
| 155 | |
| 156 | def close(self) -> None: |
| 157 | if self.proc is not None: |
| 158 | if self.proc.poll() is None: |
| 159 | self.proc.terminate() |
| 160 | try: |
| 161 | self.proc.wait(timeout=5.0) |
| 162 | except subprocess.TimeoutExpired: |
| 163 | self.proc.kill() |
| 164 | self.proc.wait(timeout=5.0) |
| 165 | if self.proc.stdout is not None: |
| 166 | self.proc.stdout.close() |
| 167 | if self.proc.stderr is not None: |
| 168 | self.proc.stderr.close() |
| 169 | self.proc = None |
| 170 | if self._t_out is not None: |
| 171 | self._t_out.join(timeout=2.0) |
| 172 | if self._t_err is not None: |
| 173 | self._t_err.join(timeout=2.0) |
| 174 | |
| 175 | def __exit__(self, exc_type, exc, tb) -> None: |
| 176 | self.close() |
| 177 | |
| 178 | |
| 179 | def _http_json( |
| 180 | port: int, |
| 181 | method: str, |
| 182 | path: str, |
| 183 | payload: dict | None = None, |
| 184 | timeout: float = 120.0, |
| 185 | ) -> tuple[int, dict[str, str], dict, float]: |
| 186 | t0 = time.monotonic() |
| 187 | conn = http.client.HTTPConnection("127.0.0.1", port, timeout=timeout) |
| 188 | try: |
| 189 | headers: dict[str, str] = {} |
| 190 | body: bytes | None = None |
| 191 | if payload is not None: |
| 192 | body = json.dumps(payload).encode("utf-8") |
| 193 | headers["Content-Type"] = "application/json" |
| 194 | conn.request(method, path, body=body, headers=headers) |
| 195 | resp = conn.getresponse() |
| 196 | raw = resp.read().decode("utf-8", errors="replace") |
| 197 | dt_ms = (time.monotonic() - t0) * 1000.0 |
| 198 | hdrs = {k.lower(): v for k, v in resp.getheaders()} |
| 199 | data = json.loads(raw) if raw.strip() else {} |
| 200 | return resp.status, hdrs, data, dt_ms |
| 201 | finally: |
| 202 | conn.close() |
| 203 | |
| 204 | |
| 205 | def _http_sse( |
| 206 | port: int, |
| 207 | path: str, |
| 208 | payload: dict, |
| 209 | timeout: float = 120.0, |
| 210 | ) -> tuple[int, float, list[tuple[float, dict]], dict | None]: |
| 211 | t0 = time.monotonic() |
| 212 | conn = http.client.HTTPConnection("127.0.0.1", port, timeout=timeout) |
| 213 | try: |
| 214 | body = json.dumps(payload).encode("utf-8") |
| 215 | conn.request("POST", path, body=body, headers={"Content-Type": "application/json"}) |
| 216 | resp = conn.getresponse() |
| 217 | status = resp.status |
| 218 | chunks: list[tuple[float, dict]] = [] |
| 219 | usage: dict | None = None |
| 220 | ttft_ms = 0.0 |
| 221 | if status != 200: |
| 222 | raw = resp.read().decode("utf-8", errors="replace") |
| 223 | return status, (time.monotonic() - t0) * 1000.0, [(0.0, {"error_body": raw})], None |
| 224 | while True: |
| 225 | line_b = resp.readline() |
| 226 | if not line_b: |
| 227 | break |
| 228 | line = line_b.decode("utf-8", errors="replace").strip() |
| 229 | if not line.startswith("data: "): |
| 230 | continue |
| 231 | item = line[6:].strip() |
| 232 | if item == "[DONE]": |
| 233 | break |
| 234 | obj = json.loads(item) |
| 235 | now = time.monotonic() |
| 236 | if ttft_ms == 0.0: |
| 237 | ch = obj.get("choices") or [] |
| 238 | if ch and (ch[0].get("delta") or {}).get("content"): |
| 239 | ttft_ms = (now - t0) * 1000.0 |
| 240 | if "usage" in obj and obj["usage"] is not None: |
| 241 | usage = obj["usage"] |
| 242 | chunks.append((now, obj)) |
| 243 | if ttft_ms == 0.0: |
| 244 | ttft_ms = (time.monotonic() - t0) * 1000.0 |
| 245 | return status, ttft_ms, chunks, usage |
| 246 | finally: |
| 247 | conn.close() |
| 248 | |
| 249 | |
| 250 | def _sse_text(chunks: list[tuple[float, dict]]) -> str: |
| 251 | parts: list[str] = [] |
| 252 | for _, obj in chunks: |
| 253 | for ch in obj.get("choices") or []: |
| 254 | d = ch.get("delta") or {} |
| 255 | c = d.get("content") |
| 256 | if isinstance(c, str): |
| 257 | parts.append(c) |
| 258 | return "".join(parts) |
| 259 | |
| 260 | |
| 261 | def _check_static_invariants() -> None: |
| 262 | serve_path = ROOT / "native" / "serve.om" |
| 263 | text = serve_path.read_text(encoding="utf-8") |
| 264 | nlines = len(text.splitlines()) |
| 265 | if nlines >= 8192: |
| 266 | raise AssertionError(f"native/serve.om has {nlines} lines (must be < 8192)") |
| 267 | for mut in ("OMUTMETH", "OMUTPATH", "OMUTBIG", "OMUTJSON", "OMUTLOOP", "OMUTSEED", "OMUTMID"): |
| 268 | if f"const {mut} ulong 1" not in text: |
| 269 | raise AssertionError(f"Missing mutant guard {mut} in native/serve.om") |
| 270 | |
| 271 | |
| 272 | def _build_target(target: str, work: Path, omc: str) -> Path: |
| 273 | build_out = work / f"bin_{target}" |
| 274 | build_out.mkdir(parents=True, exist_ok=True) |
| 275 | res = _run_cmd( |
| 276 | ["sh", str(ROOT / "scripts" / "build.sh")], |
| 277 | env={"TARGET": target, "OMC": omc, "OUT": str(build_out)}, |
| 278 | timeout=180.0, |
| 279 | ) |
| 280 | if res.returncode != 0: |
| 281 | raise RuntimeError(f"build.sh TARGET={target} failed rc={res.returncode}:\n{res.stdout}\n{res.stderr}") |
| 282 | name = "ollm-gb10" if target == "gb10" else ("ollm-macos" if target == "macos" else f"ollm-{target}" if target != "aarch64" else "ollm") |
| 283 | bin_path = build_out / name |
| 284 | if not bin_path.exists(): |
| 285 | raise RuntimeError(f"Missing expected binary {bin_path}") |
| 286 | return bin_path |
| 287 | |
| 288 | |
| 289 | def _bpe_token_count(ollm_bin: Path, merges: Path, v: int, text: str, scratch: Path) -> int: |
| 290 | txt = scratch / "tok_check.txt" |
| 291 | toks = scratch / "tok_check.toks" |
| 292 | txt.write_text(text, encoding="utf-8") |
| 293 | r = _run_cmd([str(ollm_bin), "bpeenc", str(merges), str(v), str(txt), str(toks)]) |
| 294 | if r.returncode != 0: |
| 295 | raise RuntimeError(f"bpeenc failed rc={r.returncode}: {r.stdout} {r.stderr}") |
| 296 | return toks.stat().st_size // 2 |
| 297 | |
| 298 | |
| 299 | def _make_prompt_with_tokens(ollm_bin: Path, merges: Path, v: int, unit: str, target_toks: int, scratch: Path) -> tuple[str, int]: |
| 300 | unit_cnt = _bpe_token_count(ollm_bin, merges, v, unit * 8, scratch) |
| 301 | toks_per_rep = max(0.1, unit_cnt / 8.0) |
| 302 | reps = max(1, int(target_toks / toks_per_rep)) |
| 303 | s = unit * reps |
| 304 | c = _bpe_token_count(ollm_bin, merges, v, s, scratch) |
| 305 | for _ in range(12): |
| 306 | if c < target_toks - 10: |
| 307 | need = max(1, int((target_toks - 4 - c) / toks_per_rep)) |
| 308 | s += unit * need |
| 309 | c = _bpe_token_count(ollm_bin, merges, v, s, scratch) |
| 310 | elif c > target_toks: |
| 311 | over = max(1, int((c - (target_toks - 4)) / toks_per_rep)) |
| 312 | cur_reps = len(s) // len(unit) |
| 313 | if cur_reps <= over: |
| 314 | break |
| 315 | s = unit * (cur_reps - over) |
| 316 | c = _bpe_token_count(ollm_bin, merges, v, s, scratch) |
| 317 | else: |
| 318 | break |
| 319 | return s, c |
| 320 | |
| 321 | |
| 322 | def _setup_models(ollm_bin: Path, work: Path) -> dict[str, Path]: |
| 323 | corpus0 = work / "corpus0.txt" |
| 324 | corpus1 = work / "corpus1.txt" |
| 325 | base_txt = ( |
| 326 | "sovereign verified deterministic compute builds clean reproducible kernels across every single token step.\n" |
| 327 | "quickly jumping wizards vex bold nymphs fighting over extra lazy brown dogs and quiet quartz stones.\n" |
| 328 | * 40 |
| 329 | ) |
| 330 | s0_txt = "alpha specialist strand focuses sharply on symbolic proof verification and theorem bounds.\n" * 40 |
| 331 | s1_txt = "beta specialist strand routes hardware telemetry and memory bounds without allocation drift.\n" * 40 |
| 332 | corpus0.write_text(base_txt + s0_txt, encoding="utf-8") |
| 333 | corpus1.write_text(s1_txt + base_txt, encoding="utf-8") |
| 334 | |
| 335 | merges = work / "merges.bin" |
| 336 | toks0 = work / "toks0.bin" |
| 337 | toks1 = work / "toks1.bin" |
| 338 | v_fit = 320 |
| 339 | v = 300 |
| 340 | for cmd in ( |
| 341 | [str(ollm_bin), "bpefit", str(corpus0), str(merges), str(v_fit)], |
| 342 | [str(ollm_bin), "bpeenc", str(merges), str(v), str(corpus0), str(toks0)], |
| 343 | [str(ollm_bin), "bpeenc", str(merges), str(v), str(corpus1), str(toks1)], |
| 344 | ): |
| 345 | r = _run_cmd(cmd) |
| 346 | if r.returncode != 0: |
| 347 | raise RuntimeError(f"{cmd} failed rc={r.returncode}: {r.stdout} {r.stderr}") |
| 348 | |
| 349 | base_ck = work / "base.ck" |
| 350 | spec0_ck = work / "spec0.ck" |
| 351 | spec1_ck = work / "spec1.ck" |
| 352 | s0_sp = work / "s0.sp" |
| 353 | s1_sp = work / "s1.sp" |
| 354 | long_ck = work / "long.ck" |
| 355 | for cmd in ( |
| 356 | [str(ollm_bin), "init", str(base_ck), str(v), "64", "16", "2", "32", "4", "1", "11", "4", "10000"], |
| 357 | [str(ollm_bin), "train", str(base_ck), str(toks0), "2", "2"], |
| 358 | [str(ollm_bin), "grow", str(base_ck), str(spec0_ck), "5", "6", "10000"], |
| 359 | [str(ollm_bin), "trainf", str(spec0_ck), str(toks0), "4", "2", "4"], |
| 360 | [str(ollm_bin), "spext", str(base_ck), str(spec0_ck), str(s0_sp)], |
| 361 | [str(ollm_bin), "grow", str(base_ck), str(spec1_ck), "5", "6", "10000"], |
| 362 | [str(ollm_bin), "trainf", str(spec1_ck), str(toks1), "4", "2", "4"], |
| 363 | [str(ollm_bin), "spext", str(base_ck), str(spec1_ck), str(s1_sp)], |
| 364 | [str(ollm_bin), "init", str(long_ck), str(v), "32", "8", "1", "16", "1", "1", "7", "2", "10000"], |
| 365 | ): |
| 366 | r = _run_cmd(cmd) |
| 367 | if r.returncode != 0: |
| 368 | raise RuntimeError(f"{cmd} failed rc={r.returncode}: {r.stdout} {r.stderr}") |
| 369 | |
| 370 | return { |
| 371 | "merges": merges, |
| 372 | "base": base_ck, |
| 373 | "s0": s0_sp, |
| 374 | "s1": s1_sp, |
| 375 | "long": long_ck, |
| 376 | } |
| 377 | |
| 378 | |
| 379 | def _suite_a_concurrency(ollm_bin: Path, models: dict[str, Path], port: int) -> dict[str, object]: |
| 380 | metrics: dict[str, object] = {} |
| 381 | with ManagedServer( |
| 382 | [str(ollm_bin), "serve", str(port), str(models["base"]), str(models["merges"]), "slots=8", "ctx=8192", "test=1"], |
| 383 | port, |
| 384 | ) as srv: |
| 385 | results: list[tuple[int, int, str, float, list[tuple[float, dict]], dict | None]] = [None] * 6 # type: ignore |
| 386 | |
| 387 | def worker(idx: int) -> None: |
| 388 | if idx < 2: |
| 389 | payload = { |
| 390 | "messages": [{"role": "user", "content": f"stream request {idx}"}], |
| 391 | "stream": True, |
| 392 | "stream_options": {"include_usage": True}, |
| 393 | "ollm_test_output": "alpha beta gamma delta epsilon ", |
| 394 | "ollm_test_delay_ms": 40, |
| 395 | "temperature": 0, |
| 396 | } |
| 397 | st, _, ch, us = _http_sse(port, "/v1/chat/completions", payload) |
| 398 | results[idx] = (idx, st, _sse_text(ch), 0.0, ch, us) |
| 399 | elif idx < 4: |
| 400 | payload = { |
| 401 | "messages": [ |
| 402 | {"role": "system", "content": "Be concise."}, |
| 403 | {"role": "user", "content": f"turn1 {idx}"}, |
| 404 | {"role": "assistant", "content": "ok"}, |
| 405 | {"role": "user", "content": f"turn2 {idx}"}, |
| 406 | ], |
| 407 | "ollm_test_output": f"reply-{idx}", |
| 408 | "ollm_test_delay_ms": 45, |
| 409 | "temperature": 0, |
| 410 | } |
| 411 | st, _, data, dt = _http_json(port, "POST", "/v1/chat/completions", payload) |
| 412 | txt = ((data.get("choices") or [{}])[0].get("message") or {}).get("content", "") |
| 413 | results[idx] = (idx, st, txt, dt, [], data.get("usage")) |
| 414 | else: |
| 415 | payload = { |
| 416 | "messages": [ |
| 417 | { |
| 418 | "role": "user", |
| 419 | "content": [ |
| 420 | {"type": "text", "text": f"part1-{idx} "}, |
| 421 | {"type": "text", "text": "part2"}, |
| 422 | ], |
| 423 | } |
| 424 | ], |
| 425 | "ollm_test_output": f"parts-{idx}", |
| 426 | "ollm_test_delay_ms": 45, |
| 427 | "temperature": 0, |
| 428 | } |
| 429 | st, _, data, dt = _http_json(port, "POST", "/v1/chat/completions", payload) |
| 430 | txt = ((data.get("choices") or [{}])[0].get("message") or {}).get("content", "") |
| 431 | results[idx] = (idx, st, txt, dt, [], data.get("usage")) |
| 432 | |
| 433 | threads = [threading.Thread(target=worker, args=(i,)) for i in range(6)] |
| 434 | for t in threads: |
| 435 | t.start() |
| 436 | |
| 437 | max_inflight = 0 |
| 438 | seen_max_slots = 0 |
| 439 | for _ in range(30): |
| 440 | try: |
| 441 | st_h, _, hdata, _ = _http_json(port, "GET", "/health", timeout=5.0) |
| 442 | if st_h == 200: |
| 443 | max_inflight = max(max_inflight, int(hdata.get("in_flight", 0))) |
| 444 | seen_max_slots = int(hdata.get("max_slots", 0)) |
| 445 | except Exception: |
| 446 | pass |
| 447 | if all(not t.is_alive() for t in threads): |
| 448 | break |
| 449 | time.sleep(0.02) |
| 450 | |
| 451 | for t in threads: |
| 452 | t.join(timeout=30.0) |
| 453 | if t.is_alive(): |
| 454 | raise AssertionError("Concurrent worker thread timed out") |
| 455 | srv.assert_alive() |
| 456 | |
| 457 | statuses = [r[1] for r in results] |
| 458 | if any(s != 200 for s in statuses): |
| 459 | raise AssertionError(f"Expected 6 HTTP 200 responses, got {statuses}") |
| 460 | if seen_max_slots != 8 or max_inflight < 4: |
| 461 | raise AssertionError(f"Expected max_slots=8 & in_flight>=4 mid-flight, got max_slots={seen_max_slots} max_inflight={max_inflight}") |
| 462 | c0_times = [ts for ts, obj in results[0][4] if ((obj.get("choices") or [{}])[0].get("delta") or {}).get("content")] |
| 463 | c1_times = [ts for ts, obj in results[1][4] if ((obj.get("choices") or [{}])[0].get("delta") or {}).get("content")] |
| 464 | if not c0_times or not c1_times or max(c0_times[0], c1_times[0]) >= min(c0_times[-1], c1_times[-1]): |
| 465 | raise AssertionError(f"SSE streams were not interleaved: c0={c0_times} c1={c1_times}") |
| 466 | if not results[0][5] or not results[1][5]: |
| 467 | raise AssertionError("Missing stream_options.include_usage payload") |
| 468 | metrics["concurrent_6_503s"] = 0 |
| 469 | metrics["max_in_flight_seen"] = max_inflight |
| 470 | |
| 471 | # Saturation 503 check with slots=2 |
| 472 | with ManagedServer( |
| 473 | [str(ollm_bin), "serve", str(port), str(models["base"]), str(models["merges"]), "slots=2", "ctx=8192", "test=1"], |
| 474 | port, |
| 475 | ) as srv: |
| 476 | res_sat: list[tuple[int, dict[str, str], dict]] = [] |
| 477 | |
| 478 | def hold(i: int) -> None: |
| 479 | st, _, data, _ = _http_json( |
| 480 | port, |
| 481 | "POST", |
| 482 | "/v1/chat/completions", |
| 483 | { |
| 484 | "messages": [{"role": "user", "content": f"hold-{i}"}], |
| 485 | "ollm_test_output": "abcdef", |
| 486 | "ollm_test_delay_ms": 120, |
| 487 | "temperature": 0, |
| 488 | }, |
| 489 | ) |
| 490 | res_sat.append((st, {}, data)) |
| 491 | |
| 492 | t1 = threading.Thread(target=hold, args=(1,)) |
| 493 | t2 = threading.Thread(target=hold, args=(2,)) |
| 494 | t1.start() |
| 495 | t2.start() |
| 496 | |
| 497 | busy_seen = False |
| 498 | for _ in range(30): |
| 499 | _, _, hdata, _ = _http_json(port, "GET", "/health") |
| 500 | if int(hdata.get("in_flight", 0)) == 2 and hdata.get("busy") is True: |
| 501 | busy_seen = True |
| 502 | break |
| 503 | time.sleep(0.015) |
| 504 | if not busy_seen: |
| 505 | raise AssertionError("Did not observe in_flight=2 busy=true on slots=2") |
| 506 | |
| 507 | st3, hdr3, data3, _ = _http_json( |
| 508 | port, |
| 509 | "POST", |
| 510 | "/v1/chat/completions", |
| 511 | {"messages": [{"role": "user", "content": "overflow"}], "temperature": 0}, |
| 512 | ) |
| 513 | if st3 != 503 or hdr3.get("retry-after") != "1" or (data3.get("error") or {}).get("code") != "server_busy": |
| 514 | raise AssertionError(f"Expected 503 server_busy with Retry-After:1, got st={st3} hdr={hdr3} data={data3}") |
| 515 | |
| 516 | t1.join(timeout=20.0) |
| 517 | t2.join(timeout=20.0) |
| 518 | srv.assert_alive() |
| 519 | _, _, h_after, _ = _http_json(port, "GET", "/health") |
| 520 | if int(h_after.get("in_flight", -1)) != 0 or h_after.get("busy") is not False: |
| 521 | raise AssertionError(f"Slots leaked after completion: {h_after}") |
| 522 | metrics["saturation_503_ok"] = True |
| 523 | return metrics |
| 524 | |
| 525 | |
| 526 | def _suite_b_prefix_cache_and_strands(ollm_bin: Path, models: dict[str, Path], work: Path, port: int) -> dict[str, object]: |
| 527 | merges = models["merges"] |
| 528 | shared_prefix, prefix_toks = _make_prompt_with_tokens( |
| 529 | ollm_bin, merges, 300, "sovereign deterministic compute ", 528, work |
| 530 | ) |
| 531 | if prefix_toks < 512: |
| 532 | raise AssertionError(f"Prefix too short: {prefix_toks}") |
| 533 | |
| 534 | metrics: dict[str, object] = {"shared_prefix_tokens": prefix_toks} |
| 535 | with ManagedServer( |
| 536 | [ |
| 537 | str(ollm_bin), |
| 538 | "serve", |
| 539 | str(port), |
| 540 | str(models["base"]), |
| 541 | str(merges), |
| 542 | "slots=8", |
| 543 | "ctx=8192", |
| 544 | f"strand={models['s0']}", |
| 545 | f"strand={models['s1']}", |
| 546 | ], |
| 547 | port, |
| 548 | ) as srv: |
| 549 | st_m, _, mdata, _ = _http_json(port, "GET", "/v1/models") |
| 550 | if st_m != 200: |
| 551 | raise AssertionError(f"/v1/models failed: {st_m}") |
| 552 | model_ids = [d.get("id") for d in mdata.get("data") or []] |
| 553 | for req_id in ("strand:0", "strand:1", "spclip"): |
| 554 | if req_id not in model_ids: |
| 555 | raise AssertionError(f"Missing {req_id} in /v1/models: {model_ids}") |
| 556 | |
| 557 | # Cold uncached baselines (cache_prefix: false) for base, strand:0, strand:1, spclip |
| 558 | cold_outputs: dict[str, str] = {} |
| 559 | cold_times: dict[str, float] = {} |
| 560 | configs = [ |
| 561 | ("base", {"strand": "base"}), |
| 562 | ("strand0", {"strand": 0}), |
| 563 | ("strand1", {"strand": 1}), |
| 564 | ("spclip", {"strand": "spclip", "spclip_mode": 1, "spclip_weights": [1000, 1000]}), |
| 565 | ] |
| 566 | for name, extra in configs: |
| 567 | req = { |
| 568 | "prompt": shared_prefix + f" query-{name}:", |
| 569 | "max_tokens": 12, |
| 570 | "temperature": 0, |
| 571 | "seed": 42, |
| 572 | "cache_prefix": False, |
| 573 | } |
| 574 | req.update(extra) |
| 575 | st, _, data, dt = _http_json(port, "POST", "/v1/completions", req) |
| 576 | if st != 200: |
| 577 | raise AssertionError(f"Cold {name} failed st={st}: {data}") |
| 578 | ptd = (data.get("usage") or {}).get("prompt_tokens_details") or {} |
| 579 | if int(ptd.get("cached_tokens", -1)) != 0: |
| 580 | raise AssertionError(f"cache_prefix=false still reported cached_tokens={ptd}") |
| 581 | cold_outputs[name] = ((data.get("choices") or [{}])[0]).get("text", "") |
| 582 | cold_times[name] = dt |
| 583 | |
| 584 | # Warm cached sequence: first base populates trunk KV for shared_prefix; subsequent base, strand:0, strand:1, spclip hit! |
| 585 | warm_outputs: dict[str, str] = {} |
| 586 | warm_times: dict[str, float] = {} |
| 587 | # Populate with exact shared prefix + base suffix |
| 588 | req_pop = {"prompt": shared_prefix + " seed:", "max_tokens": 8, "temperature": 0, "seed": 42, "strand": "base"} |
| 589 | st_p, ttft_cold_sse, _, us_p = _http_sse( |
| 590 | port, |
| 591 | "/v1/chat/completions", |
| 592 | { |
| 593 | "messages": [{"role": "user", "content": shared_prefix}], |
| 594 | "max_tokens": 8, |
| 595 | "temperature": 0, |
| 596 | "seed": 42, |
| 597 | "stream": True, |
| 598 | "stream_options": {"include_usage": True}, |
| 599 | "strand": "base", |
| 600 | }, |
| 601 | ) |
| 602 | if st_p != 200 or not us_p: |
| 603 | raise AssertionError(f"SSE populate failed: {st_p} {us_p}") |
| 604 | st_pw, ttft_warm_sse, _, us_pw = _http_sse( |
| 605 | port, |
| 606 | "/v1/chat/completions", |
| 607 | { |
| 608 | "messages": [{"role": "user", "content": shared_prefix}], |
| 609 | "max_tokens": 8, |
| 610 | "temperature": 0, |
| 611 | "seed": 42, |
| 612 | "stream": True, |
| 613 | "stream_options": {"include_usage": True}, |
| 614 | "strand": 0, |
| 615 | }, |
| 616 | ) |
| 617 | if st_pw != 200 or not us_pw: |
| 618 | raise AssertionError(f"SSE warm hit failed: {st_pw} {us_pw}") |
| 619 | sse_cached = int((us_pw.get("prompt_tokens_details") or {}).get("cached_tokens", 0)) |
| 620 | if sse_cached < 512: |
| 621 | raise AssertionError(f"SSE cross-strand warm hit cached_tokens={sse_cached} < 512") |
| 622 | |
| 623 | # Also test non-streaming /v1/completions cross-strand prefix cache populate + hits + bit-exact parity |
| 624 | st_b0, _, db0, dt_b0 = _http_json(port, "POST", "/v1/completions", {"prompt": shared_prefix + " query-base:", "max_tokens": 12, "temperature": 0, "seed": 42, "strand": "base"}) |
| 625 | if st_b0 != 200: |
| 626 | raise AssertionError(f"base warm/pop failed: {st_b0}") |
| 627 | for name, extra in configs: |
| 628 | req = { |
| 629 | "prompt": shared_prefix + f" query-{name}:", |
| 630 | "max_tokens": 12, |
| 631 | "temperature": 0, |
| 632 | "seed": 42, |
| 633 | } |
| 634 | req.update(extra) |
| 635 | st, _, data, dt = _http_json(port, "POST", "/v1/completions", req) |
| 636 | if st != 200: |
| 637 | raise AssertionError(f"Warm {name} failed: {st} {data}") |
| 638 | cached_toks = int(((data.get("usage") or {}).get("prompt_tokens_details") or {}).get("cached_tokens", 0)) |
| 639 | if cached_toks < 512: |
| 640 | raise AssertionError(f"Expected cached_tokens >= 512 for {name}, got {cached_toks}") |
| 641 | txt = ((data.get("choices") or [{}])[0]).get("text", "") |
| 642 | if txt != cold_outputs[name]: |
| 643 | raise AssertionError(f"Parity mismatch on {name}: cached={txt!r} != cold={cold_outputs[name]!r}") |
| 644 | warm_outputs[name] = txt |
| 645 | warm_times[name] = dt |
| 646 | |
| 647 | if not (ttft_warm_sse < ttft_cold_sse): |
| 648 | raise AssertionError(f"Expected warm SSE TTFT < cold SSE TTFT: warm={ttft_warm_sse:.2f}ms cold={ttft_cold_sse:.2f}ms") |
| 649 | |
| 650 | _, _, hdata, _ = _http_json(port, "GET", "/health") |
| 651 | kvc = hdata.get("kv_cache") or {} |
| 652 | if int(kvc.get("hits", 0)) < 3 or int(kvc.get("tokens_saved", 0)) < 1536: |
| 653 | raise AssertionError(f"Unexpected /health kv_cache stats: {kvc}") |
| 654 | |
| 655 | # Bit-exactness vs offline CLI spsamp & spclip on <= T_ck prompt (single chunk <= 64 tokens) |
| 656 | short_padded = "sovereign deterministic compute builds clean " |
| 657 | _, _, ds0_a, _ = _http_json(port, "POST", "/v1/completions", {"prompt": short_padded, "max_tokens": 8, "temperature": 0, "seed": 42, "strand": 0}) |
| 658 | _, _, ds0_b, _ = _http_json(port, "POST", "/v1/completions", {"prompt": short_padded, "max_tokens": 8, "temperature": 0, "seed": 42, "strand": 0}) |
| 659 | _, _, dsc_b, _ = _http_json(port, "POST", "/v1/completions", {"prompt": short_padded, "max_tokens": 8, "temperature": 0, "seed": 42, "strand": "spclip", "spclip_mode": 1, "spclip_weights": [1000, 1000]}) |
| 660 | if ds0_a["choices"][0]["text"] != ds0_b["choices"][0]["text"]: |
| 661 | raise AssertionError("Short prompt cold vs cached parity failed for strand 0") |
| 662 | r_s0_pad = _run_cmd([str(ollm_bin), "spsamp", str(models["base"]), str(models["s0"]), "8", "0", short_padded, "42", str(merges)]) |
| 663 | r_clip_pad = _run_cmd([ |
| 664 | str(ollm_bin), "spclip", str(models["base"]), "1", short_padded, "8", "0", "42", str(merges), |
| 665 | "2", "1000", "1", str(models["s0"]), "1000", "1", str(models["s1"]), |
| 666 | ]) |
| 667 | if r_s0_pad.returncode != 0 or r_clip_pad.returncode != 0: |
| 668 | raise RuntimeError(f"Offline parity CLI failed: spsamp={r_s0_pad.stderr} spclip={r_clip_pad.stderr}") |
| 669 | if r_s0_pad.stdout != ds0_b["choices"][0]["text"]: |
| 670 | raise AssertionError(f"Serve strand:0 != CLI spsamp: cli={r_s0_pad.stdout!r} srv={ds0_b['choices'][0]['text']!r}") |
| 671 | if r_clip_pad.stdout != dsc_b["choices"][0]["text"]: |
| 672 | raise AssertionError(f"Serve spclip != CLI spclip: cli={r_clip_pad.stdout!r} srv={dsc_b['choices'][0]['text']!r}") |
| 673 | |
| 674 | srv.assert_alive() |
| 675 | metrics["cold_ttft_ms"] = round(ttft_cold_sse, 2) |
| 676 | metrics["warm_ttft_ms"] = round(ttft_warm_sse, 2) |
| 677 | metrics["ttft_speedup"] = round(ttft_cold_sse / max(0.01, ttft_warm_sse), 2) |
| 678 | metrics["kv_hits"] = int(kvc["hits"]) |
| 679 | metrics["tokens_saved"] = int(kvc["tokens_saved"]) |
| 680 | return metrics |
| 681 | |
| 682 | |
| 683 | def _suite_c_collision_and_lru(ollm_bin: Path, models: dict[str, Path], port: int) -> dict[str, object]: |
| 684 | merges = models["merges"] |
| 685 | metrics: dict[str, object] = {} |
| 686 | prompt_a = "alpha alpha alpha alpha alpha alpha alpha alpha alpha alpha alpha alpha " |
| 687 | prompt_b = "omega omega omega omega omega omega omega omega omega omega omega omega " |
| 688 | with ManagedServer( |
| 689 | [str(ollm_bin), "serve", str(port), str(models["base"]), str(merges), "slots=4", "ctx=8192", "kvblks=64", "test=1"], |
| 690 | port, |
| 691 | ) as srv: |
| 692 | st_b_cold, _, db_cold, _ = _http_json( |
| 693 | port, "POST", "/v1/completions", |
| 694 | {"prompt": prompt_b, "max_tokens": 8, "temperature": 0, "seed": 7, "cache_prefix": False}, |
| 695 | ) |
| 696 | st_a, _, _, _ = _http_json( |
| 697 | port, "POST", "/v1/completions", |
| 698 | {"prompt": prompt_a, "max_tokens": 8, "temperature": 0, "seed": 7, "ollm_test_collide": True}, |
| 699 | ) |
| 700 | st_b_col, _, db_col, _ = _http_json( |
| 701 | port, "POST", "/v1/completions", |
| 702 | {"prompt": prompt_b, "max_tokens": 8, "temperature": 0, "seed": 7, "ollm_test_collide": True}, |
| 703 | ) |
| 704 | if st_b_cold != 200 or st_a != 200 or st_b_col != 200: |
| 705 | raise AssertionError(f"Collision test bad status: {st_b_cold} {st_a} {st_b_col}") |
| 706 | cached_col = int(((db_col.get("usage") or {}).get("prompt_tokens_details") or {}).get("cached_tokens", -1)) |
| 707 | if cached_col != 0: |
| 708 | raise AssertionError(f"Expected cached_tokens=0 on forced collision, got {cached_col}") |
| 709 | if db_col["choices"][0]["text"] != db_cold["choices"][0]["text"]: |
| 710 | raise AssertionError("Hash collision corrupted Prompt B output!") |
| 711 | _, _, hdata, _ = _http_json(port, "GET", "/health") |
| 712 | rej = int((hdata.get("kv_cache") or {}).get("collisions_rejected", 0)) |
| 713 | if rej < 1: |
| 714 | raise AssertionError(f"Expected collisions_rejected >= 1, got {hdata}") |
| 715 | srv.assert_alive() |
| 716 | metrics["collisions_rejected"] = rej |
| 717 | |
| 718 | # LRU bounded eviction check with kvblks=8 |
| 719 | with ManagedServer( |
| 720 | [str(ollm_bin), "serve", str(port), str(models["base"]), str(merges), "slots=4", "ctx=8192", "kvblks=8"], |
| 721 | port, |
| 722 | ) as srv: |
| 723 | for i in range(10): |
| 724 | p = f"lru distinct item number {i} " * 4 |
| 725 | st, _, _, _ = _http_json(port, "POST", "/v1/completions", {"prompt": p, "max_tokens": 2, "temperature": 0}) |
| 726 | if st != 200: |
| 727 | raise AssertionError(f"LRU req {i} failed: {st}") |
| 728 | _, _, hdata, _ = _http_json(port, "GET", "/health") |
| 729 | kvc = hdata.get("kv_cache") or {} |
| 730 | if int(kvc.get("capacity", 0)) != 8 or int(kvc.get("entries", 99)) > 8 or int(kvc.get("evictions", 0)) <= 0: |
| 731 | raise AssertionError(f"LRU bounded eviction failed: {kvc}") |
| 732 | srv.assert_alive() |
| 733 | metrics["lru_evictions"] = int(kvc["evictions"]) |
| 734 | return metrics |
| 735 | |
| 736 | |
| 737 | def _suite_d_long_context(ollm_bin: Path, models: dict[str, Path], work: Path, port: int) -> dict[str, object]: |
| 738 | merges = models["merges"] |
| 739 | long_ck = models["long"] |
| 740 | metrics: dict[str, object] = {} |
| 741 | |
| 742 | # CLI > 32768 must exit 2 |
| 743 | r_bad = _run_cmd([str(ollm_bin), "serve", str(port), str(long_ck), str(merges), "ctx=32769"]) |
| 744 | if r_bad.returncode != 2: |
| 745 | raise AssertionError(f"Expected exit 2 for ctx=32769, got rc={r_bad.returncode}") |
| 746 | |
| 747 | p8k_ok, n8k_ok = _make_prompt_with_tokens(ollm_bin, merges, 300, "x ", 8180, work) |
| 748 | p8k_over, n8k_over = _make_prompt_with_tokens(ollm_bin, merges, 300, "x ", 8200, work) |
| 749 | if not (8160 <= n8k_ok + 1 < 8192) or (n8k_over + 1 < 8192): |
| 750 | raise AssertionError(f"Unexpected 8K token counts: ok={n8k_ok} over={n8k_over}") |
| 751 | |
| 752 | with ManagedServer( |
| 753 | [str(ollm_bin), "serve", str(port), str(long_ck), str(merges), "slots=2", "ctx=8192", "test=1"], |
| 754 | port, |
| 755 | ) as srv: |
| 756 | st_ok, _, d_ok, _ = _http_json(port, "POST", "/v1/completions", {"prompt": p8k_ok, "max_tokens": 2, "temperature": 0}) |
| 757 | if st_ok != 200: |
| 758 | raise AssertionError(f"8K boundary request failed st={st_ok}: {d_ok}") |
| 759 | st_ov, _, d_ov, _ = _http_json(port, "POST", "/v1/completions", {"prompt": p8k_over, "max_tokens": 2, "temperature": 0}) |
| 760 | if st_ov != 400 or (d_ov.get("error") or {}).get("code") != "context_length_exceeded": |
| 761 | raise AssertionError(f"Expected 400 context_length_exceeded over 8K, got st={st_ov} data={d_ov}") |
| 762 | |
| 763 | # Verify generous default output limit (>= 4096) when max_tokens is omitted |
| 764 | big_out = "a" * 4200 |
| 765 | st_gen, _, d_gen, _ = _http_json( |
| 766 | port, |
| 767 | "POST", |
| 768 | "/v1/chat/completions", |
| 769 | { |
| 770 | "messages": [{"role": "user", "content": "hi"}], |
| 771 | "ollm_test_output": big_out, |
| 772 | "temperature": 0, |
| 773 | }, |
| 774 | ) |
| 775 | if st_gen != 200: |
| 776 | raise AssertionError(f"Default output >=4096 check failed st={st_gen}: {d_gen}") |
| 777 | comp_toks = int((d_gen.get("usage") or {}).get("completion_tokens", 0)) |
| 778 | if comp_toks < 4096: |
| 779 | raise AssertionError(f"Default max_tokens truncated at {comp_toks} < 4096") |
| 780 | srv.assert_alive() |
| 781 | metrics["ctx_8k_ok_tokens"] = n8k_ok + 1 |
| 782 | metrics["default_out_tokens"] = comp_toks |
| 783 | |
| 784 | p32k_ok, n32k_ok = _make_prompt_with_tokens(ollm_bin, merges, 300, "z ", 32750, work) |
| 785 | p32k_over, n32k_over = _make_prompt_with_tokens(ollm_bin, merges, 300, "z ", 32785, work) |
| 786 | if not (32700 <= n32k_ok + 1 < 32768) or (n32k_over + 1 < 32768): |
| 787 | raise AssertionError(f"Unexpected 32K token counts: ok={n32k_ok} over={n32k_over}") |
| 788 | |
| 789 | with ManagedServer( |
| 790 | [str(ollm_bin), "serve", str(port), str(long_ck), str(merges), "slots=2", "ctx=32768", "kvcache=16", "kvblks=8192"], |
| 791 | port, |
| 792 | ) as srv: |
| 793 | st_32_cold, _, d_32_cold, dt_32_cold = _http_json( |
| 794 | port, "POST", "/v1/completions", {"prompt": p32k_ok, "max_tokens": 2, "temperature": 0, "seed": 9}, timeout=180.0 |
| 795 | ) |
| 796 | if st_32_cold != 200: |
| 797 | raise AssertionError(f"32K cold failed st={st_32_cold}: {d_32_cold}") |
| 798 | st_32_warm, _, d_32_warm, dt_32_warm = _http_json( |
| 799 | port, "POST", "/v1/completions", {"prompt": p32k_ok, "max_tokens": 2, "temperature": 0, "seed": 9}, timeout=180.0 |
| 800 | ) |
| 801 | if st_32_warm != 200: |
| 802 | raise AssertionError(f"32K warm failed st={st_32_warm}: {d_32_warm}") |
| 803 | c32 = int(((d_32_warm.get("usage") or {}).get("prompt_tokens_details") or {}).get("cached_tokens", 0)) |
| 804 | if c32 < 32700 or dt_32_warm >= dt_32_cold: |
| 805 | raise AssertionError(f"32K prefix cache check failed: cached={c32} cold={dt_32_cold:.1f}ms warm={dt_32_warm:.1f}ms") |
| 806 | st_32_ov, _, d_32_ov, _ = _http_json( |
| 807 | port, "POST", "/v1/completions", {"prompt": p32k_over, "max_tokens": 2, "temperature": 0}, timeout=60.0 |
| 808 | ) |
| 809 | if st_32_ov != 400 or (d_32_ov.get("error") or {}).get("code") != "context_length_exceeded": |
| 810 | raise AssertionError(f"Expected 400 context_length_exceeded over 32K, got st={st_32_ov} data={d_32_ov}") |
| 811 | srv.assert_alive() |
| 812 | metrics["ctx_32k_ok_tokens"] = n32k_ok + 1 |
| 813 | metrics["ctx_32k_cold_ms"] = round(dt_32_cold, 1) |
| 814 | metrics["ctx_32k_warm_ms"] = round(dt_32_warm, 1) |
| 815 | return metrics |
| 816 | |
| 817 | |
| 818 | def _suite_e_openai_and_disconnect(ollm_bin: Path, models: dict[str, Path], port: int) -> None: |
| 819 | with ManagedServer( |
| 820 | [str(ollm_bin), "serve", str(port), str(models["base"]), str(models["merges"]), "slots=4", "ctx=8192", "test=1"], |
| 821 | port, |
| 822 | ) as srv: |
| 823 | # Stop sequence & top_k / top_p |
| 824 | st_s, _, d_s, _ = _http_json( |
| 825 | port, |
| 826 | "POST", |
| 827 | "/v1/chat/completions", |
| 828 | { |
| 829 | "messages": [{"role": "user", "content": "stop test"}], |
| 830 | "ollm_test_output": "hello STOP world", |
| 831 | "stop": ["STOP"], |
| 832 | "top_k": 5, |
| 833 | "top_p": 0.9, |
| 834 | "temperature": 0.5, |
| 835 | }, |
| 836 | ) |
| 837 | if st_s != 200 or d_s["choices"][0]["message"]["content"] != "hello " or d_s["choices"][0]["finish_reason"] != "stop": |
| 838 | raise AssertionError(f"Stop/top_k check failed: {st_s} {d_s}") |
| 839 | |
| 840 | # Tool call emission |
| 841 | st_t, _, d_t, _ = _http_json( |
| 842 | port, |
| 843 | "POST", |
| 844 | "/v1/chat/completions", |
| 845 | { |
| 846 | "messages": [{"role": "user", "content": "call a tool"}], |
| 847 | "tools": [{"type": "function", "function": {"name": "ping"}}], |
| 848 | "tool_choice": "auto", |
| 849 | "ollm_test_output": '<tool_call>{"name":"ping","arguments":{"x":1}}</tool_call>', |
| 850 | "temperature": 0, |
| 851 | }, |
| 852 | ) |
| 853 | tcalls = d_t["choices"][0]["message"].get("tool_calls") or [] |
| 854 | if st_t != 200 or d_t["choices"][0]["finish_reason"] != "tool_calls" or len(tcalls) != 1: |
| 855 | raise AssertionError(f"Tool call check failed: {st_t} {d_t}") |
| 856 | |
| 857 | # 404 & 405 |
| 858 | st_404, _, _, _ = _http_json(port, "GET", "/v1/doesnotexist") |
| 859 | st_405, _, _, _ = _http_json(port, "GET", "/v1/chat/completions") |
| 860 | if st_404 != 404 or st_405 != 405: |
| 861 | raise AssertionError(f"Expected 404/405, got {st_404}/{st_405}") |
| 862 | |
| 863 | # Mid-stream client disconnect cleanup -> in_flight returns to 0 |
| 864 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 865 | try: |
| 866 | s.settimeout(10.0) |
| 867 | s.connect(("127.0.0.1", port)) |
| 868 | req_body = json.dumps({ |
| 869 | "messages": [{"role": "user", "content": "drop mid stream"}], |
| 870 | "stream": True, |
| 871 | "ollm_test_output": "token0 token1 token2 token3 token4 ", |
| 872 | "ollm_test_delay_ms": 60, |
| 873 | "temperature": 0, |
| 874 | }).encode("utf-8") |
| 875 | raw_req = ( |
| 876 | f"POST /v1/chat/completions HTTP/1.1\r\n" |
| 877 | f"Host: 127.0.0.1:{port}\r\n" |
| 878 | f"Content-Type: application/json\r\n" |
| 879 | f"Content-Length: {len(req_body)}\r\n\r\n" |
| 880 | ).encode("ascii") + req_body |
| 881 | s.sendall(raw_req) |
| 882 | _ = s.recv(512) |
| 883 | finally: |
| 884 | s.close() |
| 885 | |
| 886 | cleaned = False |
| 887 | for _ in range(50): |
| 888 | _, _, hdata, _ = _http_json(port, "GET", "/health") |
| 889 | if int(hdata.get("in_flight", -1)) == 0: |
| 890 | cleaned = True |
| 891 | break |
| 892 | time.sleep(0.05) |
| 893 | if not cleaned: |
| 894 | raise AssertionError("Slot did not release after client disconnect") |
| 895 | srv.assert_alive() |
| 896 | |
| 897 | |
| 898 | def _suite_f_gb10(omc: str, merges: Path, work: Path, port: int) -> dict[str, object]: |
| 899 | gb10_bin = _build_target("gb10", work, omc) |
| 900 | gpu_ck = work / "gpu.ck" |
| 901 | gpu_corpus = work / "gpu_corpus.txt" |
| 902 | gpu_merges = work / "gpu_merges.bin" |
| 903 | gpu_txt = ( |
| 904 | (ROOT / "docs" / "README.md").read_text(encoding="utf-8") |
| 905 | + "\n" |
| 906 | + (ROOT / "scripts" / "verify-om.sh").read_text(encoding="utf-8") |
| 907 | ) |
| 908 | gpu_corpus.write_text(gpu_txt, encoding="utf-8") |
| 909 | rm = _run_cmd([str(gb10_bin), "bpefit", str(gpu_corpus), str(gpu_merges), "512"]) |
| 910 | if rm.returncode != 0: |
| 911 | raise RuntimeError(f"gpu bpefit failed rc={rm.returncode}: {rm.stdout} {rm.stderr}") |
| 912 | r = _run_cmd([str(gb10_bin), "init", str(gpu_ck), "512", "64", "64", "2", "128", "2", "1", "13", "2", "10000"]) |
| 913 | if r.returncode != 0: |
| 914 | raise RuntimeError(f"gpu init failed rc={r.returncode}: {r.stdout} {r.stderr}") |
| 915 | p8k, _ = _make_prompt_with_tokens(gb10_bin, gpu_merges, 512, "g ", 8180, work) |
| 916 | p8k_over, _ = _make_prompt_with_tokens(gb10_bin, gpu_merges, 512, "g ", 8200, work) |
| 917 | |
| 918 | with ManagedServer( |
| 919 | [str(gb10_bin), "gserve", str(port), str(gpu_ck), str(gpu_merges), "slots=4", "ctx=8192"], |
| 920 | port, |
| 921 | ) as srv: |
| 922 | sts: list[int] = [0] * 4 |
| 923 | |
| 924 | def gworker(i: int) -> None: |
| 925 | st, _, _, _ = _http_sse( |
| 926 | port, |
| 927 | "/v1/chat/completions", |
| 928 | { |
| 929 | "messages": [{"role": "user", "content": f"gpu stream {i}"}], |
| 930 | "stream": True, |
| 931 | "max_tokens": 6, |
| 932 | "temperature": 0, |
| 933 | "seed": 100 + i, |
| 934 | }, |
| 935 | ) |
| 936 | sts[i] = st |
| 937 | |
| 938 | ts = [threading.Thread(target=gworker, args=(i,)) for i in range(4)] |
| 939 | for t in ts: |
| 940 | t.start() |
| 941 | for t in ts: |
| 942 | t.join(timeout=60.0) |
| 943 | if sts != [200, 200, 200, 200]: |
| 944 | raise AssertionError(f"GB10 gserve 4 concurrent streams failed: {sts}") |
| 945 | |
| 946 | st_8k, _, _, dt_8k = _http_json( |
| 947 | port, "POST", "/v1/completions", {"prompt": p8k, "max_tokens": 2, "temperature": 0}, timeout=120.0 |
| 948 | ) |
| 949 | if st_8k != 200: |
| 950 | raise AssertionError(f"GB10 gserve 8K long-context failed: {st_8k}") |
| 951 | st_ov, _, d_ov, _ = _http_json( |
| 952 | port, "POST", "/v1/completions", {"prompt": p8k_over, "max_tokens": 2, "temperature": 0} |
| 953 | ) |
| 954 | if st_ov != 400 or (d_ov.get("error") or {}).get("code") != "context_length_exceeded": |
| 955 | raise AssertionError(f"GB10 gserve >8K refusal failed: {st_ov} {d_ov}") |
| 956 | srv.assert_alive() |
| 957 | return {"gb10_concurrent_4_200": True, "gb10_8k_ms": round(dt_8k, 1)} |
| 958 | |
| 959 | |
| 960 | def main() -> int: |
| 961 | _check_static_invariants() |
| 962 | omc = _find_omc() |
| 963 | with tempfile.TemporaryDirectory(prefix="helix-serve-scale-") as tmpdir: |
| 964 | work = Path(tmpdir) |
| 965 | ollm_env = os.environ.get("OLLM_BIN", "").strip() |
| 966 | ollm_bin = Path(ollm_env) if ollm_env else _build_target("aarch64", work, omc) |
| 967 | magic = ollm_bin.read_bytes()[:4] |
| 968 | if magic != b"\x7fELF": |
| 969 | raise AssertionError(f"Expected ELF binary for TARGET=aarch64, got {magic!r}") |
| 970 | |
| 971 | if platform.system() != "Linux" or platform.machine() not in ("aarch64", "arm64"): |
| 972 | print("SERVE_SCALING_BUILD_PASS (live HTTP execution requires Linux aarch64)") |
| 973 | return 0 |
| 974 | |
| 975 | port = _pick_safe_port() |
| 976 | models = _setup_models(ollm_bin, work) |
| 977 | m_a = _suite_a_concurrency(ollm_bin, models, port) |
| 978 | m_b = _suite_b_prefix_cache_and_strands(ollm_bin, models, work, port) |
| 979 | m_c = _suite_c_collision_and_lru(ollm_bin, models, port) |
| 980 | m_d = _suite_d_long_context(ollm_bin, models, work, port) |
| 981 | _suite_e_openai_and_disconnect(ollm_bin, models, port) |
| 982 | m_f: dict[str, object] = {} |
| 983 | if os.environ.get("OLLM_GB10_LIVE", "") == "1": |
| 984 | m_f = _suite_f_gb10(omc, models["merges"], work, port) |
| 985 | |
| 986 | summary = {**m_a, **m_b, **m_c, **m_d, **m_f} |
| 987 | print("SERVE_SCALING_METRICS " + json.dumps(summary, sort_keys=True)) |
| 988 | print("SERVE_SCALING_PASS") |
| 989 | return 0 |
| 990 | |
| 991 | |
| 992 | if __name__ == "__main__": |
| 993 | raise SystemExit(main()) |