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
70 changes: 57 additions & 13 deletions openverifiablellm/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,39 @@
import logging
import json
import platform
from typing import Union, Optional

logger = logging.getLogger(__name__)
MERKLE_CHUNK_SIZE_BYTES = 1024 * 1024 # 1MB

# Merkle Tree Chunk-Level Hashing for Large Files
def compute_merkle_root(file_path: Union[str, Path], chunk_size: int = 1024 * 1024) -> str:
path = Path(file_path)
leaves = []

with path.open("rb") as f:
while chunk := f.read(chunk_size):
# reuse compute_sha256
leaf_hex = compute_sha256(chunk)
leaves.append(bytes.fromhex(leaf_hex))

if not leaves:
return compute_sha256(b"")

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
parent_hex = compute_sha256(combined)
next_level.append(bytes.fromhex(parent_hex))

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 +105,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, chunk_size=MERKLE_CHUNK_SIZE_BYTES),
"processed_merkle_root": compute_merkle_root(processed_path, chunk_size=MERKLE_CHUNK_SIZE_BYTES),
"chunk_size_bytes": MERKLE_CHUNK_SIZE_BYTES,
# ---------------------------------------------------------------

"preprocessing_version": "v1",
"python_version": platform.python_version()
}
Expand All @@ -86,28 +124,34 @@ def generate_manifest(raw_path, processed_path):

logger.info("Manifest written to %s", manifest_path)

# helpers
def compute_sha256(file_path: Union[str, Path]) -> str:
# helpers:Update compute_sha256() to support bytes input directly.
def compute_sha256(
*,
data: Optional[Union[bytes, bytearray]] = None,
file_path: Optional[Union[str, Path]] = None,
) -> str:
"""
Compute SHA256 hash of a file.
Compute SHA256 hash of a file OR raw bytes.

This is used for both raw and processed files to ensure integrity.
This provides a deterministic fingerprint of the dataset,
enabling reproducibility and verification.

Parameters
----------
file_path : Union[str, Path]
Path to the dataset file (string or Path-like).

Returns
-------
str
SHA256 hash string.
Exactly one of `data` or `file_path` must be provided.
"""
path = Path(file_path)

if (data is None) == (file_path is None):
raise ValueError(
"Exactly one of 'data' or 'file_path' must be provided."
)

sha256 = hashlib.sha256()

if data is not None:
sha256.update(data)
return sha256.hexdigest()

path = Path(file_path)
with path.open("rb") as f:
while chunk := f.read(8192):
sha256.update(chunk)
Expand Down
69 changes: 68 additions & 1 deletion tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import hashlib
import pytest
from openverifiablellm import utils
import json

"""
Unit and integration tests for OpenVerifiableLLM preprocessing pipeline.
Expand Down Expand Up @@ -126,4 +127,70 @@ 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 = json.loads(manifest_file.read_text())

assert "raw_merkle_root" in manifest
assert "processed_merkle_root" in manifest
assert "chunk_size_bytes" in manifest

# --------------- compute_merkle_root ------------------------------------

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)

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
Loading