#!/usr/bin/env python3 """Two live streams must never share each other's bytes. junction handles every connection in its own thread. relay_stream() and relay_dechunk() used to keep their read buffer in a `static` array, so two concurrent answers read into the same memory: each client received deltas from several completions, and splinter assembled them into text with words missing and sentences from other answers spliced in. This test gives every completion a unique id and every delta an index. A correct stream contains the indices 0..N-1 in order, all from one id. Any mixture is a failure. Run against the real junction binary and a local fake upstream only; no models, no network. """ import json import os import socket import subprocess import sys import tempfile import threading import time import urllib.request from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer JUNCTION_PORT = int(os.environ.get("RACE_JUNCTION_PORT", "0")) UPSTREAM_PORT = int(os.environ.get("RACE_UPSTREAM_PORT", "0")) CLIENTS = 8 ROUNDS = 3 EVENTS = 240 def free_port(): """A port nobody holds right now; the test binds it immediately after.""" with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind(("127.0.0.1", 0)) return s.getsockname()[1] class Upstream(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def log_message(self, *a): pass def do_POST(self): n = int(self.headers.get("Content-Length", "0")) self.rfile.read(n) with self.server.id_lock: rid = self.server.next_id self.server.next_id += 1 self.send_response(200) self.send_header("Content-Type", "text/event-stream") self.send_header("Transfer-Encoding", "chunked") self.send_header("Cache-Control", "no-store") self.end_headers() def write_chunk(payload): self.wfile.write(b"%x\r\n" % len(payload) + payload + b"\r\n") self.wfile.flush() for i in range(EVENTS): obj = {"id": "chatcmpl-%d" % rid, "object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {"content": "%d:%d " % (rid, i)}}]} write_chunk(b"data: " + json.dumps(obj).encode() + b"\n\n") # The race window is between junction's read() and write(). Jitter # keeps the threads from marching in lockstep. time.sleep(0.0004 + (i % 7) * 0.00015) write_chunk(b'data: {"id":"end","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}\n\n') write_chunk(b"data: [DONE]\n\n") write_chunk(b"") def wait_port(port, seconds=5.0): end = time.time() + seconds while time.time() < end: try: with socket.create_connection(("127.0.0.1", port), 0.1): return True except OSError: time.sleep(0.02) return False def one(client_no, url, results, lock): body = json.dumps({"model": "fake", "stream": True, "messages": [{"role": "user", "content": "go"}]}).encode() req = urllib.request.Request(url, data=body, headers={ "Content-Type": "application/json", "Authorization": "Bearer test"}) try: with urllib.request.urlopen(req, timeout=30) as resp: raw = resp.read() except Exception as e: # noqa: BLE001 - report, do not crash the suite with lock: results.append((client_no, "http error: %r" % (e,))) return ids, indices, errors = set(), [], [] for line in raw.decode("utf-8", "replace").splitlines(): if not line.startswith("data: "): continue payload = line[6:] if payload == "[DONE]": continue try: obj = json.loads(payload) except Exception as e: # noqa: BLE001 errors.append("bad JSON (%s): %.100r" % (e, payload)) continue delta = ((obj.get("choices") or [{}])[0].get("delta") or {}).get("content") if not delta: continue try: rid, i = delta.strip().split(":") ids.add(rid) indices.append(int(i)) except ValueError: errors.append("bad delta: %.100r" % (delta,)) if errors: detail = "; ".join(errors[:3]) elif len(ids) != 1: detail = "deltas came from %d completions: %s" % (len(ids), sorted(ids)) elif indices != list(range(EVENTS)): detail = "indices not 0..%d (got %d, first gap at %s)" % ( EVENTS - 1, len(indices), next((i for i, v in enumerate(indices) if i != v), len(indices))) else: detail = "" with lock: results.append((client_no, detail)) def main(): global JUNCTION_PORT, UPSTREAM_PORT binary = sys.argv[1] if len(sys.argv) > 1 else "./junction" if JUNCTION_PORT == 0: JUNCTION_PORT = free_port() if UPSTREAM_PORT == 0: UPSTREAM_PORT = free_port() while UPSTREAM_PORT == JUNCTION_PORT: UPSTREAM_PORT = free_port() tmp = tempfile.mkdtemp(prefix="junction-race-") config = os.path.join(tmp, "race.conf") with open(config, "w") as f: f.write("""listen 127.0.0.1:%d max_inflight %d cache_ttl 0 probe_interval 0 endpoint fake { base http://127.0.0.1:%d/v1 kind local context 100000 timeout 30 idle_timeout 15 } req for "*" check none pass fake """ % (JUNCTION_PORT, CLIENTS * 2, UPSTREAM_PORT)) upstream = ThreadingHTTPServer(("127.0.0.1", UPSTREAM_PORT), Upstream) upstream.daemon_threads = True upstream.next_id = 0 upstream.id_lock = threading.Lock() threading.Thread(target=upstream.serve_forever, daemon=True).start() log = open(os.path.join(tmp, "junction.log"), "w") junction = subprocess.Popen([binary, "--config", config], stdout=log, stderr=subprocess.STDOUT) try: if not wait_port(JUNCTION_PORT) or not wait_port(UPSTREAM_PORT): print("junction or fake upstream did not come up", file=sys.stderr) return 1 url = "http://127.0.0.1:%d/v1/chat/completions" % JUNCTION_PORT failures = 0 for round_no in range(ROUNDS): results, lock = [], threading.Lock() threads = [threading.Thread(target=one, args=(i, url, results, lock)) for i in range(CLIENTS)] for t in threads: t.start() for t in threads: t.join() for client_no, detail in sorted(results): if detail: print("round %d client %d: %s" % (round_no + 1, client_no, detail)) failures += 1 if failures: print("stream race: %d of %d streams carried foreign or missing deltas" % (failures, ROUNDS * CLIENTS)) log.flush() with open(log.name) as f: tail = f.read()[-1500:] if tail: print("junction log tail:\n" + tail, file=sys.stderr) return 1 print("%d/%d streams clean" % (ROUNDS * CLIENTS, ROUNDS * CLIENTS)) return 0 finally: junction.terminate() try: junction.wait(timeout=5) except subprocess.TimeoutExpired: junction.kill() upstream.shutdown() log.close() if __name__ == "__main__": sys.exit(main())