Skip to content
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -332,3 +332,5 @@ __pycache__/
*.pyo
*.pyd
*.bz2

*.venv
54 changes: 54 additions & 0 deletions openverifiablellm/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,53 @@

logger = logging.getLogger(__name__)

# Merkle Tree Chunk-Level Hashing for Large Files
def compute_merkle_root(file_path: Union[str, Path], chunk_size: int = 1024 * 1024) -> str:
"""
Compute the Merkle Root hash of a file by splitting it into chunks.

This allows researchers to cryptographically verify specific chunks
or subsets of the training data without re-hashing the entire dataset.

Parameters
----------
file_path : Union[str, Path]
Path to the dataset file.
chunk_size : int
Size of each chunk in bytes (default: 1MB).

Returns
-------
str
The final Merkle Root hash string.
"""
path = Path(file_path)
leaves = []

# 1. Read file in chunks and hash each chunk (raw bytes)
with path.open("rb") as f:
while chunk := f.read(chunk_size):
leaves.append(hashlib.sha256(chunk).digest())
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

# Handle empty files deterministically
if not leaves:
return hashlib.sha256(b"").hexdigest()

# 2. Build the tree bottom-up
while len(leaves) > 1:
next_level = []
for i in range(0, len(leaves), 2):
left = leaves[i]
right = leaves[i + 1] if i + 1 < len(leaves) else left

combined = left + right
next_level.append(hashlib.sha256(combined).digest())

leaves = next_level

return leaves[0].hex()


# extract clean wikipage from actual wikipage
def extract_text_from_xml(input_path):
"""
Expand Down Expand Up @@ -74,6 +121,13 @@ def generate_manifest(raw_path, processed_path):
"dump_date": extract_dump_date(raw_path.name),
"raw_sha256": compute_sha256(str(raw_path)),
"processed_sha256": compute_sha256(str(processed_path)),

# ---------------- ADDED FIELDS ----------------
"raw_merkle_root": compute_merkle_root(raw_path),
"processed_merkle_root": compute_merkle_root(processed_path),
"chunk_size_bytes": 1024 * 1024,
# ---------------------------------------------------------------
Comment thread
aniket866 marked this conversation as resolved.
Resolved

"preprocessing_version": "v1",
"python_version": platform.python_version()
}
Expand Down
53 changes: 53 additions & 0 deletions tests/test_merkle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import hashlib
import pytest
from pathlib import Path
from openverifiablellm import utils


# Merkle Root Tests

def test_merkle_root_deterministic(tmp_path):
file = tmp_path / "data.txt"
file.write_text("hello wikipedia")

root1 = utils.compute_merkle_root(file, chunk_size=4)
root2 = utils.compute_merkle_root(file, chunk_size=4)

assert root1 == root2


def test_merkle_root_changes_when_content_changes(tmp_path):
file = tmp_path / "data.txt"
file.write_text("content A")

root1 = utils.compute_merkle_root(file)

file.write_text("content B")

root2 = utils.compute_merkle_root(file)

assert root1 != root2


def test_merkle_root_single_chunk_equals_sha256(tmp_path):
file = tmp_path / "data.txt"
content = "small file"
file.write_text(content)

# Large chunk size ensures single leaf
merkle_root = utils.compute_merkle_root(file, chunk_size=10_000)

expected = hashlib.sha256(content.encode()).hexdigest()

assert merkle_root == expected


def test_merkle_root_empty_file(tmp_path):
file = tmp_path / "empty.txt"
file.write_text("")

root = utils.compute_merkle_root(file)

expected = hashlib.sha256(b"").hexdigest()

assert root == expected
Comment thread
aniket866 marked this conversation as resolved.
Resolved
21 changes: 20 additions & 1 deletion tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,4 +126,23 @@ def test_extract_text_from_xml_end_to_end(tmp_path, monkeypatch):
assert processed_file.exists()

assert "Hello World" in processed_file.read_text()


# --------------- manifest includes merkle fields ------------------------------------

def test_manifest_contains_merkle_fields(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)

raw_file = tmp_path / "raw.txt"
raw_file.write_text("dummy data")

processed_file = tmp_path / "processed.txt"
processed_file.write_text("cleaned data")

utils.generate_manifest(raw_file, processed_file)

manifest_file = tmp_path / "data/dataset_manifest.json"
manifest = manifest_file.read_text()

assert "raw_merkle_root" in manifest
assert "processed_merkle_root" in manifest
assert "chunk_size_bytes" in manifest
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved