Skip to content

feat: add canonical deterministic directory-level hashing - #7

Closed
Varshiniputtabakula wants to merge 3 commits into
AOSSIE-Org:mainfrom
Varshiniputtabakula:feat-directory-hash
Closed

Varshiniputtabakula wants to merge 3 commits into
AOSSIE-Org:mainfrom
Varshiniputtabakula:feat-directory-hash

Conversation

@Varshiniputtabakula

@Varshiniputtabakula Varshiniputtabakula commented Feb 25, 2026 •

Copy link
Copy Markdown

Adds deterministic recursive directory-level hashing to strengthen dataset fingerprinting for future sharded preprocessing outputs.

KEY FEATURES:

  1. Ignores hidden files and hidden directories
  2. Normalizes relative paths (POSIX style)
    3.Incorporates file content hashes
    4.Uses delimiter separation to prevent boundary ambiguity
  3. Ensures deterministic ordering through lexicographic sorting

TEST COVERAGE:
Includes comprehensive pytest coverage for:

  1. Determinism (same directory → same hash)
  2. Content modification detection
  3. File addition detection
  4. Rename sensitivity
  5. Hidden file handling
  6. Hidden directory handling
  7. Empty directory behavior
  8. Failure on non-existent directory

This provides a canonical dataset-level fingerprint primitive for reproducibility.

Summary by CodeRabbit

  • New Features

    • Added a deterministic directory-hashing utility that computes a SHA-256 digest from each file’s relative POSIX path and content, ignoring hidden files and directories; validates input and raises errors for missing or non-directory paths.
  • Tests

    • Added comprehensive tests for determinism, content and structure changes (add, rename, move), hidden entries ignored, empty-directory behavior, and error handling.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This PR adds deterministic recursive directory-level hashing functionality to strengthen dataset fingerprinting capabilities. The implementation provides a canonical way to compute SHA256 hashes for entire directories while ignoring hidden files/directories and ensuring deterministic ordering.

Changes:

  • Added compute_directory_hash() function in openverifiablellm/utils.py that recursively hashes directory contents
  • Added comprehensive test suite in tests/test_directory_hash.py covering determinism, content changes, hidden file handling, and error cases
  • Minor whitespace cleanup in openverifiablellm/utils.py

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 7 comments.

File Description
openverifiablellm/utils.py Added compute_directory_hash() function with NumPy-style docstring; includes logic for recursive traversal, hidden file filtering, POSIX path normalization, and deterministic sorting. Also removed trailing whitespace.
tests/test_directory_hash.py New test file with 8 test cases covering determinism, content modification, file addition, rename sensitivity, hidden file/directory handling, empty directory behavior, and error handling for non-existent directories.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread tests/test_directory_hash.py Outdated

def test_nonexistent_directory_raises():
with pytest.raises(FileNotFoundError):
compute_directory_hash("non_existent_dir")

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 test coverage for the case where a file path is passed instead of a directory path. The function checks both not directory.exists() and not directory.is_dir() at line 140, but only the non-existent directory case is tested. Consider adding a test that passes a file path to verify FileNotFoundError is raised with an appropriate message.

Suggested change
compute_directory_hash("non_existent_dir")
compute_directory_hash("non_existent_dir")
def test_file_path_raises_file_not_found(tmp_path):
# Create a regular file, not a directory
file_path = tmp_path / "not_a_directory.txt"
file_path.write_text("content", encoding="utf-8")
# Passing a file path instead of a directory should raise FileNotFoundError
with pytest.raises(FileNotFoundError):
compute_directory_hash(file_path)

Copilot uses AI. Check for mistakes.
Comment thread tests/test_directory_hash.py Outdated
Comment on lines +1 to +93
import pytest
from pathlib import Path
from openverifiablellm.utils import compute_directory_hash
import hashlib

def test_directory_hash_is_deterministic(tmp_path):
# Create files
file1 = tmp_path / "a.txt"
file2 = tmp_path / "b.txt"

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():
with pytest.raises(FileNotFoundError):
compute_directory_hash("non_existent_dir")

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 test coverage for file deletion. While tests cover file addition (line 32-41), content modification (line 20-30), and rename (line 43-54), there's no test verifying that deleting a file changes the directory hash. This is a fundamental operation that should be tested to ensure the hash changes when files are removed.

Copilot uses AI. Check for mistakes.
Comment thread tests/test_directory_hash.py Outdated

