chemistry-knowledge / verify.py
janwein's picture
Release ChemBricks curated knowledge 2026-09-17.1
7943e63 verified
Raw History Blame Contribute Delete
10.1 kB
"""Verify or seal the distributable dataset without contacting any service."""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
import re
import sys
sys.dont_write_bytecode = True
ROOT = Path(__file__).resolve().parent
TOP_FILES = {"README.md", "LICENSE", "CURATION.md", "DATA_DICTIONARY.md", "UPLOAD.md",
"CITATION.cff", "build_dataset.py", "write_card.py", "verify.py", "upload.py",
"test_release.py", "verification.json", ".gitignore"}
PUBLIC_DIRS = {"data", "assets", "schemas", "provenance", "examples"}
SECRET = re.compile(r"\b(?:github_pat_[A-Za-z0-9_]{30,}|gh[pousr]_[A-Za-z0-9]{30,}|hf_[A-Za-z0-9]{25,}|sk-(?:ant-|proj-)?[A-Za-z0-9_-]{24,})\b|-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----")
PRIVATE = re.compile(r"/home/[A-Za-z0-9_.-]+/|https?://[^\s\"<>]*\.ts\.net\b")
def digest(raw):
return hashlib.sha256(raw).hexdigest()
def canonical(value):
return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode()
def read_rows(path):
with path.open(encoding="utf-8") as stream:
return [json.loads(line) for line in stream if line.strip()]
def pointer(value, path):
if path in ("", "$"):
return value
parts = path[1:].split("/") if path.startswith("/") else path.removeprefix("$.").split(".")
for part in parts:
if isinstance(value, str):
value = json.loads(value)
part = part.replace("~1", "/").replace("~0", "~")
value = value[int(part)] if isinstance(value, list) else value[part]
return value
def references(value):
if isinstance(value, dict):
if isinstance(value.get("request_id"), str) and isinstance(value.get("path"), str):
yield value
for child in value.values():
yield from references(child)
elif isinstance(value, list):
for child in value:
yield from references(child)
def verify_evidence(row):
public = json.loads(row["public_row_json"])
assert digest(canonical({k:v for k,v in public.items() if k != "sha256"})) == row["row_sha256"] == public["sha256"], "Public tool-row hash mismatch"
assert public["args"] == json.loads(row["args_json"]), "Arguments differ"
assert public["response"] == json.loads(row["response_json"]), "Response differs"
for key, other in [("request_id","request_id"),("tool","tool"),("status","status"),("line","source_line"),("ts","timestamp"),("duration_ms","duration_ms")]:
assert public[key] == row[other], "Evidence projection differs: " + key
assert re.fullmatch("[0-9a-f]{64}", row["source_row_sha256"]), "Invalid source row hash"
request = public.get("request", {})
assert not any(k in request or k in request.get("params", {}) for k in ("_meta", "meta", "metadata")), "Client metadata was retained"
assert not SECRET.search(row["public_row_json"]) and not PRIVATE.search(row["public_row_json"]), "Private evidence content"
return public
def manifest_files(root):
files = []
for path in sorted(root.rglob("*")):
relative = path.relative_to(root)
if not path.is_file() or path.is_symlink():
continue
if (len(relative.parts) == 1 and relative.name in TOP_FILES) or relative.parts[0] in PUBLIC_DIRS:
if "__pycache__" not in relative.parts and path.suffix != ".pyc":
files.append(path)
return files
def seal(root=ROOT):
root = Path(root).resolve()
assert root == ROOT or root.is_relative_to(ROOT), "Seal output must remain inside huggingface/"
manifest = json.loads((root / "manifest.json").read_text())
manifest["files"] = {str(p.relative_to(root)): {"sha256":digest(p.read_bytes()), "bytes":p.stat().st_size} for p in manifest_files(root)}
(root / "manifest.json").write_text(json.dumps(manifest, ensure_ascii=True, allow_nan=False, indent=2) + "\n")
names = [*manifest["files"], "manifest.json"]
(root / "SHA256SUMS").write_text("".join(digest((root/name).read_bytes()) + " " + name + "\n" for name in sorted(names)))
return manifest
def verify(root=ROOT):
from jsonschema import Draft202012Validator
root = Path(root).resolve()
manifest = json.loads((root / "manifest.json").read_text())
assert manifest["license"] == "mit" and manifest["created_by"] == "ChemBricks"
for name, item in manifest["files"].items():
path = (root / name).resolve()
assert path.is_relative_to(root) and not (root / name).is_symlink()
assert digest(path.read_bytes()) == item["sha256"] and path.stat().st_size == item["bytes"], "File differs: " + name
sums = {}
for line in (root / "SHA256SUMS").read_text().splitlines():
expected, name = line.split(" ", 1)
assert name in manifest["files"] or name == "manifest.json", "Unexpected checksum path"
assert name not in sums, "Duplicate checksum path"
assert digest((root/name).read_bytes()) == expected, "Checksum differs: " + name
sums[name] = expected
assert set(sums) == set(manifest["files"]) | {"manifest.json"}
data = {}
for name in ("records", "claims", "evidence"):
schema = json.loads((root / "schemas" / (name + ".schema.json")).read_text())
validator = Draft202012Validator(schema)
data[name] = read_rows(root / "data" / (name + ".jsonl"))
for row in data[name]:
validator.validate(row)
serialized = json.dumps(row)
assert not SECRET.search(serialized) and not PRIVATE.search(serialized), "Private material in " + name
expected = manifest["evidence_rows" if name == "evidence" else name]
assert len(data[name]) == expected, "Count differs: " + name
by_call = {}
for row in data["evidence"]:
key = row["source_capture_id"], row["request_id"]
assert key not in by_call, "Duplicate evidence join key"
by_call[key] = verify_evidence(row)
provenance = {row["record_id"]: row for row in read_rows(root / "provenance/records.jsonl")}
ledger_raw = (root / "provenance/source-ledger.jsonl").read_bytes()
assert digest(ledger_raw) == manifest["source_ledger_sha256"]
chain = read_rows(root / "provenance/source-ledger.jsonl")
previous, ledger = "0" * 64, {}
for i, row in enumerate(chain, 1):
assert row["prev"] == previous and row["record_id"] not in ledger
assert digest((row["record_sha256"] + row["tools_sha256"] + row["trace_sha256"] + previous).encode()) == row["entry"]
previous = row["entry"]
ledger[row["record_id"]] = (i,row)
assert previous == manifest["source_ledger_head"] and len(chain) == manifest["source_ledger_entries"]
for rid, source in provenance.items():
assert (source["ledger_line"],source["ledger"]) == ledger[rid]
assert source["release_license"] == "mit"
claim_index = {}
for row in data["claims"]:
key = row["record_id"], row["claim_id"]
assert key not in claim_index and row["id"] == ":".join(key)
claim = json.loads(row["claim_json"])
confidence = json.loads(row["source_confidence_json"])
assert claim["verdict"] == row["verdict"] == "passed"
assert confidence["context_eligible"] and not confidence["issues"] and confidence["prediction_timing"] != "fail"
assert all(s["verdict"] == "passed" and not s["quarantined"] for s in confidence["sources"])
assert row["statement"] == claim["statement"] and row["value_json"] == json.dumps(claim.get("value"),sort_keys=True,separators=(",",":"))
assert row["license"] == "mit" and row["creator"] == "ChemBricks"
assert row["source_capture_id"] == provenance[row["record_id"]]["ledger"]["tools_sha256"]
for ref in references([claim, confidence]):
source = by_call[(row["source_capture_id"], ref["request_id"])]
pointer(source["response"], ref["path"])
claim_index[key] = row
seen = set()
for row in data["records"]:
rid = row["record_id"]
assert rid not in seen
seen.add(rid)
source = provenance[rid]
assert source["full_record_eligible"] and source["ledger"]["record_sha256"] == row["source_record_sha256"]
assert digest(row["trace_markdown"].encode()) == source["ledger"]["trace_sha256"] == row["source_trace_sha256"]
assert row["source_capture_id"] == source["ledger"]["tools_sha256"]
assert row["license"] == "mit" and row["creator"] == "ChemBricks"
claims = json.loads(row["claims_json"])
assert len(claims) == row["claims_count"]
assert json.loads(row["validation_gates_json"])["G6"] == "pass"
for claim in claims:
exported = claim_index[(rid,claim["id"])]
assert exported["full_record_eligible"] and json.loads(exported["claim_json"]) == claim
confidence = json.loads(row["source_confidence_json"])
assert all(item["context_eligible"] for item in confidence.values())
assert all(row["full_record_eligible"] == (row["record_id"] in seen) for row in data["claims"])
card = (root / "README.md").read_text()
metadata = json.loads(card.split("---",2)[1])
assert metadata["license"] == "mit" and metadata["language"] == ["en"]
assert {c["config_name"] for c in metadata["configs"]} == set(data)
for config in metadata["configs"]:
assert config["data_files"] == [{"split":"corpus","path":"data/" + config["config_name"] + ".jsonl"}]
assert "assets/knowledge-path.svg" in card and "https://chembricks.ai" in card and "https://cmbx.ai" in card
assert "MIT License" in (root / "LICENSE").read_text()
print(json.dumps({"status":"pass","records":len(data["records"]),"claims":len(data["claims"]),"evidence_rows":len(data["evidence"]),"files":len(manifest["files"])}))
return manifest
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--seal", action="store_true")
args = parser.parse_args()
if args.seal:
seal()
verify()