Skip to content

fix(watch): serialize _rebuild_lock on Windows via msvcrt (#3881) - #3883

Closed
harshaygadekar wants to merge 1 commit into
Graphify-Labs:v8from
harshaygadekar:fix/windows-rebuild-lock
Closed

harshaygadekar wants to merge 1 commit into
Graphify-Labs:v8from
harshaygadekar:fix/windows-rebuild-lock

Conversation

@harshaygadekar

Copy link
Copy Markdown
Contributor

Closes #3881.

Problem

On Windows, _rebuild_lock in graphify/watch.py catches ImportError when importing fcntl and immediately falls back to yield True. Because fcntl does not exist on Windows, every caller is handed the lock simultaneously.

When git hooks (like post-commit and post-checkout back-to-back) or a background watcher and an explicit graphify update run at roughly the same time on Windows, they execute concurrently. Both write to .graph.tmp.json without synchronization and attempt os.replace onto graph.json, causing PermissionError: [WinError 32], truncated JSON files, or mismatched community labels across rebuilds.

The original lock issue (#1037) was reported on Windows, but only the POSIX fcntl.flock half landed. Additionally, four lock tests in tests/test_watch.py and three pending queue tests were marked skipif(sys.platform == "win32"), so Windows CI never ran the locking test suite.

RCA

In graphify/watch.py:

try:
    import fcntl
except ImportError:
    yield True
    return

On Windows, fcntl is never available. The early return bypassed lock creation, acquisition, PID writing, and cleanup entirely.

Fix

  1. Stdlib Windows file locking (msvcrt.locking):
    When fcntl is unavailable, use Python's built-in msvcrt module on Windows.

    • Non-blocking (blocking=False): Calls msvcrt.locking(fh.fileno(), msvcrt.LK_NBLCK, 1). If already locked, raises OSError, caught to yield False.
    • Blocking (blocking=True): Loops with a short 50ms sleep until LK_NBLCK succeeds, avoiding msvcrt.LK_LOCK's 10-second timeout.
    • Unlock: Calls msvcrt.locking(fh.fileno(), msvcrt.LK_UNLCK, 1) in finally:.
    • Kernel safety: Windows automatically releases byte-range locks if the holding process crashes or is terminated.
  2. Byte offset past PID payload (_win_lock_offset = 4096):
    Windows byte-range locks are mandatory. If byte 0 is locked, external pollers attempting to read the holder PID from .rebuild.lock hit PermissionError: [Errno 13]. Locking 1 byte at offset 4096 preserves concurrent read access to byte 0 while enforcing strict mutual exclusion.

  3. Enable tests on Windows:
    Removed skipif(win32) from the 4 lock tests and 3 pending queue tests in tests/test_watch.py, and added test_rebuild_lock_blocks_concurrent_process to assert that a second process is rejected when the lock is held.

Verification/Test Suite

Before fix (Windows 11, Python 3.14):

Running a holder subprocess with a concurrent non-blocking caller:

[*] Testing _rebuild_lock in: C:\Users\harsha\AppData\Local\Temp\tmptqo4ovrx\graphify-out
[*] Holder process status: HOLDER_ACQUIRED True
[*] Second caller non-blocking acquisition result: True
[FAIL] Issue #3881 reproduced! Both processes acquired the lock simultaneously.

After fix (Windows 11, Python 3.14):

[*] Testing _rebuild_lock in: C:\Users\harsha\AppData\Local\Temp\tmppsk29nce\graphify-out
[*] Holder process status: HOLDER_ACQUIRED True
[*] Second caller non-blocking acquisition result: False
[*] External reader successfully read PID: 19168
[SUCCESS] Lock correctly serialized concurrent processes.

Test suite:

$ uv run pytest tests/test_watch.py -k "test_rebuild_lock or pending or contention or drains" -v
tests/test_watch.py::test_rebuild_lock_writes_pid_with_newline PASSED      [ 10%]
tests/test_watch.py::test_rebuild_lock_removed_after_release PASSED        [ 20%]
tests/test_watch.py::test_rebuild_lock_does_not_accumulate_pids_across_runs PASSED [ 30%]
tests/test_watch.py::test_rebuild_lock_non_blocking_does_not_clobber_holder PASSED [ 40%]
tests/test_watch.py::test_rebuild_lock_blocks_concurrent_process PASSED    [ 50%]
tests/test_watch.py::test_queue_and_drain_pending_round_trip PASSED        [ 60%]
tests/test_watch.py::test_drain_pending_dedupes_and_skips_blank_lines PASSED [ 70%]
tests/test_watch.py::test_queue_pending_noop_on_empty_list PASSED          [ 80%]
tests/test_watch.py::test_rebuild_code_queues_on_lock_contention PASSED    [ 90%]
tests/test_watch.py::test_rebuild_code_merges_pending_on_acquire PASSED    [100%]
tests/test_watch.py::test_rebuild_code_drains_late_arrivals PASSED         [100%]

11 passed, 171 deselected in 1.15s

Closes Graphify-Labs#3881.

On Windows, _rebuild_lock falls back to yield True when fcntl cannot be
imported, leaving concurrent rebuilds completely unserialized and causing
file collisions on .graph.tmp.json.

Implement Windows file locking using Python's standard library msvcrt module.
Lock a byte range at offset 4096 so external readers can still read the owning
PID at byte 0 without hitting Windows mandatory lock PermissionErrors.

Un-skip the 4 rebuild lock tests and 3 pending queue tests on Windows, and
add test_rebuild_lock_blocks_concurrent_process.
Copilot AI lite review requested due to automatic review settings September 27, 2026 17:29

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions

Copy link
Copy Markdown

Thanks for the pull request, @harshaygadekar. A maintainer will review it soon.

Want to talk it through while it is in review? Come join us on our Discord server. For longer-form discussion there is also GitHub Discussions.

A couple of things that speed up review: make sure the test suite passes on Python 3.10 and 3.13, and that the change keeps extraction deterministic.

@graphify-labs graphify-labs Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Graphify reviewed this change.

Worth a look — the grounded gate found no coupling regressions or blocking issues, but 1 advisory finding(s) below merit a look before merge.

Formal verification. No changes could be formally verified in this run.


Graphify review — findings

Adds Windows support to the per-repo rebuild lock in _rebuild_lock, using msvcrt.locking at byte offset 4096 (so external pollers can still read the PID at byte 0) when fcntl is unavailable, and only falls back to a no-op yield(True) when neither is present. Removes the win32 skips from the lock tests and adds test_rebuild_lock_blocks_concurrent_process, which spawns a subprocess to verify a second process can't acquire a held lock non-blocking.

Worth a look

  • Releaser can unlink a lock file after another process has acquired it — graphify/watch.py:238 · Escalate · high
    • agreed by 2 of 2 members but NOT verified (no proof, no reproducing execution) — consensus is not a verdict; needs human review
Analysis details — impact, health, verification

Impact & health

Graphify review

Impact — 640 functions depend on the 446 functions this change touches.

Health — this change adds coupling hotspots:

  • new: _rebuild_code() — 146 callers, 55 callees
  • new: main() — 98 callers, 3 callees
  • new: dispatch_command() — 2 callers, 125 callees
  • new: watch() — 5 callers, 7 callees
  • new: _reconcile_graph_html() — 6 callers, 5 callees
  • new: _reconcile_existing_graph() — 1 callers, 8 callees
  • new: _reconcile_markdown_links() — 1 callers, 7 callees
  • new: test_poisoned_manifest_is_healed() — 0 callers, 6 callees

Verification — 640 functions in the blast radius were not formally verified this run (proofs are advisory here).

Gate & verification

graphify gate

PASS — objectively clean (no health regressions, tests not run — proofs not run this pass (advisory)). Grounded, not self-assessed.

Advisory (not blocking):

  • verification_scope: 468 function(s) in the blast radius were not formally verified this run

Test selection

Test selection

8 of 302 test file(s) selected (3%) via static blast radius.

  • tests/test_elixir_import_resolution.py — impact
  • tests/test_external_stub_endpoints.py — impact
  • tests/test_kotlin_grammar.py — impact
  • tests/test_labeling.py — impact
  • tests/test_markdown_code_spans.py — impact
  • tests/test_terraform_modules.py — impact
  • tests/test_watch.py — impact, changed-test
  • tests/test_watch_manifest_location.py — impact

Selection is safe under the controlled-regression assumption; always-run tests + a periodic full run are the backstops. Advisory — it never changes the check verdict.

Formal verification

Could not verify: Could not verify \_rebuild\_lock.

The verifier did not have enough to check \_rebuild\_lock, so it is saying so rather than guessing. No false assurance is the whole point.

Guarantee: No guarantee either way, this is an honest abstention, not a pass.

Note: Reason: no capturable inputs from the test suite; property tier: not verifiable: all 9 sampled inputs raised on both versions — the function never executed, so 'no divergence' would be vacuous

· 8 more finding(s) on lines outside this diff (see the check run).

safishamsi added a commit that referenced this pull request Sep 27, 2026
Security: close the Fortran cpp #include arbitrary-file-read
(GHSA-pcc4-rvhr-2pr8), the last Aider/Devin monolith --watch shell sink
(#3852), and terraform name/value secret redaction (#3870). Plus Windows
watch rebuild locking (#3883), C# tuple element-name refs (#3877), JSX
component-usage calls (#3855), and nested scan-root Python import
projection (#3867).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@safishamsi

Copy link
Copy Markdown
Member

Shipped in v0.9.70 (now on PyPI) via an authorship-preserving cherry-pick, so your commit keeps contributor-graph credit. Thanks @harshaygadekar! Serializes rebuilds on Windows via msvcrt byte-range locking; POSIX fcntl path unchanged.

Release: https://github.com/Graphify-Labs/graphify/releases/tag/v0.9.70

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

3 participants