Skip to content

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.

Servers: one request log for the three of them, with the lifecycle in the shared module

MangetsuC402ab74deb8d
diff --git a/doc/env_vars.md b/doc/env_vars.md
index 0d4a84e..9edb0ef 100644
--- a/doc/env_vars.md
+++ b/doc/env_vars.md
@@ -787,6 +787,14 @@ The file that holds the tuned dense GEMM solution per shape class. Point it at a
skip the autotune; the GLM lane copies `tools/lanes/assets/tune_seed.txt` to the path it sets.
Without it the first GLM launch spends about ten minutes tuning before the port opens.
+#### `MIMO_IMAGE_MAX_PIXELS` (default: `2097152`)
+
+Pixel cap applied to an image the MiMo server preprocesses: the tower sees `min(cap, the pack's own
+limit)`, and the image is resized (aspect kept, multiples of 32) until it fits. The default is 2 097 152
+pixels — 8 192 patches, 2 048 text tokens — because the pack's config would allow 8 388 608 and one tower
+pass at that size needs far more attention memory than is worth it. Raise it for a pack with more
+headroom, lower it to make vision cheaper; raising it past the pack's limit changes nothing.
+
#### `EXL3_MIMO_FP32_MLP_LAYERS` (default: `none`)
Which MiMo layers build their MoE and MLP intermediates in fp32 instead of fp16. Syntax: `47`,
@@ -997,14 +1005,14 @@ The same lane also exports `EXL3_HOST_LEAN`, `EXL3_HOST_CUTS`, `EXL3_LOAD_DEVICE
| variable | default | what it does |
|---|---|---|
-| `KYOJIN_REQLOG` | unset = off | Path of a per-request lifecycle log, or `1`/`on`/`yes` for `~/.cache/kyojin/requests.log` (`0`/`off`/`none`/`no`/`false` disable it). Numbers and event names only, never prompt or reply text; one line per event and a heartbeat (`alive`) while a job is queued, prefilling or decoding. For a streaming reply the heartbeat also carries the **output accounting** (`out_events`, `out_chars`, `last_out_s`) and the request ends with one `sse_summary` line, which is what tells "the client was sent nothing" from "the client showed nothing"; see [tools/glm/SERVE.md](../tools/glm/SERVE.md) for the event table. Shared by the three servers (`tools/strix_halo/serve_reqlog.py`, with `serve_reqlog.py` symlinks in `tools/glm`, `tools/qwen` and `tools/mimo`). |
+| `KYOJIN_REQLOG` | unset = off | Path of a per-request lifecycle log, or `1`/`on`/`yes` for `~/.cache/kyojin/requests.log` (`0`/`off`/`none`/`no`/`false` disable it). Numbers and event names only, never prompt or reply text; one line per event and a heartbeat (`alive`) while a job is queued, prefilling or decoding. For a streaming reply the heartbeat also carries the **output accounting** (`out_events`, `out_chars`, `last_out_s`) and the request ends with one `sse_summary` line, which is what tells "the client was sent nothing" from "the client showed nothing"; the event tables, the shared/GLM-only split and how to read it are in [logging.md](logging.md). Served by all three servers from one module (`tools/strix_halo/serve_reqlog.py`, with `serve_reqlog.py` symlinks in `tools/glm`, `tools/qwen` and `tools/mimo`): the whole request lifecycle — the request table, the id on every line, the heartbeat and the route wrapper (`Lifecycle`) — is that module's, so the three servers emit one vocabulary, which `tools/test_serve_logging.py` checks against all three at once; each server's document only points back here and to [logging.md](logging.md). |
| `KYOJIN_REQLOG_HEARTBEAT_S` | `10` | Seconds between `alive` lines; `0` disables the heartbeat (the log stays on). |
#### SSE keep-alive (all three servers)
| variable | default | what it does |
|---|---|---|
-| `KYOJIN_SSE_PING_S` | `0` = off | Seconds a stream may go without a data event before the server writes one SSE comment line (`: waiting <n> s`), which keeps a client that only watches its socket from treating a long prefill — or a long decode nothing is being written for — as a dead server. The comment counts from the request's arrival, comes once per interval and only after that much silence: a stream that is producing text never gets one, and one that stops gets them again (a reply holding a `<tool_call>` back until its XML closes is decoded for minutes while the client hears nothing). The `role` chunk a client gets immediately does not count as output, so the whole prefill is covered. Shared by the three servers (`tools/strix_halo/serve_ping.py`, with `serve_ping.py` symlinks in `tools/glm`, `tools/qwen` and `tools/mimo`), read per request, reported on one start-up line. With the default nothing is written at all. Worth setting on any server that sees long prompts — an image conversation can prefill for minutes — together with a client-side timeout that is long enough; each comment is also an `sse_ping` line in the request log (`KYOJIN_REQLOG`) when that is on. |
+| `KYOJIN_SSE_PING_S` | `0` = off | Seconds a stream may go without a data event before the server writes one SSE comment line (`: waiting <n> s`), which keeps a client that only watches its socket from treating a long prefill — or a long decode nothing is being written for — as a dead server. The comment counts from the request's arrival, comes once per interval and only after that much silence: a stream that is producing text never gets one, and one that stops gets them again (a reply holding a `<tool_call>` back until its XML closes is decoded for minutes while the client hears nothing). The `role` chunk a client gets immediately does not count as output, so the whole prefill is covered. Shared by the three servers (`tools/strix_halo/serve_ping.py`, with `serve_ping.py` symlinks in `tools/glm`, `tools/qwen` and `tools/mimo`), read per request, reported on one start-up line. With the default nothing is written at all. Worth setting on any server that sees long prompts — an image conversation can prefill for minutes — together with a client-side timeout that is long enough; each comment is also an `sse_ping` line in the request log (`KYOJIN_REQLOG`) when that is on and the server's pinger is wired to it (GLM's is). See [logging.md](logging.md). |
#### `KYOJIN_HEALTH_DIR` (default: `~/.cache/kyojin`)
diff --git a/doc/logging.md b/doc/logging.md
new file mode 100644
index 0000000..6789e1b
--- /dev/null
+++ b/doc/logging.md
@@ -0,0 +1,152 @@
+# Request log and stream keep-alive
+
+The three servers write the same request log and answer a silent stream the same way: both are one shared
+implementation, `tools/strix_halo/serve_reqlog.py` (the `Lifecycle` and `StreamStats` classes) and
+`tools/strix_halo/serve_ping.py` (`ServePing`), reached through `serve_reqlog.py` / `serve_ping.py`
+symlinks in `tools/glm`, `tools/qwen` and `tools/mimo`. `tools/test_serve_logging.py` runs the same
+requests against all three and fails if one of them writes an event the others do not, or a field that
+differs, so this document describes one format, not three.
+
+Everything here is **off by default**: a deployment that sets neither switch writes no file and not one
+extra byte on the wire.
+
+## Switches
+
+| 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 (the log itself stays on) |
+| `KYOJIN_SSE_PING_S` | `0` = off | seconds a stream may go without a data event before the server writes one SSE comment line |
+
+Each server prints one line per switch at start-up, so the state is discoverable without looking for a
+file:
+
+```
+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)
+serve: SSE keep-alive: a comment line after 10 s without output (KYOJIN_SSE_PING_S)
+serve: SSE keep-alive off (set KYOJIN_SSE_PING_S=<seconds> to hold a silent stream open)
+```
+
+## Format
+
+Every line is `<local ISO timestamp with milliseconds> <event> srv=<glm|qwen|mimo> key=value ...`.
+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. A field whose value is not known is left out rather
+than written empty (an unknown value is `None` at the call site and the writer skips it), which is why
+the field lists below are what a request *can* report, not what every line of it carries.
+
+## Shared events (all three servers)
+
+In the order a request that goes all the way through produces them:
+
+| event | written when | useful fields |
+|---|---|---|
+| `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` (GLM/Qwen only), `processing`/`running` (whichever the server keeps) |
+| `alive` | every `KYOJIN_REQLOG_HEARTBEAT_S` while tracked | `phase` (`parse`/`queued`/`prefill`/`decode`/`stream`), `elapsed_s`, the in-flight counters, and for a streaming reply **`out_events` / `out_chars` / `last_out_s`** |
+| `job_first_token` | first generated token | `elapsed_s` — when the model first produced anything |
+| `sse_headers` | streaming: the SSE response is open | `path` |
+| `sse_first_content` | streaming: first frame with text | `first_s` since arrival — the gap the client experiences as silence |
+| `sse_ping` | a keep-alive comment went to the client | `n` (which comment of this request), `waited_s` — how long the client had been waiting |
+| `sse_done` | stream closed | `out_tokens` |
+| `sse_summary` | one line when a streaming reply ends (or the client leaves) | `out_events`, `out_chars`, `last_out_s` (since the last *data event*), `comments`, `comment_chars`, `last_comment_s`, `errors`/`error`, `path` |
+| `job_done` | job finished | `prompt_tokens`, `cache_n`, `cache_pct`, `new_tokens`, `prefill_s`, `decode_s`, `elapsed_s` |
+| `req_done` | response returned | `status`, `elapsed_s`, `path` |
+| `client_left` | client hung up first | `path`, `stage` (`handler`/`waiting`/`stream`) |
+| `job_skipped` | job cancelled while still queued | `queued_s` |
+| `job_error` | the job failed in the worker | `error`, `elapsed_s` |
+| `stream_error` | a streaming reply failed mid-stream | `error` |
+| `req_error` | the route raised something else | `error`, `elapsed_s`, `path` |
+
+## GLM-only events
+
+GLM is the server with an image cache and a disk tier, so it is the one with lines that cannot exist
+elsewhere. They go through the log's raw `log()` call, and no other server needs to match them:
+
+| event | written when | useful fields |
+|---|---|---|
+| `serve_start` | once, when the server is ready | `model`, `model_id`, `pid`, `ctx`, `cache_tokens`, `sessions`, `num_draft`, `row_budget`, `max_history`, `vision`, `conv_gemm`, `dense_tune`, `moe_fused`, `image_cache_mb`, `image_cache_items`, `image_cache_format`, `image_cache_policy`, `image_cache_dir`, `image_cache_dir_cap_mb`, `image_cache_dir_lock_s`, `heartbeat_s`, `sse_ping_s` |
+| `img_cache` | an image request, after `job_done` | `imgs`, `hits`, `misses`, `first_missing`, `entries`, `mb`, `budget_mb`, `item_cap`, `evicted` |
+| `img_disk` | the same request, when `--image-cache-dir` is set | `files`, `mb`, `cap_mb`, `locked`, `loaded`, `stored`, `dropped`, `skipped`, `written_bytes`, `written_mb`, `skipped_mb`, `errors` |
+
+`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. See
+[tools/glm/SERVE.md](../tools/glm/SERVE.md) for what the cache does and
+[env_vars.md](env_vars.md) for its switches.
+
+## Reading it: output accounting
+
+**`out_events` is the number that answers "was the server actually writing?"** A client that reports
+silence for ten minutes while `out_events` climbs means the bytes were on the wire and the client did not
+show them; a flat `out_events` with a rising `last_out_s` means the server had nothing to send, and the
+`phase` then says what it was doing instead (`prefill` = still processing the prompt, `decode` =
+generating into something not sent yet, typically a tool call held until its XML closes). A keep-alive
+comment does not count as output, so a stream that is only being kept alive still reads as flat.
+
+Measured example of the decode case (a `write_file` call with a 6.8 KB argument, one generation of
+98.7 s): nine comments at 17 s … 98 s, while the heartbeat reads the same numbers throughout —
+`phase=decode out_events=135 out_chars=29397 last_out_s=2.5 → 12.5 → … → 82.5` — because the 2 144 tokens
+of the tool call were held back and the client was sent nothing for 95 s. The closing summary is
+`out_events=138 out_chars=40067 last_out_s=0 comments=9`: the reply arrived in three frames at the end.
+A client that gave up at 90 s of silence would have been aborted there, with the whole generation lost.
+
+Cost when enabled: one `write`+`flush` per event on the event loop, tens of bytes per line; with the log
+off every call is a no-op. For a slow request,
+`grep -E 'alive|job_first_token|job_done' ~/.cache/kyojin/requests.log` shows whether it was waiting in
+the queue, prefilling a prompt the cache could not serve, or decoding.
+
+## The stream keep-alive (`KYOJIN_SSE_PING_S`)
+
+The request log makes a quiet server visible **to you**; this switch makes it visible **to the client**. A
+streaming request is answered with its headers and one empty role chunk, and then nothing at all until the
+prompt is prefilled — hundreds of seconds for a large image conversation — so a client that aborts a
+stream it has not heard from in two minutes gives up on a server that is working, and (the page cache
+being empty for that request) a retry starts the whole prefill again.
+
+With `KYOJIN_SSE_PING_S=<seconds>` set, a stream that has written no data event for that long gets one
+SSE **comment** line, which every event-stream client skips:
+
+```
+: waiting 105 s
+
+```
+
+It counts from the request's arrival, appears once per interval, and covers **every** silence, not only
+the prefill:
+
+* the prefill of a long prompt (the `role` chunk a client gets immediately is not output);
+* the decode of a reply that writes a file — the whole `<tool_call>` is held back until its XML closes,
+ so a 7 KB `content` argument is ~100 s of generation the client never sees. Measured on this box with a
+ `write_file` call: `sse_first_content first_s=1.3`, then nine comments at 16 s … 96 s, while `job_done`
+ reported `new_tokens=2195 prefill_s=1.1 decode_s=99.5`. Before the comments covered decode, agent
+ clients aborted those turns at ~300 s of silence and every retry paid the full prefill again (the page
+ cache of a cancelled request is released).
+
+A stream that is producing text never gets a comment. Default `0` = off: nothing is ever written and a
+stream is byte-for-byte what it was. Each comment is also one `sse_ping` line in the request log, so the
+two timelines can still be lined up. It does not replace a client-side timeout — it keeps a client that
+tolerates comments from giving up, and tells you the server was alive if one does anyway.
+
+## Privacy
+
+Nothing derived from the request is written except numbers: token counts, message and 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.
+
+## Implementation, in one paragraph
+
+`Lifecycle` (in `tools/strix_halo/serve_reqlog.py`) owns the request table, the context variable that
+names the request, the `alive` heartbeat, the route wrapper that stamps `req=` on every line, the summary
+line and one method per event above; `StreamStats`/`StreamWriter` count what a streaming reply actually
+wrote; `ReqLog` opens the file, formats the lines and skips unknown fields. `ServePing` (in
+`serve_ping.py`) owns the comment timing and asks `StreamStats` whether the request has been silent. A
+server's own part is **where each phase begins** — its worker picks a job up, its route opens a stream —
+and the counters it keeps; an event or a field a server does not have is simply not passed, so nothing
+anywhere branches on which server is running.
diff --git a/tools/glm/SERVE.md b/tools/glm/SERVE.md
index fff0773..f7a6feb 100644
--- a/tools/glm/SERVE.md
+++ b/tools/glm/SERVE.md
@@ -219,102 +219,18 @@ parse, 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`, `image_cache_format`, `sse_ping_s` |
-| `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`, and for a streaming reply **`out_events` / `out_chars` / `last_out_s`** — what the client has been sent so far, and how long since the last *data event* (a keep-alive comment does not count) |
-| `sse_summary` | one line when a streaming reply ends (or the client leaves) | `out_events`, `out_chars`, `last_out_s` (since the last data event), `comments` (keep-alive comments, counted apart from data events), `comment_chars`, `last_comment_s`, `errors` |
-| `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 |
-| `sse_ping` | a keep-alive comment went to the client (only with `KYOJIN_SSE_PING_S`) | `n` (which comment of this request), `waited_s` — how long the client had been waiting |
-| `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` |
-| `img_disk` | the same request, when `--image-cache-dir` is set | `files`, `mb`, `cap_mb`, `locked`, `loaded`, `stored`, `dropped`, `skipped`, `written_bytes`, `written_mb`, `skipped_mb`, `errors` |
-| `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).
-
-**`out_events` is the number that answers "was the server actually writing?"** A client that reports
-silence for ten minutes while `out_events` climbs means the bytes were on the wire and the client did not
-show them; a flat `out_events` with a rising `last_out_s` means the server had nothing to send, and the
-`phase` then says what it was doing instead (`prefill` = still processing the prompt, `decode` = generating
-into something not sent yet, typically a tool call held until its XML closes). In the 2026-10-15 incident
-the agent aborted at its 600 s ceiling in every combination of those, and only these counters can tell
-them apart afterwards.
-
-Measured example of the decode case (a `write_file` call with a 6.8 KB argument, one generation of
-98.7 s): nine comments at 17 s … 98 s, while the heartbeat reads the same numbers throughout —
-`phase=decode out_events=135 out_chars=29397 last_out_s=2.5 → 12.5 → … → 82.5` — because the 2 144 tokens
-of the tool call were held back and the client was sent nothing for 95 s. The closing summary is
-`out_events=138 out_chars=40067 last_out_s=0 comments=9`: the reply arrived in three frames at the end.
-A client that gave up at 90 s of silence would have been aborted there, with the whole generation lost.
-
-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.
-
-## Diagnostics: keeping a slow stream alive
-
-The request log makes a quiet server visible **to you**; `KYOJIN_SSE_PING_S` makes it visible **to the
-client**. A streaming request is answered with its headers and one empty role chunk, and then nothing at
-all until the prompt is prefilled — hundreds of seconds for a large image conversation — so a client that
-aborts a stream it has not heard from in two minutes gives up on a server that is working, and (the page
-cache being empty for that request) a retry starts the whole prefill again.
-
-With `KYOJIN_SSE_PING_S=<seconds>` set, a stream that has written no data event for that long gets one
-SSE **comment** line, which every event-stream client skips:
-
-```
-: waiting 105 s
-
-```
-
-It counts from the request's arrival, appears once per interval, and covers **every** silence, not only
-the prefill:
-
-* the prefill of a long prompt (the `role` chunk a client gets immediately is not output);
-* the decode of a reply that writes a file — the whole `<tool_call>` is held back until its XML closes,
- so a 7 KB `content` argument is ~100 s of generation the client never sees. Measured on this box with
- a `write_file` call: `sse_first_content first_s=1.3`, then nine comments at 16 s … 96 s, while
- `job_done` reported `new_tokens=2195 prefill_s=1.1 decode_s=99.5`. Before the comments covered
- decode, agent clients aborted those turns at ~300 s of silence and every retry paid the full prefill
- again (the page cache of a cancelled request is released).
-
-A stream that is producing text never gets a comment. All three servers share the module
-(`tools/strix_halo/serve_ping.py`), which is one `await ping.comment(response, started)` before each
-poll. Default `0` = off: nothing is ever written and a stream is byte-for-byte what it was. Each
-comment is also one `sse_ping` line in the request log, so the two timelines can still be lined up. It
-does not replace a client-side timeout — it keeps a client that tolerates comments from giving up, and
-tells you the server was alive if one does anyway.
+The log is shared code and its switches, format, every event, the shared/GLM-only split and how to read
+the output accounting are documented once, in [doc/logging.md](../../doc/logging.md). What belongs to
+this server:
+
+* **its events are the reference vocabulary** — `img_cache`, `img_disk` and `serve_start` exist here
+ because this is the server with an image cache, a disk tier and a start-up record; the other two run
+ the same `Lifecycle` and `tools/test_serve_logging.py` holds all three to the same field lists;
+* the start-up lines an operator sees are `serve: request log …` and `serve: SSE keep-alive …`;
+* **GLM is the only server whose pinger also writes its comments to the log**, so `sse_ping` lines and
+ the `sse_ping_s` field of `serve_start` appear here and not on Qwen or MiMo.
+
+Turn it on with `KYOJIN_REQLOG=<path>` (or `1`); both switches are in [doc/env_vars.md](../../doc/env_vars.md).
## Start-up progress on `/health`
diff --git a/tools/glm/serve.py b/tools/glm/serve.py
index 937dae5..cb29eb1 100644
--- a/tools/glm/serve.py
+++ b/tools/glm/serve.py
@@ -7,7 +7,6 @@ import argparse
import asyncio
import base64
import contextlib
-import contextvars
import functools
import io
import json
@@ -33,7 +32,7 @@ from serve_metrics import Metrics
# 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, StreamWriter, sanitize
+from serve_reqlog import Lifecycle, ReqLog, StreamWriter, refusal_text, sanitize
# serve_ping.py is a symlink to the shared tools/strix_halo/serve_ping.py: an SSE comment line every
# KYOJIN_SSE_PING_S while a stream has nothing to send yet (off by default), so the same silence is
# visible to the client and not only in the log file.
@@ -405,15 +404,6 @@ 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:
@@ -1032,7 +1022,6 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
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)
# SSE keep-alive: off unless KYOJIN_SSE_PING_S names an interval, in which case a stream that has
# nothing to send yet (queued, or prefilling a long prompt) writes a ':' comment line every N
@@ -1040,74 +1029,21 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
ping = ServePing.from_env(reqlog)
app.update(ping=ping)
+ # The lifecycle a request goes through is logged by one shared implementation (tools/strix_halo/
+ # serve_reqlog.py): the request table, the id every line carries, the 'alive' heartbeat and the route
+ # wrapper. This server only says when a phase begins; the events it has and the counters it keeps are
+ # the ones its own call sites pass. `processing`/`running` are this server's two counts.
+ lifecycle = Lifecycle(reqlog, ping=ping,
+ counters=lambda: {"processing": processing, "running": running})
+
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)
+ return lifecycle.reqid()
- # The streaming writer of each in-flight request (nothing for a JSON reply). The heartbeat reads
- # its counters, which is what tells "the client was sent nothing" from "the client showed nothing".
- writers: dict[str, StreamWriter] = {}
+ writers = lifecycle.writers # the streaming writer per in-flight request (the heartbeat reads it)
- async def heartbeat() -> None:
- while True:
- await asyncio.sleep(reqlog.heartbeat_s)
- now = time.perf_counter()
- for rid, st in list(inflight.items()):
- writer = writers.get(rid)
- stats = writer.stats if writer is not None else None
- reqlog.log("alive", req=rid, phase=st.get("phase"), elapsed_s=round(now - st["t0"], 2),
- prompt_tokens=st.get("prompt_tokens"),
- out_events=stats.events if stats else None,
- out_chars=stats.bytes if stats else None,
- last_out_s=round(stats.since_data_s(), 1) if stats else None,
- 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:
- writer = writers.pop(rid, None)
- if writer is not None:
- # One line that says what this request sent: a stalled decode shows a flat
- # out_events with comments, a working stream a rate, a client that could not keep
- # up a growing graph error.
- for event, fields in writer.stats.lines():
- reqlog.log(event, req=rid, path=request.path, **fields)
- inflight.pop(rid, None)
- current_req.reset(token)
- return wrapper
+ def track(rid: str | None, phase: str, **fields: Any) -> None:
+ lifecycle.track(rid, phase, **fields)
def salt_of(body: dict[str, Any]) -> str | None:
try:
@@ -1204,7 +1140,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
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))
+ lifecycle.job_skipped(rid, time.perf_counter() - (body.get("_queued_at") or time.perf_counter()))
out.put_nowait(None)
queue.task_done()
continue
@@ -1215,12 +1151,11 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
try:
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)
+ lifecycle.job_started(rid, started - (body.get("_queued_at") or started),
+ 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 = True
if sessions == 1:
@@ -1237,8 +1172,8 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
**({"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))
+ lifecycle.first_token(rid, started,
+ prompt_tokens=body.get("_prompt_tokens"))
out.put_nowait(delta)
finally:
running -= 1
@@ -1251,8 +1186,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
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))
+ lifecycle.job_error(rid, exc, started)
out.put_nowait(exc)
finally:
processing -= 1
@@ -1265,12 +1199,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
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))
+ lifecycle.job_done(rid, st, started, prompt_tokens=prompt_tokens)
if body.get("_img_stats"):
reqlog.log("img_cache", req=rid, **body["_img_stats"])
@@ -1278,7 +1207,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
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())
+ background["heartbeat"] = asyncio.create_task(lifecycle.heartbeat_forever())
async def close(app_: web.Application) -> None:
for t in app_["worker_tasks"]:
@@ -1323,7 +1252,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")
+ lifecycle.client_left(path)
print(f"serve: client left {path}, job cancelled", file=sys.stderr, flush=True)
return web.Response(status=499)
@@ -1375,9 +1304,9 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
body["_queued_at"] = time.perf_counter()
ahead = queue.qsize() # requests already waiting when this one arrived
await 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")))
+ lifecycle.queued(body["_reqid"], "/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 ""
# This request's SSE keep-alive, and the moment its wait started: every comment counts from
# there, which is what the client has actually been waiting for. Off (the default) this costs one
@@ -1413,9 +1342,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)
- writer = writers[body["_reqid"]] = StreamWriter(response) # what the heartbeat reports on
- track(body["_reqid"], "stream", prompt_tokens=prompt_tokens)
- reqlog.log("sse_headers", req=body["_reqid"], path="/v1/chat/completions")
+ writer = lifecycle.stream_started(body["_reqid"], "/v1/chat/completions", response,
+ prompt_tokens=prompt_tokens)
# 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"
@@ -1432,7 +1360,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
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))
+ lifecycle.first_content(body["_reqid"], body["_queued_at"])
key = "reasoning_content" if mode == "reasoning" else "content"
await writer.write(sse(event({key: piece})))
ping.note_output() # the client has text: comments wait for the next silence
@@ -1459,7 +1387,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
{"usage": usage(text[len(prefix):]), "timings": timings(text)}))
await writer.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))
+ lifecycle.stream_done(body["_reqid"], int(request_stats.get("new_tokens") or 0))
except ConnectionResetError:
client_left(cancel, "stream") # client left: nothing to send
return response
@@ -1468,7 +1396,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
raise
except Exception as exc: # noqa: BLE001
cancel.set()
- reqlog.log("stream_error", req=body["_reqid"], error=sanitize(exc))
+ lifecycle.stream_error(body["_reqid"], 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:
@@ -1654,9 +1582,8 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
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")))
+ lifecycle.queued(job["_reqid"], "/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,
@@ -1672,9 +1599,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)
- writer = writers[job["_reqid"]] = StreamWriter(response) # what the heartbeat reports on
- track(job["_reqid"], "stream", prompt_tokens=prompt_tokens)
- reqlog.log("sse_headers", req=job["_reqid"], path="/v1/completions")
+ writer = lifecycle.stream_started(job["_reqid"], "/v1/completions", response,
+ prompt_tokens=prompt_tokens)
# Same keep-alive as /v1/chat/completions, but this route writes no role chunk: the first
# thing the client sees is text, so a comment covers the whole wait before it.
ping = app["ping"].per_request()
@@ -1691,8 +1617,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
safe = 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))
+ lifecycle.first_content(job["_reqid"], job["_queued_at"])
await writer.write(sse(chunk(text[sent:safe], None)))
ping.note_output()
sent = safe
@@ -1702,7 +1627,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
await writer.write(sse(chunk("", reason) | {"usage": usage}))
await writer.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))
+ lifecycle.stream_done(job["_reqid"], int(request_stats.get("new_tokens") or 0))
except ConnectionResetError:
client_left(cancel, "stream")
except asyncio.CancelledError:
@@ -1710,7 +1635,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
raise
except Exception as exc: # noqa: BLE001
cancel.set()
- reqlog.log("stream_error", req=job["_reqid"], error=sanitize(exc))
+ lifecycle.stream_error(job["_reqid"], exc)
try:
await writer.write(sse({"error": {"message": f"{type(exc).__name__}: {exc}"}}))
await response.write_eof()
@@ -1777,10 +1702,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", logged(completions))
+ app.router.add_post("/v1/chat/completions", lifecycle.wrapped(completions))
app.router.add_post("/apply-template", apply_template)
app.router.add_post("/tokenize", tokenize)
- app.router.add_post("/v1/completions", logged(v1_completions))
+ app.router.add_post("/v1/completions", lifecycle.wrapped(v1_completions))
app.router.add_post("/completion", completion)
app.on_startup.append(start)
app.on_cleanup.append(close)
diff --git a/tools/mimo/SERVE.md b/tools/mimo/SERVE.md
index a5c9893..a294efe 100644
--- a/tools/mimo/SERVE.md
+++ b/tools/mimo/SERVE.md
@@ -37,7 +37,8 @@ Model id in requests: `MiMo-2.6-EXL3`.
The server loads the vision tower from `<model>/vision/vision.safetensors` at start (1.4 GiB GPU memory, about 2 s).
The file is in the hub pack; a pack downloaded before it was added needs `hf download` again. An image goes in a user
message as an OpenAI `image_url` part; the URL is a `data:` URI or a local file path (the server does not fetch remote
-URLs). One image takes 24 to about 1,100 tokens depending on its size (capped at 2,097,152 pixels, `MIMO_IMAGE_MAX_PIXELS`). `--no-vision`
+URLs). One image takes 24 to about 1,100 tokens depending on its size (capped at 2 097 152 pixels by
+`MIMO_IMAGE_MAX_PIXELS`, [doc/env_vars.md](../../doc/env_vars.md)). `--no-vision`
skips the tower; an image request then gets HTTP 400, also when the file is missing. Audio and video are not supported.
`--ctx 0` (default) takes the max context from the model config, following `text_config` when the
@@ -50,11 +51,6 @@ top-level config does not carry `max_position_embeddings` — the GLM fix.
`stop` (string or list), `temperature`, `top_p`, `max_completion_tokens` or `max_tokens` (the first wins; default: all the free context, thinking included; `--default-max-tokens` sets a limit). A reply cut by the limit reports `finish_reason: "length"`. An engine failure mid-stream ends with an `error` frame, `finish_reason: "error"` and `[DONE]`. Tool calls are emitted only
once the XML block closes, so a client never sees half a JSON payload.
- `GET /v1/models` — one entry, `MiMo-2.6-EXL3`.
-- A turn is silent on the wire for as long as the server has nothing to send (headers and one empty role
- chunk, then nothing until text is ready — including a decode that is holding a `<tool_call>` back until
- its XML closes), so `KYOJIN_SSE_PING_S=<seconds>` makes the server write an SSE comment
- (`: waiting <n> s`) after that much silence. Off by default, shared with the other two servers; the
- switch and its start-up line are in [doc/env_vars.md](../../doc/env_vars.md).
- `GET /health` — `{"status","model","generator","spec_gate"}` once ready (load progress while starting: see below); with the gate on, `spec_gate`
carries the live counters `n_spec n_plain n_off n_shadow n_probe_fail t_plain t_spec
tok_round`. Useful while tuning.
@@ -65,6 +61,15 @@ top-level config does not carry `max_position_embeddings` — the GLM fix.
`--spec-gate` falls back to plain. A request cancelled mid-stream is not counted in this
first version.
+## Diagnostics: the request log
+
+The log and the stream keep-alive are shared code: switches, format, every event and how to read the
+output accounting are documented once, in [doc/logging.md](../../doc/logging.md). This server writes the
+same events as GLM except for `serve_start`, `img_cache` and `img_disk` (GLM's image cache and disk tier)
+and `sse_ping` (this server's pinger writes no log line); `tools/test_serve_logging.py` checks the shared
+part against all three servers at once. Turn it on with `KYOJIN_REQLOG=<path>` (or `1`) and hold a silent
+stream open with `KYOJIN_SSE_PING_S=<seconds>`; both are in [doc/env_vars.md](../../doc/env_vars.md).
+
## 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/mimo/serve.py b/tools/mimo/serve.py
index e5e97b5..e4dff6c 100644
--- a/tools/mimo/serve.py
+++ b/tools/mimo/serve.py
@@ -23,6 +23,7 @@ import re
import sys
import time
import uuid
+import functools
from collections.abc import AsyncIterator
from pathlib import Path
from typing import Any
@@ -41,7 +42,7 @@ from serve_metrics import Metrics
from serve_ping import ServePing
# serve_reqlog.py is a symlink to the shared tools/strix_halo/serve_reqlog.py: off unless
# KYOJIN_REQLOG names a path. Its output accounting also feeds the end-of-stream summary here.
-from serve_reqlog import ReqLog, StreamWriter
+from serve_reqlog import Lifecycle, ReqLog, StreamWriter, refusal_text, sanitize
from image_cache import ImageEmbeddingCache, digest
DEFAULT_MODEL = os.path.expanduser("~/models/mimo26-exl3")
@@ -513,12 +514,24 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
app.update(engine=engine, model_id=model_id, template=template, queue=queue, metrics=Metrics())
# SSE keep-alive: off unless KYOJIN_SSE_PING_S names an interval (see tools/strix_halo/serve_ping.py).
# A request copies this pinger, so its timers are its own; the start-up line reports the setting.
- app.update(ping=ServePing.from_env())
- # Request log: off unless KYOJIN_REQLOG names a path (numbers and event names only). The name is
- # bound here, not only stored on the app: the streaming route logs from inside its own scope, and
- # an unbound name there raises after the reply is complete, which costs the client its connection.
+ ping = ServePing.from_env()
+ app.update(ping=ping)
+ # Request log: off unless KYOJIN_REQLOG names a path (numbers and event names only). The name is bound
+ # here, not only stored on the app: the streaming route logs from inside its own scope, and an unbound
+ # name there raises after the reply is complete, which costs the client its connection.
reqlog = ReqLog.from_env(server="mimo")
app.update(reqlog=reqlog)
+ background: dict[str, Any] = {} # the heartbeat task, created at start-up (nothing when the log is off)
+
+ # The request lifecycle is logged by one shared implementation (tools/strix_halo/serve_reqlog.py).
+ # This server says when a phase begins and which counters it keeps; everything else — the request
+ # table, the id on every line, the 'alive' heartbeat, the route wrapper and the summary line — is
+ # the same code the other two servers run. `processing` is this server's only live count.
+ lifecycle = Lifecycle(reqlog, ping=ping, counters=lambda: {"processing": processing})
+
+ def reqid() -> str | None:
+ """The log id of the request being handled (None outside a logged route)."""
+ return lifecycle.reqid()
def observe(st: dict[str, Any], prompt_tokens: int) -> None:
accepted = int(st.get("accepted_draft_tokens", 0))
@@ -555,7 +568,13 @@ 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")
+ # `started` is when generation begins (what job_done reports as elapsed_s); the queue wait is
+ # the difference, and it is logged on its own as wait_s.
+ wait = time.perf_counter() - (body.get("_queued_at") or time.perf_counter())
+ started = time.perf_counter() - wait
if cancel is not None and cancel.is_set(): # the client left while the job was queued: no prefill, no decode
+ lifecycle.job_skipped(rid, wait)
out.put_nowait(None)
queue.task_done()
continue
@@ -565,6 +584,10 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
async with lock:
if store is not None:
store.busy = True
+ lifecycle.job_started(rid, wait, prompt_tokens=body.get("_prompt_tokens"),
+ images=len(body.get("_images") or ()),
+ messages=len(body.get("messages") or ()), processing=processing)
+ first_token = False # flipped once, so the log gets exactly one job_first_token line
async for delta in engine.generate(
body["_prompt"],
max_tokens=token_limit(body),
@@ -572,12 +595,17 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
top_p=body.get("top_p", SERVE_DEFAULTS["top_p"]), stop=body.get("_stop", []),
reset_gate=body.get("_reset_gate", False),
cancel=body.get("_cancel"), **({"images": body["_images"]} if body.get("_images") else {})):
+ if not first_token:
+ first_token = True
+ lifecycle.first_token(rid, started, prompt_tokens=body.get("_prompt_tokens"))
out.put_nowait(delta)
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)))
+ lifecycle.job_done(rid, request_stats, started, prompt_tokens=body.get("_prompt_tokens"))
out.put_nowait(None)
except Exception as exc: # noqa: BLE001
+ lifecycle.job_error(rid, exc, started)
out.put_nowait(exc)
finally:
processing -= 1
@@ -587,13 +615,19 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
async def start(_: web.Application) -> None:
app["worker_task"] = asyncio.create_task(worker())
+ if reqlog.enabled and reqlog.heartbeat_s > 0:
+ background["heartbeat"] = asyncio.create_task(lifecycle.heartbeat_forever())
async def close(app_: web.Application) -> None:
app_["worker_task"].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,
writer: StreamWriter | None = None, ping: ServePing | None = None,
- ping_at: float = 0.0) -> AsyncIterator[str]:
+ ping_at: float = 0.0, rid: str | None = None) -> AsyncIterator[str]:
"""Items the worker produced for one request. Nothing is written to the client while a job is
queued or prefilling (and never, for a non-streaming reply), so a client that hung up is noticed
by polling the transport. Raises ConnectionResetError and sets `cancel` when it has left.
@@ -606,6 +640,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
cancel.set()
if ping is not None:
ping.limit()
+ lifecycle.client_left("/v1/chat/completions", "waiting", rid=rid)
raise ConnectionResetError("client left")
if ping is not None:
try: # before the wait, so a stall is covered from its start
@@ -625,6 +660,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()
+ lifecycle.client_left(path)
print(f"serve: client left {path}, job cancelled", file=sys.stderr, flush=True)
return web.Response(status=499)
@@ -671,7 +707,13 @@ 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["_queued_at"] = time.perf_counter()
+ ahead = queue.qsize() # requests already waiting when this one arrived
await queue.put((body, out, request_stats))
+ lifecycle.queued(body["_reqid"], "/v1/chat/completions", queued_ahead=ahead,
+ prompt_tokens=prompt_tokens, messages=len(body.get("messages") or ()),
+ images=len(body.get("_images") or ()), stream=bool(body.get("stream")))
# MiMo's generation prompt is "<|im_start|>assistant\n": no implicit <think> block.
# This request's SSE keep-alive and the moment its wait started (see tools/strix_halo/serve_ping.py);
# None for a JSON reply, which has nobody to write a comment to. `deltas` takes the reply's stream
@@ -680,7 +722,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
ping_at = time.perf_counter()
def deltas(writer: StreamWriter | None = None) -> AsyncIterator[str]:
- return drain(request, cancel, out, writer, ping, ping_at)
+ return drain(request, cancel, out, writer, ping, ping_at, body.get("_reqid"))
def usage(raw: str) -> dict[str, int]:
completion_tokens = engine.count_tokens(raw)
@@ -709,7 +751,8 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
response = web.StreamResponse(headers={"Content-Type": "text/event-stream",
"Cache-Control": "no-cache"})
await response.prepare(request)
- writer = StreamWriter(response) # counts what the client is sent (see serve_reqlog)
+ writer = lifecycle.stream_started(body["_reqid"], "/v1/chat/completions", response,
+ prompt_tokens=prompt_tokens)
# 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 = "", 0, "content"
@@ -717,6 +760,9 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
# MiMo opens a turn with "<think>" only when the template asked for it, but a
# <think>...</think> pair can appear in the output either way, so both tags are watched.
tag_mode = {"<think>": "reasoning", "</think>": "content", TOOL_OPEN: "tool"}
+ # A mutable cell, not a flag: the nested flush() assigns it, and a plain name assigned there
+ # would be local to that closure (UnboundLocalError) instead of shared with the handler.
+ seen = {"text": False} # flipped at the first frame with text: the client's first sign of life
async def flush(final: bool) -> None:
nonlocal done, mode
@@ -727,7 +773,10 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
piece = stop_text(text[done:end], body["_stop"])[0]
if piece:
key = "reasoning_content" if mode == "reasoning" else "content"
- await response.write(sse(event({key: piece})))
+ if not seen["text"]:
+ seen["text"] = True
+ lifecycle.first_content(body["_reqid"], body["_queued_at"])
+ await writer.write(sse(event({key: piece})))
ping.note_output() # the client has text: comments wait for the next silence
done = end
if not hits:
@@ -737,7 +786,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
mode = tag_mode[tag]
try:
- await response.write(sse(event({"role": "assistant", "content": ""})))
+ await writer.write(sse(event({"role": "assistant", "content": ""})))
ping.note_output()
async for delta in deltas(writer):
text += delta
@@ -747,11 +796,12 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
message = parse_completion(text, body.get("tools"))
if "tool_calls" in message:
for n, call in enumerate(message["tool_calls"]): # one stream message per call (clients that read one call per message)
- await response.write(sse(event({"tool_calls": [dict(call, index=n)]})))
- await response.write(sse(event({}, finish_for(message, text)) |
- {"usage": usage(text), "timings": timings()}))
- await response.write(b"data: [DONE]\n\n")
+ await writer.write(sse(event({"tool_calls": [dict(call, index=n)]})))
+ await writer.write(sse(event({}, finish_for(message, text)) |
+ {"usage": usage(text), "timings": timings()}))
+ await writer.write(b"data: [DONE]\n\n")
await response.write_eof()
+ lifecycle.stream_done(body["_reqid"], int(request_stats.get("new_tokens") or 0))
except ConnectionResetError:
client_left(cancel, "stream") # client left: nothing to send
return response
@@ -760,18 +810,16 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
raise
except Exception as exc: # noqa: BLE001
cancel.set()
+ lifecycle.stream_error(body["_reqid"], 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:
- await response.write(sse({"error": {"message": f"{type(exc).__name__}: {exc}"}}))
- await response.write(sse(event({}, "error")))
- await response.write(b"data: [DONE]\n\n")
+ await writer.write(sse({"error": {"message": f"{type(exc).__name__}: {exc}"}}))
+ await writer.write(sse(event({}, "error")))
+ await writer.write(b"data: [DONE]\n\n")
await response.write_eof()
except ConnectionError:
pass
- finally:
- for event, fields in writer.stats.lines():
- reqlog.log(event, path="/v1/chat/completions", **fields)
return response
try:
@@ -829,7 +877,8 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
if room:
n_predict = min(n_predict, room)
stops = body.get("stop", [])
- job = {"_prompt": prompt, "max_tokens": n_predict,
+ job = {"_reqid": reqid(), "_queued_at": time.perf_counter(),
+ "_prompt": prompt, "max_tokens": n_predict,
"temperature": float(body.get("temperature", SERVE_DEFAULTS["temperature"])),
"top_p": float(body.get("top_p", SERVE_DEFAULTS["top_p"])),
"_stop": [stops] if isinstance(stops, str) else list(stops),
@@ -910,9 +959,9 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
app.router.add_get("/v1/models", models)
app.router.add_get("/health", health)
app.router.add_get("/metrics", metrics_view)
- app.router.add_post("/v1/chat/completions", completions)
+ app.router.add_post("/v1/chat/completions", lifecycle.wrapped(completions))
app.router.add_post("/apply-template", apply_template)
- app.router.add_post("/completion", completion)
+ app.router.add_post("/completion", lifecycle.wrapped(completion))
app.on_startup.append(start)
app.on_cleanup.append(close)
return app
diff --git a/tools/qwen/SERVE.md b/tools/qwen/SERVE.md
index cba7014..effa426 100644
--- a/tools/qwen/SERVE.md
+++ b/tools/qwen/SERVE.md
@@ -91,11 +91,6 @@ The pack is tied to one set of weights: download it from the same model repo.
- Debug extensions (all optional): `"speculative": false` decodes plain for that request, `"cache_prompt": false`
forgets the prompt cache first (cold run), `"return_token_ids": true` adds the generated ids. Switching
speculative mode or `cache_prompt: false` rebuilds the Generator and so drops the prompt cache (400 with `--sessions` > 1).
-- A turn is silent on the wire for as long as the server has nothing to send (headers and one empty role
- chunk, then nothing until text is ready — including a decode that is holding a `<tool_call>` back until
- its XML closes), so `KYOJIN_SSE_PING_S=<seconds>` makes the server write an SSE comment
- (`: waiting <n> s`) after that much silence. Off by default, shared with the other two servers; the
- switch and its start-up line are in [doc/env_vars.md](../../doc/env_vars.md).
- vLLM-style extensions (also used by the RigMark benchmark): `POST /tokenize` (`{"prompt"|"messages", "add_special_tokens"}` ->
`{"tokens", "count", "max_model_len"}`); `/v1/completions` takes `prompt` as a list of token ids (`[1, 2, 3]` or `[[1, 2, 3]]`):
@@ -106,6 +101,15 @@ The pack is tied to one set of weights: download it from the same model repo.
when it changes, running requests finish, the prompt cache is dropped (a fresh Generator, as `cache_prompt: false` does), and the
request starts. The same salt, or no salt at all, never drops anything, so only the first request after a change pays the rebuild.
+## Diagnostics: the request log
+
+The log and the stream keep-alive are shared code: switches, format, every event and how to read the
+output accounting are documented once, in [doc/logging.md](../../doc/logging.md). This server writes the
+same events as GLM except for `serve_start`, `img_cache` and `img_disk` (GLM's image cache and disk tier)
+and `sse_ping` (this server's pinger writes no log line); `tools/test_serve_logging.py` checks the shared
+part against all three servers at once. Turn it on with `KYOJIN_REQLOG=<path>` (or `1`) and hold a silent
+stream open with `KYOJIN_SSE_PING_S=<seconds>`; both are in [doc/env_vars.md](../../doc/env_vars.md).
+
## 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/qwen/serve.py b/tools/qwen/serve.py
index 9bf4ae1..510d731 100644
--- a/tools/qwen/serve.py
+++ b/tools/qwen/serve.py
@@ -16,6 +16,7 @@ import argparse
import asyncio
import base64
import contextlib
+import functools
import gc
import importlib.util
import io
@@ -48,7 +49,7 @@ import serve_compat # noqa: E402 (vLLM-style token-id prompts, cache_salt, /to
from serve_ping import ServePing # noqa: E402
# serve_reqlog.py is a symlink to the shared tools/strix_halo/serve_reqlog.py: off unless
# KYOJIN_REQLOG names a path. Its output accounting also feeds the end-of-stream summary here.
-from serve_reqlog import ReqLog, StreamWriter # noqa: E402
+from serve_reqlog import Lifecycle, ReqLog, StreamWriter, refusal_text, sanitize # noqa: E402
def _load_mimo():
@@ -1267,12 +1268,27 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
app.update(engine=engine, model_id=model_id, template=template, defaults=defaults)
# SSE keep-alive: off unless KYOJIN_SSE_PING_S names an interval (see tools/strix_halo/serve_ping.py).
# A request copies this pinger, so its timers are its own; the start-up line reports the setting.
- app.update(ping=ServePing.from_env())
- # Request log: off unless KYOJIN_REQLOG names a path (numbers and event names only). The name is
- # bound here, not only stored on the app: the streaming routes log from inside their own scope, and
- # an unbound name there raises after the reply is complete, which costs the client its connection.
+ ping = ServePing.from_env()
+ app.update(ping=ping)
+ # Request log: off unless KYOJIN_REQLOG names a path (numbers and event names only). The name is bound
+ # here, not only stored on the app: the streaming routes log from inside their own scope, and an
+ # unbound name there raises after the reply is complete, which costs the client its connection.
reqlog = ReqLog.from_env(server="qwen")
app.update(reqlog=reqlog)
+ background: dict[str, Any] = {} # the heartbeat task, created at start-up (nothing when the log is off)
+
+ # The request lifecycle is logged by one shared implementation (tools/strix_halo/serve_reqlog.py).
+ # This server says when a phase begins and which counters it keeps; everything else — the request
+ # table, the id on every line, the 'alive' heartbeat, the route wrapper and the summary line — is
+ # the same code the other two servers run. `running` is this server's only live count.
+ lifecycle = Lifecycle(reqlog, ping=ping, counters=lambda: {"running": running})
+
+ def reqid() -> str | None:
+ """The log id of the request being handled (None outside a logged route)."""
+ return lifecycle.reqid()
+
+ def track(rid: str | None, phase: str, **fields: Any) -> None:
+ lifecycle.track(rid, phase, **fields)
def err(status: int, message: str) -> web.Response:
return web.json_response({"error": {"message": message, "type": "invalid_request_error", "code": status}},
@@ -1322,11 +1338,27 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
job, out = await queue.get()
store = getattr(engine, "slot_store", None)
stats: dict[str, Any] = {}
+ rid = job.get("_reqid")
+ # `started` is when generation begins (what job_done reports as elapsed_s); the queue wait is
+ # the difference, and it is logged on its own as wait_s.
+ wait = time.perf_counter() - (job.get("_queued_at") or time.perf_counter())
+ started = time.perf_counter() - wait
+ if job.get("cancel") is not None and job["cancel"].is_set():
+ # the client left while the job was queued: no prefill, no decode, one line
+ lifecycle.job_skipped(rid, wait)
+ out.put_nowait(("done", {}))
+ queue.task_done()
+ continue
try:
async with admit(job.get("cache_salt")):
running += 1
if store is not None:
store.busy = True
+ track(rid, "prefill", prompt_tokens=job.get("prompt_tokens"))
+ lifecycle.job_started(rid, wait, prompt_tokens=job.get("prompt_tokens"),
+ images=len(job.get("images") or ()),
+ messages=job.get("messages"), sessions=sessions, running=running)
+ first_token = False # flipped once, so the log gets exactly one job_first_token line
try:
async for delta in engine.generate(
job["prompt"], stats=stats, max_tokens=job["max_tokens"], sampling=job["sampling"],
@@ -1337,6 +1369,9 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
seed=job.get("seed"), reasoning_first=job.get("reasoning_first", False),
thinking_budget=job.get("thinking_budget"), loop_guard=job.get("loop_guard"),
loop_final=job.get("loop_final"), logprobs=job.get("logprobs")):
+ if not first_token:
+ first_token = True
+ lifecycle.first_token(rid, started, prompt_tokens=job.get("prompt_tokens"))
out.put_nowait(delta)
finally:
running -= 1
@@ -1348,18 +1383,26 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
f"new={int(done.get('new_tokens') or 0)} prefill_s={float(done.get('time_prefill') or 0):.3f} "
f"generate_s={float(done.get('time_generate') or 0):.3f} stop={done.get('eos_reason')}",
file=sys.stderr, flush=True)
+ lifecycle.job_done(rid, done, started, prompt_tokens=job.get("prompt_tokens"))
out.put_nowait(("done", done))
except Exception as exc: # noqa: BLE001
+ lifecycle.job_error(rid, exc, started)
out.put_nowait(exc)
finally:
queue.task_done()
async def start(_: web.Application) -> None:
app["worker_tasks"] = [asyncio.create_task(worker()) for _ in range(sessions)]
+ if reqlog.enabled and reqlog.heartbeat_s > 0:
+ background["heartbeat"] = asyncio.create_task(lifecycle.heartbeat_forever())
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()
def check_sessions(job: dict[str, Any]) -> None:
# both rebuild the Generator, which would drop the jobs of the other sessions (without a drafter there is
@@ -1424,7 +1467,7 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
lp = logprobs_arg(body.get("logprobs"), body.get("top_logprobs"), chat=True)
if lp is not None and body.get("stream"):
raise BadRequest("logprobs are returned on non-streaming requests only")
- job = {"logprobs": lp, "seed": seed, "thinking_budget": budget, "loop_guard": body.get("loop_guard"), "loop_final": body.get("loop_final"), "prompt": prompt, "prompt_tokens": prompt_tokens, "max_tokens": max_tokens,
+ job = {"logprobs": lp, "seed": seed, "thinking_budget": budget, "loop_guard": body.get("loop_guard"), "loop_final": body.get("loop_final"), "prompt": prompt, "prompt_tokens": prompt_tokens, "max_tokens": max_tokens, "messages": len(messages),
"sampling": sampling_from(body, defaults), "stop": stops, "images": images,
"speculative": body.get("speculative", True) is not False,
"cache_prompt": body.get("cache_prompt", True) is not False,
@@ -1432,6 +1475,8 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
"return_token_ids": bool(body.get("return_token_ids")), "cancel": asyncio.Event()}
check_sessions(job)
job["cache_salt"] = salt_of(body)
+ job["_reqid"] = None # set by the route, which knows the request's log id
+ job["_queued_at"] = None
return job
async def completions(request: web.Request) -> web.StreamResponse:
@@ -1449,8 +1494,13 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
return base | {"choices": [{"index": 0, "delta": delta, "finish_reason": finish}]}
out: asyncio.Queue = asyncio.Queue()
+ job["_reqid"] = reqid()
+ job["_queued_at"] = queued_at = time.perf_counter() # the wait a streaming client's comments count from
+ ahead = queue.qsize() # requests already waiting when this one arrived
await queue.put((job, out))
- queued_at = time.perf_counter() # the wait a streaming client's comments count from
+ lifecycle.queued(job["_reqid"], "/v1/chat/completions", queued_ahead=ahead,
+ prompt_tokens=job.get("prompt_tokens"), messages=len(body.get("messages") or ()),
+ images=len(job.get("images") or ()), stream=bool(body.get("stream")))
def finish_and_stats(stats: dict[str, Any], text: str, has_calls: bool):
n_new = int(stats.get("new_tokens") or engine.count_tokens(text))
@@ -1509,12 +1559,14 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
if body.get("stream", False):
response = web.StreamResponse(headers={"Content-Type": "text/event-stream", "Cache-Control": "no-cache"})
await response.prepare(request)
- writer = StreamWriter(response) # counts what the client is sent (see serve_reqlog)
ping, ping_at = app["ping"].per_request(), queued_at
+ writer = lifecycle.stream_started(job["_reqid"], "/v1/chat/completions", response,
+ prompt_tokens=job.get("prompt_tokens"))
try:
await writer.write(sse(event({"role": "assistant", "content": ""})))
ping.note_output()
stats, full = {}, ""
+ visible = False # flipped at the first frame with text: the client's first sign of life
async for item in pieces(writer, ping, ping_at):
if isinstance(item, dict):
stats = item
@@ -1529,6 +1581,9 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
full += item
for kind, piece in sp.feed(item):
key = "reasoning_content" if kind == "reasoning" else "content"
+ if not visible:
+ visible = True
+ lifecycle.first_content(job["_reqid"], queued_at)
await writer.write(sse(event({key: piece})))
ping.note_output() # the client has text: comments wait for the next silence
for kind, piece in sp.finish():
@@ -1545,13 +1600,16 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
await writer.write(sse(final))
await writer.write(b"data: [DONE]\n\n")
await response.write_eof()
+ lifecycle.stream_done(job["_reqid"], int(stats.get("new_tokens") or 0))
except ConnectionResetError: # client left: stop the job, no traceback
job["cancel"].set()
+ lifecycle.client_left("/v1/chat/completions", "stream", rid=job["_reqid"])
except asyncio.CancelledError:
job["cancel"].set()
raise
except Exception as exc: # noqa: BLE001
job["cancel"].set()
+ lifecycle.stream_error(job["_reqid"], exc)
try:
await writer.write(sse({"error": {"message": f"{type(exc).__name__}: {exc}"}}))
# End the stream the OpenAI way: a bare drop makes clients report "stream ended without finish_reason".
@@ -1560,9 +1618,6 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
await response.write_eof()
except ConnectionError:
pass
- finally:
- for event, fields in writer.stats.lines():
- reqlog.log(event, path="/v1/chat/completions", **fields)
return response
try:
@@ -1592,6 +1647,7 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
if job["logprobs"] is not None:
payload["choices"][0]["logprobs"] = format_logprobs(
stats.get("logprobs", []), stats.get("logprob_token_ids", stats.get("token_ids", [])), engine.token_str, chat=True)
+ # The worker logs job_done for this job as well (a JSON reply takes the same path as a stream).
return web.json_response(payload)
async def apply_template(request: web.Request) -> web.Response:
@@ -1664,7 +1720,8 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
if room < 1:
raise BadRequest(f"context length exceeded: prompt is longer than the server context ({ctx})")
n_predict = min(n_predict, room)
- job = {"prompt": prompt, "max_tokens": n_predict,
+ job = {"_reqid": reqid(), "_queued_at": time.perf_counter(), "messages": 0,
+ "prompt": prompt, "max_tokens": n_predict,
"sampling": sampling_from({k: body.get(k) for k in ("temperature", "top_p", "top_k", "min_p")}, defaults),
"stop": stops, "images": [], "speculative": True,
"seed": body.get("seed") if isinstance(body.get("seed"), int) and not isinstance(body.get("seed"), bool) else None,
@@ -1675,7 +1732,10 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
except (BadRequest, TypeError, ValueError) as exc:
return err(400, str(exc))
out: asyncio.Queue = asyncio.Queue()
+ ahead = queue.qsize()
await queue.put((job, out))
+ lifecycle.queued(job["_reqid"], "/completion", queued_ahead=ahead, messages=0, images=0,
+ stream=False)
text, stats = "", {}
while True:
item = await out.get()
@@ -1743,7 +1803,8 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
if room < 1:
raise BadRequest(f"context length exceeded: prompt is {prompt_tokens} tokens, the server context is {ctx}")
max_tokens = min(max_tokens, room)
- job = {"cache_salt": salt_of(body), "prompt_ids": prompt_ids, "ignore_eos": body.get("ignore_eos") is True,
+ job = {"_reqid": reqid(), "_queued_at": time.perf_counter(), "messages": 0,
+ "cache_salt": salt_of(body), "prompt_ids": prompt_ids, "ignore_eos": body.get("ignore_eos") is True,
"logprobs": lp, "prompt": prompt, "max_tokens": max_tokens, "stop": stops, "images": [], "speculative": body.get("speculative", True) is not False, "seed": seed,
"sampling": sampling_from(body, defaults), "cache_prompt": body.get("cache_prompt", True) is not False,
"loop_guard": body.get("loop_guard"), "cancel": asyncio.Event()}
@@ -1765,8 +1826,13 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
return reason, serve_compat.usage(n_prompt, n_new, int(stats.get("cached_tokens") or 0))
out: asyncio.Queue = asyncio.Queue()
+ job["_reqid"] = reqid()
+ job["_queued_at"] = queued_at = time.perf_counter() # the wait a streaming client's comments count from
+ ahead = queue.qsize()
await queue.put((job, out))
- queued_at = time.perf_counter() # the wait a streaming client's comments count from
+ lifecycle.queued(job["_reqid"], "/v1/completions", queued_ahead=ahead,
+ prompt_tokens=job.get("prompt_tokens"), messages=0, images=0,
+ stream=bool(body.get("stream")))
async def pieces(writer: StreamWriter | None = None, ping: ServePing | None = None,
ping_at: float = 0.0) -> AsyncIterator[str | dict]:
@@ -1774,6 +1840,7 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
tr = request.transport
if tr is None or tr.is_closing():
job["cancel"].set()
+ lifecycle.client_left("/v1/completions", "waiting", rid=job.get("_reqid"))
raise ConnectionResetError("client left")
if ping is not None:
# A ':' comment while the engine works, checked before every poll: the only thing a
@@ -1797,35 +1864,39 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
if body.get("stream", False):
response = web.StreamResponse(headers={"Content-Type": "text/event-stream", "Cache-Control": "no-cache"})
await response.prepare(request)
- writer = StreamWriter(response) # counts what the client is sent (see serve_reqlog)
ping, ping_at = app["ping"].per_request(), queued_at
+ writer = lifecycle.stream_started(job["_reqid"], "/v1/completions", response,
+ prompt_tokens=job.get("prompt_tokens"))
try:
- stats, full = {}, ""
+ stats, full, visible = {}, "", False
async for item in pieces(writer, ping, ping_at):
if isinstance(item, dict):
stats = item
elif not isinstance(item, Retract):
full += item
+ if not visible:
+ visible = True
+ lifecycle.first_content(job["_reqid"], queued_at)
await writer.write(sse(chunk(item, None)))
reason, usage = reason_usage(stats, full)
await writer.write(sse(chunk("", reason) | {"usage": usage}))
await writer.write(b"data: [DONE]\n\n")
await response.write_eof()
+ lifecycle.stream_done(job["_reqid"], int(stats.get("new_tokens") or 0))
except ConnectionResetError:
job["cancel"].set()
+ lifecycle.client_left("/v1/completions", "stream", rid=job["_reqid"])
except asyncio.CancelledError:
job["cancel"].set()
raise
except Exception as exc: # noqa: BLE001
job["cancel"].set()
+ lifecycle.stream_error(job["_reqid"], exc)
try:
await writer.write(sse({"error": {"message": f"{type(exc).__name__}: {exc}"}}))
await response.write_eof()
except ConnectionError:
pass
- finally:
- for event, fields in writer.stats.lines():
- reqlog.log(event, path="/v1/chat/completions", **fields)
return response
try:
@@ -1882,11 +1953,11 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
app.router.add_get("/v1/models", models)
app.router.add_get("/health", health)
- app.router.add_post("/v1/chat/completions", completions)
+ app.router.add_post("/v1/chat/completions", lifecycle.wrapped(completions))
app.router.add_post("/apply-template", apply_template)
app.router.add_post("/tokenize", tokenize)
- app.router.add_post("/completion", completion)
- app.router.add_post("/v1/completions", v1_completions)
+ app.router.add_post("/completion", lifecycle.wrapped(completion))
+ app.router.add_post("/v1/completions", lifecycle.wrapped(v1_completions))
if getattr(engine, "slot_store", None) is not None:
app.router.add_get("/slots", slots)
app.router.add_post("/slots/{id}", slot_action)
diff --git a/tools/strix_halo/serve_reqlog.py b/tools/strix_halo/serve_reqlog.py
index d09d34e..cc23b27 100644
--- a/tools/strix_halo/serve_reqlog.py
+++ b/tools/strix_halo/serve_reqlog.py
@@ -27,12 +27,16 @@ event name, then `key=value` fields; every line of one request carries the same
"""
from __future__ import annotations
+import asyncio
+import contextvars
+import functools
import json
import os
import pathlib
import sys
import threading
import time
+import uuid
from typing import Any
DEFAULT_PATH = "~/.cache/kyojin/requests.log"
@@ -130,6 +134,233 @@ class StreamWriter:
await self.response.write_eof()
+class Lifecycle:
+ """The request lifecycle a server logs, in one place for all of them.
+
+ Every server used to carry its own copy of this: the request table, the context variable that names
+ the request, the 'alive' heartbeat, and the route wrapper that stamps one id on every line. The
+ copies drifted (one server forgot an argument, another measured a different span, a third spelled an
+ event differently), so the machinery lives here and a server only says **when** something happened.
+
+ A server keeps its own event *call sites* — where in its worker and its routes the phases begin is
+ the one thing that genuinely differs — and calls the method for the event it has:
+
+ log = Lifecycle(ReqLog.from_env("glm"), ping=ServePing.from_env(reqlog),
+ counters=lambda: {"processing": processing, "running": running})
+ app.router.add_post("/v1/chat/completions", log.wrapped(completions))
+ log.queued(rid, "/v1/chat/completions", prompt_tokens=n, images=len(imgs), stream=True)
+ ...
+ await log.heartbeat_forever() # started on app startup, cancelled on cleanup
+
+ **An event or field a server does not have is simply not passed**, which is what keeps one
+ implementation usable by three servers: `ReqLog.log` skips `None` fields and accepts any event name,
+ so a missing counter or an event a server never reaches leaves no line and no branch anywhere. What a
+ server does report is up to its call sites, never to a per-server flag in here. The one event with
+ server-specific fields is the raw `log()` escape hatch (`img_cache` on GLM, `serve_start`), which
+ carries whatever that server measured.
+
+ Counters are pulled per heartbeat through `counters()`, so each server reports the ones it has
+ (GLM tracks requests in flight and running separately; Qwen and MiMo have one number).
+ """
+
+ def __init__(self, reqlog: "ReqLog", ping: Any = None, counters: Any = None,
+ server: str | None = None) -> None:
+ self.reqlog = reqlog
+ self.ping = ping
+ self.counters = counters
+ self.server = server or getattr(reqlog, "server", None)
+ self.inflight: dict[str, dict[str, Any]] = {}
+ self.writers: dict[str, StreamWriter] = {}
+ self.current: contextvars.ContextVar[str | None] = contextvars.ContextVar("reqid", default=None)
+ self._counters: dict[str, Any] = {}
+
+ # ---- request identity and per-request state ---------------------------------------------------
+
+ def reqid(self) -> str | None:
+ """The log id of the request being handled (None outside a wrapped route)."""
+ return self.current.get()
+
+ def track(self, rid: str | None, phase: str, **fields: Any) -> None:
+ """Record the phase a request is in, and anything the heartbeat should repeat."""
+ if rid is None:
+ return
+ st = self.inflight.setdefault(rid, {"t0": time.perf_counter()})
+ st["phase"] = phase
+ st.update(fields)
+
+ def writer(self, rid: str | None, response: Any, path: str | None = None) -> StreamWriter:
+ """The request's stream writer: what it writes is counted, and the heartbeat reports it."""
+ writer = StreamWriter(response)
+ writer.path = path # so the summary line can name the route, as it always has
+ if rid is not None:
+ self.writers[rid] = writer
+ return writer
+
+ def log(self, event: str, **fields: Any) -> None:
+ """A line only this server writes (a start-up record, a cache report): pass it through."""
+ self.reqlog.log(event, **fields)
+
+ # ---- request level ---------------------------------------------------------------------------
+
+ def request_started(self, rid: str, request: Any) -> float:
+ """Open a request: id, arrival time, and the `req_start` line. Returns the start time."""
+ self.current.set(rid)
+ started = time.perf_counter()
+ self.track(rid, "parse")
+ self.reqlog.log("req_start", req=rid, path=request.path, method=request.method,
+ bytes=request.content_length)
+ return started
+
+ def refused(self, rid: str, path: str, exc: Any, started: float) -> None:
+ self.reqlog.log("req_refused", req=rid, path=path, status=exc.status,
+ reason=refusal_text(exc), elapsed_s=round(time.perf_counter() - started, 3))
+
+ def handler_left(self, rid: str, path: str) -> None:
+ self.reqlog.log("client_left", req=rid, path=path, stage="handler")
+
+ def request_error(self, rid: str, path: str, exc: BaseException, started: float) -> None:
+ self.reqlog.log("req_error", req=rid, path=path, error=sanitize(exc),
+ elapsed_s=round(time.perf_counter() - started, 3))
+
+ def request_done(self, rid: str, path: str, response: Any, started: float) -> None:
+ self.reqlog.log("req_done", req=rid, path=path, status=response.status,
+ elapsed_s=round(time.perf_counter() - started, 3))
+
+ def client_left(self, path: str, stage: str = "waiting", rid: str | None = None) -> None:
+ """The client hung up first: the server's side of a cancelled turn, on record."""
+ self.reqlog.log("client_left", req=rid if rid is not None else self.reqid(), path=path, stage=stage)
+
+ def wrapped(self, handler: Any) -> Any:
+ """Wrap a route so its lifecycle lands in the log: one id per request, `grep <id>` follows it."""
+ @functools.wraps(handler)
+ async def wrapper(request: Any) -> Any:
+ rid = f"r{uuid.uuid4().hex[:12]}"
+ token = self.current.set(rid)
+ started = time.perf_counter()
+ self.track(rid, "parse")
+ self.reqlog.log("req_start", req=rid, path=request.path, method=request.method,
+ bytes=request.content_length)
+ try:
+ response = await handler(request)
+ except asyncio.CancelledError:
+ self.handler_left(rid, request.path)
+ raise
+ except Exception as exc: # noqa: BLE001 classified here
+ if hasattr(exc, "status"): # aiohttp's HTTPException
+ self.refused(rid, request.path, exc, started)
+ else:
+ self.request_error(rid, request.path, exc, started)
+ raise
+ else:
+ self.request_done(rid, request.path, response, started)
+ return response
+ finally:
+ self.finish(rid)
+ self.current.reset(token)
+ return wrapper
+
+ def finish(self, rid: str) -> None:
+ """Close a request: its summary line (what the client was sent) and its bookkeeping."""
+ writer = self.writers.pop(rid, None)
+ if writer is not None:
+ for event, fields in writer.stats.lines():
+ self.reqlog.log(event, req=rid, path=getattr(writer, "path", None), **fields)
+ self.inflight.pop(rid, None)
+
+ # ---- job level (the worker side) -------------------------------------------------------------
+
+ def queued(self, rid: str | None, path: str, **fields: Any) -> None:
+ """The request is in the worker queue: what it is, and how many are ahead of it."""
+ self.track(rid, "queued", prompt_tokens=fields.get("prompt_tokens"))
+ self.reqlog.log("req_queued", req=rid, path=path, **fields)
+
+ def job_started(self, rid: str | None, wait: float, **fields: Any) -> None:
+ """The worker picked the job up: `wait` is the queue time, the rest is what this server knows."""
+ self.track(rid, "prefill", prompt_tokens=fields.get("prompt_tokens"))
+ self.reqlog.log("job_start", req=rid, wait_s=round(wait, 3), **fields)
+
+ def job_skipped(self, rid: str | None, queued_s: float) -> None:
+ """A job cancelled while it was still queued: no prefill, no decode, one line."""
+ self.reqlog.log("job_skipped", req=rid, queued_s=round(queued_s, 3))
+
+ def first_token(self, rid: str | None, started: float, **fields: Any) -> None:
+ """The model produced its first token, and the request moves to decode."""
+ self.track(rid, "decode", prompt_tokens=fields.get("prompt_tokens"))
+ self.reqlog.log("job_first_token", req=rid, elapsed_s=round(time.perf_counter() - started, 3))
+
+ def job_done(self, rid: str | None, stats: Any, started: float, prompt_tokens: int = 0) -> None:
+ """A finished job: what the prompt cache did (cache_n vs prompt tokens) and how long each phase
+ took. `prompt_tokens` is the fallback for an engine (or a fake one in tests) that reports none."""
+ st = stats or {}
+ prompt = int(st.get("prompt_tokens") or prompt_tokens or 0)
+ cache_n = int(st.get("cached_tokens") or 0)
+ self.reqlog.log("job_done", req=rid, elapsed_s=round(time.perf_counter() - started, 3),
+ prompt_tokens=prompt, cache_n=cache_n,
+ cache_pct=round(100.0 * cache_n / prompt, 1) if prompt 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))
+
+ def job_error(self, rid: str | None, exc: BaseException, started: float | None = None) -> None:
+ self.reqlog.log("job_error", req=rid, error=sanitize(exc),
+ elapsed_s=round(time.perf_counter() - started, 3) if started else None)
+
+ def stream_error(self, rid: str | None, exc: BaseException) -> None:
+ self.reqlog.log("stream_error", req=rid, error=sanitize(exc))
+
+ # ---- stream level ----------------------------------------------------------------------------
+
+ def stream_started(self, rid: str | None, path: str, response: Any, prompt_tokens: int = 0) -> StreamWriter:
+ """The SSE headers are out: register the writer the heartbeat reads and log the headers."""
+ writer = self.writer(rid, response, path)
+ self.track(rid, "stream", prompt_tokens=prompt_tokens)
+ self.reqlog.log("sse_headers", req=rid, path=path)
+ return writer
+
+ def first_content(self, rid: str | None, since: float) -> None:
+ """The first frame with text in it: the gap the client experiences as silence, in seconds."""
+ self.reqlog.log("sse_first_content", req=rid,
+ first_s=round(time.perf_counter() - since, 3))
+
+ def stream_done(self, rid: str | None, out_tokens: int = 0) -> None:
+ self.reqlog.log("sse_done", req=rid, out_tokens=out_tokens)
+
+ # ---- heartbeat -------------------------------------------------------------------------------
+
+ def heartbeat_fields(self, st: dict[str, Any], rid: str) -> dict[str, Any]:
+ """One `alive` line's fields: the phase, the counters, and what the client has been sent."""
+ writer = self.writers.get(rid)
+ stats = writer.stats if writer is not None else None
+ return dict(phase=st.get("phase"), elapsed_s=round(time.perf_counter() - st["t0"], 2),
+ prompt_tokens=st.get("prompt_tokens"),
+ out_events=stats.events if stats else None,
+ out_chars=stats.bytes if stats else None,
+ last_out_s=round(stats.since_data_s(), 1) if stats else None)
+
+ async def heartbeat_forever(self, interval_s: float | None = None) -> None:
+ """One `alive` line per in-flight request every interval, until cancelled.
+
+ Started by a server on app startup and cancelled on cleanup; a no-op loop when the log is off
+ (nothing is in flight then either, since `track` is what fills the table)."""
+ every = interval_s if interval_s is not None else self.reqlog.heartbeat_s
+ while True:
+ await asyncio.sleep(every)
+ for rid, st in list(self.inflight.items()):
+ self._counters = dict(self.counters() if self.counters else {})
+ self.reqlog.log("alive", req=rid, **self.heartbeat_fields(st, rid), **self._counters)
+
+
+def refusal_text(exc: Any) -> str:
+ """The server's own refusal text, without the exception type (the line already names the request).
+
+ A JSON parse error is reduced to line/column: its message quotes the request body."""
+ cause = getattr(exc, "__cause__", None)
+ if isinstance(cause, json.JSONDecodeError):
+ return sanitize(cause)
+ text = " ".join(str(getattr(exc, "reason", "") or "").split())[:160]
+ return text or type(exc).__name__
+
+
class ReqLog:
"""Append-only event log. Every method is safe to call when logging is disabled or broken."""
diff --git a/tools/test_serve_logging.py b/tools/test_serve_logging.py
new file mode 100644
index 0000000..2b738ad
--- /dev/null
+++ b/tools/test_serve_logging.py
@@ -0,0 +1,239 @@
+#!/usr/bin/env python3
+"""The three servers must log the same thing: one vocabulary, one set of fields per event.
+
+The request log is shared code (tools/strix_halo/serve_reqlog.py) and the point of sharing it is that a
+server cannot invent its own spelling of an event or forget a field the others report. This test runs the
+same requests against all three servers - model-free, each serve.py loaded from its own path so the three
+modules cannot shadow each other - and compares what they wrote.
+
+ kyojin/.venv/bin/python -m unittest tools.test_serve_logging
+
+What is asserted:
+
+* every event a server writes is one this log defines (a typo like `job_started` fails here);
+* the events a streamed chat request produces are the same on all three, field for field, once the
+ counters each server actually keeps are taken out (`running`, `processing`) - a server that reports
+ fewer counters is not a difference in vocabulary;
+* `req=` is on every line, and every request opens and closes (`req_start` .. `req_done`), so
+ `grep <id>` works on all three;
+* the heartbeat carries the output accounting on all three.
+"""
+from __future__ import annotations
+
+import asyncio
+import importlib.util
+import os
+import re
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+TOOLS = Path(__file__).resolve().parent
+
+# Every event name the shared log defines. A server writing anything else has invented a spelling.
+KNOWN_EVENTS = {
+ "req_start", "req_queued", "req_refused", "req_error", "req_done",
+ "job_start", "job_skipped", "job_first_token", "job_done", "job_error",
+ "alive", "sse_headers", "sse_first_content", "sse_ping", "sse_done", "stream_error",
+ "sse_summary", "client_left",
+ # server-specific lines that go through the raw log() escape hatch
+ "serve_start", "img_cache", "img_disk", "rss",
+}
+# Counters each server keeps; keeping one and not the other is not a vocabulary difference.
+COUNTER_FIELDS = {"running", "processing"}
+# The keep-alive fields only exist for a request that produced a comment, and whether one is due at all
+# depends on how often a server polls its queue (Qwen polls once a second, GLM and MiMo twice), so a
+# server with no comment is not missing a field. `test_a_comment_fills_the_summary` covers them.
+COMMENT_FIELDS = {"comments", "comment_chars", "last_comment_s"}
+# Fields that only exist where the feature does: MiMo has no --sessions (one request at a time), so
+# there is no session count to report. A server may have them or not; it may not have anything else.
+OPTIONAL_FIELDS = {"sessions", "messages"}
+
+
+class FakeGenerator:
+ num_draft_tokens = 2
+
+
+class FakeEngine:
+ """What all three servers need from an engine, and nothing more."""
+
+ ctx = 4096
+ supports_vision = True
+ spec_on = False
+ sessions = 1
+
+ def __init__(self) -> None:
+ self.greedy_generator = FakeGenerator()
+
+ def count_tokens(self, text: str) -> int:
+ return len(text.split())
+
+ def spec_stats(self) -> dict:
+ return {}
+
+ def gate_stats(self) -> dict:
+ return {}
+
+ def reset_gate(self) -> None:
+ pass
+
+ async def generate(self, prompt, **kw):
+ await asyncio.sleep(0.5) # a prefill long enough to produce 'alive' lines
+ for piece in ("he", "llo"):
+ yield piece
+
+
+def load_server(name: str):
+ """Load tools/<name>/serve.py under a private module name, with its own folder on sys.path."""
+ here = TOOLS / name
+ sys.path.insert(0, str(here))
+ try:
+ spec = importlib.util.spec_from_file_location(f"{name}_serve_under_test", here / "serve.py")
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ spec.loader.exec_module(module)
+ return module
+ finally:
+ sys.path.remove(str(here))
+
+
+def parse_log(path: Path) -> dict[str, dict[str, set[str]]]:
+ """{request id: {event: fields}}; the heartbeat's own lines land under the key '-' if untagged."""
+ out: dict[str, dict[str, set[str]]] = {}
+ for line in path.read_text(encoding="utf-8").splitlines():
+ parts = line.split(" ")
+ name = parts[1]
+ fields = {p.split("=", 1)[0] for p in parts[2:] if "=" in p}
+ rid = next((p[4:] for p in parts[2:] if p.startswith("req=")), "-")
+ out.setdefault(rid, {}).setdefault(name, set()).update(fields - {"req"})
+ return out
+
+
+def run_battery(name: str, log_path: Path) -> dict[str, dict[str, set[str]]]:
+ """One streamed chat request and one refused request against one server."""
+ serve = load_server(name)
+
+ async def go() -> None:
+ from aiohttp.test_utils import TestClient, TestServer
+ app = serve.create_app(FakeEngine(), "m", "{{ messages[0].content }}")
+ client = TestClient(TestServer(app))
+ await client.start_server()
+ try:
+ r = await client.post("/v1/chat/completions", json={
+ "model": "m", "stream": True, "messages": [{"role": "user", "content": "hi"}]})
+ await r.read()
+ r = await client.post("/v1/chat/completions", json={"model": "m", "messages": []})
+ await r.read()
+ finally:
+ await client.close()
+
+ os.environ["KYOJIN_REQLOG"] = str(log_path)
+ os.environ["KYOJIN_REQLOG_HEARTBEAT_S"] = "0.2"
+ os.environ["KYOJIN_SSE_PING_S"] = "0.2"
+ try:
+ asyncio.run(go())
+ finally:
+ for key in ("KYOJIN_REQLOG", "KYOJIN_REQLOG_HEARTBEAT_S", "KYOJIN_SSE_PING_S"):
+ os.environ.pop(key, None)
+ return parse_log(log_path)
+
+
+class LoggingVocabularyTests(unittest.TestCase):
+ """All three servers, one log format."""
+
+ @classmethod
+ def setUpClass(cls) -> None:
+ cls.tmp = tempfile.TemporaryDirectory()
+ cls.events = {name: run_battery(name, Path(cls.tmp.name) / f"{name}.log")
+ for name in ("glm", "qwen", "mimo")}
+
+ @classmethod
+ def tearDownClass(cls) -> None:
+ cls.tmp.cleanup()
+
+ def streamed(self, name: str) -> dict[str, set[str]]:
+ """The streamed request's events (the one that writes sse_headers and a summary)."""
+ for events in self.events[name].values():
+ if "sse_headers" in events and "sse_summary" in events:
+ return events
+ self.fail(f"{name}: no streamed request in the log ({sorted(self.events[name])})")
+
+ def test_every_event_name_is_one_the_log_defines(self):
+ for name, requests in self.events.items():
+ for rid, events in requests.items():
+ for event in events:
+ self.assertIn(event, KNOWN_EVENTS,
+ f"{name} wrote an unknown event {event!r} (req={rid})")
+
+ def test_the_three_servers_write_the_same_events_for_a_streamed_request(self):
+ seen = {}
+ for name in ("glm", "qwen", "mimo"):
+ events = self.streamed(name)
+ # A server whose run produced no keep-alive comment has no comment fields: that is the
+ # polling interval (Qwen polls its queue once a second), not a different vocabulary.
+ commented = "sse_ping" in events
+ seen[name] = {e: f - COUNTER_FIELDS - (set() if commented else COMMENT_FIELDS)
+ for e, f in events.items()}
+ reference = seen["glm"]
+ for name, events in seen.items():
+ self.assertEqual(set(events), set(reference),
+ f"{name} writes {sorted(set(events) ^ set(reference))} that GLM does not")
+ for event, fields in events.items():
+ theirs, ours = seen["glm"][event], fields
+ self.assertEqual(theirs - OPTIONAL_FIELDS, ours - OPTIONAL_FIELDS,
+ f"{name}: fields of {event!r} differ from GLM")
+ self.assertTrue(ours - theirs <= OPTIONAL_FIELDS,
+ f"{name}: {event!r} lacks {sorted((theirs - ours) - OPTIONAL_FIELDS)}")
+
+ def test_every_request_is_traceable_by_id_on_all_three(self):
+ for name, requests in self.events.items():
+ traced = [rid for rid in requests if rid != "-"]
+ self.assertTrue(traced, f"{name}: no line carries a req= id")
+ for rid in traced:
+ self.assertIn("req_start", requests[rid], f"{name}: {rid} has no req_start")
+ self.assertTrue({"req_done", "req_refused"} & set(requests[rid]),
+ f"{name}: {rid} never closed")
+
+ def test_the_heartbeat_reports_output_accounting_on_all_three(self):
+ for name, requests in self.events.items():
+ alive = [ev["alive"] for ev in requests.values() if "alive" in ev]
+ self.assertTrue(alive, f"{name}: no alive line")
+ for fields in alive:
+ self.assertTrue({"phase", "elapsed_s"} <= fields, f"{name}: alive without phase/elapsed_s")
+ self.assertTrue({"out_events", "out_chars", "last_out_s"} <= fields,
+ f"{name}: alive without the output accounting: {sorted(fields)}")
+
+ def test_a_comment_fills_the_summary(self):
+ """The keep-alive's own accounting: a stream that wrote a comment reports it in its summary.
+
+ Whether a comment is due at all is timing (Qwen polls its queue once a second, GLM and MiMo
+ twice), so a server without one is skipped rather than failed; `sse_ping` itself is checked on
+ the server that produced it."""
+ checked = 0
+ for name in ("glm", "qwen", "mimo"):
+ pings = [ev["sse_ping"] for ev in self.events[name].values() if "sse_ping" in ev]
+ if not pings:
+ continue # this run's timing produced none
+ checked += 1
+ for fields in pings:
+ self.assertTrue({"n", "waited_s"} <= fields,
+ f"{name}: sse_ping lacks n/waited_s: {sorted(fields)}")
+ summary = self.streamed(name).get("sse_summary")
+ self.assertIsNotNone(summary, f"{name}: comments without a summary")
+ self.assertTrue(COMMENT_FIELDS <= summary,
+ f"{name}: a commented stream's summary lacks {sorted(COMMENT_FIELDS - summary)}")
+ if not checked:
+ self.skipTest("no server produced a comment in this run")
+
+ def test_the_reference_server_reports_both_counters(self):
+ # GLM is the complete implementation: the others report the one counter they keep, and that is
+ # the only field difference this test tolerates.
+ self.assertTrue({"running", "processing"} <= self.streamed("glm")["alive"])
+ for name in ("qwen", "mimo"):
+ self.assertTrue(COUNTER_FIELDS & self.streamed(name)["alive"],
+ f"{name}: the heartbeat names no in-flight counter")
+
+
+if __name__ == "__main__":
+ unittest.main()