Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 63 additions & 3 deletions openverifiablellm/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def extract_text_from_xml(input_path):
project_root = Path.cwd()
output_dir = project_root / "data" / "processed"
output_dir.mkdir(parents=True, exist_ok=True)

output_path = output_dir / "wiki_clean.txt"

with bz2.open(input_path, "rb") as f:
Expand All @@ -58,7 +58,7 @@ def extract_text_from_xml(input_path):
elem.clear()
logger.info("Preprocessing complete. Output saved to %s", output_path)
generate_manifest(input_path,output_path)

# generate data manifest
def generate_manifest(raw_path, processed_path):
raw_path = Path(raw_path)
Expand Down Expand Up @@ -114,6 +114,66 @@ def compute_sha256(file_path: Union[str, Path]) -> str:

return sha256.hexdigest()

def compute_directory_hash(directory_path: Union[str, Path]) -> str:
"""
Compute a deterministic SHA256 hash of a directory.

The hash incorporates:
- Relative file paths (normalized to POSIX style)
- File contents (via compute_sha256)

Hidden files and files inside hidden directories (starting with '.')
are ignored.

Parameters
----------
directory_path : Union[str, Path]
Path to directory to hash.

Returns
-------
str
SHA256 hex digest representing directory contents.
"""
directory = Path(directory_path)

if not directory.exists():
raise FileNotFoundError(directory)

if not directory.is_dir():
raise NotADirectoryError(directory)

sha256 = hashlib.sha256()

entries = []

for f in directory.rglob("*"):
if not f.is_file():
continue

Comment on lines +150 to +153

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

cat openverifiablellm/utils.py | head -200 | tail -100

Repository: AOSSIE-Org/OpenVerifiableLLM

Length of output: 2693


🏁 Script executed:

rg -n 'compute_directory_hash|is_file|is_symlink|symlink' openverifiablellm/utils.py -A 2 -B 1

Repository: AOSSIE-Org/OpenVerifiableLLM

Length of output: 325


🏁 Script executed:

find tests -name '*.py' -type f | xargs rg -l 'compute_directory_hash|symlink' 2>/dev/null

Repository: AOSSIE-Org/OpenVerifiableLLM

Length of output: 100


🏁 Script executed:

rg -n 'symlink|test.*hash' tests/ -A 3 -B 1

Repository: AOSSIE-Org/OpenVerifiableLLM

Length of output: 1843


🏁 Script executed:

cat tests/test_directory_hash.py

Repository: AOSSIE-Org/OpenVerifiableLLM

Length of output: 3503


🏁 Script executed:

python3 <<'EOF'
from pathlib import Path
import tempfile
import os

# Test is_file() behavior with symlinks
with tempfile.TemporaryDirectory() as tmpdir:
    tmpdir_path = Path(tmpdir)
    
    # Create a regular file
    regular_file = tmpdir_path / "regular.txt"
    regular_file.write_text("content")
    
    # Create a symlink to the regular file
    symlink_file = tmpdir_path / "symlink.txt"
    symlink_file.symlink_to(regular_file)
    
    # Test is_file() behavior
    print(f"regular_file.is_file(): {regular_file.is_file()}")
    print(f"symlink_file.is_file(): {symlink_file.is_file()}")
    print(f"symlink_file.is_symlink(): {symlink_file.is_symlink()}")
    
    # Test what rglob includes
    print("\nFiles from rglob('*'):")
    for f in tmpdir_path.rglob("*"):
        print(f"  {f.name}: is_file={f.is_file()}, is_symlink={f.is_symlink()}")
EOF

Repository: AOSSIE-Org/OpenVerifiableLLM

Length of output: 276


🏁 Script executed:

rg -n 'is_symlink|symlink' tests/test_directory_hash.py

Repository: AOSSIE-Org/OpenVerifiableLLM

Length of output: 54


Exclude symlinked files from directory hashing.

At line 151, is_file() returns True for symlinks to files, allowing content outside the target directory to be included in the hash. This breaks deterministic reproducibility across systems where symlinks may reference different paths or external content.

The function currently provides no test coverage for symlink behavior.

♻️ Proposed fix
    for f in directory.rglob("*"):
