"""Final cold-start grid and stability using the same CPU tokenizer runtime as llama."""
import json, os, subprocess
from pathlib import Path

root=Path('/home/lab/bench/ornith/modular/sglang')
shared=Path('/home/lab/bench/ornith/modular/shared')
env={**os.environ,'CUDA_VISIBLE_DEVICES':''}
python='/home/lab/venvs/vllm/bin/python'
base=['--base','http://127.0.0.1:8130/v1','--model','ornith-sglang']
def bench(name,args):
    out=root/'results'/name
    if out.exists():raise RuntimeError(f'Refusing to overwrite {out}')
    rc=subprocess.run([python,str(shared/'bench.py'),*base,'--out',str(out),
         '--gpu','GPU-f4a988cb-c310-b618-5a9c-4462d4d33add',*args],env=env).returncode
    data=json.loads((out/'summary.json').read_text()) if (out/'summary.json').exists() else {}
    return {'exit':rc,**data}
records={}
subprocess.run(['python3',str(shared/'quality.py'),*base,'--out',str(root/'results'/'quality-final-int8-e5m2.json')],env=env)
records['grid']=bench('final-int8-e5m2-grid',[
    '--lengths','4096,32768,131072,262144','--concurrency','1,3','--repeats','5','--seed','4400'])
(root/'results'/'final-acceptance.json').write_text(json.dumps(records,indent=2))
if not (records['grid'].get('completed') and records['grid'].get('all_pass') and records['grid'].get('batches')==40):
    raise SystemExit('Full grid did not pass: not promoting or starting long stability.')
records['stability']=bench('final-int8-e5m2-stability',[
    '--lengths','262144','--concurrency','3','--repeats','1','--duration','1800','--seed','72901'])
(root/'results'/'final-acceptance.json').write_text(json.dumps(records,indent=2))
records['throughput']=bench('final-int8-e5m2-throughput',[
    '--lengths','4096','--concurrency','1,3','--repeats','5','--task','throughput','--max-output','512','--seed','85009'])
(root/'results'/'final-acceptance.json').write_text(json.dumps(records,indent=2))
print('FINAL ACCEPTANCE FINISHED; review all individual records before promoting.',flush=True)
