"""hr_drive.py OUT [attr|c8] (c8: three waves of 8 concurrent only) -- served load for the head call-site evidence: prod sampler, thinking on, no max_tokens, streaming.
Phases: c1 (sequential), c4, short prefill x2 concurrent, long prefill (7k + 25k concurrent; then a decoder with a 25k prefill
arriving 4 s later). Per request: TTFT (first streamed delta), total, usage. flag_truth dumped after every phase."""
import json, os, random, subprocess, sys, threading, time, urllib.request

BASE = "http://127.0.0.1:19741"; out = sys.argv[1]; attr = len(sys.argv) > 2
os.makedirs(out, exist_ok=True); S3C = 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 flag_truth(tag):
    # admin endpoints answer loopback only: ask from inside the container (out/<tag>/drive -> container hr-<tag>)
    name = "hr-" + os.path.basename(os.path.dirname(os.path.abspath(out)))
    code = "import urllib.request,sys; sys.stdout.write(urllib.request.urlopen('http://127.0.0.1:8000/v1/admin/flag_truth', timeout=120).read().decode())"
    r = subprocess.run(["docker", "exec", name, "python3", "-c", code], capture_output=True)
    open(f"{out}/flag_truth.{tag}.json", "wb").write(r.stdout)
    if r.returncode: print("flag_truth failed", tag, r.stderr[-200:], flush=True)
def chat(content, tag, ph, seed):
    body = {"model": "Qwen3.8-27B", "messages": [{"role": "user", "content": content}], "stream": True, "seed": seed,
            "stream_options": {"include_usage": True}}
    req = urllib.request.Request(BASE + "/v1/chat/completions", data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
    t0 = time.time(); t1 = None; 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"]
            ch = d.get("choices") or []
            if t1 is None and ch and any(ch[0].get("delta", {}).get(k) for k in ("content", "reasoning_content", "reasoning")): t1 = time.time()
    except Exception as e: err = repr(e)[:300]
    t2 = time.time(); u = usage or {}
    r = {"phase": ph, "tag": tag, "ttft_s": None if t1 is None else round(t1 - t0, 4), "total_s": round(t2 - t0, 3),
         "prompt_tokens": u.get("prompt_tokens"), "completion_tokens": u.get("completion_tokens"), "err": err,
         "prefill_steps": (u.get("prompt_tokens_details") or {}).get("prefill_steps")}
    with lock: rows.append(r)
    print(" ", json.dumps(r), flush=True)
def conc(items, ph, stagger=0.0):
    ts = [threading.Thread(target=chat, args=(c, t, ph, 1000 + i)) for i, (c, t) in enumerate(items)]
    for t in ts: t.start(); time.sleep(stagger)
    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."]
def long_doc(n_par, seed):
    rng = random.Random(seed)
    return " ".join(f"Paragraph {i}: the committee reviewed item {rng.randint(1, 999)} for project {rng.choice('ABCDEFGH')} "
        f"and recorded outcome {rng.randint(1, 99)} with note '{rng.choice(['approved', 'deferred', 'rejected', 'escalated'])}'." for i in range(n_par))
if attr and sys.argv[2] == "c8":
    phase("c8")
    for w in range(3): conc([(QS[(w + k) % 6], f"c8.{w}.{k}") for k in range(8)], "c8")
    flag_truth("c8"); json.dump(rows, open(f"{out}/requests.json", "w"), indent=0); print("DRIVE DONE", flush=True); sys.exit(0)
if not attr:
    phase("c1")
    for i in range(10): chat(QS[i % 6], f"c1.{i}", "c1", 2000 + i)
    flag_truth("c1"); phase("c4")
    for w in range(3): conc([(QS[(w + k) % 6], f"c4.{w}.{k}") for k in range(4)], "c4")
    flag_truth("c4")
phase("prefill_short")
for w in range(2): conc([("Reply with one word: what colour is grass?", f"ps.{w}.0"), ("Name one planet.", f"ps.{w}.1")], "prefill_short")
flag_truth("prefill_short"); phase("prefill_long")
conc([(long_doc(260, 11) + "\nWhich items were escalated? Answer briefly.", "pl.7k"),
      (long_doc(900, 12) + "\nSummarise the outcomes for project C in three bullets.", "pl.25k")], "prefill_long")
flag_truth("prefill_long"); phase("prefill_long_decoder")
conc([("Explain step by step how the Fast Fourier Transform reduces complexity, and derive the radix-2 recurrence.", "pd.dec"),
      (long_doc(900, 13) + "\nSummarise the outcomes for project D in three bullets.", "pd.25k")], "prefill_long_decoder", stagger=4.0)
flag_truth("prefill_long_decoder"); phase("done"); time.sleep(3)
json.dump(rows, open(f"{out}/requests.json", "w"), indent=0)
try: open(f"{out}/metrics.txt", "wb").write(urllib.request.urlopen(BASE + "/metrics", timeout=60).read())
except Exception as e: print("metrics failed", repr(e)[:200])
print("DRIVE DONE", flush=True)
