"""lp_drive.py OUT -- logprobs evidence load: prod sampler, thinking on, no max_tokens, streaming; every request asks for
logprobs (top 5); phases c1 (4 serial), c4 (two waves of 4), c8 (one wave of 8), prompt (prompt_logprobs on a long prompt)."""
import json, os, sys, threading, time, urllib.request
BASE = "http://127.0.0.1:19741"; out = sys.argv[1]; os.makedirs(out, exist_ok=True)
S3C = os.environ.get("HR_CACHE", os.path.expanduser("~/headroute/cache")) + "/s3c"; rows = []; lock = threading.Lock()
def phase(p):
    try:
        open(S3C + "/phase.tmp", "w").write(p); os.replace(S3C + "/phase.tmp", S3C + "/phase")
    except OSError: pass
    time.sleep(1.5); print(time.strftime("%T"), "phase", p, flush=True)
def chat(content, tag, ph, seed, extra):
    body = {"model": "Qwen3.8-27B", "messages": [{"role": "user", "content": content}], "stream": True, "seed": seed,
            "stream_options": {"include_usage": True}, **extra}
    req = urllib.request.Request(BASE + "/v1/chat/completions", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
    t0 = time.time(); n_lp = 0; n_plp = 0; usage = None; err = None
    try:
        for line in urllib.request.urlopen(req, timeout=10800):
            if not line.startswith(b"data: ") or line.startswith(b"data: [DONE]"): continue
            d = json.loads(line[6:])
            if d.get("usage"): usage = d["usage"]
            if d.get("prompt_logprobs"): n_plp += len(d["prompt_logprobs"])
            for ch in d.get("choices") or []:
                n_lp += len(((ch.get("logprobs") or {}).get("content")) or [])
                if ch.get("prompt_logprobs"): n_plp += len(ch["prompt_logprobs"])
    except Exception as e:
        err = repr(e)[:300]
        try: err += " " + e.read().decode()[:300]
        except Exception: pass
    u = usage or {}
    r = {"phase": ph, "tag": tag, "total_s": round(time.time() - t0, 3), "prompt_tokens": u.get("prompt_tokens"),
         "completion_tokens": u.get("completion_tokens"), "logprob_entries": n_lp, "prompt_logprob_entries": n_plp, "err": err}
    with lock: rows.append(r)
    print(" ", json.dumps(r), flush=True)
def conc(items, ph, extra):
    ts = [threading.Thread(target=chat, args=(c, t, ph, 1000 + i, extra)) for i, (c, t) in enumerate(items)]
    for t in ts: t.start()
    for t in ts: t.join()
QS = ["Explain why the sky is blue, briefly.", "Write a short Python function that checks whether a number is prime, and explain it.",
      "What are three differences between TCP and UDP?", "Give me a two-sentence summary of the causes of the French Revolution.",
      "How many prime numbers are there between 1 and 50? List them.", "Describe how a hash map handles collisions."]
LP = {"logprobs": True, "top_logprobs": 5}
phase("c1")
for i in range(4): chat(QS[i], f"c1.{i}", "c1", 2000 + i, LP)
phase("c4")
for w in range(2): conc([(QS[(w + k) % 6], f"c4.{w}.{k}") for k in range(4)], "c4", LP)
phase("c8"); conc([(QS[k % 6], f"c8.{k}") for k in range(8)], "c8", LP)
phase("prompt")
doc = " ".join(f"Paragraph {i}: the committee reviewed item {i * 7 % 999} and recorded outcome {i * 13 % 99}." for i in range(60))
def completion(prompt, tag, extra):
    # prompt_logprobs is a /v1/completions field (teacher-forced walk over the prompt, tile by tile)
    body = {"model": "Qwen3.8-27B", "prompt": prompt, "max_tokens": 1, "seed": 7, **extra}
    req = urllib.request.Request(BASE + "/v1/completions", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
    t0 = time.time(); n = 0; err = None; u = {}
    try:
        d = json.loads(urllib.request.urlopen(req, timeout=10800).read()); u = d.get("usage") or {}
        n = sum(len(c.get("prompt_logprobs") or []) for c in d.get("choices") or [])
    except Exception as e:
        err = repr(e)[:200]
        try: err += " " + e.read().decode()[:300]
        except Exception: pass
    r = {"phase": "prompt", "tag": tag, "total_s": round(time.time() - t0, 3), "prompt_tokens": u.get("prompt_tokens"),
         "completion_tokens": u.get("completion_tokens"), "logprob_entries": 0, "prompt_logprob_entries": n, "err": err}
    rows.append(r); print(" ", json.dumps(r), flush=True)
completion(doc, "prompt.0", {"prompt_logprobs": 5})
completion(" ".join(QS), "prompt.1", {"prompt_logprobs": 2})
json.dump(rows, open(f"{out}/requests.json", "w"), indent=0); print("DRIVE DONE", flush=True)
