#!/usr/bin/env python3
"""clientcheck.py - is your LLM benchmark client the bottleneck?

A fixed-latency OpenAI-compatible mock server (standard library only) plus a probe.
Point any load generator (vllm bench serve, guidellm, aiperf, k6, your own AsyncOpenAI
script) at the mock. The server knows the true time to first token (TTFT) and the true
inter-token latency (ITL) it delivered, and how many requests were really in flight.
Whatever your tool reports above those numbers was added on the client side.

  python3 clientcheck.py serve  --port 8765 --ttft-ms 50 --itl-ms 20 --tokens 64
  # ... run your tool against http://127.0.0.1:8765/v1 (model name: mock) ...
  python3 clientcheck.py report --port 8765            # server-side truth, then resets

  python3 clientcheck.py probe  --port 8765 --client aiohttp --concurrency 1,64,256 \
          --requests-per-level 4x
  # built-in clients: aiohttp, openai (AsyncOpenAI with its default HTTP client),
  # openai-aiohttp (AsyncOpenAI with DefaultAioHttpClient), httpx (bare httpx.AsyncClient)

Pin the server and the client to different cores (taskset -c 0 / taskset -c 1) so they do
not compete. `report` prints the server's own timer lateness; if its p99 is above ~2 ms the
server, not the client, is the limit at that load, and the row should not be trusted.
"""
import argparse, asyncio, heapq, json, os, socket, statistics, sys, time

# ----------------------------------------------------------------------------- server

class Stats:
    def __init__(self):
        self.reset()

    def reset(self):
        self.t0 = None              # first arrival
        self.t_last = None          # last completion
        self.t_arr_last = None      # last arrival
        self.arrivals = 0
        self.done = 0
        self.inflight = 0
        self.max_inflight = 0
        self.area = 0.0             # integral of inflight over time
        self.t_prev = None
        self.ttft = []              # server-side: first token written - request parsed
        self.first_late = []        # first token written - first token due
        self.tok_late_hist = [0] * 12   # token lateness buckets: <0.25,0.5,1,2,4,8,16,32,64,128,256,inf ms
        self.tok_late_max = 0.0
        self.tokens = 0
        self.e2e = []

    def _tick(self, now):
        if self.t_prev is not None:
            self.area += self.inflight * (now - self.t_prev)
        self.t_prev = now

    def arrive(self, now):
        if self.t0 is None:
            self.t0 = now
        self._tick(now)
        self.arrivals += 1
        self.t_arr_last = now
        self.inflight += 1
        self.max_inflight = max(self.max_inflight, self.inflight)

    def finish(self, now, t_arr):
        self._tick(now)
        self.inflight -= 1
        self.done += 1
        self.t_last = now
        self.e2e.append(now - t_arr)

    def late(self, sec):
        ms = sec * 1000.0
        self.tokens += 1
        if ms > self.tok_late_max:
            self.tok_late_max = ms
        b, edge = 0, 0.25
        while b < 11 and ms >= edge:
            b += 1
            edge *= 2
        self.tok_late_hist[b] += 1


def pct(xs, p):
    if not xs:
        return None
    xs = sorted(xs)
    k = (len(xs) - 1) * p / 100.0
    lo = int(k)
    hi = min(lo + 1, len(xs) - 1)
    return xs[lo] + (xs[hi] - xs[lo]) * (k - lo)


def hist_pct(hist, p):
    edges = [0.25 * 2 ** i for i in range(11)] + [float("inf")]
    total = sum(hist)
    if not total:
        return 0.0
    need, acc = total * p / 100.0, 0
    for i, n in enumerate(hist):
        acc += n
        if acc >= need:
            return edges[i]
    return edges[-1]


