File size: 19,553 Bytes
e5277d2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 | #!/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())
|