Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-train/blob/main/tests/omegallm/serve-check.py # aien-train AIEN training programme: language-model history, GB10 constraints and the route to training on the project engine. Plans and runnable checks are distinguished. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-train / tests / omegallm / serve-check.py` 623 lines ยท 36071 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Referee for `ollm serve` (DRA-119, native/omegallm/serve.om). 3 4 Usage: serve-check.py PORT OLLM CK MERGES [TPORT [ALLEN_PROMPT]] 5 Talks to an `ollm serve` already listening on 127.0.0.1:PORT (default options) and, when TPORT is 6 given, to a second one started with `tplmax=4000 test=1` on TPORT. Prints one line per check, 7 `PASS name detail` or `FAIL name detail` (or `NOT_RUN name reason`, not counted), then 8 `SUMMARY pass=N fail=M`; exit 1 on any FAIL. Every check is protocol only (no quality claim). 9 The content oracle is the same binary's `sample` command (the CLI's sampler, cmdsamp) on the 10 interim template, decoded with Python's UTF-8 decoder (errors="replace", the maximal-subpart 11 U+FFFD practice that serve.om follows); each parity_ check also compares the sha256 of the served 12 text (UTF-8) with the sha256 of `sample`'s raw stdout and, when the environment names 13 SERVE_PARITY_DIR, keeps both there. The model id oracle reads the checkpoint header here 14 (model_id), independently of serve.om. Tool-call checks script the model's output with the 15 test-only member ollm_test_output, so they test the protocol, not the model. 16 """ 17 import hashlib 18 import http.client 19 import json 20 import os 21 import socket 22 import struct 23 import subprocess 24 import sys 25 import threading 26 import time 27 28 PORT, OLLM, CK, MERGES = int(sys.argv[1]), sys.argv[2], sys.argv[3], sys.argv[4] 29 TPORT = int(sys.argv[5]) if len(sys.argv) > 5 else 0 30 ALLEN = sys.argv[6] if len(sys.argv) > 6 else "/opt/allen-chat/system-prompt.txt" 31 TLOG = os.environ.get("SERVE_TLOG", "") 32 SAMPLE_VERB = os.environ.get("SAMPLE_VERB", "sample") 33 if SAMPLE_VERB not in ("sample", "gsample", "gsampb"): 34 raise SystemExit("unsupported SAMPLE_VERB") 35 # optional: a directory for the parity files (served and sampled bytes per case) 36 PDIR = os.environ.get("SERVE_PARITY_DIR") or None 37 HOST = "127.0.0.1" 38 results = [] 39 LAST = {} 40 41 42 def model_id(path): 43 """The id serve.om must report, read here from the checkpoint header (ckpt.om layout): 44 magic u64 at 0 (OLLMCK01 -> 1, OLLMCK02 -> 2), V T D H F L B u64 at 8..64, step at 72, 45 payload FNV-1a 64 at header length - 8 (112 for CK01, 120 for CK02).""" 46 with open(path, "rb") as f: 47 h = f.read(120) 48 mg = struct.unpack_from(" 0 else 0 159 check(f"chat_json_t{tm}", ok, f"{st} model={j.get('model')} usage={u} finish={ch.get('finish_reason')} s={dt:.2f} tok/s={tps:.3f} content={content!r} oracle={want!r}") 160 parity(f"json_t{tm}_seed{seed}_n{n}", content, raw) 161 162 req.update(stream=True, stream_options={"include_usage": True}) 163 st, ct, out, dt = call("POST", "/v1/chat/completions", req) 164 ev, done = sse(out) if st == 200 else ([], False) 165 deltas = [e["choices"][0]["delta"] for e in ev if e.get("choices")] 166 text = "".join(d.get("content", "") for d in deltas) 167 fins = [e["choices"][0].get("finish_reason") for e in ev if e.get("choices")] 168 usage = [e["usage"] for e in ev if e.get("usage")] 169 ok = (st == 200 and ct.startswith("text/event-stream") and done and deltas and deltas[0].get("role") == "assistant" 170 and all(e.get("object") == "chat.completion.chunk" and e.get("model") == MID for e in ev) 171 and fins[-1] == ch.get("finish_reason") 172 and all(f is None for f in fins[:-1]) and text == content and usage == [u] and ev[-1].get("choices") == []) 173 check(f"chat_sse_t{tm}", ok, f"{st} events={len(ev)} done={done} usage={usage} s={dt:.2f} text={text!r}") 174 parity(f"sse_t{tm}_seed{seed}_n{n}", text if st == 200 else None, raw) 175 176 # allen-chat's body shapes (/opt/allen-chat/allen_chat.py): system + user, tools, tool_choice none 177 ac = {"model": "omega", "messages": [{"role": "system", "content": "Be brief."}, {"role": "user", "content": "hi"}], 178 "max_tokens": 4, "temperature": 0.3, "stream": False, 179 "tools": [{"type": "function", "function": {"name": "x", "parameters": {"type": "object"}}}], "tool_choice": "none"} 180 st, ct, out, _ = call("POST", "/v1/chat/completions", ac) 181 j = json.loads(out) if st == 200 else {} 182 check("allen_chat_shape", st == 200 and j["choices"][0]["finish_reason"] in ("stop", "length") and "tool_calls" not in j["choices"][0]["message"], f"{st} {out[:200]!r}") 183 184 185 # --- parity with the retired 35B (serve layer) ------------------------------------------------- 186 def post(body, port=None, raw=None): 187 st, ct, out, _ = call("POST", "/v1/chat/completions", body, raw=raw, port=port) 188 j = json.loads(out) if st == 200 else {} 189 return st, (j.get("choices") or [{}])[0], out 190 191 192 def post_sse(body, port=None, raw=None): 193 st, ct, out, _ = call("POST", "/v1/chat/completions", dict(body, stream=True) if body is not None else None, raw=raw, port=port) 194 ev, done = sse(out) if st == 200 else ([], False) 195 deltas = [e["choices"][0]["delta"] for e in ev if e.get("choices")] 196 text = "".join(d.get("content") or "" for d in deltas) 197 fins = [e["choices"][0].get("finish_reason") for e in ev if e.get("choices")] 198 calls = [tc for d in deltas for tc in (d.get("tool_calls") or [])] 199 ok = st == 200 and done and all(f is None for f in fins[:-1]) 200 return ok, text, (fins[-1] if fins else None), calls 201 202 203 def raw_with(body, extra): 204 """body as JSON with the literal member text extra appended (numbers json.dumps would write with an exponent).""" 205 return (json.dumps(body)[:-1] + ", " + extra + "}").encode() 206 207 208 def refused(body, word, port=None, raw=None, code_want="invalid_request"): 209 st, ct, out, _ = call("POST", "/v1/chat/completions", body, raw=raw, port=port) 210 code, msg, typ = err_code(out) 211 return st == 400 and code == code_want and word in msg, f"{st} {code} {msg!r}" 212 213 214 check("health_idle", h.get("busy") is False and h.get("in_flight") == 0, f"{h}") 215 216 base = {"messages": msgs, "max_tokens": 12, "temperature": 0, "seed": 7} 217 greedy = oracle(msgs, 7, 12, 0) 218 sample8 = oracle(msgs, 7, 12, 800) 219 st, ch0, out = post(base) 220 fin0 = ch0.get("finish_reason") 221 222 # content as an array of text parts, joined with no separator 223 parts = [{"role": "user", "content": [{"type": "text", "text": "What is "}, {"type": "text", "text": "Omega?"}]}] 224 st, ch, out = post(dict(base, messages=parts)) 225 check("content_parts", st == 200 and ch.get("message", {}).get("content") == greedy, f"{st} {out[:160]!r} oracle={greedy!r}") 226 img = [{"role": "user", "content": [{"type": "text", "text": "a"}, {"type": "image_url", "image_url": {"url": "http://127.0.0.1/x.png"}}]}] 227 check("refuse_image_part", *refused(dict(base, messages=img), "image_url")) 228 check("refuse_part_no_text", *refused(dict(base, messages=[{"role": "user", "content": [{"type": "text"}]}]), "parts")) 229 230 # stop: a substring that occurs once in the greedy output cuts it there (JSON and SSE) 231 stop = next((greedy[i:i + L] for L in (3, 2, 4) for i in range(2, len(greedy) - L + 1) 232 if greedy[i:i + L].isascii() and greedy[i:i + L].isprintable() and greedy.count(greedy[i:i + L]) == 1), None) 233 if stop is None: 234 check("stop_found", False, f"no unique printable ASCII substring in {greedy!r}") 235 else: 236 want = greedy[:greedy.index(stop)] 237 for name, sv in (("stop_str", stop), ("stop_array", ["@@absent@@", stop])): 238 st, ch, out = post(dict(base, stop=sv)) 239 check(f"{name}_json", st == 200 and ch["message"]["content"] == want and ch["finish_reason"] == "stop", 240 f"stop={stop!r} {out[:200]!r} want={want!r}") 241 ok, text, fin, _ = post_sse(dict(base, stop=sv)) 242 check(f"{name}_sse", ok and text == want and fin == "stop", f"stop={stop!r} text={text!r} fin={fin} want={want!r}") 243 st, ch, out = post(dict(base, stop="@@absent@@")) 244 check("stop_absent_control", st == 200 and ch["message"]["content"] == greedy and ch["finish_reason"] == fin0, 245 f"{out[:200]!r} fin0={fin0}") 246 for name, sv in (("refuse_stop_empty", ""), ("refuse_stop_nine", ["a"] * 9), ("refuse_stop_number", 5), 247 ("refuse_stop_long", "x" * 129)): 248 check(name, *refused(dict(base, stop=sv), "stop")) 249 250 # top_k / top_p at temperature 0.8 (fixed seed 7) 251 s8 = dict(base, temperature=0.8) 252 check("sample_differs_from_greedy", sample8 != greedy, f"sample={sample8!r} greedy={greedy!r}") 253 for name, extra, want in (("top_k1_is_greedy", '"top_k": 1', greedy), ("top_p_min_is_greedy", '"top_p": 0.000001', greedy), 254 ("top_p0_is_greedy", '"top_p": 0', greedy), 255 ("top_k0_is_sample", '"top_k": 0', sample8), ("top_k_neg1_is_sample", '"top_k": -1', sample8), 256 ("top_p1_is_sample", '"top_p": 1', sample8), ("top_k_V_is_sample", '"top_k": 4096', sample8)): 257 st, ch, out = post(None, raw=raw_with(s8, extra)) 258 check(name, st == 200 and ch["message"]["content"] == want, f"{extra} {out[:200]!r} want={want!r}") 259 mid = raw_with(s8, '"top_k": 40, "top_p": 0.9') 260 st, ch1, out1 = post(None, raw=mid) 261 st2, ch2, out2 = post(None, raw=mid) 262 ok, text, fin, _ = post_sse(None, raw=raw_with(dict(s8, stream=True), '"top_k": 40, "top_p": 0.9')) 263 c1 = ch1.get("message", {}).get("content") 264 check("top_kp_repeat_and_sse", st == 200 and st2 == 200 and c1 == ch2.get("message", {}).get("content") and ok and text == c1, 265 f"json={c1!r} sse={text!r}") 266 check("top_kp_filters_control", c1 is not None and c1 != sample8, f"filtered={c1!r} unfiltered={sample8!r}") 267 for name, extra, word in (("refuse_top_p_neg", '"top_p": -0.1', "top_p"), ("refuse_top_p_big", '"top_p": 1.5', "top_p"), 268 ("refuse_top_p_exp", '"top_p": 1e-3', "top_p"), ("refuse_top_k_str", '"top_k": "x"', "top_k"), 269 ("refuse_top_k_frac", '"top_k": 1.5', "top_k"), ("refuse_top_k_neg2", '"top_k": -2', "top_k")): 270 check(name, *refused(None, word, raw=raw_with(s8, extra))) 271 272 # tools and a tool-call history render into the documented template (oracle on the same text) 273 tools = [{"type": "function", "function": {"name": "get_weather", "parameters": {"type": "object", "properties": {"city": {"type": "string"}}}}}] 274 hist = [{"role": "user", "content": "Weather in Paris?"}, 275 {"role": "assistant", "content": None, "tool_calls": [ 276 {"id": "c1", "type": "function", "function": {"name": "get_weather", "arguments": "{\"city\":\"Paris\"}"}}, 277 {"id": "c2", "type": "function", "function": {"name": "get_weather", "arguments": {"city": "Rome"}}}]}, 278 {"role": "tool", "tool_call_id": "c1", "content": "sunny"}] 279 tpl = ("tools: " + json.dumps(tools) + "\nuser: Weather in Paris?\nassistant: " 280 + "{\"name\":\"get_weather\",\"arguments\":{\"city\":\"Paris\"}}" 281 + "{\"name\":\"get_weather\",\"arguments\":" + json.dumps({"city": "Rome"}) + "}" 282 + "\ntool: sunny\nassistant: ") 283 want = oracle_tpl(tpl, 7, 4, 0) # 4 tokens: this prompt is over 200 tokens and every token reruns the forward 284 st, ch, out = post(dict(base, messages=hist, tools=tools, tool_choice="none", max_tokens=4)) 285 check("tools_history_template", st == 200 and ch["message"]["content"] == want and "tool_calls" not in ch["message"], 286 f"{st} {out[:200]!r} oracle={want!r}") 287 st, ch, out = post(dict(base, messages=hist, tool_choice="none", max_tokens=4)) 288 check("tools_absent_control", st == 200 and ch["message"]["content"] != want, f"{out[:160]!r}") 289 check("refuse_tool_calls_shape", *refused(dict(base, messages=[{"role": "assistant", "tool_calls": [{"id": "c"}]}]), "tool_calls")) 290 check("refuse_tools_no_name", *refused(dict(base, tools=[{"type": "function", "function": {}}]), "tools")) 291 check("refuse_tool_choice", *refused(dict(base, tools=tools, tool_choice="sometimes"), "tool_choice")) 292 check("refuse_content_absent", *refused(dict(base, messages=[{"role": "user"}]), "content")) 293 check("refuse_test_member", *refused(dict(base, ollm_test_output="hi"), "test=1")) 294 295 # token-based sizing: the template cap is 65536 bytes here; beyond 4000 bytes the context decides 296 check("big_template_is_context", *refused({"messages": [{"role": "user", "content": "x" * 5000}]}, "context window is 256", 297 code_want="context_length_exceeded")) 298 check("refuse_template_bytes", *refused({"messages": [{"role": "user", "content": "x" * 66000}]}, "over 65536 bytes")) 299 if os.path.exists(ALLEN): 300 with open(ALLEN, encoding="utf-8") as f: 301 sp = f.read() 302 st, ct, out, _ = call("POST", "/v1/chat/completions", {"messages": [{"role": "system", "content": sp}, {"role": "user", "content": "hi"}], "max_tokens": 8}) 303 code, msg, typ = err_code(out) 304 nt = int(msg.split()[2]) if code == "context_length_exceeded" else 0 305 check("allen_prompt_context", st == 400 and code == "context_length_exceeded" and "context window is 256" in msg and nt > 256, 306 f"bytes={len(sp.encode())} {st} {code} {msg!r}") 307 else: 308 print("NOT_RUN allen_prompt_context", ALLEN, "absent", flush=True) 309 310 # --- negative controls ------------------------------------------------------------------------ 311 long_text = " ".join(f"word{i} omega{i * 7}" for i in range(300))[:3800] 312 st, ct, out, _ = call("POST", "/v1/chat/completions", {"messages": [{"role": "user", "content": long_text}], "max_tokens": 4}) 313 code, msg, typ = err_code(out) 314 check("refuse_context", st == 400 and code == "context_length_exceeded" and "context window is 256" in msg, f"{st} {code} {msg!r}") 315 316 for name, raw in (("refuse_bad_json", b"{\"messages\": [}"), ("refuse_not_object", b"[1]"), 317 ("refuse_trailing", b"{\"messages\":[{\"role\":\"user\",\"content\":\"a\"}]} x")): 318 st, ct, out, _ = call("POST", "/v1/chat/completions", raw=raw) 319 code, msg, typ = err_code(out) 320 check(name, st == 400 and typ == "invalid_request_error", f"{st} {code} {msg!r}") 321 322 bad = [("refuse_empty_messages", {"messages": []}), 323 ("refuse_content_number", {"messages": [{"role": "user", "content": 5}]}), 324 ("refuse_no_role", {"messages": [{"content": "a"}]}), 325 ("refuse_neg_temp", {"messages": msgs, "temperature": -1}), 326 ("refuse_hot_temp", {"messages": msgs, "temperature": 2.5}), 327 ("refuse_zero_max", {"messages": msgs, "max_tokens": 0}), 328 ("refuse_n2", {"messages": msgs, "n": 2}), 329 ("refuse_stream_str", {"messages": msgs, "stream": "yes"})] 330 for name, body in bad: 331 st, ct, out, _ = call("POST", "/v1/chat/completions", body) 332 code, msg, typ = err_code(out) 333 check(name, st == 400 and code == "invalid_request", f"{st} {code} {msg!r}") 334 335 st, ct, out, _ = call("POST", "/v1/chat/completions", raw=b"{\"messages\":[{\"role\":\"user\",\"content\":\"a\"}],\"temperature\":1e-3}") 336 code, msg, typ = err_code(out) 337 check("refuse_exp_temp", st == 400 and code == "invalid_request" and "temperature" in msg, f"{st} {code} {msg!r}") 338 339 st, ct, out, _ = call("GET", "/v1/nope") 340 check("refuse_404", st == 404 and err_code(out)[0] == "not_found", f"{st} {out!r}") 341 st, ct, out, _ = call("GET", "/v1/chat/completions") 342 check("refuse_405", st == 405 and err_code(out)[0] == "method_not_allowed", f"{st} {out!r}") 343 344 s = socket.create_connection((HOST, PORT), timeout=30) 345 s.sendall(b"POST /v1/chat/completions HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\nContent-Length: `1000000`\r\n\r\n") 346 resp = b"" 347 while True: 348 b = s.recv(65536) 349 if not b: 350 break 351 resp += b 352 s.close() 353 check("refuse_413", resp.startswith(b"HTTP/1.1 413") and b"request_too_large" in resp, f"{resp[:120]!r}") 354 355 # the JSON parser's tape holds 65532 tokens: past it the body is 413 request_too_large, not invalid_json 356 for name, n, want in (("refuse_json_tokens", 70000, 413), ("json_tokens_under_cap_control", 60000, 200)): 357 st, ct, out, _ = call("POST", "/v1/chat/completions", {"messages": msgs, "max_tokens": 1, "temperature": 0, "x": [0] * n}) 358 code, msg, typ = err_code(out) if st != 200 else (None, "", None) 359 ok = st == 413 and code == "request_too_large" and "65532 JSON tokens" in msg if want == 413 else st == 200 360 check(name, ok, f"zeros={n} {st} {code} {msg!r}") 361 362 # One request per connection: a client that keeps its connection open (allen-chat pools one) 363 # must not hold the serial listener; the next client is answered at once. 364 held = http.client.HTTPConnection(HOST, PORT, timeout=30) 365 held.request("GET", "/health") 366 r = held.getresponse() 367 r.read() 368 conn_hdr = (r.getheader("Connection") or "").lower() 369 t0 = time.monotonic() 370 st, ct, out, _ = call("GET", "/health", timeout=5) 371 dt = time.monotonic() - t0 372 held.close() 373 check("held_conn_not_blocking", conn_hdr == "close" and st == 200 and dt < 2, 374 f"Connection={conn_hdr!r} next={st} in {dt:.3f}s") 375 376 # A connection that sends nothing waits in a pending slot: the next client is answered at once, and 377 # the silent one is closed unanswered 10 s after its accept. Control: a connection that started a 378 # head does hold the serial listener, up to its 10 s head deadline (the documented bound). 379 silent = socket.create_connection((HOST, PORT), timeout=30) 380 t_s = time.monotonic() 381 time.sleep(0.1) 382 t0 = time.monotonic() 383 st, ct, out, _ = call("GET", "/health", timeout=30) 384 dt = time.monotonic() - t0 385 check("silent_conn_not_blocking", st == 200 and dt < 1, f"next={st} after {dt:.3f}s") 386 partial = socket.create_connection((HOST, PORT), timeout=30) 387 partial.sendall(b"GET /health HTTP/1.1\r\n") 388 time.sleep(0.1) 389 t0 = time.monotonic() 390 st, ct, out, _ = call("GET", "/health", timeout=30) 391 dt = time.monotonic() - t0 392 partial.close() 393 check("partial_head_holds_control", st == 200 and 7 < dt < 15, f"next={st} after {dt:.3f}s") 394 try: 395 eof = silent.recv(64) 396 except OSError as e: 397 eof = repr(e).encode() 398 dts = time.monotonic() - t_s 399 silent.close() 400 check("silent_conn_closed_10s", eof == b"" and 8 < dts < 20, f"recv={eof!r} after {dts:.3f}s") 401 402 st, ct, out, _ = call("GET", "/health") 403 check("alive_after_negatives", st == 200, f"{st}") 404 405 406 # --- POST /v1/completions: prompt is the whole template (start token + prompt, no role lines) --- 407 def cpost(body, port=None, raw=None): 408 st, ct, out, _ = call("POST", "/v1/completions", body, raw=raw, port=port) 409 j = json.loads(out) if st == 200 else {} 410 return st, j, out 411 412 413 def crefused(body, word, port=None, raw=None, code_want="invalid_request"): 414 st, ct, out, _ = call("POST", "/v1/completions", body, raw=raw, port=port) 415 code, msg, typ = err_code(out) 416 return st == 400 and code == code_want and word in msg, f"{st} {code} {msg!r}" 417 418 419 cprompt = "fn main to long\n" 420 cwant = oracle_tpl(cprompt, 7, 8, 0) 421 st, j, out = cpost({"model": "ollm", "prompt": cprompt, "max_tokens": 8, "temperature": 0, "seed": 7}) 422 ch = (j.get("choices") or [{}])[0] 423 u = j.get("usage", {}) 424 check("cmpl_greedy_parity", st == 200 and j.get("object") == "text_completion" and j.get("id", "").startswith("cmpl-ollm-") 425 and ch.get("index") == 0 and ch.get("finish_reason") in ("stop", "length") and ch.get("text") == cwant 426 and "message" not in ch and u.get("total_tokens") == u.get("prompt_tokens", 0) + u.get("completion_tokens", 0) 427 and 1 <= u.get("completion_tokens", 0) <= 8, f"{st} {out[:240]!r} oracle={cwant!r}") 428 chatw = oracle_tpl("user: " + cprompt + "\nassistant: ", 7, 8, 0) 429 check("cmpl_no_chat_template_control", chatw != cwant, f"chat_template={chatw!r} raw={cwant!r}") 430 st, j, out = cpost({"prompt": cprompt, "max_tokens": 8, "top_p": 0, "temperature": 0.8, "seed": 7}) 431 check("cmpl_top_p0_is_greedy", st == 200 and (j.get("choices") or [{}])[0].get("text") == cwant, f"{out[:200]!r}") 432 cb = {"prompt": cprompt, "max_tokens": 4} 433 for name, body, word in (("cmpl_refuse_stream", dict(cb, stream=True), "stream is not supported on /v1/completions"), 434 ("cmpl_refuse_messages", dict(cb, messages=msgs), "takes prompt"), 435 ("cmpl_refuse_tools", dict(cb, tools=tools), "takes prompt"), 436 ("cmpl_refuse_tool_choice", dict(cb, tool_choice="none"), "takes prompt"), 437 ("cmpl_refuse_no_prompt", {"max_tokens": 4}, "prompt must be a non-empty string"), 438 ("cmpl_refuse_prompt_number", dict(cb, prompt=5), "prompt must be a non-empty string"), 439 ("cmpl_refuse_prompt_array", dict(cb, prompt=["a"]), "prompt must be a non-empty string"), 440 ("cmpl_refuse_prompt_empty", dict(cb, prompt=""), "prompt must be a non-empty string"), 441 ("cmpl_refuse_n2", dict(cb, n=2), "n = 1"), 442 ("cmpl_refuse_prompt_bytes", dict(cb, prompt="x" * 66000), "over 65536 bytes")): 443 check(name, *crefused(body, word)) 444 check("cmpl_refuse_context", *crefused({"prompt": long_text, "max_tokens": 4}, "context window is 256", code_want="context_length_exceeded")) 445 st, ct, out, _ = call("GET", "/v1/completions") 446 check("cmpl_refuse_405", st == 405 and err_code(out)[0] == "method_not_allowed", f"{st} {out!r}") 447 st, ct, out, _ = call("GET", "/v1/nope") 448 check("refuse_404_lists_completions", st == 404 and "POST /v1/completions" in err_code(out)[1], f"{st} {out!r}") 449 st, ct, out, _ = call("GET", "/health") 450 check("alive_after_cmpl", st == 200, f"{st}") 451 452 # --- second server: tplmax=4000 test=1 (scripted output: protocol checks, not model checks) ---- 453 if TPORT: 454 st, ct, out, _ = call("GET", "/health", port=TPORT) 455 check("t_health_idle", st == 200 and json.loads(out) == {"status": "ok", "in_flight": 0, "busy": False}, f"{st} {out!r}") 456 check("t_refuse_template_bytes", *refused({"messages": [{"role": "user", "content": "x" * 4100}]}, "over 4000 bytes", port=TPORT)) 457 458 tools2 = tools + [{"type": "function", "function": {"name": "get_time"}}] 459 user = [{"role": "user", "content": "Weather in Paris?"}] 460 tb = {"messages": user, "tools": tools2, "max_tokens": 200, "temperature": 0} 461 462 plain = "hello world, no tools here" 463 st, ch, out = post(dict(tb, ollm_test_output=plain), port=TPORT) 464 check("t_forced_plain", st == 200 and ch["message"]["content"] == plain and ch["finish_reason"] == "stop" 465 and "tool_calls" not in ch["message"], f"{out[:200]!r}") 466 467 one = 'Sure.\n{"name": "get_weather", "arguments": {"city": "Paris"}}\n' 468 st, ch, out = post(dict(tb, ollm_test_output=one), port=TPORT) 469 m = ch.get("message", {}) 470 tc = m.get("tool_calls") or [{}] 471 f = tc[0].get("function", {}) 472 check("t_tool_call_json", st == 200 and ch["finish_reason"] == "tool_calls" and m.get("content") == "Sure." and len(tc) == 1 473 and tc[0].get("id", "").startswith("call_") and tc[0].get("type") == "function" and f.get("name") == "get_weather" 474 and f.get("arguments") == '{"city": "Paris"}', f"{out[:300]!r}") 475 ok, text, fin, calls = post_sse(dict(tb, ollm_test_output=one), port=TPORT) 476 cf = calls[0].get("function", {}) if calls else {} 477 check("t_tool_call_sse", ok and text == "Sure." and fin == "tool_calls" and len(calls) == 1 and calls[0].get("index") == 0 478 and calls[0].get("id", "").startswith("call_") and cf.get("name") == "get_weather" and cf.get("arguments") == '{"city": "Paris"}', 479 f"text={text!r} fin={fin} calls={calls}") 480 481 two = '{"name":"get_weather","arguments":"{\\"city\\":\\"Rome\\"}"} {"name":"get_time"}' 482 st, ch, out = post(dict(tb, ollm_test_output=two), port=TPORT) 483 m = ch.get("message", {}) 484 tc = m.get("tool_calls") or [] 485 check("t_tool_calls_two", st == 200 and ch["finish_reason"] == "tool_calls" and m.get("content") is None and len(tc) == 2 486 and [t["function"]["name"] for t in tc] == ["get_weather", "get_time"] 487 and [t["function"]["arguments"] for t in tc] == ['{"city":"Rome"}', "{}"] and tc[0]["id"] != tc[1]["id"], f"{out[:400]!r}") 488 489 # controls: each is the same text with one thing wrong, so it stays plain content (finish stop) 490 for name, body in (("t_ctl_undeclared", dict(tb, ollm_test_output=one.replace("get_weather", "launch"))), 491 ("t_ctl_bad_json", dict(tb, ollm_test_output=one.replace('"Paris"}}', '"Paris"}'))), 492 ("t_ctl_trailing_text", dict(tb, ollm_test_output=one + "and more")), 493 ("t_ctl_tool_choice_none", dict(tb, ollm_test_output=one, tool_choice="none")), 494 ("t_ctl_no_tools", {"messages": user, "max_tokens": 200, "temperature": 0, "ollm_test_output": one})): 495 st, ch, out = post(body, port=TPORT) 496 check(name + "_json", st == 200 and ch["finish_reason"] == "stop" and ch["message"]["content"] == body["ollm_test_output"] 497 and "tool_calls" not in ch["message"], f"{out[:300]!r}") 498 ok, text, fin, calls = post_sse(body, port=TPORT) 499 check(name + "_sse", ok and fin == "stop" and text == body["ollm_test_output"] and not calls, f"text={text!r} fin={fin}") 500 501 # a role tool message after an assistant tool_calls turn is accepted and answered (one tool 502 # declared: with two the prompt is 265 tokens, past T = 256) 503 st, ch, out = post(dict(tb, messages=hist, tools=tools, ollm_test_output="It is sunny in Paris."), port=TPORT) 504 check("t_tool_result_turn", st == 200 and ch["message"]["content"] == "It is sunny in Paris." and ch["finish_reason"] == "stop", 505 f"{out[:200]!r}") 506 507 # busy: while a delayed stream generates, /health reports it and a second completion gets 503 508 slow = " ".join(f"w{i}" for i in range(20)) 509 box = {} 510 th = threading.Thread(target=lambda: box.update(r=post_sse({"messages": user, "max_tokens": 200, "temperature": 0, 511 "ollm_test_output": slow, "ollm_test_delay_ms": 300}, port=TPORT))) 512 th.start() 513 time.sleep(1.5) 514 st, ct, out, _ = call("GET", "/health", port=TPORT) 515 hb = json.loads(out) if st == 200 else {} 516 stm, ct, outm, _ = call("GET", "/v1/models", port=TPORT) 517 st5, ct, out5, _ = call("POST", "/v1/chat/completions", base, port=TPORT) 518 ra = LAST[threading.get_ident()].get("retry-after") 519 code, msg, typ = err_code(out5) 520 th.join() 521 ok, text, fin, _ = box.get("r", (False, "", None, [])) 522 check("t_busy_health", hb == {"status": "ok", "in_flight": 1, "busy": True} and stm == 200, f"{st} {out!r} models={stm}") 523 check("t_busy_503", st5 == 503 and code == "server_busy" and ra == "1", f"{st5} {code} retry-after={ra!r} {msg!r}") 524 check("t_busy_stream_whole", ok and text == slow and fin == "stop", f"text={text!r} fin={fin}") 525 st, ct, out, _ = call("GET", "/health", port=TPORT) 526 check("t_health_after", st == 200 and json.loads(out).get("in_flight") == 0, f"{out!r}") 527 528 slowb = {"messages": user, "max_tokens": 200, "temperature": 0, "ollm_test_output": slow, "ollm_test_delay_ms": 300} 529 # side connections during a generation: silent ones wait in pending slots and cost it nothing; 530 # control: one that started a head stalls the side channel up to its 250 ms head deadline 531 box = {} 532 th = threading.Thread(target=lambda: box.update(r=post_sse(slowb, port=TPORT))) 533 th.start() 534 time.sleep(1.0) 535 sil = [socket.create_connection((HOST, TPORT), timeout=30) for _ in range(3)] 536 time.sleep(0.3) 537 t0 = time.monotonic() 538 st, ct, out, _ = call("GET", "/health", port=TPORT) 539 d1 = time.monotonic() - t0 540 hb1 = json.loads(out) if st == 200 else {} 541 part = socket.create_connection((HOST, TPORT), timeout=30) 542 part.sendall(b"GET /health HTTP/1.1\r\n") 543 t0 = time.monotonic() 544 st, ct, out, _ = call("GET", "/health", port=TPORT) 545 d2 = time.monotonic() - t0 546 hb2 = json.loads(out) if st == 200 else {} 547 th.join() 548 part.close() 549 for s_ in sil: 550 s_.close() 551 ok, text, fin, _ = box.get("r", (False, "", None, [])) 552 check("t_side_silent_no_stall", hb1.get("busy") is True and d1 < 0.2 and ok and text == slow, 553 f"health {d1:.3f}s {hb1} stream_ok={ok} text_ok={text == slow}") 554 check("t_side_partial_head_control", hb2.get("busy") is True and 0.15 < d2 < 1.5, f"health {d2:.3f}s {hb2}") 555 556 # a non-streaming client that leaves mid-generation frees the slot at the next token 557 # (svgone); control: a client that stays gets its whole answer and the slot stays busy 558 body = json.dumps(slowb).encode() 559 gone = socket.create_connection((HOST, TPORT), timeout=30) 560 gone.sendall(b"POST /v1/chat/completions HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\nContent-Length: " 561 + str(len(body)).encode() + b"\r\n\r\n" + body) 562 time.sleep(1.0) 563 gone.close() 564 time.sleep(1.0) 565 st, ct, out, _ = call("GET", "/health", port=TPORT) 566 hg = json.loads(out) if st == 200 else {} 567 check("t_disconnect_frees_slot", hg == {"status": "ok", "in_flight": 0, "busy": False}, f"{st} {out!r}") 568 if TLOG: 569 with open(TLOG) as f: 570 lines = [l.split() for l in f if l.startswith("C 499 ")] 571 check("t_disconnect_logged", len(lines) >= 1 and lines[0][4] == "4", f"{lines}") 572 else: 573 print("NOT_RUN t_disconnect_logged SERVE_TLOG unset", flush=True) 574 box = {} 575 th = threading.Thread(target=lambda: box.update(r=post(slowb, port=TPORT))) 576 th.start() 577 time.sleep(2.0) 578 st, ct, out, _ = call("GET", "/health", port=TPORT) 579 hk = json.loads(out) if st == 200 else {} 580 th.join() 581 stk, chk, outk = box.get("r", (0, {}, b"")) 582 check("t_connected_stays_control", hk.get("in_flight") == 1 and stk == 200 and chk.get("message", {}).get("content") == slow 583 and chk.get("finish_reason") == "stop", f"health={hk} {stk} {outk[:120]!r}") 584 st, ch, out = post(base, port=TPORT) 585 check("t_idle_not_busy_control", st == 200 and ch["message"]["content"] == greedy, f"{out[:200]!r}") 586 587 # /v1/completions on the test server: scripted output, busy 503, and a client that leaves 588 cslow = {"prompt": "x", "max_tokens": 200, "temperature": 0, "ollm_test_output": slow, "ollm_test_delay_ms": 300} 589 st, j, out = cpost(dict(cslow, ollm_test_delay_ms=0), port=TPORT) 590 check("t_cmpl_forced", st == 200 and j["choices"][0]["text"] == slow and j["choices"][0]["finish_reason"] == "stop", f"{out[:200]!r}") 591 box = {} 592 th = threading.Thread(target=lambda: box.update(r=cpost(cslow, port=TPORT))) 593 th.start() 594 time.sleep(1.5) 595 st, ct, out, _ = call("GET", "/health", port=TPORT) 596 hb = json.loads(out) if st == 200 else {} 597 st5, ct, out5, _ = call("POST", "/v1/completions", cb, port=TPORT) 598 ra = LAST[threading.get_ident()].get("retry-after") 599 code, msg, typ = err_code(out5) 600 th.join() 601 stb, jb, outb = box.get("r", (0, {}, b"")) 602 check("t_cmpl_busy_503", hb.get("busy") is True and st5 == 503 and code == "server_busy" and ra == "1", f"health={hb} {st5} {code} {msg!r}") 603 check("t_cmpl_busy_whole", stb == 200 and (jb.get("choices") or [{}])[0].get("text") == slow, f"{outb[:200]!r}") 604 body = json.dumps(cslow).encode() 605 gone = socket.create_connection((HOST, TPORT), timeout=30) 606 gone.sendall(b"POST /v1/completions HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\nContent-Length: " 607 + str(len(body)).encode() + b"\r\n\r\n" + body) 608 time.sleep(1.0) 609 gone.close() 610 time.sleep(1.0) 611 st, ct, out, _ = call("GET", "/health", port=TPORT) 612 hg = json.loads(out) if st == 200 else {} 613 check("t_cmpl_disconnect_frees_slot", hg == {"status": "ok", "in_flight": 0, "busy": False}, f"{st} {out!r}") 614 if TLOG: 615 with open(TLOG) as f: 616 lines = [l.split() for l in f if l.startswith("C 499 ")] 617 check("t_cmpl_disconnect_logged", len(lines) == 2 and lines[1][4] == "4" and int(lines[1][3]) < 200, f"{lines}") 618 else: 619 print("NOT_RUN t_cmpl_disconnect_logged SERVE_TLOG unset", flush=True) 620 621 fails = results.count(False) 622 print(f"SUMMARY pass={results.count(True)} fail={fails}", flush=True) 623 sys.exit(1 if fails else 0)