Skip to content

[Bug]: _ensure_stat_index binds to the first root per process while the index is keyed by absolute path — a multi-root process gets wrong hashes and atexit writes the corruption to disk (184 cached files reported as 0) #3989

Closed

Description

@Rasco94

Pre-flight checks

What happened?

_ensure_stat_index binds the stat index to the first root a process ever sees and then returns forever, while the index is keyed by the file's absolute path — but file_hash is computed from the content plus the path relative to the root. Any process that touches two different roots therefore gets, from the second root onward, hashes computed under the first root. And because atexit flushes the accumulated index into whatever _GRAPHIFY_OUT points at when the process exits, the corruption is written to disk and outlives the process.

cache.py:329-333:

def _ensure_stat_index(root: Path) -> None:
    global _stat_index, _stat_index_root, _stat_index_dirty
    if _stat_index_root is not None:
        return                      # bound to the FIRST root, for the life of the process

and the key omits the root:

abs_key = str(p.resolve())          # does NOT contain the root
entry = _stat_index.get(abs_key)
if entry and entry["size"] == st.st_size and entry["mtime_ns"] == st.st_mtime_ns:
    return entry["hash"]            # hash computed under a DIFFERENT root

What this does in practice, measured on our install:

_cache/<project-A>/cache/stat-index.json   5,960 entries, 1.34 MB
   containing paths belonging to projects B and C, which share nothing with A

and the user-visible effect for project A:

before deleting the poisoned index :  574 files,   0 in cache,    0 nodes
after  deleting the poisoned index :  574 files, 184 in cache, 1,990 nodes

199 cache entries were on disk and invisible. Had we run a rebuild in that state we would have written an empty graph over a good one (1,911 nodes).

The failure is silent in both directions: on read you are served cache that is not yours; on write you deposit an entry under a key nobody will ever look up. Nothing warns.

Why this is easy to hit

The CLI is safe — it runs one root per process. But anyone who uses the library across projects is not, and the natural shape is the dangerous one:

# WRONG, and nothing says so
for name, root in projects:
    gc._GRAPHIFY_OUT = str(CACHE / name)
    gc.check_semantic_cache(files, root=root)      # 2nd iteration onward: wrong hashes

Resetting the globals by hand between iterations is not enough, because the atexit handler stays registered and still writes the accumulated index into the last _GRAPHIFY_OUT at exit. We verified that: reads came back correct, and the file on disk was still poisoned.

We hit this twice in four days before understanding it, both times noticed only because a number did not add up between two measurements of the same thing.

Suggested fixes, in order of preference

  1. Key the index by (root, absolute path), or store the root in the entry and ignore entries whose root differs. This makes multi-root processes correct rather than merely documented.
  2. Keep a dict of indexes per root instead of one bound index, and flush each to its own location.
  3. At minimum: warn() when _ensure_stat_index is called with a root different from the bound one — a one-line change that turns a silent wrong answer into a visible one — and say in the API docs that one process must touch one root.

Steps to reproduce

import graphify.cache as gc
from pathlib import Path

# two roots, same file content, different relative paths
# run both in ONE process, as a library user naturally would
for name, root in [("A", Path("/corpus/a")), ("B", Path("/corpus/b"))]:
    gc._GRAPHIFY_OUT = f"/tmp/out/{name}"
    print(name, gc.file_hash(root / "doc.md", root=root))

# the second hash is computed under root A: it is the SAME value, although the
# relative path differs, so it must not be.
# then inspect /tmp/out/B/cache/stat-index.json and observe it contains
# absolute paths from corpus A.

Detection on an existing install — a healthy index contains only paths under its own project's source:

python3 -c "import json,sys;d=json.load(open(sys.argv[1]));print(len(d));[print(' ',k) for k in list(d)[:3]]" \
  <graphify-out>/cache/stat-index.json

Error output or graph output

# poisoned index belonging to project A:
5,960 entries, 1.34 MB
  /corpus/other-project/00-INDEX.md
  /corpus/yet-another/journal/...

# same project, before and after deleting that file:
before:  574 files,   0 in cache,    0 nodes
after :  574 files, 184 in cache, 1,990 nodes

# no warning is emitted in either state — that silence is the report.

Graphify version

0.9.73 (the binding at cache.py:331 is unchanged from 0.8.18, where we first hit it)

Operating System

Linux

Additional context

stat-index.json is derived cache, so deleting it is a safe workaround — it regenerates at the cost of recomputing hashes. We now run one subprocess per project, which also works. Both are workarounds for something the library could make correct; option 3 alone would have saved us two incidents.

Activity

  1. github-actions commented on Oct 2, 2026

    @github-actions

    Thanks for opening this issue, @Rasco94. A maintainer will take a look soon.

    If you would like to discuss it in real time, come say hi on our Discord server. For longer-form questions and ideas there is also GitHub Discussions.

    To help us triage, please make sure the report includes what you expected, what actually happened, and the steps (and a small sample) to reproduce it.

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