Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
GLM server: a request log module for debugging (KYOJIN_REQLOG, off by default)
MangetsuC88d73e41ee06
diff --git a/tools/glm/SERVE.md b/tools/glm/SERVE.mdindex 22824d9..b20704d 100644--- a/tools/glm/SERVE.md+++ b/tools/glm/SERVE.md@@ -175,6 +175,53 @@ simply absent. GLM tool calls are emitted by the model as `<\u200btool_call>namedeliberate so plain prose never triggers the parser; arg values are JSON-parsed when theyparse, otherwise kept as strings.+## Diagnostics: the request log++**It is off unless you ask for it.** With `KYOJIN_REQLOG` unset, nothing is opened and every call is a+no-op: a default deployment behaves exactly as before and writes no file. The server prints which of the+two it is at start-up, so the switch stays discoverable:++```+serve: request log off (set KYOJIN_REQLOG=<path> to enable, numbers and event names only)+serve: request log /home/you/.cache/kyojin/requests.log (heartbeat 10 s, numbers and event names only, no prompt or reply text)+```++| variable | default | meaning |+|---|---|---|+| `KYOJIN_REQLOG` | **unset = off** | a path, or `1`/`on`/`yes` for `~/.cache/kyojin/requests.log`; `0`/`off`/`none`/`no`/`false` also disable it |+| `KYOJIN_REQLOG_HEARTBEAT_S` | `10` | seconds between `alive` lines while a job is queued, prefilling or decoding; `0` disables the heartbeat |++Every line is `<local ISO timestamp with ms> <event> srv=glm key=value ...`, and every line of one request+carries the same opaque `req=` id, so `grep <id>` follows one request from arrival to reply across the+queue and the worker. Events, in the order a request that goes through produces them:++| event | written when | useful fields |+|---|---|---|+| `serve_start` | server ready, once | `ctx`, `cache_tokens`, `sessions`, `num_draft`, `row_budget`, `vision`, `conv_gemm`, `dense_tune`, `image_cache_mb`, `image_cache_items` |+| `req_start` | request arrives | `path`, `method`, `bytes` |+| `req_refused` | 400/404/... answer | `status`, `reason` (the server's own text; a JSON parse error is reduced to line/column) |+| `req_queued` | handed to the worker queue | `queued_ahead`, `prompt_tokens`, `messages`, `images`, `stream` |+| `job_start` | worker picks it up | `wait_s` (queue time), `prompt_tokens`, `images`, `sessions`, `processing`, `running` |+| `alive` | every `KYOJIN_REQLOG_HEARTBEAT_S` while tracked | `phase` (`parse`/`queued`/`prefill`/`decode`/`stream`), `elapsed_s`, `processing`, `running` |+| `job_first_token` | first generated token | `elapsed_s` — when the model first produced anything |+| `sse_headers` / `sse_first_content` | streaming: headers sent / first frame with text | `first_s` since arrival — the gap the client experiences as silence |+| `job_done` | job finished | `prompt_tokens`, `cache_n`, `cache_pct`, `new_tokens`, `prefill_s`, `decode_s`, `elapsed_s` |+| `img_cache` | image request, after `job_done` | `imgs`, `hits`, `misses`, `first_missing`, `entries`, `mb`, `budget_mb`, `item_cap`, `evicted` |+| `sse_done` / `req_done` | stream closed / response returned | `out_tokens`, `status`, `elapsed_s` |+| `client_left` | client hung up first | `path`, `stage` |+| `job_skipped` / `job_error` / `stream_error` / `req_error` | cancelled before start / failure | `error` (type plus a truncated message) |++`img_cache` is the line for image sessions: `hits` and `misses` are the embeddings the cache already held+and the ones it re-encoded, and **`first_missing` is the index of the first picture that had to be+re-encoded — the paged KV prefix can only match up to it.** A full hit has no `first_missing` field at all;+`evicted` counts entries this call pushed out. Nothing in the log reports prompt, reply, tool or+image-path text; the one exception is the server's own refusal `reason`, which is why a JSON parse error is+reduced to line/column (its message quotes the body).++Cost when enabled: one `write`+`flush` per event on the event loop, tens of bytes per line. When a request+is slow, `grep -E 'alive|job_first_token|job_done' requests.log` shows whether it was waiting in the queue,+prefilling a prompt the cache could not serve, or decoding.+## Start-up progress on `/health`The port answers from the first second, while the model is still loading. `GET /health` returns `200 {"status":"ok","source":"kyojin"}`diff --git a/tools/glm/serve.py b/tools/glm/serve.pyindex 1d7daf5..976edd8 100644--- a/tools/glm/serve.py+++ b/tools/glm/serve.py@@ -7,6 +7,8 @@ import argparseimport asyncioimport base64import contextlib+import contextvars+import functoolsimport ioimport jsonimport os@@ -27,6 +29,11 @@ import startup_health # noqa: E402 (GET /health with load progress while the mimport serve_compat # noqa: E402 (vLLM-style token-id prompts, cache_salt, /tokenize, usage details)# serve_metrics.py is a symlink to the shared tools/strix_halo/serve_metrics.pyfrom serve_metrics import Metrics+# serve_reqlog.py is a symlink to the shared tools/strix_halo/serve_reqlog.py: one line per request+# lifecycle event (numbers and event names only, never prompt or reply text) plus a heartbeat while a job+# is queued or prefilling, so "the client went silent" can be lined up with what the server was doing.+# Off unless KYOJIN_REQLOG names a path; the server prints which of the two it is at start-up.+from serve_reqlog import ReqLog, sanitizefrom image_cache import ImageEmbeddingCache, digestDEFAULT_MODEL = "~/models/glm53-exl3-td205"@@ -341,6 +348,16 @@ def _bad(reason: str) -> web.HTTPBadRequest:return web.HTTPBadRequest(reason=reason)+def refusal_text(exc: web.HTTPException) -> str:+ """The server's own refusal text for the request log, without the exception type (the line already says+ which request it was). A JSON parse error is reduced to line/column: its message quotes the request body."""+ cause = exc.__cause__+ if isinstance(cause, json.JSONDecodeError):+ return sanitize(cause)+ text = " ".join(str(exc.reason or "").split())[:160]+ return text or type(exc).__name__++def extract_images(messages: list[dict[str, Any]]) -> list[str]:"""Image URLs of the messages in prompt order (OpenAI image_url parts). Video and audio parts are refused:this server has no such tower, and dropping them silently would let the model invent an answer."""@@ -528,15 +545,38 @@ class ResidentEngine:pp.patch_size * pp.merge_size, pp.min_image_tokens, pp.max_image_tokens)return (th // pp.patch_size) * (tw // pp.patch_size) // (v.spatial_merge_size ** 2)- def _embed(self, images: list[tuple[Any, str]]) -> list:+ def _embed(self, images: list[tuple[Any, str]], stats: dict[str, Any] | None = None) -> list:"""One MMEmbedding per image. The same bytes give the same embedding object (same pseudo token ids), so a- history turn that repeats an image still matches the paged KV cache (see image_cache.py)."""+ history turn that repeats an image still matches the paged KV cache (see image_cache.py).++ `stats`, when given, receives what the cache did for this request. A hit keeps the object and therefore+ the pseudo ids the KV pages were keyed on; a miss re-encodes the picture and the paged prefix can only+ match up to it, so `first_missing` (index of the first picture not held) is the number to watch. This+ only reports: the cache policy itself is untouched."""+ cache = self.emb_cache+ entries_before = len(cache)+ built: set[int] = set()+def build(image):t0 = time.perf_counter()emb = self.vision.get_image_embeddings(tokenizer=self.tokenizer, image=image)+ built.add(id(emb)) # tells a hit from a miss once get_many() hands the list back in prompt orderprint(f"serve: image {image.size[0]}x{image.size[1]} -> {emb.mm_length} tokens, tower {(time.perf_counter() - t0) * 1000:.0f} ms", flush=True)return emb- return self.emb_cache.get_many(images, build)++ out = cache.get_many(images, build)+ if stats is not None:+ missed = [id(emb) in built for emb in out]+ misses = sum(missed)+ stats.update({+ "imgs": len(out), "hits": len(out) - misses, "misses": misses,+ "first_missing": next((i for i, m in enumerate(missed) if m), None),+ "entries": len(cache), "mb": round(cache.nbytes / 2 ** 20, 1),+ "budget_mb": round(float(getattr(cache, "max_bytes", 0)) / 2 ** 20, 1),+ "item_cap": int(getattr(cache, "max_items", 0) or 0),+ "evicted": max(0, entries_before + misses - len(cache)),+ })+ return outdef count_tokens(self, text: str) -> int:return int(self.tokenizer.encode(text, encode_special_tokens=True).numel())@@ -548,11 +588,14 @@ class ResidentEngine:async def generate(self, prompt: str, *, max_tokens: int, temperature: float,top_p: float, stop: list[str], sampler_kw: dict | None = None,cancel: asyncio.Event | None = None,- images: list | None = None, stats: dict | None = None,+ images: list | None = None, stats: dict | None = None, img_stats: dict | None = None,prompt_ids: list[int] | None = None, ignore_eos: bool = False) -> AsyncIterator[str]:"""Yield incremental decoded text. With sessions == 1 the caller serializes access to this method; withsessions > 1 several calls may run at once and the final stats of a request land in `stats`.+ `img_stats` (optional) receives the image-embedding cache hit/miss counts of this request; it is kept+ apart from `stats` because `stats` is the Generator's own end-of-job report.+When `cancel` is set (client gone) the job is cancelled between two generator steps. A step is oneprefill chunk or one decode step, so a drop during prefill stops at the next chunk boundary."""import time@@ -567,9 +610,9 @@ class ResidentEngine:self.slot_store.note_prompt("", ids)elif images:if self.sessions > 1: # the tower must not run next to a Generator step: run it on the driver, between steps- embs = await self._post(self._embed, images)+ embs = await self._post(self._embed, images, img_stats)else:- embs = await asyncio.get_running_loop().run_in_executor(None, self._embed, images)+ embs = await asyncio.get_running_loop().run_in_executor(None, self._embed, images, img_stats)for emb in embs:prompt = prompt.replace(IMAGE_TRIPLE, emb.text_alias, 1)ids = self.tokenizer.encode(prompt, encode_special_tokens=True, embeddings=embs)@@ -888,6 +931,67 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:app = web.Application(client_max_size=64 * 1024**2, middlewares=[startup_health.json_errors_middleware()])app.update(engine=engine, model_id=model_id, template=template, queue=queue, metrics=Metrics())+ # Request log: off unless KYOJIN_REQLOG names a path, in which case every generation request gets one line+ # per lifecycle event (numbers and event names only, never prompt or reply text) plus an 'alive' heartbeat+ # while it is queued or running. `inflight` is what the heartbeat walks; it holds no request content.+ reqlog = ReqLog.from_env(server="glm")+ app.update(reqlog=reqlog)+ inflight: dict[str, dict[str, Any]] = {}+ background: dict[str, Any] = {} # the heartbeat task, created at start-up (nothing when the log is off)+ current_req: contextvars.ContextVar[str | None] = contextvars.ContextVar("reqid", default=None)++ def reqid() -> str | None:+ """The log id of the request being handled (None outside a logged route)."""+ return current_req.get()++ def track(rid: str | None, phase: str, **fields: Any) -> None:+ if rid is None:+ return+ st = inflight.setdefault(rid, {"t0": time.perf_counter()})+ st["phase"] = phase+ st.update(fields)++ async def heartbeat() -> None:+ while True:+ await asyncio.sleep(reqlog.heartbeat_s)+ now = time.perf_counter()+ for rid, st in list(inflight.items()):+ reqlog.log("alive", req=rid, phase=st.get("phase"), elapsed_s=round(now - st["t0"], 2),+ prompt_tokens=st.get("prompt_tokens"), processing=processing, running=running)++ def logged(handler):+ """Wrap a route so its lifecycle lands in the request log. The id is opaque and per request; every+ line of one request carries it, so `grep <id>` follows the request across the queue and the worker."""+ @functools.wraps(handler)+ async def wrapper(request: web.Request) -> web.StreamResponse:+ rid = f"r{uuid.uuid4().hex[:12]}"+ token = current_req.set(rid)+ started = time.perf_counter()+ track(rid, "parse")+ reqlog.log("req_start", req=rid, path=request.path, method=request.method,+ bytes=request.content_length)+ try:+ response = await handler(request)+ except web.HTTPException as exc:+ reqlog.log("req_refused", req=rid, path=request.path, status=exc.status,+ reason=refusal_text(exc), elapsed_s=round(time.perf_counter() - started, 3))+ raise+ except asyncio.CancelledError:+ reqlog.log("client_left", req=rid, path=request.path, stage="handler")+ raise+ except Exception as exc: # noqa: BLE001+ reqlog.log("req_error", req=rid, path=request.path, error=sanitize(exc),+ elapsed_s=round(time.perf_counter() - started, 3))+ raise+ else:+ reqlog.log("req_done", req=rid, path=request.path, status=response.status,+ elapsed_s=round(time.perf_counter() - started, 3))+ return response+ finally:+ inflight.pop(rid, None)+ current_req.reset(token)+ return wrapper+def salt_of(body: dict[str, Any]) -> str | None:try:salt = serve_compat.cache_salt(body)@@ -981,15 +1085,25 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:while True:body, out, request_stats = await queue.get()cancel = body.get("_cancel")+ rid = body.get("_reqid")if cancel is not None and cancel.is_set(): # the client left while the job was queued: no prefill, no decode+ reqlog.log("job_skipped", req=rid, queued_s=round(time.perf_counter() - body.get("_queued_at", time.perf_counter()), 3))out.put_nowait(None)queue.task_done()continuestore = getattr(engine, "slot_store", None)processing += 1 # admitted: counted from the dequeue, incl. lock and slot restore+ started = time.perf_counter()+ first_token = False # flipped once, so the log gets exactly one job_first_token linetry:async with admit(body.get("_cache_salt")):running += 1+ track(rid, "prefill", prompt_tokens=body.get("_prompt_tokens"),+ images=len(body.get("_images") or ()))+ reqlog.log("job_start", req=rid, wait_s=round(started - body.get("_queued_at", started), 3),+ prompt_tokens=body.get("_prompt_tokens"), images=len(body.get("_images") or ()),+ messages=body.get("_messages"), sessions=sessions, processing=processing,+ running=running)if store is not None:store.busy = Trueif sessions == 1:@@ -999,10 +1113,15 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:body["_prompt"],max_tokens=token_limit(body), temperature=body.get("temperature", 0.0),top_p=body.get("top_p", 1.0), stop=body.get("_stop", []),- cancel=body.get("_cancel"), **({"images": body["_images"]} if body.get("_images") else {}),+ cancel=body.get("_cancel"), img_stats=body.get("_img_stats"),+ **({"images": body["_images"]} if body.get("_images") else {}),**({"prompt_ids": body["_prompt_ids"]} if body.get("_prompt_ids") is not None else {}),**({"ignore_eos": True} if body.get("_ignore_eos") else {}),**({"stats": request_stats} if sessions > 1 else {})):+ if not first_token:+ first_token = True+ track(rid, "decode")+ reqlog.log("job_first_token", req=rid, elapsed_s=round(time.perf_counter() - started, 3))out.put_nowait(delta)finally:running -= 1@@ -1012,8 +1131,11 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:request_stats.update(getattr(engine, "last_stats", None) or {})if request_stats:observe(request_stats, body.get("_prompt_tokens") or int(request_stats.get("prompt_tokens", 0)))+ log_job_done(rid, body, request_stats, started)out.put_nowait(None)except Exception as exc:+ reqlog.log("job_error", req=rid, error=sanitize(exc),+ elapsed_s=round(time.perf_counter() - started, 3))out.put_nowait(exc)finally:processing -= 1@@ -1021,13 +1143,33 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:store.busy = Falsequeue.task_done()+ def log_job_done(rid: str | None, body: dict[str, Any], st: dict[str, Any], started: float) -> None:+ """One line per finished job: what the prompt cache did (cache_n vs prompt tokens) and how long each+ phase took. This is the line that turns 'the client saw nothing for 290 s' into a number."""+ prompt_tokens = int(st.get("prompt_tokens") or body.get("_prompt_tokens") or 0)+ cache_n = int(st.get("cached_tokens") or 0)+ reqlog.log("job_done", req=rid, elapsed_s=round(time.perf_counter() - started, 3),+ prompt_tokens=prompt_tokens, cache_n=cache_n,+ cache_pct=round(100.0 * cache_n / prompt_tokens, 1) if prompt_tokens else 0.0,+ new_tokens=int(st.get("new_tokens") or 0),+ prefill_s=round(float(st.get("time_prefill") or 0.0), 3),+ decode_s=round(float(st.get("time_generate") or 0.0), 3))+ if body.get("_img_stats"):+ reqlog.log("img_cache", req=rid, **body["_img_stats"])+async def start(_: web.Application) -> None:app["worker_tasks"] = [asyncio.create_task(worker()) for _ in range(sessions)]app["worker_task"] = app["worker_tasks"][0]+ if reqlog.enabled and reqlog.heartbeat_s > 0:+ background["heartbeat"] = asyncio.create_task(heartbeat())async def close(app_: web.Application) -> None:for t in app_["worker_tasks"]:t.cancel()+ beat = background.pop("heartbeat", None)+ if beat is not None:+ beat.cancel()+ reqlog.close()async def drain(request: web.Request, cancel: asyncio.Event, out: asyncio.Queue) -> AsyncIterator[str]:"""Items the worker produced for one request. Nothing is written to the client while a job is@@ -1050,6 +1192,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:def client_left(cancel: asyncio.Event, path: str) -> web.Response:cancel.set()+ reqlog.log("client_left", req=reqid(), path=path, stage="waiting")print(f"serve: client left {path}, job cancelled", file=sys.stderr, flush=True)return web.Response(status=499)@@ -1095,7 +1238,15 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:out: asyncio.Queue = asyncio.Queue()request_stats: dict[str, Any] = {}cancel = body["_cancel"] = asyncio.Event()+ body["_reqid"] = reqid()+ body["_messages"] = len(body["messages"])+ body["_img_stats"] = {} if images else None+ body["_queued_at"] = time.perf_counter()+ ahead = queue.qsize() # requests already waiting when this one arrivedawait queue.put((body, out, request_stats))+ track(body["_reqid"], "queued", prompt_tokens=prompt_tokens)+ reqlog.log("req_queued", req=body["_reqid"], path="/v1/chat/completions", queued_ahead=ahead,+ prompt_tokens=prompt_tokens, messages=body["_messages"], images=len(images), stream=bool(body.get("stream")))prefix = "<think>" if opens_thinking(prompt) else ""def deltas() -> AsyncIterator[str]:@@ -1125,10 +1276,13 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:if body.get("stream", False):response = web.StreamResponse(headers={"Content-Type": "text/event-stream", "Cache-Control": "no-cache"})await response.prepare(request)+ track(body["_reqid"], "stream", prompt_tokens=prompt_tokens)+ reqlog.log("sse_headers", req=body["_reqid"], path="/v1/chat/completions")# Reasoning and prose stream as they decode. Tool calls are parsed only from complete# XML, so everything from <tool_call> on is held and sent once at the end.text, done, mode = prefix, len(prefix), "reasoning" if prefix else "content"hold = max([len("</think>"), len(TOOL_OPEN)] + [len(x) for x in body["_stop"]]) - 1+ visible: list[float] = [] # set at the first frame with text in it: the client's first sign of lifeasync def flush(final: bool) -> None:nonlocal done, mode@@ -1138,6 +1292,9 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:end = min(hits)[0] if hits else (len(text) if final else max(done, len(text) - hold))piece = stop_text(text[done:end], body["_stop"])[0]if piece:+ if not visible:+ visible.append(time.perf_counter())+ reqlog.log("sse_first_content", req=body["_reqid"], first_s=round(visible[0] - body["_queued_at"], 3))key = "reasoning_content" if mode == "reasoning" else "content"await response.write(sse(event({key: piece})))done = end@@ -1162,6 +1319,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:{"usage": usage(text[len(prefix):]), "timings": timings(text)}))await response.write(b"data: [DONE]\n\n")await response.write_eof()+ reqlog.log("sse_done", req=body["_reqid"], out_tokens=int(request_stats.get("new_tokens") or 0))except ConnectionResetError:client_left(cancel, "stream") # client left: nothing to sendreturn response@@ -1170,6 +1328,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:raiseexcept Exception as exc: # noqa: BLE001cancel.set()+ reqlog.log("stream_error", req=body["_reqid"], error=sanitize(exc))# Fail inside the stream, but still end it the OpenAI way: clients such as OpenCode report# "stream ended without finish_reason" and retry when the connection just drops.try:@@ -1351,7 +1510,13 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:out: asyncio.Queue = asyncio.Queue()request_stats: dict[str, Any] = {}cancel = job["_cancel"] = asyncio.Event()+ job["_reqid"] = reqid()+ job["_queued_at"] = time.perf_counter()+ ahead = queue.qsize()await queue.put((job, out, request_stats))+ track(job["_reqid"], "queued", prompt_tokens=prompt_tokens)+ reqlog.log("req_queued", req=job["_reqid"], path="/v1/completions", queued_ahead=ahead,+ prompt_tokens=prompt_tokens, images=0, stream=bool(body.get("stream")))def chunk(text: str, finish: str | None) -> dict[str, Any]:return {"id": request_id, "object": "text_completion", "created": created, "model": model_id,@@ -1367,6 +1532,8 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:if body.get("stream", False):response = web.StreamResponse(headers={"Content-Type": "text/event-stream", "Cache-Control": "no-cache"})await response.prepare(request)+ track(job["_reqid"], "stream", prompt_tokens=prompt_tokens)+ reqlog.log("sse_headers", req=job["_reqid"], path="/v1/completions")try:text, sent, stopped = "", 0, Noneasync for delta in drain(request, cancel, out):@@ -1378,6 +1545,9 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:breaksafe = max(sent, len(text) - hold)if safe > sent:+ if not sent:+ reqlog.log("sse_first_content", req=job["_reqid"],+ first_s=round(time.perf_counter() - job["_queued_at"], 3))await response.write(sse(chunk(text[sent:safe], None)))sent = safeif len(text) > sent:@@ -1386,6 +1556,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:await response.write(sse(chunk("", reason) | {"usage": usage}))await response.write(b"data: [DONE]\n\n")await response.write_eof()+ reqlog.log("sse_done", req=job["_reqid"], out_tokens=int(request_stats.get("new_tokens") or 0))except ConnectionResetError:client_left(cancel, "stream")except asyncio.CancelledError:@@ -1393,6 +1564,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:raiseexcept Exception as exc: # noqa: BLE001cancel.set()+ reqlog.log("stream_error", req=job["_reqid"], error=sanitize(exc))try:await response.write(sse({"error": {"message": f"{type(exc).__name__}: {exc}"}}))await response.write_eof()@@ -1459,10 +1631,10 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:app.router.add_get("/health", health)app.router.add_get("/v1/models", models)app.router.add_get("/metrics", metrics_view)- app.router.add_post("/v1/chat/completions", completions)+ app.router.add_post("/v1/chat/completions", logged(completions))app.router.add_post("/apply-template", apply_template)app.router.add_post("/tokenize", tokenize)- app.router.add_post("/v1/completions", v1_completions)+ app.router.add_post("/v1/completions", logged(v1_completions))app.router.add_post("/completion", completion)app.on_startup.append(start)app.on_cleanup.append(close)@@ -1574,6 +1746,20 @@ def main() -> None:startup_health.abort(f"{type(exc).__name__}: {exc}")raiseapp = create_app(engine, args.model_id, template)+ # Which run this is, in the log itself: ctx, sessions and the image-cache budget are what a later+ # "why was this request slow" question turns on, and they are not visible in the client's request.+ reqlog = app["reqlog"]+ print(f"serve: {reqlog.describe()}", flush=True)+ emb_cache = getattr(engine, "emb_cache", None)+ reqlog.log("serve_start", model=Path(args.model).name, model_id=args.model_id, pid=os.getpid(),+ ctx=args.max_ctx, cache_tokens=getattr(getattr(engine, "cache", None), "max_num_tokens", None),+ sessions=args.sessions, num_draft=args.num_draft, row_budget=getattr(engine, "row_budget", 0),+ max_history=args.max_history or max(args.num_draft, 1), vision=bool(engine.supports_vision),+ conv_gemm=os.environ.get("EXL3_CONV_GEMM"), dense_tune=os.environ.get("EXL3_DENSE_GEMM_TUNE"),+ moe_fused=os.environ.get("EXL3_MOE_FUSED", "0"),+ image_cache_mb=round(emb_cache.max_bytes / 2 ** 20, 1) if emb_cache is not None else None,+ image_cache_items=getattr(emb_cache, "max_items", None),+ heartbeat_s=reqlog.heartbeat_s)sock = startup_health.finish() # the early listener's open socket: no refused connectionif sock is not None:web.run_app(app, sock=sock)diff --git a/tools/glm/serve_reqlog.py b/tools/glm/serve_reqlog.pynew file mode 120000index 0000000..7a3e5c1--- /dev/null+++ b/tools/glm/serve_reqlog.py@@ -0,0 +1 @@+../strix_halo/serve_reqlog.py\ No newline at end of filediff --git a/tools/glm/test_serve.py b/tools/glm/test_serve.pyindex 7e8cb17..58510b3 100644--- a/tools/glm/test_serve.py+++ b/tools/glm/test_serve.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport asyncioimport json+import osimport sysimport unittestfrom pathlib import Path@@ -966,5 +967,242 @@ class VllmCompatTests(unittest.TestCase):serve.template_kwargs({"chat_template_kwargs": "x"})+class RequestLogTests(unittest.TestCase):+ """KYOJIN_REQLOG: off unless asked for; when on, one line per lifecycle event, numbers and names only."""+ template = ServeTests.template++ def setUp(self):+ import tempfile+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.log_path = Path(self.tmp.name) / "requests.log"+ for key in ("KYOJIN_REQLOG", "KYOJIN_REQLOG_HEARTBEAT_S"):+ os.environ.pop(key, None)+ self.addCleanup(os.environ.pop, key, None)++ def lines(self) -> list[str]:+ return self.log_path.read_text(encoding="utf-8").splitlines() if self.log_path.exists() else []++ def events(self) -> list[tuple[str, dict]]:+ """(event name, fields) per line; the timestamp is field 0 and the event name field 1."""+ out = []+ for line in self.lines():+ parts = line.split(" ")+ fields = {}+ for item in parts[2:]:+ key, _, value = item.partition("=")+ fields[key] = value.strip('"')+ out.append((parts[1], fields))+ return out++ def names(self) -> list[str]:+ return [name for name, _ in self.events()]++ def chat(self, body: dict, **kw) -> int:+ from aiohttp.test_utils import TestClient, TestServer++ async def check():+ client = TestClient(TestServer(serve.create_app(FakeEngine("hello"), "m", self.template)))+ await client.start_server()+ response = await client.post("/v1/chat/completions", json=body, **kw)+ await response.read()+ status = response.status+ await client.close()+ return status++ return run(check())++ def test_off_by_default_and_a_request_writes_nothing(self):+ from serve_reqlog import ReqLog+ log = ReqLog.from_env()+ self.assertFalse(log.enabled)+ self.assertIsNone(log.path)+ self.assertIn("request log off", log.describe())+ log.log("req_start", req="r1") # disabled: a no-op, never an error+ self.assertEqual(log.lines(), [])++ from aiohttp.test_utils import TestClient, TestServer++ async def check():+ app = serve.create_app(FakeEngine("hello"), "m", self.template)+ self.assertFalse(app["reqlog"].enabled)+ client = TestClient(TestServer(app))+ await client.start_server()+ response = await client.post("/v1/chat/completions", json={+ "model": "m", "messages": [{"role": "user", "content": "hi"}]})+ status = response.status+ await response.read()+ await client.close()+ return status++ self.assertEqual(run(check()), 200)+ self.assertFalse(self.log_path.exists()) # nothing is created, nothing is written+ self.assertFalse(list(Path(self.tmp.name).iterdir()))++ def test_lifecycle_lines_share_one_id_and_never_hold_request_text(self):+ os.environ["KYOJIN_REQLOG"] = str(self.log_path)+ secret, reply = "PROMPT-SECRET-7f3a", "REPLY-SECRET-9b1c"+ engine = FakeEngine(reply)+ from aiohttp.test_utils import TestClient, TestServer++ async def check():+ app = serve.create_app(engine, "m", self.template)+ self.assertTrue(app["reqlog"].enabled)+ client = TestClient(TestServer(app))+ await client.start_server()+ response = await client.post("/v1/chat/completions", json={+ "model": "m", "messages": [{"role": "user", "content": secret}]})+ body = await response.json()+ await client.close()+ return body++ body = run(check())+ self.assertEqual(body["choices"][0]["message"]["content"], reply)+ events = dict(self.events())+ for want in ("req_start", "req_queued", "job_start", "job_first_token", "job_done", "req_done"):+ self.assertIn(want, events)+ ids = {fields["req"] for name, fields in self.events() if "req" in fields}+ self.assertEqual(len(ids), 1) # every line of the request carries the same id+ self.assertEqual(events["req_queued"]["queued_ahead"], "0")+ self.assertEqual(events["job_done"]["cache_n"], "8") # the engine's own cached_tokens+ self.assertEqual(events["job_done"]["cache_pct"], "40")+ self.assertIn(secret, " ".join(engine.prompts)) # the prompt really did carry the secret+ blob = "\n".join(self.lines())+ self.assertNotIn(secret, blob)+ self.assertNotIn(reply, blob)++ def test_stream_headers_first_content_and_done(self):+ os.environ["KYOJIN_REQLOG"] = str(self.log_path)+ from aiohttp.test_utils import TestClient, TestServer++ async def check():+ client = TestClient(TestServer(serve.create_app(FakeEngine("hello"), "m", self.template)))+ await client.start_server()+ response = await client.post("/v1/chat/completions", json={+ "model": "m", "stream": True, "messages": [{"role": "user", "content": "hi"}]})+ await response.read()+ await client.close()++ run(check())+ names = self.names()+ for want in ("sse_headers", "sse_first_content", "sse_done", "req_done"):+ self.assertIn(want, names)+ self.assertLess(names.index("sse_headers"), names.index("sse_first_content"))+ self.assertLess(names.index("sse_first_content"), names.index("sse_done"))++ def test_refusals_are_logged_without_quoting_the_body(self):+ os.environ["KYOJIN_REQLOG"] = str(self.log_path)+ from aiohttp.test_utils import TestClient, TestServer++ async def check():+ client = TestClient(TestServer(serve.create_app(FakeEngine("hello"), "m", self.template)))+ await client.start_server()+ bad = await client.post("/v1/chat/completions", json={"model": "m"}) # no messages: 400+ broken = await client.post("/v1/chat/completions", data=b'{"model": "m", ',+ headers={"Content-Type": "application/json"}) # malformed JSON: 400+ await client.close()+ return bad.status, broken.status++ self.assertEqual(run(check()), (400, 400))+ refused = [fields for name, fields in self.events() if name == "req_refused"]+ self.assertEqual(len(refused), 2)+ self.assertEqual({f["status"] for f in refused}, {"400"})+ reasons = " ".join(f.get("reason", "") for f in refused)+ self.assertIn("JSONDecodeError(line=1", reasons) # reduced to line/column, not the body text+ self.assertNotIn("model", reasons)++ def test_image_request_logs_cache_hits_misses_and_budget(self):+ os.environ["KYOJIN_REQLOG"] = str(self.log_path)+ import base64+ import io+ from PIL import Image+ from aiohttp.test_utils import TestClient, TestServer+ tpl = self.template.replace("{{ m.content }}", "{% if m.content is string %}{{ m.content }}{% else %}{% for p in m.content %}{% if p.type == 'text' %}{{ p.text }}{% else %}" + serve.IMAGE_TRIPLE + "{% endif %}{% endfor %}{% endif %}")+ eng, _ = ImageEmbeddingReuseTests().make_engine()++ class VisionEngine(FakeEngine):+ supports_vision = True++ def image_tokens(self, image):+ return 3++ async def generate(self, prompt, images=None, img_stats=None, **kw):+ if images:+ serve.ResidentEngine._embed(eng, images, img_stats)+ async for piece in FakeEngine.generate(self, prompt, **kw):+ yield piece++ def uri(color):+ buf = io.BytesIO()+ Image.new("RGB", (8, 8), color).save(buf, "PNG")+ return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()++ body = {"model": "m", "messages": [{"role": "user", "content": [+ {"type": "text", "text": "look"}, {"type": "image_url", "image_url": {"url": uri((255, 0, 0))}},+ {"type": "image_url", "image_url": {"url": uri((0, 0, 255))}}]}]}++ async def check():+ client = TestClient(TestServer(serve.create_app(VisionEngine("hello"), "m", tpl)))+ await client.start_server()+ for _ in range(2): # second send: both pictures are held+ response = await client.post("/v1/chat/completions", json=body)+ await response.read()+ await client.close()++ run(check())+ cache = [fields for name, fields in self.events() if name == "img_cache"]+ self.assertEqual(len(cache), 2)+ self.assertEqual((cache[0]["imgs"], cache[0]["hits"], cache[0]["misses"]), ("2", "0", "2"))+ self.assertEqual(cache[0]["first_missing"], "0") # the prefix can only match from the start+ self.assertEqual((cache[0]["entries"], cache[0]["evicted"]), ("2", "0"))+ self.assertEqual(cache[0]["budget_mb"], "1024")+ self.assertEqual(cache[0]["item_cap"], "32")+ self.assertEqual((cache[1]["hits"], cache[1]["misses"]), ("2", "0"))+ self.assertNotIn("first_missing", cache[1]) # a full hit has no gap+ self.assertNotIn("data:image", "\n".join(self.lines())) # the image URL is never written++ def test_heartbeat_while_a_job_runs(self):+ os.environ["KYOJIN_REQLOG"] = str(self.log_path)+ os.environ["KYOJIN_REQLOG_HEARTBEAT_S"] = "0.05"+ from aiohttp.test_utils import TestClient, TestServer++ class Slow(FakeEngine):+ async def generate(self, prompt, **kwargs):+ await asyncio.sleep(0.3)+ async for piece in FakeEngine.generate(self, prompt, **kwargs):+ yield piece++ async def check():+ client = TestClient(TestServer(serve.create_app(Slow("hello"), "m", self.template)))+ await client.start_server()+ response = await client.post("/v1/chat/completions", json={+ "model": "m", "messages": [{"role": "user", "content": "hi"}]})+ await response.read()+ await client.close()++ run(check())+ alive = [fields for name, fields in self.events() if name == "alive"]+ self.assertTrue(alive, "no heartbeat lines")+ self.assertTrue(all("elapsed_s" in f and "phase" in f for f in alive))+ self.assertTrue({f["phase"] for f in alive} <= {"parse", "queued", "prefill", "decode", "stream"})++ def test_v1_completions_is_logged_too(self):+ os.environ["KYOJIN_REQLOG"] = str(self.log_path)+ from aiohttp.test_utils import TestClient, TestServer++ async def check():+ client = TestClient(TestServer(serve.create_app(FakeEngine("hello"), "m", self.template)))+ await client.start_server()+ response = await client.post("/v1/completions", json={"model": "m", "prompt": "hi", "max_tokens": 4})+ await response.read()+ await client.close()+ return response.status++ self.assertEqual(run(check()), 200)+ queued = [fields for name, fields in self.events() if name == "req_queued"]+ self.assertEqual([f["path"] for f in queued], ["/v1/completions"])+ self.assertIn("job_done", self.names())++if __name__ == "__main__":unittest.main()diff --git a/tools/strix_halo/serve_reqlog.py b/tools/strix_halo/serve_reqlog.pynew file mode 100644index 0000000..cfcc5d1--- /dev/null+++ b/tools/strix_halo/serve_reqlog.py@@ -0,0 +1,134 @@+#!/usr/bin/env python3+"""Per-request state log for the Kyojin servers: timings and counters only, never text.++A request that is refused, queued or prefilling produces **no client-visible output**, so a report of+"the server went silent" cannot be lined up with what the server was doing. This writes one line per+lifecycle event, plus a heartbeat while a job is queued or running, so the two timelines can be+compared afterwards.++**Off unless asked for.** With KYOJIN_REQLOG unset (or 0/off/none/no/false/empty) nothing is opened and+every call is a no-op, so a default deployment behaves exactly as before. The server prints one line at+start-up either way, so the switch stays discoverable when a request does go silent.++ KYOJIN_REQLOG=~/cache/kyojin/requests.log # a path, or 1/on/yes for the default path below+ KYOJIN_REQLOG_HEARTBEAT_S=10 # seconds between 'alive' lines while a job runs++Privacy: nothing derived from the request is written except numbers — token counts, message/image+counts, durations, byte counts, HTTP statuses, an opaque request id, a server tag and event names.+Prompt text, completion text, tool arguments and image paths from the body are never logged. Of the+server's own error text, only the exception type is logged plus a truncated message; JSON parse errors+are reduced to line/column because their message can quote the request body.++Reading it back: `grep req_refused`, `grep img_cache`, `grep -E 'alive|job_first_token'`, or follow one+request with `grep <req id>`. Every line starts with a local ISO timestamp with milliseconds, then the+event name, then `key=value` fields; every line of one request carries the same `req=` id.+"""+from __future__ import annotations++import json+import os+import pathlib+import sys+import threading+import time+from typing import Any++DEFAULT_PATH = "~/.cache/kyojin/requests.log"+FALSE = {"0", "off", "none", "no", "false", ""}+TRUE = {"1", "on", "yes", "true"}+++def sanitize(exc: BaseException) -> str:+ """Exception type and a short message, safe to log (no request-body snippets)."""+ if isinstance(exc, json.JSONDecodeError):+ return f"JSONDecodeError(line={exc.lineno} col={exc.colno})"+ msg = " ".join(str(exc).split())[:160]+ return f"{type(exc).__name__}: {msg}" if msg else type(exc).__name__+++def _fmt(value: Any) -> str:+ if isinstance(value, bool):+ return "1" if value else "0"+ if isinstance(value, float):+ # Whole numbers read as integers (cache_pct=40, budget_mb=1024), the rest keep milliseconds.+ return str(int(value)) if value.is_integer() else f"{value:.3f}"+ text = str(value)+ return f'"{text}"' if (" " in text or "=" in text) else text+++class ReqLog:+ """Append-only event log. Every method is safe to call when logging is disabled or broken."""++ def __init__(self, path: str | None = None, heartbeat_s: float | None = None,+ server: str | None = None) -> None:+ raw = os.environ.get("KYOJIN_REQLOG", "") if path is None else path+ raw = raw.strip()+ self.server = server+ self.enabled = raw.lower() not in FALSE+ if self.enabled and raw.lower() in TRUE:+ raw = DEFAULT_PATH+ self.path: pathlib.Path | None = pathlib.Path(raw).expanduser() if self.enabled else None+ if heartbeat_s is None:+ try:+ heartbeat_s = float(os.environ.get("KYOJIN_REQLOG_HEARTBEAT_S", "10") or 10)+ except ValueError:+ heartbeat_s = 10.0+ self.heartbeat_s = max(0.0, heartbeat_s)+ self._lock = threading.Lock()+ self._fh = None+ if self.enabled and self.path is not None:+ try:+ self.path.parent.mkdir(parents=True, exist_ok=True)+ self._fh = self.path.open("a", encoding="utf-8")+ except OSError as exc:+ print(f"serve: request log off ({type(exc).__name__}: {exc})", file=sys.stderr, flush=True)+ self.enabled, self._fh = False, None++ @classmethod+ def from_env(cls, server: str | None = None) -> "ReqLog":+ return cls(server=server)++ def describe(self) -> str:+ """One start-up line, so an operator can tell whether the log is on without looking for a file."""+ if self._fh is None or self.path is None:+ return "request log off (set KYOJIN_REQLOG=<path> to enable, numbers and event names only)"+ return (f"request log {self.path} (heartbeat {self.heartbeat_s:g} s, "+ f"numbers and event names only, no prompt or reply text)")++ def log(self, event: str, **fields: Any) -> None:+ if self._fh is None:+ return+ try:+ stamp = time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime())+ ms = int((time.time() % 1) * 1000)+ parts = [f"{stamp}.{ms:03d}", event]+ if self.server:+ parts.append(f"srv={self.server}")+ for key, value in fields.items():+ if value is None:+ continue+ parts.append(f"{key}={_fmt(value)}")+ line = " ".join(parts) + "\n"+ with self._lock:+ self._fh.write(line)+ self._fh.flush()+ except Exception: # noqa: BLE001 a logging failure must never touch serving+ pass++ def close(self) -> None:+ with self._lock:+ if self._fh is not None:+ try:+ self._fh.close()+ except OSError:+ pass+ self._fh = None++ def lines(self) -> list[str]:+ """The lines written so far (for tests and for a live tail; never opens a second handle)."""+ if self.path is None or not self.path.exists():+ return []+ with self._lock:+ if self._fh is not None:+ self._fh.flush()+ return self.path.read_text(encoding="utf-8").splitlines()