class Server:
    def __init__(self, ttft, itl, tokens, honor_max_tokens, model):
        self.ttft, self.itl, self.tokens = ttft, itl, tokens
        self.honor = honor_max_tokens
        self.model = model
        self.stats = Stats()
        self.heap = []              # (due, seq, stream)
        self.seq = 0
        self.wake = None

    def schedule(self, due, stream):
        self.seq += 1
        heapq.heappush(self.heap, (due, self.seq, stream))
        if self.wake is not None and not self.wake.done():
            self.wake.set_result(None)

    async def pump(self):
        loop = asyncio.get_running_loop()
        clock = loop.time
        while True:
            if not self.heap:
                self.wake = loop.create_future()
                await self.wake
                self.wake = None
                continue
            now = clock()
            due = self.heap[0][0]
            if due > now:
                self.wake = loop.create_future()
                h = loop.call_at(due, lambda f=self.wake: f.done() or f.set_result(None))
                await self.wake
                h.cancel()
                self.wake = None
                continue
            # write every token that is due
            while self.heap and self.heap[0][0] <= now:
                due, _, st = heapq.heappop(self.heap)
                st.emit(now, due)
            await asyncio.sleep(0)


class Stream:
    __slots__ = ("srv", "tr", "t_arr", "n", "i", "chat", "usage", "rid", "created", "stream", "proto")

    def __init__(self, srv, proto, t_arr, n, chat, usage, stream):
        self.srv, self.proto, self.tr = srv, proto, proto.tr
        self.t_arr, self.n, self.i = t_arr, n, 0
        self.chat, self.usage, self.stream = chat, usage, stream
        self.rid = "cmpl-%d" % srv.seq
        self.created = int(time.time())

    def chunk(self, text, finish):
        if self.chat:
            d = {"id": self.rid, "object": "chat.completion.chunk", "created": self.created,
                 "model": self.srv.model,
                 "choices": [{"index": 0, "delta": ({"content": text} if text is not None else {}),
                              "finish_reason": finish}]}
            if self.i == 0 and text is not None:
                d["choices"][0]["delta"]["role"] = "assistant"
        else:
            d = {"id": self.rid, "object": "text_completion", "created": self.created,
                 "model": self.srv.model,
                 "choices": [{"index": 0, "text": text or "", "finish_reason": finish}]}
        return d

    def emit(self, now, due):
        srv, st = self.srv, self.srv.stats
        if self.tr.is_closing():
            st.finish(now, self.t_arr)
            return
        if self.i == 0:
            st.ttft.append(now - self.t_arr)
            st.first_late.append(now - due)
        st.late(now - due)
        if not self.stream:
            # non-streaming: emit nothing until the last token is due
            self.i += 1
            if self.i < self.n:
                srv.schedule(due + srv.itl, self)
                return
            body = {"id": self.rid, "object": "chat.completion" if self.chat else "text_completion",
                    "created": self.created, "model": srv.model,
                    "choices": [{"index": 0, "finish_reason": "length",
                                 **({"message": {"role": "assistant", "content": " tok" * self.n}}
                                    if self.chat else {"text": " tok" * self.n})}],
                    "usage": {"prompt_tokens": 1, "completion_tokens": self.n, "total_tokens": self.n + 1}}
            self.proto.send_json(body)
            st.finish(now, self.t_arr)
            return
        last = self.i + 1 >= self.n
        payload = "data: " + json.dumps(self.chunk(" tok", "length" if last else None),
                                        separators=(",", ":")) + "\n\n"
        self.i += 1
        if last:
            if self.usage:
                u = self.chunk(None, None)
                u["choices"] = []
                u["usage"] = {"prompt_tokens": 1, "completion_tokens": self.n, "total_tokens": self.n + 1}
                payload += "data: " + json.dumps(u, separators=(",", ":")) + "\n\n"
            payload += "data: [DONE]\n\n"
        b = payload.encode()
        self.tr.write(b"%x\r\n%s\r\n" % (len(b), b))
        if last:
            self.tr.write(b"0\r\n\r\n")
            st.finish(now, self.t_arr)
        else:
            srv.schedule(due + srv.itl, self)


