Repository navigation
Description
Summary
cache.file_hash(path, root) computes
SHA256(content + b"\x00" + <path relative to root, lowercased>), falling back
to the absolute path when the file is not under root. Its stat-index
fastpath, however, memoizes by (absolute path, size, mtime_ns) — without the
root — and returns the memoized digest for every later call:
entry = _stat_index.get(abs_key)
if (entry and entry.get("hash") is not None
and entry.get("size") == st.st_size
and entry.get("mtime_ns") == st.st_mtime_ns):
return entry["hash"] # <- root of THIS call is ignoredSo within a process (or across processes sharing a persisted
stat-index.json), whichever root was used first wins: the same
file_hash(f, root) call yields different digests depending on call order.
This is an independent correctness bug in the memo key; it does not need
--out to exist, but in practice it surfaces there:
- In an
extract --outrun, an early caller (change detection) hashes corpus
files with a root that does not contain them → the absolute-path fallback
digest gets memoized → all later cache reads/writes in the run inherit
absolute-path-salted keys. - Absolute-salted keys defeat the function's documented intent ("Using a
relative path ... makes cache entries portable across machines and checkout
directories") — the resulting cache entries are machine-specific. This may
explain or contribute to the observation in multiple ./graphify-out/cache folders created in workspace #1012 that "File hashes are different in
(1) and (2) for the same file", and thematically adjacent to manifest.json uses absolute paths as keys — --update always triggers full rebuild on CI or different clone path #1964
(absolute-path keys break portability on the manifest side).
To be clear about scope: the --out cache breakage itself is fully explained by
two companion reports (#1990 — checkpoints saved under the corpus instead of
--out, and #1991 — the final semantic-cache save silently writing 0
entries). This memo bug additionally makes key derivation order-dependent,
which obscures diagnosis and breaks key portability/stability guarantees.
Environment
- graphifyy 0.9.18 (PyPI,
uv tool install), Python 3.14 (uv-managed), Windows 11 - no LLM backend involved — pure
graphify.cachebehavior
Reproduction (standalone, no LLM)
Run the script below with the graphify environment's Python. It runs two fresh
child processes with opposite call orders:
[rel_first] first=8b1b7beae984 second=8b1b7beae984 memo_returned_first_for_both=True
[abs_first] first=c34abf4dbaff second=c34abf4dbaff memo_returned_first_for_both=True
rel_first: file_hash(f, root_a) = 8b1b7beae984 (expected rel 8b1b7beae984)
abs_first: file_hash(f, root_a) = c34abf4dbaff (memo; abs = c34abf4dbaff)
same (file, root) pair, different result by call order: True
REPRO CONFIRMED (order-dependent hash)
(root_a contains the file; root_b does not. In each order, the second call
returns the first call's digest even though its salt should differ.)
repro_file_hash_memo.py
"""Minimal standalone repro: graphify.cache.file_hash's stat-index memo omits the
root anchor from its memo key, so the SAME (file, root) call returns DIFFERENT
digests depending on which root was hashed FIRST in the process.
Verified against graphifyy 0.9.18. No LLM calls; uses only temp files.
Background: the digest is SHA256(content + b"\\x00" + salt) where salt is the
path RELATIVE to root (or the absolute path when the file is not under root —
the ValueError fallback). The memo key is (absolute path, size, mtime_ns) with
NO root component, so the first computed digest is returned for every later
call regardless of root.
Run: <graphify-env-python> repro_file_hash_memo.py
Expected output ends with: REPRO CONFIRMED (order-dependent hash)
"""
from __future__ import annotations
import hashlib
import json
import subprocess
import sys
import tempfile
from pathlib import Path
CONTENT = b"repro content for file_hash memo poisoning\n"
def expected_digests(f: Path, root_containing: Path) -> tuple[str, str]:
rel = f.resolve().relative_to(root_containing.resolve()).as_posix().lower()
h1 = hashlib.sha256(); h1.update(CONTENT); h1.update(b"\x00"); h1.update(rel.encode())
h2 = hashlib.sha256(); h2.update(CONTENT); h2.update(b"\x00")
h2.update(f.resolve().as_posix().lower().encode())
return h1.hexdigest(), h2.hexdigest()
def child(order: str) -> None:
"""Run one call order in a fresh process; print JSON result."""
base = Path(tempfile.mkdtemp(prefix="fh_repro_"))
root_a = base / "corpus"; root_a.mkdir() # contains the file
root_b = base / "elsewhere"; root_b.mkdir() # does not
f = root_a / "doc.txt"; f.write_bytes(CONTENT)
from graphify.cache import file_hash
exp_rel, exp_abs = expected_digests(f, root_a)
if order == "rel_first":
first = file_hash(f, root_a) # rel salt expected
second = file_hash(f, root_b) # SHOULD be abs salt; memo returns `first`
else:
first = file_hash(f, root_b) # abs salt expected (fallback)
second = file_hash(f, root_a) # SHOULD be rel salt; memo returns `first`
print(json.dumps({"order": order, "first": first, "second": second,
"expected_rel": exp_rel, "expected_abs": exp_abs}))
def main() -> int:
results = {}
for order in ("rel_first", "abs_first"):
out = subprocess.run([sys.executable, __file__, order],
capture_output=True, text=True, check=True)
results[order] = json.loads(out.stdout.strip().splitlines()[-1])
ok = True
for order, r in results.items():
memo_hit = r["first"] == r["second"]
print(f"[{order}] first={r['first'][:12]} second={r['second'][:12]} "
f"memo_returned_first_for_both={memo_hit}")
ok &= memo_hit
a = results["rel_first"]; b = results["abs_first"]
print(f"rel_first: file_hash(f, root_a) = {a['first'][:12]} (expected rel {a['expected_rel'][:12]})")
print(f"abs_first: file_hash(f, root_a) = {b['second'][:12]} (memo; abs = {b['expected_abs'][:12]})")
divergent = a["first"] != b["second"]
print("same (file, root) pair, different result by call order:", divergent)
if ok and divergent:
print("REPRO CONFIRMED (order-dependent hash)")
return 0
print("REPRO FAILED — behavior may have been fixed upstream")
return 1
if __name__ == "__main__":
if len(sys.argv) > 1:
child(sys.argv[1])
else:
raise SystemExit(main())Expected
file_hash(f, root) returns the same digest for the same (content, root)
regardless of what was hashed earlier in the process. E.g. include the salt
component (or the resolved root) in the memo key, or skip the memo when the
relative_to fallback fired.
Suggested fix
Key the stat index by (abs_key, salt) — where salt is the relative-or-absolute
path component that actually enters the digest — or store {salt: hash} per
stat entry. Persisted stat-index.json entries would need the same treatment
(or a version bump to invalidate old single-hash entries).
Related
- multiple ./graphify-out/cache folders created in workspace #1012 (open) — "File hashes are different ... for the same file" matches this footprint
- manifest.json uses absolute paths as keys — --update always triggers full rebuild on CI or different clone path #1964 (open) — absolute-path keys vs portability (manifest side)
- Companion reports:
graphify extract --outsaves recovery checkpoints in the wrong directory #1990 (checkpoint location under--out), With --out, the final semantic-cache save resolves relative source_file paths against out_root and silently writes 0 entries #1991 (final
save writes 0 entries with--out)
Activity
fix(cache): key file_hash stat-index memo by salt, not absolute path (#…
docs: changelog entries for the #1989/#1971/#1975/#1978/#1980 fixes
safishamsi commentedon Jul 18, 2026
Fixed on v8 (ships in 0.9.19) in 995508c. The file_hash stat-index memo is now keyed by the path salt, so it is order-independent across roots and no longer poisons stat-index.json across runs. Digest computation unchanged.
fix(cache): key file_hash stat-index memo by salt, not absolute path (G…
docs: changelog entries for the Graphify-Labs#1989/Graphify-Labs#1971/G…