"""Reproduce this full release from its pinned published baseline and reviewed repairs. Original source conversion/build producer: assets/upstream_patch.py. This final release step restores reviewed file edits and original archived payloads. Requires pyarrow; huggingface_hub is used only when local baseline paths are omitted. Example: python patch.py --source-tasks BASE/tasks.parquet --source-archive BASE/archive.parquet --output restored """ import argparse,base64,copy,gzip,hashlib,io,json,tarfile from pathlib import Path import pyarrow as pa import pyarrow.parquet as pq pa.set_cpu_count(min(pa.cpu_count(),4)) def digest_files(values): h=hashlib.sha256() for name,data in sorted(values): name=name.encode();h.update(len(name).to_bytes(8,'big'));h.update(name);h.update(len(data).to_bytes(8,'big'));h.update(data) return h.hexdigest() def members(blob): with tarfile.open(fileobj=io.BytesIO(blob),mode='r:*') as t: result=[] for m in t: p=Path(m.name) if p.is_absolute() or '..' in p.parts or not(m.isfile() or m.isdir()):raise ValueError('Unsafe task archive') result.append((copy.copy(m),t.extractfile(m).read() if m.isfile() else None)) return result def sha(path): with Path(path).open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest() def main(): ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('--source-tasks',type=Path);ap.add_argument('--source-archive',type=Path);ap.add_argument('--output',type=Path,required=True);ap.add_argument('--cache',type=Path);a=ap.parse_args();root=Path(__file__).resolve().parent;a.output.mkdir(parents=True,exist_ok=True) if any((a.output/n).exists() for n in ['tasks.parquet','archive.parquet']):raise ValueError('Output Parquets already exist') with tarfile.open(root/'assets/release-repairs.tar.gz','r:gz') as assets: spec=json.load(assets.extractfile('spec.json')) for kind in ['tasks','archive']: key='source_'+kind;p=getattr(a,key) if p is None: from huggingface_hub import hf_hub_download p=Path(hf_hub_download('FWeindel/validated-tasks',f'{spec["dataset"]}/{kind}.parquet',repo_type='dataset',revision=spec['baseline_revision'],cache_dir=str(a.cache or a.output.parent/'patch-hf-cache'))) if sha(p)!=spec['baseline_sha256'][kind]:raise ValueError('Pinned baseline mismatch: '+kind) setattr(a,key,p) schema=pa.ipc.read_schema(pa.BufferReader(base64.b64decode(spec['task_schema'])));metadata={k.encode():base64.b64decode(v) for k,v in spec['metadata'].items()};image_path=root/'cached_images/manifest.json' if image_path.exists():metadata[b'ot.images.v1']=image_path.read_bytes() schema=schema.with_metadata(metadata);seen=set() with pq.ParquetWriter(a.output/'tasks.parquet',schema,compression='zstd') as w: for batch in pq.ParquetFile(a.source_tasks).iter_batches(batch_size=32,use_threads=False): out=[] for row in batch.to_pylist(): n=row['path'];s=spec['tasks'].get(n) if s is None:continue ms=members(row['task_binary']);before={m.name:d for m,d in ms if d is not None} if digest_files(before.items())!=s['source_content_sha256']:raise ValueError('Source task drift: '+n) changed=s['changes'];result=[];remaining=dict(changed) for m,d in ms: if m.name in remaining: fix=remaining.pop(m.name) if fix is None:continue d=assets.extractfile(fix['asset']).read();m.mode=fix['mode'];m.size=len(d) result.append((m,d)) for name,fix in remaining.items(): if fix is None:raise ValueError('Missing deleted member') d=assets.extractfile(fix['asset']).read();m=tarfile.TarInfo(name);m.mode=fix['mode'];m.size=len(d);result.append((m,d)) if digest_files((m.name,d) for m,d in result if d is not None)!=s['content_sha256']:raise ValueError('Output task mismatch: '+n) buf=io.BytesIO() with tarfile.open(fileobj=buf,mode='w') as t: for m,d in result:t.addfile(m,io.BytesIO(d) if d is not None else None) out.append({**s['row'],'task_binary':buf.getvalue()});seen.add(n) if out:w.write_table(pa.Table.from_pylist(out,schema=schema)) if seen!=set(spec['tasks']):raise ValueError('Incomplete task coverage') base={r['path']:r['task_binary'] for b in pq.ParquetFile(a.source_archive).iter_batches(batch_size=32,use_threads=False) for r in b.to_pylist()};archived=[] for n,s in spec['archive'].items(): blob=assets.extractfile(s['asset']).read() if s.get('asset') else base[n] if hashlib.sha256(blob).hexdigest()!=s['binary_sha256']:raise ValueError('Archive payload drift: '+n) archived.append({**s['row'],'task_binary':blob}) ar_schema=pa.ipc.read_schema(pa.BufferReader(base64.b64decode(spec['archive_schema'])));pq.write_table(pa.Table.from_pylist(archived,schema=ar_schema),a.output/'archive.parquet',compression='zstd') print(json.dumps({'retained':len(seen),'archived':len(archived),'task_content_hashes_verified':True,'original_archive_payloads_verified':True})) if __name__=='__main__':main()