Files
gabrielvidalandClaude Opus 5.5 aeadd836eb perf(watch): inotify instead of polling for the transcript watcher and the workspace walk
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>
2026-10-26 23:03:24 +01:00

274 lines
10 KiB
Python

"""inotify-backed directory-tree watching, with nothing to install.
The poll loops used to find the handful of files that moved by re-stat'ing
everything: the transcript watcher walked ~1 500 files every 2 s and the
workspace walk visited ~8 000 dirs (120 000 files) every 2 min — together
most of this service's idle CPU. A :class:`TreeWatch` asks the kernel
instead: one inotify watch per directory, new directories picked up as they
appear, and :meth:`TreeWatch.changes` hands back the paths that moved since
the last call.
Linux only (ctypes onto libc). :meth:`TreeWatch.open` returns None wherever
it can't work — no inotify, ``WATCH_INOTIFY=0`` — and a watch that hits the
per-user watch limit later turns itself off (``ok`` goes False): callers keep
their poll loop for both cases. A missed event can't be ruled out either (a
queue overflow, which ``changes`` reports), so every caller still runs a slow
full sweep behind it.
"""
import ctypes
import errno
import os
import select
import struct
IN_MODIFY = 0x00000002
IN_ATTRIB = 0x00000004
IN_CLOSE_WRITE = 0x00000008
IN_MOVED_FROM = 0x00000040
IN_MOVED_TO = 0x00000080
IN_CREATE = 0x00000100
IN_DELETE = 0x00000200
IN_DELETE_SELF = 0x00000400
IN_MOVE_SELF = 0x00000800
IN_UNMOUNT = 0x00002000
IN_Q_OVERFLOW = 0x00004000
IN_IGNORED = 0x00008000
IN_ONLYDIR = 0x01000000
IN_DONT_FOLLOW = 0x02000000
IN_EXCL_UNLINK = 0x04000000
IN_ISDIR = 0x40000000
# A file's content or mtime moved — what the transcript watcher wants on top
# of the entry events every watch carries.
FILE_CHANGES = IN_MODIFY | IN_CLOSE_WRITE | IN_ATTRIB
# Entries appearing / disappearing, and the dir itself going away.
_ENTRY = IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO
_SELF = IN_DELETE_SELF | IN_MOVE_SELF | IN_UNMOUNT
_FLAGS = IN_ONLYDIR | IN_DONT_FOLLOW | IN_EXCL_UNLINK
_HEADER = struct.Struct("iIII") # wd, mask, cookie, len — then the name
_O_NONBLOCK = 0o4000
_O_CLOEXEC = 0o2000000
_libc = None
def _lib():
"""libc's inotify entry points, or None (not Linux / not glibc-like)."""
global _libc
if _libc is None:
try:
lib = ctypes.CDLL(None, use_errno=True)
lib.inotify_init1.argtypes = [ctypes.c_int]
lib.inotify_add_watch.argtypes = [ctypes.c_int, ctypes.c_char_p,
ctypes.c_uint32]
lib.inotify_rm_watch.argtypes = [ctypes.c_int, ctypes.c_int]
_libc = lib
except (OSError, AttributeError):
_libc = False
return _libc or None
class WatchLimit(OSError):
"""The per-user inotify watch limit (``fs.inotify.max_user_watches``)."""
class TreeWatch:
"""inotify watches over every directory under ``roots``.
``prune(name)`` skips a directory (and its subtree) by name — what
``IGNORE_DIRS`` does to the workspace walk. ``file_mask`` adds per-file
events (:data:`FILE_CHANGES`) to the entry events every watch reports.
Symlinked dirs are not followed. A root that doesn't exist yet is picked
up by the first :meth:`changes` after it appears.
Single-threaded: one thread calls :meth:`wait` / :meth:`changes`."""
def __init__(self, fd: int, lib, roots, file_mask: int, prune):
self._fd = fd
self._lib = lib
self._mask = _ENTRY | _SELF | _FLAGS | file_mask
self._prune = prune or (lambda _name: False)
self.roots = [os.fspath(r).rstrip("/") or "/" for r in roots]
self._wd: dict[int, str] = {} # watch descriptor → dir path
self._root_wd: dict[str, int] = {} # root → its own wd
self.ok = True # False once the watch limit hit
self._found: set[str] = set() # files met while adding dirs
for r in self.roots:
self._add_root(r)
@classmethod
def open(cls, roots, file_mask: int = 0, prune=None) -> "TreeWatch | None":
if os.environ.get("WATCH_INOTIFY", "1") == "0":
return None
lib = _lib()
if lib is None:
return None
fd = lib.inotify_init1(_O_NONBLOCK | _O_CLOEXEC)
if fd < 0:
return None
tw = cls(fd, lib, roots, file_mask, prune)
if not tw.ok:
tw.close()
return None
tw._found.clear() # the initial tree isn't news
return tw
def fileno(self) -> int:
return self._fd
def close(self) -> None:
if self._fd >= 0:
os.close(self._fd)
self._fd = -1
@property
def watches(self) -> int:
return len(self._wd)
# ── adding watches ──────────────────────────────────────────────────
def _watch(self, path: str) -> int | None:
wd = self._lib.inotify_add_watch(self._fd, os.fsencode(path), self._mask)
if wd < 0:
err = ctypes.get_errno()
if err == errno.ENOSPC:
raise WatchLimit(err, "inotify watch limit reached")
return None # vanished, not a dir, unreadable: nothing to watch
self._wd[wd] = path
return wd
def _add_tree(self, top: str) -> int | None:
"""Watch ``top`` and every dir below it, noting the files met;
returns ``top``'s watch descriptor.
Each dir is watched *before* it is listed, so a file created in it
meanwhile is either listed or reported by its own event."""
stack = [top]
top_wd = None
try:
while stack:
d = stack.pop()
wd = self._watch(d)
if wd is None:
continue
if d == top:
top_wd = wd
try:
it = os.scandir(d)
except OSError:
continue
with it:
for e in it:
try:
if e.is_dir(follow_symlinks=False):
if not self._prune(e.name):
stack.append(e.path)
else:
self._found.add(e.path)
except OSError:
continue
except WatchLimit:
self.ok = False
return top_wd
def _add_root(self, root: str) -> None:
if not os.path.isdir(root):
return
wd = self._add_tree(root)
if wd is not None:
self._root_wd[root] = wd
def _drop_under(self, path: str) -> None:
"""Forget (and unwatch) ``path`` and everything below it — a dir
moved away keeps its watches, which would report the old paths."""
pre = path + "/"
for wd, p in list(self._wd.items()):
if p == path or p.startswith(pre):
self._lib.inotify_rm_watch(self._fd, wd)
self._wd.pop(wd, None)
# ── reading ─────────────────────────────────────────────────────────
def wait(self, timeout: float | None) -> bool:
"""Block until events are queued (True) or ``timeout`` s pass."""
if self._fd < 0:
return False
p = select.poll() # not select(): this process can hold fds > 1024
p.register(self._fd, select.POLLIN)
try:
return bool(p.poll(None if timeout is None else timeout * 1000))
except OSError:
return False
def _read(self) -> list[tuple[int, int, str]]:
out = []
while True:
try:
buf = os.read(self._fd, 64 * 1024)
except BlockingIOError:
break
except OSError:
break
if not buf:
break
off = 0
while off + _HEADER.size <= len(buf):
wd, mask, _cookie, n = _HEADER.unpack_from(buf, off)
off += _HEADER.size
name = buf[off:off + n].split(b"\0", 1)[0]
off += n
out.append((wd, mask, os.fsdecode(name)))
return out
def changes(self) -> tuple[set[str], bool]:
"""``(paths, lost)`` since the last call, without blocking.
``paths``: files whose entry or (with ``file_mask``) content changed,
files found in directories that appeared (new dirs are watched on the
spot), and directories that went away. ``lost``: the kernel dropped
events (queue overflow) — the caller must rescan. The tree's watches
are re-added on overflow, so the watch itself recovers."""
lost = False
paths: set[str] = set()
for wd, mask, name in self._read():
if mask & IN_Q_OVERFLOW:
lost = True
continue
d = self._wd.get(wd)
if mask & IN_IGNORED:
self._wd.pop(wd, None)
for r, rwd in list(self._root_wd.items()):
if rwd == wd:
del self._root_wd[r] # re-added once it exists again
continue
if d is None:
continue
if mask & _SELF and not name:
if mask & IN_MOVE_SELF and d in self._root_wd:
self._drop_under(d)
self._root_wd.pop(d, None)
continue
p = os.path.join(d, name) if name else d
if mask & IN_ISDIR:
if mask & (IN_CREATE | IN_MOVED_TO):
if not self._prune(name):
self._add_tree(p)
elif mask & IN_MOVED_FROM:
self._drop_under(p)
paths.add(p)
elif mask & IN_DELETE:
paths.add(p)
continue
paths.add(p)
if lost:
for r in self.roots: # dirs created while events were dropped
self._add_root(r)
self._found = set() # the caller rescans everything anyway
return set(), True
for r in self.roots: # a root that appeared (or came back) since
if r not in self._root_wd and os.path.isdir(r):
self._add_root(r)
paths |= self._found
self._found = set()
return paths, False