"""Bounded auxiliary compatibility and greedy-preservation screening."""
import argparse,json,pathlib,subprocess,urllib.request,os,signal
p=argparse.ArgumentParser();p.add_argument('cases',nargs='+');p.add_argument('--baseline',default='full-int8-bf16');a=p.parse_args()
r=pathlib.Path('/home/lab/bench/ornith/modular/vllm')
def bounded(cmd,seconds=600):
 process=subprocess.Popen(cmd,start_new_session=True)
 try:return process.wait(timeout=seconds)
 except subprocess.TimeoutExpired:
  os.killpg(process.pid,signal.SIGINT)
  try:process.wait(timeout=15)
  except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGTERM);process.wait(timeout=15)
  raise
for name in a.cases:
 if (r/'thermal-stop.json').exists():print('THERMAL SAFETY LATCH; stopping auxiliary matrix.',flush=True);break
 print('AUXILIARY',name,flush=True);out=r/'runs'/name
 launch=subprocess.run(['python3',str(r/'candidate.py'),str(r/'cases'/f'{name}.json')])
 if launch.returncode:continue
 try:
  bounded(['python3',str(r/'greedy_compare.py'),'--out',str(out/'greedy.json'),'--baseline',str(r/'runs'/a.baseline/'greedy.json')])
  bounded(['python3',str(r/'quality_gate.py'),'--out',str(out/'quality.json')])
  bounded(['python3',str(r/'final_suite.py'),'--id',name,'--out','short-throughput','--lengths','4096','--concurrency','1,3','--repeats','1','--task','throughput','--max-output','512','--seed','85009'])
  with urllib.request.urlopen('http://127.0.0.1:8140/metrics',timeout=5) as response:(out/'metrics.txt').write_bytes(response.read())
 except Exception as exc:
  (out/'screening-error.json').write_text(json.dumps({'error':str(exc)}));print(type(exc).__name__,str(exc),flush=True)
print('AUXILIARY SCREEN COMPLETE',flush=True)
