Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
Servers: keep a silent stream alive, and count what each request sent
MangetsuCae53ebc69809
diff --git a/doc/env_vars.md b/doc/env_vars.mdindex 52d6784..0d4a84e 100644--- a/doc/env_vars.md+++ b/doc/env_vars.md@@ -993,6 +993,19 @@ The same lane also exports `EXL3_HOST_LEAN`, `EXL3_HOST_CUTS`, `EXL3_LOAD_DEVICE### Server state+#### Request log (all three servers)++| 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_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_HEALTH_DIR` (default: `~/.cache/kyojin`)Where the three servers keep the per-model start-up timings they use to weight `/health` loaddiff --git a/tools/glm/SERVE.md b/tools/glm/SERVE.mdindex 78e6a6c..fff0773 100644--- a/tools/glm/SERVE.md+++ b/tools/glm/SERVE.md@@ -239,14 +239,16 @@ queue and the worker. Events, in the order a request that goes through produces| 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` |+| `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` |+| `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` |@@ -261,10 +263,59 @@ re-encoded — the paged KV prefix can only match up to it.** A full hit has noimage-path text; the one exception is the server's own refusal `reason`, which is why a JSON parse error isreduced 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 requestis 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.+## 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"}`@@ -335,9 +386,11 @@ models:```bash# unittest: no extra dependency, which is what this checkout's venv haspython -m unittest tools.glm.test_serve tools.glm.test_serve_glm_additional \+ tools.strix_halo.test_serve_ping tools.strix_halo.test_image_cache \tools.test_serve_compat tools.test_startup_health# the same under pytest, if it is installedpython -m pytest -q tools/glm/test_serve.py tools/glm/test_serve_glm_additional.py \+ tools/strix_halo/test_serve_ping.py tools/strix_halo/test_image_cache.py \tools/test_serve_compat.py tools/test_startup_health.py```@@ -346,13 +399,16 @@ split mid-token, covering template rendering, think/tool parsing, stop strings,framing, `/v1/models`, usage, and the streamed open-`<think>` path. No GPU needed.`tools/strix_halo/test_image_cache.py` covers the shared cache itself, including both eviction policies (the-default LRU and `KYOJIN_IMAGE_CACHE_POLICY=tail`).+default LRU and `KYOJIN_IMAGE_CACHE_POLICY=tail`). `tools/strix_halo/test_serve_ping.py` covers the shared+keep-alive timing (off by default, one comment per interval, retired at the first token, one pinger per+request).`test_serve_glm_additional.py` holds the tests for what this checkout adds locally: the-request log (`KYOJIN_REQLOG`, off by default, no request text) and the image cache+request log (`KYOJIN_REQLOG`, off by default, no request text), the image cache(`--image-cache-mb` / `--image-cache-items`, the defaults of the `--image-cache-dir*` options,-the row format, what `img_cache` reports). It is a file of its own so upstream's `test_serve.py`-stays untouched and merges cleanly.+the row format, what `img_cache` reports) and the SSE keep-alive (a comment reaches the client before+the first token, and nothing at all with the switch off). It is a file of its own so upstream's+`test_serve.py` stays untouched and merges cleanly.## Lane launcherdiff --git a/tools/glm/serve.py b/tools/glm/serve.pyindex 2eda89b..937dae5 100644--- a/tools/glm/serve.py+++ b/tools/glm/serve.py@@ -33,7 +33,11 @@ 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, sanitize+from serve_reqlog import ReqLog, StreamWriter, 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.+from serve_ping import ServePingfrom image_cache import ImageEmbeddingCache, digestDEFAULT_MODEL = "~/models/glm53-exl3-td205"@@ -1030,6 +1034,12 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application: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+ # seconds. The pinger is per request; the switch and the start-up line are shared by the three servers.+ ping = ServePing.from_env(reqlog)+ app.update(ping=ping)+def reqid() -> str | None:"""The log id of the request being handled (None outside a logged route)."""return current_req.get()@@ -1041,13 +1051,23 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:st["phase"] = phasest.update(fields)+ # 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] = {}+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 Nonereqlog.log("alive", req=rid, phase=st.get("phase"), elapsed_s=round(now - st["t0"], 2),- prompt_tokens=st.get("prompt_tokens"), processing=processing, running=running)+ 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@@ -1078,6 +1098,13 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:elapsed_s=round(time.perf_counter() - started, 3))return responsefinally:+ 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@@ -1261,15 +1288,29 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:beat.cancel()reqlog.close()- async def drain(request: web.Request, cancel: asyncio.Event, out: asyncio.Queue) -> AsyncIterator[str]:+ async def drain(request: web.Request, cancel: asyncio.Event, out: asyncio.Queue,+ writer: StreamWriter | None = None, ping: ServePing | None = None,+ ping_at: float | None = None) -> AsyncIterator[str]:"""Items the worker produced for one request. Nothing is written to the client while a job isqueued 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."""+ by polling the transport. Raises ConnectionResetError and sets `cancel` when it has left.++ For a streaming reply (`writer`, `ping`, `ping_at` given), the keep-alive is asked before each+ poll whether a comment is due: the client sees that the server is still working on a prompt (or+ on a held-back tool call) it has not answered yet, which is all it can see until then."""while True:tr = request.transportif tr is None or tr.is_closing():cancel.set()+ if ping is not None:+ ping.limit()raise ConnectionResetError("client left")+ if ping is not None:+ try: # before the wait, so a stall is covered from its start+ await ping.comment(writer, ping_at or 0.0)+ except ConnectionResetError:+ cancel.set()+ raisetry:item = await asyncio.wait_for(out.get(), 0.5)except asyncio.TimeoutError:@@ -1338,9 +1379,15 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:reqlog.log("req_queued", req=body["_reqid"], path="/v1/chat/completions", queued_ahead=ahead,prompt_tokens=prompt_tokens, messages=body["_messages"], images=len(images), stream=bool(body.get("stream")))prefix = "<think>" if opens_thinking(prompt) else ""+ # 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+ # comparison per empty poll. A JSON reply has no stream to write a comment to, so `deltas` takes+ # the response per call instead of closing over one that a non-streaming request never sets.+ ping = app["ping"].per_request() if body.get("stream", False) else None+ ping_at = body["_queued_at"]- def deltas() -> AsyncIterator[str]:- return drain(request, cancel, out)+ def deltas(writer: StreamWriter | None = None) -> AsyncIterator[str]:+ return drain(request, cancel, out, writer, ping, ping_at)def usage(raw: str) -> dict[str, int]:return serve_compat.usage(prompt_tokens, engine.count_tokens(raw), int(request_stats.get("cached_tokens") or 0))@@ -1366,6 +1413,7 @@ 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 ontrack(body["_reqid"], "stream", prompt_tokens=prompt_tokens)reqlog.log("sse_headers", req=body["_reqid"], path="/v1/chat/completions")# Reasoning and prose stream as they decode. Tool calls are parsed only from complete@@ -1386,7 +1434,8 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:visible.append(time.perf_counter())reqlog.log("sse_first_content", req=body["_reqid"], first_s=round(visible[0] - body["_queued_at"], 3))key = "reasoning_content" if mode == "reasoning" else "content"- await response.write(sse(event({key: piece})))+ await writer.write(sse(event({key: piece})))+ ping.note_output() # the client has text: comments wait for the next silencedone = endif not hits:return@@ -1395,8 +1444,9 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:mode = {"</think>": "content", "<think>": "reasoning", TOOL_OPEN: "tool"}[tag]try:- await response.write(sse(event({"role": "assistant", "content": ""})))- async for delta in deltas():+ await writer.write(sse(event({"role": "assistant", "content": ""})))+ ping.note_output()+ async for delta in deltas(writer):text += deltaawait flush(False)text, _ = stop_text(text, body["_stop"])@@ -1404,10 +1454,10 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:message = parse_completion(text)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[len(prefix):])) |+ await writer.write(sse(event({"tool_calls": [dict(call, index=n)]})))+ await writer.write(sse(event({}, finish_for(message, text[len(prefix):])) |{"usage": usage(text[len(prefix):]), "timings": timings(text)}))- await response.write(b"data: [DONE]\n\n")+ 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))except ConnectionResetError:@@ -1422,9 +1472,9 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:# 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@@ -1622,11 +1672,16 @@ 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 ontrack(job["_reqid"], "stream", prompt_tokens=prompt_tokens)reqlog.log("sse_headers", req=job["_reqid"], path="/v1/completions")+ # 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()+ ping_at = job["_queued_at"]try:text, sent, stopped = "", 0, None- async for delta in drain(request, cancel, out):+ async for delta in drain(request, cancel, out, writer, ping, ping_at):text += deltacut, stopped = stop_text(text, job["_stop"])if stopped is not None:@@ -1638,13 +1693,14 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:if not sent:reqlog.log("sse_first_content", req=job["_reqid"],first_s=round(time.perf_counter() - job["_queued_at"], 3))- await response.write(sse(chunk(text[sent:safe], None)))+ await writer.write(sse(chunk(text[sent:safe], None)))+ ping.note_output()sent = safeif len(text) > sent:- await response.write(sse(chunk(text[sent:], None)))+ await writer.write(sse(chunk(text[sent:], None)))reason, usage = finish_and_usage(text, stopped)- await response.write(sse(chunk("", reason) | {"usage": usage}))- await response.write(b"data: [DONE]\n\n")+ 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))except ConnectionResetError:@@ -1656,7 +1712,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:cancel.set()reqlog.log("stream_error", req=job["_reqid"], error=sanitize(exc))try:- await response.write(sse({"error": {"message": f"{type(exc).__name__}: {exc}"}}))+ await writer.write(sse({"error": {"message": f"{type(exc).__name__}: {exc}"}}))await response.write_eof()except ConnectionError:pass@@ -1873,7 +1929,9 @@ def main() -> None:# Which run this is, in the log itself: ctx, sessions and the image-cache budget are what a later# "why was this request slow" question turns on, and they are not visible in the client's request.reqlog = app["reqlog"]+ ping = app["ping"]print(f"serve: {reqlog.describe()}", flush=True)+ print(f"serve: {ping.describe()}", flush=True)emb_cache = getattr(engine, "emb_cache", None)reqlog.log("serve_start", model=Path(args.model).name, model_id=args.model_id, pid=os.getpid(),ctx=args.max_ctx, cache_tokens=getattr(getattr(engine, "cache", None), "max_num_tokens", None),@@ -1888,7 +1946,8 @@ def main() -> None:image_cache_dir=str(engine.emb_disk.path) if getattr(engine, "emb_disk", None) else None,image_cache_dir_cap_mb=round(engine.emb_disk.max_bytes / 2 ** 20) if getattr(engine, "emb_disk", None) else None,image_cache_dir_lock_s=engine.emb_disk.lock_s if getattr(engine, "emb_disk", None) else None,- heartbeat_s=reqlog.heartbeat_s)+ heartbeat_s=reqlog.heartbeat_s,+ sse_ping_s=ping.interval_s or None)sock = startup_health.finish() # the early listener's open socket: no refused connectionif sock is not None:web.run_app(app, sock=sock)diff --git a/tools/glm/serve_ping.py b/tools/glm/serve_ping.pynew file mode 120000index 0000000..43afe37--- /dev/null+++ b/tools/glm/serve_ping.py@@ -0,0 +1 @@+../strix_halo/serve_ping.py\ No newline at end of filediff --git a/tools/glm/test_serve_glm_additional.py b/tools/glm/test_serve_glm_additional.pyindex 77ee2de..74e3aad 100644--- a/tools/glm/test_serve_glm_additional.py+++ b/tools/glm/test_serve_glm_additional.py@@ -511,5 +511,162 @@ class RequestLogTests(unittest.TestCase):self.assertIn("job_done", self.names())+class SSEKeepAliveTests(unittest.TestCase):+ """KYOJIN_SSE_PING_S: a stream that has nothing to send yet writes a ':' comment (off by default)."""++ def setUp(self):+ os.environ.pop("KYOJIN_SSE_PING_S", None)+ self.addCleanup(os.environ.pop, "KYOJIN_SSE_PING_S", None)++ def test_a_ping_reaches_the_client_before_the_first_token(self):+ os.environ["KYOJIN_SSE_PING_S"] = "0.2"+ from aiohttp.test_utils import TestClient, TestServer++ class Slow(FakeEngine):+ async def generate(self, prompt, **kwargs):+ await asyncio.sleep(0.9) # a prefill the client has to sit through+ async for piece in FakeEngine.generate(self, prompt, **kwargs):+ yield piece++ async def check():+ client = TestClient(TestServer(serve.create_app(Slow("hello"), "m", TEMPLATE)))+ await client.start_server()+ response = await client.post("/v1/chat/completions", json={+ "model": "m", "stream": True, "messages": [{"role": "user", "content": "hi"}]})+ chunks = []+ while True:+ try:+ data = await asyncio.wait_for(response.content.readany(), 5)+ except (asyncio.IncompleteReadError, asyncio.TimeoutError):+ break+ if not data:+ break+ chunks.append(data)+ await client.close()+ return b"".join(chunks)++ body = run(check())+ self.assertTrue([line for line in body.split(b"\n") if line.startswith(b":")], body[:400])+ self.assertLess(body.index(b": waiting"), body.index(b"hello")) # before the first token+ self.assertTrue(body.rstrip().endswith(b"data: [DONE]")) # the stream still ends the OpenAI way++ def test_a_ping_covers_a_tool_call_the_server_holds_back(self):+ """A reply that writes a file is withheld until the XML closes, so the client hears nothing for+ the whole generation: that silence was aborting real agent turns, and it has to be commented."""+ os.environ["KYOJIN_SSE_PING_S"] = "0.2"+ from aiohttp.test_utils import TestClient, TestServer++ # GLM's own tool-call shape (tools/glm/serve.py TOOL_OPEN): a big <arg_value> is what a+ # "write this file" call looks like, and the whole block is held until </tool_call>.+ tool_call = ("<tool_call>\nwrite_file<arg_key>path</arg_key><arg_value>/out/notes.md</arg_value>\n"+ "<arg_key>content</arg_key><arg_value>"+ + ("One transcribed line.\n" * 30) + "</arg_value>\n</tool_call>")++ class Writer(FakeEngine):+ async def generate(self, prompt, **kwargs):+ for i in range(0, len(tool_call), 3): # ~ a decode step per chunk, like the engine+ await asyncio.sleep(0.02)+ yield tool_call[i:i + 3]++ async def check():+ client = TestClient(TestServer(serve.create_app(Writer(""), "m", TEMPLATE)))+ await client.start_server()+ response = await client.post("/v1/chat/completions", json={+ "model": "m", "stream": True, "messages": [{"role": "user", "content": "hi"}]})+ chunks = []+ while True:+ try:+ data = await asyncio.wait_for(response.content.readany(), 5)+ except (asyncio.IncompleteReadError, asyncio.TimeoutError):+ break+ if not data:+ break+ chunks.append(data)+ await client.close()+ return b"".join(chunks)++ body = run(check())+ self.assertGreaterEqual(body.count(b": waiting"), 2, body[:400]) # not only before the first byte+ # the call itself still arrives whole, once, and the stream still ends the OpenAI way+ self.assertIn(b'"tool_calls"', body) # the held call still arrives, whole+ self.assertLessEqual(body.count(b"tool_calls"), 2) # once as a message, once in usage+ self.assertTrue(body.rstrip().endswith(b"data: [DONE]"))++ def test_the_log_says_whether_the_server_was_writing(self):+ """The accounting that separates "the client showed nothing" from "the server sent nothing".++ A streaming reply logs `out_events`/`out_chars` per heartbeat and one `sse_summary` at the end;+ a held-back tool call is the case where the numbers stay flat while the engine decodes.+ """+ import tempfile+ tmp = tempfile.TemporaryDirectory()+ self.addCleanup(tmp.cleanup)+ os.environ["KYOJIN_REQLOG"] = str(Path(tmp.name) / "requests.log")+ os.environ["KYOJIN_REQLOG_HEARTBEAT_S"] = "0.2"+ self.addCleanup(os.environ.pop, "KYOJIN_REQLOG", None)+ self.addCleanup(os.environ.pop, "KYOJIN_REQLOG_HEARTBEAT_S", None)+ from aiohttp.test_utils import TestClient, TestServer++ class Slow(FakeEngine):+ async def generate(self, prompt, **kwargs):+ await asyncio.sleep(1.2) # heartbeats land while nothing is sent+ async for piece in FakeEngine.generate(self, prompt, **kwargs):+ yield piece++ async def check():+ client = TestClient(TestServer(serve.create_app(Slow("hello"), "m", TEMPLATE)))+ await client.start_server()+ response = await client.post("/v1/chat/completions", json={+ "model": "m", "stream": True, "messages": [{"role": "user", "content": "hi"}]})+ body = await response.read()+ await client.close()+ return body++ run(check())+ events = []+ for line in Path(os.environ["KYOJIN_REQLOG"]).read_text(encoding="utf-8").splitlines():+ parts = line.split(" ")+ fields = {}+ for item in parts[2:]:+ key, _, value = item.partition("=")+ fields[key] = value.strip('"')+ events.append((parts[1], fields))+ alive = [f for name, f in events if name == "alive"]+ self.assertTrue(alive)+ self.assertTrue(all({"out_events", "out_chars", "last_out_s"} <= set(f) for f in alive), alive[:3])+ # while the engine holds everything back, the counters stand still across heartbeats — which is+ # exactly the evidence the incident was missing (it cannot be reconstructed after the fact)+ stalled = [f for f in alive if f["phase"] in ("prefill", "decode")]+ self.assertGreaterEqual(len(stalled), 2, alive[:3])+ self.assertEqual({f["out_events"] for f in stalled}, {"1"}, stalled[:3])+ summary = [f for name, f in events if name == "sse_summary"]+ self.assertEqual(len(summary), 1, summary)+ self.assertGreaterEqual(int(summary[0]["out_events"]), 2) # role chunk + content+ self.assertGreater(int(summary[0]["out_chars"]), 0)+ self.assertEqual(summary[0].get("errors", "0"), "0")++ def test_nothing_is_written_when_the_switch_is_off(self):+ from aiohttp.test_utils import TestClient, TestServer++ class Slow(FakeEngine):+ async def generate(self, prompt, **kwargs):+ await asyncio.sleep(0.5)+ async for piece in FakeEngine.generate(self, prompt, **kwargs):+ yield piece++ async def check():+ client = TestClient(TestServer(serve.create_app(Slow("hello"), "m", TEMPLATE)))+ await client.start_server()+ response = await client.post("/v1/chat/completions", json={+ "model": "m", "stream": True, "messages": [{"role": "user", "content": "hi"}]})+ body = await response.read()+ await client.close()+ return body++ body = run(check())+ self.assertEqual([line for line in body.split(b"\n") if line.startswith(b":")], [])+ self.assertIn(b"hello", body)++if __name__ == "__main__":unittest.main()diff --git a/tools/mimo/SERVE.md b/tools/mimo/SERVE.mdindex a7c07b6..a5c9893 100644--- a/tools/mimo/SERVE.md+++ b/tools/mimo/SERVE.md@@ -50,6 +50,11 @@ 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 onlyonce 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_spectok_round`. Useful while tuning.diff --git a/tools/mimo/serve.py b/tools/mimo/serve.pyindex 1220e5d..f2bb61a 100644--- a/tools/mimo/serve.py+++ b/tools/mimo/serve.py@@ -35,6 +35,13 @@ sys.path.append(str(Path(__file__).resolve().parent.parent))import startup_health # noqa: E402 (GET /health with load progress while the model loads)# serve_metrics.py is a symlink to the shared tools/strix_halo/serve_metrics.pyfrom serve_metrics import Metrics+# 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 a long prefill does+# not look like a hung server to a client that only watches its socket.+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, StreamWriterfrom image_cache import ImageEmbeddingCache, digestDEFAULT_MODEL = os.path.expanduser("~/models/mimo26-exl3")@@ -504,6 +511,11 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:processing = 0 # admitted requests; closure, app config is immutable after startupapp = web.Application(client_max_size=64 * 1024**2, middlewares=[startup_health.json_errors_middleware()])app.update(engine=engine, model_id=model_id, template=template, queue=queue, metrics=Metrics())+ # 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).+ app.update(reqlog=ReqLog.from_env(server="mimo"))def observe(st: dict[str, Any], prompt_tokens: int) -> None:accepted = int(st.get("accepted_draft_tokens", 0))@@ -576,15 +588,28 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:async def close(app_: web.Application) -> None:app_["worker_task"].cancel()- async def drain(request: web.Request, cancel: asyncio.Event, out: asyncio.Queue) -> AsyncIterator[str]:+ 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]:"""Items the worker produced for one request. Nothing is written to the client while a job isqueued 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."""+ by polling the transport. Raises ConnectionResetError and sets `cancel` when it has left.+ `ping` (a streaming request) is asked before every poll whether a keep-alive comment is due,+ and `ping_at` is the moment the client's wait started: a comment is the only thing it can see+ while the engine works on a prompt (or on a tool call) it has not answered yet."""while True:tr = request.transportif tr is None or tr.is_closing():cancel.set()+ if ping is not None:+ ping.limit()raise ConnectionResetError("client left")+ if ping is not None:+ try: # before the wait, so a stall is covered from its start+ await ping.comment(writer, ping_at)+ except ConnectionResetError:+ cancel.set()+ raisetry:item = await asyncio.wait_for(out.get(), 0.5)except asyncio.TimeoutError:@@ -645,9 +670,14 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:cancel = body["_cancel"] = asyncio.Event()await queue.put((body, out, request_stats))# 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+ # per call: closing over one that a non-streaming request never sets leaves the cell unbound.+ ping = app["ping"].per_request() if body.get("stream", False) else None+ ping_at = time.perf_counter()- def deltas() -> AsyncIterator[str]:- return drain(request, cancel, out)+ def deltas(writer: StreamWriter | None = None) -> AsyncIterator[str]:+ return drain(request, cancel, out, writer, ping, ping_at)def usage(raw: str) -> dict[str, int]:completion_tokens = engine.count_tokens(raw)@@ -676,6 +706,7 @@ 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)# 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"@@ -694,6 +725,7 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:if piece:key = "reasoning_content" if mode == "reasoning" else "content"await response.write(sse(event({key: piece})))+ ping.note_output() # the client has text: comments wait for the next silencedone = endif not hits:return@@ -703,7 +735,8 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:try:await response.write(sse(event({"role": "assistant", "content": ""})))- async for delta in deltas():+ ping.note_output()+ async for delta in deltas(writer):text += deltaawait flush(False)text, _ = stop_text(text, body["_stop"])@@ -733,6 +766,9 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:await response.write_eof()except ConnectionError:pass+ finally:+ for event, fields in writer.stats.lines():+ reqlog.log(event, path="/v1/chat/completions", **fields)return responsetry:@@ -985,6 +1021,8 @@ def main() -> None:f"spec_gate={engine.spec_gate_on} ctx={ctx} "f"max_position={config_max_position(engine.config)} vision={engine.supports_vision}", flush=True)app = create_app(engine, args.model_id, template)+ print(f"msrv: {app['ping'].describe()}", flush=True)+ print(f"msrv: {app['reqlog'].describe()}", flush=True)sock = startup_health.finish() # the early listener's open socket: no refused connectionif sock is not None:web.run_app(app, sock=sock)diff --git a/tools/mimo/serve_ping.py b/tools/mimo/serve_ping.pynew file mode 120000index 0000000..43afe37--- /dev/null+++ b/tools/mimo/serve_ping.py@@ -0,0 +1 @@+../strix_halo/serve_ping.py\ No newline at end of filediff --git a/tools/mimo/serve_reqlog.py b/tools/mimo/serve_reqlog.pynew file mode 120000index 0000000..7a3e5c1--- /dev/null+++ b/tools/mimo/serve_reqlog.py@@ -0,0 +1 @@+../strix_halo/serve_reqlog.py\ No newline at end of filediff --git a/tools/mimo/test_serve.py b/tools/mimo/test_serve.pyindex 5577d82..e51e1f8 100644--- a/tools/mimo/test_serve.py+++ b/tools/mimo/test_serve.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport asyncioimport json+import osimport sysimport unittestfrom pathlib import Path@@ -635,5 +636,68 @@ class ImageEmbeddingReuseTests(unittest.TestCase):self.assertEqual(len(calls), 2)+class SSEKeepAliveTests(unittest.TestCase):+ """KYOJIN_SSE_PING_S: a stream that has nothing to send yet writes a ':' comment (off by default)."""++ def setUp(self):+ os.environ.pop("KYOJIN_SSE_PING_S", None)+ self.addCleanup(os.environ.pop, "KYOJIN_SSE_PING_S", None)++ def test_a_ping_reaches_the_client_before_the_first_token(self):+ os.environ["KYOJIN_SSE_PING_S"] = "0.2"+ from aiohttp.test_utils import TestClient, TestServer++ class Slow(FakeEngine):+ async def generate(self, prompt, **kwargs):+ await asyncio.sleep(0.9) # a prefill the client has to sit through+ async for piece in FakeEngine.generate(self, prompt, **kwargs):+ yield piece++ async def check():+ client = TestClient(TestServer(serve.create_app(Slow("hello"), "m", TEMPLATE)))+ await client.start_server()+ r = await client.post("/v1/chat/completions", json={+ "model": "m", "stream": True, "messages": [{"role": "user", "content": "hi"}]})+ chunks = []+ while True:+ try:+ data = await asyncio.wait_for(r.content.readany(), 5)+ except (asyncio.IncompleteReadError, asyncio.TimeoutError):+ break+ if not data:+ break+ chunks.append(data)+ await client.close()+ return b"".join(chunks)++ body = run(check())+ pings = [line for line in body.split(b"\n") if line.startswith(b":")]+ self.assertTrue(pings, body[:400])+ self.assertLess(body.index(b": waiting"), body.index(b"hello")) # before the first token+ self.assertTrue(body.rstrip().endswith(b"data: [DONE]")) # the stream still ends the OpenAI way++ def test_nothing_is_written_when_the_switch_is_off(self):+ from aiohttp.test_utils import TestClient, TestServer++ class Slow(FakeEngine):+ async def generate(self, prompt, **kwargs):+ await asyncio.sleep(0.5)+ async for piece in FakeEngine.generate(self, prompt, **kwargs):+ yield piece++ async def check():+ client = TestClient(TestServer(serve.create_app(Slow("hello"), "m", TEMPLATE)))+ await client.start_server()+ r = await client.post("/v1/chat/completions", json={+ "model": "m", "stream": True, "messages": [{"role": "user", "content": "hi"}]})+ body = await r.read()+ await client.close()+ return body++ body = run(check())+ self.assertEqual([line for line in body.split(b"\n") if line.startswith(b":")], [])+ self.assertIn(b"hello", body)++if __name__ == "__main__":unittest.main()diff --git a/tools/qwen/SERVE.md b/tools/qwen/SERVE.mdindex 3dc4610..cba7014 100644--- a/tools/qwen/SERVE.md+++ b/tools/qwen/SERVE.md@@ -91,6 +91,11 @@ 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. Switchingspeculative 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]]`):diff --git a/tools/qwen/serve.py b/tools/qwen/serve.pyindex ae09de7..74193f1 100644--- a/tools/qwen/serve.py+++ b/tools/qwen/serve.py@@ -42,6 +42,13 @@ sys.path.append(str(HERE.parent))import startup_health # noqa: E402 (GET /health with load progress while the model loads)import image_cache # noqa: E402 (shared bounded LRU of image embeddings; symlink to tools/strix_halo)import serve_compat # noqa: E402 (vLLM-style token-id prompts, cache_salt, /tokenize, usage details)+# 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 a long prefill does+# not look like a hung server to a client that only watches its socket.+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: E402def _load_mimo():@@ -1258,6 +1265,11 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Anadmit_lock = asyncio.Lock()app = web.Application(client_max_size=64 * 1024**2, middlewares=[startup_health.json_errors_middleware()])app.update(engine=engine, model_id=model_id, template=template, 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).+ app.update(reqlog=ReqLog.from_env(server="qwen"))def err(status: int, message: str) -> web.Response:return web.json_response({"error": {"message": message, "type": "invalid_request_error", "code": status}},@@ -1435,6 +1447,7 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Anout: asyncio.Queue = asyncio.Queue()await queue.put((job, out))+ queued_at = time.perf_counter() # the wait a streaming client's comments count fromdef finish_and_stats(stats: dict[str, Any], text: str, has_calls: bool):n_new = int(stats.get("new_tokens") or engine.count_tokens(text))@@ -1461,13 +1474,23 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Antimings["rejected_draft_tokens"] = int(stats["rejected_draft_tokens"])return reason, usage, timings- async def pieces() -> AsyncIterator[str | dict]:+ async def pieces(writer: StreamWriter | None = None, ping: ServePing | None = None,+ ping_at: float = 0.0) -> AsyncIterator[str | dict]:while True:# a non-streaming client that hung up is only noticed here (nothing is written until the end)tr = request.transportif tr is None or tr.is_closing():job["cancel"].set()raise ConnectionResetError("client left")+ if ping is not None:+ # A ':' comment while the engine works, checked before every poll: the only thing a+ # streaming client can see until the prompt (or a held-back tool call) is done. It is+ # None for a JSON reply.+ try:+ await ping.comment(writer, ping_at)+ except ConnectionResetError:+ job["cancel"].set()+ raisetry:item = await asyncio.wait_for(out.get(), 1.0)except asyncio.TimeoutError:@@ -1483,10 +1506,13 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Anif 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_attry:- await response.write(sse(event({"role": "assistant", "content": ""})))+ await writer.write(sse(event({"role": "assistant", "content": ""})))+ ping.note_output()stats, full = {}, ""- async for item in pieces():+ async for item in pieces(writer, ping, ping_at):if isinstance(item, dict):stats = itemcontinue@@ -1500,20 +1526,21 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Anfull += itemfor kind, piece in sp.feed(item):key = "reasoning_content" if kind == "reasoning" else "content"- await response.write(sse(event({key: piece})))+ await writer.write(sse(event({key: piece})))+ ping.note_output() # the client has text: comments wait for the next silencefor kind, piece in sp.finish():key = "reasoning_content" if kind == "reasoning" else "content"- await response.write(sse(event({key: piece})))+ await writer.write(sse(event({key: piece})))calls = parse_tool_calls(sp.tool_text, job["tools"])if calls:for i, c in enumerate(calls): # one stream message per call: some clients read only the first call of a message- await response.write(sse(event({"tool_calls": [dict(c, index=i)]})))+ await writer.write(sse(event({"tool_calls": [dict(c, index=i)]})))reason, usage, timings = finish_and_stats(stats, full, bool(calls))final = event({}, reason) | {"usage": usage, "timings": timings}if job["return_token_ids"]:final["token_ids"] = stats.get("token_ids", [])- await response.write(sse(final))- await response.write(b"data: [DONE]\n\n")+ await writer.write(sse(final))+ await writer.write(b"data: [DONE]\n\n")await response.write_eof()except ConnectionResetError: # client left: stop the job, no tracebackjob["cancel"].set()@@ -1523,13 +1550,16 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Anexcept Exception as exc: # noqa: BLE001job["cancel"].set()try:- await response.write(sse({"error": {"message": f"{type(exc).__name__}: {exc}"}}))+ 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".- await response.write(sse(event({}, "error")))- await response.write(b"data: [DONE]\n\n")+ 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 responsetry:@@ -1733,13 +1763,23 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Anout: asyncio.Queue = asyncio.Queue()await queue.put((job, out))+ queued_at = time.perf_counter() # the wait a streaming client's comments count from- async def pieces() -> AsyncIterator[str | dict]:+ async def pieces(writer: StreamWriter | None = None, ping: ServePing | None = None,+ ping_at: float = 0.0) -> AsyncIterator[str | dict]:while True:tr = request.transportif tr is None or tr.is_closing():job["cancel"].set()raise ConnectionResetError("client left")+ if ping is not None:+ # A ':' comment while the engine works, checked before every poll: the only thing a+ # streaming client can see until the prompt (or a held-back tool call) is done.+ try:+ await ping.comment(writer, ping_at)+ except ConnectionResetError:+ job["cancel"].set()+ raisetry:item = await asyncio.wait_for(out.get(), 1.0)except asyncio.TimeoutError:@@ -1754,17 +1794,19 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Anif 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_attry:stats, full = {}, ""- async for item in pieces():+ async for item in pieces(writer, ping, ping_at):if isinstance(item, dict):stats = itemelif not isinstance(item, Retract):full += item- await response.write(sse(chunk(item, None)))+ await writer.write(sse(chunk(item, None)))reason, usage = reason_usage(stats, full)- await response.write(sse(chunk("", reason) | {"usage": usage}))- await response.write(b"data: [DONE]\n\n")+ await writer.write(sse(chunk("", reason) | {"usage": usage}))+ await writer.write(b"data: [DONE]\n\n")await response.write_eof()except ConnectionResetError:job["cancel"].set()@@ -1774,10 +1816,13 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Anexcept Exception as exc: # noqa: BLE001job["cancel"].set()try:- await response.write(sse({"error": {"message": f"{type(exc).__name__}: {exc}"}}))+ 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 responsetry:@@ -1933,6 +1978,8 @@ def main() -> None:startup_health.abort(f"{type(exc).__name__}: {exc}")raiseapp = create_app(engine, args.model_id, template, defaults, args.default_max_tokens)+ print(f"qserve: {app['ping'].describe()}", flush=True)+ print(f"qserve: {app['reqlog'].describe()}", flush=True)async def serve() -> None:runner = web.AppRunner(app)diff --git a/tools/qwen/serve_ping.py b/tools/qwen/serve_ping.pynew file mode 120000index 0000000..43afe37--- /dev/null+++ b/tools/qwen/serve_ping.py@@ -0,0 +1 @@+../strix_halo/serve_ping.py\ No newline at end of filediff --git a/tools/qwen/serve_reqlog.py b/tools/qwen/serve_reqlog.pynew file mode 120000index 0000000..7a3e5c1--- /dev/null+++ b/tools/qwen/serve_reqlog.py@@ -0,0 +1 @@+../strix_halo/serve_reqlog.py\ No newline at end of filediff --git a/tools/qwen/test_serve.py b/tools/qwen/test_serve.pyindex 64237a9..7b12afe 100644--- a/tools/qwen/test_serve.py+++ b/tools/qwen/test_serve.py@@ -983,5 +983,59 @@ class VllmCompatTests(unittest.TestCase):self.assertEqual(self.post(FakeEngine("x"), "/v1/completions", {"model": "m", "prompt": "hi", "cache_salt": "a"})[0], 400)+class SSEKeepAliveTests(unittest.TestCase):+ """KYOJIN_SSE_PING_S: a stream that has nothing to send yet writes a ':' comment (off by default)."""++ def setUp(self):+ os.environ.pop("KYOJIN_SSE_PING_S", None)+ self.addCleanup(os.environ.pop, "KYOJIN_SSE_PING_S", None)++ def test_a_ping_reaches_the_client_before_the_first_token(self):+ os.environ["KYOJIN_SSE_PING_S"] = "0.2"++ class Slow(FakeEngine):+ async def generate(self, prompt, **kw):+ # this server polls its queue once a second, so the wait has to outlast a poll+ await asyncio.sleep(2.3) # a prefill the client has to sit through+ async for piece in FakeEngine.generate(self, prompt, **kw):+ yield piece++ async def fn(client):+ r = await client.post("/v1/chat/completions", json={+ "model": "m", "stream": True, "messages": [{"role": "user", "content": "hi"}]})+ chunks = []+ while True:+ try:+ data = await asyncio.wait_for(r.content.readany(), 5)+ except (asyncio.IncompleteReadError, asyncio.TimeoutError):+ break+ if not data:+ break+ chunks.append(data)+ return b"".join(chunks)++ body = with_client(Slow("hello"), fn)+ self.assertTrue([line for line in body.split(b"\n") if line.startswith(b":")], body[:400])+ # this template opens a <think> block, so the first visible token is reasoning content ("hel")+ self.assertLess(body.index(b": waiting"), body.index(b"hel")) # before the first token+ self.assertTrue(body.rstrip().endswith(b"data: [DONE]")) # the stream still ends the OpenAI way++ def test_nothing_is_written_when_the_switch_is_off(self):+ class Slow(FakeEngine):+ async def generate(self, prompt, **kw):+ await asyncio.sleep(1.3)+ async for piece in FakeEngine.generate(self, prompt, **kw):+ yield piece++ async def fn(client):+ r = await client.post("/v1/chat/completions", json={+ "model": "m", "stream": True, "messages": [{"role": "user", "content": "hi"}]})+ return await r.read()++ body = with_client(Slow("hello"), fn)+ self.assertEqual([line for line in body.split(b"\n") if line.startswith(b":")], [])+ self.assertIn(b"hel", body)++if __name__ == "__main__":unittest.main()diff --git a/tools/strix_halo/serve_ping.py b/tools/strix_halo/serve_ping.pynew file mode 100644index 0000000..3ad43b5--- /dev/null+++ b/tools/strix_halo/serve_ping.py@@ -0,0 +1,155 @@+#!/usr/bin/env python3+"""SSE keep-alive for the kyojin servers: a comment line whenever a stream has nothing to send.++A streaming request is answered with its SSE headers and one empty role chunk, and after that the+client hears nothing until text is ready. Two silences are long enough to matter:++* the prefill of a long prompt — a large image conversation is hundreds of thousands of tokens, and a+ client that aborts a stream it has not heard from for a couple of minutes aborts a server that is+ working; an aborted request leaves no reusable state behind, so the retry pays the whole prefill again;+* the decode of a reply that writes a file — a tool call is parsed only from complete XML, so the whole+ `<tool_call>` is held back and a 7 KB `content` argument is minutes of generation that the client+ never sees (`probe` runs measured 99 s of decode with nothing on the wire).++This writes an SSE **comment** — a line starting with ':', which every event-stream client skips — after+N seconds without a data event, whenever that happens, so a client that only watches its socket sees+that the server is alive and a client that never sees one can report a genuinely dead server.++**Off unless asked for.** With KYOJIN_SSE_PING_S unset (or 0) nothing is ever written:++ KYOJIN_SSE_PING_S=15 # seconds of silence before one ': waiting <n> s' comment line++The interval is read when a request starts streaming, and the server prints one line at start-up+either way, so the switch stays discoverable when a request does go quiet. The class holds timers+only: the caller writes the comment to its own StreamResponse, and every request makes its own+pinger, which keeps this module free of aiohttp and gives the three servers exactly one+implementation of the timing rules.+"""+from __future__ import annotations++import os+import sys+import time+from typing import Any+++class ServePing:+ """Times the keep-alive comments of one streaming request. Cheap enough to call on every poll.++ A comment is due when the client has heard nothing for the interval, whatever the server is doing:+ prefilling a long prompt, waiting in the queue, or decoding. The last case matters because a tool+ call is parsed only from complete XML, so a reply that writes a large file holds its whole+ `<tool_call>` back and a client watching only its socket sees nothing while the model types it.+ `note_output` is called with every data event the request writes, which is what ends a silence.+ """++ def __init__(self, interval_s: float = 0.0, reqlog: Any = None) -> None:+ self.interval_s = max(0.0, float(interval_s))+ self.reqlog = reqlog+ self.enabled = self.interval_s > 0.0+ self.sent = 0 # comment lines written; for the log and for tests+ self._last_sent = 0.0 # perf_counter of the last comment (one per interval, not per poll)+ self._last_output = 0.0 # perf_counter of the last data event this request wrote++ @classmethod+ def from_env(cls, reqlog: Any = None) -> "ServePing":+ """Read KYOJIN_SSE_PING_S. A value that is not a positive number means off, with one line to+ stderr: this is a client-visible protocol switch, so a server that was asked for it and did+ not get it should say so rather than look like a client that ignores the comments."""+ raw = os.environ.get("KYOJIN_SSE_PING_S", "").strip()+ try:+ interval = float(raw) if raw else 0.0+ except ValueError:+ print(f"serve: SSE keep-alive off (KYOJIN_SSE_PING_S={raw!r} is not a number)",+ file=sys.stderr, flush=True)+ return cls(0.0, reqlog)+ if raw and interval <= 0: # "0" is the documented way of asking for off, so it stays quiet+ if interval < 0:+ print(f"serve: SSE keep-alive off (KYOJIN_SSE_PING_S={raw!r} is negative)",+ file=sys.stderr, flush=True)+ return cls(0.0, reqlog)+ return cls(interval, reqlog)++ def per_request(self) -> "ServePing":+ """This request's own timers, from the application's settings.++ The interval is fixed for the life of a server, so it is parsed once (from_env) and copied+ into one pinger per streaming request: its timers belong to a request, and two+ sessions pinging into the same object would time each other's comments."""+ return ServePing(self.interval_s, self.reqlog) if self.enabled else self++ def describe(self) -> str:+ """One start-up line, so an operator can tell whether the comments are on and how often."""+ if not self.enabled:+ return "SSE keep-alive off (set KYOJIN_SSE_PING_S=<seconds> to hold a silent stream open)"+ return (f"SSE keep-alive: a comment line after {self.interval_s:g} s without output "+ f"(KYOJIN_SSE_PING_S)")++ def due(self, started: float) -> float | None:+ """Whether a comment is due, and the seconds to name in it (None = not now).++ `started` is the perf_counter the request's wait began at, so the comment counts what the+ client has actually been waiting for. Due means the interval has passed since that start,+ since the request's last data event, and since the last comment itself — so a stream that is+ writing never gets comments, and one that has gone quiet gets them even while the engine keeps+ producing (a held-back tool call is decoded the whole time and sent at the end).++ Checking writes nothing: the caller writes the comment and then calls `sent_comment`, which is+ what makes this usable from a loop that must also poll for output.+ """+ if not self.enabled:+ return None+ now = time.perf_counter()+ for mark in (started, self._last_output, self._last_sent):+ if now - mark < self.interval_s:+ return None+ return now - started++ def sent_comment(self, waited: float) -> None:+ """Record a comment the caller just wrote, and log the number of the request's comments."""+ self._last_sent = time.perf_counter()+ self.sent += 1+ if self.reqlog is not None:+ self.reqlog.log("sse_ping", n=self.sent, waited_s=round(waited, 2))++ async def comment(self, writer: Any, started: float) -> None:+ """Write one comment if the client has waited for it. Never returns with a dead connection.++ This is the whole keep-alive, one call, so the three servers' polling loops grow by one line:+ they call it before every poll, because the moment a stall begins is not a moment a poll+ happens to time out — a reply that holds a large tool call back keeps producing deltas (and+ writing nothing to the client) the whole time it is decoded.++ `writer` is the request's StreamWriter (or None for a reply with no stream). Comments are+ counted as comments, not as data events, so a flat `out_events` in the log still means the+ model wrote nothing the client could render.+ """+ if writer is None:+ return+ waited = self.due(started)+ if waited is None:+ return+ data = f": waiting {waited:.0f} s\n\n".encode()+ stats = getattr(writer, "stats", None)+ try:+ if stats is None: # a bare StreamResponse: nothing to record into+ await writer.write(data)+ else: # counted as a comment, not as a data event+ await writer.response.write(data)+ except ConnectionError as exc:+ self.limit()+ raise ConnectionResetError("client left") from exc+ if stats is not None:+ stats.note_comment(len(data))+ self.sent_comment(waited)++ def note_output(self) -> None:+ """The request wrote a data event: the client has something, so the silence clock restarts.++ A comment comes again only after the interval has passed with nothing written (which is what+ a decode that is holding a tool call back looks like from the socket)."""+ self._last_output = time.perf_counter()++ def limit(self) -> None:+ """Stop commenting: the request is over, or nobody is left to write to."""+ self.enabled = Falsediff --git a/tools/strix_halo/serve_reqlog.py b/tools/strix_halo/serve_reqlog.pyindex cfcc5d1..d09d34e 100644--- a/tools/strix_halo/serve_reqlog.py+++ b/tools/strix_halo/serve_reqlog.py@@ -4,7 +4,9 @@A request that is refused, queued or prefilling produces **no client-visible output**, so a report of"the server went silent" cannot be lined up with what the server was doing. This writes one line perlifecycle event, plus a heartbeat while a job is queued or running, so the two timelines can be-compared afterwards.+compared afterwards. The heartbeat and the per-request summary carry the request's **output+accounting** (`out_events`, `out_chars`, `last_out_s`), which is what separates "the server was+writing to a client that did not show it" from "the server had nothing to write".**Off unless asked for.** With KYOJIN_REQLOG unset (or 0/off/none/no/false/empty) nothing is opened andevery call is a no-op, so a default deployment behaves exactly as before. The server prints one line at@@ -56,6 +58,78 @@ def _fmt(value: Any) -> str:return f'"{text}"' if (" " in text or "=" in text) else text+class StreamStats:+ """What one streaming request actually wrote to its client: bytes, data events, silence.++ A client that reports "the server went silent" is believed or not depending on whether the bytes+ were on the wire, and the heartbeat alone cannot tell the two apart. Every write of a streaming+ reply goes through this, so at any moment `out_events` / `out_chars` say what the client has been+ sent and `last_out_s` how long ago; a reply whose engine is decoding into a held-back tool call+ shows up as a flat line, and one that is streaming shows a rate.+ """++ def __init__(self) -> None:+ self.bytes = 0+ self.events = 0+ self.comments = 0 # SSE keep-alive comments (not data events)+ self.comment_bytes = 0+ self.errors = 0+ self.last_error: str | None = None+ self.t0 = time.perf_counter()+ self.last_data = self.t0+ self.last_comment = self.t0++ def note(self, n: int) -> None:+ self.bytes += n+ self.events += 1+ self.last_data = time.perf_counter()++ def note_comment(self, n: int) -> None:+ self.comments += 1+ self.comment_bytes += n+ self.last_comment = time.perf_counter()++ def fail(self, exc: BaseException) -> None:+ self.errors += 1+ self.last_error = sanitize(exc)++ def since_data_s(self) -> float:+ """Seconds since the last **data event**: comments do not count as content.++ This is the number that matters when a client reports silence — a reply that is decoding into a+ held-back tool call sends comments (which keep the socket alive) and no events at all, and this+ says how long that has been going on.+ """+ return time.perf_counter() - self.last_data++ def lines(self) -> list[tuple[str, dict[str, Any]]]:+ """The summary event and its fields, in the order they read best."""+ return [("sse_summary", {+ "out_events": self.events, "out_chars": self.bytes, "last_out_s": round(self.since_data_s(), 2),+ "comments": self.comments or None, "comment_chars": self.comment_bytes or None,+ "last_comment_s": round(time.perf_counter() - self.last_comment, 2) if self.comments else None,+ "errors": self.errors or None, "error": self.last_error})]+++class StreamWriter:+ """A StreamResponse that records what it wrote (see `StreamStats`). One per streaming reply."""++ def __init__(self, response: Any, stats: StreamStats | None = None) -> None:+ self.response = response+ self.stats = stats if stats is not None else StreamStats()++ async def write(self, data: bytes) -> None:+ try:+ await self.response.write(data)+ except BaseException as exc: # noqa: BLE001 counted, then re-raised+ self.stats.fail(exc)+ raise+ self.stats.note(len(data))++ async def write_eof(self) -> None:+ await self.response.write_eof()++class ReqLog:"""Append-only event log. Every method is safe to call when logging is disabled or broken."""diff --git a/tools/strix_halo/test_serve_ping.py b/tools/strix_halo/test_serve_ping.pynew file mode 100644index 0000000..9830436--- /dev/null+++ b/tools/strix_halo/test_serve_ping.py@@ -0,0 +1,161 @@+#!/usr/bin/env python3+"""Model-free tests for the shared SSE keep-alive (tools/strix_halo/serve_ping.py).++The timing rules live in one place because the three servers share them, so they are tested here+once: when a comment is due, that it is one per interval and not one per poll, that a retired+pinger stays quiet, and that the switch is off unless KYOJIN_SSE_PING_S says otherwise.++ kyojin/.venv/bin/python -m unittest tools.strix_halo.test_serve_ping # 8 tests, no GPU, no model+"""+from __future__ import annotations++import contextlib+import importlib.util+import io+import os+import time+import unittest+from pathlib import Path++# Load the shared module by its own path: `serve_ping` is also a symlink in tools/glm, tools/qwen and+# tools/mimo, and a test run that imported one of those first would otherwise hand this file a second+# copy of the class (tests/ and the servers must see the same one).+_spec = importlib.util.spec_from_file_location("strix_halo_serve_ping", Path(__file__).with_name("serve_ping.py"))+_serve_ping = importlib.util.module_from_spec(_spec)+_spec.loader.exec_module(_serve_ping)+ServePing = _serve_ping.ServePing+++class SwitchTests(unittest.TestCase):+ """KYOJIN_SSE_PING_S: unset or 0 means off, a positive number is the interval, junk says so once."""++ def setUp(self):+ os.environ.pop("KYOJIN_SSE_PING_S", None)+ self.addCleanup(os.environ.pop, "KYOJIN_SSE_PING_S", None)++ def stderr(self) -> str:+ buf = io.StringIO()+ with contextlib.redirect_stderr(buf):+ return buf.getvalue()++ def test_off_by_default(self):+ ping = ServePing.from_env()+ self.assertFalse(ping.enabled)+ self.assertEqual(ping.interval_s, 0.0)+ self.assertIn("off", ping.describe())+ self.assertIsNone(ping.due(time.perf_counter())) # and never writes anything++ def test_zero_is_off_and_says_nothing(self):+ os.environ["KYOJIN_SSE_PING_S"] = "0"+ self.assertFalse(ServePing.from_env().enabled)+ self.assertEqual(self.stderr(), "") # asking for off is not a mistake++ def test_an_interval_is_read_and_described(self):+ os.environ["KYOJIN_SSE_PING_S"] = "15"+ ping = ServePing.from_env()+ self.assertTrue(ping.enabled)+ self.assertEqual(ping.interval_s, 15.0)+ self.assertIn("15 s", ping.describe())++ def test_junk_and_negative_values_are_off_with_one_line(self):+ for raw in ("soon", "-3"):+ os.environ["KYOJIN_SSE_PING_S"] = raw+ with self.subTest(raw=raw):+ buf = io.StringIO()+ with contextlib.redirect_stderr(buf):+ ping = ServePing.from_env()+ self.assertFalse(ping.enabled)+ self.assertIn("KYOJIN_SSE_PING_S", buf.getvalue()) # a switch that was asked for is reported+++class TimingTests(unittest.TestCase):+ """A comment covers every silence (queue, prefill, decode), once per interval, and never during output."""++ def test_a_comment_is_due_after_the_interval_and_not_before(self):+ ping = ServePing(interval_s=0.2)+ started = time.perf_counter()+ self.assertIsNone(ping.due(started)) # nothing due while the client just arrived+ time.sleep(0.25)+ waited = ping.due(started)+ self.assertIsNotNone(waited)+ self.assertGreaterEqual(waited, 0.2)+ self.assertEqual(ping.sent, 0) # asking is not sending+ ping.sent_comment(waited)+ self.assertEqual(ping.sent, 1)++ def test_only_one_comment_per_interval_even_though_polling_is_faster(self):+ ping = ServePing(interval_s=0.25)+ started = time.perf_counter()+ while time.perf_counter() - started < 0.15: # the servers poll twice a second+ time.sleep(0.01)+ ping.due(started)+ self.assertEqual(ping.sent, 0) # polling is not what makes a comment due+ time.sleep(0.15)+ ping.sent_comment(ping.due(started))+ self.assertIsNone(ping.due(started)) # and not a second one right after+ self.assertEqual(ping.sent, 1)++ def test_a_retired_pinger_stays_quiet(self):+ ping = ServePing(interval_s=0.1)+ started = time.perf_counter()+ time.sleep(0.15)+ ping.sent_comment(ping.due(started))+ ping.limit() # the stream is over / nobody is listening+ time.sleep(0.15)+ self.assertIsNone(ping.due(started))+ self.assertEqual(ping.sent, 1)++ def test_output_silences_the_comments_and_silence_brings_them_back(self):+ # The case that matters for a held-back tool call: the request writes nothing for minutes in+ # the middle of a generation, and the client must still see that the connection is alive.+ ping = ServePing(interval_s=0.15)+ started = time.perf_counter()+ ping.note_output() # the role chunk went out+ for _ in range(10): # a stream that keeps writing: no comments+ time.sleep(0.02)+ ping.note_output()+ self.assertIsNone(ping.due(started))+ self.assertEqual(ping.sent, 0)+ time.sleep(0.2) # ...and then the model goes quiet+ ping.sent_comment(ping.due(started))+ ping.note_output() # the next data event ends the silence+ self.assertIsNone(ping.due(started))+ time.sleep(0.2)+ ping.sent_comment(ping.due(started))+ self.assertEqual(ping.sent, 2)++ def test_the_end_of_the_stream_ends_the_comments(self):+ ping = ServePing(interval_s=0.1)+ started = time.perf_counter()+ time.sleep(0.12)+ ping.sent_comment(ping.due(started))+ ping.limit() # [DONE] went out: the request is over+ time.sleep(0.15)+ self.assertIsNone(ping.due(started))+ self.assertEqual(ping.sent, 1)++ def test_each_request_gets_its_own_timers(self):+ os.environ["KYOJIN_SSE_PING_S"] = "0.1"+ self.addCleanup(os.environ.pop, "KYOJIN_SSE_PING_S", None)+ app = ServePing.from_env()+ first, second = app.per_request(), app.per_request()+ self.assertIsNot(first, second)+ started = time.perf_counter()+ time.sleep(0.15)+ self.assertIsNotNone(first.due(started))+ self.assertIsNotNone(second.due(started)) # one session's wait does not mute another's+ first.limit() # the first session is over+ self.assertIsNone(first.due(started))+ second._last_sent = 0.0 # what this really checks is `limit`'s scope+ self.assertIsNotNone(second.due(started))+ self.assertTrue(app.enabled) # the application's own settings are untouched++ def test_the_interval_is_fixed_when_the_switch_is_read(self):+ app = ServePing(interval_s=0.1)+ os.environ["KYOJIN_SSE_PING_S"] = "3600" # a later change does not reach a running server+ self.addCleanup(os.environ.pop, "KYOJIN_SSE_PING_S", None)+ self.assertEqual(app.per_request().interval_s, 0.1)+++if __name__ == "__main__":+ unittest.main()