Skip to content

file_hash stat-index memo omits the root anchor: same (file, root) call returns different digests depending on call order #1989

Closed

Description

@tomipetteri-ops

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 ignored

So 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:

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.cache behavior

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

Activity

  1. safishamsi commented on Jul 18, 2026

    @safishamsi
    Member

    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.

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