Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
fs: Preserve child watches when removing parent subscriptions (#65998)
Anthony Eid9e84b066b55b
diff --git a/crates/fs/src/fs_watcher.rs b/crates/fs/src/fs_watcher.rsindex b17969d6fe9..c9c75fb2cc8 100644--- a/crates/fs/src/fs_watcher.rs+++ b/crates/fs/src/fs_watcher.rs@@ -3,7 +3,7 @@ use gpui::{BackgroundExecutor, Task};use notify::{Event, EventKind};use parking_lot::Mutex;use std::{- collections::HashMap,+ collections::{BTreeSet, HashMap},ops::DerefMut,path::Path,pin::Pin,@@ -541,7 +541,7 @@ fn path_is_under(path: &SanitizedPath, root: &SanitizedPath, case_insensitive: b////// Folded keys use path-component spelling so separators and `.` components/// agree with exact path equality. macOS also normalizes Unicode before folding.-#[derive(Clone, Debug, PartialEq, Eq, Hash)]+#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]enum WatchKey {Exact(Arc<Path>),Folded(Arc<str>),@@ -790,6 +790,10 @@ fn coalesce_pending_rescans(pending_paths: &mut Vec<PathEvent>, path_events: &mu});}+fn path_depth(path: &SanitizedPath) -> usize {+ path.as_path().components().count()+}+fn is_covered_rescan(kind: Option<PathEventKind>, path: &Path, ancestor: &Path) -> bool {kind == Some(PathEventKind::Rescan) && path != ancestor && path.starts_with(ancestor)}@@ -800,15 +804,28 @@ pub struct WatcherRegistrationId(u32);struct WatcherRegistrationState {callback: Arc<dyn Fn(¬ify::Event) + Send + Sync>,key: WatchKey,- path: Arc<SanitizedPath>,}struct PathRegistrationState {+ path: Arc<SanitizedPath>,+ /// Empty while a backend watch is retained for covered descendants that+ /// could not get their own backend watch.watcher_ids: Vec<WatcherRegistrationId>,- has_os_watcher: bool,+ coverage: Coverage,stale: bool,}+enum Coverage {+ /// Has its own backend watch. On recursive backends, that watch also+ /// serves the descendant registrations listed here by [`path_depth`] and+ /// key, so promotion proceeds shallowest first without re-sorting.+ Watched {+ covered: BTreeSet<(usize, WatchKey)>,+ },+ /// Served by the recursive backend watch of this ancestor registration.+ CoveredBy(WatchKey),+}+/// The registered watch paths for one backend, keyed by [`WatchKey`] so that/// add (dedup), remove, and dispatch share a single notion of path identity.#[derive(Default)]@@ -823,30 +840,31 @@ impl WatchPaths {self.0.get_mut(key)}- fn entry(- &mut self,- key: WatchKey,- ) -> std::collections::hash_map::Entry<'_, WatchKey, PathRegistrationState> {- self.0.entry(key)- }-- fn remove(&mut self, key: &WatchKey) {- self.0.remove(key);- }-- /// True if a recursive registration on a strict ancestor already covers- /// `path`. Only poll watches and native macOS/Windows watches are recursive.- fn covered_by_recursive_ancestor(&self, path: &SanitizedPath, recursive: bool) -> bool {+ /// The nearest strict ancestor whose recursive backend watch covers `path`.+ /// Only poll watches and native macOS/Windows watches are recursive.+ fn covering_ancestor(&self, path: &SanitizedPath, recursive: bool) -> Option<WatchKey> {if !recursive {- return false;+ return None;}- path.as_path().ancestors().skip(1).any(|ancestor| {+ path.as_path().ancestors().skip(1).find_map(|ancestor| {let ancestor = SanitizedPath::unchecked_new(ancestor);- self.0.contains_key(&WatchKey::exact(ancestor))- || self.0.contains_key(&WatchKey::folded(ancestor))+ [WatchKey::exact(ancestor), WatchKey::folded(ancestor)]+ .into_iter()+ .find(|key| {+ self.0.get(key).is_some_and(|registration| {+ matches!(registration.coverage, Coverage::Watched { .. })+ })+ })})}+ fn covered_by_mut(&mut self, key: &WatchKey) -> Option<&mut BTreeSet<(usize, WatchKey)>> {+ match &mut self.0.get_mut(key)?.coverage {+ Coverage::Watched { covered } => Some(covered),+ Coverage::CoveredBy(_) => None,+ }+ }+/// Collects the watcher ids of every registration whose directory is an/// ancestor of (or equal to) `path`. Both exact and folded keys are probed,/// so a real-cased event path matches a folded registration and vice versa.@@ -886,20 +904,6 @@ impl WatcherState {);}}-- fn remove_registration(&mut self, id: WatcherRegistrationId) -> Option<Arc<SanitizedPath>> {- let registration_state = self.watchers.remove(&id)?;- let path_state = self.paths.get_mut(®istration_state.key)?;- path_state.watcher_ids.retain(|&existing| existing != id);- if !path_state.watcher_ids.is_empty() {- return None;- }-- let was_actually_watched = path_state.has_os_watcher;- self.paths.remove(®istration_state.key);-- was_actually_watched.then_some(registration_state.path)- }}pub(crate) trait WatchBackend: Send {@@ -1012,14 +1016,12 @@ impl OsWatcher {let path = SanitizedPath::from_arc(path);let key = WatchKey::for_registration(&path, case_insensitive);let mut state = self.state.lock();- let path_already_covered = state- .paths- .covered_by_recursive_ancestor(&path, self.recursive);- let path_already_registered = state.paths.contains(&key);-- if path_already_registered {+ let new_coverage = if state.paths.contains(&key) {self.rewatch_if_stale(&mut state, &path, &key)?;- } else if !path_already_covered {+ None+ } else if let Some(ancestor) = state.paths.covering_ancestor(&path, self.recursive) {+ Some(Coverage::CoveredBy(ancestor))+ } else {if self.kind == OsWatcherKind::Native && state.is_native_watch_limit_cooldown_active() {self.diagnostics.record(|| {WatchDiagnosticEvent::new(@@ -1044,7 +1046,10 @@ impl OsWatcher {}Err(error) => return Err(error),}- }+ Some(Coverage::Watched {+ covered: BTreeSet::new(),+ })+ };let id = state.last_registration;state.last_registration = WatcherRegistrationId(id.0 + 1);@@ -1052,18 +1057,31 @@ impl OsWatcher {let registration_state = WatcherRegistrationState {callback: Arc::new(cb),key: key.clone(),- path,};state.watchers.insert(id, registration_state);- state- .paths- .entry(key)- .and_modify(|registration| registration.watcher_ids.push(id))- .or_insert_with(|| PathRegistrationState {- watcher_ids: vec![id],- has_os_watcher: !path_already_covered,- stale: false,- });+ match new_coverage {+ None => {+ if let Some(registration) = state.paths.get_mut(&key) {+ registration.watcher_ids.push(id);+ }+ }+ Some(coverage) => {+ if let Coverage::CoveredBy(ancestor) = &coverage+ && let Some(covered) = state.paths.covered_by_mut(ancestor)+ {+ covered.insert((path_depth(&path), key.clone()));+ }+ state.paths.0.insert(+ key,+ PathRegistrationState {+ path,+ watcher_ids: vec![id],+ coverage,+ stale: false,+ },+ );+ }+ }Ok(Some(id))}@@ -1112,10 +1130,114 @@ impl OsWatcher {pub fn remove(&self, id: WatcherRegistrationId) {let mut state = self.state.lock();- let Some(path) = state.remove_registration(id) else {+ let Some(registration) = state.watchers.remove(&id) else {return;};- self.unwatch(path.as_path()).log_err();+ let key = registration.key;+ let Some(path_state) = state.paths.get_mut(&key) else {+ return;+ };+ path_state.watcher_ids.retain(|&existing| existing != id);+ if !path_state.watcher_ids.is_empty() {+ return;+ }+ match &path_state.coverage {+ Coverage::Watched { .. } => self.release_watch(&mut state, key),+ Coverage::CoveredBy(ancestor) => {+ let ancestor = ancestor.clone();+ let covered_entry = (path_depth(&path_state.path), key);+ state.paths.0.remove(&covered_entry.1);+ let Some(ancestor_state) = state.paths.get_mut(&ancestor) else {+ return;+ };+ let retained = ancestor_state.watcher_ids.is_empty();+ let Coverage::Watched { covered } = &mut ancestor_state.coverage else {+ return;+ };+ // A retained watch stopped at its shallowest covered registration,+ // so only that registration leaving can unblock its release.+ let blocked_release = covered.first() == Some(&covered_entry);+ covered.remove(&covered_entry);+ if retained && blocked_release {+ self.release_watch(&mut state, ancestor);+ }+ }+ }+ }++ /// Unwatches the unused backend watch at `key` once every registration it+ /// covers is served by another watch.+ ///+ /// Replacements are installed shallowest first, so one can cover deeper+ /// registrations. If one cannot be installed, the watch is retained for+ /// the registrations still covered by it, and is reconsidered when the one+ /// that could not be promoted is removed.+ fn release_watch(&self, state: &mut WatcherState, key: WatchKey) {+ // Exclude this watch from coverage checks while it stays installed.+ let Some(mut released) = state.paths.0.remove(&key) else {+ return;+ };+ let mut pending = match &mut released.coverage {+ Coverage::Watched { covered } => std::mem::take(covered),+ Coverage::CoveredBy(_) => {+ state.paths.0.insert(key, released);+ return;+ }+ };+ while let Some((depth, covered_key)) = pending.pop_first() {+ let Some(covered_path) = state+ .paths+ .0+ .get(&covered_key)+ .map(|registration| registration.path.clone())+ else {+ continue;+ };+ let coverage = match state.paths.covering_ancestor(&covered_path, self.recursive) {+ Some(ancestor) => {+ if let Some(covered) = state.paths.covered_by_mut(&ancestor) {+ covered.insert((depth, covered_key.clone()));+ }+ Coverage::CoveredBy(ancestor)+ }+ None if self.watch_replacement(state, &covered_path) => Coverage::Watched {+ covered: BTreeSet::new(),+ },+ None => {+ pending.insert((depth, covered_key));+ released.coverage = Coverage::Watched { covered: pending };+ state.paths.0.insert(key, released);+ return;+ }+ };+ if let Some(registration) = state.paths.get_mut(&covered_key) {+ registration.coverage = coverage;+ registration.stale = false;+ }+ }++ // Forget the watch even if unwatching fails: notify can report failure+ // after dropping the watch (FSEvents restarts its stream afterwards), so+ // a later registration of this path must install a fresh watch.+ self.unwatch(released.path.as_path()).log_err();+ }++ fn watch_replacement(&self, state: &mut WatcherState, path: &SanitizedPath) -> bool {+ if self.kind == OsWatcherKind::Native && state.is_native_watch_limit_cooldown_active() {+ return false;+ }+ match self.watch(path.as_path()) {+ Ok(()) => true,+ Err(error) => {+ if self.kind == OsWatcherKind::Native && is_max_files_watch_error(&error) {+ state.start_native_watch_limit_cooldown(path.as_path());+ }+ log::error!(+ "failed to restore watch for {path:?}; retaining its covering watch: {error:#}"+ );+ false+ }+ }}fn watch(&self, path: &Path) -> anyhow::Result<()> {@@ -1424,7 +1546,10 @@ mod tests {watched_paths: HashSet<PathBuf>,watch_calls: Vec<PathBuf>,unwatch_calls: Vec<PathBuf>,+ operations: Vec<(&'static str, PathBuf)>,fail_with_watch_limit: bool,+ failed_paths: HashSet<PathBuf>,+ failed_unwatch_paths: HashSet<PathBuf>,}struct SharedFakeWatchBackend(Arc<Mutex<FakeWatchBackend>>);@@ -1434,9 +1559,13 @@ mod tests {let path = path.to_path_buf();let mut backend = self.0.lock();backend.watch_calls.push(path.clone());+ backend.operations.push(("watch", path.clone()));if backend.fail_with_watch_limit {return Err(notify::Error::new(notify::ErrorKind::MaxFilesWatch));}+ if backend.failed_paths.contains(&path) {+ return Err(notify::Error::generic("injected watch failure"));+ }backend.watched_paths.insert(path);Ok(())}@@ -1445,11 +1574,15 @@ mod tests {let path = path.to_path_buf();let mut backend = self.0.lock();backend.unwatch_calls.push(path.clone());- if backend.watched_paths.remove(&path) {- Ok(())- } else {- Err(notify::Error::generic("path was not watched"))+ backend.operations.push(("unwatch", path.clone()));+ if !backend.watched_paths.remove(&path) {+ return Err(notify::Error::watch_not_found());}+ // Like FSEvents failing to restart its stream after removing the path.+ if backend.failed_unwatch_paths.contains(&path) {+ return Err(notify::Error::generic("injected unwatch failure"));+ }+ Ok(())}}@@ -1506,7 +1639,7 @@ mod tests {}#[test]- fn covered_child_registration_is_not_unwatched_after_parent_is_removed() {+ fn covered_child_registration_is_promoted_before_parent_is_unwatched() {let backend = Arc::new(Mutex::new(FakeWatchBackend::default()));let watcher = test_os_watcher(OsWatcherKind::Poll, Some(backend.clone()));let parent = Arc::<Path>::from(Path::new("/repo"));@@ -1522,11 +1655,221 @@ mod tests {.expect("child watch registered");watcher.remove(parent_registration);+ assert_eq!(+ backend.lock().watched_paths,+ HashSet::from([child.to_path_buf()])+ );+ assert_eq!(+ backend.lock().operations,+ [+ ("watch", parent.to_path_buf()),+ ("watch", child.to_path_buf()),+ ("unwatch", parent.to_path_buf()),+ ]+ );watcher.remove(child_registration);let backend = backend.lock();- assert_eq!(backend.watch_calls, &[parent.to_path_buf()]);- assert_eq!(backend.unwatch_calls, &[parent.to_path_buf()]);+ assert_eq!(+ backend.watch_calls,+ &[parent.to_path_buf(), child.to_path_buf()]+ );+ assert_eq!(+ backend.unwatch_calls,+ &[parent.to_path_buf(), child.to_path_buf()]+ );+ assert!(backend.watched_paths.is_empty());+ assert!(watcher.state.lock().paths.0.is_empty());+ }++ #[test]+ fn promoted_ancestor_covers_deeper_subscribers() {+ let backend = Arc::new(Mutex::new(FakeWatchBackend::default()));+ let watcher = test_os_watcher(OsWatcherKind::Poll, Some(backend.clone()));+ let root = watcher+ .add(Path::new("/repo").into(), true, |_| {})+ .expect("watch root")+ .expect("registered root");+ // Several deeper subscribers make an unordered promotion unlikely to+ // reach the shallowest one first by chance.+ let deep = (0..8)+ .map(|index| {+ watcher+ .add(+ PathBuf::from(format!("/repo/child/deep{index}")).into(),+ true,+ |_| {},+ )+ .expect("watch deep")+ .expect("registered deep")+ })+ .collect::<Vec<_>>();+ let child = watcher+ .add(Path::new("/repo/child").into(), true, |_| {})+ .expect("watch child")+ .expect("registered child");+ watcher.remove(root);+ assert_eq!(+ backend.lock().watched_paths,+ HashSet::from([PathBuf::from("/repo/child")])+ );+ assert_eq!(backend.lock().watch_calls.len(), 2);+ watcher.remove(child);+ assert_eq!(backend.lock().watched_paths.len(), deep.len());+ for deep in deep {+ watcher.remove(deep);+ }+ assert!(backend.lock().watched_paths.is_empty());+ assert!(watcher.state.lock().paths.0.is_empty());+ }++ #[test]+ fn failed_promotion_retains_coverage_without_retaining_removed_callback() {+ let backend = Arc::new(Mutex::new(FakeWatchBackend::default()));+ let watcher = test_os_watcher(OsWatcherKind::Poll, Some(backend.clone()));+ let (parent_fired, parent_callback) = fired_count();+ let (child_fired, child_callback) = fired_count();+ let parent = watcher+ .add(Path::new("/repo").into(), false, parent_callback)+ .expect("watch parent")+ .expect("registered parent");+ let child = watcher+ .add(Path::new("/repo/child").into(), false, child_callback)+ .expect("watch child")+ .expect("registered child");+ backend+ .lock()+ .failed_paths+ .insert(PathBuf::from("/repo/child"));++ watcher.remove(parent);+ assert_eq!(+ backend.lock().watched_paths,+ HashSet::from([PathBuf::from("/repo")])+ );+ watcher.dispatch(Ok(modify_event("/repo/child/file")));+ assert_eq!(*parent_fired.lock(), 0);+ assert_eq!(*child_fired.lock(), 1);++ watcher.remove(child);+ assert!(backend.lock().watched_paths.is_empty());+ assert!(watcher.state.lock().paths.0.is_empty());+ }++ #[cfg(target_os = "macos")]+ #[test]+ fn native_child_delivery_survives_parent_removal() {+ let directory = tempfile::tempdir().expect("temporary directory");+ let root = directory.path().canonicalize().expect("canonical root");+ let child = root.join("child");+ std::fs::create_dir(&child).expect("create child");+ let executor = BackgroundExecutor::new(Arc::new(gpui::TestDispatcher::new(0)));+ let watcher = OsWatcher::new(OsWatcherKind::Native, executor.clone());+ let parent = watcher+ .add(root.as_path().into(), false, |_| {})+ .expect("watch parent")+ .expect("registered parent");+ let (sender, receiver) = std::sync::mpsc::channel();+ watcher+ .add(child.as_path().into(), false, move |event| {+ sender.send(event.clone()).expect("receiver alive");+ })+ .expect("watch child")+ .expect("registered child");+ std::thread::sleep(Duration::from_millis(500));+ for phase in ["before", "after"] {+ if phase == "after" {+ watcher.remove(parent);+ }+ let file = child.join(phase);+ std::fs::write(&file, b"probe").expect("write probe");+ let deadline = Instant::now() + Duration::from_secs(5);+ loop {+ executor.run_until_parked();+ if receiver.try_iter().any(|event| event.paths.contains(&file)) {+ break;+ }+ assert!(Instant::now() < deadline, "missing {phase} event");+ std::thread::sleep(Duration::from_millis(20));+ }+ }+ }++ #[test]+ fn partial_promotion_releases_retained_parent_when_failed_subscriber_leaves() {+ let backend = Arc::new(Mutex::new(FakeWatchBackend::default()));+ let watcher = test_os_watcher(OsWatcherKind::Poll, Some(backend.clone()));+ let registrations = [+ "/repo",+ "/repo/a",+ "/repo/other/deep",+ "/unrelated",+ "/repo/other/deep/deeper",+ ]+ .map(|path| {+ watcher+ .add(Path::new(path).into(), false, |_| {})+ .expect("watch")+ .expect("registered")+ });+ backend+ .lock()+ .failed_paths+ .insert(PathBuf::from("/repo/other/deep"));+ watcher.remove(registrations[0]);+ assert_eq!(+ backend.lock().watched_paths,+ HashSet::from([+ PathBuf::from("/repo"),+ PathBuf::from("/repo/a"),+ PathBuf::from("/unrelated")+ ])+ );+ // Only removing the registration that blocked promotion retries it.+ let watch_calls = backend.lock().watch_calls.len();+ watcher.remove(registrations[3]);+ watcher.remove(registrations[1]);+ watcher.remove(registrations[4]);+ assert_eq!(backend.lock().watch_calls.len(), watch_calls);+ assert_eq!(+ backend.lock().watched_paths,+ HashSet::from([PathBuf::from("/repo")])+ );++ watcher.remove(registrations[2]);+ assert!(backend.lock().watched_paths.is_empty());+ assert!(watcher.state.lock().paths.0.is_empty());+ }++ #[test]+ fn failed_unwatch_is_not_trusted_when_path_is_registered_again() {+ for kind in [OsWatcherKind::Native, OsWatcherKind::Poll] {+ let backend = Arc::new(Mutex::new(FakeWatchBackend::default()));+ let watcher = test_os_watcher(kind, Some(backend.clone()));+ let path = PathBuf::from("/repo");+ backend.lock().failed_unwatch_paths.insert(path.clone());++ let registration = watcher+ .add(path.as_path().into(), false, |_| {})+ .expect("watch")+ .expect("registered");+ watcher.remove(registration);+ assert!(backend.lock().watched_paths.is_empty());+ assert!(watcher.state.lock().paths.0.is_empty());++ let registration = watcher+ .add(path.as_path().into(), false, |_| {})+ .expect("watch again")+ .expect("registered again");+ assert_eq!(backend.lock().watch_calls, [path.clone(), path.clone()]);+ assert_eq!(backend.lock().watched_paths, HashSet::from([path.clone()]));++ // The backend already dropped this watch, as inotify does when a+ // watched directory is deleted.+ backend.lock().watched_paths.clear();+ watcher.remove(registration);+ assert!(watcher.state.lock().paths.0.is_empty());+ }}#[gpui::test]diff --git a/crates/fs/src/fs_watcher/diagnostics.rs b/crates/fs/src/fs_watcher/diagnostics.rsindex aae768c935c..6a883c17a8f 100644--- a/crates/fs/src/fs_watcher/diagnostics.rs+++ b/crates/fs/src/fs_watcher/diagnostics.rs@@ -1,4 +1,4 @@-use super::{OsWatcher, OsWatcherKind};+use super::{Coverage, OsWatcher, OsWatcherKind};use parking_lot::Mutex;use serde::Serialize;use std::{@@ -40,6 +40,7 @@ pub struct WatcherSnapshot {#[derive(Clone, Debug, Serialize)]pub struct WatchRoot {pub path: String,+ /// Zero when the backend watch is retained only for covered descendants.pub registrations: usize,}@@ -188,13 +189,10 @@ impl WatchRecording {.paths.0.values()- .filter(|path| path.has_os_watcher)- .filter_map(|path| {- let registration = state.watchers.get(path.watcher_ids.first()?)?;- Some(WatchRoot {- path: registration.path.as_path().to_string_lossy().into_owned(),- registrations: path.watcher_ids.len(),- })+ .filter(|path| matches!(path.coverage, Coverage::Watched { .. }))+ .map(|path| WatchRoot {+ path: path.path.as_path().to_string_lossy().into_owned(),+ registrations: path.watcher_ids.len(),}).collect();roots.sort_by(|left, right| left.path.cmp(&right.path));@@ -392,4 +390,28 @@ mod tests {assert_eq!(snapshot.events[1].operation, "unwatch_error");assert!(snapshot.events[1].detail.contains("unwatch failed"));}++ #[gpui::test]+ fn recording_snapshots_retained_roots_without_registrations(cx: &TestAppContext) {+ let watcher = watcher(OsWatcherKind::Poll, cx);+ let root = util::path!("/root");+ let registration = watcher+ .add(Path::new(root).into(), false, |_| {})+ .unwrap()+ .unwrap();+ let covered = watcher+ .add(Path::new(util::path!("/root/fail")).into(), false, |_| {})+ .unwrap()+ .unwrap();+ let recording = WatchRecording::new([watcher.clone()]);++ watcher.remove(registration);+ let roots = &recording.snapshot().watchers[0].roots;+ assert_eq!(roots.len(), 1);+ assert_eq!(roots[0].path, root);+ assert_eq!(roots[0].registrations, 0);++ watcher.remove(covered);+ assert!(recording.snapshot().watchers[0].roots.is_empty());+ }}