import json,os,pathlib,subprocess,time,shutil
os.umask(0o077);R=pathlib.Path(__file__).parent
def shell(cmd):return subprocess.check_output(cmd,text=True,timeout=10)
def gpu():return int(shell(['nvidia-smi','--id=0','--query-gpu=memory.used','--format=csv,noheader,nounits']).strip())
data=json.loads(shell(['docker','inspect','contextra-analytics-1']))[0]
assert data['State']['Status']=='exited'
assert data['Image']=='sha256:228fc2493dcb81454453d05a66528dd5927d74a40fb85f76d6950afbf0b56d1a'
baseline=gpu();assert baseline<16384
mem=dict((l.split(':')[0],int(l.split()[1])) for l in pathlib.Path('/proc/meminfo').read_text().splitlines())
assert mem['MemAvailable']>4*1024**2 and shutil.disk_usage('/').free>2*1024**3
name='codex-frame-isolation-synthetic-r01'
cmd=['docker','run','--rm','--pull','never','--name',name,'--network','none','--gpus','device=0',
 '--cpus','2','--memory','2g','--ulimit','core=0','-e','NVIDIA_VISIBLE_DEVICES=0',
 '-e','NVIDIA_DRIVER_CAPABILITIES=compute,video,utility','-e','PYTHONDONTWRITEBYTECODE=1',
 '--mount',f'type=bind,src={R},dst=/evidence','--entrypoint','timeout',data['Image'],'40s','python3','/evidence/synthetic.py']
start=time.monotonic();peak=baseline;reason=None
with (R/'synthetic.log').open('w') as log:
 p=subprocess.Popen(cmd,stdout=log,stderr=subprocess.STDOUT)
 try:
  while p.poll() is None:
   peak=max(peak,gpu())
   if peak-baseline>2048 or time.monotonic()-start>45:reason='TIME_OR_GPU_CAP';break
   time.sleep(1)
 finally:
  if p.poll() is None:subprocess.run(['docker','kill',name],capture_output=True,timeout=10)
  p.wait(timeout=15)
summary=dict(returncode=p.returncode,reason=reason,gpu_before=baseline,gpu_peak=peak,gpu_after=gpu(),elapsed_s=round(time.monotonic()-start,2))
(R/'synthetic-resources.json').write_text(json.dumps(summary,indent=2));print(json.dumps(summary))
if (R/'synthetic.json').exists():print((R/'synthetic.json').read_text())
