"""Needle-in-a-haystack check used in the Octave KV post.

The haystack is vLLM's own Python source with 16 look-alike keys
(`# PROJECT KEY Aldebaran: WK3DEGZD`) spread over the first ~120k tokens.
Prefixes of 32k, 64k and 126k tokens are sent to a running vLLM server and the
model is asked for each key present (thinking off). Finally it reports decode
tok/s at the longest length.

Usage:
    vllm serve cyankiwi/Qwen3.8-27B-AWQ-INT4 --kv-cache-dtype octave_k3v3 ...
    python niah_octave.py --vllm-src /path/to/vllm --out niah_octave_k3v3.jsonl

The model name is read from /v1/models unless --model is given. The haystack
depends on the vLLM source tree, so use the same checkout for every row.
"""
import argparse
import glob
import json
import os
import random
import time
import urllib.request as u

ap = argparse.ArgumentParser()
ap.add_argument("--url", default="http://127.0.0.1:8000")
ap.add_argument("--model", default=None)
ap.add_argument("--vllm-src", default=".")
ap.add_argument("--lens", default="32000,64000,126000")
ap.add_argument("--out", default="niah.jsonl")
args = ap.parse_args()

URL = args.url
LENS = [int(x) for x in args.lens.split(",")]
OUT = open(args.out, "w")


def log(d):
    print(json.dumps(d, ensure_ascii=False), flush=True)
    OUT.write(json.dumps(d, ensure_ascii=False) + "\n")
    OUT.flush()


def post(path, body):
    req = u.Request(URL + path, json.dumps(body).encode(),
                    {"Content-Type": "application/json"})
    return json.load(u.urlopen(req, timeout=3600))


M = args.model or json.load(u.urlopen(URL + "/v1/models"))["data"][0]["id"]


def tok(s):
    return post("/tokenize", {"model": M, "prompt": s,
                              "add_special_tokens": False})["tokens"]


src = os.path.abspath(args.vllm_src)
files = sorted(glob.glob(os.path.join(src, "vllm", "**", "*.py"), recursive=True))
assert files, f"no vllm/**/*.py under {src}"
txt, n = [], 0
for f in files:
    s = open(f, errors="ignore").read()
    txt.append(f"\n# ==== file: {os.path.relpath(f, src)} ====\n{s}")
    n += len(s)
    if n > 700_000:
        break
body = tok("".join(txt))
NEED = max(LENS)
assert len(body) >= NEED, len(body)

NAMES = ["Aldebaran", "Betelgeuse", "Canopus", "Deneb", "Electra", "Fomalhaut",
         "Gacrux", "Hadar", "Izar", "Jabbah", "Kochab", "Lesath", "Mirach",
         "Naos", "Okab", "Pollux"]
r = random.Random(7)
KEYS = {nm: "".join(r.choice("ABCDEFGHJKLMNPQRSTUVWXYZ23456789") for _ in range(8))
        for nm in NAMES}
master, pos, prev = [], {}, 0
for i, nm in enumerate(NAMES):
    at = 4_000 + 7_700 * i
    master += body[prev:at]
    pos[nm] = len(master)
    master += tok(f"\n# PROJECT KEY {nm}: {KEYS[nm]}\n")
    prev = at
master = (master + body[prev:NEED + 2000])[:NEED]

# Qwen3 chat format with thinking off, built by hand so the prefix is exact.
HEAD = tok("<|im_start|>user\n")


def tail(q):
    return tok(f"\n\n{q}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n")


def stream(prompt, max_tokens, ignore_eos=False):
    b = {"model": M, "prompt": prompt, "max_tokens": max_tokens,
         "temperature": 0.6, "top_p": 0.95, "top_k": 20, "stream": True,
         "stream_options": {"include_usage": True}, "ignore_eos": ignore_eos}
    t0 = time.time()
    tf = tl = None
    out, usage = [], None
    req = u.Request(URL + "/v1/completions", json.dumps(b).encode(),
                    {"Content-Type": "application/json"})
    for line in u.urlopen(req, timeout=3600):
        line = line.decode().strip()
        if not line.startswith("data:") or line == "data: [DONE]":
            continue
        ev = json.loads(line[5:])
        if ev.get("usage"):
            usage = ev["usage"]
        if ev.get("choices") and ev["choices"][0].get("text"):
            now = time.time()
            tf = tf or now
            tl = now
            out.append(ev["choices"][0]["text"])
    return "".join(out), (tf or time.time()) - t0, tf, tl, usage


log({"event": "setup", "model": M, "master_tokens": len(master), "key_pos": pos})
tot = ok = 0
for L in LENS:
    pre = HEAD + master[:L]
    good = 0
    present = [nm for nm in NAMES if pos[nm] < L]
    for nm in present:
        q = (f"What is the PROJECT KEY {nm} that appears in the text above? "
             "Answer only the 8-character key.")
        ans, ttft, *_ = stream(pre + tail(q), 24)
        hit = KEYS[nm] in ans
        good += hit
        log({"event": "key", "L": L, "name": nm, "depth": round(pos[nm] / L, 3),
             "ok": hit,
             "confused_with": [o for o in NAMES if o != nm and KEYS[o] in ans],
             "ans": ans.strip()[:40], "ttft_s": round(ttft, 2)})
    tot += len(present)
    ok += good
    log({"event": "length", "L": L, "ok": good, "n": len(present)})

L = LENS[-1]
q = "Explain in detail what the last code file in the text above does."
_, ttft, tf, tl, us = stream(HEAD + master[:L] + tail(q), 400, True)
nn = us["completion_tokens"] if us else 400
log({"event": "decode", "L": L, "tok_s": round((nn - 1) / (tl - tf), 1), "gen": nn})
log({"event": "done", "ok": ok, "n": tot})
