From 8bc4164f35cecaeb448291714b3bbf5ac3eec714 Mon Sep 17 00:00:00 2001 From: Hasan Basbunar Date: Mon, 30 Nov 2026 08:31:12 +0100 Subject: [PATCH] proxy v6.63: a duration is counted on the monotonic clock The hold and the keeper of a stream the engine has not answered counted on time.time(): a clock set forward by more than MAX_SILENCE_S (an NTP step after a boot, a hand) dropped a waiting stream as silent, and one set back wrote no more keepalive until it caught up (an in-process proxy with its clock moved, 2026-11-30). Every duration is counted on time.monotonic() now; what is compared with systemd's timestamps, and what dates the engine's facts, keeps the wall clock, an age below zero being no age. Co-Authored-By: Claude Opus 5.5 --- keepalive-proxy.py | 78 ++++++++++--------- tests/test_proxy_clock.py | 148 +++++++++++++++++++++++++++++++++++++ tests/test_proxy_resent.py | 2 +- 3 files changed, 192 insertions(+), 36 deletions(-) create mode 100644 tests/test_proxy_clock.py diff --git a/keepalive-proxy.py b/keepalive-proxy.py index 38157d03..6d778ac3 100755 --- a/keepalive-proxy.py +++ b/keepalive-proxy.py @@ -2436,6 +2436,12 @@ def tokenize_count(body, path): _POOL = {"tokens": None, "window": None, "ts": 0.0} +def fresh(ts, ttl): + """Whether what was read at ts (time.time()) is younger than ttl. An age below zero, after a clock + set back, is none: what it dates is read again instead of kept for the length of the jump.""" + return 0 <= time.time() - ts < ttl + + def invalidate_pool(): """Forget the cached pool, because the engine that reported it is gone. @@ -2598,7 +2604,7 @@ def _vllm_facts(key, timeout): def pool_tokens(): follow_engine_restarts() - if _POOL["tokens"] and time.time() - _POOL["ts"] < 600: + if _POOL["tokens"] and fresh(_POOL["ts"], 600): return _POOL["tokens"] try: try: @@ -2655,7 +2661,7 @@ def served_vocab(): engine turns every request carrying one of these fields into another 8-second probe, and a guard against a denial of service becomes one.""" follow_engine_restarts() # v6.37: a lane switch drops the last engine's vocabulary - if time.time() - _VOCAB["ts"] < (3600 if _VOCAB["size"] else 60): + if fresh(_VOCAB["ts"], 3600 if _VOCAB["size"] else 60): return _VOCAB["size"] _VOCAB["ts"] = time.time() # claimed before the probe, so a failure counts # The served name: vLLM refuses any other with a 404 before it looks at logit_bias (SGLang @@ -3527,7 +3533,7 @@ def served_models(): The whole list, because a lane that advertises an alias next to its path should answer to both, and the first one is the name the answers carry.""" follow_engine_restarts() - if _SERVED["names"] and time.time() - _SERVED["ts"] < 600: + if _SERVED["names"] and fresh(_SERVED["ts"], 600): return _SERVED["names"] try: key = _api_key() @@ -5852,7 +5858,7 @@ class Server(ThreadingHTTPServer): self._conn_lock = threading.Lock() self._conn_open = {} # address -> connections open from it, network peers only self._conn_counted = set() # the connections counted there, released once they end - self._conn_refusal_logged = 0.0 + self._conn_refusal_logged = None super().__init__(*args, **kwargs) def _conn_release(self, addr): @@ -5874,8 +5880,9 @@ class Server(ThreadingHTTPServer): self._conn_open[addr] = self._conn_open.get(addr, 0) + 1 self._conn_counted.add(request) if full: - if time.time() - self._conn_refusal_logged >= 60: # one line a minute, not one a connection - self._conn_refusal_logged = time.time() + now = time.monotonic() + if self._conn_refusal_logged is None or now - self._conn_refusal_logged >= 60: # one line a minute + self._conn_refusal_logged = now log(f"{addr} REFUSED a connection: past {MAX_CONN_PER_ADDRESS} open from one address " f"or {MAX_REMOTE_CONN} from the network (PROXY_MAX_CONN_PER_ADDRESS, PROXY_MAX_REMOTE_CONN)") self.shutdown_request(request) @@ -6211,8 +6218,8 @@ class H(BaseHTTPRequestHandler): self.wfile.flush() self.connection.shutdown(socket.SHUT_WR) self.connection.settimeout(idle_s) - end = time.time() + total_s - while time.time() < end and self.connection.recv(65536): + end = time.monotonic() + total_s + while time.monotonic() < end and self.connection.recv(65536): pass except OSError: pass @@ -6382,14 +6389,14 @@ class H(BaseHTTPRequestHandler): l = f"{self._last:.1f}s" if getattr(self, "_last", None) is not None else "never" st = f" [{self._bytes}b relayed, first event at {f}, last at {l}]" if not quiet: - log(f"{getattr(self, '_peer', '?')} {self.command} {self.path.split('?')[0]} {outcome} in {time.time()-self._t0:.1f}s{st}") + log(f"{getattr(self, '_peer', '?')} {self.command} {self.path.split('?')[0]} {outcome} in {time.monotonic()-self._t0:.1f}s{st}") def _note_gave_up(self, outcome: str) -> None: """Role 9: a client that left a long prompt without an answer, kept for RESEND_WINDOW_S.""" fp = getattr(self, "_prompt_fp", None) if not fp or outcome not in GAVE_UP_OUTCOMES or getattr(self, "_first", None) is not None: return - now = time.time() + now = time.monotonic() waited = now - self._t0 if waited < RESEND_MIN_S: return @@ -6403,7 +6410,7 @@ class H(BaseHTTPRequestHandler): """Role 9: the same long prompt again, soon after its client left it without an answer.""" with _GAVE_UP_LOCK: g = _GAVE_UP.get(self._prompt_fp) - if not g or time.time() - g["t"] > RESEND_WINDOW_S or g.get("resent"): + if not g or time.monotonic() - g["t"] > RESEND_WINDOW_S or g.get("resent"): return g["resent"] = True secs, n = g["secs"], g["n"] @@ -6874,8 +6881,9 @@ class H(BaseHTTPRequestHandler): if self._hold_until is None: if engine_answers(): return False - self._hold_until = time.time() + HOLD_MAX_S - self._held_from = time.time() + self._held_from = time.monotonic() + self._hold_until = self._held_from + HOLD_MAX_S + self._held_vocab = _VOCAB["ts"] # what was learned of the lane before: judged again once it is over self._hold_rounds = 0 log(f"{self._peer} holding: the engine does not answer ({why[:120]}) and its unit is on its " f"way back; this request waits for it, at most {HOLD_MAX_S:.0f}s") @@ -6895,19 +6903,19 @@ class H(BaseHTTPRequestHandler): self._held_sse = True next_ka = 0.0 pause = self._hold_rounds > 0 # a pause before the engine is asked again - while time.time() < self._hold_until: + while time.monotonic() < self._hold_until: if streamed: - if time.time() >= next_ka: + if time.monotonic() >= next_ka: try: self._chunk(self._keepalive()) except Exception: self._caller_left = True; return False - next_ka = time.time() + KEEPALIVE_S + next_ka = time.monotonic() + KEEPALIVE_S elif self._client_left(): self._caller_left = True; return False if pause: pause = False elif engine_answers(): - log(f"{self._peer} the engine answers again after {time.time() - self._held_from:.0f}s held; relaying") + log(f"{self._peer} the engine answers again after {time.monotonic() - self._held_from:.0f}s held; relaying") return True if not engine_coming(): log(f"{self._peer} the engine's unit is no longer on its way back; not waiting for it") @@ -7019,7 +7027,7 @@ class H(BaseHTTPRequestHandler): # already begun could orphan its generation (sglang#35255, in neither image served # here), so the watch starts once the engine has kept the stream waiting. The times # count from the request going out. - start = time.time() + start = time.monotonic() if done.wait(min(1.0, KEEPALIVE_S)): return sock = self.connection @@ -7033,7 +7041,7 @@ class H(BaseHTTPRequestHandler): while not done.is_set(): if self._stopped_while_routed(done): return - now = time.time() + now = time.monotonic() if now - start >= MAX_SILENCE_S: self._silent_before_head = now - start self._end_upstream(done, f"the engine has not answered in {now - start:.0f}s") @@ -7057,10 +7065,10 @@ class H(BaseHTTPRequestHandler): return next_ka = now + KEEPALIVE_S if not peek: - done.wait(min(KEEPER_TICK_S, max(0.0, next_ka - time.time()))) + done.wait(min(KEEPER_TICK_S, max(0.0, next_ka - time.monotonic()))) continue try: - readable = poller.poll(min(KEEPER_TICK_S, max(0.0, next_ka - time.time())) * 1000) + readable = poller.poll(min(KEEPER_TICK_S, max(0.0, next_ka - time.monotonic())) * 1000) except OSError: return if done.is_set(): @@ -7082,10 +7090,10 @@ class H(BaseHTTPRequestHandler): def _drain_detached(self, resp): """Read an abandoned response to its end in the background: see DRAIN_MAX_S.""" - t0 = time.time() + t0 = time.monotonic() def go(): try: - while time.time() - t0 < DRAIN_MAX_S: + while time.monotonic() - t0 < DRAIN_MAX_S: if not resp.read1(65536): break except Exception: @@ -7093,7 +7101,7 @@ class H(BaseHTTPRequestHandler): finally: try: resp.close() except Exception: pass - log(f"drained an abandoned {self.path.split('?')[0]} for {time.time()-t0:.0f}s") + log(f"drained an abandoned {self.path.split('?')[0]} for {time.monotonic()-t0:.0f}s") threading.Thread(target=go, daemon=True).start() def _relay_inner(self, resp): @@ -7229,7 +7237,7 @@ class H(BaseHTTPRequestHandler): try: resp.close() except Exception: pass else: - drain_t0[0] = time.time() + drain_t0[0] = time.monotonic() drain.set() def unblock(): @@ -7288,7 +7296,7 @@ class H(BaseHTTPRequestHandler): # same as the zombie would have, the log stays clean, and the # slot is released when the generation ends instead of being # held by a request whose state no longer exists. - if time.time() - drain_t0[0] > DRAIN_MAX_S: + if time.monotonic() - drain_t0[0] > DRAIN_MAX_S: log(f"drain ceiling reached after {DRAIN_MAX_S:.0f}s, " f"dropping the socket for {self.path.split('?')[0]}") break @@ -7332,7 +7340,7 @@ class H(BaseHTTPRequestHandler): # raising, and Python 3.14 warns of it at compile time (PEP 765) if drain.is_set(): log(f"drained an abandoned {self.path.split('?')[0]} for " - f"{time.time() - drain_t0[0]:.0f}s") + f"{time.monotonic() - drain_t0[0]:.0f}s") try: resp.close() except Exception: pass elif not cut and not ours(): @@ -7353,7 +7361,7 @@ class H(BaseHTTPRequestHandler): try: resp.close() except Exception: pass else: - drain_t0[0] = time.time() + drain_t0[0] = time.monotonic() drain.set() spool.clear() # drained, never written: what waited freed (the 4th review of v1.44.0) @@ -7420,7 +7428,7 @@ class H(BaseHTTPRequestHandler): try: resp.close() except Exception: pass self._done("UPSTREAM CUT"); return - now = time.time() - self._t0 + now = time.monotonic() - self._t0 if self._first is None: self._first = now self._last = now; self._bytes += len(val) if kind == "x": @@ -7468,7 +7476,7 @@ class H(BaseHTTPRequestHandler): # ---- verbs ------------------------------------------------------------- def _handle_inner(self, with_body): - self._t0 = time.time() + self._t0 = time.monotonic() self._peer = f"{self.client_address[0]}:{self.client_address[1]}" self._bytes = 0; self._first = None; self._last = None self._tool_calls = {}; self._tool_bytes = 0; self._answer_body = bytearray() # role 8 @@ -7694,7 +7702,7 @@ class H(BaseHTTPRequestHandler): # It was judged once, before, and went to the engine that came back as it was: # an id the old lane held and the new one does not took it down (found in # review, 2026-10-16). - if _VOCAB["ts"] < getattr(self, "_held_from", 0.0): + if _VOCAB["ts"] == getattr(self, "_held_vocab", None): _VOCAB.update(size=0, ts=0.0) if self._sampling_refused(asked): return @@ -8756,7 +8764,7 @@ class H(BaseHTTPRequestHandler): if cut >= 0: self._watch_tools(lines[:cut + 1], anthropic) tail = lines[cut + 1:][-TOOL_WATCH_MAX:] - t = time.time() - self._t0 + t = time.monotonic() - self._t0 self._first = t if self._first is None else self._first self._last, self._bytes = t, self._bytes + len(b) try: @@ -9308,7 +9316,7 @@ class H(BaseHTTPRequestHandler): finally: self._release_body() if not getattr(self, "_ended", False): - self._t0 = getattr(self, "_t0", time.time()) + self._t0 = getattr(self, "_t0", time.monotonic()) self._peer = getattr(self, "_peer", "?") try: self._done("no outcome (client vanished mid-request)") except Exception: pass @@ -9323,13 +9331,13 @@ class H(BaseHTTPRequestHandler): self._get_inner() finally: if not getattr(self, "_ended", False): - self._t0 = getattr(self, "_t0", time.time()) + self._t0 = getattr(self, "_t0", time.monotonic()) self._peer = getattr(self, "_peer", "?") try: self._done("no outcome (client vanished mid-request)") except Exception: pass def _get_inner(self): - self._t0 = time.time() + self._t0 = time.monotonic() self._peer = f"{self.client_address[0]}:{self.client_address[1]}" self._bytes = 0; self._first = None; self._last = None self._tool_calls = {}; self._tool_bytes = 0; self._answer_body = bytearray() # role 8 diff --git a/tests/test_proxy_clock.py b/tests/test_proxy_clock.py new file mode 100644 index 00000000..0dcbfb17 --- /dev/null +++ b/tests/test_proxy_clock.py @@ -0,0 +1,148 @@ +"""A box's clock that jumps: a duration is not read on it (v6.63). + +The hold, and the keeper of a stream the engine has not answered, counted their times on time.time(). +Set forward by more than MAX_SILENCE_S while a stream waited (an NTP step after a boot, a hand), the +proxy dropped it as silent; set back, it wrote no more keepalive until the clock caught up, and the +client gave up (an in-process proxy with its clock moved, 2026-11-30). The caches the engine's facts +are kept in have an age, which a clock set back made negative: kept for the length of the jump.""" +import http.server +import importlib.util +import json +import os +import socket +import sys +import threading +import time +import unittest +from pathlib import Path + +REPO = Path(__file__).resolve().parents[1] + + +def _no_key(): + raise FileNotFoundError("no serving key in this harness") + + +class Clock: + """The time module, its wall clock moved by shift.""" + shift = 0.0 + + def __getattr__(self, name): + return getattr(time, name) + + def time(self): + return time.time() + self.shift + + +class Engine(http.server.BaseHTTPRequestHandler): + """Answers a stream after the seconds its prompt says, headers included.""" + protocol_version = "HTTP/1.1" + + def log_message(self, *a): + pass + + def do_POST(self): + raw = self.rfile.read(int(self.headers.get("Content-Length") or 0)) + time.sleep(float(json.loads(raw)["messages"][0]["content"])) + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.send_header("Connection", "close") + self.end_headers() + self.wfile.write(b'data: {"id":"e","choices":[{"index":0,"delta":{"content":"hello"}}]}\n\ndata: [DONE]\n\n') + + +class AClockThatJumps(unittest.TestCase): + @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}", KEEPALIVE_S="0.3", MAX_SILENCE_S="100", + CLIENT_IO_S="10", PROMPT_CEILING_TOKENS="0", PROXY_HOLD_UNITS="") + spec = importlib.util.spec_from_file_location(f"kp_clock_{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.mod._api_key = _no_key + cls.mod.time = cls.clock = Clock() + cls.mod.log = lambda msg: None + 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): + self.clock.shift = 0.0 + self.addCleanup(setattr, self.clock, "shift", 0.0) + + def stream_with_a_jump(self, jump): + raw = json.dumps({"stream": True, "messages": [{"role": "user", "content": "2.6"}]}).encode() + s = socket.create_connection(("127.0.0.1", self.proxy.server_address[1]), timeout=10) + self.addCleanup(s.close) + s.sendall(b"POST /v1/chat/completions HTTP/1.1\r\nHost: p\r\nContent-Type: application/json\r\n" + b"Content-Length: %d\r\n\r\n" % len(raw) + raw) + threading.Timer(1.0, setattr, (self.clock, "shift", jump)).start() + got = b"" + while True: + c = s.recv(65536) + if not c: + return got + got += c + + def test_a_waiting_stream_outlives_a_clock_set_forward(self): + got = self.stream_with_a_jump(4000.0) + self.assertIn(b"hello", got, "dropped as silent: the engine answered 2.6 s after the request") + self.assertIn(b"data: [DONE]", got) + + def test_a_waiting_stream_keeps_its_keepalives_under_a_clock_set_back(self): + got = self.stream_with_a_jump(-4000.0) + self.assertIn(b"hello", got) + self.assertGreaterEqual(got.count(b'"id":"keepalive"'), 5, "none was written after the jump") + + def a_hold(self, answers_after): + m, h = self.mod, self.mod.H.__new__(self.mod.H) + h.path, h._peer, h._pair_box, h._hold_until, h._held_sse = "/v1/chat/completions", "t", None, None, True + wrote = [] + h._chunk = wrote.append + end = time.monotonic() + answers_after + for name, fn in (("engine_coming", lambda: True), ("engine_answers", lambda: time.monotonic() > end)): + self.addCleanup(setattr, m, name, getattr(m, name)) + setattr(m, name, fn) + for name, value in (("HOLD_MAX_S", 30.0), ("HOLD_POLL_S", 0.05)): + self.addCleanup(setattr, m, name, getattr(m, name)) + setattr(m, name, value) + return h._hold("the engine does not answer", True), wrote + + def test_a_hold_outlives_a_clock_set_forward(self): + threading.Timer(0.5, setattr, (self.clock, "shift", 4000.0)).start() + came, _ = self.a_hold(1.5) + self.assertTrue(came, "held 30 s at most, and the engine came back after 1.5 s") + + def test_a_hold_keeps_its_keepalives_under_a_clock_set_back(self): + threading.Timer(0.5, setattr, (self.clock, "shift", -4000.0)).start() + came, wrote = self.a_hold(2.0) + self.assertTrue(came) + self.assertGreaterEqual(len(wrote), 5, "none was written after the jump") + + def test_what_is_learned_of_an_engine_has_no_negative_age(self): + m = self.mod + asked = [] + for name in ("_server_info", "follow_engine_restarts"): + self.addCleanup(setattr, m, name, getattr(m, name)) + m.follow_engine_restarts = lambda: False + m._server_info = lambda *a: asked.append(1) or {"max_total_num_tokens": 7, "max_req_input_len": 5} + self.addCleanup(setattr, m, "_api_key", m._api_key) + m._api_key = lambda: "k" + m._POOL.update(tokens=9, window=9, ts=self.clock.time()) + self.assertEqual(m.pool_tokens(), 9) + self.clock.shift = -4000.0 + self.assertEqual(m.pool_tokens(), 7, "kept for the length of the jump") + self.assertEqual(asked, [1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_proxy_resent.py b/tests/test_proxy_resent.py index 4010560d..69d0bd8e 100644 --- a/tests/test_proxy_resent.py +++ b/tests/test_proxy_resent.py @@ -191,7 +191,7 @@ class OnlyAClientThatLeftBeforeAnyAnswerCounts(unittest.TestCase): def gave_up(self, outcome, first=None): self.mod._GAVE_UP.clear() handler = type("H", (), {})() - handler._prompt_fp, handler._first, handler._t0 = "f" * 16, first, time.time() - 600 + handler._prompt_fp, handler._first, handler._t0 = "f" * 16, first, time.monotonic() - 600 self.mod.H._note_gave_up(handler, outcome) return bool(self.mod._GAVE_UP)