#!/usr/bin/env python3 """New finite public-API run + read-only GPU/X11 observer. No device tuning.""" import argparse,hashlib,importlib.util,json,os,pathlib,signal,subprocess,sys,time,traceback A=pathlib.Path(__file__).resolve().parent;ROOT=A.parent;P=pathlib.Path(json.loads((A/'staging.json').read_text())['root']) def read(p): try:return json.loads(p.read_text()) except FileNotFoundError:return {} def main(): ap=argparse.ArgumentParser();ap.add_argument('--name',required=True);ap.add_argument('--sequence');ap.add_argument('--cycles',type=int,default=1);ap.add_argument('--headless',action='store_true');ap.add_argument('--video-seconds',type=int,default=0);args=ap.parse_args();assert 0<=args.video_seconds<=240 scope=read(A/'scope.json');cases=list((A/'runs').glob('*/campaign/campaign-result.json'));used=sum(len(read(p)['rows']) for p in cases);reserved=sum(read(p)['reserved_physics_calls'] for p in cases);assert used+2<=scope['limits']['kit_launches'];assert reserved+(27250 if args.sequence else args.cycles*4500+250)<=scope['limits']['physics_calls'] O=A/'runs'/args.name;O.mkdir(parents=True);E=O/'observer';E.mkdir();cli=P/'scripts/go2_fl_skill.py';reg=O/'session/registration.json';out=O/'campaign' env=os.environ.copy();env.update(PYTHONPATH='',PYTHONDONTWRITEBYTECODE='1',DISPLAY=':1',XAUTHORITY='/run/user/1000/gdm/Xauthority',XDG_RUNTIME_DIR='/run/user/1000') commands=[['/usr/bin/python3.12',str(cli),'authorize','--registration',str(reg)],['/usr/bin/python3.12',str(cli),'run','--registration',str(reg),'--output',str(out),'--controller','analytic']] commands[1]+=(['--sequence',args.sequence] if args.sequence else ['--command','x_bias-16mm','--cycles',str(args.cycles)]) if not args.headless:commands[1].append('--gui') helper=pathlib.Path('/home/cen/sf-runs/simskill-gui-v041-authority-01/desktop_trial.py');spec=importlib.util.spec_from_file_location('external_x11',helper);x=importlib.util.module_from_spec(spec);spec.loader.exec_module(x);x.P=P r={'commands':commands,'began_wall':time.time(),'prior_kit_launches':used,'scope_limit':scope['limits'],'source_observer_sha256':hashlib.sha256(pathlib.Path(__file__).read_bytes()).hexdigest()};closed=False;child=None;gpu=None;video=None;w=None;view=None;probed=False;shot=False try: with (E/'authorize.log').open('w') as f:subprocess.run(commands[0],cwd=P,env=env,stdout=f,stderr=subprocess.STDOUT,check=True) gpu=subprocess.Popen(['nvidia-smi','--id=0','--query-gpu=timestamp,utilization.gpu,utilization.memory,memory.used,power.draw,power.limit,clocks.current.sm,clocks.current.memory,pstate,temperature.gpu','--format=csv','-lms','500'],stdout=(E/'gpu.csv').open('w'),stderr=(E/'gpu.stderr.log').open('w')) child=subprocess.Popen(commands[1],cwd=P,env=env,stdout=(E/'public-run.log').open('w'),stderr=subprocess.STDOUT) deadline=time.monotonic()+1400 while child.poll() is None and time.monotonic()=500 and args.video_seconds and video is None: vcmd=[str(x.FF),'-hide_banner','-y','-f','x11grab','-framerate','30','-video_size',f"{w['width']//2*2}x{w['height']//2*2}",'-i',f"{env['DISPLAY']}+{w['x']},{w['y']}",'-an','-c:v','libx264','-preset','ultrafast','-crf','24','-pix_fmt','yuv420p','-t',str(args.video_seconds),str(E/'live-kit-window.mp4')] video=subprocess.Popen(vcmd,stdout=(E/'screen-video.log').open('w'),stderr=subprocess.STDOUT);r['video_command']=vcmd;r['video_started_wall']=time.time();r['video_start_gui']=g;r['video_scope']='Owned live X11 window;30Hz capture sampling NOT a claim of render or display FPS; observer overhead included in active loop measurement' if w is not None and g.get('last_tick',0)>2500 and not shot: x.screenshot(w,E/'actual-moving-window.png');r['moving_capture']={'window':w,'gui':g,'wall':time.time()};shot=True if w is not None and status.get('state')=='viewing_final' and not closed: if view is None:view=time.monotonic();r['final_counts_before']=read(out/'run/physics-counts.json') elif time.monotonic()-view>=2: x.screenshot(w,E/'actual-final-window.png');r['final_counts_after']=read(out/'run/physics-counts.json');x.wm_close(w);closed=True;r['wm_delete_wall']=time.time() time.sleep(.2) if child.poll() is None: if w is not None and not closed:x.wm_close(w);closed=True raise TimeoutError('Observer wall deadline; no physical retry') r['waited_exit']=child.wait();r['window_absent_after_wait']=True if args.headless else x.window() is None;r['campaign_success']=read(out/'campaign-result.json').get('success');r['worker_success']=read(out/'run/worker-result.json').get('success') except BaseException: r['observer_error']=traceback.format_exc() if child is not None and child.poll() is None: if w is not None and not closed:x.wm_close(w) try:r['waited_exit']=child.wait(timeout=150) except subprocess.TimeoutExpired:r['cleanup_wait_timeout']=True finally: if video is not None: if video.poll() is None:video.send_signal(signal.SIGINT) try:r['video_waited_exit']=video.wait(timeout=30) except subprocess.TimeoutExpired:video.terminate();r['video_waited_exit']=video.wait(timeout=10) if gpu is not None: gpu.terminate();r['gpu_observer_exit']=gpu.wait(timeout=10) r['ended_wall']=time.time();(E/'result.json').write_text(json.dumps(r,indent=2)+'\n') print(json.dumps(r,indent=2)) if __name__=='__main__':main()