"""Bounded final-target auxiliary comparisons, only this GPU1 service."""
import json, os, shlex, subprocess, time, urllib.request
from pathlib import Path
root=Path('/home/lab/bench/ornith/modular/sglang')
shared=Path('/home/lab/bench/ornith/modular/shared')
profiles=['baseline','kv4','mtp4','mtp4-int8','mtp4-int4','dflash16-bf16','dflash16-int8','dflash16-int4']
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_cmd():return subprocess.check_output(['tmux','display-message','-p','-t','%68','#{pane_current_command}'],text=True).strip()
for profile in profiles:
    print('\nAUXILIARY',profile,'CONTEXT8192 ONLY',flush=True)
    subprocess.run(['/bin/bash','/home/lab/bench/ornith/sglang/manage.sh','stop'],check=True)
    for _ in range(60):
        if pane_cmd()=='bash' and not healthy():break
        time.sleep(1)
    if pane_cmd()!='bash':raise RuntimeError('Codex pane busy: no keys sent')
    log=root/'logs'/f'aux-{profile}.log'
    if log.exists():raise RuntimeError(f'Refusing to overwrite {log}')
    cmd=f'bash {root}/frozen/auxiliary-8k-v2.sh {profile} 2>&1 | tee {log}'
    subprocess.run(['tmux','send-keys','-t','%68','-l',cmd],check=True)
    subprocess.run(['tmux','send-keys','-t','%68','Enter'],check=True)
    started=time.monotonic();ready=False
    while time.monotonic()-started<900:
        if healthy():ready=True;break
        if time.monotonic()-started>25 and pane_cmd()=='bash':break
        time.sleep(3)
    row={'profile':profile,'ready':ready,'startup_seconds':time.monotonic()-started,'context':8192}
    if ready:
        q=root/'results'/f'quality-aux-{profile}.json'
        common=['--base','http://127.0.0.1:8130/v1','--model','ornith-sglang']
        row['quality_exit']=subprocess.run(['python3',str(shared/'quality.py'),*common,'--out',str(q)]).returncode
        for task,length,reps,outputs in [('retrieval',8192,1,256),('throughput',4096,5,512)]:
            out=root/'results'/f'aux-{profile}-{task}'
            cmd=['/home/lab/venvs/vllm/bin/python',str(shared/'bench.py'),*common,'--out',str(out),
                 '--lengths',str(length),'--concurrency','1,3','--repeats',str(reps),'--task',task,
                 '--max-output',str(outputs),'--seed','4400','--timeout','300',
                 '--gpu','GPU-f4a988cb-c310-b618-5a9c-4462d4d33add']
            row[task+'_exit']=subprocess.run(cmd,env={**os.environ,'CUDA_VISIBLE_DEVICES':''}).returncode
    else:
        row['failure_tail']='\n'.join(log.read_text(errors='replace').splitlines()[-30:])
    records.append(row)
    (root/'auxiliary-matrix.json').write_text(json.dumps(records,indent=2))
    print(json.dumps(row),flush=True)
print('Auxiliary comparisons complete. Last short profile remains active pending final restoration.',flush=True)
