"""Validate local release contracts. No network calls or remote mutations. Requires requirements-validation.txt. Reports checks to stdout; changes no files. """ from __future__ import annotations import csv import hashlib import json import math from pathlib import Path import re import sys import jsonschema import yaml from huggingface_hub import DatasetCard ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "publisher")) from publish import verify_local def digest(path): return hashlib.sha256(path.read_bytes()).hexdigest() def main(): checks = [] release, expected = verify_local(ROOT) checks.append("Checksum allowlist, required files, safe paths and token-pattern scan") for file in ROOT.rglob("*.json"): if ".venv" not in str(file): json.loads(file.read_text(encoding="utf-8")) checks.append("JSON artifacts parse") baseline = json.loads((ROOT/"validation/SCIENTIFIC_BASELINE_SHA256.json").read_text()) for relative, expected_sha in baseline["files"].items(): assert digest(ROOT/relative) == expected_sha, relative checks.append(f"{len(baseline['files'])} original scientific files preserved byte for byte") for change in baseline.get("formatting_only_changes", []): content = (ROOT/change["path"]).read_text(encoding="utf-8") assert content.count(change["replacement"]) == 1 original = content.replace(change["replacement"], change["original"]) assert hashlib.sha256(original.encode()).hexdigest() == change["original_sha256"] checks.append("Supplement differs only by its recorded inline-math formatting correction") export = json.loads((ROOT/"data/export_manifest.json").read_text()) rows_by_config = {} for name, record in export["configs"].items(): file = ROOT/record["path"] assert digest(file) == record["sha256"], name rows = [json.loads(line) for line in file.read_text(encoding="utf-8").splitlines()] assert len(rows) == record["rows"], name schema = json.loads((ROOT/"schemas"/(name+".schema.json")).read_text()) jsonschema.Draft202012Validator.check_schema(schema) validator = jsonschema.Draft202012Validator(schema) for row in rows: validator.validate(row) if "source_sha256" in row: assert digest(ROOT/row["source_path"]) == row["source_sha256"], row rows_by_config[name] = rows checks.append("Six JSONL configurations: counts, hashes, strict schemas and source provenance") readme = (ROOT/"README.md").read_text(encoding="utf-8") metadata = yaml.safe_load(readme.split("---", 2)[1]) DatasetCard(readme) # local SDK parser only; no .validate() network call configs = metadata["configs"] assert {c["config_name"] for c in configs} == set(rows_by_config) for config in configs: assert config["data_files"][0]["path"] == export["configs"][config["config_name"]]["path"] assert sum(bool(c.get("default")) for c in configs) == 1 assert metadata["license"] == "cc-by-4.0" checks.append("Hub dataset card parses; six explicit configs and one default map to real files") for document in {row["source_path"] for row in rows_by_config["research_sections"]}: chunks = [r for r in rows_by_config["research_sections"] if r["source_path"] == document] source = (ROOT/document).read_text(encoding="utf-8") assert "".join(row["text"] for row in chunks) == source lines = source.splitlines(keepends=True) for row in chunks: assert row["text"] == "".join(lines[row["source_line_start"]-1:row["source_line_end"]]) assert hashlib.sha256(row["text"].encode()).hexdigest() == row["text_sha256"] checks.append("All three scientific text sources reconstructed exactly from retrieval chunks") raw_csv = {} for row in rows_by_config["kinetic_runs"]: name = row["source_path"] if name not in raw_csv: with (ROOT/name).open(newline="") as stream: raw_csv[name] = list(csv.DictReader(stream)) source = raw_csv[name][row["source_row"]-2] for key, value in source.items(): if key == "mode": assert row[key] == value else: assert float(row[key]) == float(value) fractions = [row[key] for key in ("correct_fraction", "wrong_fraction", "missing_fraction")] assert all(-1e-12 <= value <= 1+1e-12 for value in fractions) assert abs(sum(fractions)-1) < 1e-10 assert all(math.isfinite(value) for value in row.values() if isinstance(value, (float, int))) checks.append("775 kinetic records agree field by field with raw CSV and retain normalized outcomes") code = [row["symbols"] for row in rows_by_config["interface_codebook"]] assert len(code) == 128 assert min(sum(a != b for a,b in zip(x,y)) for i,x in enumerate(code) for y in code[i+1:]) == 3 with (ROOT/"results/example_codebook.csv").open() as stream: assert code == [list(map(int,row)) for row in csv.reader(stream)] checks.append("All 128 headerless source codewords retained; minimum Hamming distance is three") for row in rows_by_config["claims"]: assert (ROOT/row["evidence_path"]).is_file(), row["id"] checks.append("Twelve claim records resolve to evidence files") cff = yaml.safe_load((ROOT/"CITATION.cff").read_text()) assert cff["cff-version"] == "1.2.0" and cff["type"] == "dataset" assert cff["authors"][0]["name"] == release["author"] assert cff["version"] == release["release_version"] == "1.0.1" assert cff["url"] == release["repository_url"] checks.append("Citation identity, version and canonical destination are consistent") # File links only. Remote accessibility and renderer-specific anchor slugs # are intentionally not asserted by this offline check. checked_links = 0 for file in ROOT.rglob("*.md"): content = file.read_text(encoding="utf-8") content = re.sub(r"\$\$.*?\$\$", "", content, flags=re.S) content = re.sub(r"\$[^\n$]+\$", "", content) for target in re.findall(r"\[[^\]\n]+\]\(([^)]+)\)", content): if re.match(r"[a-zA-Z][a-zA-Z0-9+.-]*:", target) or target.startswith("#"): continue relative = target.split("#",1)[0] if relative: assert (file.parent/relative).exists(), (str(file.relative_to(ROOT)), target) checked_links += 1 checks.append(f"{checked_links} local Markdown file links resolve") bat = (ROOT/"PUBLISH_TO_HUGGINGFACE.bat").read_bytes() assert b"--publish --open" in bat and b"DisableDelayedExpansion" in bat assert b"\r\n" in bat and b"\n" not in bat.replace(b"\r\n",b"") checks.append("Windows launcher has CRLF lines and fixed publisher target") print(json.dumps({"status":"passed", "checks": checks, "data_records":sum(len(rows) for rows in rows_by_config.values()), "checksum_listed_files_including_manifest":len(expected), "not_validated_here":["actual authenticated Hub upload", "Windows execution", "Hub Dataset Viewer ingestion", "physical science premises"]}, indent=2)) if __name__ == "__main__": main()