"""Read-only experiment summarization. No inference or service mutation."""
import json,pathlib,re,statistics
r=pathlib.Path('/home/lab/bench/ornith/modular/vllm');rows=[]
for d in sorted((r/'runs').iterdir()):
 if not d.is_dir():continue
 row={'id':d.name,'evidence':str(d)}
 if (d/'hardware.csv').exists():row['hardware_csv']=(d/'hardware.csv').read_text()
 for name in ('readiness','capacity-gate','greedy','quality','quality-shared'):
  f=d/(name+'.json')
  if not f.exists():continue
  data=json.loads(f.read_text())
  if name=='readiness':row.update(ready=data.get('ready'),env=data.get('config',{}).get('env',{}),startup_seconds=data.get('startup_seconds'),launcher=data.get('launcher'),launcher_sha256=data.get('launcher_sha256'))
  elif name=='greedy':row['greedy_all_exact']=data.get('all_exact')
  elif name.startswith('quality'):
   results=data.get('results',[]) if isinstance(data,dict) else data
   row['quality']={x.get('case',x.get('name','unknown')):x.get('pass') for x in results}
  else:row[name]=data
 log=d/'server.log'
 if log.exists():
  text=log.read_text(errors='replace');row['runtime_memory_lines']=[s for s in text.splitlines() if any(x in s for x in ('GPU KV cache size:','Actual usage is','Graph capturing finished'))][-3:]
  row['last_errors']=[s for s in text.splitlines() if re.search(r'(ValueError:|RuntimeError:|NotImplementedError:|AssertionError:|CUDA out of memory)',s)][-3:]
 row['benchmarks']=[]
 for f in sorted(d.glob('*/summary.json')):
  summary=json.loads(f.read_text());rowsfile=f.parent/'results.jsonl'
  batches=[json.loads(s) for s in rowsfile.read_text().splitlines() if s] if rowsfile.exists() else []
  results=[x for b in batches for x in b.get('results',[])]
  item={'path':str(f.parent),'summary':summary,'requests':len(results),'http_stream_ok':sum(bool(x.get('ok')) for x in results),'retrieval_pass':sum(x.get('retrieval_pass') is True for x in results),'retrieval_fail':sum(x.get('retrieval_pass') is False for x in results)}
  item['groups']=[]
  for length,concurrency in sorted({(x['length_budget'],x['concurrency']) for x in batches}):
   selected=[b for b in batches if b['length_budget']==length and b['concurrency']==concurrency];entries=[x for b in selected for x in b['results']]
   group={'length':length,'concurrency':concurrency,'batches':len(selected),'requests':len(entries)}
   for key in ('ttft_seconds','decode_tok_s_estimate','seconds'):
    values=[x[key] for x in entries if x.get(key) is not None]
    if values:group[key+'_median']=statistics.median(values)
   group['aggregate_e2e_tok_s_median']=statistics.median(b['aggregate_tok_s'] for b in selected)
   item['groups'].append(group)
  gpu=f.parent/'gpu.json'
  if gpu.exists():
   samples=[x['values'].split(',') for x in json.loads(gpu.read_text()) if x.get('values') and len(x['values'].split(','))==4]
   if samples:item.update(max_device_mib=max(float(x[0]) for x in samples),max_temperature_c=max(float(x[2]) for x in samples))
  row['benchmarks'].append(item)
 rows.append(row)
output={'gpu_uuid':'GPU-5f32faf3-97b9-895e-0a9e-ffa0f51bca3f','thermal_latch':json.loads((r/'thermal-stop.json').read_text()) if (r/'thermal-stop.json').exists() else None,'thermal_events':[{'path':str(f),'record':json.loads(f.read_text())} for f in sorted((r/'thermal-events').glob('*.json'))],'runs':rows,'caveat':'Readiness, small quality screen, full-grid validation, and sustained residency are distinct. No implicit promotion from ready=true.'}
(r/'experiment-report.json').write_text(json.dumps(output,indent=2));print('Saved',r/'experiment-report.json')
