The two poll loops were ~15 % of a core at idle: the watcher re-stat'd every source transcript each 2 s tick, and the indexer re-walked the workspace (~8 000 dirs / 120 000 files, a Path + relative_to per file) every 2 min. fswatch.TreeWatch (ctypes onto libc, nothing to install) watches every dir of a tree, picks up new dirs as they appear, skips pruned names and reports queue overflows. The watcher drains it each tick and stats only the reported paths — a full re-walk every WATCH_RESCAN_SECS (60 s) and after an overflow stay as the safety net. WorkspaceWatch (its own thread) marks the indexer's cached walk dirty when a context file appears or goes, so the walk runs on that, on save, and every WALK_SAFETY_SECS (30 min); the walk itself now filters on strings before building any path. Without inotify (WATCH_INOTIFY=0, not Linux, the watch limit) both keep the old cadence. Side by side on the live mounts (threads running, a client polling the list every 5 s): 28–40 % → ~4 % of a core, list p90 1.3–2.6 s → ~150–180 ms. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
225 lines
8.6 KiB
Python
225 lines
8.6 KiB
Python
"""inotify watching (fswatch): the tree watch itself, the transcript watcher
|
|
on top of it (and its poll fallback), and the workspace watch that tells the
|
|
indexer when to re-walk — plus the cheaper walk returning what the old one did."""
|
|
|
|
import os
|
|
import pathlib
|
|
import tempfile
|
|
import time
|
|
import unittest
|
|
|
|
TMP = pathlib.Path(tempfile.mkdtemp())
|
|
os.environ.setdefault("WORKSPACE", str(TMP / "ws"))
|
|
|
|
import fswatch # noqa: E402
|
|
from events import Hub, Watcher # noqa: E402
|
|
from files import discovery # noqa: E402
|
|
|
|
|
|
def until(pred, secs: float = 3.0) -> bool:
|
|
end = time.monotonic() + secs
|
|
while time.monotonic() < end:
|
|
if pred():
|
|
return True
|
|
time.sleep(0.02)
|
|
return pred()
|
|
|
|
|
|
class TreeWatchTest(unittest.TestCase):
|
|
def setUp(self):
|
|
self.root = pathlib.Path(tempfile.mkdtemp(dir=TMP))
|
|
(self.root / "a").mkdir()
|
|
(self.root / "a" / "old.jsonl").write_text("x\n")
|
|
self.late = self.root.parent / (self.root.name + "-late")
|
|
self.tw = fswatch.TreeWatch.open([self.root, self.late],
|
|
file_mask=fswatch.FILE_CHANGES,
|
|
prune=lambda n: n == "node_modules")
|
|
if self.tw is None:
|
|
self.skipTest("no inotify here")
|
|
|
|
def tearDown(self):
|
|
self.tw.close()
|
|
|
|
def test_the_initial_tree_is_not_news(self):
|
|
self.assertEqual(self.tw.changes(), (set(), False))
|
|
|
|
def test_an_append_is_reported(self):
|
|
with (self.root / "a" / "old.jsonl").open("a") as fh:
|
|
fh.write("y\n")
|
|
self.assertTrue(self.tw.wait(2))
|
|
self.assertEqual(self.tw.changes()[0], {str(self.root / "a" / "old.jsonl")})
|
|
|
|
def test_a_new_dir_is_watched_and_its_files_reported(self):
|
|
sub = self.root / "b" / "subagents"
|
|
sub.mkdir(parents=True)
|
|
(sub / "agent-1.jsonl").write_text("1\n")
|
|
self.assertTrue(until(lambda: str(sub / "agent-1.jsonl") in self.tw.changes()[0]))
|
|
with (sub / "agent-1.jsonl").open("a") as fh:
|
|
fh.write("2\n")
|
|
self.assertTrue(until(lambda: str(sub / "agent-1.jsonl") in self.tw.changes()[0]))
|
|
|
|
def test_a_pruned_dir_is_not_watched(self):
|
|
before = self.tw.watches
|
|
(self.root / "node_modules" / "x").mkdir(parents=True)
|
|
(self.root / "node_modules" / "x" / "f").write_text("1")
|
|
time.sleep(0.05)
|
|
self.assertEqual(self.tw.changes()[0], set())
|
|
self.assertEqual(self.tw.watches, before)
|
|
|
|
def test_a_root_that_appears_later_is_picked_up(self):
|
|
(self.late / "p").mkdir(parents=True)
|
|
(self.late / "p" / "s.jsonl").write_text("1")
|
|
self.assertIn(str(self.late / "p" / "s.jsonl"), self.tw.changes()[0])
|
|
with (self.late / "p" / "s.jsonl").open("a") as fh:
|
|
fh.write("2")
|
|
self.assertTrue(until(lambda: str(self.late / "p" / "s.jsonl") in self.tw.changes()[0]))
|
|
|
|
def test_a_dir_moved_away_stops_reporting(self):
|
|
(self.root / "b").mkdir()
|
|
self.tw.changes()
|
|
os.rename(self.root / "b", TMP / f"gone-{self.root.name}")
|
|
self.assertIn(str(self.root / "b"), self.tw.changes()[0])
|
|
(TMP / f"gone-{self.root.name}" / "f.jsonl").write_text("1")
|
|
time.sleep(0.05)
|
|
self.assertEqual(self.tw.changes()[0], set())
|
|
|
|
|
|
class _Meta:
|
|
def reload_if_changed(self):
|
|
return False
|
|
|
|
|
|
class _Indexer:
|
|
def __init__(self):
|
|
self.calls = []
|
|
|
|
def scan_transcripts(self, only=None):
|
|
self.calls.append(only)
|
|
|
|
|
|
class WatcherTest(unittest.TestCase):
|
|
def setUp(self):
|
|
self.src = pathlib.Path(tempfile.mkdtemp(dir=TMP))
|
|
(self.src / "p").mkdir()
|
|
(self.src / "p" / "s1.jsonl").write_text("1\n")
|
|
self.hub, self.ix = Hub(), _Indexer()
|
|
self.w = Watcher([self.src], _Meta(), self.ix, self.hub)
|
|
self.q = self.hub.subscribe()
|
|
self.w._scan_sources() # what run() does before opening the watch
|
|
self.w._full_at = time.monotonic()
|
|
self.w._tw = fswatch.TreeWatch.open([str(self.src)],
|
|
file_mask=fswatch.FILE_CHANGES)
|
|
|
|
def tearDown(self):
|
|
if self.w._tw:
|
|
self.w._tw.close()
|
|
|
|
def events(self):
|
|
out = []
|
|
while not self.q.empty():
|
|
out.append(self.q.get_nowait())
|
|
return out
|
|
|
|
def test_a_quiet_tick_publishes_nothing(self):
|
|
self.w._tick()
|
|
self.assertEqual(self.events(), [])
|
|
self.assertEqual(self.ix.calls, [])
|
|
|
|
def test_a_write_is_published_with_its_id(self):
|
|
if self.w._tw is None:
|
|
self.skipTest("no inotify here")
|
|
with (self.src / "p" / "s1.jsonl").open("a") as fh:
|
|
fh.write("2\n")
|
|
(self.src / "p" / "s2").mkdir()
|
|
(self.src / "p" / "s2" / "agent.jsonl").write_text("1\n")
|
|
time.sleep(0.05)
|
|
self.w._tick()
|
|
self.assertEqual(self.ix.calls, [["p/s1.jsonl", "p/s2/agent.jsonl"]])
|
|
self.assertEqual(len(self.events()), 1)
|
|
|
|
def test_without_inotify_it_polls(self):
|
|
if self.w._tw:
|
|
self.w._tw.close()
|
|
self.w._tw = None
|
|
with (self.src / "p" / "s1.jsonl").open("a") as fh:
|
|
fh.write("2\n")
|
|
self.w._tick()
|
|
self.assertEqual(self.ix.calls, [["p/s1.jsonl"]])
|
|
|
|
def test_the_safety_rescan_catches_a_missed_write(self):
|
|
if self.w._tw is None:
|
|
self.skipTest("no inotify here")
|
|
self.w._tw.close() # no event can come in any more…
|
|
self.w._tw = fswatch.TreeWatch.open([str(TMP / "elsewhere")])
|
|
with (self.src / "p" / "s1.jsonl").open("a") as fh:
|
|
fh.write("2\n")
|
|
self.w._tick()
|
|
self.assertEqual(self.ix.calls, [])
|
|
self.w._full_at -= self.w.rescan_secs # …until the full rescan is due
|
|
self.w._tick()
|
|
self.assertEqual(self.ix.calls, [["p/s1.jsonl"]])
|
|
|
|
|
|
def _old_iter_files(ws: pathlib.Path):
|
|
"""The walk before it went string-first (what it must still return)."""
|
|
for dirpath, dirnames, filenames in os.walk(ws):
|
|
dirnames[:] = [d for d in dirnames if d not in discovery.IGNORE_DIRS]
|
|
for fn in filenames:
|
|
ap = pathlib.Path(dirpath) / fn
|
|
rel = pathlib.PurePosixPath(ap.relative_to(ws).as_posix())
|
|
if discovery._is_context_file(rel):
|
|
yield ap, rel
|
|
|
|
|
|
class WorkspaceTest(unittest.TestCase):
|
|
def setUp(self):
|
|
self.ws = pathlib.Path(tempfile.mkdtemp(dir=TMP))
|
|
for rel in ("CLAUDE.md", ".claude/skills/x/SKILL.md", ".claude/settings.json",
|
|
"data/plans/p.md", "data/shot.png", "data/tmp/secret.md",
|
|
"projects/a/CLAUDE.md", "projects/a/src/x.ts",
|
|
"projects/a/packages/b/CLAUDE.md", "projects/a/.claude/agents/r.md",
|
|
"projects/a/node_modules/c/CLAUDE.md", "projects/a/data/d.md",
|
|
"projects/b/.claude", "notes.md"):
|
|
p = self.ws / rel
|
|
p.parent.mkdir(parents=True, exist_ok=True)
|
|
p.write_text("x")
|
|
|
|
def test_the_walk_returns_what_it_used_to(self):
|
|
old = discovery.WORKSPACE
|
|
discovery.WORKSPACE = self.ws.resolve()
|
|
try:
|
|
new = list(discovery._iter_files())
|
|
finally:
|
|
discovery.WORKSPACE = old
|
|
self.assertEqual(new, list(_old_iter_files(self.ws.resolve())))
|
|
self.assertIn(pathlib.PurePosixPath("projects/a/packages/b/CLAUDE.md"),
|
|
[r for _a, r in new])
|
|
|
|
def test_the_watch_flags_context_files_only(self):
|
|
ww = discovery.WorkspaceWatch(self.ws)
|
|
ww.start()
|
|
if not until(lambda: ww.active):
|
|
self.skipTest("no inotify here")
|
|
self.assertTrue(until(ww.take)) # the start-up re-walk
|
|
old = discovery.WORKSPACE
|
|
discovery.WORKSPACE = self.ws.resolve()
|
|
try:
|
|
ww.known(list(discovery._iter_files()))
|
|
finally:
|
|
discovery.WORKSPACE = old
|
|
(self.ws / "projects" / "a" / "src" / "y.ts").write_text("x")
|
|
(self.ws / "projects" / "c" / "deep").mkdir(parents=True)
|
|
time.sleep(0.2)
|
|
self.assertFalse(ww.take()) # nothing it exposes
|
|
(self.ws / "projects" / "c" / "deep" / "CLAUDE.md").write_text("x")
|
|
self.assertTrue(until(ww.take)) # a CLAUDE.md in a new dir
|
|
(self.ws / "projects" / "a" / ".claude" / "agents" / "r.md").write_text("y")
|
|
time.sleep(0.2)
|
|
self.assertFalse(ww.take()) # an edit: the re-stat's job
|
|
os.rename(self.ws / "projects" / "a" / "packages", TMP / f"pk-{self.ws.name}")
|
|
self.assertTrue(until(ww.take)) # a dir that held one moved off
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|