mirror of
https://github.com/hasso5703/alzeo.git
synced 2026-12-05 20:34:17 +01:00
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 <noreply@anthropic.com>
149 lines
6.3 KiB
Python
149 lines
6.3 KiB
Python
"""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()
|