Files
alzeo/tests/test_proxy_chunked_body.py
Hasan BasbunarandClaude Opus 5.5 4e22e96e44 proxy, cockpit: what an independent review found in this version, each with its test
A key header of 64 KB of "\n" was read in 8.7 s under the interpreter's lock, with no key, every stream of the box still: it is
refused at once. The red banner of a start that barely moves is no longer drawn again at each reading, its Stop with it. The
words of a box with no lane name what starts one, and a start's length by lane. llama-server's own /chat/completions gets a
chat keepalive. The relay's sign-in page names where this browser reaches the cockpit, through a tunnel or TLS. A body the
cockpit does not read is never its connection's next request. A chunked body shows its size in Traffic. The other box of a
pair is told before a silent stream is cut, and binds nothing for it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:28:36 +01:00

268 lines
12 KiB
Python

"""A request body sent in chunks (v6.63).
A client that streams its body (.NET's PostAsJsonAsync, a fetch with a stream body, Go and Java clients,
a gateway in front) sends Transfer-Encoding: chunked and no Content-Length. The proxy read that as no
body at all: the engine got an empty one and answered "Field required" to a client that had sent it
(Node 24 and http.client, 2026-11-30). The body is decoded and goes on with a Content-Length; one framed
two ways, or wrong, is refused and its connection closed."""
import http.client
import http.server
import importlib.util
import json
import os
import re
import socket
import sys
import threading
import time
import unittest
from pathlib import Path
REPO = Path(__file__).resolve().parents[1]
KEY = "the-serving-key-of-this-test"
class Engine(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
seen = []
def log_message(self, *a):
pass
def do_POST(self):
raw = self.rfile.read(int(self.headers.get("Content-Length") or 0))
if self.path == "/v1/chat/completions":
self.seen.append((raw, self.headers.get("Content-Length"), self.headers.get("Transfer-Encoding")))
out = json.dumps({"got": len(raw)}).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(out)))
self.end_headers()
self.wfile.write(out)
class Base(unittest.TestCase):
ENV = {}
@classmethod
def setUpClass(cls):
saved = dict(os.environ)
cls.addClassCleanup(lambda: (os.environ.clear(), os.environ.update(saved)))
cls.engine = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Engine)
cls.engine.daemon_threads = True
threading.Thread(target=cls.engine.serve_forever, daemon=True).start()
cls.addClassCleanup(cls.engine.server_close)
cls.addClassCleanup(cls.engine.shutdown)
os.environ.update({"UPSTREAM": f"http://127.0.0.1:{cls.engine.server_port}", "CLIENT_IO_S": "5",
"PROMPT_CEILING_TOKENS": "0", "PROXY_HOLD_UNITS": "", "QWEN38_UPSTREAM_API_KEY": KEY, **cls.ENV})
spec = importlib.util.spec_from_file_location(f"kp_chunk_{time.time_ns()}", REPO / "keepalive-proxy.py")
cls.mod = importlib.util.module_from_spec(spec)
sys.argv = ["keepalive-proxy.py"]
spec.loader.exec_module(cls.mod)
cls.journal = []
cls.mod.log = cls.journal.append
cls.mod._SERVED.update(names=("m",), engine="sglang", ts=time.time())
cls.mod._POOL.update(tokens=10_000_000, window=1000, ts=time.time())
cls.proxy = cls.mod.Server(("127.0.0.1", 0), cls.mod.H)
threading.Thread(target=cls.proxy.serve_forever, daemon=True).start()
cls.addClassCleanup(cls.proxy.server_close)
cls.addClassCleanup(cls.proxy.shutdown)
def setUp(self):
Engine.seen.clear()
self.journal.clear()
@staticmethod
def chunks(*parts, end=b"0\r\n\r\n"):
return b"".join(b"%x\r\n" % len(p) + p + b"\r\n" for p in parts) + end
def send(self, body, headers=("Transfer-Encoding: chunked",), version="HTTP/1.1", key=KEY, half=False, path="/v1/chat/completions"):
"""(status, the answer's body, whether the proxy then closed) to a request sent raw."""
s = socket.create_connection(("127.0.0.1", self.proxy.server_address[1]), timeout=8)
try:
auth = f"Authorization: Bearer {key}\r\n" if key else ""
s.sendall((f"POST {path} {version}\r\nHost: p\r\nContent-Type: application/json\r\n{auth}"
+ "".join(h + "\r\n" for h in headers) + "\r\n").encode())
try:
s.sendall(body)
except OSError:
pass
if half:
s.shutdown(socket.SHUT_WR)
got, closed = b"", False
try:
while True:
c = s.recv(65536)
if not c:
closed = True
break
got += c
except ConnectionResetError:
closed = True
except (socket.timeout, TimeoutError):
pass
finally:
s.close()
head, _, rest = got.partition(b"\r\n\r\n")
return int(head.split(b" ")[1]) if head.startswith(b"HTTP/") else 0, rest, closed, len(re.findall(rb"HTTP/1\.1 \d{3} ", got))
ASK = {"model": "m", "messages": [{"role": "user", "content": "café " * 40}]}
RAW = json.dumps(ASK, ensure_ascii=False).encode()
class AChunkedBodyReachesTheEngineWhole(Base):
def reaches(self, body, raw=RAW, **k):
status, rest, closed, answers = self.send(body, **k)
self.assertEqual((status, closed, answers), (200, True, 1), rest)
self.assertEqual(len(Engine.seen), 1)
got, length, te = Engine.seen[0]
self.assertEqual(got, raw)
self.assertEqual((length, te), (str(len(raw)), None), "the engine gets a Content-Length")
def test_one_chunk(self):
self.reaches(self.chunks(RAW))
self.assertEqual(sum(f"-> POST /v1/chat/completions body={len(RAW)}b" in ln for ln in self.journal), 1,
"the cockpit's Traffic reads its size there")
self.assertEqual(sum("-> POST" in ln for ln in self.journal), 1)
def test_many_chunks_cut_anywhere(self):
self.reaches(self.chunks(*[RAW[i:i + 1] for i in range(len(RAW))]))
def test_extensions_trailers_and_a_size_in_capitals(self):
body = b"%X;name=value\r\n" % len(RAW) + RAW + b"\r\n0\r\nX-Trailer: 1\r\nX-Other: 2\r\n\r\n"
self.reaches(body)
def test_a_large_one(self):
raw = json.dumps({"model": "m", "messages": [{"role": "user", "content": "x" * 3_000_000}]}).encode()
self.reaches(self.chunks(*[raw[i:i + 700_001] for i in range(0, len(raw), 700_001)]), raw=raw)
def test_the_coding_named_in_capitals(self):
self.reaches(self.chunks(RAW), headers=("Transfer-Encoding: Chunked",))
def test_expect_100_continue(self):
s = socket.create_connection(("127.0.0.1", self.proxy.server_address[1]), timeout=8)
self.addCleanup(s.close)
s.sendall(f"POST /v1/chat/completions HTTP/1.1\r\nHost: p\r\nAuthorization: Bearer {KEY}\r\n"
f"Content-Type: application/json\r\nTransfer-Encoding: chunked\r\nExpect: 100-continue\r\n\r\n".encode())
self.assertIn(b"100 Continue", s.recv(1000))
s.sendall(self.chunks(RAW))
self.assertIn(b"200 OK", s.recv(1000))
self.assertEqual(Engine.seen[0][0], RAW)
def test_http_client_sends_one_as_a_gateway_does(self):
c = http.client.HTTPConnection("127.0.0.1", self.proxy.server_address[1], timeout=8)
self.addCleanup(c.close)
c.request("POST", "/v1/chat/completions", body=iter([RAW[:30], RAW[30:]]), encode_chunked=True,
headers={"Authorization": f"Bearer {KEY}", "Content-Type": "application/json", "Transfer-Encoding": "chunked"})
self.assertEqual(c.getresponse().status, 200)
self.assertEqual(Engine.seen[0][0], RAW)
def test_the_guards_read_it(self):
raw = json.dumps({**ASK, "top_logprobs": 999999, "logprobs": True}).encode()
status, rest, _, _ = self.send(self.chunks(raw))
self.assertEqual(status, 400, rest)
self.assertIn(b"top_logprobs", rest)
self.assertEqual(Engine.seen, [])
def test_the_next_request_of_the_connection_is_never_read_from_its_bytes(self):
smuggled = (f"POST /v1/chat/completions HTTP/1.1\r\nHost: p\r\nAuthorization: Bearer {KEY}\r\n"
f"Content-Length: 2\r\n\r\n{{}}").encode()
status, _, closed, answers = self.send(self.chunks(RAW) + smuggled)
self.assertEqual((status, closed, answers, len(Engine.seen)), (200, True, 1, 1))
class ABodyFramedWrongIsRefused(Base):
def refused(self, want, body=None, **k):
status, rest, closed, answers = self.send(self.chunks(RAW) if body is None else body, **k)
self.assertEqual((status, closed, answers), (want, True, 1), rest)
self.assertEqual(Engine.seen, [], "the engine was asked")
return json.loads(rest.decode())["error"]["message"]
def test_a_content_length_beside_its_chunks(self):
for length in (len(RAW), 0, 5):
self.refused(400, headers=(f"Content-Length: {length}", "Transfer-Encoding: chunked"))
def test_chunks_on_http_1_0(self):
self.refused(400, version="HTTP/1.0")
def test_another_coding(self):
for te in ("gzip, chunked", "gzip", "identity", "chunked, chunked", "xchunked", ""):
self.refused(501, headers=(f"Transfer-Encoding: {te}",))
self.refused(501, headers=("Transfer-Encoding: gzip", "Transfer-Encoding: chunked"))
def test_a_size_that_is_none(self):
for size in (b"", b"-5", b"+5", b"0x5", b"5_0", b"zz", b"5 5", b"f" * 16, b"5" + b" " * 1100):
with self.subTest(size=size[:20]):
Engine.seen.clear()
self.refused(400, body=size + b"\r\n" + RAW + b"\r\n0\r\n\r\n")
def test_a_chunk_longer_than_its_size(self):
self.refused(400, body=b"5\r\n" + RAW + b"\r\n0\r\n\r\n")
def test_trailers_without_end(self):
self.refused(400, body=b"%x\r\n" % len(RAW) + RAW + b"\r\n0\r\n" + b"X: y\r\n" * 3000 + b"\r\n")
def test_one_cut_by_its_caller_is_not_sent_on(self):
for body in (b"%x\r\n" % len(RAW) + RAW[:50], self.chunks(RAW, end=b""), self.chunks(RAW, end=b"0\r\n"), b"5"):
self.journal.clear()
status, _, _, _ = self.send(body, half=True)
self.assertIn(status, (0, 400))
self.assertEqual(Engine.seen, [])
self.assertTrue([ln for ln in self.journal if "CLIENT GONE before its body" in ln or "REFUSED" in ln], self.journal)
self.assertEqual(sum("-> POST" in ln for ln in self.journal), 1, self.journal)
def test_the_key_is_asked_before_a_chunk_is_read(self):
for key in (None, "another"):
status, _, _, _ = self.send(self.chunks(RAW), key=key)
self.assertEqual(status, 401)
self.assertEqual(Engine.seen, [])
class ItsCeilings(Base):
ENV = {"MAX_BODY_BYTES": "300000", "BODY_SMALL_BYTES": "70000", "BODY_BUDGET_BYTES": "200000", "BODY_WAIT_S": "0.2"}
def test_over_the_cap(self):
status, rest, closed, _ = self.send(self.chunks(*[b"x" * 50_000] * 7))
self.assertEqual((status, closed), (413, True))
self.assertIn(b"300000b cap", rest)
self.assertEqual(Engine.seen, [])
def test_a_size_over_the_cap_is_refused_before_its_bytes(self):
status, _, _, _ = self.send(b"ffffffff\r\n")
self.assertEqual(status, 413)
def no_body_in_flight(self):
"""The room of the request before is given back after its answer."""
for _ in range(100):
if not self.mod._BODY_BUDGET["used"]:
return
time.sleep(0.02)
self.fail(f"{self.mod._BODY_BUDGET} once every request is over")
def test_the_bodies_in_flight_leave_it_no_room(self):
self.no_body_in_flight()
with self.mod._BODY_ROOM:
self.mod._BODY_BUDGET["used"] = 150_000
self.mod._BODY_READERS.add(-1) # an older body being read: this one waits for no room
self.addCleanup(self.mod._BODY_READERS.discard, -1)
self.addCleanup(self.mod._BODY_BUDGET.update, used=0)
status, rest, _, _ = self.send(self.chunks(*[b"x" * 50_000] * 4))
self.assertEqual(status, 503, rest)
self.assertEqual(Engine.seen, [])
for _ in range(50):
if self.mod._BODY_BUDGET["used"] == 150_000:
break
time.sleep(0.02)
self.assertEqual(self.mod._BODY_BUDGET["used"], 150_000, "its room was given back")
def test_its_room_is_given_back_once_it_is_answered(self):
raw = json.dumps({"model": "m", "messages": [{"role": "user", "content": "x" * 150_000}]}).encode()
status, _, _, _ = self.send(self.chunks(raw))
self.assertEqual(status, 200)
self.no_body_in_flight()
if __name__ == "__main__":
unittest.main()