Skip to content

file_hash() stat fastpath returns a STALE digest when a file is rewritten with same-length content inside one mtime tick #2612

Closed

Description

@rajarshidattapy

Labels: bug, cache, correctness
Version: 0.9.38 (commit 10ad921)
Environment: Windows 11, Python 3.13.6, NTFS

Summary

graphify/cache.py:file_hash() uses a (size, mtime_ns) stat fastpath to skip re-reading a
file. On filesystems whose timestamp granularity is coarser than the interval between two
writes (NTFS updates mtime on a ~15.6 ms system tick), a file that is rewritten with
different content of the same byte length keeps the same (size, mtime_ns). The memo
therefore returns the digest of the previous content.

Because file_hash() is the identity used for semantic-cache keys and for incremental
change detection, a stale digest means graphify believes changed content is unchanged.

This is not theoretical: it makes a shipped test fail roughly half the time (see
"Collateral evidence").

Steps to reproduce

# hashrepro.py
import pathlib, tempfile, hashlib
from graphify.cache import file_hash

root = pathlib.Path(tempfile.mkdtemp())
f = root / "mod.py"

collisions = 0
for i in range(20):
    f.write_text("x = 1  # aaa\n")      # 13 bytes
    h1 = file_hash(f, root)
    f.write_text("x = 2  # bbb\n")      # 13 bytes, DIFFERENT content
    h2 = file_hash(f, root)
    if h1 == h2:
        collisions += 1

print(f"stale digest returned in {collisions}/20 trials")
$ python hashrepro.py
stale digest returned in 19/20 trials

Each trial also confirms st1.st_size == st2.st_size and st1.st_mtime_ns == st2.st_mtime_ns
is True, which is what lets the memo fire.

Actual behavior

file_hash() returns the digest computed from the old content. Downstream:

  • Semantic cache: check_semantic_cache() keys on this digest, so an LLM extraction
    produced for the old content is served for the new content. The graph silently reflects
    code that is no longer on disk, and no re-billing/re-extraction is triggered to correct it.
  • Incremental update: the manifest records the file as unchanged, so graphify update
    skips re-extracting it.
  • prune_semantic_cache(): two different contents collapse to one cache entry, so the
    orphan that should be swept is indistinguishable from the live entry.

Expected behavior

file_hash() is documented as "SHA256 of file contents + path relative to root". Two
different file contents must never yield the same digest. The stat fastpath is an
optimisation and must not be able to return a digest for content that is no longer present.

Root cause

graphify/cache.py:363-378:

st = p.stat()
entry = _stat_index.get(abs_key)
if (isinstance(entry, dict)
        and entry.get("size") == st.st_size
        and entry.get("mtime_ns") == st.st_mtime_ns):
    hashes = entry.get("hashes")
    if isinstance(hashes, dict):
        cached = hashes.get(salt)
        if isinstance(cached, str):
            return cached          # <-- stale when mtime granularity > write interval

(size, mtime_ns) is only a safe change-detector when the clock resolution is finer than
the shortest possible interval between two writes. That does not hold on NTFS, and is not
guaranteed on ext4/APFS either for writes inside the same nanosecond-truncated tick.

Impact / realistic triggers

The dangerous pattern is "a file is hashed, then rewritten at the same length before the
clock ticks"
, inside one process. Realistic cases:

  • graphify watch is a long-lived process that hashes on every rebuild. Two saves in quick
    succession (editor autosave, format-on-save followed by a manual save) with the same
    length leaves the second one invisible.
  • Formatters, codemods, and sed -i sweeps rewrite many files in a burst; length-preserving
    edits are common (x = 1 → x = 2, < → >, renaming to a same-length identifier).
  • Any single-process flow that hashes a file before and after a rewrite.

I did not observe the stale digest surviving into a later, separate process in my
testing — a fresh run recomputed correctly. So the current blast radius is per-process, not
a permanently poisoned on-disk index. That still covers watch and any single long run.

Collateral evidence

tests/test_cache.py::test_semantic_prune_sweeps_both_namespaces_against_same_live_set
fails ~50% of the time in isolation because of exactly this:

$ for i in $(seq 8); do pytest "tests/test_cache.py::test_semantic_prune_sweeps_both_namespaces_against_same_live_set" -q --tb=no -p no:randomly | tail -1; done
1 passed
1 failed
1 failed
1 passed
1 failed
1 failed
1 failed
1 passed

The test writes "# A\n\nContent A.\n" then "# B\n\nContent B.\n" — same length. When
h_old == h_live the two save_semantic_cache calls write to one file, and
prune_semantic_cache returns 0 instead of 2.

Suggested fix

Make the fastpath refuse to trust an entry whose recorded mtime is too close to "now" to be
distinguishable — the standard trick used by build systems (git's racily-clean handling,
ccache, Bazel):

if (isinstance(entry, dict)
        and entry.get("size") == st.st_size
        and entry.get("mtime_ns") == st.st_mtime_ns
        # racily-clean guard: a file whose mtime is within one filesystem tick of
        # the index write cannot be proven unchanged by stat alone -- re-read it.
        and st.st_mtime_ns < entry.get("indexed_at_ns", 0) - _MTIME_GRANULARITY_NS):

recording indexed_at_ns = time.time_ns() alongside size/mtime_ns when the entry is
stored. _MTIME_GRANULARITY_NS can be probed once per cache root (write two files, diff the
mtimes) or conservatively fixed at ~20 ms on Windows / ~1 ms elsewhere.

A smaller alternative, if the extra field is unwelcome: also record and compare
st.st_ctime_ns, which NTFS updates on write — though this weakens the fastpath on
filesystems where ctime tracks metadata only.

Related

Activity

  1. added a commit that references this issue on Aug 11, 2026
  2. safishamsi commented on Aug 11, 2026

    @safishamsi
    Member

    Fixed in v0.9.40 (graphifyy==0.9.40 on PyPI). file_hash()'s stat fastpath now uses a racily-clean guard (fall back to a content hash for files modified within the mtime granularity window), so a same-size rewrite within one mtime tick no longer serves a stale digest. Thanks @rajarshidattapy for the fix (PR #2613).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions