fix(watch): keep the recursive handler alive off Linux (#5074)

The pruned watch tree is Linux-only. macOS and Windows still use a
recursive schedule, so `watched` stays empty and the handler's parent
guard dropped every event. Apply the guard only when the manual tree is
active, and leave the recursive fallback alone when an ignore file
changes.

Add a darwin-simulated regression test and make the schedule contract
tests platform-aware.

(cherry picked from commit 2ee00533dd)
This commit is contained in:
Deepjyoti-Sarmah authored and safishamsi committed 2026-11-09 14:09:19 +00:00
1 parent ce66353f93
commit 43e1d4650a
3 files changed
+92 -20

No files matched your search

+23 -17
View File
@@ -3608,30 +3608,36 @@ def watch(watch_path: Path, debounce: float = 3.0) -> None:
root_config_path = watch_root_for_ignore / RC_FILENAME
override_snapshot: dict[str, str] = activate_language_overrides(watch_root_for_ignore)
config_changed = False
# Only Linux prunes the recursive watch tree. macOS and Windows keep the
# recursive schedule, so their handler must not require a `watched` entry.
manual = sys.platform.startswith("linux")
class Handler(FileSystemEventHandler):
def on_any_event(self, event):
nonlocal last_trigger, pending, override_snapshot, config_changed
nonlocal ignore_patterns, ignored
if event.is_directory:
if not _is_read_only_event(event):
path = Path(os.fsdecode(event.src_path)).resolve()
if path.parent not in watched:
return
if event.event_type == "created":
add_tree(path, emit_existing=True)
elif event.event_type == "deleted":
remove_tree(path)
elif event.event_type == "moved":
remove_tree(path)
dest = Path(os.fsdecode(event.dest_path)).resolve()
if under_root(dest):
add_tree(dest, emit_existing=True)
if not manual or _is_read_only_event(event):
return
path = Path(os.fsdecode(event.src_path)).resolve()
if path.parent not in watched:
return
if event.event_type == "created":
add_tree(path, emit_existing=True)
elif event.event_type == "deleted":
remove_tree(path)
elif event.event_type == "moved":
remove_tree(path)
dest = Path(os.fsdecode(event.dest_path)).resolve()
if under_root(dest):
add_tree(dest, emit_existing=True)
return
if _is_read_only_event(event):
return
path = Path(os.fsdecode(event.src_path))
if path.parent not in watched or not path.parent.exists():
if manual and (
path.parent not in watched or not path.parent.exists()
):
return
if path.name in {".graphifyignore", ".gitignore"}:
ignore_patterns = _load_graphifyignore(
@@ -3640,8 +3646,9 @@ def watch(watch_path: Path, debounce: float = 3.0) -> None:
ignored = ignored_predicate(
watch_root_for_ignore, gitignore=ignore_gitignore
)
remove_tree(watch_root_for_ignore)
add_tree(watch_root_for_ignore, emit_existing=False)
if manual:
remove_tree(watch_root_for_ignore)
add_tree(watch_root_for_ignore, emit_existing=False)
return
# Atomic replacement reports the new root config in dest_path.
dest_raw = getattr(event, "dest_path", None)
@@ -3675,7 +3682,6 @@ def watch(watch_path: Path, debounce: float = 3.0) -> None:
changed.add(path)
handler = Handler()
manual = sys.platform.startswith("linux")
observer = (
Observer()
if manual
+64 -3
View File
@@ -1864,6 +1864,64 @@ def test_watch_handler_honors_graphifyignore(tmp_path, monkeypatch):
assert rebuild_calls, "non-ignored .py write should have triggered _rebuild_code"
@pytest.mark.skipif(not _watchdog_available(), reason="watchdog not installed")
def test_watch_non_linux_handler_accepts_events_without_watched_entry(
tmp_path, monkeypatch
):
"""#5075: macOS and Windows keep the recursive schedule, so their handler
must accept file events even though the manual `watched` map is empty."""
import threading
from graphify import watch as watch_mod
from watchdog import observers
from watchdog.events import FileCreatedEvent
from watchdog.observers import polling
watch_root = tmp_path / "corpus"
watch_root.mkdir()
target = watch_root / "app.py"
target.write_text("x = 1\n", encoding="utf-8")
captured = {}
rebuild_calls: list[Path] = []
class FakeObserver:
def schedule(self, handler, path, *, recursive=False, event_filter=None):
captured["handler"] = handler
captured["recursive"] = recursive
def start(self):
pass
fake = FakeObserver()
monkeypatch.setattr(observers, "Observer", lambda: fake)
monkeypatch.setattr(polling, "PollingObserver", lambda: fake)
monkeypatch.setattr(sys, "platform", "darwin")
monkeypatch.setattr(
watch_mod, "_rebuild_code", lambda p, **kw: rebuild_calls.append(p) or True
)
monkeypatch.setattr(watch_mod, "_notify_only", lambda p: None)
thread = threading.Thread(
target=watch_mod.watch,
args=(watch_root,),
kwargs={"debounce": 0.1},
daemon=True,
)
thread.start()
deadline = time.monotonic() + 5.0
while time.monotonic() < deadline and "handler" not in captured:
time.sleep(0.01)
assert captured.get("recursive") is True
captured["handler"].on_any_event(FileCreatedEvent(str(target)))
deadline = time.monotonic() + 5.0
while time.monotonic() < deadline and not rebuild_calls:
time.sleep(0.05)
assert rebuild_calls, "the recursive handler dropped a real file event"
@pytest.mark.skipif(not _watchdog_available(), reason="watchdog not installed")
def test_watch_loads_graphifyignore_once(tmp_path, monkeypatch):
"""gh-928: .graphifyignore must be parsed exactly once at watch() startup,
@@ -4938,7 +4996,7 @@ def test_watch_schedules_change_only_event_filter(tmp_path, monkeypatch):
_run_watch_with_fake_observer(tmp_path, monkeypatch, FakeObserver())
assert captured["recursive"] is False
assert captured["recursive"] is (not sys.platform.startswith("linux"))
assert captured["event_filter"] == _watch_event_filter()
assert we.FileOpenedEvent not in captured["event_filter"]
if hasattr(we, "FileClosedNoWriteEvent"):
@@ -4957,7 +5015,10 @@ def test_watch_falls_back_when_watchdog_lacks_event_filter(tmp_path, monkeypatch
_run_watch_with_fake_observer(tmp_path, monkeypatch, OldObserver())
assert captured == {"recursive": False, "called": True}
assert captured == {
"recursive": not sys.platform.startswith("linux"),
"called": True,
}
@pytest.mark.skipif(not _watchdog_available(), reason="watchdog not installed")
@@ -4994,7 +5055,7 @@ def test_watch_warns_when_observer_hides_event_filter_in_kwargs(
with caplog.at_level(logging.WARNING, logger="graphify.watch"):
_run_watch_with_fake_observer(tmp_path, monkeypatch, KwargsObserver())
assert captured == {"recursive": False}
assert captured == {"recursive": not sys.platform.startswith("linux")}
assert any("event_filter" in r.getMessage() for r in caplog.records)
+5
View File
@@ -1,3 +1,4 @@
import sys
from pathlib import Path
import pytest
@@ -5,6 +6,10 @@ import pytest
pytest.importorskip("watchdog")
@pytest.mark.skipif(
not sys.platform.startswith("linux"),
reason="the pruned watch tree is Linux-only",
)
def test_watch_schedules_only_kept_directories(tmp_path, monkeypatch):
"""#5033: ignored directories must not get an inotify watch.