"""The keepalive injection, which is the reason this proxy exists, and had no test. An agent CLI gives up on a silent stream. opencode and the AI SDK were measured dying at 140 to 180 seconds of silence, and a Qwen3.8 prefill of 200,000 tokens is longer than that, so the proxy writes something into the stream while the engine is quiet. Everything about that is easy to get subtly wrong, and one version did: v6.4 injected a keepalive in the middle of an SSE event and corrupted the stream. Coverage said 68% of keepalive-proxy.py before this file, and the missing 175 statements included this whole loop: the injection, the per-dialect payload, the max-silence drop, the mid-stream cut, and the non-streamed relay path. A fake engine here controls its own silence to the millisecond, so the tests are about the proxy's behaviour and not about timing luck. """ import http.server import importlib.util import json import os import socket import struct import sys import threading import time import unittest from pathlib import Path def _no_key(): """The serving key this harness's proxy holds: none, whatever HOME holds. Its clients send no key, as these tests were written, and since v6.34 a proxy that knows a key refuses them at the door (the CI's offline step gives HOME one). The door has its own tests, in tests/test_proxy_door.py.""" raise FileNotFoundError("no serving key in this harness") def _keep_env(cls): """Put os.environ back as this class found it, once it is done: the variables set for the proxy under test (UPSTREAM and the rest) stayed set for every module after this one (found in review, 2026-09-24; tests/test_suite_isolation.py holds it).""" saved = dict(os.environ) cls.addClassCleanup(lambda: (os.environ.clear(), os.environ.update(saved))) HERE = Path(__file__).resolve() REPO = HERE.parents[1] KEEPALIVE_S = 0.3 MAX_SILENCE_S = 1.5 class Engine(http.server.BaseHTTPRequestHandler): """Answers with a scripted pattern of events and silences. The request body says what to do: "silent:" n seconds of silence before the first event "gap:" n seconds of silence between two events "forever" never answer at all after the head "nonsse" a plain JSON answer, not a stream "cut" one event then close the socket mid-stream "bangs" an answer made of exclamation marks """ protocol_version = "HTTP/1.1" def log_message(self, *a): pass def _sse_head(self): self.send_response(200) self.send_header("Content-Type", "text/event-stream") self.send_header("Connection", "close") self.end_headers() def _event(self, text): rec = json.dumps({"id": "e", "choices": [{"delta": {"content": text}}]}) self.wfile.write(b"data: " + rec.encode() + b"\n\n") self.wfile.flush() def do_POST(self): raw = self.rfile.read(int(self.headers.get("Content-Length") or 0)).decode() # the script is the PROMPT, not the whole JSON: splitting the JSON text # gave tokens like '"silent:0.9"}]}' which match nothing, so the first # version of this engine never slept and three tests passed for the # wrong reason try: body = json.loads(raw)["messages"][0]["content"] except Exception: body = raw if self.path.split("?")[0] == "/abort_request": out = b'{"ok":true}' self.send_response(200) self.send_header("Content-Length", str(len(out))) self.end_headers() self.wfile.write(out) return if "reset" in body: # a genuine transport error, not a clean close: this is what makes # the proxy read an exception rather than end of stream self._sse_head() self._event("one") self.connection.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0)) self.connection.close() return if "nonsse" in body: payload = json.dumps({"choices": [{"message": { "content": "!" * 300 if "bangs" in body else "plain answer"}}]}).encode() self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(payload))) self.end_headers() self.wfile.write(payload) return if "headless" in body: time.sleep(6) # never an answer: its caller is told before return self._sse_head() try: if "forever" in body: time.sleep(30) return for token in body.split(): if token.startswith("silent:") or token.startswith("gap:"): time.sleep(float(token.split(":", 1)[1])) continue if "cut" in body: self._event("one") return # close mid-stream, no [DONE] self._event("hello") self.wfile.write(b"data: [DONE]\n\n") self.wfile.flush() except Exception: pass class Base(unittest.TestCase): @classmethod def setUpClass(cls): _keep_env(cls) 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() os.environ.update(UPSTREAM=f"http://127.0.0.1:{cls.engine.server_port}", KEEPALIVE_S=str(KEEPALIVE_S), MAX_SILENCE_S=str(MAX_SILENCE_S), CLIENT_IO_S="10", PROMPT_CEILING_TOKENS="0") spec = importlib.util.spec_from_file_location( f"kp_ka_{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.proxy = cls.mod.Server(("127.0.0.1", 0), cls.mod.H) threading.Thread(target=cls.proxy.serve_forever, daemon=True).start() cls.port = cls.proxy.server_address[1] @classmethod def tearDownClass(cls): cls.proxy.shutdown() cls.proxy.server_close() cls.engine.shutdown() cls.engine.server_close() def ask(self, prompt, path="/v1/chat/completions", read_for=None, headers="", **fields): """Send a request and read everything the proxy writes until it closes.""" raw = json.dumps({**fields, "messages": [{"role": "user", "content": prompt}]}).encode() s = socket.create_connection(("127.0.0.1", self.port), timeout=30) s.sendall(f"POST {path} HTTP/1.1\r\nHost: p\r\nContent-Type: application/json\r\n{headers}" f"Content-Length: {len(raw)}\r\n\r\n".encode() + raw) s.settimeout(read_for or 30) got = b"" try: while True: c = s.recv(8192) if not c: break got += c except (socket.timeout, TimeoutError): pass finally: s.close() return got @staticmethod def sse_records(chunked: bytes) -> list[bytes]: """The SSE records out of a chunked HTTP body, in order.""" head, _, body = chunked.partition(b"\r\n\r\n") out, rest = [], body # chunked framing: \r\n\r\n while True: line, _, rest = rest.partition(b"\r\n") if not line: break try: n = int(line.split(b";")[0], 16) except ValueError: break if n == 0: break out.append(rest[:n]) rest = rest[n + 2:] return out class KeepaliveInjection(Base): def test_a_silent_engine_gets_keepalives_and_the_answer_still_arrives(self): got = self.ask(f"silent:{KEEPALIVE_S * 3:.2f}") self.assertIn(b"hello", got) self.assertIn(b"[DONE]", got) self.assertIn(b'"id":"keepalive"', got, "no keepalive was injected") def test_the_openai_keepalive_is_an_authentic_empty_chunk(self): """A comment (`: ping`) is ignored by opencode's stall detector, which is why this is a real chunk. A client parsing it must find valid JSON, no content, and a choice to read: the commonest loop of all reads chunk.choices[0].delta.content, and raised an IndexError on an empty list (openai-python, 2026-11-30).""" got = self.ask(f"silent:{KEEPALIVE_S * 3:.2f}", model="qwen3.8-27b", stream=True) kas = [r for r in self.sse_records(got) if b'"id":"keepalive"' in r] self.assertTrue(kas, self.sse_records(got)) for rec in kas: self.assertTrue(rec.startswith(b"data: "), rec) payload = json.loads(rec[len(b"data: "):].strip()) self.assertEqual(payload["choices"], [{"index": 0, "delta": {}, "finish_reason": None}]) self.assertIsNone(payload["choices"][0]["delta"].get("content")) self.assertEqual(payload["object"], "chat.completion.chunk") self.assertEqual(payload["model"], "qwen3.8-27b", "the model the request named") def test_the_anthropic_keepalive_is_the_official_ping_event(self): got = self.ask(f"silent:{KEEPALIVE_S * 3:.2f}", path="/v1/messages") self.assertIn(b"event: ping", got) self.assertIn(b'{"type": "ping"}', got) self.assertNotIn(b'"id":"keepalive"', got, "the openai keepalive was sent on the anthropic route") def test_a_keepalive_never_lands_inside_an_event(self): """The v6.4 bug: a keepalive injected mid-JSON-line corrupts the stream. Every record the client receives must parse on its own.""" got = self.ask(f"silent:{KEEPALIVE_S * 2:.2f} gap:{KEEPALIVE_S * 2:.2f}") for rec in self.sse_records(got): text = rec.strip() if not text or text == b"data: [DONE]": continue self.assertTrue(text.startswith(b"data: ") or text.startswith(b"event: "), f"a record does not start a line: {text[:60]!r}") for line in text.split(b"\n"): if line.startswith(b"data: ") and line[6:].strip() != b"[DONE]": json.loads(line[6:]) # raises on a torn record def test_a_fast_answer_gets_no_keepalive_at_all(self): got = self.ask("now") self.assertIn(b"hello", got) self.assertNotIn(b"keepalive", got, "a keepalive was injected into a fast answer") class EachRouteHasItsOwnKeepalive(Base): """One shape went to every route but Anthropic's: a chat chunk inside a /v1/responses stream raised in openai-python's .stream() and read as an error in the AI SDK (2026-11-30).""" SILENT = f"silent:{KEEPALIVE_S * 3:.2f}" def records(self, *a, **k): return [r for r in self.sse_records(self.ask(*a, **k)) if b"keepalive" in r] def test_a_completions_stream_gets_a_text_completion_chunk(self): kas = self.records(self.SILENT, path="/v1/completions", model="m", stream=True) self.assertTrue(kas) for rec in kas: payload = json.loads(rec[len(b"data: "):].strip()) self.assertEqual(payload["object"], "text_completion") self.assertEqual(payload["choices"], [{"index": 0, "text": "", "finish_reason": None, "logprobs": None}]) self.assertEqual(payload["model"], "m") def test_a_responses_stream_gets_comments_before_its_first_event(self): """No event may come before response.created; a comment is no event.""" recs = self.sse_records(self.ask(self.SILENT, path="/v1/responses")) first = next(i for i, r in enumerate(recs) if b"hello" in r) self.assertGreaterEqual(first, 2, recs) self.assertEqual(set(recs[:first]), {b": keepalive\n\n"}) def test_a_responses_stream_gets_the_typed_event_after_its_first_event(self): h = self.mod.H.__new__(self.mod.H) h.path, h._first = "/v1/responses?x=1", None self.assertEqual(h._keepalive(), b": keepalive\n\n") h._first = 0.1 self.assertEqual(h._keepalive(), b'event: keepalive\ndata: {"type":"keepalive"}\n\n') def test_codex_gets_the_typed_event_from_the_start(self): """Only an event resets its idle timer, and it skips a type it does not know (0.144.4).""" for agent in ("codex_exec/0.144.4 (Linux; arm64)", "codex_cli_rs/0.172.0", "Codex Desktop/1.0"): recs = self.sse_records(self.ask(self.SILENT, path="/v1/responses", headers=f"User-Agent: {agent}\r\n")) first = next(i for i, r in enumerate(recs) if b"hello" in r) self.assertEqual(set(recs[:first]), {b'event: keepalive\ndata: {"type":"keepalive"}\n\n'}, agent) def test_llama_servers_own_chat_route_gets_a_chat_chunk(self): self.assertEqual(self.mod.keepalive_for("/chat/completions", "m"), self.mod.ka_openai("m")) def test_the_other_box_of_a_pair_is_told_before_the_cut_of_a_silent_stream(self): """A bare cut reads there as the death of this box's engine, and bound the request for 10 minutes.""" said = [] h = self.mod.H.__new__(self.mod.H) h.path = "/v1/chat/completions" h._chunk = lambda b: said.append("error" if b"upstream_silent" in b else b) h._say_ended_by_order = lambda: said.append("ended") h.connection = type("C", (), {"shutdown": lambda self, how: said.append("cut")})() h._end_silent(3600) self.assertEqual(said, ["error", "ended", "cut"]) def test_a_route_with_a_shape_of_its_own_gets_comments(self): recs = self.sse_records(self.ask(self.SILENT, path="/generate", stream=True)) self.assertIn(b": keepalive\n\n", recs) self.assertFalse([r for r in recs if b'"id":"keepalive"' in r], recs) def test_the_model_is_read_as_the_body_writes_it(self): asked = self.mod.asked_model self.assertEqual(asked(b'{"model": "a/b-1.2", "messages": []}'), "a/b-1.2") self.assertEqual(asked(b'{"messages":[{"content":"say \\"model\\": \\"no\\""}],"model":"yes"}'), "yes") self.assertEqual(asked('{"model":"caf\\u00e9"}'.encode()), "caf\u00e9") for body in (b"", None, b"not json", b'{"model": 3}', b'{"model": "\\ud8"}'): self.assertEqual(asked(body), "keepalive", body) def test_the_order_of_the_other_box_of_a_pair_is_unchanged(self): """Compared byte for byte between two boxes that may run different versions.""" self.assertEqual(self.mod.HOP_ENDED_OPENAI, b'data: {"id":"keepalive","object":"chat.completion.chunk","created":0,"model":"keepalive",' b'"choices":[],"x_alzeo_ended":"order"}\n\n') self.assertEqual(self.mod.HOP_ENDED_ANTHROPIC, b'event: ping\ndata: {"type": "ping", "x_alzeo_ended": "order"}\n\n') class SilenceCeiling(Base): def test_an_engine_silent_past_the_ceiling_is_dropped(self): t0 = time.time() got = self.ask("forever", read_for=MAX_SILENCE_S + 8) elapsed = time.time() - t0 self.assertLess(elapsed, MAX_SILENCE_S + 6, "the drop never happened") self.assertGreaterEqual(elapsed, MAX_SILENCE_S - 0.5, "it dropped before the ceiling") self.assertIn(b'"id":"keepalive"', got, "it dropped without ever keeping the client alive") def test_an_anthropic_client_is_told_why_its_stream_ended(self): got = self.ask("forever", path="/v1/messages", read_for=MAX_SILENCE_S + 8) self.assertIn(b"event: ping", got) self.assertIn(b"silent", got.lower(), "the drop was silent on the anthropic route") self.assertTrue(got.endswith(b"0\r\n\r\n"), got[-40:]) def test_an_openai_client_is_told_and_its_stream_is_cut_not_ended(self): """It got no event and the last chunk of a whole answer: openai-python and the AI SDK took an empty answer, or half of one, for a finished one (2026-11-30). Both silences: the engine that opened its stream, and the one that never answered.""" for path in ("/v1/chat/completions", "/v1/completions", "/v1/responses"): for prompt in ("forever", "headless"): got = self.ask(prompt, path=path, read_for=MAX_SILENCE_S + 8, stream=True) with self.subTest(path=path, prompt=prompt): self.assertTrue(got.startswith(b"HTTP/1.1 200"), got[:60]) self.assertIn(b'"upstream_silent"', got) self.assertNotIn(b"data: [DONE]", got) self.assertFalse(got.endswith(b"0\r\n\r\n"), "ended as a whole answer") class NonStreamedAndCutStreams(Base): def test_a_non_streamed_answer_is_relayed_whole(self): got = self.ask("nonsse") self.assertIn(b"plain answer", got) def test_a_non_streamed_wall_of_markers_is_named_in_the_answer_path(self): """The corruption guard: a non-streamed answer cannot be withheld, so what the proxy can do is see it: the answer still arrives, and the journal names the corruption. Only the first half was asserted, so a proxy that saw nothing passed (found in review, 2026-09-24).""" logged = [] real_log, self.mod.log = self.mod.log, logged.append try: got = self.ask("nonsse bangs") end = time.time() + 3 while time.time() < end and not any("corrupted output" in m for m in logged): time.sleep(0.02) finally: self.mod.log = real_log self.assertIn(b"!" * 100, got) self.assertTrue(any("corrupted output in a non-streamed answer" in m for m in logged), logged) def test_an_engine_that_closes_without_done_still_ends_the_body_cleanly(self): """A clean close with no [DONE] is end of stream, not an error: the proxy forwards what arrived and terminates the chunked body. It must not invent a [DONE] the engine never sent.""" got = self.ask("cut") self.assertIn(b"one", got) self.assertIn(b"0\r\n\r\n", got, "the chunked body was not terminated") self.assertNotIn(b"[DONE]", got, "the proxy invented an end the engine never sent") def test_a_transport_error_mid_stream_reaches_the_client_as_one(self): """A reset is different from a close: the read raises, and the client's stream is cut the same way, with no chunk to end the body, so no client takes what it got for a whole answer, and no event in the engine's place. The error event this test wanted made Claude Code send the request again without a stream, held in silence by v6.28 while the engine came back, which it gave up on after about 330 s (an engine made a zombie under real clients, 2026-10-01); a cut stream it sends again as a stream.""" for path in ("/v1/messages", "/v1/chat/completions"): with self.subTest(path=path): got = self.ask("reset", path=path) self.assertIn(b"one", got) self.assertNotIn(b"0\r\n\r\n", got, "the cut body was closed as if it were whole") self.assertNotIn(b"interrupted", got.lower()) self.assertNotIn(b"[DONE]", got) def test_a_transport_error_mid_stream_ends_an_openai_stream_without_a_lie(self): got = self.ask("reset") self.assertIn(b"one", got) self.assertNotIn(b"[DONE]", got) if __name__ == "__main__": unittest.main(verbosity=2)