#!/usr/bin/env python3 """Read-only Hub recovery for a new machine, before further collection. Recover from committed batch manifests, including uploads whose public index was never published. Only text/metadata are stored locally; video/audio are verified by LFS SHA-256 (or streamed and discarded when unavailable). """ from __future__ import annotations import argparse import contextlib import fcntl import hashlib import importlib.util import json import os from pathlib import Path import re import sqlite3 import sys import urllib.request KINDS={'text','video','audio','metadata'} def load_module(name,path): spec=importlib.util.spec_from_file_location(name,path) module=importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def atomic_bytes(path,body,immutable=False): path=Path(path) if path.is_symlink(): raise ValueError('Refusing a symlink in recovered state') if path.exists(): if path.read_bytes()==body: return False if immutable: raise ValueError('Existing retained file conflicts with fixed remote bytes') path.parent.mkdir(parents=True,exist_ok=True) temporary=path.with_name(path.name+'.restore.tmp') if temporary.is_symlink(): raise ValueError('Refusing symlink temporary file') temporary.write_bytes(body) temporary.replace(path) return True def read_small_remote(api,repo,path,head,up,maximum=64*1024*1024): from huggingface_hub import hf_hub_url url=hf_hub_url(repo,path,repo_type='dataset',revision=head,endpoint='https://huggingface.co') headers={'Accept-Encoding':'identity','User-Agent':'PAR-state-restore/1'} if api.token: headers['Authorization']='Bearer '+api.token opener=urllib.request.build_opener(up.StripCrossHostAuth()) with opener.open(urllib.request.Request(url,headers=headers),timeout=45) as response: if response.status!=200: raise ValueError('Recovery requires a complete small-file response') declared=response.headers.get('Content-Length') if declared and int(declared)>maximum: raise ValueError('Small-file recovery response exceeds bound') body=response.read(maximum+1) if len(body)>maximum: raise ValueError('Small-file recovery response exceeds bound') return body def validate_batch(value,path,repo,db,up): if str(value.get('schema_version'))!='1' or value.get('repo_id')!=repo: raise ValueError('Unexpected committed batch manifest schema/repository') batch_id=value.get('batch_id','') if not re.fullmatch('[0-9a-f]{24}',batch_id) or path!=f'manifests/batches/{batch_id}.json': raise ValueError('Batch manifest identity/path mismatch') assets=value.get('assets',[]) if not assets: raise ValueError('Committed batch has no assets') seen=set(); groups={} for a in assets: eid=a.get('event_id','') if not re.fullmatch('[A-Za-z0-9_-]{8,100}',eid) or a.get('kind') not in KINDS: raise ValueError('Unexpected recovered event/asset identity') remote=db.safe_remote_path(a['remote_path']) if not remote.startswith(f'data/events/{eid}/') or remote in seen: raise ValueError('Recovered path is duplicated or outside its event namespace') if not re.fullmatch('[0-9a-f]{64}',a.get('sha256','')) or not isinstance(a.get('size_bytes'),int) or a['size_bytes']<=0: raise ValueError('Recovery asset lacks a full SHA-256 and byte size') seen.add(remote);groups.setdefault(eid,[]).append(a) for group in groups.values(): if {a['kind'] for a in group}!=KINDS or len(group)!=4: raise ValueError('Recovery only accepts complete four-asset events') if len({Path(a['remote_path']).name for a in group})!=4: raise ValueError('Recovered local asset basenames collide') if value.get('event_count')!=len(groups) or value.get('total_bytes')!=sum(a['size_bytes'] for a in assets): raise ValueError('Committed batch count/size differs from its asset list') public=sorted([{k:a[k] for k in ('event_id','kind','remote_path','size_bytes','sha256')} for a in assets],key=lambda a:a['remote_path']) if hashlib.sha256(up.json_bytes(public)).hexdigest()[:24]!=batch_id: raise ValueError('Committed batch content hash does not match batch identifier') return groups def validate_existing_event(path,event_id,assets): if not path.is_file(): return old=json.loads(path.read_text(encoding='utf-8')) expected={(a['kind'],a['remote_path'],a['size_bytes'],a['sha256']) for a in assets} actual={(a['kind'],a['remote_path'],a['size_bytes'],a['sha256']) for a in old.get('assets',[])} if old.get('event_id')!=event_id or actual!=expected: raise ValueError('Existing local event manifest conflicts with committed immutable assets') def local_batch_is_verified(ledger,repo,head,groups,incoming,db): for eid,assets in groups.items(): event=incoming/eid marker=event/'remote_verified.json' manifest=event/'event.manifest.json' if not marker.is_file() or not manifest.is_file(): return False validate_existing_event(manifest,eid,assets) r=json.loads(marker.read_text(encoding='utf-8')) if r.get('repo_id')!=repo or r.get('event_id')!=eid or r.get('verified') is not True: return False proofs={(a.get('remote_path'),a.get('sha256'),a.get('size_bytes'),a.get('verified_commit')) for a in r.get('assets',[])} for a in assets: old=ledger.execute('SELECT * FROM transfer_assets WHERE repo_id=? AND remote_path=?',(repo,a['remote_path'])).fetchone() if not old or old['state'] not in ('verified','local_removed') or old['verified_commit']!=head: return False if any(old[k]!=a[k] for k in ('event_id','kind','size_bytes','sha256')): raise ValueError('Existing transfer ledger conflicts with remote manifest') if old['verification_method'] not in ('hub_lfs_sha256_and_size','remote_full_stream_sha256_and_size') or not old['verified_at']: return False if (a['remote_path'],a['sha256'],a['size_bytes'],head) not in proofs: return False if a['kind'] in ('text','metadata'): local=event/Path(a['remote_path']).name if not local.is_file(): return False if local.is_symlink() or local.stat().st_size!=a['size_bytes'] or db.digest(local)!=a['sha256']: raise ValueError('Retained local text/metadata conflicts with remote manifest') return True def restore(args): from huggingface_hub import HfApi,get_token root=args.root.resolve();work=args.work.resolve() db=load_module('par_restore_database',root/'scripts/database.py') up=load_module('par_restore_uploader',root/'scripts/batch_upload.py') if args.repo_id!=db.REPO: raise ValueError('Database protocol is configured for Jiaxuannn/PAR; migrate its repo contract before another destination') incoming=work/'incoming';state=work/'state';receipts=state/'upload_receipts' for p in (incoming,state,receipts):p.mkdir(parents=True,exist_ok=True) ledger_path=state/'transfer_ledger.sqlite' api=HfApi(endpoint='https://huggingface.co',token=get_token()) head=api.repo_info(args.repo_id,repo_type='dataset').sha files=api.list_repo_files(args.repo_id,repo_type='dataset',revision=head) paths=sorted(p for p in files if re.fullmatch(r'manifests/batches/[0-9a-f]{24}\.json',p)) summary={'repo_id':args.repo_id,'verified_revision':head,'remote_batch_manifests':len(paths), 'restored_events':0,'reused_verified_batches':0,'remote_asset_checks':0,'retained_files_downloaded':0, 'retained_bytes_downloaded':0,'media_files_written':0,'media_bytes_written':0, 'media_bytes_streamed_for_verification':0,'remote_mutations':0} all_event_ids=set();all_manifests=[] with (state/'transfer_ledger.sqlite.lock').open('a') as lock: try:fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) except BlockingIOError:raise RuntimeError('Another uploader/recovery process is using this ledger') from None with contextlib.closing(up.open_ledger(ledger_path)) as ledger, contextlib.closing(db.connect(state/'par.sqlite')) as con: db.init(con) db.import_inventory(con,root/'inventory/source_records.csv',root/'config/sources.json') for remote_manifest in paths: raw=read_small_remote(api,args.repo_id,remote_manifest,head,up,8*1024*1024) batch=json.loads(raw) groups=validate_batch(batch,remote_manifest,args.repo_id,db,up) for eid,assets in groups.items(): validate_existing_event(incoming/eid/'event.manifest.json',eid,assets) for a in assets: old=ledger.execute('SELECT * FROM transfer_assets WHERE repo_id=? AND remote_path=?',(args.repo_id,a['remote_path'])).fetchone() if old and any(old[k]!=a[k] for k in ('event_id','kind','size_bytes','sha256')): raise ValueError('Immutable asset conflict during remote recovery') reusable=local_batch_is_verified(ledger,args.repo_id,head,groups,incoming,db) methods={};verified_at=up.utcnow() if reusable: summary['reused_verified_batches']+=1 for a in batch['assets']: r=ledger.execute('SELECT * FROM transfer_assets WHERE repo_id=? AND remote_path=?',(args.repo_id,a['remote_path'])).fetchone() methods[a['remote_path']]=r['verification_method'] else: all_paths=[a['remote_path'] for a in batch['assets']]+[remote_manifest] remote_map=up.get_remote_map(api,args.repo_id,all_paths,head) for a in batch['assets']: info=remote_map.get(a['remote_path']) methods[a['remote_path']]=up.verify_remote(a,info,api,args.repo_id,head) summary['remote_asset_checks']+=1 if a['kind'] in ('video','audio') and methods[a['remote_path']]=='remote_full_stream_sha256_and_size': summary['media_bytes_streamed_for_verification']+=a['size_bytes'] manifest_asset={'remote_path':remote_manifest,'size_bytes':len(raw),'sha256':hashlib.sha256(raw).hexdigest()} methods[remote_manifest]=up.verify_remote(manifest_asset,remote_map.get(remote_manifest),api,args.repo_id,head) local_batch_manifest=receipts/(batch['batch_id']+'.manifest.json') atomic_bytes(local_batch_manifest,raw,immutable=True) for eid,assets in groups.items(): event_dir=incoming/eid;event_dir.mkdir(parents=True,exist_ok=True) for a in assets: local=event_dir/Path(a['remote_path']).name if a['kind'] not in ('text','metadata'): continue if local.exists(): if local.is_symlink() or local.stat().st_size!=a['size_bytes'] or db.digest(local)!=a['sha256']: raise ValueError('Existing retained file differs; refusing overwrite') else: data=read_small_remote(api,args.repo_id,a['remote_path'],head,up) if len(data)!=a['size_bytes'] or hashlib.sha256(data).hexdigest()!=a['sha256']: raise ValueError('Downloaded retained file checksum mismatch') atomic_bytes(local,data,immutable=True) summary['retained_files_downloaded']+=1;summary['retained_bytes_downloaded']+=len(data) metadata_asset=next(a for a in assets if a['kind']=='metadata') metadata=json.loads((event_dir/Path(metadata_asset['remote_path']).name).read_text(encoding='utf-8')) if metadata.get('event_id')!=eid: raise ValueError('Recovered metadata belongs to another event') local_assets=[dict(a,local_path=str(event_dir/Path(a['remote_path']).name)) for a in assets] event_manifest={'schema_version':'1','event_id':eid,'quality_status':'full_av_text_verified', 'hq_status':metadata.get('hq_status','not_assessed'), 'readiness_evidence':metadata.get('technical_quality',{}),'assets':local_assets} manifest_path=event_dir/'event.manifest.json' atomic_bytes(manifest_path,up.json_bytes(event_manifest)) up.register(ledger,args.repo_id,list(up.read_manifests(manifest_path))) with ledger: for a in assets: old=ledger.execute('SELECT * FROM transfer_assets WHERE repo_id=? AND remote_path=?',(args.repo_id,a['remote_path'])).fetchone() if not reusable: ledger.execute("UPDATE transfer_assets SET state=CASE WHEN state='local_removed' THEN state ELSE 'verified' END,verified_commit=?,verification_method=?,verified_at=? WHERE repo_id=? AND remote_path=?", (head,methods[a['remote_path']],verified_at,args.repo_id,a['remote_path'])) all_manifests.append(manifest_path);all_event_ids.add(eid) with ledger: ledger.execute('''INSERT INTO transfer_batches(repo_id,batch_id,created_at,state,commit_sha,completed_at) VALUES(?,?,?,'verified',?,?) ON CONFLICT(repo_id,batch_id) DO UPDATE SET state='verified', commit_sha=excluded.commit_sha,completed_at=CASE WHEN transfer_batches.commit_sha=excluded.commit_sha AND transfer_batches.completed_at IS NOT NULL THEN transfer_batches.completed_at ELSE excluded.completed_at END,last_error_type=NULL''', (args.repo_id,batch['batch_id'],batch['created_at'],head,verified_at)) ledger.executemany('INSERT OR IGNORE INTO transfer_batch_items(repo_id,batch_id,remote_path) VALUES(?,?,?)', [(args.repo_id,batch['batch_id'],a['remote_path']) for a in batch['assets']]) up.write_event_markers(ledger,args.repo_id) verification=dict(batch,verified_commit=head,verified_at=verified_at,verification_methods=methods, recovery_source=remote_manifest,recovery_mode='fixed_revision_read_only') verified_file=receipts/(batch['batch_id']+'.verified.json') if not reusable or not verified_file.is_file(): atomic_bytes(verified_file,up.json_bytes(verification)) print(json.dumps({'stage':'batch_restored','batch_id':batch['batch_id'],'events':len(groups), 'reused_verification':reusable,'media_files_written':0}),flush=True) # Receipt creation precedes ingest; no missing media file is invented as local data. collection_status_path=incoming/'collection_status.json' collection_status=json.loads(collection_status_path.read_text(encoding='utf-8')) if collection_status_path.is_file() else {} for manifest_path in sorted(set(all_manifests)): m=json.loads(manifest_path.read_text(encoding='utf-8')) db.ingest_one(con,manifest_path,m) metadata_asset=next(a for a in m['assets'] if a['kind']=='metadata') metadata=json.loads(Path(metadata_asset['local_path']).read_text(encoding='utf-8')) url=metadata['primary_url'] prior=collection_status.get(url,{}) if prior.get('manifest') and Path(prior['manifest']).is_file(): validate_existing_event(Path(prior['manifest']),m['event_id'],m['assets']) collection_status[url]={**prior,'status':'complete','manifest':str(manifest_path), 'updated_at':prior.get('updated_at') if prior.get('status')=='complete' else up.utcnow(), 'restored_remote_revision':head} if all_manifests: atomic_bytes(collection_status_path,up.json_bytes(collection_status)) synchronization=db.sync_transfer(con,ledger_path) summary.update(restored_events=len(all_event_ids),database_status=db.status(con),transfer_sync=synchronization) summary['completed_at']=up.utcnow() atomic_bytes(state/'remote_restore_status.json',up.json_bytes(summary)) return summary def main(): os.umask(0o077) p=argparse.ArgumentParser(description=__doc__) p.add_argument('--work',type=Path,required=True) p.add_argument('--repo-id',default='Jiaxuannn/PAR') p.add_argument('--root',type=Path,default=Path(__file__).resolve().parents[1]) args=p.parse_args() try: print(json.dumps(restore(args),ensure_ascii=False,indent=2),flush=True) except Exception as exc: # Exception strings can contain redirected/signed URLs; print only a safe class. print(json.dumps({'error_type':type(exc).__name__,'status':'restore_failed', 'action':'Keep local state and inspect the failing batch with the fixed-revision receipt; no remote writes occurred.'}),file=sys.stderr) raise SystemExit(1) from None if __name__=='__main__':main()