"""Compute-node build, native streaming verification, and explicit public release.""" from __future__ import annotations import argparse from collections import Counter import hashlib import importlib.metadata import json import os from pathlib import Path import shutil import tarfile from .export_sft_v3 import export_sft from .io import sha256_file, write_json_atomic from .quality_v2 import validate_record_quality_v2 from .serializers_v3 import canonical_json_v3 from .v2_cli import run_build_v2, _source_snapshot_contents_match OLD_REPO = "voidful/barbet-bgd-synthetic-sft-1m-tw-v2" REPO = "voidful/barbet-sft" PROJECT = Path(__file__).resolve().parents[2] def require_compute() -> None: if not os.environ.get("SLURM_JOB_ID"): raise RuntimeError("Full release work must run within a Slurm compute allocation") def native_streaming_verify(root: Path, report: dict) -> dict: """Read every row using datasets, comparing per-shard full row digests.""" from datasets import load_dataset counts: Counter = Counter() checked = [] for shard in report["shards"]: stream = load_dataset( "parquet", data_files={shard["split"]: str(root / shard["path"])}, split=shard["split"], streaming=True, cache_dir=str(root / ".native-datasets-cache"), ) digest = hashlib.sha256() count = 0 for row in stream: if not isinstance(row["messages"], list): raise ValueError("datasets did not return a list of message structs") if [turn["role"] for turn in row["messages"]] != ["system", "user", "assistant"]: raise ValueError("invalid native message role order") digest.update(canonical_json_v3(row).encode("utf-8") + b"\n") count += 1 if count != shard["records"] or digest.hexdigest() != shard["rows_sha256"]: raise ValueError(f"native datasets digest mismatch: {shard['path']}") counts[shard["split"]] += count checked.append({"path": shard["path"], "records": count, "rows_sha256": digest.hexdigest()}) print(f"Native datasets verified {sum(counts.values())} records", flush=True) if dict(counts) != report["split_counts"]: raise ValueError("native datasets split counts differ from Parquet export") result = {"verified": True, "records": sum(counts.values()), "split_counts": dict(counts), "shards": checked, "datasets_version": importlib.metadata.version("datasets")} write_json_atomic(root / "reports" / "native-streaming-verification.json", result) return result def dataset_card(report: dict) -> str: counts = report["split_counts"] return f'''--- pretty_name: Barbet SFT language: - zh - en license: other license_name: barbet-sft-public-access license_link: LICENSE_DATA.md task_categories: - text-generation size_categories: - 1M dict: marker = json.loads((root / "_PROMOTED.json").read_text()) if not marker["training_promotion_passed"] or not marker["public_release_promotion_passed"]: raise ValueError("canonical promotion/public-owner-authorization did not pass") if (sha256_file(root / "manifest.json") != marker["manifest_sha256"] or sha256_file(root / "reports/postwrite-verification.json") != marker["postwrite_report_sha256"]): raise ValueError("canonical promotion manifest/report hashes changed") manifest = json.loads((root / "manifest.json").read_text()) source_bundle = manifest["metadata"]["source_bundle"] snapshot = manifest["metadata"]["source_snapshot"] if not _source_snapshot_contents_match(snapshot, source_bundle): raise ValueError("pinned code snapshot integrity check failed") exported = export_sft(root, root, record_validator=validate_record_quality_v2, progress=print) native = native_streaming_verify(root, exported) code_dir = root / "code" if code_dir.exists(): raise FileExistsError(code_dir) with tarfile.open(root / "source_bundle_snapshot.tar.gz", "r:gz") as archive: archive.extractall(code_dir, filter="data") for entry in source_bundle["files"]: if sha256_file(code_dir / entry["logical_path"]) != entry["sha256"]: raise ValueError(f"extracted source differs from snapshot: {entry['logical_path']}") shutil.copyfile(code_dir / "LICENSE_DATA.md", root / "LICENSE_DATA.md") (root / "README.md").write_text(dataset_card(exported), encoding="utf-8") artifact_files = [] for path in sorted(root.rglob("*")): relative = path.relative_to(root) if not path.is_file() or any(part.startswith(".") for part in relative.parts): continue if "__pycache__" in relative.parts or path.name.endswith(".incomplete"): continue artifact_files.append({"path": relative.as_posix(), "bytes": path.stat().st_size, "sha256": sha256_file(path)}) result = { "release": "barbet-sft-v3", "records": exported["records"], "split_counts": exported["split_counts"], "verified": True, "checks": {"canonical_full_promotion": True, "explicit_owner_public_authorization": True, "sft_full_readback": exported["verified"], "native_full_streaming": native["verified"]}, "artifact_files": artifact_files, "public_access_is_not_additional_copyright_license": True, } write_json_atomic(root / "reports" / "release-verification.json", result) return result def publish(root: Path) -> dict: from huggingface_hub import HfApi from huggingface_hub.errors import RepositoryNotFoundError report = json.loads((root / "reports/release-verification.json").read_text()) mandatory_checks = {"canonical_full_promotion", "explicit_owner_public_authorization", "sft_full_readback", "native_full_streaming"} if (report.get("verified") is not True or report.get("records") != 1_000_000 or any(report.get("checks", {}).get(key) is not True for key in mandatory_checks)): raise ValueError("release did not pass full verification") paths = [] for item in report["artifact_files"]: path = root / item["path"] if path.stat().st_size != item["bytes"] or sha256_file(path) != item["sha256"]: raise ValueError(f"release artifact changed: {item['path']}") paths.append(item["path"]) paths.append("reports/release-verification.json") api = HfApi() config = json.loads((root / "config.snapshot.json").read_text()) expected_base = config["previous_release"]["revision"] receipt_path = root / "reports/upload-receipt.json" allowed_revisions = {expected_base} if receipt_path.exists(): receipt = json.loads(receipt_path.read_text()) if receipt.get("repo_id") != REPO: raise ValueError("upload receipt belongs to another repository") allowed_revisions.add(receipt["commit"]) try: existing = api.repo_info(REPO, repo_type="dataset") except RepositoryNotFoundError: existing = None if existing is None: original = api.repo_info(OLD_REPO, repo_type="dataset") if original.id != OLD_REPO or original.sha not in allowed_revisions: raise ValueError("original repository does not match explicit rename target") api.move_repo(from_id=OLD_REPO, to_id=REPO, repo_type="dataset") existing = api.repo_info(REPO, repo_type="dataset") elif existing.id != REPO: raise ValueError("unexpected repository redirect") else: original = api.repo_info(OLD_REPO, repo_type="dataset") if original.id != REPO: raise ValueError("barbet-sft is a separate existing repository, not the requested rename") if existing.sha not in allowed_revisions: raise ValueError("target repository has unexpected changes; refusing to overwrite") commit = api.upload_folder( repo_id=REPO, repo_type="dataset", folder_path=str(root), allow_patterns=paths, parent_commit=existing.sha, commit_message="Release reviewed Taiwan-centric Barbet SFT 1M with fixed-schema messages and full audits", ) write_json_atomic(receipt_path, {"repo_id": REPO, "commit": commit.oid}) remote = api.repo_info(REPO, repo_type="dataset", revision=commit.oid, files_metadata=True) remote_files = {file.rfilename: file for file in remote.siblings} for filename in paths: file = remote_files.get(filename) local = root / filename if file is None or file.size != local.stat().st_size: raise ValueError(f"remote file missing or size mismatch: {filename}") if file.lfs and file.lfs.sha256 != sha256_file(local): raise ValueError(f"remote LFS hash mismatch: {filename}") if not file.lfs: raw = local.read_bytes() digest = hashlib.sha1(f"blob {len(raw)}\0".encode() + raw).hexdigest() if file.blob_id != digest: raise ValueError(f"remote Git blob hash mismatch: {filename}") api.update_repo_settings(repo_id=REPO, repo_type="dataset", private=False, gated=False) anonymous = HfApi(token=False).repo_info(REPO, repo_type="dataset") if anonymous.private or anonymous.sha != commit.oid: raise ValueError("anonymous public verification failed or revision changed") from datasets import load_dataset anonymous_rows = {} export_report = json.loads((root / "reports/sft-export-verification.json").read_text()) for split in ("train", "validation", "test"): stream = load_dataset(REPO, name="sft", split=split, streaming=True, token=False, revision=commit.oid, cache_dir=str(root / ".anonymous-load-cache")) row = next(iter(stream)) expected = next(item for item in export_report["shards"] if item["split"] == split) if (row["record_id"] != expected["first_record_id"] or row["locale"] != "zh-TW" or not isinstance(row["messages"], list) or hashlib.sha256(canonical_json_v3(row["messages"]).encode()).hexdigest() != row["messages_sha256"]): raise ValueError(f"anonymous SFT loading failed: {split}") anonymous_rows[split] = row["record_id"] result = {"repo_id": REPO, "url": f"https://huggingface.co/datasets/{REPO}", "commit": commit.oid, "public": True, "anonymous_access": True, "verified_uploaded_files": len(paths), "anonymous_split_first_rows": anonymous_rows} write_json_atomic(root / "reports/remote-publication.json", result) return result def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("command", choices=["build", "finalize", "publish"]) parser.add_argument("--config", default=str(PROJECT / "configs/barbet_sft.json")) parser.add_argument("--output", required=True) parser.add_argument("--workers", type=int, default=16) args = parser.parse_args() require_compute() root = Path(args.output).resolve() if args.command == "build": run_build_v2(config_path=args.config, output_root=root, workers=args.workers) result = finalize(root) elif args.command == "finalize": result = finalize(root) else: result = publish(root) print(json.dumps(result, ensure_ascii=False, indent=2), flush=True) if __name__ == "__main__": main()