Skip to content

atexit stat-index flush recreates the analyzed directory if it was deleted mid-run (worktree race leaves husk dirs) #2974

Closed

Description

@ebalitbit

Summary

_flush_stat_index in graphify/cache.py runs at atexit and does p.parent.mkdir(parents=True, exist_ok=True) before writing graphify-out/cache/stat-index.json. If the analyzed directory is deleted while graphify is running, the exit-time flush recreates the deleted directory tree, leaving a "husk" containing nothing but graphify-out/cache/stat-index.json.

Observed on graphifyy 0.9.17 (macOS, Python 3.13).

Real-world trigger

A git post-commit hook that runs graphify update . >/dev/null 2>&1 & (backgrounded), in a workflow that uses short-lived git worktree checkouts:

  1. Agent/CI commits in a worktree → hook starts graphify update . in the background.
  2. The branch is merged and git worktree remove deletes the worktree.
  3. graphify finishes, its atexit flush mkdir -ps the dead path back into existence.

Over a few weeks this left 81 resurrected <repo>-<branch> directories next to the main repo, each containing only the stat-index file.

Deterministic repro

import shutil
from pathlib import Path
from graphify import cache

corpus = Path("husk-race-corpus").resolve()
corpus.mkdir()
f = corpus / "a.md"
f.write_text("# hello\nbody\n")

cache.file_hash(f, corpus)      # dirties the stat index
shutil.rmtree(corpus)           # corpus deleted mid-run
cache._flush_stat_index()       # what atexit will do

print("husk resurrected!" if corpus.exists() else "ok")
# prints: husk resurrected!  -> corpus/graphify-out/cache/stat-index.json exists

Suggested fix

Skip the flush when the corpus root no longer exists — a missing root means the cache has no home anymore, and recreating the directory is worse than dropping one cache write:

def _flush_stat_index() -> None:
    global _stat_index_dirty, _stat_index_root
    if not _stat_index_dirty or _stat_index_root is None:
        return
    if not _stat_index_root.exists():   # corpus deleted while we ran
        _stat_index_dirty = False
        return
    p = _stat_index_file(_stat_index_root)
    ...

Verified locally: with the guard, the repro above leaves the deleted directory deleted, and a live corpus still gets its stat-index written as before. Happy to open a PR with this change if useful.

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