Skip to content

Post-commit hook lock-skip drops changes on rapid commits (follow-up #1037) #1059

Closed

Description

@bitnash

Summary

Follow-up to #1037 (closed 2026-05-27). The _rebuild_lock added in 0.8.21 successfully prevents the graph.json corruption that issue described, but it uses a non-blocking skip-on-contention strategy that silently drops the
changed_paths of every concurrent rebuild attempt.

Real-world impact: a typical "fix small thing, commit, fix another, commit" cadence loses the second commit's changes from the graph. The user only finds out when the next graphify query returns stale results, or when they manually
run graphify update ..

Environment

  • graphify 0.8.22 (latest as of report)
  • Python 3.10.12
  • Ubuntu 22.04 (WSL2)
  • Standard graphify hook install

Symptom

After two back-to-back commits, ~/.cache/graphify-rebuild.log contains:

[graphify hook] 1 file(s) changed - rebuilding graph...
[graphify watch] Rebuild already in progress for <repo> - skipping.
[graphify hook] 1 file(s) changed - rebuilding graph...
[graphify watch] No code-graph topology changes detected; outputs left untouched.

Notice the skipping line — the second commit's changed_paths are gone. No second pass happens. The in-flight rebuild only reflects the first commit's file set. The user's manifest.json will show the second file with an old
mtime/hash until they manually re-run.

Why this slipped through #1037's fix

#1037 was filed against the JSON-corruption symptom (no lock at all). The maintainer correctly added _rebuild_lock with fcntl.flock to serialize access. But the lock's failure mode in the post-commit hook path is:

# watch.py:322
if acquire_lock:
    with _rebuild_lock(out, blocking=block_on_lock) as got:
        if not got:
            print("[graphify watch] Rebuild already in progress for "
                  f"{watch_path.resolve()} - skipping.")
            return False  # ← changed_paths lost forever
        ...

block_on_lock=False is the default for the hook (correct — we don't want the background process to wait), but the alternative isn't "wait", it's "drop the work". There's no queue, no retry, no signal to the in-flight holder.

Minimal repro

graphify hook install
for i in 1 2; do
  echo "// test $i" >> src/some_file.ts
  git add src/some_file.ts && git commit -m "test $i"
done
# Wait for background rebuilds
until [ ! -f graphify-out/.rebuild.lock ]; do sleep 1; done
grep -c "queued\|skipping" ~/.cache/graphify-rebuild.log
# Expected with a fix: each commit's changes captured (e.g. drain-loop in log)
# Actual: at least one "skipping" line, changes from that commit dropped

Suggested fix: pending-queue + drain loop

The cleanest minimal-invasive fix is a sentinel file (graphify-out/.pending_changes) that concurrent processes append to before attempting the lock. The in-flight holder drains it (plus its own initial paths) and loops draining
until empty, with a safety cap.

Sketch of the change in watch.py:

# New helpers near _rebuild_lock
_PENDING_FILE = ".pending_changes"

def _queue_pending(out_dir: Path, changed_paths: list[Path]) -> None:
    if not changed_paths:
        return
    try:
        out_dir.mkdir(parents=True, exist_ok=True)
        with (out_dir / _PENDING_FILE).open("a", encoding="utf-8") as fh:
            for p in changed_paths:
                fh.write(f"{p}\n")
    except OSError:
        pass

def _drain_pending(out_dir: Path) -> list[Path]:
    pending = out_dir / _PENDING_FILE
    if not pending.exists():
        return []
    try:
        text = pending.read_text(encoding="utf-8")
        pending.unlink()
    except OSError:
        return []
    seen, result = set(), []
    for line in text.splitlines():
        line = line.strip()
        if line and line not in seen:
            seen.add(line)
            result.append(Path(line))
    return result
# Modified lock block in _rebuild_code (~line 322)
out = watch_path / _GRAPHIFY_OUT
if acquire_lock:
    if changed_paths is not None:
        _queue_pending(out, changed_paths)   # queue BEFORE locking
    with _rebuild_lock(out, blocking=block_on_lock) as got:
        if not got:
            print("[graphify watch] Rebuild already in progress for "
                  f"{watch_path.resolve()} - queued for in-flight rebuild.")
            return False  # the holder will pick up our queued paths
        # Drain pending — our own + any peers' that skipped
        if changed_paths is None:
            _drain_pending(out)  # discard; full rebuild covers it
            effective = None
        else:
            queued = _drain_pending(out)
            merged = {str(p): p for p in list(changed_paths) + list(queued)}
            effective = list(merged.values())
        ok = _rebuild_code(watch_path, changed_paths=effective,
                           follow_symlinks=follow_symlinks, force=force,
                           no_cluster=no_cluster, acquire_lock=False)
        # Drain loop for late arrivals queued during the rebuild
        if changed_paths is not None:
            MAX_LATE_PASSES = 20
            for _ in range(MAX_LATE_PASSES):
                late = _drain_pending(out)
                if not late:
                    break
                _rebuild_code(watch_path, changed_paths=late,
                              follow_symlinks=follow_symlinks, force=force,
                              no_cluster=no_cluster, acquire_lock=False)
            else:
                print("[graphify watch] hit max late-drain passes — "
                      "letting subsequent hooks pick up the rest.")
        return ok

Key properties:

  • Non-blocking for concurrent commits (hook still returns fast)
  • Eventual consistency: late arrivals captured in the next drain
  • Bounded: caps at 20 late passes to prevent starvation under continuous-CI load
  • Backward-compatible: full-corpus rebuilds (changed_paths=None) still work as before

Local validation

I patched my install with this change and tested four scenarios:

Test Result
Unit: _queue_pending + _drain_pending (append + dedup + delete) ✅
2-thread race (Python concurrency) ✅ second worker prints "queued", both paths in graph
4-process race (OS-level subprocesses) ✅ 1 acquires, 3 queue, all 4 files in graph
Deterministic drain (pre-queue 3 paths, call _rebuild_code with 1) ✅ queue empty after, "Rebuilt: …" confirmed
End-to-end: 3 real consecutive commits via git hook ✅ log shows "queued × 2" + "drain pass × 1", manifest mtime fresh for all 3 files

Happy to send a PR if useful — let me know the preferred branch.

Activity

  1. safishamsi commented on May 29, 2026

    @safishamsi
    Member

    Fixed in f0badd9 — rapid back-to-back commits now queue their changed_paths to .pending_changes before attempting the lock. The lock-holder drains and merges all queued paths, then runs a late-drain loop after rebuild. No more silent drops.

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