diff --git a/keepalive-proxy.py b/keepalive-proxy.py index cedcf904..b87e5611 100755 --- a/keepalive-proxy.py +++ b/keepalive-proxy.py @@ -4345,6 +4345,36 @@ def _peek(sock): return sock.recv(1, socket.MSG_PEEK | socket.MSG_DONTWAIT) +class _Wake(threading.Event): + """The end of a request's wait, as an Event a select() also waits on: set() makes its pipe readable. The + keepers watched the caller in a select() of 0.5 s and _forward joins them before relaying, so every + non-streamed answer, and every stream whose engine took more than a second, waited for the keeper's next + tick: 503 ms through the proxy for an answer the engine gave in 35 ms (measured on the reference box, + v1.41.0, 2026-11-03).""" + + def __init__(self): + super().__init__() + self._r, self._w = os.pipe() + os.set_blocking(self._w, False) + + def fileno(self): + return self._r + + def set(self): + super().set() + try: + os.write(self._w, b"x") + except OSError: + pass # already written, or closed: the Event says it + + def close(self): + for fd in (self._r, self._w): + try: + os.close(fd) + except OSError: + pass + + def _counted_peer(addr): """True for a peer whose connections count against the network's ceilings: any but loopback.""" try: @@ -5396,9 +5426,11 @@ class H(BaseHTTPRequestHandler): if self._stopped_while_routed(done): return try: - readable, _, _ = select.select([sock], [], [], 0.5) + readable, _, _ = select.select([sock, done] if isinstance(done, _Wake) else [sock], [], [], 0.5) except (OSError, ValueError): return + if done.is_set(): + return # the answer came: woken at once (_Wake), not at the next tick if not readable: continue try: @@ -5506,9 +5538,12 @@ class H(BaseHTTPRequestHandler): done.wait(min(0.5, max(0.0, next_ka - time.time()))) continue try: - readable, _, _ = select.select([sock], [], [], min(0.5, max(0.0, next_ka - time.time()))) + readable, _, _ = select.select([sock, done] if isinstance(done, _Wake) else [sock], [], [], + min(0.5, max(0.0, next_ka - time.time()))) except (OSError, ValueError): return + if done.is_set(): + return # the engine answered: woken at once (_Wake) if not readable: continue try: @@ -6451,7 +6486,7 @@ class H(BaseHTTPRequestHandler): if not self._floor_refused(): self._cut_stopped() return None - done = threading.Event() + done = _Wake() self._wlock = threading.Lock() # the keeper writes into the stream until _open returns whole = bool(body) and answered_whole(body) keeper = None @@ -6465,6 +6500,8 @@ class H(BaseHTTPRequestHandler): done.set() # headers, or an error: the generation is over if keeper is not None: keeper.join(timeout=CLIENT_IO_S) + if keeper is None or not keeper.is_alive(): + done.close() # a keeper still in select() keeps its pipe: never a reused fd there with self._wlock: # and nothing is half-written into the stream pass if getattr(self, "_caller_left", False): diff --git a/tests/test_proxy_hold.py b/tests/test_proxy_hold.py index c1eb33f7..9c7d1e2c 100644 --- a/tests/test_proxy_hold.py +++ b/tests/test_proxy_hold.py @@ -66,6 +66,7 @@ class Engine(http.server.BaseHTTPRequestHandler): body = self.rfile.read(int(self.headers.get("Content-Length") or 0)) if self.server.mode == "starting": return self._empty(503) + time.sleep(getattr(self.server, "delay", 0)) if self.path == "/tokenize": return self._json(200, {"count": len(body) // 4}) self.server.generations.append(self.path) @@ -99,7 +100,7 @@ class Box: """One engine port, one proxy, one systemctl state file. The proxy runs as its own process, or (inproc) in this one, where the coverage gate of CI can see its lines.""" - def __init__(self, test, units=UNITS, hold_max="30", state="activating", inproc=False): + def __init__(self, test, units=UNITS, hold_max="30", state="activating", inproc=False, keepalive="1"): self.test = test self.t = Path(tempfile.mkdtemp(prefix="proxy-hold-")) test.addCleanup(shutil.rmtree, self.t, True) @@ -125,7 +126,7 @@ class Box: self.srv = None self.generations = [] env = dict(os.environ, UPSTREAM=f"http://127.0.0.1:{self.engine_port}", HOME=str(self.t / "home"), - PATH=f"{self.t / 'bin'}:{os.environ.get('PATH', '')}", KEEPALIVE_S="1", + PATH=f"{self.t / 'bin'}:{os.environ.get('PATH', '')}", KEEPALIVE_S=keepalive, PROXY_HOLD_MAX_S=hold_max, PROXY_HOLD_POLL_S="0.2") env.pop("PROXY_HOLD_UNITS", None) if units: @@ -157,12 +158,13 @@ class Box: """What `systemctl list-jobs --no-legend` prints: JOB UNIT TYPE STATE.""" self.jobs_file.write_text("".join(ln + "\n" for ln in lines)) - def start_engine(self, mode="up", pool=200000, info_mode=None): + def start_engine(self, mode="up", pool=200000, info_mode=None, delay=0.0): if self.srv is None: self.srv = localports.serve(self.engine_port, http.server.ThreadingHTTPServer, Engine) self.srv.generations = self.generations threading.Thread(target=self.srv.serve_forever, daemon=True).start() self.srv.mode, self.srv.pool, self.srv.info_mode = mode, pool, info_mode or mode + self.srv.delay = delay # seconds before each generation is answered def stop_engine(self): if self.srv is not None: @@ -304,6 +306,40 @@ class ANonStreamedRequestWaitsInSilence(unittest.TestCase): self.assertEqual(json.loads(reply.raw)["choices"][0]["message"]["content"], "four") +class AnAnswerIsRelayedTheMomentItComes(unittest.TestCase): + """The keepers watched the caller in a select() of 0.5 s and the relay waited for their next tick: a + non-streamed answer took 503 ms through the proxy for 35 ms at the engine, and a stream whose engine took + over a second lost up to 0.5 s more (measured on the reference box, v1.41.0, 2026-11-03).""" + INPROC = False + + def box(self, **kw): + return Box(self, inproc=self.INPROC, **kw) + + def test_a_non_streamed_answer_is_relayed_at_once(self): + box = self.box() + box.start_engine() + took = [] + for _ in range(3): + reply = box.send(stream=False) + self.assertTrue(reply.done.wait(15)) + self.assertEqual((reply.status, json.loads(reply.raw)["choices"][0]["message"]["content"]), (200, "four")) + took.append(reply.first_at) + self.assertLess(min(took), 0.25, took) + + def test_a_stream_whose_engine_took_over_a_second_is_relayed_at_once(self): + # no keepalive is due in the meantime (5 s), so the headers the client gets are the engine's + box = self.box(keepalive="5") + box.start_engine(delay=1.05) + took = [] + for _ in range(3): + reply = box.send(stream=True) + self.assertTrue(reply.done.wait(15)) + self.assertEqual(reply.status, 200) + self.assertTrue(any('"four"' in e for e in reply.content()), reply.events) + took.append(reply.first_at - 1.05) + self.assertLess(min(took), 0.25, took) + + class WhatIsNotWaitedFor(unittest.TestCase): INPROC = False @@ -620,6 +656,16 @@ class ANonStreamedRequestWaitsInSilenceInProcess(ANonStreamedRequestWaitsInSilen super().test_it_gets_its_answer_when_the_engine_is_back() +class AnAnswerIsRelayedTheMomentItComesInProcess(AnAnswerIsRelayedTheMomentItComes): + INPROC = True + + def test_a_non_streamed_answer_is_relayed_at_once(self): + super().test_a_non_streamed_answer_is_relayed_at_once() + + def test_a_stream_whose_engine_took_over_a_second_is_relayed_at_once(self): + super().test_a_stream_whose_engine_took_over_a_second_is_relayed_at_once() + + class WhatIsNotWaitedForInProcess(WhatIsNotWaitedFor): INPROC = True @@ -679,7 +725,7 @@ class AHoldEndsInProcess(AHoldEnds): class EveryCaseHasItsInProcessTwin(unittest.TestCase): def test_each_twin_declares_every_case_of_its_class(self): for twin in (AStreamedRequestWaitsForItsEngineInProcess, ANonStreamedRequestWaitsInSilenceInProcess, - WhatIsNotWaitedForInProcess, AHoldEndsInProcess): + AnAnswerIsRelayedTheMomentItComesInProcess, WhatIsNotWaitedForInProcess, AHoldEndsInProcess): base = twin.__bases__[0] cases = {n for n in vars(base) if n.startswith("test_")} self.assertTrue(cases, base.__name__)