Skip to content

_rebuild_lock is a no-op on Windows, so the #1037 race is still unfixed there #3881

Closed

Description

@xz02108040

Summary

graphify.watch._rebuild_lock falls back to yield True when fcntl can't be imported. Its docstring says so: "Falls back to a no-op yield(True) on platforms without fcntl (Windows)." So on Windows every caller "gets" the lock and concurrent rebuilds are never serialized.

#1037 was reported on Windows 11 and proposed "Serialize via flock (POSIX) or msvcrt.locking (Windows)". Only the POSIX half landed, so the race described there still exists on Windows in 0.9.61.

Environment

  • graphifyy 0.9.61, Python 3.13.3
  • Windows 11 Pro (build 26200), Git for Windows (Git Bash); commits and pulls also via GitHub Desktop 3.6.6 (bundled git 2.53.0)

Reproduction

import subprocess, sys
from pathlib import Path
from graphify.watch import _rebuild_lock

out = Path("graphify-out")
with _rebuild_lock(out) as a:
    with _rebuild_lock(out) as b:
        print("nested:", a, b)

holder = subprocess.Popen(
    [sys.executable, "-c",
     "import time; from pathlib import Path; from graphify.watch import _rebuild_lock\n"
     "with _rebuild_lock(Path('graphify-out')) as g:\n"
     "    print('holder', g, flush=True); time.sleep(5)"],
    stdout=subprocess.PIPE, text=True)
holder.stdout.readline()
with _rebuild_lock(out) as c:
    print("second process while holder runs:", c)
holder.wait()

Output on Windows:

nested: True True
second process while holder runs: True

graphify-out/.rebuild.lock is never created. With fcntl I'd expect True False and False.

Why it matters

On Windows these paths all run unserialized:

  • post-commit and post-checkout rebuilds fired back-to-back. The installed post-checkout hook even says "The flock inside _rebuild_code still prevents pile-ups when commit + checkout fire back-to-back", which doesn't hold on Windows.
  • a hook rebuild plus a manual graphify update: cli.py calls _rebuild_code(..., block_on_lock=True), which doesn't wait here.
  • the Post-commit hook lock-skip drops changes on rapid commits (follow-up #1037) #1059 pending queue: since the lock is always acquired, contenders never defer to the running rebuild; each runs its own.

All of them write the same fixed temp file graphify-out/.graph.tmp.json, os.replace it onto graph.json, then write GRAPH_REPORT.md, .graphify_labels.json and .sig. Two overlapping rebuilds can therefore:

I haven't captured a fresh corruption on 0.9.61; the list above follows from the code path and the original #1037 report.

Suggested fix

Take a Windows byte-range lock on the same .rebuild.lock with msvcrt.locking: LK_NBLCK for the non-blocking case, and a retry loop for blocking=True (LK_LOCK gives up after 10 attempts). Windows releases the lock when the handle closes or the process dies, so no stale-lock cleanup is needed, same as flock.

One caveat: Windows byte-range locks are mandatory, so locking byte 0 would stop external pollers from reading the PID written there. Locking a byte past the payload (for example at a large fixed offset) avoids that.

As defense in depth, a per-process temp name such as .graph.tmp.<pid>.json would stop overlapping writers from clobbering each other's temp file even when the lock is missing.

Current workaround

Our post-merge hook waits 60 s before running graphify update, so a just-started hook rebuild can finish, then runs it once more 60 s later to overwrite a possibly stale result. It works in practice but only narrows the window.

Activity

  1. github-actions commented on Sep 27, 2026

    @github-actions

    Thanks for opening this issue, @xz02108040. 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.

  2. harshaygadekar commented on Sep 27, 2026

    @harshaygadekar
    Contributor

    Confirmed and reproduced on windows 11 (Python 3.14). The issue is valid.

    Reproduction

    Tested concurrent non-blocking acquisition between a background holder process and the main process:

    import subprocess, sys, time
    from pathlib import Path
    from graphify.watch import _rebuild_lock
    
    out = Path("graphify-out")
    holder = subprocess.Popen([
        sys.executable, "-c",
        "import time, sys; from pathlib import Path; from graphify.watch import _rebuild_lock; "
        f"with _rebuild_lock(Path(r'{out}')) as got: "
        "    print('HOLDER_ACQUIRED', got, flush=True); time.sleep(2)"
    ], stdout=subprocess.PIPE, text=True)
    
    print(holder.stdout.readline().strip())
    with _rebuild_lock(out, blocking=False) as second:
        print("Second caller non-blocking acquisition:", second)
    holder.wait()

    Output on unpatched code:

    HOLDER_ACQUIRED True
    Second caller non-blocking acquisition: True
    

    Because fcntl is missing on windows, _rebuild_lock catches the ImportError and hits the early yield True. Mutual exclusion is completely bypassed, .rebuild.lock is never even created, and overlapping rebuilds (hooks firing back-to-back, watcher + manual update) run concurrently against .graph.tmp.json.

    Triage and Fix

    I made the fix for this, that uses python's standard library msvcrt on windows (msvcrt.locking):

    • Uses msvcrt.LK_NBLCK for non-blocking calls (yielding False on contested lock) and a short sleep loop for blocking mode.
    • Locks a 1-byte range at offset 4096 rather than byte 0. Because windows byte-range locks are mandatory, locking byte 0 prevents external inspection tools from reading the PID payload and throws PermissionError: [Errno 13]. Locking past the first block preserves read access to the PID at byte 0 while guaranteeing mutual exclusion.
    • Unlocks with msvcrt.LK_UNLCK in finally:. the OS kernel also automatically releases the lock if the process exits or crashes.
    • Un-skips the 4 rebuild lock tests and 3 pending queue tests in tests/test_watch.py on windows, and adds a cross-process contention test.

    Post-fix verification:

    HOLDER_ACQUIRED True
    Second caller non-blocking acquisition: False
    External reader read PID: 19168
    [SUCCESS] Lock correctly serialized concurrent processes.
    

    All 11 watch/lock tests pass locally on windows in 1.15s, ruff and skillgen --check are clean. I have already opened a PR for review referencing this issue.

  3. added a commit that references this issue on Sep 27, 2026
    e4a6f50
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