"""One-variable decode-graph comparison on identical INT8/E5M2/FI-prefill target."""
import json, os, subprocess, time, urllib.request
from pathlib import Path
root=Path('/home/lab/bench/ornith/modular/sglang');shared=Path('/home/lab/bench/ornith/modular/shared')
records=[]
def healthy():
    try:
        with urllib.request.urlopen('http://127.0.0.1:8130/health',timeout=2) as r:return r.status==200
    except Exception:return False
def pane():return subprocess.check_output(['tmux','display-message','-p','-t','%68','#{pane_current_command}'],text=True).strip()
for label,launcher in [('graphs-on','int8-e5m2-flashinfer-256k.sh'),('graphs-off','int8-e5m2-flashinfer-eager-256k.sh')]:
    subprocess.run(['/bin/bash','/home/lab/bench/ornith/sglang/manage.sh','stop'],check=True)
    for _ in range(60):
        if pane()=='bash' and not healthy():break
        time.sleep(1)
    if pane()!='bash':raise RuntimeError('Owned Codex pane not idle')
    log=root/'logs'/f'control-{label}.log'
    if log.exists():raise RuntimeError('Do not overwrite graph control evidence')
    command=f'bash {root}/frozen/{launcher} 2>&1 | tee {log}'
    subprocess.run(['tmux','send-keys','-t','%68','-l',command],check=True)
    subprocess.run(['tmux','send-keys','-t','%68','Enter'],check=True)
    start=time.monotonic();ready=False
    while time.monotonic()-start<900:
        if healthy():ready=True;break
        if time.monotonic()-start>25 and pane()=='bash':break
        time.sleep(3)
    row={'profile':label,'ready':ready,'startup_seconds':time.monotonic()-start}
    if ready:
        base=['--base','http://127.0.0.1:8130/v1','--model','ornith-sglang']
        row['quality_exit']=subprocess.run(['python3',str(shared/'quality.py'),*base,'--out',str(root/'results'/f'quality-control-{label}.json')]).returncode
        cmd=['/home/lab/venvs/vllm/bin/python',str(shared/'bench.py'),*base,
             '--out',str(root/'results'/f'control-{label}-throughput'),'--lengths','4096',
             '--concurrency','1,3','--repeats','5','--task','throughput','--max-output','512','--seed','85009',
             '--gpu','GPU-f4a988cb-c310-b618-5a9c-4462d4d33add']
        row['bench_exit']=subprocess.run(cmd,env={**os.environ,'CUDA_VISIBLE_DEVICES':''}).returncode
    records.append(row);(root/'graph-control.json').write_text(json.dumps(records,indent=2));print(json.dumps(row),flush=True)
print('Graph control complete; restore final frozen profile before cold acceptance grid.',flush=True)
