serve: say Connection: close on every response

The server is HTTP/1.0 and closes the connection after each response, but
never said so. A client that pools connections (.NET's SocketsHttpHandler)
then sometimes put its next request on the closing socket and got
'response ended prematurely' without the server ever reading it: 25 of
~1000 requests in one night from an agent app, each 1-24 ms after the
previous answer.
This commit is contained in:
Evan authored and Niko1221 committed 2026-10-05 13:16:53 +02:00
1 parent 38c9a4dce2
commit a42a0c0b00
2 files changed
+32

No files matched your search

+8
View File
@@ -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
+24
View File
@@ -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, "</think>\n\n" + cls.ANSWER, max_context=CTX)
cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
cls.svc = Service(MockEngine(tok, "</think>\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()