diff --git a/crates/ide-host/src/plugins/index_ops.rs b/crates/ide-host/src/plugins/index_ops.rs index a6d6afd1b6..10e4593d27 100644 --- a/crates/ide-host/src/plugins/index_ops.rs +++ b/crates/ide-host/src/plugins/index_ops.rs @@ -16,8 +16,10 @@ pub struct NavigationFiles { } /// Discovery offers at most this many files; larger projects get navigation -/// on the first ones instead of none. -const MAX_NAVIGATION_FILES: usize = 20_000; +/// on the first ones instead of none. As many as one graph covers, so the +/// "covers N of M files" notice stays true. +const MAX_NAVIGATION_FILES: usize = super::navigation::MAX_FILES; +const MAX_INDEX_BATCH: usize = 128; /// The first `limit` files by path that `in_scope` accepts, and how many it accepts in all. /// Sorting keeps the covered files the same across index rebuilds. @@ -80,6 +82,15 @@ pub fn plugin_navigation_invalidate( Ok(()) } +struct LoadedNavigationDoc { + path: PathBuf, + document: Option, + version: Option, + text: String, + symbols: Vec, + scope: String, +} + #[command(trust = trusted)] pub async fn plugin_navigation_index( host: &crate::Host, @@ -88,8 +99,8 @@ pub async fn plugin_navigation_index( paths: Vec, request: ide_core::RequestId, ) -> IdeResult<()> { - if paths.len() > 16 { - return Err(IdeError::invalid("navigation batches are limited to 16 files")); + if paths.len() > MAX_INDEX_BATCH { + return Err(IdeError::invalid("navigation batches are limited to 128 files")); } let plugins = plugins.clone(); let project = host.project(window)?; @@ -99,33 +110,45 @@ pub async fn plugin_navigation_index( if !project.is_trusted() { return Err(IdeError::unavailable("project is not trusted")); } + let extensions = plugins.navigation_extensions(&project.root); + let project_roots = project.roots(); // A project window group's members are project scope. let mut roots = vec![project.root.clone()]; roots.extend(crate::project::workspace_member_roots(&project.root)); - for path in paths { + + let mut loaded_docs = Vec::with_capacity(paths.len()); + let mut evict_paths = Vec::new(); + for raw_path in paths { if cancel.is_cancelled() { return Err(IdeError::cancelled()); } - let Ok(path) = ide_plugin::resolve_in_roots(&roots, &path.to_string_lossy()) else { + let Ok(path) = ide_plugin::resolve_in_roots(&roots, &raw_path.to_string_lossy()) else { + evict_paths.push(raw_path); continue; }; - let extensions = plugins.navigation_extensions(&project.root); if !path.extension().and_then(|e| e.to_str()).is_some_and(|e| extensions.iter().any(|x| x == e)) { + evict_paths.push(path); continue; } let document = project.documents.by_path(&path); let (text, version, language) = if let Some(id) = document { - let snapshot = project.documents.text_snapshot(id)?; + let Ok(snapshot) = project.documents.text_snapshot(id) else { + evict_paths.push(path); + continue; + }; if snapshot.large { + evict_paths.push(path); continue; } (snapshot.text, Some(snapshot.version), snapshot.language) } else { let Ok(loaded) = project.documents.load_file_bounded(&path, super::navigation::MAX_DOCUMENT_BYTES) else { + evict_paths.push(path); continue; }; if loaded.binary || loaded.large { + evict_paths.push(path); continue; } let text = loaded.text; @@ -133,23 +156,42 @@ pub async fn plugin_navigation_index( (text, None, language) }; if text.len() > crate::plugins::navigation::MAX_DOCUMENT_BYTES { + evict_paths.push(path); continue; } let symbols = project .index .symbols_for_text(&path, &text) .unwrap_or_else(|| project.syntax.syntax().tags(&language, &text)); - let roots = project.roots(); - let scope = roots + let scope = project_roots .roots .iter() .filter(|r| path.starts_with(project.root.join(&r.path))) .max_by_key(|r| r.path.len()) .and_then(|r| r.detected_from.as_deref()) - .unwrap_or(""); - plugins.index_navigation( + .unwrap_or("") + .to_owned(); + loaded_docs.push(LoadedNavigationDoc { path, document, version, text, symbols, scope }); + } + + if !evict_paths.is_empty() { + plugins.invalidate_client_navigation(&project.root, Some(&client), Some(&evict_paths)); + } + + if !loaded_docs.is_empty() { + let snapshots: Vec<_> = loaded_docs + .iter() + .map(|doc| crate::plugins::navigation::Snapshot { + path: &doc.path, + version: doc.version, + text: &doc.text, + symbols: &doc.symbols, + scope: &doc.scope, + }) + .collect(); + if let Err(err) = plugins.index_navigation_batch( &project.root, - crate::plugins::navigation::Snapshot { path: &path, version, text: &text, symbols: &symbols, scope }, + &snapshots, Invocation { command_chain: Vec::new(), client: Some(client.clone()), @@ -158,10 +200,33 @@ pub async fn plugin_navigation_index( selected_paths: Vec::new(), global_settings: false, }, - )?; + Some(&cancel), + ) { + let remaining_paths: Vec = loaded_docs + .into_iter() + .filter(|doc| { + cancel.is_cancelled() + || doc.document.is_some_and(|id| project.documents.version(id).ok() != doc.version) + }) + .map(|doc| doc.path) + .collect(); + if !remaining_paths.is_empty() { + plugins.invalidate_client_navigation(&project.root, Some(&client), Some(&remaining_paths)); + } + return Err(err); + } + // A document edit while WASM was executing must not publish stale ranges. - if cancel.is_cancelled() || document.is_some_and(|id| project.documents.version(id).ok() != version) { - plugins.invalidate_client_navigation(&project.root, Some(&client), Some(&[path])); + let stale_paths: Vec = loaded_docs + .into_iter() + .filter(|doc| { + cancel.is_cancelled() + || doc.document.is_some_and(|id| project.documents.version(id).ok() != doc.version) + }) + .map(|doc| doc.path) + .collect(); + if !stale_paths.is_empty() { + plugins.invalidate_client_navigation(&project.root, Some(&client), Some(&stale_paths)); } } Ok(()) diff --git a/crates/ide-host/src/plugins/navigation.rs b/crates/ide-host/src/plugins/navigation.rs index dd10359fe1..c165f4f8b7 100644 --- a/crates/ide-host/src/plugins/navigation.rs +++ b/crates/ide-host/src/plugins/navigation.rs @@ -15,6 +15,66 @@ pub const MAX_DOCUMENT_BYTES: usize = ide_lsp::MAX_INJECTED_DOCUMENT_BYTES; /// Files one plugin's graph covers per project and window. pub const MAX_FILES: usize = 20_000; const MAX_EDGES: usize = 4096; +const MAX_GRAPH_EDGES: usize = 200_000; +const MAX_ACTOR_CHUNK: usize = 16; + +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub struct BatchIndexSummary { + pub skipped_invalid: usize, +} + +fn edges_are_empty(edges: &Edges) -> bool { + edges.definitions.is_empty() && edges.references.is_empty() && edges.aliases.is_empty() && edges.markers.is_empty() +} + +fn validate_edges(plugin_id: &str, path: &Path, text: &str, edges: &Edges) -> IdeResult<()> { + if edges_are_empty(edges) { + return Ok(()); + } + let lines: Vec<_> = text.split('\n').map(|l| l.encode_utf16().count()).collect(); + let output_bytes = edges + .definitions + .iter() + .chain(&edges.references) + .chain(&edges.markers) + .map(|a| a.key.len().saturating_add(32)) + .sum::() + .saturating_add(edges.aliases.iter().map(|a| a.prefix.len() + a.target.len()).sum::()); + if output_bytes > MAX_DOCUMENT_BYTES { + return Err(IdeError::invalid("document index output is too large")); + } + if edges.aliases.len() > 256 + || edges.aliases.iter().any(|a| { + !a.prefix.ends_with('#') || !a.target.ends_with('#') || a.prefix.len() > 1024 || a.target.len() > 1024 + }) + || edges.definitions.len() + edges.references.len() > MAX_EDGES + || edges + .definitions + .iter() + .chain(&edges.references) + .any(|a| a.key.is_empty() || a.key.len() > 1024 || !valid_range(&lines, a.range)) + { + return Err(IdeError::invalid(format!("{plugin_id}: invalid navigation anchors in {}", path.display()))); + } + if edges.markers.len() > MAX_EDGES + || edges.markers.iter().any(|a| a.key.is_empty() || a.key.len() > 1024 || !valid_range(&lines, a.range)) + { + return Err(IdeError::invalid(format!("{plugin_id}: invalid navigation markers in {}", path.display()))); + } + Ok(()) +} + +fn to_index_symbols(symbols: &[SymbolTag]) -> Vec { + symbols + .iter() + .map(|s| ide_plugin::indexing::IndexSymbol { + name: s.name.clone(), + kind: serde_json::to_value(s.kind).ok().and_then(|v| v.as_str().map(str::to_owned)).unwrap_or_default(), + container: s.container.clone(), + range: s.range, + }) + .collect() +} pub struct Snapshot<'a> { pub path: &'a Path, @@ -236,7 +296,6 @@ impl PluginHost { if plugins.is_empty() { return Ok(()); } - let lines: Vec<_> = text.split('\n').map(|l| l.encode_utf16().count()).collect(); for plugin in plugins { // A full graph keeps the files it covers; discovery already told the user // the rest are left out, so they are skipped without running the plugin. @@ -250,64 +309,14 @@ impl PluginHost { self.changed(); } let (owned_path, owned_text) = (path.to_string_lossy().into_owned(), text.to_owned()); - let symbols = symbols - .iter() - .map(|s| ide_plugin::indexing::IndexSymbol { - name: s.name.clone(), - kind: serde_json::to_value(s.kind) - .ok() - .and_then(|v| v.as_str().map(str::to_owned)) - .unwrap_or_default(), - container: s.container.clone(), - range: s.range, - }) - .collect::>(); + let symbols = to_index_symbols(symbols); let ctx = invocation.clone(); let started = std::time::Instant::now(); let result = actor.call(None, move |rt| rt.index_document(&owned_path, &owned_text, &symbols, ctx)); let edges = self .finish_provider_call(&plugin, &actor, started, result) .ok_or_else(|| IdeError::unavailable("document indexer did not return a result"))?; - let output_bytes = edges - .definitions - .iter() - .chain(&edges.references) - .chain(&edges.markers) - .map(|a| a.key.len().saturating_add(32)) - .sum::() - .saturating_add(edges.aliases.iter().map(|a| a.prefix.len() + a.target.len()).sum::()); - if output_bytes > MAX_DOCUMENT_BYTES { - return Err(IdeError::invalid("document index output is too large")); - } - if edges.aliases.len() > 256 - || edges.aliases.iter().any(|a| { - !a.prefix.ends_with('#') - || !a.target.ends_with('#') - || a.prefix.len() > 1024 - || a.target.len() > 1024 - }) - || edges.definitions.len() + edges.references.len() > MAX_EDGES - || edges - .definitions - .iter() - .chain(&edges.references) - .any(|a| a.key.is_empty() || a.key.len() > 1024 || !valid_range(&lines, a.range)) - { - return Err(IdeError::invalid(format!( - "{}: invalid navigation anchors in {}", - plugin.id(), - path.display() - ))); - } - if edges.markers.len() > MAX_EDGES - || edges.markers.iter().any(|a| a.key.is_empty() || a.key.len() > 1024 || !valid_range(&lines, a.range)) - { - return Err(IdeError::invalid(format!( - "{}: invalid navigation markers in {}", - plugin.id(), - path.display() - ))); - } + validate_edges(plugin.id(), path, text, &edges)?; let mut index = self.navigation.lock(); if index.epochs.get(root).copied() != generation { return Err(IdeError::cancelled()); @@ -322,16 +331,19 @@ impl PluginHost { if !graph.instance.ptr_eq(&Arc::downgrade(&plugin)) { *graph = Graph { instance: Arc::downgrade(&plugin), ..Default::default() }; } + graph.remove(path); + if edges_are_empty(&edges) { + continue; + } if graph.files.len() >= MAX_FILES && !graph.files.contains_key(path) { continue; } - graph.remove(path); if graph.edges + edges.definitions.len() + edges.references.len() + edges.aliases.len() + edges.markers.len() - > 200_000 + > MAX_GRAPH_EDGES { return Err(IdeError::unavailable("navigation association limit reached")); } @@ -340,6 +352,191 @@ impl PluginHost { Ok(()) } + /// Index a batch of bounded snapshots in short actor chunks (up to 16 files per call). + /// Full graphs skip uncovered files before running the plugin, empty-edge documents are not + /// stored, and individual invalid documents are skipped/evicted without failing the batch. + pub fn index_navigation_batch( + &self, + root: &Path, + snapshots: &[Snapshot<'_>], + invocation: Invocation, + cancel: Option<&ide_core::CancellationToken>, + ) -> IdeResult { + if snapshots.is_empty() { + return Ok(BatchIndexSummary::default()); + } + if !(self.project_policy.read())(root) { + return Err(IdeError::unavailable("project is not trusted")); + } + let mut roots = vec![root.to_path_buf()]; + roots.extend(crate::project::workspace_member_roots(root)); + let mut summary = BatchIndexSummary::default(); + let mut prepared = Vec::with_capacity(snapshots.len()); + for snap in snapshots { + if snap.text.len() > MAX_DOCUMENT_BYTES { + tracing::warn!(path = %snap.path.display(), "navigation document is too large"); + summary.skipped_invalid += 1; + continue; + } + let path = dunce::simplified(snap.path); + match ide_plugin::resolve_in_roots(&roots, &path.to_string_lossy()) { + Ok(real) if real == path => { + let extension = path.extension().and_then(|e| e.to_str()).unwrap_or_default().to_owned(); + prepared.push((path.to_owned(), extension, snap)); + } + Ok(_) | Err(_) => { + tracing::warn!(path = %path.display(), "navigation skipped invalid path"); + summary.skipped_invalid += 1; + } + } + } + if prepared.is_empty() { + return Ok(summary); + } + + let project_key = (root.to_owned(), invocation.client.clone()); + let generation = self.navigation.lock().epochs.get(root).copied(); + let plugins: Vec<(Arc, Vec)> = self + .plugins + .read() + .values() + .filter(|p| { + p.status().is_live() + && p.dev_root.as_deref().is_none_or(|r| r == root) + && p.meta.lock().granted.contains(&Capability::ProjectRead) + }) + .filter_map(|p| declaration(p).map(|d| (p.clone(), d.extensions))) + .collect(); + if plugins.is_empty() { + return Ok(summary); + } + + for (plugin, exts) in plugins { + let matching_indices: Vec = { + let index = self.navigation.lock(); + let full_graph = index + .projects + .get(&project_key) + .and_then(|g| g.get(plugin.id())) + .filter(|g| g.instance.ptr_eq(&Arc::downgrade(&plugin)) && g.files.len() >= MAX_FILES); + prepared + .iter() + .enumerate() + .filter_map(|(idx, (path, ext, _))| { + if !exts.iter().any(|e| e == ext) { + return None; + } + if full_graph.is_some_and(|g| !g.files.contains_key(path)) { + return None; + } + Some(idx) + }) + .collect() + }; + if matching_indices.is_empty() { + continue; + } + if cancel.is_some_and(ide_core::CancellationToken::is_cancelled) { + return Err(IdeError::cancelled()); + } + let (actor, activated) = self.ensure_active(&plugin, invocation.client.as_deref())?; + if activated { + self.changed(); + } + + for chunk in matching_indices.chunks(MAX_ACTOR_CHUNK) { + if cancel.is_some_and(ide_core::CancellationToken::is_cancelled) { + return Err(IdeError::cancelled()); + } + let items: Vec<_> = chunk + .iter() + .map(|&idx| { + let (ref path, _, snap) = prepared[idx]; + (idx, path.to_string_lossy().into_owned(), snap.text.to_owned(), to_index_symbols(snap.symbols)) + }) + .collect(); + let ctx = invocation.clone(); + let chunk_cancel = cancel.cloned(); + let started = std::time::Instant::now(); + let result = actor.call(None, move |rt| { + let mut out = Vec::with_capacity(items.len()); + for (idx, owned_path, owned_text, symbols) in items { + if chunk_cancel.as_ref().is_some_and(ide_core::CancellationToken::is_cancelled) { + return Ok(None); + } + let edges = rt.index_document(&owned_path, &owned_text, &symbols, ctx.clone())?; + out.push((idx, edges)); + } + Ok(Some(out)) + }); + let Some(maybe_edges) = self.finish_provider_call(&plugin, &actor, started, result) else { + let mut index = self.navigation.lock(); + if let Some(graph) = index.projects.get_mut(&project_key).and_then(|g| g.get_mut(plugin.id())) { + for &idx in chunk { + graph.remove(&prepared[idx].0); + } + } + return Err(IdeError::unavailable("document indexer did not return a result")); + }; + let Some(chunk_edges) = maybe_edges else { + return Err(IdeError::cancelled()); + }; + if cancel.is_some_and(ide_core::CancellationToken::is_cancelled) { + return Err(IdeError::cancelled()); + } + + let mut index = self.navigation.lock(); + if index.epochs.get(root).copied() != generation { + return Err(IdeError::cancelled()); + } + if index.projects.len() >= 16 && !index.projects.contains_key(&project_key) { + return Err(IdeError::unavailable("navigation project limit reached")); + } + let graph = + index.projects.entry(project_key.clone()).or_default().entry(plugin.id().to_owned()).or_default(); + if !graph.instance.ptr_eq(&Arc::downgrade(&plugin)) { + *graph = Graph { instance: Arc::downgrade(&plugin), ..Default::default() }; + } + for (idx, edges) in chunk_edges { + let (ref path, _, snap) = prepared[idx]; + graph.remove(path); + if let Err(err) = validate_edges(plugin.id(), path, snap.text, &edges) { + tracing::warn!("{err}"); + summary.skipped_invalid += 1; + continue; + } + if edges_are_empty(&edges) { + continue; + } + if graph.files.len() >= MAX_FILES && !graph.files.contains_key(path) { + continue; + } + let new_edges = + edges.definitions.len() + edges.references.len() + edges.aliases.len() + edges.markers.len(); + if graph.edges + new_edges > MAX_GRAPH_EDGES { + tracing::warn!( + plugin = %plugin.id(), + path = %path.display(), + "navigation association limit reached; skipping document" + ); + summary.skipped_invalid += 1; + continue; + } + graph.insert( + path.clone(), + File { + version: snap.version, + scope: snap.scope.to_owned(), + hash: snapshot_hash(snap.text), + edges, + }, + ); + } + } + } + Ok(summary) + } + /// Resolves only current live providers. Disable/reload/trap cannot retain /// navigable stale data, even if a background snapshot finished concurrently. pub fn navigation_at( diff --git a/crates/ide-host/tests/plugin_indexing.rs b/crates/ide-host/tests/plugin_indexing.rs index 868bdeb527..3d0801f912 100644 --- a/crates/ide-host/tests/plugin_indexing.rs +++ b/crates/ide-host/tests/plugin_indexing.rs @@ -394,7 +394,17 @@ fn a_full_graph_keeps_updating_its_files_and_skips_others_without_running_the_pl let f = Fixture::new(); let source = f.index("source.idx", SOURCE, &[method()], Some(1), ""); for i in 1..MAX_FILES { - f.index(&format!("filler/{i}.idx"), "", &[], None, ""); + let p = f.root.join(format!("filler/{i}.idx")); + let txt = format!("def filler:{i}\n"); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(&p, &txt).unwrap(); + f.host + .index_navigation( + &f.root, + Snapshot { path: &p, version: None, text: &txt, symbols: &[], scope: "" }, + Invocation { workspace_root: Some(f.root.clone()), ..Default::default() }, + ) + .unwrap(); } let calls = f.host.info_of("test.indexer").unwrap().stats.calls; let mapping = f.index("mapping.idx", MAPPING, &[], Some(1), ""); @@ -403,4 +413,99 @@ fn a_full_graph_keeps_updating_its_files_and_skips_others_without_running_the_pl f.index("source.idx", SOURCE, &[method()], Some(2), ""); assert_eq!(f.host.info_of("test.indexer").unwrap().stats.calls, calls + 1, "covered files still update"); assert!(f.host.navigation_at(&f.root, &source, 2, Pos::new(1, 5), None, |_| None).is_none()); + + // Batch indexing on the same full graph also skips uncovered files before invoking WASM. + let calls_before_batch = f.host.info_of("test.indexer").unwrap().stats.calls; + std::fs::write(&source, SOURCE).unwrap(); + f.host + .index_navigation_batch( + &f.root, + &[ + Snapshot { path: &mapping, version: Some(2), text: MAPPING, symbols: &[], scope: "" }, + Snapshot { path: &source, version: Some(3), text: SOURCE, symbols: &[], scope: "" }, + ], + Invocation { workspace_root: Some(f.root.clone()), ..Default::default() }, + None, + ) + .unwrap(); + assert_eq!( + f.host.info_of("test.indexer").unwrap().stats.calls, + calls_before_batch + 1, + "batch only invokes WASM for the already-covered file" + ); +} + +#[test] +fn empty_edges_do_not_consume_graph_slots_and_batch_isolates_invalid_documents() { + let f = Fixture::new(); + let source = f.index("src/source.idx", SOURCE, &[method()], Some(1), "app"); + let mapping = f.index("resources/mapping.idx", MAPPING, &[], Some(1), "app"); + assert!(f.host.navigation_at(&f.root, &mapping, 1, reference_pos(), None, |_| None).is_some()); + + // Re-indexing `source` with empty content evicts its previous anchors cleanly. + std::fs::write(&source, "").unwrap(); + f.host + .index_navigation( + &f.root, + Snapshot { path: &source, version: Some(2), text: "", symbols: &[], scope: "app" }, + Invocation { workspace_root: Some(f.root.clone()), ..Default::default() }, + ) + .unwrap(); + assert!(f.host.navigation_at(&f.root, &mapping, 1, reference_pos(), None, |_| None).is_none()); + assert!(f.host.navigation_markers(&f.root, std::slice::from_ref(&mapping), None, |_| None).is_empty()); + + // Mixed batch containing 200 empty files, one invalid document, and two valid connected files: + // the invalid document is skipped/evicted while valid documents still commit cleanly. + let mut empty_paths = Vec::with_capacity(200); + for i in 0..200 { + let p = f.root.join(format!("empty/E{i}.idx")); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(&p, "// nothing\n").unwrap(); + empty_paths.push(p); + } + let bad = f.root.join("batch/bad.idx"); + let connected_a = f.root.join("batch/source.idx"); + let connected_b = f.root.join("batch/mapping.idx"); + std::fs::create_dir_all(bad.parent().unwrap()).unwrap(); + std::fs::write(&bad, "invalid key\n").unwrap(); + std::fs::write(&connected_a, SOURCE).unwrap(); + std::fs::write(&connected_b, MAPPING).unwrap(); + + let mut snapshots: Vec> = empty_paths + .iter() + .map(|p| Snapshot { path: p, version: None, text: "// nothing\n", symbols: &[], scope: "app" }) + .collect(); + snapshots.push(Snapshot { path: &bad, version: Some(1), text: "invalid key\n", symbols: &[], scope: "app" }); + snapshots.push(Snapshot { path: &connected_a, version: Some(1), text: SOURCE, symbols: &[], scope: "app" }); + snapshots.push(Snapshot { path: &connected_b, version: Some(1), text: MAPPING, symbols: &[], scope: "app" }); + + let summary = f + .host + .index_navigation_batch( + &f.root, + &snapshots, + Invocation { workspace_root: Some(f.root.clone()), ..Default::default() }, + None, + ) + .unwrap(); + assert_eq!(summary.skipped_invalid, 1); + + let res = f.host.navigation_at(&f.root, &connected_b, 1, reference_pos(), None, |_| None).unwrap(); + assert_eq!(res.targets[0].path.0, connected_a); + let markers = f.host.navigation_markers(&f.root, &[connected_a.clone(), connected_b.clone()], None, |_| None); + assert_eq!(markers.len(), 2); + + // Pre-cancelled batch aborts without publishing or modifying entries. + let cancelled_file = f.root.join("batch/cancelled.idx"); + std::fs::write(&cancelled_file, SOURCE).unwrap(); + let token = ide_core::CancellationToken::new(); + token.cancel(); + let cancelled_res = f.host.index_navigation_batch( + &f.root, + &[Snapshot { path: &cancelled_file, version: Some(1), text: SOURCE, symbols: &[], scope: "app" }], + Invocation { workspace_root: Some(f.root.clone()), ..Default::default() }, + Some(&token), + ); + assert!(cancelled_res.is_err()); + assert!(f.host.navigation_markers(&f.root, &[cancelled_file], None, |_| None).is_empty()); } diff --git a/src/features/plugins/navigation.test.ts b/src/features/plugins/navigation.test.ts index 4339d9589d..2f1ffcb5db 100644 --- a/src/features/plugins/navigation.test.ts +++ b/src/features/plugins/navigation.test.ts @@ -243,3 +243,32 @@ it("indexes the first files of a large project and says how many it covers, in o await setLocale(locale); } }); + +it("dispatches large queues in 128-file batches without per-batch invalidation and prioritizes active views", async () => { + const bulk = Array.from({ length: 300 }, (_, i) => `/project/Bulk${i}.java`); + mocks.files.mockResolvedValue({ + status: "ok", + data: { paths: bulk, indexing: false, extensions: ["java"], total: 300, truncated: false }, + }); + off = startPluginNavigation(); + await vi.advanceTimersByTimeAsync(100); + expect(mocks.index).toHaveBeenCalledTimes(3); + expect(mocks.index.mock.calls[0]?.[0]).toHaveLength(128); + expect(mocks.index.mock.calls[1]?.[0]).toHaveLength(128); + expect(mocks.index.mock.calls[2]?.[0]).toHaveLength(44); + expect(mocks.invalidate).not.toHaveBeenCalledWith(expect.any(Array)); + + mocks.index.mockClear(); + const nextBulk = Array.from({ length: 200 }, (_, i) => `/project/Next${i}.java`); + mocks.events.get("fsChanged")?.({ created: nextBulk, modified: [], removed: [] }); + const ctx = { doc: 2, path: "/project/Active.java", language: "java", uiMode: "Java", readOnly: false }; + const extension = useEditorRegistry.getState().contributions.get("plugins.navigation")!; + view = new EditorView({ + state: EditorState.create({ doc: "class Active {}", extensions: [lspDoc.of(ctx), extension.extensions(ctx)] }), + }); + await vi.advanceTimersByTimeAsync(200); + expect(mocks.index).toHaveBeenCalledTimes(2); + expect(mocks.index.mock.calls[0]?.[0][0]).toBe("/project/Active.java"); + expect(mocks.index.mock.calls[0]?.[0]).toHaveLength(128); + expect(mocks.index.mock.calls[1]?.[0]).toHaveLength(73); +}); diff --git a/src/features/plugins/navigation.ts b/src/features/plugins/navigation.ts index 0868d73116..9289a62537 100644 --- a/src/features/plugins/navigation.ts +++ b/src/features/plugins/navigation.ts @@ -18,6 +18,8 @@ import { pluginsBackend } from "./backend"; import { invalidatePluginMarkers, settlePluginMarkers } from "./markerStore"; import { usePlugins } from "./store"; +const INDEX_BATCH_SIZE = 128; + export function startPluginNavigation(): () => void { if (!isTauri()) return () => {}; let generation = 0; @@ -25,7 +27,8 @@ export function startPluginNavigation(): () => void { let running = false; let request: number | null = null; let timer: ReturnType | undefined; - let pending = new Set(); + const priorityPending = new Set(); + const pending = new Set(); const dirty = new Set(); /** Paths whose last index batch failed: retried on the next usages or refactoring. */ const failed = new Set(); @@ -73,7 +76,24 @@ export function startPluginNavigation(): () => void { (p.status === "active" || p.status === "inactive") && p.contributions.some((c) => c.point === "documentIndexers"), ); - const notify = () => invalidateNavigationProviders(); + let lastNotifyAt = 0; + const notify = () => { + lastNotifyAt = Date.now(); + invalidateNavigationProviders(); + }; + const takeBatch = (limit: number): string[] => { + const out: string[] = []; + for (const set of [priorityPending, pending]) { + for (const p of set) { + out.push(p); + set.delete(p); + if (out.length >= limit) return out; + } + } + return out; + }; + const hasQueued = () => priorityPending.size > 0 || pending.size > 0; + const isQueued = (path: string) => priorityPending.has(path) || pending.has(path); let flushing: Promise | null = null; function flush(): Promise { @@ -86,32 +106,32 @@ export function startPluginNavigation(): () => void { } async function runFlush() { timer = undefined; - if (running || !ready() || !pending.size) return; + if (running || !ready() || !hasQueued()) return; running = true; const at = generation; - const paths = [...pending].slice(0, 8); - paths.forEach((p) => pending.delete(p)); + const paths = takeBatch(INDEX_BATCH_SIZE); + const batchSet = new Set(paths); const id = nextRequestId(); request = id; try { - await Promise.all([...views].filter(([, p]) => paths.includes(p)).map(([v]) => whenSynced(v))); + const openViews = [...views].filter(([, p]) => batchSet.has(p)); + await Promise.all(openViews.map(([v]) => whenSynced(v))); if (at !== generation || !ready()) return; - await call(commands.pluginNavigationInvalidate(paths)); await call(commands.pluginNavigationIndex(paths, id)); if (at === generation) { paths.forEach((p) => { failed.delete(p); - if (!pending.has(p)) dirty.delete(p); + if (!isQueued(p)) dirty.delete(p); }); - settlePluginMarkers(paths.filter((p) => !pending.has(p))); - notify(); + settlePluginMarkers(paths.filter((p) => !isQueued(p))); + if (openViews.length > 0 || !hasQueued() || Date.now() - lastNotifyAt >= 250) notify(); } } catch (error) { if (at === generation && isCancelled(error)) paths.forEach((p) => pending.add(p)); else if (at === generation) { // Not "still updating": the batch is done, its paths just have no fresh index. paths.forEach((p) => { - if (pending.has(p)) return; + if (isQueued(p)) return; dirty.delete(p); failed.add(p); }); @@ -121,15 +141,22 @@ export function startPluginNavigation(): () => void { } finally { request = null; running = false; - if (pending.size && ready()) timer = setTimeout(() => void flush(), 20); + if (hasQueued() && ready()) timer = setTimeout(() => void flush(), 0); } } function queue(paths: string[], priority = false) { const matching = paths.filter(eligible); if (!matching.length || !ready()) return; invalidatePluginMarkers(matching); - matching.forEach((p) => dirty.add(p)); - pending = priority ? new Set([...matching, ...pending]) : new Set([...pending, ...matching]); + for (const p of matching) { + dirty.add(p); + if (priority) { + pending.delete(p); + priorityPending.add(p); + } else if (!priorityPending.has(p)) { + pending.add(p); + } + } notify(); clearTimeout(timer); timer = setTimeout(() => void flush(), priority ? 150 : 30); @@ -172,6 +199,7 @@ export function startPluginNavigation(): () => void { generation++; if (request !== null) void commands.cancelRequest(request); clearTimeout(timer); + priorityPending.clear(); pending.clear(); dirty.clear(); failed.clear(); @@ -197,7 +225,7 @@ export function startPluginNavigation(): () => void { await discover(); if (!eligible(path)) return; if (failed.size) queue([...failed]); - while (ready() && at === generation && (pending.size || flushing)) { + while (ready() && at === generation && (hasQueued() || flushing)) { clearTimeout(timer); await flush(); }