Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.
C++
serve: a request waiting for the single turn sends keep-alives, and gives its place up when cancelled (#1619)
Niko1221875d6a922a2c
diff --git a/serve/server.py b/serve/server.pyindex 8ac047a65..862b22e2a 100644--- a/serve/server.py+++ b/serve/server.py@@ -196,6 +196,7 @@ def focused_recovery_prompt(tok, ids, generated):LOOPBACK_NAMES = ("localhost", "127.0.0.1", "::1")+QUEUE_BEAT_S = 10.0 # a request waiting for the single turn sends a keep-alive this often (#1619)CTX_SLACK = 8 # `strata --serve` rejects prompt + max_new + 8 > context: keep the same margin here# The live tok/s is a rate over a window, not a mean since the first token: a mean reads ~1/elapsed at the first# token (the Monitor showed five-digit numbers) and then undershoots for the first second of every answer.@@ -3469,7 +3470,32 @@ class Service:self.status["queued"] += 1try:# --batch: the engine runs several requests at once (StrataEngine.generate_batched orders them)- with (contextlib.nullcontext() if getattr(self.engine, "batch", 0) else self.fifo):+ turn = contextlib.ExitStack()+ if not getattr(self.engine, "batch", 0):+ # #1619: a request waiting for the single turn sends a keep-alive every QUEUE_BEAT_S, so a client with+ # a stream idle timeout does not abort a healthy queued request (and its retry read the prompt again);+ # a client that left while queued gives its place up instead of taking the turn only to cancel there+ got = False+ try:+ while not got:+ got = self.fifo.acquire(timeout=QUEUE_BEAT_S)+ if got:+ turn.callback(self.fifo.release)+ elif cancel.is_set():+ break+ else:+ yield "ping", None+ except BaseException: # the consumer closed us at a ping: no longer queued+ with self.status_lock:+ self.status["queued"] -= 1+ raise+ if not got: # cancelled while queued+ with self.status_lock:+ self.status["queued"] -= 1+ yield "done", {"finish": "cancel", "completion_tokens": 0, "reused": 0, "timings": None,+ "reasoning_tokens": 0, "reasoning_recoveries": 0}+ return+ with turn:try:with self.status_lock:if trace is not None:diff --git a/serve/test_queue_keepalive.py b/serve/test_queue_keepalive.pynew file mode 100644index 000000000..d7d356561--- /dev/null+++ b/serve/test_queue_keepalive.py@@ -0,0 +1,77 @@+"""#1619: a request waiting for the single request turn sends keep-alive comments (a client with a stream idle+timeout must not abort a healthy queued request), and one cancelled while queued leaves without taking the turn.++ python -m unittest serve.test_queue_keepalive -v+"""+import http.client+import json+import threading+import time+import unittest+from pathlib import Path+from unittest import mock++import serve.server as server+from serve.frontend import ChatTemplate+from serve.server import ByteTokenizer, MockEngine, Service, serve++ROOT = Path(__file__).resolve().parents[1]+++class QueueKeepAlive(unittest.TestCase):+ def setUp(self):+ tok = ByteTokenizer()+ self.svc = Service(MockEngine(tok, "ok"), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))+ self.httpd = serve(self.svc, port=0)+ self.addCleanup(self.httpd.server_close)+ self.addCleanup(self.httpd.shutdown)+ p = mock.patch.object(server, "QUEUE_BEAT_S", 0.1)+ p.start()+ self.addCleanup(p.stop)++ def test_a_queued_stream_gets_keep_alives_then_its_answer(self):+ self.svc.fifo.acquire() # another request holds the turn+ c = http.client.HTTPConnection("127.0.0.1", self.httpd.server_address[1], timeout=10)+ self.addCleanup(c.close)+ body = {"stream": True, "messages": [{"role": "user", "content": "hi"}]}+ c.request("POST", "/v1/chat/completions", json.dumps(body), {"Content-Type": "application/json"})+ r = c.getresponse()+ seen = b""+ t0 = time.monotonic()+ while seen.count(b": keep-alive") < 2 and time.monotonic() - t0 < 5:+ seen += r.fp.readline()+ self.assertGreaterEqual(seen.count(b": keep-alive"), 2, seen)+ self.assertEqual(self.svc.status["queued"], 1)+ self.svc.fifo.release()+ rest = r.read()+ self.assertIn(b"[DONE]", rest)+ self.assertIn(b'"finish_reason": "stop"', rest) # the answer ran once the turn was free+ self.assertEqual(self.svc.status["queued"], 0)++ def test_a_request_cancelled_while_queued_never_takes_the_turn(self):+ self.svc.fifo.acquire()+ self.addCleanup(self.svc.fifo.release)+ cancel = threading.Event()+ ids = self.svc.tok.encode("hi")+ run = self.svc.run(ids, False, None, 8, {}, cancel)+ first = next(run)+ self.assertEqual(first, ("ping", None))+ self.assertEqual(self.svc.status["queued"], 1)+ cancel.set()+ rest = list(run)+ self.assertEqual([k for k, _ in rest], ["done"])+ self.assertEqual(rest[0][1]["finish"], "cancel")+ self.assertEqual(self.svc.status["queued"], 0)+ self.assertTrue(self.svc.fifo.locked()) # still the other request's: we never held it++ def test_closing_a_queued_request_is_no_longer_queued(self):+ self.svc.fifo.acquire()+ self.addCleanup(self.svc.fifo.release)+ run = self.svc.run(self.svc.tok.encode("hi"), False, None, 8, {}, threading.Event())+ next(run)+ run.close()+ self.assertEqual(self.svc.status["queued"], 0)+++if __name__ == "__main__":+ unittest.main()diff --git a/serve/test_server.py b/serve/test_server.pyindex 368ac30fd..bcf722a88 100644--- a/serve/test_server.py+++ b/serve/test_server.py@@ -3577,21 +3577,21 @@ class StatusHandover(unittest.TestCase):def __init__(self):self.lock, self.armed = threading.Lock(), False- def acquire(self, blocking=True):- return self.lock.acquire(blocking)+ def acquire(self, blocking=True, timeout=-1):+ return self.lock.acquire(blocking, timeout)def __enter__(self):self.lock.acquire()def __exit__(self, *exc):+ self.release()++ def release(self):self.lock.release()if self.armed:self.armed = Falsesecond_running.wait(5)- def release(self):- self.lock.release()-svc = Service(Engine(tok, "</think>\n\n" + "y" * 40, max_context=CTX), tok,ChatTemplate(ROOT / "serve/chat_template.jinja"))svc.fifo = SlowRelease()