class Proto(asyncio.Protocol):
    def __init__(self, srv):
        self.srv = srv
        self.buf = b""

    def connection_made(self, tr):
        self.tr = tr
        s = tr.get_extra_info("socket")
        if s is not None:
            s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

    def data_received(self, data):
        self.buf += data
        while True:
            h = self.buf.find(b"\r\n\r\n")
            if h < 0:
                return
            head = self.buf[:h].decode("latin-1").split("\r\n")
            clen = 0
            for line in head[1:]:
                k, _, v = line.partition(":")
                if k.strip().lower() == "content-length":
                    clen = int(v.strip())
            if len(self.buf) < h + 4 + clen:
                return
            body = self.buf[h + 4:h + 4 + clen]
            self.buf = self.buf[h + 4 + clen:]
            method, path = head[0].split(" ")[:2]
            self.handle(method, path.split("?")[0], body)

    def send_json(self, obj, status="200 OK"):
        b = json.dumps(obj).encode()
        self.tr.write(b"HTTP/1.1 %s\r\nContent-Type: application/json\r\nContent-Length: %d\r\n\r\n%s"
                      % (status.encode(), len(b), b))

    def handle(self, method, path, body):
        srv = self.srv
        loop = asyncio.get_running_loop()
        if path in ("/v1/completions", "/v1/chat/completions") and method == "POST":
            now = loop.time()
            try:
                req = json.loads(body or b"{}")
            except ValueError:
                req = {}
            n = srv.tokens
            if srv.honor:
                mt = req.get("max_completion_tokens") or req.get("max_tokens")
                if isinstance(mt, int) and mt > 0:
                    n = mt
            stream = bool(req.get("stream"))
            usage = bool((req.get("stream_options") or {}).get("include_usage"))
            srv.stats.arrive(now)
            st = Stream(srv, self, now, n, path.endswith("chat/completions"), usage, stream)
            if stream:
                self.tr.write(b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n"
                              b"Cache-Control: no-cache\r\nTransfer-Encoding: chunked\r\n\r\n")
            srv.schedule(now + srv.ttft, st)
        elif path == "/v1/models":
            self.send_json({"object": "list", "data": [{"id": srv.model, "object": "model",
                                                        "created": 0, "owned_by": "clientcheck",
                                                        "max_model_len": 1 << 20}]})
        elif path in ("/health", "/v1/health", "/ping"):
            self.send_json({"status": "ok"})
        elif path == "/stats":
            self.send_json(summary(srv))
            if method == "POST":
                srv.stats.reset()
        else:
            self.send_json({"error": {"message": "not found: " + path}}, "404 Not Found")


def summary(srv):
    s = srv.stats
    span = (s.t_last - s.t0) if (s.t0 is not None and s.t_last is not None) else 0.0
    ms = lambda x: None if x is None else round(x * 1000, 3)
    return {
        "configured": {"ttft_ms": srv.ttft * 1000, "itl_ms": srv.itl * 1000, "tokens": srv.tokens,
                       "honor_max_tokens": srv.honor},
        "requests_arrived": s.arrivals, "requests_finished": s.done,
        "span_s": round(span, 3),
        "arrival_spread_s": round(s.t_arr_last - s.t0, 3) if s.t0 is not None else None,
        "requests_per_s": round(s.done / span, 2) if span else None,
        "tokens_per_s": round(s.tokens / span, 1) if span else None,
        "mean_inflight": round(s.area / span, 1) if span else None,
        "max_inflight": s.max_inflight,
        "server_ttft_ms": {"p50": ms(pct(s.ttft, 50)), "p90": ms(pct(s.ttft, 90)), "p99": ms(pct(s.ttft, 99))},
        "server_e2e_ms": {"p50": ms(pct(s.e2e, 50)), "p99": ms(pct(s.e2e, 99))},
        "server_timer_lateness_ms": {"first_token_p99": ms(pct(s.first_late, 99)),
                                     "any_token_p50_le": min(hist_pct(s.tok_late_hist, 50), round(s.tok_late_max, 3)),
                                     "any_token_p99_le": min(hist_pct(s.tok_late_hist, 99), round(s.tok_late_max, 3)),
                                     "any_token_max": round(s.tok_late_max, 3)},
    }


async def serve(a):
    srv = Server(a.ttft_ms / 1000, a.itl_ms / 1000, a.tokens, not a.ignore_max_tokens, a.model)
    loop = asyncio.get_running_loop()
    server = await loop.create_server(lambda: Proto(srv), a.host, a.port, backlog=8192, reuse_address=True)
    print("mock OpenAI server on http://%s:%d/v1  model=%s ttft=%sms itl=%sms tokens=%d (max_tokens %s)"
          % (a.host, a.port, a.model, a.ttft_ms, a.itl_ms, a.tokens,
             "ignored" if a.ignore_max_tokens else "honored"), flush=True)
    pump = asyncio.ensure_future(srv.pump())
    async with server:
        await server.serve_forever()


# ----------------------------------------------------------------------------- report

def http_json(port, path, method="GET"):
    import urllib.request
    req = urllib.request.Request("http://127.0.0.1:%d%s" % (port, path), method=method,
                                 data=b"" if method == "POST" else None)
    with urllib.request.urlopen(req, timeout=30) as r:
        return json.loads(r.read())


def report(a):
    r = http_json(a.port, "/stats", "POST" if not a.keep else "GET")
    if a.json:
        print(json.dumps(r, indent=1))
        return
    c = r["configured"]
    print("server-side truth (what your tool should have measured):")
    print("  requests finished      %d of %d arrived" % (r["requests_finished"], r["requests_arrived"]))
    if not r["requests_finished"]:
        print("  (nothing finished yet)")
        return
    print("  TTFT  p50/p90/p99      %.1f / %.1f / %.1f ms   (configured %.0f ms)"
          % (r["server_ttft_ms"]["p50"], r["server_ttft_ms"]["p90"], r["server_ttft_ms"]["p99"], c["ttft_ms"]))
    print("  ITL                    %.0f ms configured; server timer lateness p99 <= %s ms, max %.1f ms"
          % (c["itl_ms"], r["server_timer_lateness_ms"]["any_token_p99_le"],
             r["server_timer_lateness_ms"]["any_token_max"]))
    print("  in flight              mean %s, max %d" % (r["mean_inflight"], r["max_inflight"]))
    print("  throughput             %s req/s, %s tok/s over %.2f s (arrivals spread over %.2f s)"
          % (r["requests_per_s"], r["tokens_per_s"], r["span_s"], r["arrival_spread_s"]))
    late = r["server_timer_lateness_ms"]["any_token_p99_le"]
    if late > 2:
        print("  WARNING: the mock server itself ran late (p99 > 2 ms). Give it its own core or lower the load.")
    print("If your tool reports a TTFT well above the server's, or a lower concurrency / request rate")
    print("than you asked for, the difference was added by the client.")


# ----------------------------------------------------------------------------- probe clients

async def run_aiohttp(url, body, n_req, conc, rec):
    import aiohttp
    conn = aiohttp.TCPConnector(limit=0, force_close=False)
    timeout = aiohttp.ClientTimeout(total=None, sock_read=None)
    async with aiohttp.ClientSession(connector=conn, timeout=timeout) as s:
        async def one():
            t0 = time.perf_counter()
            times = []
            async with s.post(url + "/completions", json=body) as r:
                async for line in r.content:
                    if line.startswith(b"data: ") and line[6:12] != b"[DONE]":
                        times.append(time.perf_counter())
            rec.append((t0, times))
        await drive(one, n_req, conc, rec)


async def run_httpx(url, body, n_req, conc, rec):
    import httpx
    limits = httpx.Limits(max_connections=None, max_keepalive_connections=None)
    async with httpx.AsyncClient(limits=limits, timeout=None) as c:
        async def one():
            t0 = time.perf_counter()
            times = []
            async with c.stream("POST", url + "/completions", json=body) as r:
                async for line in r.aiter_lines():
                    if line.startswith("data: ") and line[6:12] != "[DONE]":
                        times.append(time.perf_counter())
            rec.append((t0, times))
        await drive(one, n_req, conc, rec)


