Skip to content

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

Python

Chunked request bodies through 0084's request_body.read_body (patch 0094, issues #67 and #74)

MiaAI-Lab8154167e3e4d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 118c488..d1ed050 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,26 @@ Every change to this recipe, newest first. Each release names the image it serve
## Unreleased
+- **Chunked request bodies** (patch `0094-chunked-request-bodies`, issues #67 and #74): a `Transfer-Encoding: chunked`
+ request (AI SDK clients, Chatbox, proxies) has no `Content-Length`, so v0.6.0 read it as an empty body ("messages
+ must be a list" 400) and parsed the unread chunks as the next request on the keep-alive connection (the stdlib
+ answers that in HTTP/0.9 mode: an HTML error page with no status line). The chat, completions, tokenizer and
+ Responses routes, the MLX-style server and the 404 path now read bodies through `request_body.read_body`, the reader
+ patch `0084` brings from upstream TensorFold's 977f2cc by Jordi Posthumus (@JordiPosthumus); each route keeps its
+ own limit (96 MiB for chat). A body with both `Content-Length` and `Transfer-Encoding`, or another transfer coding,
+ is now a 400 with the connection closed. CPU test: `tools/test_chunked_bodies.py` (`--source-root` the patched
+ `src`; `--expect-stock` shows the failure on the unpatched source).
+- **Streamed requests are refused at saturation** (patch `0095-stream-admission`, issue #50): 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 headers had gone out, so streaming clients saw 200 and an error event. A request
+ admitted between the check and `submit` still gets the old error event. CPU test: `tools/test_stream_admission.py`.
+- **Responses `include`** (patch `0093-responses-include`, issue #73): `/v1/responses` accepts OpenAI's `include`
+ values and ignores them (once logged per value); an unknown value or a non-list is still a 400. CPU test:
+ `tools/test_responses_include.py`.
+- **Default sampling at greedy's pace** (issue #91): `scripts/config.sh` now sets `TENSORFOLD_NUCLEUS_UNION=1`
+ (patch `0034`; `NUCLEUS_UNION=0` restores stock). The merged nucleus test gives the same draws; stock sent almost
+ every sampled step to a whole-vocabulary CPU sort (~15 tok/s against greedy's ~58). CPU test:
+ `tools/test_nucleus_union.py`. To measure on the Sparks: sampled against greedy tok/s on 2 and 3 Sparks.
- **The drafter checks its candidate ids** (patch `0092-glm-draft-candidates-checked`, issue #80): an id outside the
vocabulary (a float's bits read as an id) is logged with its value and the rows are copied again once the device is
idle; only a second bad read fails, as before. A mitigation: the root cause of #80 is not yet found, and the log line
diff --git a/CREDITS.md b/CREDITS.md
index 006eab2..fd42b47 100644
--- a/CREDITS.md
+++ b/CREDITS.md
@@ -123,6 +123,10 @@ checkpoint's ShapleyMcg attribution and the drafter's license).
[ashhart](https://github.com/ashhart), and its request body reading (`server/request_body.py`, commit 977f2cc) by
Jordi Posthumus ([JordiPosthumus](https://github.com/JordiPosthumus)); backported to v0.6.0 by Eduardo Florencio
([eduffd](https://github.com/eduffd)) in [PR #90](https://github.com/MiaAI-Lab/GLM-5.3-Flash-EXL3-2x-DGX-Sparks-TensorFold/pull/90).
+- `0094-chunked-request-bodies` (chunked request bodies on the chat, completions, tokenizer and Responses routes and the
+ 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.
- `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 7c156a0..f96e35f 100644
--- a/README.md
+++ b/README.md
@@ -656,6 +656,7 @@ applied with `patch -p0` in filename order); `start.sh` rebuilds or re-pulls the
| Spill tier | `0088-glm-spill-tier` | kept prompt states written to local disk on every Spark when they leave the pool (early, in the background, past `SPILL_HIGHWATER`) and read back beside decoding streams, also after a clean restart (`SPILL_GIB`, off by default; authored by Robert Wojciechowski, [wojo](https://github.com/wojo), #78) | [Spill tier](#spill-tier-optional) |
| 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 |
| 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/0094-chunked-request-bodies.patch b/patches/0094-chunked-request-bodies.patch
new file mode 100644
index 0000000..ad31b75
--- /dev/null
+++ b/patches/0094-chunked-request-bodies.patch
@@ -0,0 +1,125 @@
+# Chunked request bodies (Transfer-Encoding: chunked) on POST routes, issues #67 and #74. v0.6.0 reads a body only by
+# Content-Length: a chunked request (what a proxy or an HTTP client streaming its body sends) has none, so the body was
+# read as empty ("messages must be a list" 400) and its unread chunks were parsed as the next request on the
+# keep-alive connection (the stdlib answers that in HTTP/0.9 mode: an HTML error page with no status line).
+# The reader is not written here: it is tensorfold/server/request_body.py read_body(), upstream TensorFold's 977f2cc
+# by Jordi Posthumus (JordiPosthumus), which patch 0084 adds for the Anthropic route (chunked incl. extensions and
+# trailers, strict sizes, Content-Length + Transfer-Encoding refused, size limit enforced while reading, the connection
+# closed on any framing error). This patch only uses it at the remaining body-reading sites, each keeping its own limit:
+# chat/completions and the tokenizer routes in cuda/http.py (96 MiB: up to 50 pictures or 4 clips as data URLs),
+# the MLX-style server/http.py (32 MiB), /v1/responses (32 MiB), and the 404 path's _discard_body (32 MiB). Requires 0084.
+# Behaviour change: a body with both Content-Length and Transfer-Encoding, or any other transfer coding, is now a 400
+# with Connection: close (read_body's rule) instead of being read by Content-Length.
+
+diff --git tensorfold/cuda/http.py tensorfold/cuda/http.py
+--- tensorfold/cuda/http.py
++++ tensorfold/cuda/http.py
+@@ -12,6 +12,7 @@
+ from tensorfold.server.cancellation import RequestCancelled, socket_cancellation
+ from tensorfold.server.errors import CapacityError, RequestError, admission_response, error_body
+ from tensorfold.server.http import Server
++from tensorfold.server.request_body import read_body
+ from tensorfold.server.stacks import Rearming
+
+ if TYPE_CHECKING:
+@@ -65,13 +66,9 @@
+ """Read a refused request's body, so it cannot reach the next request on this connection."""
+
+ try:
+- length = int(self.headers.get("Content-Length", 0))
+- except ValueError:
+- length = -1
+- if 0 <= length <= 32 * 1024**2:
+- self.rfile.read(length)
+- else:
+- self.close_connection = True
++ read_body(self) # Content-Length or chunked; a refusal has closed the connection
++ except RequestError:
++ pass
+
+ def _stream_error(self, error: dict[str, Any]) -> None:
+ """End an open stream with an error event and ``[DONE]``, as the MLX server does."""
+@@ -111,12 +108,10 @@
+ self._discard_body()
+ return self._json(404, {"error": "not found"})
+ try:
+- length = int(self.headers.get("Content-Length", 0))
+- if not 0 <= length <= 96 * 1024**2: # up to 50 pictures or 4 clips as data URLs
+- self.close_connection = True # the unread body must not reach the next request
+- return self._json(400, {"error": {"message": "request body exceeds the 96 MiB limit",
+- "type": "invalid_request_error"}})
+- body = json.loads(self.rfile.read(length) or b"{}")
++ # up to 50 pictures or 4 clips as data URLs; Content-Length or chunked (patch 0094)
++ body = json.loads(read_body(self, limit=96 * 1024**2) or b"{}")
++ except RequestError as exc:
++ return self._json(400, {"error": {"message": str(exc), "type": "invalid_request_error"}})
+ except (json.JSONDecodeError, UnicodeDecodeError):
+ return self._json(400, {"error": {"message": "the request body is not JSON", "type": "invalid_request_error"}})
+ if tokenizer: # vLLM's /tokenize and /detokenize
+diff --git tensorfold/server/http.py tensorfold/server/http.py
+--- tensorfold/server/http.py
++++ tensorfold/server/http.py
+@@ -12,6 +12,7 @@
+
+ from tensorfold.engine import grammar
+ from tensorfold.server import anthropic, responses
++from tensorfold.server.request_body import read_body
+ from tensorfold.server.tools import (active_tool_specs, parse_tool_calls_from_content, stream_tool_call_deltas,
+ tool_choice_requires_call)
+ from tensorfold.server.errors import CapacityError, RequestError, admission_response, error_body
+@@ -104,13 +105,9 @@
+ """Read a refused request's body, so it cannot reach the next request on this connection."""
+
+ try:
+- length = int(self.headers.get("Content-Length", "0"))
+- except ValueError:
+- length = -1
+- if 0 <= length <= 32 * 1024**2:
+- self.rfile.read(length)
+- else:
+- self.close_connection = True
++ read_body(self) # Content-Length or chunked; a refusal has closed the connection
++ except RequestError:
++ pass
+
+ def _route(self) -> str:
+ # Tolerate query strings, trailing slashes and client URLs with or without the /v1 prefix.
+@@ -198,11 +195,7 @@
+ return
+
+ try:
+- length = int(self.headers.get("Content-Length", "0"))
+- if not 0 <= length <= 32 * 1024**2:
+- self.close_connection = True # the unread body must not reach the next request
+- raise RequestError("request body exceeds the 32 MiB limit")
+- body = parse_numbers(json.loads(self.rfile.read(length) or b"{}"))
++ body = parse_numbers(json.loads(read_body(self) or b"{}")) # Content-Length or chunked (patch 0094)
+ validate_modalities(body)
+ probability_options(body)
+ named = reply_model(app, body) # the id the request asked for, as vLLM names it
+diff --git tensorfold/server/responses.py tensorfold/server/responses.py
+--- tensorfold/server/responses.py
++++ tensorfold/server/responses.py
+@@ -14,6 +14,7 @@
+ from typing import Any, Callable
+
+ from tensorfold.server.errors import RequestError
++from tensorfold.server.request_body import read_body
+ from tensorfold.server.responses_translate import Reply, _id, messages, translate
+
+ LIMIT = 32 * 1024**2
+@@ -182,12 +183,9 @@
+
+ store = store_for(app)
+ try:
+- length = int(handler.headers.get("Content-Length") or 0)
+- if not 0 <= length <= LIMIT:
+- handler.close_connection = True # the unread body must not reach the next request
+- raise RequestError("request body exceeds the 32 MiB limit")
++ data = read_body(handler, limit=LIMIT) # Content-Length or chunked (patch 0094)
+ try:
+- body = json.loads(handler.rfile.read(length) or b"{}")
++ body = json.loads(data or b"{}")
+ except (ValueError, UnicodeDecodeError):
+ raise RequestError("the request body is not JSON") from None
+ request = translate(body, store)
diff --git a/scripts/config.sh b/scripts/config.sh
index 83d9f3a..7c158ef 100644
--- a/scripts/config.sh
+++ b/scripts/config.sh
@@ -224,6 +224,7 @@ export TF_GLM_CLEAR_THINKING="${TF_GLM_CLEAR_THINKING:-0}"
# queues as every scheduler always has; 0 refuses anything past the lanes. A single-instance deployment with
# no load balancer in front of it should set a small value (ours: 0, in scripts/local.sh).
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"
# 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
diff --git a/tools/test_chunked_bodies.py b/tools/test_chunked_bodies.py
new file mode 100644
index 0000000..570d62f
--- /dev/null
+++ b/tools/test_chunked_bodies.py
@@ -0,0 +1,161 @@
+"""CPU-only in-process HTTP test of chunked request bodies (issues #67 and #74).
+
+ python3 -B tools/test_chunked_bodies.py --source-root /path/to/patched/src
+Use --expect-stock on the unpatched source to reproduce the reports: a Transfer-Encoding: chunked body is read as empty
+("messages must be a list", 400), and its unread chunks, taken for the next request, draw the stdlib's HTML
+"Error response" after the JSON, with no status line (HTTP/0.9 mode), past the declared Content-Length.
+Runs the real CUDA-server handler (tensorfold.cuda.http) on a loopback port with a stub app; no torch, GPU or models.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import socket
+import sys
+import threading
+from http.server import ThreadingHTTPServer
+
+
+def start(root):
+ sys.path.insert(0, root)
+ from tensorfold.cuda.http import make_handler
+ from tensorfold.server.errors import RequestError
+
+ class App:
+ model_ids = ["m"]
+ served_name = "m"
+
+ def reply_model(self, body):
+ return "m"
+
+ def prepare(self, body, chat):
+ if not isinstance(body.get("messages"), list):
+ raise RequestError("messages must be a list")
+ return body
+
+ def run(self, body, chat, emit, prepared=None, cancelled=None):
+ text = body["messages"][-1]["content"]
+ return {"content": "echo:" + str(text), "reasoning": None, "calls": None, "finish": "stop",
+ "stats": {}, "prompt_tokens": 3, "completion_tokens": 2}
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), make_handler(App()))
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ return server
+
+
+def chunked(payload: bytes, size=7, ext="", trailer=b"") -> bytes:
+ out = b""
+ for i in range(0, len(payload), size):
+ part = payload[i:i + size]
+ out += f"{len(part):x}{ext}\r\n".encode() + part + b"\r\n"
+ return out + b"0\r\n" + trailer + b"\r\n"
+
+
+def request(path, body: bytes, *, chunks=None, extra=b"") -> bytes:
+ head = f"POST {path} HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\n".encode() + extra
+ if chunks is not None:
+ return head + b"Transfer-Encoding: chunked\r\n\r\n" + chunks
+ return head + f"Content-Length: {len(body)}\r\n\r\n".encode() + body
+
+
+def read_response(sock_file):
+ """One response read by its Content-Length, as a strict keep-alive client would; (status, headers, body)."""
+
+ line = sock_file.readline()
+ if not line.startswith(b"HTTP/1.") :
+ raise AssertionError(f"not a status line (framing lost): {line!r}")
+ status = int(line.split()[1])
+ headers = {}
+ while (h := sock_file.readline()) not in (b"\r\n", b""):
+ k, _, v = h.decode().partition(":")
+ headers[k.strip().lower()] = v.strip()
+ return status, headers, sock_file.read(int(headers.get("content-length", 0)))
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--source-root", required=True)
+ ap.add_argument("--expect-stock", action="store_true")
+ args = ap.parse_args()
+ server = start(args.source_root)
+ port = server.server_address[1]
+ msgs = json.dumps({"model": "m", "messages": [{"role": "user", "content": "hi"}]}).encode()
+
+ def conn():
+ s = socket.create_connection(("127.0.0.1", port), timeout=5)
+ return s, s.makefile("rb")
+
+ if args.expect_stock:
+ s, f = conn()
+ s.sendall(request("/v1/chat/completions", msgs, chunks=chunked(msgs)))
+ status, _, body = read_response(f)
+ extra = f.read1(65536) if hasattr(f, "read1") else b""
+ s.settimeout(1)
+ try:
+ extra = extra or s.recv(65536)
+ except OSError:
+ pass
+ assert status == 400 and b"messages must be a list" in body, (status, body)
+ print(f"stock: 400 {body.decode()}; bytes after the declared Content-Length: {extra[:60]!r}")
+ return
+
+ # 1. a chunked chat completion, then more requests on the same connection: exact framing throughout
+ s, f = conn()
+ s.sendall(request("/v1/chat/completions", msgs, chunks=chunked(msgs)))
+ status, _, body = read_response(f)
+ assert status == 200 and json.loads(body)["choices"][0]["message"]["content"] == "echo:hi", (status, body)
+ s.sendall(request("/v1/chat/completions", msgs)) # Content-Length, same socket
+ assert read_response(f)[0] == 200
+ s.sendall(request("/v1/chat/completions", b"{}", chunks=chunked(b"{}", ext=";name=v", trailer=b"X-T: 1\r\n")))
+ status, _, body = read_response(f) # no messages: a clean 400 and a usable socket
+ assert status == 400 and b"messages must be a list" in body, (status, body)
+ s.sendall(request("/v1/chat/completions", msgs, chunks=chunked(msgs, size=1))) # one byte a chunk
+ assert read_response(f)[0] == 200
+ s.sendall(b"GET /v1/models HTTP/1.1\r\nHost: x\r\n\r\n")
+ assert read_response(f)[0] == 200, "framing lost after the chunked requests"
+ # 2. the chunks arriving in separate TCP segments
+ raw = request("/v1/chat/completions", msgs, chunks=chunked(msgs, size=5))
+ for i in range(0, len(raw), 9):
+ s.sendall(raw[i:i + 9])
+ assert read_response(f)[0] == 200
+ # 3. a refused path with a chunked body: 404, the body consumed, the socket still framed
+ s.sendall(request("/nope", msgs, chunks=chunked(msgs)))
+ assert read_response(f)[0] == 404
+ s.sendall(request("/v1/chat/completions", msgs))
+ assert read_response(f)[0] == 200, "a refused chunked body leaked into the next request"
+ s.close()
+ # 3b. /v1/responses, chunked
+ s, f = conn()
+ rbody = json.dumps({"model": "m", "input": "hi", "store": False}).encode()
+ s.sendall(request("/v1/responses", rbody, chunks=chunked(rbody, size=6)))
+ status, _, body = read_response(f)
+ assert status == 200 and json.loads(body)["status"] == "completed", (status, body)
+ s.sendall(request("/v1/responses", rbody))
+ assert read_response(f)[0] == 200, "framing lost after a chunked /v1/responses"
+ s.close()
+ # 4. malformed chunking: a 400 and the connection closed
+ for bad in (b"zz\r\nabc\r\n0\r\n\r\n", b"3\r\nabcde\r\n0\r\n\r\n", b"3\r\nabc"):
+ s, f = conn()
+ s.sendall(request("/v1/chat/completions", b"", chunks=bad))
+ s.shutdown(socket.SHUT_WR) if bad.endswith(b"abc") else None
+ status, headers, body = read_response(f)
+ assert status == 400 and "malformed chunked" in body.decode(), (bad, status, body)
+ assert headers.get("connection") == "close", headers
+ s.close()
+ # 5. a body past the limit is refused as soon as its chunks say so, and the connection closed
+ s, f = conn()
+ s.sendall(request("/v1/chat/completions", b"", chunks=f"{97 * 1024 ** 2:x}\r\n".encode()))
+ status, headers, body = read_response(f)
+ assert status == 400 and "96 MiB" in body.decode() and headers.get("connection") == "close", (status, body, headers)
+ s.close()
+ # 6. Transfer-Encoding with another coding is refused
+ s, f = conn()
+ s.sendall(request("/v1/chat/completions", b"", chunks=b"", extra=b"X: 1\r\n").replace(b"chunked", b"gzip, chunked"))
+ status, headers, body = read_response(f)
+ assert status == 400 and "Transfer-Encoding" in body.decode(), (status, body)
+ s.close()
+ print("chunked request bodies: framing intact on keep-alive connections, malformed and oversize bodies refused and closed")
+
+
+if __name__ == "__main__":
+ main()