"""Copy project-generated audio to E, verify hashes, then gated per-file D cleanup.""" import argparse import hashlib import json from pathlib import Path import shutil from datetime import datetime, timezone REPO=Path(__file__).resolve().parents[2] SOURCE=(REPO/'data/tts-pilot').resolve() BATCH=SOURCE/'corpus50000-20261114' SUFFIXES={'.wav','.mp3','.pcm','.opus','.ogg','.flac','.m4a'} def sha(path): with path.open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest() def destination(): policy=json.loads((BATCH/'storage-policy.json').read_text(encoding='utf-8')) root=Path(policy['backup_base']).resolve() if root.drive.upper()!='E:' or policy['primary']!='minio':raise RuntimeError('Expected E backup and MinIO primary') return root def checked(root,relative): candidate=(root/relative).resolve() if not candidate.is_relative_to(root) or candidate==root or candidate.suffix.lower() not in SUFFIXES: raise RuntimeError('Audio path escaped its authorized root') return candidate def backup(): target=destination();target.mkdir(parents=True,exist_ok=True) manifest=[];total=0 for p in SOURCE.rglob('*'): if not p.is_file() or p.suffix.lower() not in SUFFIXES:continue rel=p.relative_to(SOURCE);src=checked(SOURCE,rel);dst=checked(target,rel) digest=sha(src);dst.parent.mkdir(parents=True,exist_ok=True) if dst.exists(): if sha(dst)!=digest:raise RuntimeError('Existing backup differs: '+str(rel)) else: temp=dst.with_suffix(dst.suffix+'.copying');shutil.copy2(src,temp) if sha(temp)!=digest:raise RuntimeError('Copied backup hash mismatch') temp.replace(dst) manifest.append({'relative':rel.as_posix(),'sha256':digest,'bytes':src.stat().st_size});total+=src.stat().st_size if len(manifest)%2000==0:print('BACKUP_VERIFIED',len(manifest),flush=True) payload={'created_at':datetime.now(timezone.utc).isoformat(),'source':str(SOURCE),'backup':str(target),'count':len(manifest),'bytes':total,'files':manifest} text=json.dumps(payload,ensure_ascii=False) (target/'d-audio-backup-manifest.json').write_text(text,encoding='utf-8') (BATCH/'d-audio-backup-manifest.json').write_text(text,encoding='utf-8') print(json.dumps({'backup_verified':len(manifest),'bytes':total,'backup':str(target)}),flush=True) def cleanup(): target=destination();manifest_path=BATCH/'d-audio-backup-manifest.json' if manifest_path.read_bytes()!=(target/'d-audio-backup-manifest.json').read_bytes():raise RuntimeError('Backup manifests differ') manifest=json.loads(manifest_path.read_text(encoding='utf-8')) if manifest['source']!=str(SOURCE) or manifest['backup']!=str(target):raise RuntimeError('Backup roots changed') audit=json.loads((BATCH/'minio-backup-audit.json').read_text(encoding='utf-8')) if audit['primary']!='minio' or not all(audit[k] for k in ['database_paths_verified','remote_sha256_verified','e_backup_sha256_verified']): raise RuntimeError('MinIO/database/backup verification has not passed') remote_manifest=BATCH/'minio-backup-verified.jsonl' if sha(remote_manifest)!=audit['manifest_sha256']:raise RuntimeError('MinIO verification manifest changed') remote={v['id']:v for v in map(json.loads,remote_manifest.read_text(encoding='utf-8').splitlines())} deleted=0;freed=0 for row in manifest['files']: rel=Path(row['relative']);src=checked(SOURCE,rel);dst=checked(target,rel) if sha(dst)!=row['sha256']:raise RuntimeError('E backup changed: '+str(rel)) if rel.parts[0]=='corpus50000-20261114': record=remote.get(src.stem) if not record or record['sha256']!=row['sha256']:raise RuntimeError('MinIO audit missing for production audio') if src.exists(): if sha(src)!=row['sha256']:raise RuntimeError('D source changed after backup') src.unlink();deleted+=1;freed+=row['bytes'] if deleted and deleted%2000==0:print('D_AUDIO_DELETED',deleted,flush=True) result={'checked_at':datetime.now(timezone.utc).isoformat(),'deleted_files':deleted,'freed_bytes':freed,'backup':str(target),'minio_verified_production_files':audit['count']} (BATCH/'d-audio-cleanup-receipt.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf-8') print(json.dumps(result),flush=True) if __name__=='__main__': parser=argparse.ArgumentParser();parser.add_argument('mode',choices=['backup','cleanup']);args=parser.parse_args() backup() if args.mode=='backup' else cleanup()