GLM-5.3-Flash EXL3 on 2x DGX Spark with TensorFold
Python
Patch 0113: GET and DELETE request bodies read before the response
Christopher A. Williamson7d2566da8bf9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cf3dba7..bc9d71a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -158,6 +158,15 @@ Every change to this recipe, newest first. Each release names the image it servevision line for 15 minutes, every rank spinning); with the patch it serves in 145 s. Both loaders now copy eachtensor out of the mmap first (`.clone()`): the same bytes, one host copy a tensor at start; the main weights usedirect reads and never had the problem. CPU check: `tools/mmap_upload_check.py` (fails on the unpatched loaders).+- **A GET with a body no longer breaks the next request on its connection** (patch `0113-http-get-delete-body-discard`,+ by [cawilliamson](https://github.com/cawilliamson)): the CUDA handler's `do_GET` and `do_DELETE` never read a request+ body, so a GET or DELETE carrying one left its bytes on the keep-alive connection and the stdlib parsed them as the+ next request's start: a "Bad request syntax" 400, an HTML page with no JSON, for whatever came next. Scanners probe+ with GET bodies, and behind a pooling proxy (nginx upstream keepalive) the next request on that connection is often+ another client's: the cross-session 400s that prompted this, with the probe's bytes quoted in a real agent's error.+ Both now read the body through `0059`'s `_discard_body` (`read_body`: Content-Length or chunked; a refusal closes the+ connection) before answering; a request without one reads nothing. CPU test: `tools/test_get_bodies.py` (fails on+ the unpatched source).## v1.10 (2026-10-08): the effort line at the tail (opt-in), a kept-state share, and a checked second raildiff --git a/CREDITS.md b/CREDITS.mdindex 597b70a..28f9b06 100644--- a/CREDITS.md+++ b/CREDITS.md@@ -88,6 +88,8 @@ checkpoint's ShapleyMcg attribution and the drafter's license).past 1023.- `0059-server-refused-bodies`: TensorFold v0.6.1's fix for #181 (commit 50dfe38a, by[SxMShaDoW](https://github.com/SxMShaDoW)), backported to v0.6.0.+- `0113-http-get-delete-body-discard` (GET and DELETE bodies read before the response, as `0059` does for refused+ requests): by [cawilliamson](https://github.com/cawilliamson).- `0060-glm-keep-thinking` (earlier turns keep their reasoning, `TF_GLM_CLEAR_THINKING`): by[kky42](https://github.com/kky42), pull request #23.- `0071-glm-shared-prefix-copy` (a shared system prompt's resume keeps the writer's kept prompt, issue #43): bydiff --git a/README.md b/README.mdindex 1ea1ee2..f79dd0e 100644--- a/README.md+++ b/README.md@@ -704,6 +704,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 |+| GET and DELETE bodies | `0113-http-get-delete-body-discard` | `do_GET` and `do_DELETE` read a request's body (Content-Length or chunked, through `0059`'s `_discard_body`) before answering; they read none, so a GET with a body (scanners send them) left its bytes on the keep-alive connection, parsed as the next request on it: a stdlib "Bad request syntax" 400 for whatever came next, behind a pooling proxy often another client's (by [cawilliamson](https://github.com/cawilliamson)) | the next request on the connection is answered as sent || 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 |@@ -755,6 +756,7 @@ with [sparkDash](https://github.com/MiaAI-Lab/sparkDash) ([Performance](#perform| --- | --- || `tools/needle.py [label] [size]` | hides a passphrase in a ~195k-token prompt (the prompt comes out at ~0.8 x `size` tokens) and checks the model returns it || `tools/toolcheck.py` | makes a tool call with an array parameter and checks it comes back as a JSON array |+| `tools/test_get_bodies.py --source-root DIR` | patch 0113's checks on the CPU, against TensorFold's source with the patches applied: the real CUDA handler on a loopback port, GETs and a DELETE with Content-Length and chunked bodies, each followed by more requests on the same keep-alive connection, and a GET body past the limit closing it; `--expect-stock` reproduces the leaked body's 400 on the unpatched source || `tools/display_kv_check.py [--gpu]` | patch 0072's checks, run in the image (`docker run ... --entrypoint python`, see the file): the setting, the span's mapping and unwinding through a fake driver, the carved planes and the pool's copies; with `--gpu`, the real span on a Spark whose display reservation is free || `tools/qmm_noclusters_check.py [--time]` | patch 0103's checks: the installed 4-bit matmul against a build of the same sources with the old cluster rule, bit for bit at every decode shape of TP=4, TP=3 and TP=2 and at the 28 Mi edge, the path each call takes (and with `TF_GLM_QMM_CLUSTERS=1`), and a CUDA graph on side streams; run in the image on one GPU (`docker run --gpus all ... --entrypoint python`, see the file); `--time` prints the old and new paths' times || `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`) |diff --git a/patches/0113-http-get-delete-body-discard.patch b/patches/0113-http-get-delete-body-discard.patchnew file mode 100644index 0000000..f8b3839--- /dev/null+++ b/patches/0113-http-get-delete-body-discard.patch@@ -0,0 +1,59 @@+# GET and DELETE requests have their bodies read. The CUDA handler's do_GET and do_DELETE never read a body, so a GET+# or DELETE carrying one (scanners send GETs with a body) left those bytes on the keep-alive connection, and the+# stdlib parsed them as the start of the next request on it: a "Bad request syntax" 400, in HTML with no JSON, for+# whatever came next. Behind a pooling proxy (nginx upstream keepalive) that next request is often another client's.+# Both now call _discard_body (patch 0059's helper, read_body underneath: Content-Length or chunked, a refusal closes+# the connection) before answering, as do_POST's refusals already do. A request without a body reads nothing. A GET or+# DELETE has no use for a body, so the read is bounded at 64 KiB (not the 32 MiB a POST may carry): a larger one is+# refused unread and the connection closed, so a stream of big GET bodies cannot make the server buffer them.+# tools/test_get_bodies.py.++--- tensorfold/cuda/http.py++++ tensorfold/cuda/http.py+@@ -15,7 +15,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.request_body import LIMIT, read_body+ from tensorfold.server.stacks import Rearming++ if TYPE_CHECKING:+@@ -23,6 +23,7 @@+++ _TOKENIZER_ROUTES = ("/tokenize", "/v1/tokenize", "/detokenize", "/v1/detokenize")++_BODY_DISCARD_LIMIT = 64 * 1024 # a GET or DELETE has no use for a body: one this large closes the connection+++ def _keepalive_seconds() -> float:+@@ -127,11 +128,11 @@+ except (BrokenPipeError, ConnectionResetError): # the client has gone+ self.close_connection = True++- def _discard_body(self) -> None:++ def _discard_body(self, limit: int = LIMIT) -> None:+ """Read a refused request's body, so it cannot reach the next request on this connection."""++ try:+- read_body(self) # Content-Length or chunked; a refusal has closed the connection++ read_body(self, limit=limit) # Content-Length or chunked; a refusal has closed the connection+ except RequestError:+ pass++@@ -146,6 +147,7 @@+ self.close_connection = True++ def do_GET(self):++ self._discard_body(_BODY_DISCARD_LIMIT)+ route = self.path.split("?", 1)[0].rstrip("/")+ if route in ("/metrics", "/v1/metrics"):+ return metrics.send(self, app)+@@ -160,6 +162,7 @@+ self._json(404, {"error": "not found"})++ def do_DELETE(self):++ self._discard_body(_BODY_DISCARD_LIMIT)+ responses.delete(self, app, responses.route(self.path))++ def do_POST(self):diff --git a/tools/test_get_bodies.py b/tools/test_get_bodies.pynew file mode 100644index 0000000..a2cc738--- /dev/null+++ b/tools/test_get_bodies.py@@ -0,0 +1,136 @@+"""CPU-only in-process HTTP test of GET and DELETE requests that carry a body (patch 0113).++ python3 -B tools/test_get_bodies.py --source-root /path/to/patched/src+Use --expect-stock on the unpatched source to reproduce the failure: do_GET and do_DELETE never read a body, so a+GET with a body (scanners send them) leaves its bytes on the keep-alive connection, and the server parses them as the+start of the next request: a stdlib "Bad request syntax" 400 for whatever request comes next on that connection. Behind+a pooling proxy (nginx upstream keepalive) that next request can be another user's.+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++ class App:+ model_ids = ["m"]+ served_name = "m"++ def reply_model(self, body):+ return "m"++ def prepare(self, body, chat):+ return body++ def run(self, body, chat, emit, prepared=None, cancelled=None):+ return {"content": "ok", "reasoning": None, "calls": None, "finish": "stop",+ "stats": {}, "prompt_tokens": 3, "completion_tokens": 1}++ server = ThreadingHTTPServer(("127.0.0.1", 0), make_handler(App()))+ threading.Thread(target=server.serve_forever, daemon=True).start()+ return server+++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 with_body(method: str, path: str, body: bytes) -> bytes:+ return f"{method} {path} HTTP/1.1\r\nHost: x\r\nContent-Length: {len(body)}\r\n\r\n".encode() + body+++def chunked(method: str, path: str, body: bytes) -> bytes:+ return (f"{method} {path} HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: chunked\r\n\r\n".encode()+ + f"{len(body):x}\r\n".encode() + body + b"\r\n0\r\n\r\n")+++MODELS = b"GET /v1/models HTTP/1.1\r\nHost: x\r\n\r\n"+PROBE = b"<?php system($_GET['c']); ?>" # what the scanners put in a GET body+++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]++ 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(with_body("GET", "/v1/models", PROBE))+ assert read_response(f)[0] == 200+ s.sendall(MODELS) # the next request on the same connection+ status, _, body = read_response(f)+ assert status == 400 and b"Bad request" in body, (status, body)+ print(f"stock: the GET's body was parsed as the next request: {status} {body[:80]!r}")+ return++ msgs = json.dumps({"model": "m", "messages": [{"role": "user", "content": "hi"}]}).encode()+ # 1. a GET with a body (Content-Length), then more requests on the same connection: framing intact+ s, f = conn()+ s.sendall(with_body("GET", "/v1/models", PROBE))+ status, _, body = read_response(f)+ assert status == 200 and json.loads(body)["data"][0]["id"] == "m", (status, body)+ s.sendall(MODELS)+ assert read_response(f)[0] == 200, "a GET's body leaked into the next request"+ s.sendall(with_body("POST", "/v1/chat/completions", msgs))+ status, _, body = read_response(f)+ assert status == 200 and json.loads(body)["choices"][0]["message"]["content"] == "ok", (status, body)+ # 2. a chunked body on a GET (an unknown route: the 404 path), then the next request+ s.sendall(chunked("GET", "/nope", PROBE))+ assert read_response(f)[0] == 404+ s.sendall(MODELS)+ assert read_response(f)[0] == 200, "a chunked GET body leaked into the next request"+ # 3. a DELETE with a body, then the next request+ s.sendall(with_body("DELETE", "/v1/responses/resp_none", PROBE))+ status, _, body = read_response(f)+ assert status in (200, 404), (status, body)+ s.sendall(MODELS)+ assert read_response(f)[0] == 200, "a DELETE's body leaked into the next request"+ # 4. GETs without a body still answer at once (nothing to read, nothing waited for)+ for _ in range(3):+ s.sendall(MODELS)+ assert read_response(f)[0] == 200+ s.close()+ # 4b. a body of 100 KiB, over the 64 KiB a GET may carry: answered, connection closed, nothing buffered+ s, f = conn()+ s.sendall(f"GET /v1/models HTTP/1.1\r\nHost: x\r\nContent-Length: {100 * 1024}\r\n\r\n".encode())+ status, headers, _ = read_response(f)+ assert status == 200 and headers.get("connection") == "close", (status, headers)+ s.close()+ # 5. a GET body past the limit: refused framing closes the connection instead of reading on+ s, f = conn()+ s.sendall(f"GET /v1/models HTTP/1.1\r\nHost: x\r\nContent-Length: {97 * 1024 ** 2}\r\n\r\n".encode())+ s.settimeout(5)+ status, headers, _ = read_response(f)+ assert status == 200 and headers.get("connection") == "close", (status, headers)+ s.close()+ print("GET and DELETE bodies: read before the response, framing intact on keep-alive connections")+++if __name__ == "__main__":+ main()