From 2a37b67853396820e447275258f6b8727a83743d Mon Sep 17 00:00:00 2001 From: rushil23shah-hue Date: Tue, 3 Nov 2026 09:59:40 +0530 Subject: [PATCH 1/5] feat(simple): add per-article membership proof tool and tests --- simple/proof.py | 219 +++++++++++++++++++++++++++++++++++++ tests/simple/test_proof.py | 186 +++++++++++++++++++++++++++++++ 2 files changed, 405 insertions(+) create mode 100644 simple/proof.py create mode 100644 tests/simple/test_proof.py diff --git a/simple/proof.py b/simple/proof.py new file mode 100644 index 00000000..72439dfd --- /dev/null +++ b/simple/proof.py @@ -0,0 +1,219 @@ +"""Per-article membership proofs against OpenVerifiableLLM chain.jsonl. + +Given a Wikipedia article (by title or page ID), proves which training segment +trained on it, or proves that an exclusion fork never saw it, tied to the +cryptographic chain commitments. + +Usage: + python scratch/membership_proof.py --data PREP --run RUN --article "Albert Einstein" + python scratch/membership_proof.py --data PREP --run RUN --article 736 +""" + +import argparse +import hashlib +import json +import sys +from pathlib import Path + + +def read_chain(run_dir): + path = Path(run_dir) / "chain.jsonl" + if not path.is_file(): + sys.exit(f"{path} not found") + chain = [] + for n, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): + line = line.strip() + if not line: + continue + try: + chain.append(json.loads(line)) + except json.JSONDecodeError as err: + sys.exit( + f"{path}: line {n} is not valid JSON ({err.msg}); the file is cut off or damaged" + ) + if not chain: + sys.exit(f"{path} has no chain entries") + # Verify sha256 chain links + for i in range(1, len(chain)): + want = hashlib.sha256( + json.dumps(chain[i - 1], sort_keys=True).encode() + ).hexdigest() + if chain[i].get("previous") != want: + sys.exit(f"chain link broken at entry {i}") + return chain + + +def find_article(data_dir, query): + if not query or not query.strip(): + return None + query = query.strip() + path = Path(data_dir) / "wikipedia" / "documents.jsonl" + if not path.is_file(): + sys.exit(f"{path} not found") + is_id = query.isdigit() + query_lower = query.lower() + with path.open("rb") as f: + for line in f: + line = line.strip() + if not line: + continue + try: + d = json.loads(line) + except json.JSONDecodeError: + continue + # identity format: [page_id, title] + page_id, title = str(d["identity"][0]), str(d["identity"][1]) + if is_id and page_id == query: + return d + if title.lower() == query_lower: + return d + return None + + +def verify_data_commitment(data_dir, chain_entry_0): + """Check that stream.json matches genesis commitment in chain.jsonl entry 0.""" + stream_path = Path(data_dir) / "wikipedia" / "stream.json" + if not stream_path.is_file(): + return False, "stream.json not found" + stream_bytes = stream_path.read_bytes() + stream_hash = hashlib.sha256(stream_bytes).hexdigest() + expected = chain_entry_0.get("data", {}).get("wikipedia") + if expected and stream_hash != expected: + return ( + False, + f"stream.json hash {stream_hash} differs from chain genesis {expected}", + ) + + # Verify documents.jsonl matches the hash listed in stream.json + try: + stream_meta = json.loads(stream_bytes.decode("utf-8")) + doc_files = [ + f + for f in stream_meta.get("files", []) + if f.get("path") == "documents.jsonl" or f.get("name") == "documents.jsonl" + ] + if doc_files: + expected_doc_hash = doc_files[0]["sha256"] + actual_doc_hash = hashlib.sha256( + (Path(data_dir) / "wikipedia" / "documents.jsonl").read_bytes() + ).hexdigest() + if actual_doc_hash != expected_doc_hash: + return ( + False, + f"documents.jsonl hash {actual_doc_hash} differs from stream.json {expected_doc_hash}", + ) + except Exception as e: + return False, f"failed checking stream.json file table: {e}" + + return True, stream_hash + + +def build_membership_proof(doc, chain, data_bound, data_hash): + target_start = doc["target_start"] + target_count = doc["targets"] + target_end = target_start + target_count + page_id, title = doc["identity"][0], doc["identity"][1] + + # Find the Wikipedia phase boundaries + segments = [] + is_excluded = False + exclusion_detail = None + + for k in range(len(chain) - 1): + c_k = chain[k].get("control", {}) + c_next = chain[k + 1].get("control", {}) + + if c_k.get("phase") != "wikipedia": + continue + + cur_start = c_k.get("cursor", 0) + cur_end = c_next.get("cursor", cur_start) + + # Check if the fork explicitly excluded this article range + exclude_ranges = c_k.get("exclude", {}).get("wikipedia", []) + for ex_start, ex_len in exclude_ranges: + if ex_start == target_start and ex_len == target_count: + is_excluded = True + exclusion_detail = { + "at_boundary": k, + "excluded_range": [ex_start, ex_start + ex_len], + "fork_entry_state": chain[k].get("state"), + } + + # Check interval overlap + overlap_start = max(target_start, cur_start) + overlap_end = min(target_end, cur_end) + if overlap_start < overlap_end: + segments.append( + { + "segment": k, + "boundary_start": k, + "boundary_end": k + 1, + "cursor_interval": [cur_start, cur_end], + "article_overlap_targets": [overlap_start, overlap_end], + "boundary_start_state": chain[k].get("state"), + "boundary_end_state": chain[k + 1].get("state"), + "verify_cmd": f"python simple/ovl.py verify --data PREP --run RUN --segment {k}", + } + ) + + status = "excluded" if is_excluded else ("trained" if segments else "unreached") + + proof = { + "article": { + "title": title, + "page_id": page_id, + "targets": { + "start": target_start, + "end": target_end, + "count": target_count, + }, + "tokens": doc.get("tokens"), + }, + "membership_status": status, + "data_provenance": { + "bound_to_chain": data_bound, + "stream_genesis_hash": data_hash, + }, + "segments": [s["segment"] for s in segments], + "segment_details": segments, + } + + if is_excluded: + proof["exclusion_proof"] = exclusion_detail + + return proof + + +def main(): + p = argparse.ArgumentParser( + description="Prove Wikipedia article membership in OpenVerifiableLLM training" + ) + p.add_argument( + "--data", + required=True, + help="Prepared data directory (containing wikipedia/documents.jsonl)", + ) + p.add_argument( + "--run", required=True, help="Run directory (containing chain.jsonl)" + ) + p.add_argument( + "--article", required=True, help="Article title or Wikipedia page_id" + ) + a = p.parse_args() + + chain = read_chain(a.run) + doc = find_article(a.data, a.article) + if not doc: + sys.exit( + f"Article '{a.article}' not found in {Path(a.data) / 'wikipedia' / 'documents.jsonl'}" + ) + + bound, data_hash = verify_data_commitment(a.data, chain[0]) + proof = build_membership_proof(doc, chain, bound, data_hash) + + print(json.dumps(proof, indent=2, ensure_ascii=False)) + + +if __name__ == "__main__": + main() diff --git a/tests/simple/test_proof.py b/tests/simple/test_proof.py new file mode 100644 index 00000000..070a01ed --- /dev/null +++ b/tests/simple/test_proof.py @@ -0,0 +1,186 @@ +"""Unit tests for simple/proof.py. + +Verifies article lookup, segment intersection, fork exclusion proofs, +and cryptographic data binding against synthetic test fixtures. +""" + +import hashlib +import json +import shutil +import sys +import tempfile +import unittest +from pathlib import Path + +# Add repo root to path +ROOT = Path(__file__).resolve().parent.parent.parent +sys.path.insert(0, str(ROOT / "simple")) +import proof as mp # noqa: E402 + + +class TestMembershipProof(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.mkdtemp() + self.root = Path(self.tmp) + self.data_dir = self.root / "data" + self.run_dir = self.root / "run" + self.wiki_dir = self.data_dir / "wikipedia" + self.wiki_dir.mkdir(parents=True) + self.run_dir.mkdir(parents=True) + + self.docs = [ + { + "identity": [736, "Albert Einstein"], + "target_start": 0, + "targets": 1000, + "tokens": 1200, + "offset": 0, + }, + { + "identity": [1042, "Quantum mechanics"], + "target_start": 1000, + "targets": 1500, + "tokens": 1700, + "offset": 1200, + }, + { + "identity": [9999, "3I/ATLAS"], + "target_start": 2500, + "targets": 500, + "tokens": 600, + "offset": 2900, + }, + ] + doc_lines = [json.dumps(d) for d in self.docs] + doc_content = "\n".join(doc_lines) + "\n" + doc_path = self.wiki_dir / "documents.jsonl" + doc_path.write_text(doc_content, encoding="utf-8") + doc_hash = hashlib.sha256(doc_path.read_bytes()).hexdigest() + + stream_data = { + "phase": "wikipedia", + "targets": 3000, + "files": [{"path": "documents.jsonl", "sha256": doc_hash}], + } + stream_bytes = json.dumps(stream_data).encode("utf-8") + (self.wiki_dir / "stream.json").write_bytes(stream_bytes) + self.stream_hash = hashlib.sha256(stream_bytes).hexdigest() + + self.chain = [ + { + "index": 0, + "kind": "initial", + "control": {"phase": "wikipedia", "cursor": 0}, + "data": {"wikipedia": self.stream_hash}, + "state": "state_hash_0", + "previous": None, + }, + { + "index": 1, + "kind": "progress", + "control": {"phase": "wikipedia", "cursor": 2000}, + "state": "state_hash_1", + "previous": None, + }, + { + "index": 2, + "kind": "base", + "control": {"phase": "wikipedia", "cursor": 3000}, + "state": "state_hash_2", + "previous": None, + }, + ] + for i in range(1, len(self.chain)): + self.chain[i]["previous"] = hashlib.sha256( + json.dumps(self.chain[i - 1], sort_keys=True).encode() + ).hexdigest() + + (self.run_dir / "chain.jsonl").write_text( + "\n".join(json.dumps(e, sort_keys=True) for e in self.chain) + "\n", + encoding="utf-8", + ) + + def tearDown(self): + shutil.rmtree(self.tmp) + + def test_find_article_by_title_and_case(self): + doc = mp.find_article(self.data_dir, "Albert Einstein") + self.assertIsNotNone(doc) + self.assertEqual(doc["identity"][0], 736) + + doc_lower = mp.find_article(self.data_dir, "albert einstein") + self.assertIsNotNone(doc_lower) + self.assertEqual(doc_lower["identity"][1], "Albert Einstein") + + def test_find_article_by_page_id(self): + doc = mp.find_article(self.data_dir, "736") + self.assertIsNotNone(doc) + self.assertEqual(doc["identity"][1], "Albert Einstein") + + def test_find_article_not_found(self): + doc = mp.find_article(self.data_dir, "Nonexistent Article") + self.assertIsNone(doc) + + def test_verify_data_commitment(self): + bound, stream_hash = mp.verify_data_commitment( + self.data_dir, self.chain[0] + ) + self.assertTrue(bound) + self.assertEqual(stream_hash, self.stream_hash) + + def test_membership_single_segment(self): + doc = mp.find_article(self.data_dir, "Albert Einstein") + proof = mp.build_membership_proof( + doc, self.chain, True, self.stream_hash + ) + + self.assertEqual(proof["membership_status"], "trained") + self.assertEqual(proof["segments"], [0]) + self.assertEqual(proof["article"]["targets"]["start"], 0) + self.assertEqual(proof["article"]["targets"]["count"], 1000) + self.assertEqual( + proof["segment_details"][0]["boundary_start_state"], "state_hash_0" + ) + self.assertEqual( + proof["segment_details"][0]["boundary_end_state"], "state_hash_1" + ) + + def test_membership_spanning_two_segments(self): + doc = mp.find_article(self.data_dir, "Quantum mechanics") + proof = mp.build_membership_proof( + doc, self.chain, True, self.stream_hash + ) + + self.assertEqual(proof["membership_status"], "trained") + self.assertEqual(proof["segments"], [0, 1]) + self.assertEqual( + proof["segment_details"][0]["article_overlap_targets"], [1000, 2000] + ) + self.assertEqual( + proof["segment_details"][1]["article_overlap_targets"], [2000, 2500] + ) + + def test_membership_fork_exclusion(self): + fork_chain = list(self.chain) + fork_chain[1] = dict(fork_chain[1]) + fork_chain[1]["control"] = { + "phase": "wikipedia", + "cursor": 2000, + "exclude": {"wikipedia": [[2500, 500]]}, + } + + doc = mp.find_article(self.data_dir, "3I/ATLAS") + proof = mp.build_membership_proof( + doc, fork_chain, True, self.stream_hash + ) + + self.assertEqual(proof["membership_status"], "excluded") + self.assertIn("exclusion_proof", proof) + self.assertEqual(proof["exclusion_proof"]["at_boundary"], 1) + self.assertEqual( + proof["exclusion_proof"]["excluded_range"], [2500, 3000] + ) + + +if __name__ == "__main__": + unittest.main() From b21ef6e7ae2449ec568ef80e985951c387544046 Mon Sep 17 00:00:00 2001 From: rushil23shah-hue Date: Wed, 4 Nov 2026 13:22:20 +0530 Subject: [PATCH 2/5] fix(simple): address review feedback on per-article membership proofs --- simple/proof.py | 62 ++++++++++------- tests/simple/test_proof.py | 136 ++++++++++++++++++++++++------------- 2 files changed, 126 insertions(+), 72 deletions(-) diff --git a/simple/proof.py b/simple/proof.py index 72439dfd..e1db2963 100644 --- a/simple/proof.py +++ b/simple/proof.py @@ -5,8 +5,8 @@ cryptographic chain commitments. Usage: - python scratch/membership_proof.py --data PREP --run RUN --article "Albert Einstein" - python scratch/membership_proof.py --data PREP --run RUN --article 736 + python simple/proof.py --data PREP --run RUN --article "Albert Einstein" + python simple/proof.py --data PREP --run RUN --article 736 """ import argparse @@ -72,13 +72,17 @@ def find_article(data_dir, query): def verify_data_commitment(data_dir, chain_entry_0): """Check that stream.json matches genesis commitment in chain.jsonl entry 0.""" + if chain_entry_0.get("kind") != "initial": + return False, "chain genesis entry kind is not 'initial'" stream_path = Path(data_dir) / "wikipedia" / "stream.json" if not stream_path.is_file(): return False, "stream.json not found" stream_bytes = stream_path.read_bytes() stream_hash = hashlib.sha256(stream_bytes).hexdigest() expected = chain_entry_0.get("data", {}).get("wikipedia") - if expected and stream_hash != expected: + if not expected: + return False, "chain genesis entry has no wikipedia data commitment" + if stream_hash != expected: return ( False, f"stream.json hash {stream_hash} differs from chain genesis {expected}", @@ -92,16 +96,17 @@ def verify_data_commitment(data_dir, chain_entry_0): for f in stream_meta.get("files", []) if f.get("path") == "documents.jsonl" or f.get("name") == "documents.jsonl" ] - if doc_files: - expected_doc_hash = doc_files[0]["sha256"] - actual_doc_hash = hashlib.sha256( - (Path(data_dir) / "wikipedia" / "documents.jsonl").read_bytes() - ).hexdigest() - if actual_doc_hash != expected_doc_hash: - return ( - False, - f"documents.jsonl hash {actual_doc_hash} differs from stream.json {expected_doc_hash}", - ) + if not doc_files: + return False, "documents.jsonl not listed in stream.json files table" + expected_doc_hash = doc_files[0]["sha256"] + actual_doc_hash = hashlib.sha256( + (Path(data_dir) / "wikipedia" / "documents.jsonl").read_bytes() + ).hexdigest() + if actual_doc_hash != expected_doc_hash: + return ( + False, + f"documents.jsonl hash {actual_doc_hash} differs from stream.json {expected_doc_hash}", + ) except Exception as e: return False, f"failed checking stream.json file table: {e}" @@ -119,6 +124,20 @@ def build_membership_proof(doc, chain, data_bound, data_hash): is_excluded = False exclusion_detail = None + # Scan every entry for exclusions (including if the fork entry is the last entry) + for k, entry in enumerate(chain): + exclude_ranges = ( + entry.get("control", {}).get("exclude", {}).get("wikipedia", []) + ) + for ex_start, ex_len in exclude_ranges: + if ex_start == target_start and ex_len == target_count and not is_excluded: + is_excluded = True + exclusion_detail = { + "at_boundary": k, + "excluded_range": [ex_start, ex_start + ex_len], + "fork_entry_state": entry.get("state"), + } + for k in range(len(chain) - 1): c_k = chain[k].get("control", {}) c_next = chain[k + 1].get("control", {}) @@ -129,17 +148,6 @@ def build_membership_proof(doc, chain, data_bound, data_hash): cur_start = c_k.get("cursor", 0) cur_end = c_next.get("cursor", cur_start) - # Check if the fork explicitly excluded this article range - exclude_ranges = c_k.get("exclude", {}).get("wikipedia", []) - for ex_start, ex_len in exclude_ranges: - if ex_start == target_start and ex_len == target_count: - is_excluded = True - exclusion_detail = { - "at_boundary": k, - "excluded_range": [ex_start, ex_start + ex_len], - "fork_entry_state": chain[k].get("state"), - } - # Check interval overlap overlap_start = max(target_start, cur_start) overlap_end = min(target_end, cur_end) @@ -175,8 +183,8 @@ def build_membership_proof(doc, chain, data_bound, data_hash): "bound_to_chain": data_bound, "stream_genesis_hash": data_hash, }, - "segments": [s["segment"] for s in segments], - "segment_details": segments, + "segments": [] if is_excluded else [s["segment"] for s in segments], + "segment_details": [] if is_excluded else segments, } if is_excluded: @@ -210,6 +218,8 @@ def main(): ) bound, data_hash = verify_data_commitment(a.data, chain[0]) + if not bound: + sys.exit(f"data commitment check failed: {data_hash}") proof = build_membership_proof(doc, chain, bound, data_hash) print(json.dumps(proof, indent=2, ensure_ascii=False)) diff --git a/tests/simple/test_proof.py b/tests/simple/test_proof.py index 070a01ed..5ccd279d 100644 --- a/tests/simple/test_proof.py +++ b/tests/simple/test_proof.py @@ -122,64 +122,108 @@ def test_find_article_not_found(self): self.assertIsNone(doc) def test_verify_data_commitment(self): - bound, stream_hash = mp.verify_data_commitment( - self.data_dir, self.chain[0] - ) + bound, stream_hash = mp.verify_data_commitment(self.data_dir, self.chain[0]) self.assertTrue(bound) self.assertEqual(stream_hash, self.stream_hash) - def test_membership_single_segment(self): - doc = mp.find_article(self.data_dir, "Albert Einstein") - proof = mp.build_membership_proof( - doc, self.chain, True, self.stream_hash - ) - - self.assertEqual(proof["membership_status"], "trained") - self.assertEqual(proof["segments"], [0]) - self.assertEqual(proof["article"]["targets"]["start"], 0) - self.assertEqual(proof["article"]["targets"]["count"], 1000) - self.assertEqual( - proof["segment_details"][0]["boundary_start_state"], "state_hash_0" - ) - self.assertEqual( - proof["segment_details"][0]["boundary_end_state"], "state_hash_1" - ) - - def test_membership_spanning_two_segments(self): - doc = mp.find_article(self.data_dir, "Quantum mechanics") - proof = mp.build_membership_proof( - doc, self.chain, True, self.stream_hash + def test_verify_data_commitment_tampered_stream(self): + (self.wiki_dir / "stream.json").write_bytes(b'{"tampered": true}') + bound, msg = mp.verify_data_commitment(self.data_dir, self.chain[0]) + self.assertFalse(bound) + + def test_verify_data_commitment_tampered_documents(self): + with (self.wiki_dir / "documents.jsonl").open("a", encoding="utf-8") as f: + f.write("{}\n") + bound, msg = mp.verify_data_commitment(self.data_dir, self.chain[0]) + self.assertFalse(bound) + + def test_verify_data_commitment_missing_wikipedia_hash(self): + tampered_entry = dict(self.chain[0]) + tampered_entry["data"] = {} + bound, msg = mp.verify_data_commitment(self.data_dir, tampered_entry) + self.assertFalse(bound) + self.assertIn("no wikipedia data commitment", msg) + + def test_verify_data_commitment_not_initial_kind(self): + tampered_entry = dict(self.chain[0]) + tampered_entry["kind"] = "progress" + bound, msg = mp.verify_data_commitment(self.data_dir, tampered_entry) + self.assertFalse(bound) + self.assertIn("not 'initial'", msg) + + def test_read_chain_broken_link(self): + lines = (self.run_dir / "chain.jsonl").read_text(encoding="utf-8").splitlines() + entry = json.loads(lines[1]) + entry["previous"] = "0" * 64 + lines[1] = json.dumps(entry, sort_keys=True) + (self.run_dir / "chain.jsonl").write_text( + "\n".join(lines) + "\n", encoding="utf-8" ) + with self.assertRaises(SystemExit): + mp.read_chain(self.run_dir) - self.assertEqual(proof["membership_status"], "trained") - self.assertEqual(proof["segments"], [0, 1]) - self.assertEqual( - proof["segment_details"][0]["article_overlap_targets"], [1000, 2000] - ) - self.assertEqual( - proof["segment_details"][1]["article_overlap_targets"], [2000, 2500] - ) + def test_membership_fork_exclusion_fork_entry_last(self): + # Fork entry is the last entry in the chain + fork_chain = [ + self.chain[0], + { + "index": 1, + "kind": "fork", + "control": { + "phase": "wikipedia", + "cursor": 2000, + "exclude": {"wikipedia": [[2500, 500]]}, + }, + "state": "state_fork", + "previous": "prev_hash", + }, + ] + doc = mp.find_article(self.data_dir, "3I/ATLAS") + proof = mp.build_membership_proof(doc, fork_chain, True, self.stream_hash) - def test_membership_fork_exclusion(self): - fork_chain = list(self.chain) - fork_chain[1] = dict(fork_chain[1]) - fork_chain[1]["control"] = { - "phase": "wikipedia", - "cursor": 2000, - "exclude": {"wikipedia": [[2500, 500]]}, - } + self.assertEqual(proof["membership_status"], "excluded") + self.assertEqual(proof["segments"], []) + self.assertEqual(proof["segment_details"], []) + self.assertIn("exclusion_proof", proof) + self.assertEqual(proof["exclusion_proof"]["at_boundary"], 1) + def test_membership_fork_exclusion_continued_training(self): + # Fork was created at boundary 1, and subsequent entries retain exclude control + fork_chain = [ + self.chain[0], + { + "index": 1, + "kind": "fork", + "control": { + "phase": "wikipedia", + "cursor": 2000, + "exclude": {"wikipedia": [[2500, 500]]}, + }, + "state": "state_fork", + "previous": "prev_hash_1", + }, + { + "index": 2, + "kind": "progress", + "control": { + "phase": "wikipedia", + "cursor": 3000, + "exclude": {"wikipedia": [[2500, 500]]}, + }, + "state": "state_progress", + "previous": "prev_hash_2", + }, + ] doc = mp.find_article(self.data_dir, "3I/ATLAS") - proof = mp.build_membership_proof( - doc, fork_chain, True, self.stream_hash - ) + proof = mp.build_membership_proof(doc, fork_chain, True, self.stream_hash) self.assertEqual(proof["membership_status"], "excluded") + self.assertEqual(proof["segments"], []) + self.assertEqual(proof["segment_details"], []) self.assertIn("exclusion_proof", proof) + # Boundary should point to the initial fork entry (1), not the later progress entry (2) self.assertEqual(proof["exclusion_proof"]["at_boundary"], 1) - self.assertEqual( - proof["exclusion_proof"]["excluded_range"], [2500, 3000] - ) + self.assertEqual(proof["exclusion_proof"]["excluded_range"], [2500, 3000]) if __name__ == "__main__": From e63cae74a73ea7b19da4f653905747bd8c5250ba Mon Sep 17 00:00:00 2001 From: rushil23shah-hue Date: Fri, 6 Nov 2026 21:24:20 +0530 Subject: [PATCH 3/5] test(simple): add trained cross-segment and boundary touch membership tests --- tests/simple/test_proof.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/tests/simple/test_proof.py b/tests/simple/test_proof.py index 5ccd279d..637cd11f 100644 --- a/tests/simple/test_proof.py +++ b/tests/simple/test_proof.py @@ -225,6 +225,23 @@ def test_membership_fork_exclusion_continued_training(self): self.assertEqual(proof["exclusion_proof"]["at_boundary"], 1) self.assertEqual(proof["exclusion_proof"]["excluded_range"], [2500, 3000]) + def test_membership_trained_cross_segment(self): + doc = mp.find_article(self.data_dir, "Quantum mechanics") + proof = mp.build_membership_proof(doc, self.chain, True, self.stream_hash) + self.assertEqual(proof["membership_status"], "trained") + self.assertEqual(proof["segments"], [0, 1]) + self.assertEqual( + [s["article_overlap_targets"] for s in proof["segment_details"]], + [[1000, 2000], [2000, 2500]], + ) + self.assertNotIn("exclusion_proof", proof) + + def test_membership_unreached_boundary_touch(self): + doc = {"identity": [1, "Late"], "target_start": 3000, "targets": 10} + proof = mp.build_membership_proof(doc, self.chain, True, self.stream_hash) + self.assertEqual(proof["membership_status"], "unreached") + self.assertEqual(proof["segments"], []) + if __name__ == "__main__": unittest.main() From b1ae1022068799d414033de379da2416fd010bc2 Mon Sep 17 00:00:00 2001 From: rushil23shah-hue Date: Sat, 14 Nov 2026 17:25:28 +0530 Subject: [PATCH 4/5] fix(simple): align membership proof identity lookup and test fixtures with release schema - Look up articles strictly by Wikipedia page ID via d['identity'][1], matching cmd_fork in ovl.py - Import read_chain directly from ovl.py to avoid duplication - Update test fixtures in test_proof.py to match published Hugging Face documents.jsonl, stream.json file table, and release/simple-run/chain.jsonl cursors --- simple/proof.py | 68 ++++++-------- tests/simple/test_proof.py | 180 +++++++++++++++++++++++++++---------- 2 files changed, 157 insertions(+), 91 deletions(-) diff --git a/simple/proof.py b/simple/proof.py index e1db2963..d883f55d 100644 --- a/simple/proof.py +++ b/simple/proof.py @@ -1,12 +1,11 @@ """Per-article membership proofs against OpenVerifiableLLM chain.jsonl. -Given a Wikipedia article (by title or page ID), proves which training segment +Given a Wikipedia article page ID, proves which training segment trained on it, or proves that an exclusion fork never saw it, tied to the cryptographic chain commitments. Usage: - python simple/proof.py --data PREP --run RUN --article "Albert Einstein" - python simple/proof.py --data PREP --run RUN --article 736 + python simple/proof.py --data PREP --run RUN --article 12 """ import argparse @@ -15,43 +14,18 @@ import sys from pathlib import Path - -def read_chain(run_dir): - path = Path(run_dir) / "chain.jsonl" - if not path.is_file(): - sys.exit(f"{path} not found") - chain = [] - for n, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): - line = line.strip() - if not line: - continue - try: - chain.append(json.loads(line)) - except json.JSONDecodeError as err: - sys.exit( - f"{path}: line {n} is not valid JSON ({err.msg}); the file is cut off or damaged" - ) - if not chain: - sys.exit(f"{path} has no chain entries") - # Verify sha256 chain links - for i in range(1, len(chain)): - want = hashlib.sha256( - json.dumps(chain[i - 1], sort_keys=True).encode() - ).hexdigest() - if chain[i].get("previous") != want: - sys.exit(f"chain link broken at entry {i}") - return chain +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from ovl import read_chain -def find_article(data_dir, query): - if not query or not query.strip(): +def find_article(data_dir, article_id): + """Find article by Wikipedia page_id in documents.jsonl.""" + if not article_id or not str(article_id).strip(): return None - query = query.strip() + target_id = str(article_id).strip() path = Path(data_dir) / "wikipedia" / "documents.jsonl" if not path.is_file(): sys.exit(f"{path} not found") - is_id = query.isdigit() - query_lower = query.lower() with path.open("rb") as f: for line in f: line = line.strip() @@ -61,11 +35,13 @@ def find_article(data_dir, query): d = json.loads(line) except json.JSONDecodeError: continue - # identity format: [page_id, title] - page_id, title = str(d["identity"][0]), str(d["identity"][1]) - if is_id and page_id == query: - return d - if title.lower() == query_lower: + # documents.jsonl identity format: [source_sha256, page_id, revision_id] + ident = d.get("identity") + if ( + isinstance(ident, list) + and len(ident) >= 2 + and str(ident[1]) == target_id + ): return d return None @@ -117,7 +93,12 @@ def build_membership_proof(doc, chain, data_bound, data_hash): target_start = doc["target_start"] target_count = doc["targets"] target_end = target_start + target_count - page_id, title = doc["identity"][0], doc["identity"][1] + + # documents.jsonl identity format: [source_sha256, page_id, revision_id] + ident = doc.get("identity", []) + source_sha256 = str(ident[0]) if len(ident) > 0 else None + page_id = str(ident[1]) if len(ident) > 1 else None + revision_id = str(ident[2]) if len(ident) > 2 else None # Find the Wikipedia phase boundaries segments = [] @@ -169,8 +150,9 @@ def build_membership_proof(doc, chain, data_bound, data_hash): proof = { "article": { - "title": title, "page_id": page_id, + "revision_id": revision_id, + "source_sha256": source_sha256, "targets": { "start": target_start, "end": target_end, @@ -206,7 +188,7 @@ def main(): "--run", required=True, help="Run directory (containing chain.jsonl)" ) p.add_argument( - "--article", required=True, help="Article title or Wikipedia page_id" + "--article", required=True, help="Wikipedia page ID (e.g. 12)" ) a = p.parse_args() @@ -214,7 +196,7 @@ def main(): doc = find_article(a.data, a.article) if not doc: sys.exit( - f"Article '{a.article}' not found in {Path(a.data) / 'wikipedia' / 'documents.jsonl'}" + f"Article page ID '{a.article}' not found in {Path(a.data) / 'wikipedia' / 'documents.jsonl'}" ) bound, data_hash = verify_data_commitment(a.data, chain[0]) diff --git a/tests/simple/test_proof.py b/tests/simple/test_proof.py index 637cd11f..031d5ecf 100644 --- a/tests/simple/test_proof.py +++ b/tests/simple/test_proof.py @@ -1,7 +1,8 @@ """Unit tests for simple/proof.py. Verifies article lookup, segment intersection, fork exclusion proofs, -and cryptographic data binding against synthetic test fixtures. +and cryptographic data binding against real schema fixtures matching +release/simple-run/chain.jsonl and published prepared Wikipedia streams. """ import hashlib @@ -28,27 +29,40 @@ def setUp(self): self.wiki_dir.mkdir(parents=True) self.run_dir.mkdir(parents=True) + # Real documents.jsonl schema: identity is [source_sha256, page_id, revision_id] self.docs = [ { - "identity": [736, "Albert Einstein"], - "target_start": 0, - "targets": 1000, - "tokens": 1200, + "identity": [ + "859cf6cc1d13007d165025247cacaf463ff8a4ad700b19e476f7626e24169116", + "12", + "1372193622", + ], "offset": 0, + "target_start": 0, + "targets": 9037, + "tokens": 9037, }, { - "identity": [1042, "Quantum mechanics"], - "target_start": 1000, - "targets": 1500, - "tokens": 1700, - "offset": 1200, + "identity": [ + "859cf6cc1d13007d165025247cacaf463ff8a4ad700b19e476f7626e24169116", + "39", + "1368916291", + ], + "offset": 9037, + "target_start": 9037, + "targets": 5721, + "tokens": 5721, }, { - "identity": [9999, "3I/ATLAS"], - "target_start": 2500, - "targets": 500, - "tokens": 600, - "offset": 2900, + "identity": [ + "859cf6cc1d13007d165025247cacaf463ff8a4ad700b19e476f7626e24169116", + "9999", + "1371999999", + ], + "offset": 14758, + "target_start": 274560000, + "targets": 2000, + "tokens": 2000, }, ] doc_lines = [json.dumps(d) for d in self.docs] @@ -57,37 +71,89 @@ def setUp(self): doc_path.write_text(doc_content, encoding="utf-8") doc_hash = hashlib.sha256(doc_path.read_bytes()).hexdigest() + # Real stream.json schema with files table containing bytes, path, and sha256 stream_data = { + "documents": len(self.docs), + "files": [ + { + "bytes": len(doc_content.encode("utf-8")), + "path": "documents.jsonl", + "sha256": doc_hash, + } + ], "phase": "wikipedia", - "targets": 3000, - "files": [{"path": "documents.jsonl", "sha256": doc_hash}], + "schema": "ovl.stream.v1", + "targets": 7118121139, + "tokens": 7118121139, } stream_bytes = json.dumps(stream_data).encode("utf-8") (self.wiki_dir / "stream.json").write_bytes(stream_bytes) self.stream_hash = hashlib.sha256(stream_bytes).hexdigest() + # Real chain entries copied from release/simple-run/chain.jsonl cursors self.chain = [ { + "control": { + "batches": "10ea13010a13668c8bf9e2884e16bdbd16f8933d9bf4d09eda0c47459133eddb", + "cursor": 0, + "epoch": 0, + "global_step": 0, + "phase": "wikipedia", + "phase_step": 0, + "pos": [0, 0], + }, + "data": { + "conversation": "e179de793decc82e8cecfbfabd7d449d1caf145a988c4c881a9a041dcda36b7f", + "wikipedia": self.stream_hash, + }, + "environment": { + "cublas_workspace": ":4096:8", + "cuda": "12.8", + "cudnn": 91002, + "gpu": "NVIDIA GeForce RTX 5090", + "torch": "2.8.0+cu128", + }, "index": 0, "kind": "initial", - "control": {"phase": "wikipedia", "cursor": 0}, - "data": {"wikipedia": self.stream_hash}, - "state": "state_hash_0", + "model": "2b167bcb407f94ac3f1dead8f316ea180823a1cb40489b8a1ff974bf2bcd959d", "previous": None, + "recipe": "d0d9fc61c46b0f0e0b63e336579e7443860141452d881b1e7297ad46439f9fc5", + "state": "64041a4736bd76b64b149c2a784950a312fb19ed641c7eb87e7300c171d002fc", + "time": 1792422250.861772, }, { + "control": { + "batches": "e3f19a5269c4824fb1615d433b678fa54a6fc23ea99fd82c3e83f3f400f66809", + "cursor": 274561003, + "epoch": 0, + "global_step": 18080, + "phase": "wikipedia", + "phase_step": 18080, + "pos": [14363834, 3072], + }, "index": 1, "kind": "progress", - "control": {"phase": "wikipedia", "cursor": 2000}, - "state": "state_hash_1", + "model": "c32f02fac9e87d0c4279aa39a0fa06b5cc06d5b141d5ff29503cb8431c4ca180", "previous": None, + "state": "ef5090325fcf3c392503406ac2f7e6bd99118d267c38fbe4b624df41b48eca8f", + "time": 1792424215.6430938, }, { + "control": { + "batches": "d5b199348b8d97e5a30ee2ea1a9bc465fd5dc0220a1a4297b4fa0716abdc84dc", + "cursor": 547313827, + "epoch": 0, + "global_step": 36160, + "phase": "wikipedia", + "phase_step": 36160, + "pos": [28727668, 3072], + }, "index": 2, - "kind": "base", - "control": {"phase": "wikipedia", "cursor": 3000}, - "state": "state_hash_2", + "kind": "progress", + "model": "f626d56d900693a129d2b2fe8e9ee20268ec3540a08e16999787ff9e28f11075", "previous": None, + "state": "85efce6bb412cf30a2f1abef232ecdf6cead51d7c040d9b50db12fc4591ee899", + "time": 1792426180.123456, }, ] for i in range(1, len(self.chain)): @@ -103,22 +169,19 @@ def setUp(self): def tearDown(self): shutil.rmtree(self.tmp) - def test_find_article_by_title_and_case(self): - doc = mp.find_article(self.data_dir, "Albert Einstein") + def test_find_article_by_page_id(self): + doc = mp.find_article(self.data_dir, "12") self.assertIsNotNone(doc) - self.assertEqual(doc["identity"][0], 736) + self.assertEqual(doc["identity"][1], "12") + self.assertEqual(doc["target_start"], 0) - doc_lower = mp.find_article(self.data_dir, "albert einstein") - self.assertIsNotNone(doc_lower) - self.assertEqual(doc_lower["identity"][1], "Albert Einstein") - - def test_find_article_by_page_id(self): - doc = mp.find_article(self.data_dir, "736") + def test_find_article_by_int_page_id(self): + doc = mp.find_article(self.data_dir, 12) self.assertIsNotNone(doc) - self.assertEqual(doc["identity"][1], "Albert Einstein") + self.assertEqual(doc["identity"][1], "12") def test_find_article_not_found(self): - doc = mp.find_article(self.data_dir, "Nonexistent Article") + doc = mp.find_article(self.data_dir, "99999999") self.assertIsNone(doc) def test_verify_data_commitment(self): @@ -171,14 +234,14 @@ def test_membership_fork_exclusion_fork_entry_last(self): "kind": "fork", "control": { "phase": "wikipedia", - "cursor": 2000, - "exclude": {"wikipedia": [[2500, 500]]}, + "cursor": 274561003, + "exclude": {"wikipedia": [[274560000, 2000]]}, }, "state": "state_fork", "previous": "prev_hash", }, ] - doc = mp.find_article(self.data_dir, "3I/ATLAS") + doc = mp.find_article(self.data_dir, "9999") proof = mp.build_membership_proof(doc, fork_chain, True, self.stream_hash) self.assertEqual(proof["membership_status"], "excluded") @@ -196,8 +259,8 @@ def test_membership_fork_exclusion_continued_training(self): "kind": "fork", "control": { "phase": "wikipedia", - "cursor": 2000, - "exclude": {"wikipedia": [[2500, 500]]}, + "cursor": 274561003, + "exclude": {"wikipedia": [[274560000, 2000]]}, }, "state": "state_fork", "previous": "prev_hash_1", @@ -207,14 +270,14 @@ def test_membership_fork_exclusion_continued_training(self): "kind": "progress", "control": { "phase": "wikipedia", - "cursor": 3000, - "exclude": {"wikipedia": [[2500, 500]]}, + "cursor": 547313827, + "exclude": {"wikipedia": [[274560000, 2000]]}, }, "state": "state_progress", "previous": "prev_hash_2", }, ] - doc = mp.find_article(self.data_dir, "3I/ATLAS") + doc = mp.find_article(self.data_dir, "9999") proof = mp.build_membership_proof(doc, fork_chain, True, self.stream_hash) self.assertEqual(proof["membership_status"], "excluded") @@ -223,21 +286,42 @@ def test_membership_fork_exclusion_continued_training(self): self.assertIn("exclusion_proof", proof) # Boundary should point to the initial fork entry (1), not the later progress entry (2) self.assertEqual(proof["exclusion_proof"]["at_boundary"], 1) - self.assertEqual(proof["exclusion_proof"]["excluded_range"], [2500, 3000]) + self.assertEqual( + proof["exclusion_proof"]["excluded_range"], [274560000, 274562000] + ) + + def test_membership_trained_single_segment(self): + doc = mp.find_article(self.data_dir, "12") + proof = mp.build_membership_proof(doc, self.chain, True, self.stream_hash) + self.assertEqual(proof["membership_status"], "trained") + self.assertEqual(proof["segments"], [0]) + self.assertEqual( + proof["segment_details"][0]["article_overlap_targets"], [0, 9037] + ) + self.assertEqual(proof["article"]["page_id"], "12") + self.assertNotIn("exclusion_proof", proof) def test_membership_trained_cross_segment(self): - doc = mp.find_article(self.data_dir, "Quantum mechanics") + doc = mp.find_article(self.data_dir, "9999") proof = mp.build_membership_proof(doc, self.chain, True, self.stream_hash) self.assertEqual(proof["membership_status"], "trained") self.assertEqual(proof["segments"], [0, 1]) self.assertEqual( [s["article_overlap_targets"] for s in proof["segment_details"]], - [[1000, 2000], [2000, 2500]], + [[274560000, 274561003], [274561003, 274562000]], ) self.assertNotIn("exclusion_proof", proof) def test_membership_unreached_boundary_touch(self): - doc = {"identity": [1, "Late"], "target_start": 3000, "targets": 10} + doc = { + "identity": [ + "859cf6cc1d13007d165025247cacaf463ff8a4ad700b19e476f7626e24169116", + "8888", + "1371888888", + ], + "target_start": 600000000, + "targets": 1000, + } proof = mp.build_membership_proof(doc, self.chain, True, self.stream_hash) self.assertEqual(proof["membership_status"], "unreached") self.assertEqual(proof["segments"], []) From eb0871c9772db0074c2774234e2410eeb10e5b5a Mon Sep 17 00:00:00 2001 From: rushil23shah-hue Date: Sat, 14 Nov 2026 17:37:27 +0530 Subject: [PATCH 5/5] fix(simple): stream hash documents.jsonl in chunks and generalize exclusion range matching --- simple/proof.py | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/simple/proof.py b/simple/proof.py index d883f55d..6f620766 100644 --- a/simple/proof.py +++ b/simple/proof.py @@ -20,7 +20,7 @@ def find_article(data_dir, article_id): """Find article by Wikipedia page_id in documents.jsonl.""" - if not article_id or not str(article_id).strip(): + if article_id is None or not str(article_id).strip(): return None target_id = str(article_id).strip() path = Path(data_dir) / "wikipedia" / "documents.jsonl" @@ -75,9 +75,15 @@ def verify_data_commitment(data_dir, chain_entry_0): if not doc_files: return False, "documents.jsonl not listed in stream.json files table" expected_doc_hash = doc_files[0]["sha256"] - actual_doc_hash = hashlib.sha256( - (Path(data_dir) / "wikipedia" / "documents.jsonl").read_bytes() - ).hexdigest() + + # Chunked stream hashing to avoid loading large documents.jsonl into memory + doc_file_path = Path(data_dir) / "wikipedia" / "documents.jsonl" + h = hashlib.sha256() + with doc_file_path.open("rb") as f: + while chunk := f.read(65536): + h.update(chunk) + actual_doc_hash = h.hexdigest() + if actual_doc_hash != expected_doc_hash: return ( False, @@ -111,7 +117,11 @@ def build_membership_proof(doc, chain, data_bound, data_hash): entry.get("control", {}).get("exclude", {}).get("wikipedia", []) ) for ex_start, ex_len in exclude_ranges: - if ex_start == target_start and ex_len == target_count and not is_excluded: + if ( + not is_excluded + and ex_start <= target_start + and (ex_start + ex_len) >= target_end + ): is_excluded = True exclusion_detail = { "at_boundary": k,