Skip to content

GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold

Python

Patch 0111: a streamed reply sends SSE keep-alive comments while it waits, on every streaming route (issue #106)

BadAd84227eb10f4447
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f284a67..5fe7ba6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -36,6 +36,14 @@ Every change to this recipe, newest first. Each release names the image it serve
cold request of 50 full-size pictures (102,118 tokens) answers and resumes. Pictures past the 8th are no longer
downscaled, so they cost up to 2,048 tokens each. `TENSORFOLD_GLM_REQUEST_IMAGE_TOKENS=16384` restores the shared
budget. No patch and no image change. CPU check: `tools/picture_budget_check.py`.
+- **Streamed replies keep the connection alive while they wait** (patch `0111-server-sse-keepalive`, issue #106,
+ reported with the first version of the patch by [stevehansen](https://github.com/stevehansen)): a streamed reply
+ sent nothing between its first event and its first token, so a request waiting for a lane or filling a long prompt
+ was silent for minutes, and a proxy in front cut it as idle (reported: behind a Cloudflare Tunnel every such stream
+ ended at ~125 s). Now a stream that has sent nothing for `SSE_KEEPALIVE_S` seconds (15) writes an SSE comment line,
+ `: keepalive`, on the chat, completions, Messages and Responses streams; SSE clients skip comment lines, and the
+ events are the same bytes. `SSE_KEEPALIVE_S=0` turns it off; a value that is not a number of seconds stops the
+ server at start. Non-streamed replies are unchanged. CPU test: `tools/test_sse_keepalive.py`.
- **A prompt that fills beside other replies, ~10-14% sooner** (`FILL_ROWS`, by [BadAd84](https://github.com/BadAd84)):
while other requests decode, a new prompt filled in 1,024-row chunks (TensorFold's `TF_GLM_FILL_ROWS` default),
half the 2,048-row prompt chunk whose buffers the engine keeps anyway. `scripts/config.sh` now sets 2,048 (at
diff --git a/CREDITS.md b/CREDITS.md
index 343407f..597b70a 100644
--- a/CREDITS.md
+++ b/CREDITS.md
@@ -130,6 +130,12 @@ checkpoint's ShapleyMcg attribution and the drafter's license).
MLX-style server, issues #67, #74): uses the reader `tensorfold/server/request_body.py` (`read_body`, TensorFold
commit 977f2cc), authored by Jordi Posthumus ([JordiPosthumus](https://github.com/JordiPosthumus)) and brought in by
`0084`; the call sites are ours. TensorFold's own chunked-body issue is ashhart/TensorFold#244.
+- `0111-server-sse-keepalive` (SSE keep-alive comments while a streamed reply is silent, issue #106): the diagnosis,
+ the measurements behind a Cloudflare Tunnel, the design (a `: keepalive` comment line after
+ `TENSORFOLD_SSE_KEEPALIVE_S` seconds of silence) and the first patch and CPU test, for the chat stream, by
+ [stevehansen](https://github.com/stevehansen) in [issue #106](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/issues/106);
+ this version, which also carries the comments through the Messages and Responses streams, and its extended test,
+ by [BadAd84](https://github.com/BadAd84).
- `0085-glm-select-split-loop` (the split selection's last pass over the earlier chunks only): by
[BadAd84](https://github.com/BadAd84).
- `0086-glm-prompt-scores-loop` (the prompt scoring, one row and many pool blocks a program): by
diff --git a/README.md b/README.md
index 81c0f3e..1ea1ee2 100644
--- a/README.md
+++ b/README.md
@@ -561,6 +561,7 @@ sets a value wins: the environment, then `scripts/local.sh`, then `.env`, then t
| `TF_GLM_EFFORT_TAIL` | `0` | `1` (patch `0096`, issue #93, reported by [jdecker76](https://github.com/jdecker76)): render the reasoning-effort line just before `<\|assistant\|><think>` instead of at token 3, so switching effort or thinking on/off keeps the conversation's kept prompt (the reporter measured 0% cached becoming 98%); the model was trained with the line first, so check that Low and High still change the answers before you rely on it (`tools/toolcheck.py`, `tools/end_of_turn.py`). The previous turn's last tokens prefill again |
| `NUCLEUS_UNION` | `1` | `TENSORFOLD_NUCLEUS_UNION` (patch `0034`): a sampled step with top_p below 1 and top_k off tests the ranks' candidates together for the nucleus, instead of each rank alone (which sent almost every step to a whole-vocabulary CPU sort: ~15 tok/s against greedy's ~58); the same draws, byte for byte (`tools/test_nucleus_union.py`); `0`: stock (issue #91) |
| `TF_GLM_MAX_QUEUED` | unset | admission at saturation (patch `0082`): past the lanes plus this many queued foreground requests, a request is refused with 429 + `Retry-After: 5` instead of queueing; unset queues as every scheduler always has, `0` refuses anything past the lanes (by johnwhited, #48) |
+| `SSE_KEEPALIVE_S` | `15` | `TENSORFOLD_SSE_KEEPALIVE_S` (patch `0111`): a streamed reply that has sent nothing for this many seconds (waiting for a lane, filling a long prompt) writes an SSE comment line, `: keepalive`, so a proxy in front does not cut it as idle (Cloudflare: after about two minutes, issue #106); clients skip comment lines, and the events are the same bytes. Every streaming route; `0`: off |
| `MULTI_PREFILL` | `1` | prompts that arrive together are filled in one forward (each with the bits it gets alone); `0`: one after another |
| `STREAM_SMOOTH` / `STREAM_SMOOTH_MS` | `1` / `400` | streamed replies go out one token an event at a steady pace from a playout buffer of this many ms, so drafted bursts (~3 tokens every ~50-100 ms) and short pauses do not show; text appears that much later, the reply ends when it did, tool calls keep their place; `0`: one event a round |
| `FILL_BUDGET_MS` | `200` | while other requests decode, a new prompt fills in layer slices of about this many ms with a decode round between them; `0`: whole `FILL_ROWS` chunks, each pausing the other replies for its whole pass: about 1.3 s at the default 2,048 rows (about 0.65 s at 1,024). A request alone fills at full speed either way |
@@ -651,6 +652,9 @@ The checkpoint's own sampling defaults apply (temperature 1.0, top_p 0.95). Per
and clips, only when they are the same ones), and a shared system prompt's state is reused (`SHARED_PREFIX`).
- A POST to an unknown route is answered 404 after its body is read, so a kept-alive connection stays usable; a
client that leaves is noticed however many connections the server holds.
+- Streamed replies: while a request waits for a lane or fills its prompt, the stream carries an SSE comment line
+ (`: keepalive`) every `SSE_KEEPALIVE_S` seconds of silence (15), on every streaming route; SSE clients skip
+ comment lines, so the events and their bytes are as before. `SSE_KEEPALIVE_S=0` turns them off.
## What the patches change
@@ -701,6 +705,7 @@ applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the
| Responses `include` | `0093-responses-include` | `/v1/responses` accepts OpenAI's `include` values and ignores them (reasoning already comes as text, nothing is encrypted); an unknown value or a non-list is still a 400 (issue #73) | the AI SDK's `include: ["reasoning.encrypted_content"]` no longer fails every request |
| Chunked request bodies | `0094-chunked-request-bodies` | a `Transfer-Encoding: chunked` request body (AI SDK clients, Chatbox, proxies) is read like a `Content-Length` one on the chat, completions, tokenizer and Responses routes and the MLX-style server, each route keeping its own size limit (96 MiB for chat); a refused request's body is consumed so it cannot reach the next one. The reader is `request_body.read_body` from TensorFold's 977f2cc by Jordi Posthumus (@JordiPosthumus), which `0084` adds; this patch uses it at the remaining sites (issues #67, #74) | no dechunking proxy; a validation 400 no longer leaves HTML after the JSON on a keep-alive connection |
| Streamed admission | `0095-stream-admission` | with `TF_GLM_MAX_QUEUED` set, a streamed request to a full server is answered 429 + `Retry-After: 5` before the stream opens; `0082` checked inside `submit`, after the 200 and the headers had gone out, so a streaming client (opencode, Claude Code) got a 200 with the error as an event and never saw a retryable status (issue #50) | the same refusal for streamed and plain requests |
+| Stream keep-alive | `0111-server-sse-keepalive` | a streamed reply that has sent nothing for `TENSORFOLD_SSE_KEEPALIVE_S` seconds (15; `0`: off) writes an SSE comment line, `: keepalive`, on the chat, completions, Messages and Responses streams; a request waiting for a lane or filling a long prompt was silent from its first event to its first token, and a proxy in front cut it as idle (reported behind a Cloudflare Tunnel: every such stream at ~125 s; issue #106, with the first version of this patch by stevehansen) | the same events, byte for byte; no stream silent for longer than the setting |
| Effort line at the tail | `0096-effort-tail` | opt-in `TF_GLM_EFFORT_TAIL=1`: the reasoning-effort line is rendered before the generation prompt, not at token 3, so changing effort or thinking on/off no longer misses the kept prompt and re-prefills the whole conversation (issue #93, reported and measured by jdecker76); off, every prompt is byte-identical to before | the same prompts as before |
| Concurrent fill | `0062-glm-sliced-fill` | a new prompt's chunks run in layer slices (`FILL_BUDGET_MS`) with decode rounds between them, drafted as usual (`FILL_DRAFTS`), both ranks on the same layer boundaries; the chunk's buffers kept between slices, grouped fills, cache moves and cancellation mid-fill; whole forwards when nothing else decodes | with smooth streaming, the other replies' pauses during a 25k-token fill 630-690 ms -> 81-149 ms (table below) |
@@ -755,6 +760,7 @@ with [sparkDash](https://github.com/MiaAI-Lab/sparkDash) ([Performance](#perform
| `tools/pool_pressure.py [size]` | on a fresh server with nothing else sending requests: two conversations of ~`size` tokens (default 30000) take a turn each, others fill the pool, then each takes another turn; exit 1 when a turn resumes less than 90% of its previous prompt, 2 when the kept-prompt cap stops the fill first (a smaller pool runs it faster: `CONTEXT=131072 KV_POOL_GIB=0.5`) |
| `tools/pool_room_check.py` | patch 0074's checks, run in the image (`docker run ... --entrypoint python`, see the file): the pool's room-making on a CPU arena, what it evicts and moves, and rank 1 replaying the same ops |
| `tools/test_queued_cancellation.py --source-root DIR` | patch 0073's checks on the CPU, against TensorFold's source with the patches applied (no GPU, no server): requests that wait while every slot is busy and whose client leaves are dropped at once, in queue order; `--expect-stock` before 0073 shows the old wait |
+| `tools/test_sse_keepalive.py --source-root DIR` | patch 0111's checks on the CPU, against TensorFold's source with the patches applied (no GPU, no server): every streaming route of the real handler, over a stub that stays silent for 3 s, gets `: keepalive` about once a second with `TENSORFOLD_SSE_KEEPALIVE_S=1` and none after its last event; without its comment lines each stream is byte-identical to the stream with `0`; non-streamed replies unchanged; no thread outlives its request; `--expect-stock` before 0111 shows the silence |
| `tools/end_of_turn.py [label] [max_cut]` | 8 short French coding prompts, thinking off: counts the replies that run to `max_tokens` (48 requests) and measures P(end of turn) right after each reply's closing code fence; exit 1 above `max_cut` cut replies (default 4) |
| `tools/prompt_reuse.py [size]` | a ~33k-token conversation takes three more turns, each after a request of another conversation with the same system prompt (an agent and its sub-agents); exit 1 when a turn resumes less than 90% of its prompt. Needs `PARALLEL` above 1 |
| `tools/picture_turns.py [pictures] [size]` | a chat of ~`size` tokens (default 40000) gets one new 1920x1080 picture a turn (default 12), with a text turn after each; exit 1 when a turn re-reads more than the new picture, which is what a picture cap that moves with the picture count does from the 9th picture on |
diff --git a/patches/0111-server-sse-keepalive.patch b/patches/0111-server-sse-keepalive.patch
new file mode 100644
index 0000000..084090c
--- /dev/null
+++ b/patches/0111-server-sse-keepalive.patch
@@ -0,0 +1,168 @@
+# Streamed replies send an SSE comment line, ": keepalive", after TENSORFOLD_SSE_KEEPALIVE_S seconds (default 15; 0:
+# off) with nothing else written, on every streaming route (issue #106). A request that waits for a lane or fills a
+# long prompt sends nothing after its first event, and a proxy in front cuts an idle stream (Cloudflare: after about
+# two minutes). Comment lines are part of the SSE format and clients skip them; the events are the same bytes.
+# cuda/http.py: _Keepalive holds the stream's writes under one lock and runs the comments from a thread only while
+# App.run runs, so leaving it ends the thread before the reply's last event, its error event or a cancellation.
+# server/responses.py: Wire passes the chat stream's comment lines through to the client's socket, so the Messages
+# (server/anthropic.py) and Responses streams, which translate the chat stream, carry them too.
+# Non-streamed replies are unchanged. A bad value stops the server at import. CPU test: tools/test_sse_keepalive.py.
+diff --git tensorfold/cuda/http.py tensorfold/cuda/http.py
+index 5b48deb..7360924 100644
+--- tensorfold/cuda/http.py
++++ tensorfold/cuda/http.py
+@@ -2,6 +2,9 @@
+ from __future__ import annotations
+
+ import json
++import math
++import os
++import threading
+ import time
+ import traceback
+ import uuid
+@@ -22,6 +25,68 @@ if TYPE_CHECKING:
+ _TOKENIZER_ROUTES = ("/tokenize", "/v1/tokenize", "/detokenize", "/v1/detokenize")
+
+
++def _keepalive_seconds() -> float:
++ """``TENSORFOLD_SSE_KEEPALIVE_S`` (default 15): the longest a streamed reply stays silent before a keep-alive
++ comment; 0 turns keep-alives off."""
++
++ raw = os.environ.get("TENSORFOLD_SSE_KEEPALIVE_S", "15")
++ try:
++ seconds = float(raw)
++ except ValueError:
++ seconds = math.nan
++ if not math.isfinite(seconds) or seconds < 0:
++ raise ValueError(f"TENSORFOLD_SSE_KEEPALIVE_S={raw!r}: seconds of silence before a keep-alive, 0 for none")
++ return seconds
++
++
++_SSE_KEEPALIVE_S = _keepalive_seconds()
++
++
++class _Keepalive:
++ """A streamed reply's writes, plus an SSE comment line (``: keepalive``) whenever nothing has been written for
++ ``seconds`` while ``with`` holds it (patch 0111). A request that waits for a lane or fills a long prompt sends
++ nothing else, and a proxy in front drops a stream that stays silent (Cloudflare: after about two minutes); SSE
++ clients skip comment lines. Every write holds one lock, since the comments come from their own thread, and
++ leaving ``with`` ends that thread before it returns, so no comment follows the reply's last event."""
++
++ COMMENT = b": keepalive\n\n"
++
++ def __init__(self, wfile: Any, seconds: float) -> None:
++ self.wfile, self.seconds = wfile, seconds
++ self.lock = threading.Lock()
++ self.last = time.monotonic()
++ self.stop = threading.Event()
++ self.thread: threading.Thread | None = None
++
++ def write(self, data: bytes) -> None:
++ with self.lock:
++ self.wfile.write(data)
++ self.wfile.flush()
++ self.last = time.monotonic()
++
++ def __enter__(self) -> None:
++ if self.seconds > 0:
++ self.thread = threading.Thread(target=self._beat, name="sse-keepalive", daemon=True)
++ self.thread.start()
++
++ def __exit__(self, *exc: Any) -> None:
++ self.stop.set()
++ if self.thread is not None: # a comment being written goes out first, before the reply's last event
++ self.thread.join()
++
++ def _beat(self) -> None:
++ while not self.stop.wait(max(0.0, self.last + self.seconds - time.monotonic())):
++ with self.lock:
++ if time.monotonic() - self.last < self.seconds: # an event went out meanwhile
++ continue
++ try:
++ self.wfile.write(self.COMMENT)
++ self.wfile.flush()
++ except OSError: # the client has gone
++ return
++ self.last = time.monotonic()
++
++
+ def usage_of(result: dict[str, Any]) -> dict[str, Any]:
+ """A reply's usage as the Mac server reports it, the prompt tokens found cached included."""
+
+@@ -159,11 +224,11 @@ def make_handler(app: App):
+ self.send_header("Cache-Control", "no-cache")
+ self.send_header("Connection", "close")
+ self.end_headers()
++ keepalive = _Keepalive(self.wfile, _SSE_KEEPALIVE_S)
+
+ def emit(delta: dict[str, Any]) -> bool:
+ try:
+- self.wfile.write(f"data: {json.dumps(chunk(delta))}\n\n".encode())
+- self.wfile.flush()
++ keepalive.write(f"data: {json.dumps(chunk(delta))}\n\n".encode())
+ return True
+ except OSError: # reset, broken pipe, timed out, host unreachable: the client has gone
+ return False
+@@ -171,7 +236,8 @@ def make_handler(app: App):
+ if chat:
+ emit({"role": "assistant"})
+ try:
+- result = app.run(body, chat, emit, prepared=prepared, cancelled=cancelled)
++ with keepalive: # comments while the reply is silent, none after it
++ result = app.run(body, chat, emit, prepared=prepared, cancelled=cancelled)
+ except RequestCancelled:
+ self.close_connection = True
+ return
+diff --git tensorfold/server/anthropic.py tensorfold/server/anthropic.py
+index d443807..fc2557b 100644
+--- tensorfold/server/anthropic.py
++++ tensorfold/server/anthropic.py
+@@ -81,7 +81,7 @@ def post(handler: Any, app: Any) -> None:
+ handler.close_connection = True
+ reply.start()
+
+- wire = Wire(opened, reply.chunk)
++ wire = Wire(opened, reply.chunk, handler.wfile)
+ try:
+ _run_chat(handler, chat, wire)
+ if wire.stream or wire.status is None:
+diff --git tensorfold/server/responses.py tensorfold/server/responses.py
+index 89f45bb..3bca9e8 100644
+--- tensorfold/server/responses.py
++++ tensorfold/server/responses.py
+@@ -126,10 +126,12 @@ def _refuse(handler: Any, message: str, status: int = 400, param: str | None = N
+
+
+ class Wire:
+- """The chat handler's side of its socket: the status and headers, then the JSON body or each stream event."""
++ """The chat handler's side of its socket: the status and headers, then the JSON body or each stream event; a
++ stream's comment lines (the keep-alives of patch 0111) are written to ``comments`` as they came."""
+
+- def __init__(self, opened: Callable[[], None], event: Callable[[dict[str, Any] | None], None]) -> None:
+- self.opened, self.event = opened, event
++ def __init__(self, opened: Callable[[], None], event: Callable[[dict[str, Any] | None], None],
++ comments: Any) -> None:
++ self.opened, self.event, self.comments = opened, event, comments
+ self.status: int | None = None
+ self.stream = False
+ self.data = bytearray()
+@@ -156,6 +158,9 @@ class Wire:
+ self.event(None if line[6:] == b"[DONE]" else json.loads(line[6:]))
+ except OSError as exc: # our client has gone: the chat handler's write fails
+ raise BrokenPipeError(str(exc)) from exc
++ elif line.startswith(b":"):
++ self.comments.write(line + b"\n\n")
++ self.comments.flush()
+ return len(data)
+
+ def flush(self) -> None:
+@@ -211,7 +216,7 @@ def post(handler: Any, app: Any) -> None:
+ handler.close_connection = True
+ reply.start()
+
+- wire = Wire(opened, reply.chunk)
++ wire = Wire(opened, reply.chunk, handler.wfile)
+ try:
+ _run_chat(handler, request.chat, wire)
+ except OSError: # the client left while the reply was written
diff --git a/scripts/config.sh b/scripts/config.sh
index b995fac..286082a 100644
--- a/scripts/config.sh
+++ b/scripts/config.sh
@@ -270,6 +270,11 @@ export TF_GLM_EFFORT_TAIL="${TF_GLM_EFFORT_TAIL:-0}"
MAX_QUEUED="${MAX_QUEUED:-}"
# A streamed request is checked before its 200 goes out (patch 0095), so it gets the same 429 + Retry-After.
export TF_GLM_MAX_QUEUED="$MAX_QUEUED"
+# A streamed reply that has sent nothing for SSE_KEEPALIVE_S seconds writes an SSE comment line, ": keepalive" (patch
+# 0111). A request waiting for a lane or filling a long prompt is silent otherwise, and a proxy in front cuts an idle
+# stream (Cloudflare: after about two minutes, issue #106). Clients skip comment lines; the events are the same bytes.
+# Every streaming route (chat, completions, Messages, Responses). 0: off.
+export TENSORFOLD_SSE_KEEPALIVE_S="${SSE_KEEPALIVE_S:-${TENSORFOLD_SSE_KEEPALIVE_S:-15}}"
# Sampled decode with the checkpoint's defaults (temperature 1, top_p 0.95, top_k 0) draws from the top_p nucleus
# (patch 0034). Stock TensorFold tests each rank's candidates alone, which fails on any two ranks whenever both hold
# part of the nucleus, so every such step gathered and sorted the whole vocabulary on the CPU: ~15 tok/s against
diff --git a/tools/test_sse_keepalive.py b/tools/test_sse_keepalive.py
new file mode 100644
index 0000000..2e981d1
--- /dev/null
+++ b/tools/test_sse_keepalive.py
@@ -0,0 +1,306 @@
+"""CPU-only: a streamed reply that is silent (waiting for a lane, filling a long prompt) writes SSE keep-alive comments,
+on every streaming route, and the events a client parses stay the same bytes (patch 0111, issue #106).
+
+ python3 -B tools/test_sse_keepalive.py --source-root /path/to/patched/src [--stock-root /path/to/unpatched/src]
+Use --expect-stock on a source without patch 0111 to see every stream stay silent while its request waits.
+Runs the real CUDA-server handler (and through it the Messages and Responses routes) on a loopback port with a stub app
+whose run() is silent for a few seconds, once with TENSORFOLD_SSE_KEEPALIVE_S=1 and once with 0, each in its own process,
+with ids and clocks fixed so the runs can be compared byte for byte. Checks, with patch 0111:
+- every streamed route (chat, completions, Messages, Responses) gets ': keepalive' about once a second while silent
+ and none after its last event, error events included; a reply that keeps sending tokens gets none;
+- each stream with its comment lines taken out is byte-identical to the stream with 0 (headers included) and parses to
+ the same events by the SSE format's rules; with --stock-root, the replies with 0 are byte-identical to the unpatched
+ source's;
+- non-streamed replies are byte-identical either way; with 0 no keep-alive thread ever starts;
+- no keep-alive thread outlives its request: a client that leaves ends it with its cancelled request, or by the failed
+ write when the request goes on; a bad TENSORFOLD_SSE_KEEPALIVE_S stops the server at import.
+No torch or GPU.
+"""
+from __future__ import annotations
+
+import argparse
+import base64
+import json
+import os
+import socket
+import subprocess
+import sys
+import threading
+import time
+
+SILENCE = 3.2 # a streamed request's stub run: silent this long, then one token
+SHORT = 1.5 # a non-streamed request's: longer than a keep-alive interval
+DEAF = 6.0 # a request that goes on after its client left (no cancellation check)
+COMMENT = b": keepalive\n\n"
+ROUTES = ("/v1/chat/completions", "/v1/completions", "/v1/messages", "/v1/responses")
+LAST = {"/v1/chat/completions": b"data: [DONE]\n\n", "/v1/completions": b"data: [DONE]\n\n",
+ "/v1/messages": b"event: message_stop\n", "/v1/responses": b"event: response.completed\n"}
+BAD = ("abc", "-1", "nan", "inf", "")
+
+
+def body_for(route, stream, text):
+ if route == "/v1/completions":
+ return {"model": "stub", "stream": stream, "max_tokens": 4, "prompt": text}
+ if route == "/v1/responses":
+ return {"model": "stub", "stream": stream, "max_output_tokens": 16, "input": text, "store": False}
+ return {"model": "stub", "stream": stream, "max_tokens": 4, "messages": [{"role": "user", "content": text}]}
+
+
+def exchange(port, route, body, leave_on=None):
+ """POST ``body``; every received piece with its arrival time (s), until EOF (or until ``leave_on`` arrives: then
+ the client closes the connection, as one that gives up does)."""
+
+ data = json.dumps(body).encode()
+ sock = socket.create_connection(("127.0.0.1", port), timeout=30)
+ t0 = time.monotonic()
+ sock.sendall(f"POST {route} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\nContent-Type: application/json\r\n"
+ f"Content-Length: {len(data)}\r\n\r\n".encode() + data)
+ pieces, raw = [], b""
+ while True:
+ piece = sock.recv(65536)
+ if not piece:
+ break
+ pieces.append((time.monotonic() - t0, piece))
+ raw += piece
+ if leave_on is not None and leave_on in raw:
+ break
+ sock.close()
+ return pieces
+
+
+# -- the child: one setting, every request, raw bytes out -----------------------------------------------------------
+
+
+def child(root, seconds):
+ os.environ["TENSORFOLD_SSE_KEEPALIVE_S"] = seconds
+ import uuid
+ counter = iter(range(1, 1 << 30))
+ uuid.uuid4 = lambda: uuid.UUID(int=next(counter)) # the same ids in every run
+ time.time = lambda: 1767225600.0 # the same created / Date in every run
+ sys.path.insert(0, root)
+ try:
+ from tensorfold.cuda.http import make_handler
+ except ValueError as exc: # a bad setting: reported to the parent
+ print(json.dumps({"import_error": str(exc)}))
+ return
+ from tensorfold.server.cancellation import RequestCancelled
+ from tensorfold.server.errors import RequestError
+ from tensorfold.server.http import Server
+
+ class Stub:
+ model_ids, served_name = ["stub"], "stub"
+
+ def prepare(self, body, chat):
+ return None
+
+ def admit(self, body, chat, prepared):
+ return None
+
+ def reply_model(self, body):
+ return "stub"
+
+ def run(self, body, chat, emit, prepared=None, cancelled=None):
+ text = json.dumps(body)
+ deaf = "deaf" in text
+ end = time.monotonic() + (DEAF if deaf else SILENCE if body.get("stream") else SHORT)
+ sent = 0
+ while time.monotonic() < end: # waiting for a lane / filling a prompt
+ if not deaf and cancelled is not None and cancelled():
+ raise RequestCancelled()
+ threading.Event().wait(0.05)
+ if "busy" in text and time.monotonic() > end - SILENCE + 0.4 * (sent + 1):
+ sent += 1
+ emit({"content": f"t{sent} "}) # a reply that keeps sending: a token every 0.4 s
+ if "please fail" in text:
+ raise RequestError("the stub refused this request")
+ emit({"content": "OK"})
+ return {"final": None, "call_deltas": [], "calls": [], "finish": "stop", "stats": {}, "content": "OK",
+ "reasoning": "", "prompt_tokens": 5, "completion_tokens": 1}
+
+ server = Server(("127.0.0.1", 0), make_handler(Stub()))
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ port = server.server_address[1]
+
+ def beats():
+ return sum(t.name == "sse-keepalive" for t in threading.enumerate())
+
+ out = {"cases": {}, "threads_after": {}, "threads_most": 0, "leave": {}}
+ sampling = threading.Event()
+
+ def sample(): # the most keep-alive threads alive at once, over every request
+ while not sampling.wait(0.02):
+ out["threads_most"] = max(out["threads_most"], beats())
+
+ threading.Thread(target=sample, daemon=True).start()
+ cases = [(route, stream, "hi") for route in ROUTES for stream in (True, False)]
+ cases += [("/v1/chat/completions", True, "please fail"), ("/v1/messages", True, "please fail"),
+ ("/v1/chat/completions", True, "busy"), ("/v1/messages", True, "busy")]
+ for route, stream, text in cases:
+ key = f"{route} stream={stream} {text}"
+ pieces = exchange(port, route, body_for(route, stream, text))
+ out["cases"][key] = [(t, base64.b64encode(p).decode()) for t, p in pieces]
+ out["threads_after"][key] = beats()
+ # a client that leaves at its first keep-alive: its request is cancelled ("hi"), or goes on ("deaf") and the
+ # comments end at the first write that fails
+ for text in ("hi", "deaf"):
+ exchange(port, "/v1/chat/completions", body_for("/v1/chat/completions", True, text), leave_on=COMMENT)
+ left = time.monotonic()
+ while time.monotonic() - left < DEAF + 1 and beats():
+ time.sleep(0.05)
+ out["leave"][text] = {"threads": beats(), "seconds": time.monotonic() - left}
+ time.sleep(DEAF if text == "deaf" else 0) # the deaf request's run ends before the server does
+ sampling.set()
+ server.shutdown()
+ print(json.dumps(out))
+
+
+# -- the parent: the settings compared ------------------------------------------------------------------------------
+
+
+def sse_events(body):
+ """The events an SSE client dispatches (the format's parsing rules: comment lines and unknown fields skipped)."""
+
+ events, kind, data = [], "message", []
+ for line in body.replace(b"\r\n", b"\n").split(b"\n"):
+ if not line:
+ if data:
+ events.append((kind, b"\n".join(data)))
+ kind, data = "message", []
+ continue
+ if line.startswith(b":"):
+ continue
+ name, _, value = line.partition(b":")
+ value = value[1:] if value.startswith(b" ") else value
+ if name == b"event":
+ kind = value.decode()
+ elif name == b"data":
+ data.append(value)
+ return events
+
+
+def start_child(root, seconds):
+ return subprocess.Popen([sys.executable, "-B", os.path.abspath(__file__), "--source-root", root, "--child", seconds],
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
+
+
+def finish_child(proc, what):
+ out, err = proc.communicate(timeout=300)
+ if proc.returncode:
+ sys.exit(f"the child for {what} failed:\n{err}")
+ return json.loads(out.strip().splitlines()[-1])
+
+
+def split(pieces):
+ """(head, body, [(arrival time, the body's length so far)])"""
+
+ raw, marks = b"", []
+ for t, p in pieces:
+ raw += base64.b64decode(p)
+ marks.append((t, len(raw)))
+ cut = raw.index(b"\r\n\r\n") + 4
+ return raw[:cut], raw[cut:], [(t, end - cut) for t, end in marks if end > cut]
+
+
+def silence(pieces):
+ """The longest the client heard nothing, from its request to the end of the reply (s)."""
+
+ times = [0.0] + [t for t, _ in pieces]
+ return max(b - a for a, b in zip(times, times[1:]))
+
+
+def comment_times(body, marks):
+ times, at = [], 0
+ while (at := body.find(COMMENT, at)) >= 0:
+ times.append(next(t for t, end in marks if end >= at + len(COMMENT)))
+ at += len(COMMENT)
+ return times
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--source-root", required=True)
+ ap.add_argument("--stock-root", help="an unpatched source: the replies with 0 must equal its replies byte for byte")
+ ap.add_argument("--expect-stock", action="store_true")
+ ap.add_argument("--child")
+ args = ap.parse_args()
+ if args.child is not None:
+ return child(args.source_root, args.child)
+
+ procs = {"on": start_child(args.source_root, "1"), "off": start_child(args.source_root, "0")}
+ if args.stock_root:
+ procs["stock"] = start_child(args.stock_root, "1")
+ runs = {name: finish_child(proc, name) for name, proc in procs.items()}
+ on, off = runs["on"], runs["off"]
+ failures = []
+
+ def check(ok, message):
+ if not ok:
+ failures.append(message)
+
+ if args.expect_stock:
+ for key, pieces in on["cases"].items():
+ head, body, marks = split(pieces)
+ check(b"\n:" not in b"\n" + body, f"{key}: a comment line in the stock stream")
+ if "stream=True" in key and "busy" not in key:
+ quiet = silence(pieces)
+ check(quiet >= SILENCE - 0.5, f"{key}: no {SILENCE} s silence ({quiet:.1f} s)")
+ print(f"stock {key}: nothing received for {quiet:.1f} s while its request waits")
+ if failures:
+ sys.exit("FAILED (expected the stock behaviour):\n " + "\n ".join(failures))
+ print("stock: every streamed route is silent while its request waits, as expected")
+ return
+
+ for key, pieces in on["cases"].items():
+ head, body, marks = split(pieces)
+ head0, body0, _ = split(off["cases"][key])
+ check(head == head0, f"{key}: the headers differ between keep-alives on and off")
+ check(body.replace(COMMENT, b"") == body0, f"{key}: the stream without its comments differs from the one with 0")
+ check(COMMENT not in body0, f"{key}: a comment with TENSORFOLD_SSE_KEEPALIVE_S=0")
+ if args.stock_root:
+ check(runs["stock"]["cases"][key] and split(runs["stock"]["cases"][key])[:2] == (head0, body0),
+ f"{key}: the reply with 0 differs from the unpatched source's")
+ check(on["threads_after"][key] == 0 and off["threads_after"][key] == 0,
+ f"{key}: a keep-alive thread outlived its request ({on['threads_after'][key]})")
+ times = comment_times(body, marks)
+ if "stream=False" in key:
+ check(body == body0 and not times, f"{key}: the non-streamed reply changed")
+ print(f"{key}: byte-identical, no comment")
+ continue
+ check(sse_events(body) == sse_events(body0) and sse_events(body0), f"{key}: the parsed events differ")
+ if "busy" in key:
+ check(not times, f"{key}: keep-alives while tokens were flowing: {times}")
+ print(f"{key}: tokens every 0.4 s, no keep-alive; the same {len(sse_events(body0))} events")
+ continue
+ check(len(times) >= int(SILENCE) - 1, f"{key}: {len(times)} keep-alives in {SILENCE} s of silence: {times}")
+ check(all(0.9 <= b - a <= 1.6 for a, b in zip(times, times[1:])), f"{key}: keep-alives not ~1 s apart: {times}")
+ quiet = silence(pieces)
+ check(quiet < 1.6, f"{key}: still a {quiet:.1f} s silence")
+ last = LAST[key.split(" ")[0]] if "please fail" not in key else b"data: "
+ check(body.rfind(COMMENT) < body.rfind(last), f"{key}: a keep-alive after the stream's last event")
+ print(f"{key}: {len(times)} keep-alives at {[round(t, 1) for t in times]} s, the longest silence "
+ f"{quiet:.1f} s; without them the same {len(body0)} bytes and {len(sse_events(body0))} events as with 0")
+ if args.stock_root:
+ print("with 0: every reply byte-identical to the unpatched source's")
+ check(off["threads_most"] == 0, f"TENSORFOLD_SSE_KEEPALIVE_S=0 started {off['threads_most']} keep-alive threads")
+ check(on["threads_most"] == 1, f"{on['threads_most']} keep-alive threads at once for one request at a time")
+ print(f"keep-alive threads alive at once: {on['threads_most']} with 1, {off['threads_most']} with 0")
+ for text, limit in (("hi", 1.0), ("deaf", 3.5)):
+ leave = on["leave"][text]
+ check(leave["threads"] == 0 and leave["seconds"] < limit,
+ f"client left ({text}): {leave['threads']} keep-alive threads after {leave['seconds']:.1f} s")
+ print(f"client left ({'its request cancelled' if text == 'hi' else 'its request going on'}): "
+ f"the keep-alive thread ended {leave['seconds']:.2f} s later")
+
+ refused = {}
+ for bad in BAD:
+ refused[bad] = "TENSORFOLD_SSE_KEEPALIVE_S" in finish_child(start_child(args.source_root, bad), bad).get(
+ "import_error", "")
+ check(refused[bad], f"TENSORFOLD_SSE_KEEPALIVE_S={bad!r} was accepted")
+ print(f"bad settings refused at import: {refused}")
+ if failures:
+ sys.exit("FAILED:\n " + "\n ".join(failures))
+ print("OK")
+
+
+if __name__ == "__main__":
+ main()