"""Launch one isolated candidate; writes readiness/error evidence, never touches baseline files."""
import argparse,csv,hashlib,io,json,os,pathlib,shutil,subprocess,time,urllib.request
p=argparse.ArgumentParser();p.add_argument('config');p.add_argument('--wait',type=int,default=600); a=p.parse_args()
root=pathlib.Path('/home/lab/bench/ornith/modular/vllm'); c=json.loads(pathlib.Path(a.config).read_text())
if (root/'thermal-stop.json').exists():raise SystemExit('Thermal safety latch present; manual review required. No service restart performed.')
name=c['id'];assert name.replace('-','').replace('_','').isalnum()
directory=root/'runs'/name; directory.mkdir(parents=True,exist_ok=True)
gpu_env={**os.environ,'CUDA_VISIBLE_DEVICES':'GPU-5f32faf3-97b9-895e-0a9e-ffa0f51bca3f'}
hardware=subprocess.run(['nvidia-smi','-i',gpu_env['CUDA_VISIBLE_DEVICES'],'--query-gpu=uuid,name,driver_version,power.limit,temperature.gpu,memory.total','--format=csv'],env=gpu_env,capture_output=True,text=True,timeout=10)
(directory/'hardware.csv').write_text(hardware.stdout if hardware.returncode==0 else hardware.stderr)
if name.endswith('-250w'):
    rows=list(csv.reader(io.StringIO(hardware.stdout)))
    if hardware.returncode or len(rows)!=2 or abs(float(rows[1][3].strip().split()[0])-250)>0.1:
        raise SystemExit('Expected externally verified250W GPU2 power cap is absent; no service mutation performed.')
launcher=directory/'launch.sh'
if not launcher.exists():shutil.copy2(root/'launch.sh',launcher)
(directory/'case.json').write_text(json.dumps(c,indent=2))
current=root/'current.log'
if current.is_symlink():current.unlink()
if not current.exists():current.symlink_to(directory/'server.log')
env=os.environ.copy();env['XDG_RUNTIME_DIR']='/run/user/1000'
unit='ornith-vllm-modular'
subprocess.run(['systemctl','--user','stop',unit],env=env,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
subprocess.run(['systemctl','--user','reset-failed',unit],env=env,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
cmd=['systemd-run','--user','--unit='+unit,'--collect','-p','TimeoutStopSec=30','-p','StandardOutput=append:'+str(directory/'server.log'),'-p','StandardError=append:'+str(directory/'server.log')]
for key,value in c['env'].items():
    assert key.startswith('ORNITH_') or key in ('VLLM_USE_V2_MODEL_RUNNER',)
    cmd+=['--setenv='+key+'='+str(value)]
cmd+=['/bin/bash',str(launcher)]
subprocess.run(cmd,env=env,check=True)
start=time.time();result={'config':c,'start_epoch':start,'ready':False,'launcher':str(launcher),'launcher_sha256':hashlib.sha256(launcher.read_bytes()).hexdigest()}
url='http://127.0.0.1:'+str(c['env'].get('ORNITH_PORT',8140))
while time.time()-start<a.wait:
    status=subprocess.run(['systemctl','--user','is-active',unit],env=env,capture_output=True,text=True).stdout.strip()
    if status!='active':result['error']='service '+status;break
    try:
        with urllib.request.urlopen(url+'/health',timeout=2) as r:
            if r.status==200:
                result['ready']=True;break
    except Exception:pass
    time.sleep(5)
result['startup_seconds']=round(time.time()-start,2)
if not result['ready']:
    result['error']=result.get('error','readiness timeout')
    result['log_tail']=(directory/'server.log').read_text(errors='replace')[-18000:]
(directory/'readiness.json').write_text(json.dumps(result,indent=2))
print(json.dumps({k:v for k,v in result.items() if k!='log_tail'},indent=2),flush=True)
raise SystemExit(0 if result['ready'] else 1)
