diff --git a/crates/ide-host/src/lib.rs b/crates/ide-host/src/lib.rs index 453ee66201..9365a59dfb 100644 --- a/crates/ide-host/src/lib.rs +++ b/crates/ide-host/src/lib.rs @@ -31,6 +31,7 @@ pub mod relay; mod requests; pub mod rpc; pub mod shell_env; +pub(crate) mod singleflight; pub mod svn; mod swiftlint; pub mod trust; diff --git a/crates/ide-host/src/ops/project.rs b/crates/ide-host/src/ops/project.rs index 97d14ed87f..5d44c0c650 100644 --- a/crates/ide-host/src/ops/project.rs +++ b/crates/ide-host/src/ops/project.rs @@ -223,6 +223,7 @@ pub fn project_workspace_member_set( p.settings.reload(); p.sink.emit(IdeEvent::SettingsChanged { key: key.clone() }); } + p.invalidate_scans(); p.refresh_index_scope(); p.sink.emit(IdeEvent::ProjectRootsChanged { root: p.root.clone().into() }); } @@ -279,6 +280,7 @@ pub fn save_workspace(host: &Host, window: &str, name: &str, paths: Vec IdeResult> { host.require_trust(window)?; let project = host.project(window)?; - if let Some(plugins) = host.plugin_host() { - plugins.refresh_run_configurations(&project.root); - } - project_configs(&project.root, &project.settings.effective(), &host.config_dir) + project.run_configs_flight.run( + |epoch| epoch, + || { + if let Some(plugins) = host.plugin_host() { + plugins.refresh_run_configurations(&project.root); + } + project_configs(&project.root, &project.settings.effective(), &host.config_dir) + }, + ) } pub(super) fn project_configs( @@ -212,7 +217,9 @@ pub fn save_configs( _ => ide_sdk::apply::without_derived(c, &project.root, &settings), }) .collect(); - ide_run::save_user_configs_with_removals(&project.root, &configs, removed_detected_ids) + let result = ide_run::save_user_configs_with_removals(&project.root, &configs, removed_detected_ids); + project.run_configs_flight.invalidate(); + result } /// The project `config` runs in (a workspace member, by its working directory) and its diff --git a/crates/ide-host/src/ops/sdk.rs b/crates/ide-host/src/ops/sdk.rs index 967d764e6f..ed4547b08e 100644 --- a/crates/ide-host/src/ops/sdk.rs +++ b/crates/ide-host/src/ops/sdk.rs @@ -321,51 +321,76 @@ pub async fn sdk_project_libraries( let (root, cache, settings) = (project.root.clone(), project.build_cache_dir(), project.settings.effective()); let cancel = host.begin_project_request(window, request); let container = container_python::library_group(host, &root, &settings); - let libraries = { - let (root, settings, cancel, on_groups) = (root.clone(), settings.clone(), cancel.clone(), on_groups.clone()); - tokio::task::spawn_blocking(move || { - if let Some(group) = &container { - let _ = on_groups.send(vec![group.clone()]); - } - let groups = ide_sdk::libraries::project_libraries_stream(&root, &settings, &[], &cancel, &|groups| { - let _ = on_groups.send(groups); - }); - container.into_iter().chain(groups).collect::>() - }) - }; - let dependencies = { - let cancel = cancel.clone(); - tokio::task::spawn_blocking(move || { - if cancel.is_cancelled() { - return Vec::new(); - } - let model = crate::ops::build::load(&root, &cache, &settings); - let deps: Vec = ide_build::dependency_coordinates(&root, &model) - .into_iter() - .map(|c| ide_sdk::libraries::BuildDependency { - gradle: c.gradle, - group: c.group_id, - artifact: c.artifact_id, - version: c.version, - }) - .collect(); - if cancel.is_cancelled() { - return Vec::new(); - } - let groups = ide_sdk::libraries::dependency_groups(&root, &settings, &deps); - if !cancel.is_cancelled() { - let _ = on_groups.send(groups.clone()); - } - groups - }) - }; - let (libraries, dependencies) = tokio::join!(libraries, dependencies); + let settings_key = serde_json::to_string(&(&settings.languages, &settings.project_structure)).unwrap_or_default(); + let result = project + .libraries_flight + .run( + |epoch| (epoch, settings_key.clone()), + &cancel, + on_groups, + |leader_cancel, fanout| { + let (root, cache, settings, container) = + (root.clone(), cache.clone(), settings.clone(), container.clone()); + async move { + let libraries = { + let (root, settings, cancel, on_groups) = + (root.clone(), settings.clone(), leader_cancel.clone(), fanout.clone()); + tokio::task::spawn_blocking(move || { + if let Some(group) = &container { + let _ = on_groups.send(vec![group.clone()]); + } + let groups = ide_sdk::libraries::project_libraries_stream( + &root, + &settings, + &[], + &cancel, + &|groups| { + let _ = on_groups.send(groups); + }, + ); + container.into_iter().chain(groups).collect::>() + }) + }; + let dependencies = { + let cancel = leader_cancel.clone(); + tokio::task::spawn_blocking(move || { + if cancel.is_cancelled() { + return Vec::new(); + } + let model = crate::ops::build::load(&root, &cache, &settings); + let deps: Vec = + ide_build::dependency_coordinates(&root, &model) + .into_iter() + .map(|c| ide_sdk::libraries::BuildDependency { + gradle: c.gradle, + group: c.group_id, + artifact: c.artifact_id, + version: c.version, + }) + .collect(); + if cancel.is_cancelled() { + return Vec::new(); + } + let groups = ide_sdk::libraries::dependency_groups(&root, &settings, &deps); + if !cancel.is_cancelled() { + let _ = fanout.send(groups.clone()); + } + groups + }) + }; + let (libraries, dependencies) = tokio::join!(libraries, dependencies); + if leader_cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + Ok(ide_sdk::libraries::merge_groups( + [libraries.map_err(join_error)?, dependencies.map_err(join_error)?].concat(), + )) + } + }, + ) + .await; host.end_request(request); - if cancel.is_cancelled() { - return Err(IdeError::cancelled()); - } - let groups = - ide_sdk::libraries::merge_groups([libraries.map_err(join_error)?, dependencies.map_err(join_error)?].concat()); + let groups = result?; if host.project(window).is_ok_and(|current| std::sync::Arc::ptr_eq(¤t, &project)) { host.mcp_reports .set_libraries(window, groups.iter().flat_map(|g| g.roots.iter().map(|r| r.path.0.clone())).collect()); diff --git a/crates/ide-host/src/ops/vcs.rs b/crates/ide-host/src/ops/vcs.rs index deb7238249..d277f34414 100644 --- a/crates/ide-host/src/ops/vcs.rs +++ b/crates/ide-host/src/ops/vcs.rs @@ -2,12 +2,57 @@ use crate::Host; use ide_command::command; use ide_core::IdeResult; use ide_vcs::FileStatus; +use std::path::{Path, PathBuf}; +use std::time::SystemTime; + +type FileStamp = Option<(SystemTime, u64)>; + +/// State fingerprint for coalescing concurrent full `vcs_status` scans. +/// Captures the per-project invalidation epoch plus each repository's `index`, +/// `HEAD`, and `packed-refs` stamps so mutations (including external `git` writes +/// before FSEvents debounces) never join an older in-flight walk. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct VcsStatusKey { + epoch: u64, + repos: Vec<(PathBuf, FileStamp, FileStamp, FileStamp)>, + backends: Vec, +} + +fn file_stamp(path: &Path) -> FileStamp { + let meta = std::fs::metadata(path).ok()?; + Some((meta.modified().ok()?, meta.len())) +} + +fn vcs_status_key(project: &crate::Project, epoch: u64) -> VcsStatusKey { + let repos = project + .repos() + .all() + .iter() + .map(|repo| { + let (index, head, packed) = match repo.metadata_dirs() { + Ok([git_dir, common_dir]) => ( + file_stamp(&git_dir.join("index")), + file_stamp(&git_dir.join("HEAD")), + file_stamp(&common_dir.join("packed-refs")), + ), + Err(_) => (None, None, None), + }; + (repo.root().to_path_buf(), index, head, packed) + }) + .collect(); + let backends = project.backends().iter().map(|b| b.root().to_path_buf()).collect(); + VcsStatusKey { epoch, repos, backends } +} + +fn coalesced_full_status(project: &crate::Project) -> IdeResult> { + project.vcs_status_flight.run(|epoch| vcs_status_key(project, epoch), || merged_status(project, None)) +} /// Changes of every repository of the project. #[command(trust = always)] pub async fn vcs_status(host: &Host, window: &str) -> IdeResult> { let project = host.project(window)?; - host.blocking(move || merged_status(&project, None)).await + host.blocking(move || coalesced_full_status(&project)).await } #[command(trust = always)] @@ -30,7 +75,10 @@ pub async fn vcs_ignored_files(host: &Host, window: &str) -> IdeResult) -> IdeResult> { // `paths` that belong to no repository are ignored, and an empty list is the full status. let project = host.project(window)?; - host.blocking(move || merged_status(&project, Some(&paths))).await + host.blocking(move || { + if paths.is_empty() { coalesced_full_status(&project) } else { merged_status(&project, Some(&paths)) } + }) + .await } /// The last status failure said for each working copy root (see [`merged_status`]). @@ -195,3 +243,49 @@ fn check_worktree_away_from_project( } ide_command::domain!(vcs: vcs_status, vcs_status_paths, vcs_ignored_files); + +#[cfg(test)] +mod tests { + use super::*; + use std::process::Command; + use std::sync::Arc; + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn vcs_status_key_tracks_git_index_and_concurrent_status_succeeds() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join("repo"); + std::fs::create_dir_all(&root).unwrap(); + assert!(Command::new("git").args(["init", "-q"]).current_dir(&root).status().unwrap().success()); + std::fs::write(root.join("a.txt"), "hello\n").unwrap(); + + let host = Arc::new(crate::Host::new(crate::HostConfig::for_test(&tmp.path().join("host")))); + let project = host.open_project("main", &root).unwrap(); + host.set_project_trust(&root, true, false).await.unwrap(); + + let key_before = vcs_status_key(&project, project.vcs_status_flight.epoch()); + let (r1, r2) = tokio::join!(vcs_status(&host, "main"), vcs_status(&host, "main")); + let s1 = r1.unwrap(); + let s2 = r2.unwrap(); + assert_eq!(s1.len(), 1); + assert_eq!(s1[0].rel_path, "a.txt"); + assert_eq!(s2.len(), 1); + assert_eq!(s2[0].rel_path, "a.txt"); + + // Staging modifies `.git/index`, changing `vcs_status_key` immediately without waiting for FSEvents. + assert!(Command::new("git").args(["add", "a.txt"]).current_dir(&root).status().unwrap().success()); + let key_after = vcs_status_key(&project, project.vcs_status_flight.epoch()); + assert_ne!(key_before, key_after); + + let staged = vcs_status(&host, "main").await.unwrap(); + assert_eq!(staged.len(), 1); + assert_eq!(staged[0].staged, Some(ide_vcs::ChangeKind::Added)); + + // Saving run configs bumps `run_configs_flight` epoch immediately. + let run_epoch = project.run_configs_flight.epoch(); + crate::ops::run::save_configs(&host, "main", &[], &[]).unwrap(); + assert_ne!(project.run_configs_flight.epoch(), run_epoch); + + host.close_project("main"); + host.wait_detached_closes(); + } +} diff --git a/crates/ide-host/src/project.rs b/crates/ide-host/src/project.rs index b6249a3f19..e2c77b5e3f 100644 --- a/crates/ide-host/src/project.rs +++ b/crates/ide-host/src/project.rs @@ -20,6 +20,14 @@ use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; +type RunConfigsFlight = crate::singleflight::Singleflight>>; +type VcsStatusFlight = crate::singleflight::Singleflight>>; +type LibrariesFlight = crate::singleflight::StreamSingleflight< + (u64, String), + Vec, + Vec, +>; + /// Everything bound to one open project folder. pub struct Project { pub(crate) trusted: Arc, @@ -112,6 +120,12 @@ pub struct Project { _db_sources_watch: Option, /// The Plots tool window's folder watch, started by the first Python run ([`crate::ops::plots`]). pub(crate) plots_watch: Mutex>, + /// Coalesces overlapping `run_configs` detections for this project. + pub(crate) run_configs_flight: Arc, + /// Coalesces overlapping full `vcs_status` walks for this project. + pub(crate) vcs_status_flight: Arc, + /// Coalesces overlapping `sdk_project_libraries` streams for this project. + pub(crate) libraries_flight: Arc, /// A LightEdit window's loose files ([`Host::open_light`]): global settings only, /// nothing indexed, no language servers, repositories or project services. pub light: bool, @@ -574,8 +588,14 @@ impl Host { // synchronous startup walk and a later batch can both observe it. let notify_watch_exhausted = Arc::new(AtomicBool::new(false)); let files_events_active = Arc::new(AtomicBool::new(true)); + let run_configs_flight: Arc = Arc::default(); + let vcs_status_flight: Arc = Arc::default(); + let libraries_flight: Arc = Arc::default(); let watcher = { let files_events_active = files_events_active.clone(); + let run_configs_flight = run_configs_flight.clone(); + let vcs_status_flight = vcs_status_flight.clone(); + let libraries_flight = libraries_flight.clone(); let window = window.to_owned(); let kotlin_bridge = kotlin_bridge.clone(); let phpstan = phpstan.clone(); @@ -607,6 +627,11 @@ impl Host { sink.clone(), Box::new(move |batch| { let changed: Vec = batch.created.iter().chain(&batch.modified).cloned().collect(); + if !changed.is_empty() || !batch.removed.is_empty() || !batch.vcs.is_empty() { + run_configs_flight.invalidate(); + vcs_status_flight.invalidate(); + libraries_flight.invalidate(); + } let (ignored, ignored_gone) = ignored_changes(batch); index.ignore_rules_changed(&batch.ignore_rules); index.update(&[&changed[..], &ignored].concat(), &[&batch.removed[..], &ignored_gone].concat()); @@ -962,6 +987,9 @@ impl Host { git_metadata, _db_sources_watch: db_sources_watch, plots_watch: Mutex::default(), + run_configs_flight, + vcs_status_flight, + libraries_flight, files_events_active, light: false, }); @@ -1385,6 +1413,9 @@ impl Host { git_metadata: None, _db_sources_watch: None, plots_watch: Mutex::default(), + run_configs_flight: Arc::default(), + vcs_status_flight: Arc::default(), + libraries_flight: Arc::default(), files_events_active: Arc::new(AtomicBool::new(false)), light: true, root: dir, @@ -1467,6 +1498,14 @@ impl Project { }); } + /// Bumps per-project scan singleflight epochs so subsequent calls do not join an older + /// in-flight scan started before a settings, workspace, or repository change. + pub(crate) fn invalidate_scans(&self) { + self.run_configs_flight.invalidate(); + self.vcs_status_flight.invalidate(); + self.libraries_flight.invalidate(); + } + /// LightEdit: follow external changes to the files of `dir` (its own entries only). pub fn watch_light_dir(&self, dir: &Path) { if !self.light { @@ -2073,6 +2112,7 @@ impl Project { pub(crate) fn with_disk_sync(&self, f: impl FnOnce() -> IdeResult) -> IdeResult { let result = f(); // Failed operations can also leave changed files (for example merge conflicts). + self.vcs_status_flight.invalidate(); self.documents.sync_after_disk_change(); result } diff --git a/crates/ide-host/src/singleflight.rs b/crates/ide-host/src/singleflight.rs new file mode 100644 index 0000000000..a5cbfa458c --- /dev/null +++ b/crates/ide-host/src/singleflight.rs @@ -0,0 +1,566 @@ +//! Per-project singleflight coalescing for expensive background scans (`run_configs`, +//! `vcs_status`, `sdk_project_libraries`). +//! +//! At most one scan per project runs at a time. Concurrent callers observing the same +//! state key share the active scan's result; if state is invalidated mid-flight, waiting +//! callers wait for the running scan to finish and coalesce into a single fresh rerun. + +use crate::ops::Channel; +use ide_core::{CancellationToken, IdeError, IdeResult}; +use parking_lot::{Condvar, Mutex}; +use std::future::Future; +use std::sync::Arc; +use std::time::Duration; +use tokio::sync::Notify; + +const CANCEL_POLL: Duration = Duration::from_millis(50); + +/// Blocking singleflight coalescer with epoch-based invalidation and panic safety. +pub(crate) struct Singleflight { + state: Mutex>, + done: Condvar, +} + +struct State { + epoch: u64, + running: Option>>, +} + +struct Flight { + key: K, + result: Mutex>, +} + +impl Default for Singleflight { + fn default() -> Self { + Self { state: Mutex::new(State { epoch: 0, running: None }), done: Condvar::new() } + } +} + +impl Singleflight { + pub(crate) fn invalidate(&self) { + let mut state = self.state.lock(); + state.epoch = state.epoch.wrapping_add(1); + } + + pub(crate) fn epoch(&self) -> u64 { + self.state.lock().epoch + } + + /// Runs `f` or joins an active flight with the same key computed from `key_fn(epoch)`. + /// + /// `key_fn` runs outside the internal mutex so filesystem stamps never block invalidation. + /// At most one `f` executes concurrently; if `invalidate()` fires mid-flight, subsequent + /// callers wait for the active run to finish before coalescing into a single fresh rerun. + pub(crate) fn run(&self, key_fn: impl Fn(u64) -> K, f: F) -> V + where + F: FnOnce() -> V, + { + let mut f = Some(f); + loop { + let observed_epoch = self.epoch(); + let key = key_fn(observed_epoch); + let mut state = self.state.lock(); + if state.epoch != observed_epoch { + drop(state); + continue; + } + if let Some(flight) = state.running.clone() { + let matching = flight.key == key; + while state.running.as_ref().is_some_and(|r| Arc::ptr_eq(r, &flight)) { + self.done.wait(&mut state); + } + drop(state); + if matching && let Some(value) = flight.result.lock().clone() { + return value; + } + continue; + } + let flight = Arc::new(Flight { key, result: Mutex::new(None) }); + state.running = Some(flight.clone()); + drop(state); + + let guard = LeaderGuard { sf: self, flight: &flight }; + let value = f.take().expect("leader runs at most once")(); + *flight.result.lock() = Some(value.clone()); + drop(guard); + return value; + } + } +} + +struct LeaderGuard<'a, K, V> { + sf: &'a Singleflight, + flight: &'a Arc>, +} + +impl Drop for LeaderGuard<'_, K, V> { + fn drop(&mut self) { + let mut state = self.sf.state.lock(); + if state.running.as_ref().is_some_and(|r| Arc::ptr_eq(r, self.flight)) { + state.running = None; + } + self.sf.done.notify_all(); + } +} + +/// Async singleflight coalescer for cancellable streaming commands (`sdk_project_libraries`). +/// +/// Shares one active runner per project across concurrent callers with the same key, +/// replays and forwards streamed batches in order to joined callers, allows each caller to +/// cancel independently, and cancels the underlying runner once all callers detach. +pub(crate) struct StreamSingleflight { + state: Mutex>, +} + +struct StreamState { + epoch: u64, + next_caller_id: u64, + running: Option>>, + active_callers: usize, +} + +struct StreamFlight { + key: K, + leader_cancel: CancellationToken, + stream: Mutex>, + result: Mutex>>, + done: Notify, +} + +struct StreamFanout { + sent: Vec, + channels: Vec<(u64, Channel)>, +} + +impl Default for StreamSingleflight { + fn default() -> Self { + Self { state: Mutex::new(StreamState { epoch: 0, next_caller_id: 1, running: None, active_callers: 0 }) } + } +} + +impl StreamSingleflight +where + K: Eq + Send + Sync + 'static, + B: Clone + Send + Sync + 'static, + V: Clone + Send + Sync + 'static, +{ + pub(crate) fn invalidate(&self) { + let mut state = self.state.lock(); + state.epoch = state.epoch.wrapping_add(1); + } + + pub(crate) async fn run( + self: &Arc, + key_fn: impl Fn(u64) -> K, + caller_cancel: &CancellationToken, + on_batch: Channel, + spawn_leader: F, + ) -> IdeResult + where + F: Fn(CancellationToken, Channel) -> Fut, + Fut: Future> + Send + 'static, + { + loop { + if caller_cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + enum Action { + WaitOld(Arc>), + Joined { flight: Arc>, caller_id: u64, replay: bool }, + } + + let action = { + let mut state = self.state.lock(); + let key = key_fn(state.epoch); + if let Some(existing) = state.running.clone() { + if existing.key == key && state.active_callers > 0 && !existing.leader_cancel.is_cancelled() { + let caller_id = state.next_caller_id; + state.next_caller_id = state.next_caller_id.wrapping_add(1); + state.active_callers += 1; + Action::Joined { flight: existing, caller_id, replay: true } + } else { + Action::WaitOld(existing) + } + } else { + let caller_id = state.next_caller_id; + state.next_caller_id = state.next_caller_id.wrapping_add(1); + let flight = Arc::new(StreamFlight { + key, + leader_cancel: CancellationToken::new(), + stream: Mutex::new(StreamFanout { + sent: Vec::new(), + channels: vec![(caller_id, on_batch.clone())], + }), + result: Mutex::new(None), + done: Notify::new(), + }); + state.running = Some(flight.clone()); + state.active_callers = 1; + let runner_flight = flight.clone(); + let sf = self.clone(); + let fanout_flight = flight.clone(); + let fanout = Channel::new(move |batch: B| { + let mut stream = fanout_flight.stream.lock(); + stream.sent.push(batch.clone()); + for (_, ch) in &stream.channels { + let _ = ch.send(batch.clone()); + } + }); + let fut = spawn_leader(flight.leader_cancel.clone(), fanout); + tokio::spawn(async move { + let _guard = StreamLeaderGuard { sf, flight: runner_flight.clone() }; + let outcome = fut.await; + *runner_flight.result.lock() = Some(outcome); + }); + Action::Joined { flight, caller_id, replay: false } + } + }; + + let (flight, caller_id, replay) = match action { + Action::WaitOld(flight) => { + loop { + if caller_cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let notified = flight.done.notified(); + tokio::pin!(notified); + notified.as_mut().enable(); + if self.state.lock().running.as_ref().is_none_or(|r| !Arc::ptr_eq(r, &flight)) { + break; + } + let _ = tokio::time::timeout(CANCEL_POLL, notified).await; + } + continue; + } + Action::Joined { flight, caller_id, replay } => (flight, caller_id, replay), + }; + + let _caller = StreamCallerGuard { sf: self.clone(), flight: flight.clone(), caller_id }; + if replay { + // Replay prior batches and subscribe under `stream` lock (never nesting `state`) + // so batches are delivered strictly in order with no gaps or duplicates. + let mut stream = flight.stream.lock(); + for batch in &stream.sent { + let _ = on_batch.send(batch.clone()); + } + stream.channels.push((caller_id, on_batch.clone())); + } + + let outcome = loop { + if caller_cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let notified = flight.done.notified(); + tokio::pin!(notified); + notified.as_mut().enable(); + if let Some(res) = flight.result.lock().clone() { + break Some(res); + } + if self.state.lock().running.as_ref().is_none_or(|r| !Arc::ptr_eq(r, &flight)) { + break flight.result.lock().clone(); + } + let _ = tokio::time::timeout(CANCEL_POLL, notified).await; + }; + drop(_caller); + + match outcome { + Some(Err(e)) if e.kind == ide_core::error::ErrorKind::Cancelled => { + if caller_cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + continue; + } + Some(res) => return res, + None => continue, // Leader panicked; retry cleanly. + } + } + } +} + +struct StreamCallerGuard { + sf: Arc>, + flight: Arc>, + caller_id: u64, +} + +impl Drop for StreamCallerGuard { + fn drop(&mut self) { + self.flight.stream.lock().channels.retain(|(id, _)| *id != self.caller_id); + let mut state = self.sf.state.lock(); + if state.running.as_ref().is_some_and(|r| Arc::ptr_eq(r, &self.flight)) { + state.active_callers = state.active_callers.saturating_sub(1); + if state.active_callers == 0 { + self.flight.leader_cancel.cancel(); + } + } + } +} + +struct StreamLeaderGuard { + sf: Arc>, + flight: Arc>, +} + +impl Drop for StreamLeaderGuard { + fn drop(&mut self) { + let mut state = self.sf.state.lock(); + if state.running.as_ref().is_some_and(|r| Arc::ptr_eq(r, &self.flight)) { + state.running = None; + state.active_callers = 0; + } + drop(state); + self.flight.done.notify_waiters(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Barrier; + use std::sync::atomic::{AtomicUsize, Ordering}; + + #[test] + fn coalesces_concurrent_callers_with_same_key() { + let sf: Singleflight = Singleflight::default(); + let calls = AtomicUsize::new(0); + let active = AtomicUsize::new(0); + let max_active = AtomicUsize::new(0); + let entered = Barrier::new(2); + + std::thread::scope(|s| { + let leader = s.spawn(|| { + sf.run( + |epoch| epoch, + || { + let now = active.fetch_add(1, Ordering::SeqCst) + 1; + max_active.fetch_max(now, Ordering::SeqCst); + entered.wait(); + std::thread::sleep(Duration::from_millis(30)); + active.fetch_sub(1, Ordering::SeqCst); + calls.fetch_add(1, Ordering::SeqCst) + 1 + }, + ) + }); + entered.wait(); + let waiters: Vec<_> = (0..6).map(|_| s.spawn(|| sf.run(|epoch| epoch, || 999))).collect(); + assert_eq!(leader.join().unwrap(), 1); + for w in waiters { + assert_eq!(w.join().unwrap(), 1); + } + }); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert_eq!(max_active.load(Ordering::SeqCst), 1); + } + + #[test] + fn invalidation_serializes_into_one_trailing_rerun() { + let sf: Singleflight = Singleflight::default(); + let calls = AtomicUsize::new(0); + let active = AtomicUsize::new(0); + let max_active = AtomicUsize::new(0); + let started = Barrier::new(2); + let release = Barrier::new(2); + + std::thread::scope(|s| { + let first = s.spawn(|| { + sf.run( + |epoch| epoch, + || { + let now = active.fetch_add(1, Ordering::SeqCst) + 1; + max_active.fetch_max(now, Ordering::SeqCst); + started.wait(); + release.wait(); + let n = calls.fetch_add(1, Ordering::SeqCst) + 1; + active.fetch_sub(1, Ordering::SeqCst); + n + }, + ) + }); + started.wait(); + sf.invalidate(); + let trailing: Vec<_> = (0..4) + .map(|_| { + s.spawn(|| { + sf.run( + |epoch| epoch, + || { + let now = active.fetch_add(1, Ordering::SeqCst) + 1; + max_active.fetch_max(now, Ordering::SeqCst); + std::thread::sleep(Duration::from_millis(20)); + let n = calls.fetch_add(1, Ordering::SeqCst) + 1; + active.fetch_sub(1, Ordering::SeqCst); + n + }, + ) + }) + }) + .collect(); + std::thread::sleep(Duration::from_millis(15)); + release.wait(); + assert_eq!(first.join().unwrap(), 1); + for w in trailing { + assert_eq!(w.join().unwrap(), 2); + } + }); + assert_eq!(calls.load(Ordering::SeqCst), 2); + assert_eq!(max_active.load(Ordering::SeqCst), 1); + } + + #[test] + fn leader_panic_wakes_waiters_and_recovers() { + let sf: Singleflight = Singleflight::default(); + let started = Barrier::new(2); + let release = Barrier::new(2); + + std::thread::scope(|s| { + let panicking = s.spawn(|| { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + sf.run( + |epoch| epoch, + || { + started.wait(); + release.wait(); + panic!("boom"); + }, + ) + })) + }); + started.wait(); + let waiter = s.spawn(|| sf.run(|epoch| epoch, || 42)); + std::thread::sleep(Duration::from_millis(10)); + release.wait(); + assert!(panicking.join().unwrap().is_err()); + assert_eq!(waiter.join().unwrap(), 42); + }); + } + + #[tokio::test] + async fn stream_singleflight_replays_batches_and_handles_independent_cancellation() { + let sf: Arc>> = Arc::new(StreamSingleflight::default()); + let calls = Arc::new(AtomicUsize::new(0)); + let gate = Arc::new(Notify::new()); + + let (c1, c2) = (CancellationToken::new(), CancellationToken::new()); + let b1 = Arc::new(Mutex::new(Vec::new())); + let b2 = Arc::new(Mutex::new(Vec::new())); + let (b1_c, b2_c) = (b1.clone(), b2.clone()); + let ch1 = Channel::new(move |x: usize| b1_c.lock().push(x)); + let ch2 = Channel::new(move |x: usize| b2_c.lock().push(x)); + + let (sf1, calls1, gate1) = (sf.clone(), calls.clone(), gate.clone()); + let h1 = tokio::spawn(async move { + sf1.run( + |epoch| epoch, + &c1, + ch1, + move |_cancel, ch| { + let calls = calls1.clone(); + let gate = gate1.clone(); + async move { + calls.fetch_add(1, Ordering::SeqCst); + let _ = ch.send(1); + gate.notified().await; + let _ = ch.send(2); + Ok(vec![1, 2]) + } + }, + ) + .await + }); + + // Let leader emit batch 1, then join with follower 2. + tokio::time::sleep(Duration::from_millis(20)).await; + let (sf2, calls2) = (sf.clone(), calls.clone()); + let h2 = tokio::spawn(async move { + sf2.run( + |epoch| epoch, + &c2, + ch2, + move |_cancel, _ch| { + let calls = calls2.clone(); + async move { + calls.fetch_add(1, Ordering::SeqCst); + Ok(vec![99]) + } + }, + ) + .await + }); + + tokio::time::sleep(Duration::from_millis(20)).await; + gate.notify_waiters(); + + assert_eq!(h1.await.unwrap().unwrap(), vec![1, 2]); + assert_eq!(h2.await.unwrap().unwrap(), vec![1, 2]); + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert_eq!(*b1.lock(), vec![1, 2]); + assert_eq!(*b2.lock(), vec![1, 2]); + + // Cancelling one of two callers keeps the leader running for the remaining caller. + let gate_two = Arc::new(Notify::new()); + let c_drop = CancellationToken::new(); + let c_keep = CancellationToken::new(); + let (sf_a, gate_a, c_drop_w) = (sf.clone(), gate_two.clone(), c_drop.clone()); + let h_drop = tokio::spawn(async move { + sf_a.run( + |epoch| epoch, + &c_drop_w, + Channel::new(|_| {}), + move |cancel, ch| { + let gate = gate_a.clone(); + async move { + let _ = ch.send(10); + gate.notified().await; + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + Ok(vec![10]) + } + }, + ) + .await + }); + tokio::time::sleep(Duration::from_millis(20)).await; + let (sf_b, c_keep_w) = (sf.clone(), c_keep.clone()); + let h_keep = tokio::spawn(async move { + sf_b.run(|epoch| epoch, &c_keep_w, Channel::new(|_| {}), |_, _| async { Ok(vec![99]) }).await + }); + tokio::time::sleep(Duration::from_millis(20)).await; + c_drop.cancel(); + assert_eq!(h_drop.await.unwrap().unwrap_err().kind, ide_core::error::ErrorKind::Cancelled); + gate_two.notify_waiters(); + assert_eq!(h_keep.await.unwrap().unwrap(), vec![10]); + + // Cancelling the sole caller cancels the underlying leader token. + let leader_cancelled = Arc::new(tokio::sync::Notify::new()); + let lc = leader_cancelled.clone(); + let c3 = CancellationToken::new(); + let c3_wait = c3.clone(); + let sf3 = sf.clone(); + let h3 = tokio::spawn(async move { + sf3.run( + |epoch| epoch, + &c3_wait, + Channel::new(|_| {}), + move |cancel, _ch| { + let lc = lc.clone(); + async move { + while !cancel.is_cancelled() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + lc.notify_one(); + Err(IdeError::cancelled()) + } + }, + ) + .await + }); + tokio::time::sleep(Duration::from_millis(20)).await; + c3.cancel(); + assert_eq!(h3.await.unwrap().unwrap_err().kind, ide_core::error::ErrorKind::Cancelled); + tokio::time::timeout(Duration::from_secs(2), leader_cancelled.notified()) + .await + .expect("leader token should cancel when sole caller cancels"); + } +}