"""Durable allocated-node supervisor with native-stall recovery and streaming plans.""" from __future__ import annotations import argparse from concurrent.futures import ThreadPoolExecutor import os from pathlib import Path import shutil import subprocess import tempfile import time from .common import read, write def supervise(root,mode,group,gpu,timeout=300.): marker=root/mode/'reports/groups'/(group['group_id']+'.json') if marker.exists(): return read(marker) cache=Path(tempfile.mkdtemp(prefix='dish-exh-'+mode+'-'+str(group['index'])+'-')) log=root/mode/'reports/logs'/f'{group["index"]:04d}.log' log.parent.mkdir(parents=True,exist_ok=True) script=Path(__file__).parent/'runtime.sh' command=['bash',str(script),'-m','exhibition_dataset.render','--root',str(root),'--mode',mode, '--index',str(group['index']),'--gpu',str(gpu),'--cache-dir',str(cache)] restarts=[] success=False try: for attempt in range(1,4): started=time.time() with log.open('a') as output: process=subprocess.Popen(command,stdout=output,stderr=subprocess.STDOUT) while process.poll() is None: progress=cache/'progress.json' last=max(started,progress.stat().st_mtime if progress.exists() else started) if time.time()-last>timeout: process.kill() process.wait() restarts.append(dict(attempt=attempt,reason='native_kernel_stall', progress=read(progress) if progress.exists() else None)) break time.sleep(1) if marker.exists(): success=True result=read(marker) write(root/mode/'reports/recovery'/(group['group_id']+'.json'), dict(passed=True,attempts=attempt,restarts=restarts,reused_same_recipe=True)) return result restarts.append(dict(attempt=attempt,exit_code=process.returncode,reason='worker_exit')) raise RuntimeError('Group '+str(group['index'])+' failed three native attempts; see '+str(log)) finally: if success: shutil.rmtree(cache) else: write(root/mode/'reports/recovery'/(group['group_id']+'.json'), dict(passed=False,restarts=restarts,recovery_cache=str(cache))) def worker(root,mode,processes,prepare_exit_file=None): from dynamic_dataset.runtime import ensure_compute ensure_compute() root=Path(root).resolve() queued=set() failures=[] active={} report=root/mode/'reports/worker.status.json' started=time.time() with ThreadPoolExecutor(max_workers=processes) as executor: while True: plans=[read(p) for p in sorted((root/'private/plans').glob('*.json'))] pending=[g for g in plans if g['index'] not in queued] pending.sort(key=lambda g:(['noise','count','controls'].index(g['family_type']),g['index'])) for group in pending[:max(0,processes-len(active))]: future=executor.submit(supervise,root,mode,group,group['index']%8) active[future]=group queued.add(group['index']) for future in list(active): if not future.done(): continue group=active.pop(future) try: result=future.result() if not result['passed']: raise RuntimeError('Render report did not pass') print('COMPLETE',mode,group['index'],round(result['wall_seconds'],1),'s',flush=True) except Exception as error: failures.append(dict(index=group['index'],group_id=group['group_id'],error=str(error))) print('FAILED',mode,group['index'],str(error),flush=True) done=len(list((root/mode/'reports/groups').glob('*.json'))) write(report,dict(mode=mode,phase='rendering',pid=os.getpid(),concurrency=processes, plans_available=len(plans),groups_completed=done,active_indices=[g['index'] for g in active.values()], failed=failures,wall_seconds=time.time()-started)) prepared=(root/'reports/prepare.complete.json').exists() if prepared and len(queued)==300 and not active: break if prepare_exit_file and Path(prepare_exit_file).exists() and Path(prepare_exit_file).read_text().strip()!='0': raise RuntimeError('Planning failed; do not declare a partial benchmark complete') if failures and not active and prepared and not pending: break time.sleep(5) result=dict(passed=not failures and done==300,mode=mode,groups=done,failures=failures, wall_seconds=time.time()-started) write(root/mode/'reports/render.complete.json',result) if not result['passed']: raise RuntimeError('Incomplete rendering; resume after correcting the logged failed groups') print('FULL RENDER COMPLETE',mode,done,'families',flush=True) if __name__=='__main__': parser=argparse.ArgumentParser() parser.add_argument('--root',type=Path,required=True) parser.add_argument('--mode',choices=['static','dynamic'],required=True) parser.add_argument('--processes',type=int,default=32) parser.add_argument('--prepare-exit-file',type=Path) a=parser.parse_args() worker(a.root,a.mode,a.processes,a.prepare_exit_file)