#!/usr/bin/env python3 """Structural and scientific-contract audit for the staged dataset release.""" from __future__ import annotations import argparse import csv import hashlib import json import re from pathlib import Path import yaml RAI_FIELDS = ( "rai:dataLimitations", "rai:dataBiases", "rai:personalSensitiveInformation", "rai:dataUseCases", "rai:dataSocialImpact", "rai:hasSyntheticData", "prov:wasDerivedFrom", "prov:wasGeneratedBy", ) TYPE_MAP = { "string": "sc:Text", "int64": "sc:Integer", "float64": "sc:Float", "bool": "sc:Boolean", } BLOCKED_CONFIGS = {"infrastructure_evidence_status", "future_route_schema"} SOURCE_REVISION = "932f6f4f62c3402adf38231ed83ea9ca17cc227c" CODE_REVISION = "eb8a2f3a681a3d596d5acf454f6ce2fc5a6f677d" LICENSE_ID = "cc-by-4.0" LICENSE_SPDX = "CC-BY-4.0" LICENSE_URL = "https://creativecommons.org/licenses/by/4.0/" NONPUBLIC_REPOSITORY_URL = re.compile( r"https://github\.com/[^\s\"']+/[^/\s\"']*(?:paper|manuscript)[^/\s\"']*", re.IGNORECASE, ) def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def card_metadata(root: Path) -> dict: text = (root / "README.md").read_text(encoding="utf-8") if not text.startswith("---\n"): raise ValueError("README.md must begin with YAML frontmatter") return yaml.safe_load(text.split("---", 2)[1]) or {} def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("root", nargs="?", default=".") parser.add_argument("--json-out") parser.add_argument( "--skip-byte-checksums", action="store_true", help="verify checksum coverage and format without hashing local bytes", ) parser.add_argument( "--release-gate", action="store_true", help="also fail on acknowledged publication blockers", ) args = parser.parse_args() root = Path(args.root).resolve() errors: list[dict] = [] blockers: list[dict] = [] warnings: list[dict] = [] def error(code: str, detail) -> None: errors.append({"code": code, "detail": detail}) def blocker(code: str, detail) -> None: blockers.append({"code": code, "detail": detail}) metadata = card_metadata(root) if metadata.get("license") != LICENSE_ID: error("card.license", {"expected": LICENSE_ID, "actual": metadata.get("license")}) configs = metadata.get("configs") or [] names = [item.get("config_name") for item in configs] if len(names) != len(set(names)): error("card.duplicate_configuration", names) defaults = [item for item in configs if item.get("default") is True] if len(defaults) != 1: error("card.default_configuration", f"expected one default, got {len(defaults)}") if set(names) & BLOCKED_CONFIGS: error( "card.blocked_configuration_exposed", sorted(set(names) & BLOCKED_CONFIGS), ) manifest = json.loads((root / "metadata/release_manifest.json").read_text()) schema = json.loads((root / "metadata/schema.json").read_text()) croissant = json.loads((root / "metadata/croissant.json").read_text()) manifest_by = {item["name"]: item for item in manifest.get("configs", [])} schema_by = {item["name"]: item for item in schema.get("record_sets", [])} if set(names) != set(manifest_by): error("manifest.configuration_set", sorted(set(names) ^ set(manifest_by))) if set(names) != set(schema_by): error("schema.configuration_set", sorted(set(names) ^ set(schema_by))) if any(not str(item.get("path", "")).startswith("data/processed/") for item in manifest_by.values()): error("layers.processed_configuration_root", "every loadable configuration must live under data/processed/") if manifest.get("canonical_source_revision") != SOURCE_REVISION: error("provenance.source_revision", manifest.get("canonical_source_revision")) if manifest.get("code_revision") != CODE_REVISION: error("provenance.code_revision", manifest.get("code_revision")) if manifest.get("license") != LICENSE_SPDX: error("release.license", manifest.get("license")) if manifest.get("license_url") != LICENSE_URL: error("release.license_url", manifest.get("license_url")) if manifest.get("status") != "READY_FOR_HF_STAGING": error("release.staging_status", manifest.get("status")) pipeline_contract = json.loads((root / "metadata/pipeline_contract.json").read_text()) if pipeline_contract.get("no_requery_policy") is not True: error("pipeline.no_requery_policy", pipeline_contract.get("no_requery_policy")) if pipeline_contract.get("source", {}).get("revision") != SOURCE_REVISION: error("pipeline.source_revision", pipeline_contract.get("source", {}).get("revision")) if pipeline_contract.get("code", {}).get("revision") != CODE_REVISION: error("pipeline.code_revision", pipeline_contract.get("code", {}).get("revision")) clean_load = json.loads((root / "metadata/clean_load_audit.json").read_text()) if clean_load.get("hf_datasets_clean_load") != "PASS": error("hosting.local_hf_clean_load", clean_load.get("hf_datasets_clean_load")) if len(clean_load.get("configurations") or []) != len(names): error("hosting.local_hf_configuration_count", len(clean_load.get("configurations") or [])) croissant_receipt = json.loads( (root / "metadata/croissant_validation.json").read_text() ) if croissant_receipt.get("status") != "PASS_LOCAL_CANDIDATE": error("croissant.local_validation", croissant_receipt.get("status")) with (root / "metadata/migration_manifest.csv").open( newline="", encoding="utf-8-sig" ) as handle: migration_rows = list(csv.DictReader(handle)) if len(migration_rows) != 32: error("migration.record_count", len(migration_rows)) migration_ids = [row.get("artifact_id") for row in migration_rows] if len(migration_ids) != len(set(migration_ids)): error("migration.duplicate_artifact_id", migration_ids) migrated_targets = set() for row in migration_rows: target = row.get("target_path", "") status = row.get("migration_status", "") if status == "VERIFIED_COPY": path = root / target migrated_targets.add(target) if not path.is_file(): error("migration.missing_verified_copy", target) continue if sha256(path) != row.get("sha256"): error("migration.digest", {"artifact_id": row.get("artifact_id"), "path": target}) if path.suffix == ".csv" and row.get("row_count"): with path.open(newline="", encoding="utf-8-sig") as handle: actual_rows = len(list(csv.DictReader(handle))) if actual_rows != int(row["row_count"]): error("migration.row_count", {"artifact_id": row.get("artifact_id"), "expected": row.get("row_count"), "actual": actual_rows}) elif target: error("migration.unverified_target_exposed", {"artifact_id": row.get("artifact_id"), "status": status, "path": target}) queried_files = { path.relative_to(root).as_posix() for path in (root / "data/queried").glob("*/*") if path.is_file() } if queried_files - migrated_targets: error("migration.untracked_queried_file", sorted(queried_files - migrated_targets)) processed_config_paths = {item.get("path") for item in manifest_by.values()} if processed_config_paths - migrated_targets: error("migration.untracked_processed_configuration", sorted(processed_config_paths - migrated_targets)) with (root / "metadata/data_dictionary.csv").open( newline="", encoding="utf-8-sig" ) as handle: dictionary_rows = list(csv.DictReader(handle)) dictionary = { (row["configuration"], row["name"]): row for row in dictionary_rows } loaded = [] for item in configs: name = item["config_name"] specs = item.get("data_files") or [] if len(specs) != 1: error("card.data_files_shape", {"configuration": name, "entries": specs}) continue spec = specs[0] if spec.get("split") != "train": error("card.split", {"configuration": name, "split": spec.get("split")}) rel = spec.get("path") path = root / str(rel) if not path.is_file(): error("card.missing_data_file", {"configuration": name, "path": rel}) continue with path.open(newline="", encoding="utf-8-sig") as handle: reader = csv.DictReader(handle) fields = list(reader.fieldnames or []) rows = list(reader) m = manifest_by.get(name, {}) s = schema_by.get(name, {}) if m.get("path") != rel: error("manifest.path", {"configuration": name, "path": m.get("path")}) if m.get("split") != "train": error("manifest.split", {"configuration": name, "split": m.get("split")}) if m.get("rows") != len(rows) or s.get("rows") != len(rows): error( "schema.row_count", { "configuration": name, "csv": len(rows), "manifest": m.get("rows"), "schema": s.get("rows"), }, ) if m.get("fields") != fields: error("manifest.fields", {"configuration": name}) schema_fields = [field.get("name") for field in s.get("fields", [])] if schema_fields != fields: error("schema.fields", {"configuration": name}) key = m.get("primary_key") or [] if not key or any(column not in fields for column in key): error("manifest.primary_key", {"configuration": name, "key": key}) else: values = [tuple(row[column] for column in key) for row in rows] if any(any(value == "" for value in item) for item in values): error("data.null_primary_key", {"configuration": name, "key": key}) if len(values) != len(set(values)): error("data.duplicate_primary_key", {"configuration": name, "key": key}) for field in s.get("fields", []): row = dictionary.get((name, field.get("name"))) if not row: error( "dictionary.missing_field", {"configuration": name, "field": field.get("name")}, ) elif field.get("type") != row.get("type"): error( "schema.type", { "configuration": name, "field": field.get("name"), "schema": field.get("type"), "dictionary": row.get("type"), }, ) if row: field_name = field.get("name") declared_type = row.get("type") for index, record in enumerate(rows, start=2): value = record[field_name] if value == "": continue try: if declared_type == "int64": int(value) elif declared_type == "float64": float(value) elif declared_type == "bool" and value.lower() not in { "true", "false", }: raise ValueError("expected true or false") except ValueError: error( "data.type_parse", { "configuration": name, "field": field_name, "row": index, "type": declared_type, "value": value, }, ) break loaded.append( { "configuration": name, "path": rel, "rows": len(rows), "columns": len(fields), "primary_key": key, } ) context = croissant.get("@context") or {} if context.get("cr") != "http://mlcommons.org/croissant/": error("croissant.context", "missing Croissant namespace") if context.get("rai") != "http://mlcommons.org/croissant/RAI/": error("croissant.context", "missing RAI namespace") if croissant.get("conformsTo") != "http://mlcommons.org/croissant/1.1": error("croissant.version", croissant.get("conformsTo")) for field in RAI_FIELDS: if field not in croissant or croissant[field] in ("", None, [], {}): error("croissant.rai", field) if croissant.get("license") != LICENSE_URL: error("croissant.license", {"expected": LICENSE_URL, "actual": croissant.get("license")}) if not isinstance(croissant.get("rai:hasSyntheticData"), bool): error("croissant.synthetic_boolean", croissant.get("rai:hasSyntheticData")) for field in RAI_FIELDS: if field in {"rai:hasSyntheticData", "prov:wasDerivedFrom", "prov:wasGeneratedBy"}: continue if len(str(croissant.get(field, "")).strip()) < 80: error("croissant.rai_substantive", field) if not croissant.get("creator"): error("croissant.creator", "dataset creators are required") if croissant.get("isAccessibleForFree") is not True: error("croissant.free_access", croissant.get("isAccessibleForFree")) distributions = { item.get("name"): item for item in croissant.get("distribution", []) } record_sets = {item.get("name"): item for item in croissant.get("recordSet", [])} if set(distributions) != set(names): error("croissant.distribution_set", sorted(set(distributions) ^ set(names))) if set(record_sets) != set(names): error("croissant.record_set", sorted(set(record_sets) ^ set(names))) for name in names: m = manifest_by.get(name, {}) distribution = distributions.get(name, {}) record_set = record_sets.get(name, {}) if distribution.get("contentUrl") != m.get("path"): error("croissant.content_url", {"configuration": name}) if distribution.get("sha256") != m.get("sha256"): error("croissant.sha256", {"configuration": name}) if distribution.get("contentSize") != str(m.get("bytes")): error("croissant.content_size", {"configuration": name}) cr_fields = record_set.get("field") or [] if [item.get("name") for item in cr_fields] != m.get("fields"): error("croissant.fields", {"configuration": name}) for field in cr_fields: expected = TYPE_MAP.get( dictionary.get((name, field.get("name")), {}).get("type") ) if field.get("dataType") != expected: error( "croissant.data_type", { "configuration": name, "field": field.get("name"), "expected": expected, "actual": field.get("dataType"), }, ) checksum_path = root / "metadata/checksums.sha256" checksums = {} for line in checksum_path.read_text(encoding="utf-8").splitlines(): if not line.strip(): continue match = re.fullmatch(r"([0-9a-f]{64}) (.+)", line) if not match: error("checksums.format", line) continue checksums[match.group(2)] = match.group(1) payload = [ path for path in root.rglob("*") if path.is_file() and "__pycache__" not in path.parts and ".git" not in path.parts and path.relative_to(root).as_posix() not in { "audit_tmp.py", "metadata/checksums.sha256", "metadata/validation_run.json", } ] for path in payload: rel = path.relative_to(root).as_posix() expected = checksums.get(rel) if expected is None: error("checksums.untracked", rel) elif not args.skip_byte_checksums and sha256(path) != expected: error("checksums.mismatch", rel) stale = sorted(set(checksums) - {p.relative_to(root).as_posix() for p in payload}) if stale: error("checksums.stale", stale) if args.skip_byte_checksums: warnings.append( { "code": "checksums.byte_verification_skipped", "detail": "coverage and format checked; hash bytes must be verified on the committed Git tree", } ) ledger = json.loads((root / "metadata/claim_status.json").read_text()) for claim in ledger.get("claims", []): for rel in claim.get("supporting_artifacts", []): if not (root / rel).is_file(): error( "claim.missing_support", {"claim_id": claim.get("claim_id"), "path": rel}, ) with (root / "metadata/claim_ledger.csv").open( newline="", encoding="utf-8-sig" ) as handle: for claim in csv.DictReader(handle): for rel in claim["supporting_artifacts"].split(";"): if rel and not (root / rel).is_file(): error( "claim.missing_support", {"claim_id": claim["claim_id"], "path": rel}, ) text_suffixes = {".md", ".json", ".csv", ".yml", ".yaml", ".txt", ".cff"} for path in root.rglob("*"): if not path.is_file() or path.suffix.lower() not in text_suffixes: continue if "__pycache__" in path.parts or path.name == "checksums.sha256": continue content = path.read_text(encoding="utf-8", errors="ignore") match = NONPUBLIC_REPOSITORY_URL.search(content) if match: error( "public_boundary.nonpublic_repository_url", {"path": path.relative_to(root).as_posix(), "url": match.group(0)}, ) blocker("release.hub_publication", "dataset is not published") blocker( "release.platform_validation", "Dataset Viewer, platform Croissant merge, and official validation not run", ) report = { "verdict": "READY_FOR_HF_STAGING" if not errors else "NOT_READY", "publication_status": "NOT_YET_PUBLISHED" if blockers else "PUBLISHED", "structural_status": "PASS" if not errors else "FAIL", "errors": errors, "blockers": blockers, "warnings": warnings, "configuration_count": len(configs), "loaded": loaded, } rendered = json.dumps(report, indent=2, sort_keys=True) + "\n" if args.json_out: Path(args.json_out).write_text(rendered, encoding="utf-8") print(rendered, end="") if errors or (args.release_gate and blockers): return 1 return 0 if __name__ == "__main__": raise SystemExit(main())