"""Resume six GPU shards from durable receipts after root-disk extraction.""" import collections import fcntl import json import os from pathlib import Path import sqlite3 import subprocess import sys import time ROOT=Path('/opt/styleedit-root-20261025') APP=Path('/opt/styleedit-streaming-20261024') STATE=Path('/opt/styleedit-sixgpu-recovered') PERSIST=Path('/workspace/styleedit-streaming-20261024/root-disk-20261025') DOWNLOADER=None DOWNLOAD_RETRIES=0 UPLOADER=None UPLOAD_RETRIES=0 RESUME=None BACKUP=None os.environ.update(HF_TOKEN_PATH='/root/.styleedit-hf-token',PYTHONPATH='/opt/depth-anything-3-code/src',HF_HUB_DISABLE_PROGRESS_BARS='1',OMP_NUM_THREADS='4',OPENBLAS_NUM_THREADS='2') sys.path.insert(0,str(APP)) def atomic(path,value): path=Path(path);path.parent.mkdir(parents=True,exist_ok=True) temp=path.with_name(path.name+'.tmp');temp.write_text(json.dumps(value,indent=2));os.replace(temp,path) def status(stage,children): global DOWNLOADER,DOWNLOAD_RETRIES,UPLOADER,UPLOAD_RETRIES,BACKUP if BACKUP is not None and BACKUP.poll() is not None:BACKUP=start_backup() if UPLOADER is not None and UPLOADER.poll() is not None: if UPLOAD_RETRIES>=3:raise RuntimeError('Batch uploader repeatedly exited; queue and media preserved') UPLOAD_RETRIES+=1;UPLOADER=start_uploader() if DOWNLOADER is not None and DOWNLOADER.poll() not in (None,0): if DOWNLOAD_RETRIES>=3: raise RuntimeError('Archive download/extraction failed repeatedly; see download.log') DOWNLOAD_RETRIES+=1;DOWNLOADER=start_download() counts=collections.Counter();states=collections.Counter() for gpu in range(6): path=STATE/f'gpu{gpu}'/'jobs.sqlite' if path.exists(): with sqlite3.connect(path,timeout=30) as db: counts.update(dict(db.execute("SELECT style_id,count(*) FROM jobs WHERE status='verified' GROUP BY style_id"))) states.update(dict(db.execute('SELECT status,count(*) FROM jobs GROUP BY status'))) result={'utc':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),'stage':stage,'verified':sum(counts.values()),'counts':dict(counts),'statuses':dict(states),'root_free_bytes':__import__('shutil').disk_usage(ROOT).free,'archives_extracted':[c for c in ['source','global_style1','global_style2'] if (ROOT/(c+'.extracted.json')).exists()],'processes':{str(k):{'pid':v.pid,'returncode':v.poll()} for k,v in children.items()}} upload_status=ROOT/'batch-upload/status.json' if upload_status.exists():result['batch_upload']=json.loads(upload_status.read_text()) with sqlite3.connect(ROOT/'downloads.sqlite',timeout=30) as db: result['archive_download_bytes']=db.execute('SELECT coalesce(sum(size),0) FROM chunks').fetchone()[0] result['state_backup']={p.stem:json.loads(p.read_text()) for p in (ROOT/'state-backup').glob('*.json') if p.name!='process.json'} atomic(ROOT/'status.json',result);atomic(STATE/'status.json',result) return result class ExistingDownloader: def __init__(self,pid):self.pid=pid def poll(self): try:return None if b'local_media.py' in Path(f'/proc/{self.pid}/cmdline').read_bytes() else 1 except OSError:return 1 def process_alive(pid,expected): try: proc=Path(f'/proc/{pid}') if proc.joinpath('stat').read_text().rsplit(')',1)[1].split()[0]=='Z':return False args=proc.joinpath('cmdline').read_bytes().split(b'\0') return all(str(value).encode() in args for value in expected) except (OSError,IndexError):return False class ExistingProcess: """Attach without starting a second writer; require fresh completion evidence.""" def __init__(self,pid,expected,state=None,returncode=None): self.pid=pid;self.expected=expected;self.state=state;self.returncode=returncode;self.since=time.time() def poll(self): if self.returncode is not None:return self.returncode if process_alive(self.pid,self.expected):return None self.returncode=1 if self.state is not None: summary=self.state/'summary.json';quota=self.state/'quota-report.json' if all(p.exists() and p.stat().st_mtime>=self.since for p in [summary,quota]): if not json.loads(summary.read_text())['errors']: self.returncode=0 if json.loads(quota.read_text())['complete'] else 2 return self.returncode def start_download(): marker=ROOT/'download-process.json' if marker.exists(): existing=ExistingDownloader(json.loads(marker.read_text())['pid']) if existing.poll() is None: print('DOWNLOAD_ADOPTED',existing.pid,flush=True);return existing with (ROOT/'download.log').open('a') as log: child=subprocess.Popen([sys.executable,'-u',str(APP/'local_media.py')],stdout=log,stderr=subprocess.STDOUT,start_new_session=True) atomic(ROOT/'download-process.json',{'pid':child.pid}) return child def start_uploader(): marker=ROOT/'batch-upload/process.json' if marker.exists(): existing=ExistingProcess(json.loads(marker.read_text())['pid'],[APP/'batch_upload.py']) if existing.poll() is None: print('UPLOADER_ADOPTED',existing.pid,flush=True);return existing with (ROOT/'batch-upload.log').open('a') as log: return subprocess.Popen([sys.executable,'-u',str(APP/'batch_upload.py')],stdout=log,stderr=subprocess.STDOUT,start_new_session=True) def start_backup(): marker=ROOT/'state-backup/process.json' if marker.exists(): existing=ExistingProcess(json.loads(marker.read_text())['pid'],[APP/'state_backup.py']) if existing.poll() is None:return existing with (ROOT/'state-backup.log').open('a') as log: return subprocess.Popen([sys.executable,'-u',str(APP/'state_backup.py')],stdout=log,stderr=subprocess.STDOUT,start_new_session=True) def start(gpu,stage): if RESUME and RESUME['stage']=='processing_'+stage: old=RESUME['processes'].get(str(gpu)) if old: expected=[APP/'pipeline.py',ROOT/f'{stage}-gpu{gpu}.json',STATE/f'gpu{gpu}'] if old['returncode']==0 or (old['returncode'] is None and process_alive(old['pid'],expected)): print('SHARD_ADOPTED',gpu,old['pid'],'completed' if old['returncode']==0 else 'running',flush=True) return ExistingProcess(old['pid'],expected,STATE/f'gpu{gpu}',old['returncode']) env=dict(os.environ,CUDA_VISIBLE_DEVICES=str(gpu),STYLEEDIT_GPU_LOCK=f'/opt/styleedit-gpu-{gpu}.lock') args=[sys.executable,'-u',str(APP/'pipeline.py'),'--local-media-root',str(ROOT/'media'),'--plan',str(ROOT/f'{stage}-gpu{gpu}.json'),'--state',str(STATE/f'gpu{gpu}'),'--scratch',f'/opt/styleedit-sixgpu-scratch/gpu{gpu}','--limit','0','--per-style','100','--window','6','--download-workers','4','--upload-workers','8','--scratch-gib','60','--reserve-gib','50'] with (ROOT/f'{stage}-gpu{gpu}.log').open('a') as log: return subprocess.Popen(args,env=env,stdout=log,stderr=subprocess.STDOUT,start_new_session=True) def processing_stages(resume): stages=[('global_style1',['source','global_style1']),('all',['source','global_style1','global_style2'])] if resume: index=[name for name,_ in stages].index(resume['stage'].removeprefix('processing_')) stages=stages[index:] return stages def main(): global DOWNLOADER,UPLOADER,RESUME,BACKUP ROOT.mkdir(exist_ok=True) lock=(ROOT/'supervisor.lock').open('a');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) if '--resume' in sys.argv: RESUME=json.loads((ROOT/'status.json').read_text()) if not RESUME['stage'].startswith('processing_'):raise RuntimeError('Resume requires an existing processing stage') if not all((ROOT/(c+'.extracted.json')).exists() for c in ['source','global_style1','global_style2']):raise RuntimeError('Resume requires extracted inputs') failure=ROOT/'failure.json' if failure.exists():os.replace(failure,ROOT/f'failure-before-{int(time.time())}.json') if RESUME is None:DOWNLOADER=start_download() while not (ROOT/'RESTORED').exists(): status('restoring_runtime',{});time.sleep(20) from huggingface_hub import HfApi api=HfApi();print('AUTH_OK',api.whoami()['name'],flush=True);api.auth_check('faraway00/StyleEdit',repo_type='dataset') from reconcile_remote import reconcile if RESUME is None:reconcile() UPLOADER=start_uploader() BACKUP=start_backup() rows=json.loads((APP/'candidates.json').read_text());assignment={s:i%6 for i,s in enumerate(sorted({r['style_id'] for r in rows}))} for gpu in range(6): with sqlite3.connect(STATE/f'gpu{gpu}'/'jobs.sqlite') as db: if db.execute('PRAGMA quick_check').fetchone()!=('ok',):raise RuntimeError('Damaged recovered database') for (sid,) in db.execute("SELECT style_id FROM jobs WHERE status='verified'"): if assignment[sid]!=gpu:raise RuntimeError('Recovered style assignment changed') shard=[r for r in rows if assignment[r['style_id']]==gpu] atomic(ROOT/f'all-gpu{gpu}.json',shard) atomic(ROOT/f'global_style1-gpu{gpu}.json',[r for r in shard if r['edited_path'].startswith('global_style1/')]) import sixgpu_publish last_publish=time.monotonic() for stage,required in processing_stages(RESUME): while not all((ROOT/(c+'.extracted.json')).exists() for c in required): status('downloading_extracting_'+stage,{}) if time.monotonic()-last_publish>600: try: sixgpu_publish.publish();last_publish=time.monotonic() except Exception as error:print('MANIFEST_RETRY',type(error).__name__,str(error)[:200],flush=True) time.sleep(30) children={g:start(g,stage) for g in range(6)} scratch_retries=collections.Counter() while True: for gpu,child in list(children.items()): if child.poll()!=1 or scratch_retries[gpu]:continue with (ROOT/f'{stage}-gpu{gpu}.log').open('rb') as log: log.seek(0,2);log.seek(max(0,log.tell()-4096));tail=log.read().decode(errors='replace') if 'FileNotFoundError' in tail and 'in space' in tail: scratch_retries[gpu]+=1;children[gpu]=start(gpu,stage) print('SCRATCH_RACE_SHARD_RESUMED',gpu,children[gpu].pid,flush=True) if not any(p.poll() is None for p in children.values()):break status('processing_'+stage,children) if time.monotonic()-last_publish>600: try: sixgpu_publish.publish();last_publish=time.monotonic() except Exception as error:print('MANIFEST_RETRY',type(error).__name__,str(error)[:200],flush=True) time.sleep(30) for gpu,child in children.items(): summary=json.loads((STATE/f'gpu{gpu}'/'summary.json').read_text()) if summary['errors'] or child.returncode not in (0,2):raise RuntimeError(f'GPU {gpu} failed; outputs preserved, inspect {stage}-gpu{gpu}.log') try:sixgpu_publish.publish() except Exception as error:print('MANIFEST_RETRY',type(error).__name__,str(error)[:200],flush=True) complete=all(json.loads((STATE/f'gpu{g}'/'quota-report.json').read_text())['complete'] for g in range(6)) from batch_upload import CommitDeferred while True: try:sixgpu_publish.publish();break except CommitDeferred as deferred: status('awaiting_final_manifest',{});time.sleep(min(30,max(1,deferred.until-time.time()))) status('complete' if complete else 'candidate_pool_exhausted',{}) print('ROOT_PIPELINE_FINISHED',complete,flush=True) if __name__=='__main__': try:main() except Exception as error: atomic(ROOT/'failure.json',{'utc':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),'error':str(error)}) raise