async def run_openai(url, body, n_req, conc, rec, aio=False):
    import openai
    kw = {}
    if aio:
        kw["http_client"] = openai.DefaultAioHttpClient()
    client = openai.AsyncOpenAI(base_url=url, api_key="x", max_retries=0, **kw)
    async with client:
        async def one():
            t0 = time.perf_counter()
            times = []
            st = await client.completions.create(model=body["model"], prompt=body["prompt"],
                                                 max_tokens=body["max_tokens"], stream=True)
            async for ev in st:
                times.append(time.perf_counter())
            rec.append((t0, times))
        await drive(one, n_req, conc, rec)


RESET = None    # set by probe(): clears the server counters after the warm-up
WARMUP = True
ERRORS = []     # errors of the counted (not warm-up) requests


async def drive(one, n_req, conc, rec):
    """closed loop: keep `conc` requests in flight until n_req are done (burst if conc >= n_req).
    First a warm-up of `conc` requests opens the connections; it is not counted (--no-warmup skips it)."""
    if WARMUP:
        await _loop(one, min(conc, n_req), conc)
        rec.clear()
        ERRORS.clear()
        if RESET:
            await asyncio.get_running_loop().run_in_executor(None, RESET)
    await _loop(one, n_req, conc)


async def _loop(one, n_req, conc):
    left = [n_req]
    errors = []

    async def worker():
        while left[0] > 0:
            left[0] -= 1
            try:
                await one()
            except Exception as e:      # count, do not hide
                errors.append(repr(e)[:200])
    await asyncio.gather(*[worker() for _ in range(min(conc, n_req))])
    ERRORS.extend(errors)
    if errors:
        print("  %d request errors, first: %s" % (len(errors), errors[0]), file=sys.stderr)


def summarize(rec, srv_ttft_p50, srv_ttft_p99):
    nan = float("nan")
    srv_ttft_p50 = nan if srv_ttft_p50 is None else srv_ttft_p50
    srv_ttft_p99 = nan if srv_ttft_p99 is None else srv_ttft_p99
    ttft = [(ts[0] - t0) * 1000 for t0, ts in rec if ts]
    tpot = [(ts[-1] - ts[0]) * 1000 / (len(ts) - 1) for t0, ts in rec if len(ts) > 1]
    itl = []
    for t0, ts in rec:
        itl += [(b - a) * 1000 for a, b in zip(ts, ts[1:])]
    return {"ok": len(ttft),
            "ttft_p50": pct(ttft, 50) or nan, "ttft_p99": pct(ttft, 99) or nan,
            "added_ttft_p50": (pct(ttft, 50) or nan) - srv_ttft_p50,
            "added_ttft_p99": (pct(ttft, 99) or nan) - srv_ttft_p99,
            "tpot_p50": pct(tpot, 50) or nan, "tpot_p99": pct(tpot, 99) or nan,
            "itl_p99": pct(itl, 99) or nan, "itl_max": max(itl) if itl else nan}


def probe(a):
    clients = {"aiohttp": run_aiohttp, "httpx": run_httpx,
               "openai": run_openai,
               "openai-aiohttp": lambda *x: run_openai(*x, aio=True)}
    fn = clients[a.client]
    global RESET, WARMUP
    WARMUP = not a.no_warmup
    RESET = lambda: http_json(a.port, "/stats", "POST")
    url = "http://127.0.0.1:%d/v1" % a.port
    cfg = http_json(a.port, "/stats", "GET" if a.keep_stats else "POST")["configured"]
    body = {"model": a.model, "prompt": "hello", "max_tokens": cfg["tokens"], "stream": True}
    rows = []
    for conc in [int(x) for x in a.concurrency.split(",")]:
        if a.requests_per_level.endswith("x"):
            n_req = max(int(a.requests_per_level[:-1]) * conc, a.min_requests)
        else:
            n_req = int(a.requests_per_level)
        rec = []
        ERRORS.clear()
        t = time.perf_counter()
        asyncio.run(fn(url, body, n_req, conc, rec))
        wall = time.perf_counter() - t
        srv = http_json(a.port, "/stats", "GET" if a.keep_stats else "POST")
        s = summarize(rec, srv["server_ttft_ms"]["p50"], srv["server_ttft_ms"]["p99"])
        s.update({"client": a.client, "concurrency": conc, "requests": n_req, "wall_s": wall,
                  "errors": len(ERRORS), "first_error": ERRORS[0] if ERRORS else None,
                  "server_mean_inflight": srv["mean_inflight"], "server_max_inflight": srv["max_inflight"],
                  "server_ttft_p50": srv["server_ttft_ms"]["p50"], "server_ttft_p99": srv["server_ttft_ms"]["p99"],
                  "server_arrival_spread_s": srv["arrival_spread_s"], "server_finished": srv["requests_finished"],
                  "server_late_p99_le": srv["server_timer_lateness_ms"]["any_token_p99_le"],
                  "server_tok_s": srv["tokens_per_s"]})
        rows.append(s)
        if a.jsonl:
            with open(a.jsonl, "a") as f:
                f.write(json.dumps(s) + "\n")
    hdr = ("conc", "reqs", "TTFT p50", "TTFT p99", "added p50", "added p99", "TPOT p50", "TPOT p99",
           "srv inflight", "srv late p99")
    print("client=%s  configured TTFT %.0f ms, ITL %.0f ms, %d tokens" % (a.client, cfg["ttft_ms"], cfg["itl_ms"], cfg["tokens"]))
    print("  ".join("%12s" % h for h in hdr))
    for s in rows:
        print("  ".join("%12s" % v for v in (
            s["concurrency"], s["ok"], "%.1f" % s["ttft_p50"], "%.1f" % s["ttft_p99"], "%+.1f" % s["added_ttft_p50"], "%+.1f" % s["added_ttft_p99"],
            "%.2f" % s["tpot_p50"], "%.2f" % s["tpot_p99"], s["server_mean_inflight"],
            "<=%s" % s["server_late_p99_le"])))


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = ap.add_subparsers(dest="cmd", required=True)
    s = sub.add_parser("serve", help="run the mock OpenAI-compatible server")
    s.add_argument("--host", default="127.0.0.1")
    s.add_argument("--port", type=int, default=8765)
    s.add_argument("--ttft-ms", type=float, default=50.0)
    s.add_argument("--itl-ms", type=float, default=20.0)
    s.add_argument("--tokens", type=int, default=64, help="tokens per response (default when max_tokens is absent)")
    s.add_argument("--ignore-max-tokens", action="store_true", help="always send --tokens tokens")
    s.add_argument("--model", default="mock")
    r = sub.add_parser("report", help="print what the server really delivered, then reset its counters")
    r.add_argument("--port", type=int, default=8765)
    r.add_argument("--keep", action="store_true", help="do not reset the counters")
    r.add_argument("--json", action="store_true")
    p = sub.add_parser("probe", help="measure a built-in client against the running mock")
    p.add_argument("--port", type=int, default=8765)
    p.add_argument("--client", default="aiohttp", choices=["aiohttp", "httpx", "openai", "openai-aiohttp"])
    p.add_argument("--concurrency", default="1,16,64,256")
    p.add_argument("--requests-per-level", default="4x", help="N, or Kx for K times the concurrency")
    p.add_argument("--min-requests", type=int, default=32)
    p.add_argument("--model", default="mock")
    p.add_argument("--jsonl", help="append one JSON row per level to this file")
    p.add_argument("--no-warmup", action="store_true", help="count the first requests too (cold start / burst test)")
    p.add_argument("--keep-stats", action="store_true", help="do not reset the server counters (one level only)")
    a = ap.parse_args()
    if a.cmd == "serve":
        try:
            asyncio.run(serve(a))
        except KeyboardInterrupt:
            pass
    elif a.cmd == "report":
        report(a)
    else:
        probe(a)


if __name__ == "__main__":
    main()
