"""Six disjoint style shards; resumable indexes, verified uploads, bounded scratch.""" import collections, fcntl, json, os, shutil, sqlite3, subprocess, sys, time from pathlib import Path APP = Path(__file__).resolve().parent PERSIST = Path('/workspace/styleedit-streaming-20261024') from recovery_state import LOCAL_ROOT, DURABLE_ROOT, copy_atomic ROOT = LOCAL_ROOT PY = '/opt/da3-depth-env/bin/python' def save(path, value): path = Path(path); path.parent.mkdir(parents=True, exist_ok=True) temp = path.with_suffix('.tmp'); temp.write_text(json.dumps(value, indent=2)); os.replace(temp, path) def spawn(args, log, gpu=None): env = dict(os.environ, HF_TOKEN_PATH='/root/.styleedit-hf-token', OMP_NUM_THREADS='4', OPENBLAS_NUM_THREADS='2', HF_HUB_DISABLE_PROGRESS_BARS='1') if gpu is not None: env.update(CUDA_VISIBLE_DEVICES=str(gpu), STYLEEDIT_GPU_LOCK=f'/opt/styleedit-gpu-{gpu}.lock') stream = open(log, 'a') p = subprocess.Popen([PY, '-u', *map(str, args)], env=env, stdout=stream, stderr=subprocess.STDOUT, start_new_session=True) stream.close(); return p def prepare(): ROOT.mkdir(parents=True, exist_ok=True) rows = json.loads((APP/'candidates.json').read_text()) styles = sorted({r['style_id'] for r in rows}) # Entire styles belong to one GPU, so the 100-source quota needs no cross-process race. assignment = {s:i%6 for i,s in enumerate(styles)} # Recovery copied all six existing shards, including their WAL, to local disk. old = [] pilot = json.loads((APP/'pilot-plan.json').read_text()) for gpu in range(6): state = ROOT/f'gpu{gpu}'; state.mkdir(exist_ok=True) db = sqlite3.connect(state/'jobs.sqlite') db.execute('CREATE TABLE IF NOT EXISTS jobs(id TEXT PRIMARY KEY,style_id TEXT,source TEXT,status TEXT,record TEXT,verified_at REAL,cleaned INTEGER DEFAULT 0)') for row in old: if assignment.get(row[1]) == gpu and row[3] in ('verified','reject'): db.execute('INSERT OR IGNORE INTO jobs VALUES(?,?,?,?,?,?,?)', row) db.commit(); db.close() save(APP/f'plan-gpu{gpu}.json', [r for r in rows if assignment[r['style_id']]==gpu]) save(APP/f'pilot-gpu{gpu}.json', [r for r in pilot if assignment[r['style_id']]==gpu]) save(ROOT/'assignment.json', assignment) def processing(gpu, pilot=False): return spawn([APP/'pipeline.py', '--plan', APP/f'{"pilot" if pilot else "plan"}-gpu{gpu}.json', '--state', ROOT/f'gpu{gpu}', '--scratch', f'/opt/styleedit-sixgpu-scratch/gpu{gpu}', '--index-state', '/opt/styleedit-exact-index', '--limit','0','--per-style','100', '--window','6','--download-workers','4','--upload-workers','1', '--scratch-gib','60','--reserve-gib','40','--cleanup-seconds','60', *(['--seed-ranges'] if pilot else [])], ROOT/f'gpu{gpu}-{ "pilot" if pilot else "production"}.log', gpu) def aggregate(stage, children): counts = collections.Counter(); statuses = collections.Counter(); dirty = 0 for gpu in range(6): db = sqlite3.connect(ROOT/f'gpu{gpu}'/'jobs.sqlite', timeout=30) counts.update(dict(db.execute("SELECT style_id,count(*) FROM jobs WHERE status='verified' GROUP BY style_id"))) statuses.update(dict(db.execute('SELECT status,count(*) FROM jobs GROUP BY status'))) dirty += db.execute("SELECT count(*) FROM jobs WHERE status='verified' AND cleaned=0").fetchone()[0] db.close() save(ROOT/'status.json', {'utc':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),'stage':stage, 'verified':sum(counts.values()),'counts':dict(counts),'statuses':dict(statuses), 'verified_pending_cleanup':dirty,'processes':{k:{'pid':v.pid,'returncode':v.poll()} for k,v in children.items()}}) try: copy_atomic(ROOT/'status.json', DURABLE_ROOT/'status.json') except OSError as exc: print('STATUS_SNAPSHOT_RETRY',type(exc).__name__,str(exc),flush=True) def index_merge(): target = Path('/opt/styleedit-exact-index'); target.mkdir(exist_ok=True) tmp = target/'catalog.sqlite.tmp' if tmp.exists(): tmp.unlink() db = sqlite3.connect(tmp) db.execute('CREATE TABLE members(category TEXT,name TEXT,offset INTEGER,size INTEGER,PRIMARY KEY(category,name))') db.execute('CREATE TABLE checkpoints(category TEXT PRIMARY KEY,offset INTEGER,complete INTEGER)') for category in ['source','global_style1','global_style2']: origin = ROOT/'indexes'/category src = sqlite3.connect(origin/'catalog.sqlite') if src.execute('SELECT complete FROM checkpoints WHERE category=?',(category,)).fetchone() != (1,): raise RuntimeError('Incomplete index '+category) db.executemany('INSERT INTO members VALUES(?,?,?,?)',src.execute('SELECT * FROM members')) db.executemany('INSERT INTO checkpoints VALUES(?,?,?)',src.execute('SELECT * FROM checkpoints')) src.close(); shutil.copyfile(origin/(category+'.gzidx'), target/(category+'.gzidx')) db.commit(); db.close(); os.replace(tmp,target/'catalog.sqlite') def main(): ROOT.mkdir(parents=True,exist_ok=True) lock=open(ROOT/'supervisor.lock','a'); fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) prepare() from huggingface_hub import HfApi children={} for category in ['source','global_style1','global_style2']: path=ROOT/'indexes'/category children['index-'+category]=spawn([APP/'pipeline.py','--index',category,'--index-state',path], ROOT/f'index-{category}.log') # All six pilot workers already completed; resume exact indexing directly. while any(p.poll() is None for p in children.values()): aggregate('indexing',children) # Failed index is fatal; preserve all checkpoints and media. failed=[k for k,p in children.items() if k.startswith('index-') and p.poll() not in (None,0)] if failed: raise RuntimeError('Index failed; inspect logs: '+str(failed)) time.sleep(30) aggregate('pilot_complete',children) # Pilot's quota deficit gives exit 2 by design. Upload/model errors are not safe to ignore. for gpu in range(6): summary=json.loads((ROOT/f'gpu{gpu}'/'summary.json').read_text()) if summary['errors']:raise RuntimeError(f'Pilot GPU {gpu} errors: inspect summary before production') index_merge() # Public archive indexing can progress while the original login is restored. while True: try: api=HfApi(); api.whoami(); api.auth_check('faraway00/StyleEdit', repo_type='dataset') break except Exception as exc: aggregate('awaiting_hf_auth',{}) print('WAITING_FOR_HF_AUTH',type(exc).__name__,flush=True) time.sleep(60) children={f'gpu-{g}':processing(g) for g in range(6)} while any(p.poll() is None for p in children.values()): aggregate('production',children); time.sleep(30) aggregate('complete' if all(p.returncode==0 for p in children.values()) else 'needs_attention',children) print('SIX_GPU_FINISHED',flush=True) if __name__=='__main__': main()