Skip to content

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

Python

Streamed requests are refused 429 + Retry-After at saturation, before the 200 (patch 0094, issue #50)

MiaAI-Lab58abb16cc465
diff --git a/README.md b/README.md
index f96e35f..4f0a6f3 100644
--- a/README.md
+++ b/README.md
@@ -657,6 +657,7 @@ applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the
| Kept-state limits | `0089-glm-kept-state` | `TF_GLM_KEPT_BYTES_GIB` (a byte budget for the kept states, with the freed blocks handed back to the driver) and `TF_GLM_KEEP_PER_CHAT` (a per-conversation quota of turn-boundary states), both off by default; `/health` `kept_bytes`, `kept_mix` (authored by Thomas Wade, [ThomasWadeZ](https://github.com/ThomasWadeZ), #65) | with both at 0, nothing changes |
| 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 |
| 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) |
Concurrent prompt fill and smooth streaming on two Sparks (`PARALLEL=4`, DFlash2, 1,024-row chunks): three 400-token
diff --git a/patches/0095-stream-admission.patch b/patches/0095-stream-admission.patch
new file mode 100644
index 0000000..faaca7f
--- /dev/null
+++ b/patches/0095-stream-admission.patch
@@ -0,0 +1,36 @@
+diff --git tensorfold/cuda/http.py tensorfold/cuda/http.py
+index 59d55e3..37eee90 100644
+--- tensorfold/cuda/http.py
++++ tensorfold/cuda/http.py
+@@ -152,6 +152,11 @@ def make_handler(app: App):
+ "choices": [{"index": 0, "text": delta.get("content", ""), "finish_reason": finish}]}
+
+ if stream:
++ try:
++ app.admit(body, chat, prepared) # a full server answers 429 here, not 200 and an error event
++ except RequestError as exc:
++ code, _hd = admission_response(exc)
++ return self._json(code, {"error": error_body(exc, field)}, headers=_hd)
+ self.send_response(200)
+ self.send_header("Content-Type", "text/event-stream")
+ self.send_header("Cache-Control", "no-cache")
+diff --git tensorfold/cuda/server.py tensorfold/cuda/server.py
+index ee97e62..53cbc80 100644
+--- tensorfold/cuda/server.py
++++ tensorfold/cuda/server.py
+@@ -335,6 +335,15 @@ class App:
+ prepared.max_tokens = min(prepared.max_tokens, limit - len(prepared.prompt))
+ return prepared
+
++ def admit(self, body: dict[str, Any], chat: bool, prepared: PreparedRequest) -> None:
++ """Refuse a request with ``CapacityError`` while the scheduler's admission cap holds, before a streamed reply's
++ 200 and headers go out (``Scheduler.submit`` checks again, but by then a stream can only carry the error as an
++ event, with status 200, which a client's retry logic never sees)."""
++
++ check = getattr(getattr(self.engine, "scheduler", None), "_check_admission", None)
++ if check is not None:
++ check(body.get("priority") == "background" or (chat and is_title_request(body.get("messages"), prepared.tools)))
++
+ def sampling_for(self, body: dict[str, Any], prompt: list[int]):
+ """Keyed sampling (the seed, else one drawn from the prompt), or None for greedy; RequestError if malformed."""
+
diff --git a/tools/test_stream_admission.py b/tools/test_stream_admission.py
new file mode 100644
index 0000000..1e56db6
--- /dev/null
+++ b/tools/test_stream_admission.py
@@ -0,0 +1,101 @@
+"""CPU-only: a full server answers a STREAMED request 429 + Retry-After, not 200 and an error event (issue #50).
+
+ python3 -B tools/test_stream_admission.py --source-root /path/to/patched/src
+Use --expect-stock on a source without patch 0094 (patches 0081-0083 only) to see the 200 with the error inside the stream.
+Runs the real CUDA-server handler on a loopback port with a stub app whose scheduler refuses like ``Scheduler._check_admission``
+when its cap is reached; ``App.admit`` itself is taken from the source file and run on a fake engine. No torch or GPU.
+"""
+from __future__ import annotations
+
+import argparse
+import ast
+import json
+import socket
+import sys
+import threading
+from http.server import ThreadingHTTPServer
+from pathlib import Path
+from types import SimpleNamespace
+
+
+def admit_method(root):
+ source = (Path(root) / "tensorfold/cuda/server.py").read_text()
+ for node in ast.parse(source).body:
+ if isinstance(node, ast.ClassDef) and node.name == "App":
+ for item in node.body:
+ if isinstance(item, ast.FunctionDef) and item.name == "admit":
+ ns = {"Any": object, "PreparedRequest": object, "is_title_request": lambda messages, tools: False}
+ exec(compile(ast.fix_missing_locations(ast.Module(body=[ast.ImportFrom(
+ module="__future__", names=[ast.alias(name="annotations")], level=0), item], type_ignores=[])),
+ "<admit>", "exec"), ns)
+ return ns["admit"]
+ return None
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--source-root", required=True)
+ ap.add_argument("--expect-stock", action="store_true")
+ args = ap.parse_args()
+ sys.path.insert(0, args.source_root)
+ from tensorfold.cuda.http import make_handler
+ from tensorfold.server.errors import CapacityError, RequestError
+
+ full = [True]
+
+ class Scheduler:
+ def _check_admission(self, background):
+ if full[0] and not background:
+ raise CapacityError("all serving lanes are busy; retry shortly")
+
+ admit = admit_method(args.source_root)
+
+ class App:
+ model_ids, served_name = ["m"], "m"
+ engine = SimpleNamespace(scheduler=Scheduler())
+
+ def reply_model(self, body):
+ return "m"
+
+ def prepare(self, body, chat):
+ return SimpleNamespace(tools=None)
+
+ def run(self, body, chat, emit, prepared=None, cancelled=None):
+ Scheduler()._check_admission(body.get("priority") == "background") # Scheduler.submit's check
+ emit({"content": "hi"})
+ return {"final": {}, "calls": None, "call_deltas": [], "finish": "stop", "content": "hi", "reasoning": None,
+ "stats": {}, "prompt_tokens": 1, "completion_tokens": 1}
+
+ if admit is not None:
+ App.admit = admit
+ server = ThreadingHTTPServer(("127.0.0.1", 0), make_handler(App()))
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+
+ def post(**extra):
+ body = json.dumps({"model": "m", "messages": [{"role": "user", "content": "x"}], **extra}).encode()
+ s = socket.create_connection(server.server_address, timeout=5)
+ s.sendall(b"POST /v1/chat/completions HTTP/1.1\r\nHost: x\r\nContent-Length: %d\r\n\r\n" % len(body) + body)
+ data = b""
+ while chunk := s.recv(65536):
+ data += chunk
+ if b"[DONE]" in data or b"\r\n\r\n" in data and b"Content-Length" in data and data.endswith(b"}"):
+ break
+ s.close()
+ return data
+
+ for stream in (False, True):
+ reply = post(stream=stream)
+ status = int(reply.split()[1])
+ if args.expect_stock and stream:
+ assert status == 200 and b"lanes are busy" in reply, reply[:200]
+ print("stock: a streamed request to a full server is a 200 with the error inside the stream")
+ return
+ assert status == 429 and b"Retry-After: 5" in reply, (stream, reply[:300])
+ assert int(post(stream=True, priority="background").split()[1]) == 200, "background requests queue by design"
+ full[0] = False
+ assert int(post(stream=True).split()[1]) == 200
+ print("streamed and plain requests to a full server: 429 + Retry-After: 5; with room: 200")
+
+
+if __name__ == "__main__":
+ main()