def test_nonexistent_directory_raises():
with pytest.raises(FileNotFoundError):
compute_directory_hash("non_existent_dir")

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 test coverage for nested subdirectories. The compute_directory_hash function uses rglob to recursively traverse directories, but there are no tests verifying this behavior works correctly with files in subdirectories (e.g., creating "subdir/file.txt" and verifying it's included in the hash). This is an important code path to test since the PR description mentions "recursive directory-level hashing".

Suggested change
compute_directory_hash("non_existent_dir")
compute_directory_hash("non_existent_dir")
def test_directory_hash_includes_nested_subdirectories(tmp_path):
# Create a top-level file
(tmp_path / "a.txt").write_text("root", encoding="utf-8")
original_hash = compute_directory_hash(tmp_path)
# Create a nested subdirectory with a file inside
subdir = tmp_path / "subdir"
subdir.mkdir()
(subdir / "nested.txt").write_text("nested content", encoding="utf-8")
new_hash = compute_directory_hash(tmp_path)
# The hash should change when a file is added in a nested subdirectory,
# confirming that recursive traversal is taken into account.
assert original_hash != new_hash

Copilot uses AI. Check for mistakes.
@@ -0,0 +1,93 @@
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.
from pathlib import Path
from openverifiablellm.utils import compute_directory_hash
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.
Comment on lines +6 to +10
def test_directory_hash_is_deterministic(tmp_path):
# Create files
file1 = tmp_path / "a.txt"
file2 = tmp_path / "b.txt"

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.
Comment thread openverifiablellm/utils.py Outdated
Comment on lines +157 to +167
files.append(f)

# Sort deterministically by normalized relative path
files_sorted = sorted(
files,
key=lambda f: f.relative_to(directory).as_posix()
)

for file in files_sorted:
relative_path = file.relative_to(directory).as_posix()

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.

Performance inefficiency: relative_to(directory) is called twice for each file - once during sorting (line 162) and once again in the loop (line 166). Consider computing and storing the relative path once during the initial collection phase to avoid redundant path resolution operations, especially for large directory trees.

Suggested change
files.append(f)
# Sort deterministically by normalized relative path
files_sorted = sorted(
files,
key=lambda f: f.relative_to(directory).as_posix()
)
for file in files_sorted:
relative_path = file.relative_to(directory).as_posix()
# Precompute normalized relative path for later reuse
relative_posix = relative.as_posix()
files.append((f, relative_posix))
# Sort deterministically by normalized relative path
files_sorted = sorted(
files,
key=lambda item: item[1]
)
for file, relative_path in files_sorted:

Copilot uses AI. Check for mistakes.
@coderabbitai

coderabbitai Bot commented Feb 25, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

Added compute_directory_hash(directory_path: Union[str, Path]) -> str to compute a deterministic SHA-256 hash of a directory by enumerating non-hidden files, using each file’s relative POSIX path and SHA-256 content. Also added a comprehensive test suite exercising determinism, mutations, hidden entries, and error cases.

Changes

Cohort / File(s) Summary
Directory Hashing Utility
openverifiablellm/utils.py
New public function compute_directory_hash() that validates the input path, recursively collects non-hidden files, sorts by relative POSIX path, computes per-file SHA-256, concatenates path and content hashes with delimiters, and returns a final SHA-256 hex digest. Minor whitespace edits elsewhere in the file.
Test Suite
tests/test_directory_hash.py
New tests verifying determinism, content modification, file addition, rename/move, hidden file and hidden directory exclusion, empty-directory hash value, nonexistent-directory error, and not-a-directory error. Uses tmp_path fixtures to exercise edge cases.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

Python Lang

Poem

A rabbit pads through folders bright, 🐰
Counting paths by soft moonlight,
Bytes and names in tidy chain,
SHA whispers what they contain,
Tests hop by — the hash is right! ✨

🚥 Pre-merge checks | ✅ 2
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: add canonical deterministic directory-level hashing' accurately describes the main feature being added—a new function for deterministic directory hashing as evidenced by the new compute_directory_hash function and comprehensive test suite.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

Try Coding Plans. Let us write the prompt for your AI agent so you can ship faster (with fewer bugs).
Share your feedback on Discord.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions github-actions Bot added size/M and removed size/M labels Feb 25, 2026

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@openverifiablellm/utils.py`:
- Around line 140-141: The current check using "if not directory.exists() or not
directory.is_dir()" raises a FileNotFoundError for both missing paths and
non-directory paths; change it to first test directory.exists() and raise
FileNotFoundError(f"Path not found: {directory}") if false, and then test
directory.is_dir() and raise NotADirectoryError(f"Path is not a directory:
{directory}") if false so callers get the correct error; update the checks
around the variable "directory" in utils.py (the block containing the existing
exists()/is_dir() guard) accordingly.
- Around line 145-163: The loop calls f.relative_to(directory) multiple times;
collect the relative path once by building a list of (posix_str, Path) tuples
instead of raw Paths, e.g., compute relative = f.relative_to(directory) and
rel_posix = relative.as_posix() when iterating files, append (rel_posix, f),
sort by the rel_posix key, and update subsequent code that builds hashes or
iterates files to use the stored Path from the tuple (instead of recomputing
relative_to) so functions like files_sorted and any later hash loop use the
cached rel_posix and Path.

In `@tests/test_directory_hash.py`:
- Around line 6-93: Add a new test that verifies compute_directory_hash handles
nested subdirectories and path-ordering: create a nested structure (e.g.,
tmp_path/subdir1/c.txt and tmp_path/subdir2/d.txt), compute hash, then move a
file between subdirectories (rename tmp_path/subdir1/c.txt to
tmp_path/subdir2/c.txt) and assert the hash changes; also create the same nested
files in a different creation order and assert compute_directory_hash(tmp_path)
remains the same to confirm determinism. Reference compute_directory_hash and
use tmp_path in the new test (e.g., test_nested_directories_and_move) and
include hidden-file checks as needed to avoid interference.
- Around line 91-93: Replace the brittle hardcoded path in
test_nonexistent_directory_raises with a guaranteed-nonexistent tmp path: use
the pytest tmp_path fixture to build a Path like tmp_path / "non_existent_dir"
(do not create it), then call compute_directory_hash(str(path)) inside
pytest.raises(FileNotFoundError); this ensures the test always uses an absent
directory and is independent of the current working directory.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c70d97d and 618c1c4.

📒 Files selected for processing (2)
  • openverifiablellm/utils.py
  • tests/test_directory_hash.py

Comment thread openverifiablellm/utils.py Resolved
Comment thread openverifiablellm/utils.py Outdated
Comment on lines +145 to +163
files = []

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

relative = f.relative_to(directory)

# Ignore hidden files and any file inside hidden directories
if any(part.startswith(".") for part in relative.parts):
continue

files.append(f)

# Sort deterministically by normalized relative path
files_sorted = sorted(
files,
key=lambda f: f.relative_to(directory).as_posix()
)

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.

🧹 Nitpick | 🔵 Trivial

relative_to(directory) computed three times per file — collect once as (posix_str, path) tuples.

f.relative_to(directory) (line 151) is called again inside the sort key (line 162) and again in the hash loop (line 166). On large directories this is wasted work.

♻️ Proposed refactor
-    files = []
-
-    for f in directory.rglob("*"):
-        if not f.is_file():
-            continue
-
-        relative = f.relative_to(directory)
-
-        # Ignore hidden files and any file inside hidden directories
-        if any(part.startswith(".") for part in relative.parts):
-            continue
-
-        files.append(f)
-
-    # Sort deterministically by normalized relative path
-    files_sorted = sorted(
-        files,
-        key=lambda f: f.relative_to(directory).as_posix()
-    )
-
-    for file in files_sorted:
-        relative_path = file.relative_to(directory).as_posix()
+    entries = []
+
+    for f in directory.rglob("*"):
+        if not f.is_file():
+            continue
+
+        relative = f.relative_to(directory)
+
+        # Ignore hidden files and any file inside hidden directories
+        if any(part.startswith(".") for part in relative.parts):
+            continue
+
+        entries.append((relative.as_posix(), f))
+
+    # Sort deterministically by normalized relative path
+    entries_sorted = sorted(entries, key=lambda e: e[0])
+
+    for relative_path, file in entries_sorted:
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openverifiablellm/utils.py` around lines 145 - 163, The loop calls
f.relative_to(directory) multiple times; collect the relative path once by
building a list of (posix_str, Path) tuples instead of raw Paths, e.g., compute
relative = f.relative_to(directory) and rel_posix = relative.as_posix() when
iterating files, append (rel_posix, f), sort by the rel_posix key, and update
subsequent code that builds hashes or iterates files to use the stored Path from
the tuple (instead of recomputing relative_to) so functions like files_sorted
and any later hash loop use the cached rel_posix and Path.

Comment thread tests/test_directory_hash.py Resolved
Comment thread tests/test_directory_hash.py Resolved
@github-actions github-actions Bot added size/M and removed size/M labels Feb 25, 2026

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@openverifiablellm/utils.py`:
- Around line 141-144: The inline long exception messages raised for
missing/invalid directories should be replaced with lightweight library-specific
exception classes and shorter raises; define two small exceptions in
openverifiablellm.utils such as class PathNotFoundError(FileNotFoundError): pass
and class PathNotDirectoryError(NotADirectoryError): pass, then change the
existing raises (the ones raising FileNotFoundError and NotADirectoryError for
the variable directory) to raise PathNotFoundError() and raise
PathNotDirectoryError() (optionally with a very short message) so messages are
not embedded inline and the exceptions are discoverable by callers.

In `@tests/test_directory_hash.py`:
- Around line 91-95: Add a test in tests/test_directory_hash.py that asserts
compute_directory_hash raises NotADirectoryError when the given path exists but
is a file: create a temporary file (e.g., using tmp_path / "a_file.txt" and
write some content), call compute_directory_hash(file_path) inside a
pytest.raises(NotADirectoryError) context, and ensure this new test complements
the existing FileNotFoundError test to cover the non-directory branch.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 618c1c4 and d147b35.

📒 Files selected for processing (2)
  • openverifiablellm/utils.py
  • tests/test_directory_hash.py

Comment thread openverifiablellm/utils.py Outdated
Comment on lines +141 to +144
raise FileNotFoundError(f"Path not found: {directory}")

if not directory.is_dir():
raise NotADirectoryError(f"Path is not a directory: {directory}")

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.

🧹 Nitpick | 🔵 Trivial

Consider moving exception messages into custom exception classes (Ruff TRY003).

Ruff flags both lines for carrying long message strings inline rather than inside a dedicated exception subclass. For a library utility, a lightweight fix is to define small subclasses or use shorter messages.

♻️ Minimal fix — shorter inline messages (no new classes needed)
-        raise FileNotFoundError(f"Path not found: {directory}")
+        raise FileNotFoundError(directory)

-        raise NotADirectoryError(f"Path is not a directory: {directory}")
+        raise NotADirectoryError(directory)
📝 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
raise FileNotFoundError(f"Path not found: {directory}")
if not directory.is_dir():
raise NotADirectoryError(f"Path is not a directory: {directory}")
raise FileNotFoundError(directory)
if not directory.is_dir():
raise NotADirectoryError(directory)
🧰 Tools
🪛 Ruff (0.15.2)

[warning] 141-141: Avoid specifying long messages outside the exception class

(TRY003)


[warning] 144-144: Avoid specifying long messages outside the exception class

(TRY003)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@openverifiablellm/utils.py` around lines 141 - 144, The inline long exception
messages raised for missing/invalid directories should be replaced with
lightweight library-specific exception classes and shorter raises; define two
small exceptions in openverifiablellm.utils such as class
PathNotFoundError(FileNotFoundError): pass and class
PathNotDirectoryError(NotADirectoryError): pass, then change the existing raises
(the ones raising FileNotFoundError and NotADirectoryError for the variable
directory) to raise PathNotFoundError() and raise PathNotDirectoryError()
(optionally with a very short message) so messages are not embedded inline and
the exceptions are discoverable by callers.

Comment thread tests/test_directory_hash.py Resolved
@github-actions github-actions Bot added size/M and removed size/M labels Feb 25, 2026

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@openverifiablellm/utils.py`:
- Around line 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.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d147b35 and 5a3fd23.

📒 Files selected for processing (2)
  • openverifiablellm/utils.py
  • tests/test_directory_hash.py

Comment on lines +150 to +153
for f in directory.rglob("*"):
if not f.is_file():
continue

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.

@Archit381 Archit381 self-assigned this Feb 25, 2026
@Archit381

Copy link
Copy Markdown
Member

@Varshiniputtabakula checking hashes with this directory approach doesn't seem that helpful.

@Archit381 Archit381 closed this Feb 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants