diff --git a/serve/server.py b/serve/server.py index 22ebeabd..a23f7952 100644 --- a/serve/server.py +++ b/serve/server.py @@ -3098,6 +3098,14 @@ def make_handler(svc: Service): return True return False + def end_headers(self): + # HTTP/1.0 without keep-alive: the server closes the connection after every response. Say so, or a + # client that pools connections (.NET's SocketsHttpHandler) can put its next request on this socket + # before the close reaches it, and that request fails with "response ended prematurely" without the + # server ever reading it (a .NET agent app, 2026-10-03: 25 of ~1000 requests, 1-24 ms after the previous answer). + self.send_header("Connection", "close") + super().end_headers() + def _watch_client(self, cancel: threading.Event) -> None: """#430 #431: cancel the request as soon as its client hangs up. A non-streamed request writes nothing until it ends, and a streamed one only a keep-alive per prompt chunk (and the first write after a hang-up diff --git a/serve/test_server.py b/serve/test_server.py index a5c5be97..e1b04c1d 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -3109,11 +3109,20 @@ class StopStrings(unittest.TestCase): across tokens (and across streamed chunks).""" ANSWER = "alpha END beta STOP gamma" + +class ConnectionClose(unittest.TestCase): + """The server is HTTP/1.0 and closes the connection after every response. Without saying so, .NET's pooled + HttpClient put its next request on the closing socket and got "response ended prematurely" (2026-10-03).""" + @classmethod def setUpClass(cls): tok = ByteTokenizer() cls.engine = CountingEngine(tok, "\n\n" + cls.ANSWER, max_context=CTX) cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + + + cls.svc = Service(MockEngine(tok, "\n\nok", max_context=CTX), tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) cls.httpd = serve(cls.svc, port=0) cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}" @@ -3318,5 +3327,20 @@ class AnswerBeforeTheBody(unittest.TestCase): self.assertEqual(self.status("PUT", "/v1/chat/completions"), "HTTP/1.0 501 Unsupported method ('PUT')") + def headers(self, stream): + body = {"model": "x", "max_tokens": 20, "messages": [{"role": "user", "content": "hi"}], "stream": stream} + req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=30) as r: + r.read() + return r.headers + + def test_a_non_streamed_answer_says_the_connection_closes(self): + self.assertEqual(self.headers(stream=False).get("Connection"), "close") + + def test_a_streamed_answer_says_the_connection_closes(self): + self.assertEqual(self.headers(stream=True).get("Connection"), "close") + + if __name__ == "__main__": unittest.main()