+        if f.is_symlink():
+            continue
        if not f.is_file():
            continue
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for f in directory.rglob("*"):
if not f.is_file():
continue
for f in directory.rglob("*"):
if f.is_symlink():
continue
if not f.is_file():
continue
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openverifiablellm/utils.py` around lines 150 - 153, The directory-hashing
loop currently uses f.is_file() which returns True for symlinks to files and can
pull external content into the hash; update the loop that iterates
directory.rglob("*") (the block using variable f) to explicitly skip symlinks
(use f.is_symlink() or equivalent) in addition to non-files so symlinked files
are not included, and add unit tests covering symlink behavior to ensure
deterministic hashing across systems.

relative = f.relative_to(directory)

if any(part.startswith(".") for part in relative.parts):
continue

rel_posix = relative.as_posix()
entries.append((rel_posix, f))

entries_sorted = sorted(entries, key=lambda e: e[0])

for relative_path, file in entries_sorted:

# Include relative path in hash
sha256.update(relative_path.encode("utf-8"))
sha256.update(b"\0") # delimiter

# Include file content hash
file_hash = compute_sha256(file)
sha256.update(file_hash.encode("utf-8"))
sha256.update(b"\0") # delimiter

return sha256.hexdigest()

def extract_dump_date(filename: str):
parts = filename.split("-")
for part in parts:
Expand Down Expand Up @@ -148,7 +208,7 @@ def clean_wikitext(text: str) -> str:
if len(sys.argv) < 2:
print("Usage: python -m openverifiablellm.utils <input_dump>")
sys.exit(1)

logging.basicConfig(
level=logging.INFO,
format="%(levelname)s - %(message)s"
Expand Down
125 changes: 125 additions & 0 deletions tests/test_directory_hash.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import pytest
from pathlib import Path
from openverifiablellm.utils import compute_directory_hash

Copilot AI Feb 25, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Inconsistent import style compared to the existing test file. In tests/test_util.py, the convention is to import the module as "from openverifiablellm import utils" and then call "utils.compute_sha256()". This test file uses "from openverifiablellm.utils import compute_directory_hash" which is inconsistent. Consider using "from openverifiablellm import utils" and calling "utils.compute_directory_hash()" to maintain consistency.

Copilot uses AI. Check for mistakes.
import hashlib

Copilot AI Feb 25, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing blank line after imports section. According to PEP 8 and the pattern observed in tests/test_util.py, there should be a blank line between imports and the first function or comment section.

Copilot uses AI. Check for mistakes.
def test_directory_hash_is_deterministic(tmp_path):
# Create files
file1 = tmp_path / "a.txt"
file2 = tmp_path / "b.txt"

Comment on lines +6 to +10

Copilot AI Feb 25, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing section header comment. In tests/test_util.py, test functions are organized with section comments like "# --------------- compute_sha256 ------------------------------------". Consider adding a similar header like "# --------------- compute_directory_hash tests ------------------------------------" for consistency with the existing test file structure.

Suggested change
def test_directory_hash_is_deterministic(tmp_path):
# Create files
file1 = tmp_path / "a.txt"
file2 = tmp_path / "b.txt"
# --------------- compute_directory_hash tests ------------------------------------
def test_directory_hash_is_deterministic(tmp_path):
# Create files
file1 = tmp_path / "a.txt"
file2 = tmp_path / "b.txt"

Copilot uses AI. Check for mistakes.
file1.write_text("hello", encoding="utf-8")
file2.write_text("world", encoding="utf-8")

hash1 = compute_directory_hash(tmp_path)
hash2 = compute_directory_hash(tmp_path)

assert hash1 == hash2


def test_directory_hash_changes_on_content_modification(tmp_path):
file1 = tmp_path / "a.txt"
file1.write_text("hello", encoding="utf-8")

original_hash = compute_directory_hash(tmp_path)

file1.write_text("modified", encoding="utf-8")

new_hash = compute_directory_hash(tmp_path)

assert original_hash != new_hash

def test_directory_hash_changes_on_file_addition(tmp_path):
(tmp_path / "a.txt").write_text("hello", encoding="utf-8")

original_hash = compute_directory_hash(tmp_path)

(tmp_path / "b.txt").write_text("world", encoding="utf-8")

new_hash = compute_directory_hash(tmp_path)

assert original_hash != new_hash

def test_directory_hash_changes_on_rename(tmp_path):
file_path = tmp_path / "a.txt"
file_path.write_text("content", encoding="utf-8")

original_hash = compute_directory_hash(tmp_path)

renamed_path = tmp_path / "renamed.txt"
file_path.rename(renamed_path)

new_hash = compute_directory_hash(tmp_path)

assert original_hash != new_hash

def test_hidden_file_is_ignored(tmp_path):
(tmp_path / "a.txt").write_text("hello", encoding="utf-8")

original_hash = compute_directory_hash(tmp_path)

# Add hidden file
(tmp_path / ".hidden.txt").write_text("secret", encoding="utf-8")

new_hash = compute_directory_hash(tmp_path)

assert original_hash == new_hash


def test_hidden_directory_is_ignored(tmp_path):
# Visible file
(tmp_path / "a.txt").write_text("visible", encoding="utf-8")

original_hash = compute_directory_hash(tmp_path)

# Hidden directory with file inside
hidden_dir = tmp_path / ".hidden_dir"
hidden_dir.mkdir()
(hidden_dir / "secret.txt").write_text("secret", encoding="utf-8")

new_hash = compute_directory_hash(tmp_path)

assert original_hash == new_hash

def test_empty_directory_hash(tmp_path):
# No files inside
hash_value = compute_directory_hash(tmp_path)

# SHA256 of empty input
assert hash_value == hashlib.sha256().hexdigest()

def test_nonexistent_directory_raises(tmp_path):
missing_path = tmp_path / "non_existent_dir"

with pytest.raises(FileNotFoundError):
compute_directory_hash(missing_path)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved


def test_nested_directories_and_move(tmp_path):
subdir1 = tmp_path / "subdir1"
subdir2 = tmp_path / "subdir2"
subdir1.mkdir()
subdir2.mkdir()

file1 = subdir1 / "a.txt"
file2 = subdir2 / "b.txt"

file1.write_text("content1", encoding="utf-8")
file2.write_text("content2", encoding="utf-8")

original_hash = compute_directory_hash(tmp_path)

# Move file1 into subdir2
file1.rename(subdir2 / "a.txt")

new_hash = compute_directory_hash(tmp_path)

assert original_hash != new_hash


def test_not_a_directory_raises(tmp_path):
file_path = tmp_path / "a_file.txt"
file_path.write_text("content", encoding="utf-8")

with pytest.raises(NotADirectoryError):
compute_directory_hash(file_path)
Loading