#!/usr/bin/env python3 """Publish a verified OXT correction against an explicit immutable baseline. Only an existing public Alan0928 dataset is accepted. Existing remote bytes must match the baseline or the corrected stage. Changed LFS objects are preuploaded with direct disk reads, then all replacements/deletions are committed atomically against the inspected parent. No global HF settings or credentials are saved. This script never renames or creates a repository. """ import argparse import copy import hashlib import json from pathlib import Path import re import sys import upload_oxt_hf as core def load_baseline(folder): """Verify the old manifests without retaining old multi-GB archive payloads. LFS versions are proven from the old SHA256 inventory. For regular Git files, available small originals supply Git blob hashes; missing originals are fetched at the inspected remote revision and SHA256-checked later. """ folder = Path(folder).resolve(strict=True) if folder.is_symlink(): raise core.UploadCheckError("Baseline folder must not be a symbolic link.") manifest_path, checksum_path = folder / "upload_manifest.json", folder / "SHA256SUMS" for path in (manifest_path, checksum_path): if path.is_symlink() or not path.is_file(): raise core.UploadCheckError("Baseline manifests must be regular files.") fingerprints = {name: core.file_fingerprint(folder / name) for name in ("upload_manifest.json", "SHA256SUMS")} manifest = json.loads(manifest_path.read_text(encoding="utf-8")) if not re.fullmatch(r"Alan0928/[A-Za-z0-9][A-Za-z0-9._-]*", str(manifest.get("repo_id", ""))): raise core.UploadCheckError("Baseline must belong to an Alan0928 dataset.") if not re.fullmatch(r"[0-9a-f]{64}", str(manifest.get("source_package_sha256", ""))): raise core.UploadCheckError("Baseline source package SHA256 is invalid.") files = manifest.get("files") if not isinstance(files, dict) or not files: raise core.UploadCheckError("Baseline file inventory is invalid.") files = copy.deepcopy(files) for name, value in files.items(): core.safe_relative_name(name) if (name in ("SHA256SUMS", "upload_manifest.json") or not isinstance(value, dict) or type(value.get("bytes")) is not int or value["bytes"] < 0 or not re.fullmatch(r"[0-9a-f]{64}", str(value.get("sha256", "")))): raise core.UploadCheckError("Baseline file record is invalid.") checksums = {} for line in checksum_path.read_text(encoding="utf-8").splitlines(): match = re.fullmatch(r"([0-9a-f]{64}) (.+)", line) if not match: raise core.UploadCheckError("Baseline checksum manifest is malformed.") digest, name = match.groups() core.safe_relative_name(name) if name in checksums: raise core.UploadCheckError("Baseline checksum manifest has a duplicate entry.") checksums[name] = digest manifest_sha, manifest_git = core.file_digests(manifest_path) expected = {name: value["sha256"] for name, value in files.items()} expected["upload_manifest.json"] = manifest_sha if checksums != expected: raise core.UploadCheckError("Baseline upload and checksum manifests disagree.") sum_sha, sum_git = core.file_digests(checksum_path) files["upload_manifest.json"] = {"bytes": manifest_path.stat().st_size, "sha256": manifest_sha} files["SHA256SUMS"] = {"bytes": checksum_path.stat().st_size, "sha256": sum_sha} git_blobs = {"upload_manifest.json": manifest_git, "SHA256SUMS": sum_git} for name, value in files.items(): path = folder / name if name in git_blobs or value["bytes"] > 20_000_000 or not path.is_file(): continue if any(parent.is_symlink() for parent in (path, *path.parents) if parent != folder.parent): raise core.UploadCheckError("Baseline proof files must not use symbolic links.") fingerprints[name] = core.file_fingerprint(path) digest, git = core.verified_file_digests(path, value["sha256"], name, [], progress=False) if path.stat().st_size != value["bytes"]: raise core.UploadCheckError("Baseline proof file size differs from its manifest.") git_blobs[name] = git baseline = {"folder": folder, "manifest": manifest, "files": files, "git_blob_sha1": git_blobs, "fingerprints": fingerprints} assert_baseline_unchanged(baseline) return baseline def assert_baseline_unchanged(baseline): for name, fingerprint in baseline["fingerprints"].items(): if core.file_fingerprint(baseline["folder"] / name) != fingerprint: raise core.UploadCheckError("Baseline proof files changed during correction.") def matches(checked, name, remote): if name not in checked["files"]: return False lfs = getattr(remote, "lfs", None) lfs_sha = lfs.get("sha256") if isinstance(lfs, dict) else getattr(lfs, "sha256", None) if not lfs_sha and name not in checked["git_blob_sha1"]: return False try: core.verify_remote_entry(checked["folder"] / name, remote, checked["files"][name], checked["git_blob_sha1"].get(name)) return True except core.UploadCheckError: return False def classify_snapshot(info, files, baseline, corrected): """Reject unknown files/versions, retaining both baseline and new receipts.""" if info.private is not False: raise core.UploadCheckError("The existing dataset must remain public.") if "upload_manifest.json" not in files: raise core.UploadCheckError("Existing dataset lacks verified upload provenance.") allowed = set(baseline["files"]) | set(corrected["files"]) if set(files) - allowed: raise core.UploadCheckError("Remote contains files outside both verified stages.") current = set() for name, remote in files.items(): if matches(corrected, name, remote): current.add(name) elif not matches(baseline, name, remote): raise core.UploadCheckError("Remote file matches neither verified stage: " + name) return current def final_snapshot(info, files, corrected, ignore_attributes=False): """Check the complete final file set, not only the files changed this run.""" if set(files) != set(corrected["files"]): raise core.UploadCheckError("Remote final inventory differs from the corrected stage.") selected = {name: item for name, item in files.items() if not ignore_attributes or name != ".gitattributes"} core.verify_remote_snapshot(info, selected, corrected, require_complete=not ignore_attributes) def inspect_snapshot(api, repo_id, baseline, corrected, network, repair=False): info, files = core.read_remote_snapshot(api, repo_id, network) for name, item in files.items(): if (matches(corrected, name, item) or name not in baseline["files"] or name in baseline["git_blob_sha1"] or getattr(item, "lfs", None) is not None): continue expected = baseline["files"][name] if item.size != expected["bytes"] or item.size > 20_000_000: raise core.UploadCheckError("Unavailable baseline Git proof cannot match remote: " + name) downloaded = network.call("Read pinned baseline Git proof: " + name, lambda: api.hf_hub_download(repo_id=repo_id, repo_type="dataset", filename=name, revision=info.sha)) digest, git = core.verified_file_digests(Path(downloaded).resolve(strict=True), expected["sha256"], name, [], progress=False) if git != item.blob_id: raise core.UploadCheckError("Downloaded baseline Git proof differs from pinned snapshot.") baseline["git_blob_sha1"][name] = git try: current = classify_snapshot(info, files, baseline, corrected) except core.UploadCheckError as original: # A completed commit can have Hub-added literal LFS rules. The existing # narrowly scoped helper validates every rule before restoring them. if not repair: raise try: final_snapshot(info, files, corrected, ignore_attributes=True) except core.UploadCheckError: raise original from None info, files = core.reconcile_remote_attributes(api, repo_id, corrected, info, files, network) current = classify_snapshot(info, files, baseline, corrected) return info, files, current def prepare_addition(api, repo_id, corrected, name, network): from oxt_direct_io import DirectIOReader from oxt_hf_resume import build_verified_operation def preupload(): operation = build_verified_operation(corrected, name) path = corrected["folder"] / name with DirectIOReader(path, expected_fingerprint=corrected["fingerprints"][name]) as stream: operation.upload_info.sample = stream.read(512) stream.seek(0) operation.path_or_fileobj = stream api.preupload_lfs_files(repo_id=repo_id, repo_type="dataset", revision="main", create_pr=False, additions=[operation], num_threads=1, free_memory=False) if operation._upload_mode == "regular": # Git payloads need their bytes at commit time. Large files # must be LFS, so an unexpected server mode cannot exhaust RAM. if corrected["files"][name]["bytes"] > 20_000_000: raise core.UploadCheckError("Large corrected file was not assigned LFS: " + name) stream.seek(0) contents = stream.read() if hashlib.sha256(contents).hexdigest() != corrected["files"][name]["sha256"]: raise core.UploadCheckError("Direct-read bytes differ from verified file: " + name) operation.path_or_fileobj = contents elif operation._upload_mode == "lfs" and operation._is_uploaded: operation.path_or_fileobj = str(path) else: raise core.UploadCheckError("Preupload did not confirm the corrected file: " + name) return operation return network.call("Preupload corrected file: " + name, preupload) def commit_correction(api, repo_id, corrected, prepared, deletions, info, network): from huggingface_hub import CommitOperationDelete from oxt_hf_network import is_retryable def commit(): core.assert_staging_unchanged(corrected) additions = [copy.copy(operation) for operation in prepared] for operation in additions: operation._is_committed = False operations = additions + [CommitOperationDelete(path_in_repo=name) for name in deletions] try: api.create_commit(repo_id=repo_id, repo_type="dataset", revision="main", parent_commit=info.sha, operations=operations, num_threads=1, commit_message="Align IDEAL-FT data with FTP-1 submission conventions") except Exception as error: status = getattr(getattr(error, "response", None), "status_code", None) if not is_retryable(error) and status != 409: raise latest, files = core.read_remote_snapshot(api, repo_id, network) try: final_snapshot(latest, files, corrected, ignore_attributes=True) except core.UploadCheckError: if latest.sha != info.sha: raise core.UploadCheckError("Repository changed during the pinned correction commit.") from None raise error return latest, files latest, files = core.read_remote_snapshot(api, repo_id, network) final_snapshot(latest, files, corrected, ignore_attributes=True) return latest, files return network.call("Commit complete verified correction", commit) def update(api, repo_id, baseline, corrected, state, network, dry_run=False): core.verify_owner(network.call("Verify token owner", lambda: api.whoami())) info, files, current = inspect_snapshot(api, repo_id, baseline, corrected, network, repair=not dry_run) additions = sorted(set(corrected["files"]) - current, key=lambda name: (corrected["files"][name]["bytes"], name)) deletions = sorted(set(files) - set(corrected["files"])) plan = {"repo_id": repo_id, "parent_commit": info.sha, "unchanged_files": len(current), "replace_or_add": additions, "delete": deletions, "upload_bytes": sum(corrected["files"][name]["bytes"] for name in additions), "baseline_sha256sums": baseline["files"]["SHA256SUMS"]["sha256"], "corrected_sha256sums": corrected["files"]["SHA256SUMS"]["sha256"]} core.atomic_json(state / "update_plan.json", plan) print("Verified remote: %d unchanged, %d additions/replacements, %d deletions (%.2f GB)." % (len(current), len(additions), len(deletions), plan["upload_bytes"] / 1e9), flush=True) if dry_run: return {"status": "dry_run_verified", "remote_writes": False, **plan} prepared = [] for index, name in enumerate(additions, 1): core.assert_staging_unchanged(corrected) print("Preparing %d/%d: %s" % (index, len(additions), name), flush=True) prepared.append(prepare_addition(api, repo_id, corrected, name, network)) core.atomic_json(state / "update_progress.json", { "status": "preuploading", "time": core.utc_now(), "repo_id": repo_id, "parent_commit": info.sha, "prepared_files": index, "total_changed_files": len(additions), "last_preuploaded_file": name}) if additions or deletions: assert_baseline_unchanged(baseline) info, files = commit_correction(api, repo_id, corrected, prepared, deletions, info, network) info, files = core.reconcile_remote_attributes(api, repo_id, corrected, info, files, network) final_snapshot(info, files, corrected) core.assert_staging_unchanged(corrected) return {"status": "verified", "completed_at": core.utc_now(), "repo_id": repo_id, "url": core.ENDPOINT + "/datasets/" + repo_id, "revision": info.sha, "verified_files": len(files), "total_bytes": corrected["total_bytes"], "sha256sums_sha256": corrected["files"]["SHA256SUMS"]["sha256"], "changed_files": len(additions), "deleted_files": len(deletions), "network_retries": network.retries, "global_hf_configuration_changed": False, "token_persisted": False} def run(args, state): phase = "local_validation" network = None try: core.isolate_hf_environment(state) print("Verifying baseline checksum records and available Git proofs.", flush=True) baseline = load_baseline(args.baseline_stage) print("Verifying corrected distribution.", flush=True) corrected = core.validate_staging(args.stage, args.repo_id) if args.check_only: result = {"status": "offline_verified", "repo_id": args.repo_id, "baseline_files": len(baseline["files"]), "verified_files": len(corrected["files"]), "sha256sums_sha256": corrected["files"]["SHA256SUMS"]["sha256"], "network_used": False, "token_requested": False} else: phase = "authentication" token = core.read_token_file(args.token_file) if args.token_file else core.read_hidden_token() from huggingface_hub import HfApi from oxt_hf_network import NetworkRunner, configure_http configure_http() network = NetworkRunner() api = HfApi(endpoint=core.ENDPOINT, token=token) try: phase = "remote_inspection" if args.dry_run else "correction_and_remote_verification" result = update(api, args.repo_id, baseline, corrected, state, network, args.dry_run) finally: api.token = None token = None core.atomic_json(state / "last_update_result.json", result) print("Update result: " + result["status"], flush=True) return 0 except KeyboardInterrupt: result = {"status": "interrupted", "phase": phase, "repo_id": args.repo_id} print("Interrupted; rerun the same command to recheck and resume.", file=sys.stderr) code = 130 except Exception as error: status = getattr(getattr(error, "response", None), "status_code", None) result = {"status": "failed", "phase": phase, "repo_id": args.repo_id, "error_type": type(error).__name__} if isinstance(status, int): result["http_status"] = status if isinstance(error, core.UploadCheckError): result["reason"] = str(error) print("Stopped: " + str(error), file=sys.stderr) else: print("Stopped during %s: %s%s." % (phase, type(error).__name__, " (HTTP %d)" % status if isinstance(status, int) else ""), file=sys.stderr) code = 1 result["time"] = core.utc_now() if network is not None: result["network_operation"] = network.last_operation result["network_retries"] = network.retries core.atomic_json(state / "last_update_result.json", result) return code def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--stage", type=Path, required=True) baseline = parser.add_mutually_exclusive_group(required=True) baseline.add_argument("--baseline-stage", type=Path, help="Old stage; old LFS payloads may be absent") baseline.add_argument("--baseline-manifest", type=Path, help="Old upload_manifest.json with adjacent old SHA256SUMS") parser.add_argument("--repo-id", required=True) parser.add_argument("--state-dir", type=Path, required=True) parser.add_argument("--token-file", type=Path) modes = parser.add_mutually_exclusive_group() modes.add_argument("--check-only", action="store_true", help="Local verification; no token/network") modes.add_argument("--dry-run", action="store_true", help="Verify remote and save plan; no remote writes") args = parser.parse_args(argv) if not re.fullmatch(r"Alan0928/[A-Za-z0-9][A-Za-z0-9._-]*", args.repo_id): parser.error("repo-id must identify an Alan0928 dataset") try: if args.baseline_manifest is not None: if args.baseline_manifest.name != "upload_manifest.json": raise core.UploadCheckError("Baseline manifest must retain its upload_manifest.json name.") args.baseline_stage = args.baseline_manifest.parent args.stage = args.stage.resolve(strict=True) args.baseline_stage = args.baseline_stage.resolve(strict=True) state = args.state_dir.absolute() if args.stage == args.baseline_stage: raise core.UploadCheckError("Corrected and baseline stages must be separate.") for stage in (args.stage, args.baseline_stage): if state.resolve() == stage or stage in state.resolve().parents: raise core.UploadCheckError("State/cache must be outside both immutable stages.") with core.single_run(state): return run(args, state) except Exception as error: message = str(error) if isinstance(error, core.UploadCheckError) else type(error).__name__ print("Stopped before update: " + message, file=sys.stderr) return 1 if __name__ == "__main__": raise SystemExit(main())