From 46a544d9e4ee235bbf28ebe2ca8794b847ca93ae Mon Sep 17 00:00:00 2001 From: Paolo Tranquilli Date: Wed, 2 Dec 2026 15:04:08 +0000 Subject: [PATCH 1/6] Rust: Reuse loaded workspaces and load the next one in the background Keeps the two most recently used workspaces, so that extracting dependencies does not reload workspaces still in memory, and loads the next manifest while the current one is extracted when running on more than one thread. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 8d0772f66a6b42c7b59d25b5e8f4073d --- rust/extractor/src/main.rs | 65 +++++---- rust/extractor/src/parallel.rs | 2 +- rust/extractor/src/workspaces.rs | 222 +++++++++++++++++++++++++++++++ 3 files changed, 255 insertions(+), 34 deletions(-) create mode 100644 rust/extractor/src/workspaces.rs diff --git a/rust/extractor/src/main.rs b/rust/extractor/src/main.rs index f7f31cc2e365..f0d463fb5bb9 100644 --- a/rust/extractor/src/main.rs +++ b/rust/extractor/src/main.rs @@ -10,9 +10,8 @@ use itertools::Itertools; use ra_ap_hir::Semantics; use ra_ap_ide_db::RootDatabase; use ra_ap_ide_db::line_index::{LineCol, LineIndex}; -use ra_ap_load_cargo::LoadCargoConfig; use ra_ap_paths::{AbsPathBuf, Utf8PathBuf}; -use ra_ap_project_model::{CargoConfig, ProjectManifest}; +use ra_ap_project_model::ProjectManifest; use ra_ap_vfs::Vfs; use rust_analyzer::{ParseResult, RustAnalyzer}; use std::collections::{BTreeMap, HashSet}; @@ -24,6 +23,7 @@ use std::{env, fs}; use tracing::{error, info, warn}; use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::util::SubscriberInitExt; +use workspaces::LoadedWorkspaces; mod archive; mod config; @@ -38,6 +38,10 @@ mod toolchain; mod translate; pub mod trap; mod util; +mod workspaces; + +/// How many loaded workspaces are kept for reuse, besides the one loading in the background. +const MAX_LOADED_WORKSPACES: usize = 2; struct Extractor<'a> { archiver: &'a Archiver, @@ -128,19 +132,6 @@ impl<'a> Extractor<'a> { self.extract(&RustAnalyzer::from(err), file, source_kind); } - pub fn load_manifest( - &mut self, - project: &ProjectManifest, - config: &CargoConfig, - load_config: &LoadCargoConfig, - ) -> Option<(RootDatabase, Vfs)> { - let before = Instant::now(); - let ret = RustAnalyzer::load_workspace(project, config, load_config); - self.steps - .push(ExtractionStep::load_manifest(before, project)); - ret - } - pub fn load_source( &mut self, file: &Path, @@ -386,25 +377,29 @@ fn main() -> anyhow::Result<()> { // workspace a dependency file should be extracted. let dependency_extraction_ambiguity = workspaces.len() == 1; - for (manifest, files) in workspaces.values() { - if let Some((db, vfs)) = - extractor.load_manifest(manifest, &cargo_config, &load_cargo_config) - { + // loading in the background needs a thread beyond the sequential extraction one + let mut loaded = LoadedWorkspaces::new(MAX_LOADED_WORKSPACES, threads > 1, move |manifest| { + RustAnalyzer::load_workspace(manifest, &cargo_config, &load_cargo_config) + }); + let mut workspaces = workspaces.values().peekable(); + while let Some((manifest, files)) = workspaces.next() { + let next = workspaces.peek().map(|(next, _)| *next); + if let Some((db, vfs)) = loaded.get(manifest, next, &mut extractor.steps) { let before_crate_graph = Instant::now(); - crate_graph::extract_crate_graph(extractor.traps, &db, &vfs); + crate_graph::extract_crate_graph(extractor.traps, db, vfs); extractor .steps .push(ExtractionStep::crate_graph(before_crate_graph)); let mut items: Vec<(&Path, bool)> = files.iter().map(|f| (*f, true)).collect(); // Fast path when there is no ambiguity in dependency extraction. if dependency_extraction_ambiguity { - items.extend(dependency_files(&db, &vfs, &source_files).map(|(_, f)| (f, false))); + items.extend(dependency_files(db, vfs, &source_files).map(|(_, f)| (f, false))); } - prime_def_maps(&db, &vfs, items.iter().map(|(f, _)| *f), threads); + prime_def_maps(db, vfs, items.iter().map(|(f, _)| *f), threads); debug_assert!(items.iter().map(|(f, _)| f).all_unique()); extractor.run_parallel( - &db, - &vfs, + db, + vfs, threads, &items, |extractor, semantics, vfs, &(file, is_source)| { @@ -421,8 +416,8 @@ fn main() -> anyhow::Result<()> { }, ); if !dependency_extraction_ambiguity { - let semantics = Semantics::new(&db); - dependencies.add_manifest(manifest, &semantics, &vfs, &source_files); + let semantics = Semantics::new(db); + dependencies.add_manifest(manifest, &semantics, vfs, &source_files); } } else { for file in files { @@ -439,14 +434,17 @@ fn main() -> anyhow::Result<()> { // preferred. Note that when `dependency_extraction_ambiguity` is true then // `selected` below is empty. loop { - let selected = dependencies.by_manifests(); + let mut selected = dependencies.by_manifests().into_iter().collect_vec(); if selected.is_empty() { break; } - for (manifest, files) in selected { - if let Some((db, vfs)) = - extractor.load_manifest(manifest, &cargo_config, &load_cargo_config) - { + // The order does not affect what is extracted: start with the workspaces still loaded. + selected + .sort_by_key(|&(manifest, _)| (!loaded.contains(manifest), manifest_parent(manifest))); + let mut selected = selected.into_iter().peekable(); + while let Some((manifest, files)) = selected.next() { + let next = selected.peek().map(|(next, _)| *next); + if let Some((db, vfs)) = loaded.get(manifest, next, &mut extractor.steps) { // `has_alternative` is evaluated upfront, which is equivalent to evaluating it // just before each extraction as each file occurs at most once in `selected`. let items: Vec<_> = files @@ -458,8 +456,8 @@ fn main() -> anyhow::Result<()> { .collect(); debug_assert!(items.iter().map(|(f, _)| f).all_unique()); let extracted = extractor.run_parallel( - &db, - &vfs, + db, + vfs, threads, &items, |extractor, semantics, vfs, (file, has_alternative)| { @@ -496,6 +494,7 @@ fn main() -> anyhow::Result<()> { } } } + drop(loaded); let builtins_dir = env::var("CODEQL_EXTRACTOR_RUST_ROOT") .map(|path| Path::new(&path).join("tools").join("builtins"))?; diff --git a/rust/extractor/src/parallel.rs b/rust/extractor/src/parallel.rs index c38490a761ab..e3706487ff65 100644 --- a/rust/extractor/src/parallel.rs +++ b/rust/extractor/src/parallel.rs @@ -25,7 +25,7 @@ fn threads_from(value: Option<&str>, cores: usize) -> usize { /// Extraction recurses deeply on nested code, so workers need more than the default 2 MiB stack. /// This matches what rust-analyzer uses for its own threads. -const WORKER_STACK_SIZE: usize = 16 << 20; +pub const WORKER_STACK_SIZE: usize = 16 << 20; /// Sets the flag if the current thread unwinds while this is alive. struct AbortOnPanic<'a>(&'a AtomicBool); diff --git a/rust/extractor/src/workspaces.rs b/rust/extractor/src/workspaces.rs new file mode 100644 index 000000000000..d761ac705227 --- /dev/null +++ b/rust/extractor/src/workspaces.rs @@ -0,0 +1,222 @@ +use crate::diagnostics::ExtractionStep; +use crate::parallel::WORKER_STACK_SIZE; +use ra_ap_project_model::ProjectManifest; +use std::sync::Arc; +use std::thread::JoinHandle; +use std::time::Instant; +use tracing::{error, warn}; + +type Loaded = (Option, ExtractionStep); + +/// Workspaces loaded from manifests, keeping the `capacity` most recently used ones so that they +/// need not be reloaded when extracting dependencies. Optionally, the manifest that is going to be +/// requested next is loaded in the background meanwhile. At most `capacity + 1` workspaces are +/// held at any time. +pub struct LoadedWorkspaces<'m, W, L> { + /// Most recently used last. + loaded: Vec<(&'m ProjectManifest, W)>, + prefetched: Option<(&'m ProjectManifest, JoinHandle>)>, + load: Arc, + capacity: usize, + prefetch: bool, +} + +impl<'m, W, L> LoadedWorkspaces<'m, W, L> +where + W: Send + 'static, + L: Fn(&ProjectManifest) -> Option + Send + Sync + 'static, +{ + pub fn new(capacity: usize, prefetch: bool, load: L) -> Self { + assert!(capacity > 0); + Self { + loaded: Vec::with_capacity(capacity), + prefetched: None, + load: Arc::new(load), + capacity, + prefetch, + } + } + + pub fn contains(&self, manifest: &ProjectManifest) -> bool { + self.loaded.iter().any(|(m, _)| *m == manifest) + } + + /// Returns the workspace of `manifest`, loading it unless still loaded, or `None` if it cannot + /// be loaded. Then starts loading `next` in the background, if prefetching is enabled. + pub fn get( + &mut self, + manifest: &'m ProjectManifest, + next: Option<&'m ProjectManifest>, + steps: &mut Vec, + ) -> Option<&W> { + let found = if let Some(index) = self.loaded.iter().position(|(m, _)| *m == manifest) { + let entry = self.loaded.remove(index); + self.loaded.push(entry); + true + } else { + let prefetched = self.take_prefetched(manifest, steps); + let (workspace, step) = prefetched.unwrap_or_else(|| load_timed(&*self.load, manifest)); + steps.push(step); + workspace.is_some_and(|workspace| { + // evict before starting the next prefetch to bound the number of workspaces held + if self.loaded.len() == self.capacity { + self.loaded.remove(0); + } + self.loaded.push((manifest, workspace)); + true + }) + }; + if let Some(next) = next { + self.start_prefetch(next); + } + let (_, workspace) = self.loaded.last().filter(|_| found)?; + Some(workspace) + } + + fn take_prefetched( + &mut self, + manifest: &ProjectManifest, + steps: &mut Vec, + ) -> Option> { + let (prefetched, handle) = self.prefetched.take()?; + let loaded = handle + .join() + .unwrap_or_else(|e| std::panic::resume_unwind(e)); + if prefetched == manifest { + return Some(loaded); + } + warn!("discarding {prefetched}, loaded in the background instead of {manifest}"); + steps.push(loaded.1); + None + } + + fn start_prefetch(&mut self, next: &'m ProjectManifest) { + if !self.prefetch || self.prefetched.is_some() || self.contains(next) { + return; + } + let load = Arc::clone(&self.load); + let manifest = next.clone(); + match std::thread::Builder::new() + .stack_size(WORKER_STACK_SIZE) + .spawn(move || load_timed(&*load, &manifest)) + { + Ok(handle) => self.prefetched = Some((next, handle)), + // `next` is then loaded when requested + Err(e) => warn!("cannot load {next} in the background: {e}"), + } + } +} + +impl Drop for LoadedWorkspaces<'_, W, L> { + fn drop(&mut self) { + // do not leave cargo or proc-macro server processes behind + if let Some((manifest, handle)) = self.prefetched.take() + && handle.join().is_err() + { + error!("loading {manifest} in the background panicked"); + } + } +} + +fn load_timed( + load: &impl Fn(&ProjectManifest) -> Option, + manifest: &ProjectManifest, +) -> Loaded { + let before = Instant::now(); + let ret = load(manifest); + (ret, ExtractionStep::load_manifest(before, manifest)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Mutex; + use std::sync::atomic::{AtomicUsize, Ordering}; + + #[derive(Default)] + struct Stats { + loads: Mutex>, + live: AtomicUsize, + peak: AtomicUsize, + } + + struct Workspace(String, Arc); + + impl Drop for Workspace { + fn drop(&mut self) { + self.1.live.fetch_sub(1, Ordering::SeqCst); + } + } + + fn manifests(names: &[&str]) -> Vec { + let root = crate::cwd().unwrap(); + names + .iter() + .map(|name| ProjectManifest::from_manifest_file(root.join(name).join("Cargo.toml"))) + .collect::>() + .unwrap() + } + + /// Loads workspaces named after their directory, failing for `broken`. + fn loader(stats: &Arc) -> impl Fn(&ProjectManifest) -> Option + use<> { + let stats = Arc::clone(stats); + move |manifest| { + let name = manifest.manifest_path().parent().file_name()?.to_owned(); + // test threads are named, background loading ones are not + let background = std::thread::current().name().is_none(); + let entry = format!("{name}{}", if background { " (background)" } else { "" }); + stats.loads.lock().unwrap().push(entry); + if name == "broken" { + return None; + } + let live = stats.live.fetch_add(1, Ordering::SeqCst) + 1; + stats.peak.fetch_max(live, Ordering::SeqCst); + Some(Workspace(name, Arc::clone(&stats))) + } + } + + #[test] + fn reuses_most_recently_used_workspaces() { + let stats = Arc::default(); + let [a, b, c, broken]: &[_; 4] = &manifests(&["a", "b", "c", "broken"]).try_into().unwrap(); + let mut loaded = LoadedWorkspaces::new(2, false, loader(&stats)); + let mut steps = Vec::new(); + for manifest in [a, b, a, c, b, broken, broken] { + let got = loaded.get(manifest, None, &mut steps).map(|w| w.0.clone()); + assert_eq!(got.is_some(), manifest != broken); + } + // `c` evicts `b`, the least recently used; failed loads are not kept + assert_eq!( + *stats.loads.lock().unwrap(), + ["a", "b", "c", "b", "broken", "broken"] + ); + assert_eq!(steps.len(), 6); + assert!(loaded.contains(c) && loaded.contains(b) && !loaded.contains(a)); + } + + #[test] + fn prefetches_next_workspace_within_bound() { + let stats = Arc::default(); + let all = manifests(&["a", "b", "broken", "c", "d"]); + let mut loaded = LoadedWorkspaces::new(2, true, loader(&stats)); + let mut steps = Vec::new(); + for (i, manifest) in all.iter().enumerate() { + let got = loaded.get(manifest, all.get(i + 1), &mut steps); + assert_eq!(got.is_some(), i != 2); + } + assert_eq!( + *stats.loads.lock().unwrap(), + [ + "a", + "b (background)", + "broken (background)", + "c (background)", + "d (background)" + ] + ); + assert_eq!(steps.len(), 5); + assert!(stats.peak.load(Ordering::SeqCst) <= 3); + drop(loaded); + assert_eq!(stats.live.load(Ordering::SeqCst), 0); + } +} From 0e0ef1ea4fcde1b8131ff54aa66520e74c48ca60 Mon Sep 17 00:00:00 2001 From: Paolo Tranquilli Date: Wed, 2 Dec 2026 15:29:05 +0000 Subject: [PATCH 2/6] Rust: Keep only the current workspace loaded Older workspaces were never reused during per-file extraction, and each holds its own proc-macro server pool. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 8d0772f66a6b42c7b59d25b5e8f4073d --- rust/extractor/src/main.rs | 5 +- rust/extractor/src/workspaces.rs | 114 +++++++++++++++++-------------- 2 files changed, 62 insertions(+), 57 deletions(-) diff --git a/rust/extractor/src/main.rs b/rust/extractor/src/main.rs index f0d463fb5bb9..cf61716b268f 100644 --- a/rust/extractor/src/main.rs +++ b/rust/extractor/src/main.rs @@ -40,9 +40,6 @@ pub mod trap; mod util; mod workspaces; -/// How many loaded workspaces are kept for reuse, besides the one loading in the background. -const MAX_LOADED_WORKSPACES: usize = 2; - struct Extractor<'a> { archiver: &'a Archiver, traps: &'a trap::TrapFileProvider, @@ -378,7 +375,7 @@ fn main() -> anyhow::Result<()> { let dependency_extraction_ambiguity = workspaces.len() == 1; // loading in the background needs a thread beyond the sequential extraction one - let mut loaded = LoadedWorkspaces::new(MAX_LOADED_WORKSPACES, threads > 1, move |manifest| { + let mut loaded = LoadedWorkspaces::new(threads > 1, move |manifest| { RustAnalyzer::load_workspace(manifest, &cargo_config, &load_cargo_config) }); let mut workspaces = workspaces.values().peekable(); diff --git a/rust/extractor/src/workspaces.rs b/rust/extractor/src/workspaces.rs index d761ac705227..6b9c198d7c5f 100644 --- a/rust/extractor/src/workspaces.rs +++ b/rust/extractor/src/workspaces.rs @@ -8,16 +8,13 @@ use tracing::{error, warn}; type Loaded = (Option, ExtractionStep); -/// Workspaces loaded from manifests, keeping the `capacity` most recently used ones so that they -/// need not be reloaded when extracting dependencies. Optionally, the manifest that is going to be -/// requested next is loaded in the background meanwhile. At most `capacity + 1` workspaces are -/// held at any time. +/// The workspace loaded from the last requested manifest, kept so that it need not be reloaded +/// if requested again. Optionally, the manifest that is going to be requested next is loaded in +/// the background meanwhile, so at most two workspaces are held at any time. pub struct LoadedWorkspaces<'m, W, L> { - /// Most recently used last. - loaded: Vec<(&'m ProjectManifest, W)>, + current: Option<(&'m ProjectManifest, W)>, prefetched: Option<(&'m ProjectManifest, JoinHandle>)>, load: Arc, - capacity: usize, prefetch: bool, } @@ -26,19 +23,17 @@ where W: Send + 'static, L: Fn(&ProjectManifest) -> Option + Send + Sync + 'static, { - pub fn new(capacity: usize, prefetch: bool, load: L) -> Self { - assert!(capacity > 0); + pub fn new(prefetch: bool, load: L) -> Self { Self { - loaded: Vec::with_capacity(capacity), + current: None, prefetched: None, load: Arc::new(load), - capacity, prefetch, } } pub fn contains(&self, manifest: &ProjectManifest) -> bool { - self.loaded.iter().any(|(m, _)| *m == manifest) + self.current.as_ref().is_some_and(|(m, _)| *m == manifest) } /// Returns the workspace of `manifest`, loading it unless still loaded, or `None` if it cannot @@ -49,27 +44,17 @@ where next: Option<&'m ProjectManifest>, steps: &mut Vec, ) -> Option<&W> { - let found = if let Some(index) = self.loaded.iter().position(|(m, _)| *m == manifest) { - let entry = self.loaded.remove(index); - self.loaded.push(entry); - true - } else { + if !self.contains(manifest) { let prefetched = self.take_prefetched(manifest, steps); + self.current = None; let (workspace, step) = prefetched.unwrap_or_else(|| load_timed(&*self.load, manifest)); steps.push(step); - workspace.is_some_and(|workspace| { - // evict before starting the next prefetch to bound the number of workspaces held - if self.loaded.len() == self.capacity { - self.loaded.remove(0); - } - self.loaded.push((manifest, workspace)); - true - }) - }; + self.current = workspace.map(|workspace| (manifest, workspace)); + } if let Some(next) = next { self.start_prefetch(next); } - let (_, workspace) = self.loaded.last().filter(|_| found)?; + let (_, workspace) = self.current.as_ref()?; Some(workspace) } @@ -132,29 +117,42 @@ mod tests { use super::*; use std::sync::Mutex; use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::mpsc::{Receiver, Sender, channel}; + use std::time::Duration; - #[derive(Default)] struct Stats { loads: Mutex>, live: AtomicUsize, peak: AtomicUsize, + /// Background loads wait for a message on this, so that tests can check that `get` + /// returns while the next workspace is still loading. + gate: Mutex>, } - struct Workspace(String, Arc); + struct Workspace(Arc); impl Drop for Workspace { fn drop(&mut self) { - self.1.live.fetch_sub(1, Ordering::SeqCst); + self.0.live.fetch_sub(1, Ordering::SeqCst); } } - fn manifests(names: &[&str]) -> Vec { + fn stats() -> (Arc, Sender<()>) { + let (sender, receiver) = channel(); + let stats = Stats { + loads: Mutex::default(), + live: AtomicUsize::default(), + peak: AtomicUsize::default(), + gate: Mutex::new(receiver), + }; + (Arc::new(stats), sender) + } + + fn manifests(names: [&str; N]) -> [ProjectManifest; N] { let root = crate::cwd().unwrap(); - names - .iter() - .map(|name| ProjectManifest::from_manifest_file(root.join(name).join("Cargo.toml"))) - .collect::>() - .unwrap() + names.map(|name| { + ProjectManifest::from_manifest_file(root.join(name).join("Cargo.toml")).unwrap() + }) } /// Loads workspaces named after their directory, failing for `broken`. @@ -164,6 +162,11 @@ mod tests { let name = manifest.manifest_path().parent().file_name()?.to_owned(); // test threads are named, background loading ones are not let background = std::thread::current().name().is_none(); + if background { + let gate = stats.gate.lock().unwrap(); + gate.recv_timeout(Duration::from_secs(10)) + .expect("background load not released"); + } let entry = format!("{name}{}", if background { " (background)" } else { "" }); stats.loads.lock().unwrap().push(entry); if name == "broken" { @@ -171,38 +174,43 @@ mod tests { } let live = stats.live.fetch_add(1, Ordering::SeqCst) + 1; stats.peak.fetch_max(live, Ordering::SeqCst); - Some(Workspace(name, Arc::clone(&stats))) + Some(Workspace(Arc::clone(&stats))) } } #[test] - fn reuses_most_recently_used_workspaces() { - let stats = Arc::default(); - let [a, b, c, broken]: &[_; 4] = &manifests(&["a", "b", "c", "broken"]).try_into().unwrap(); - let mut loaded = LoadedWorkspaces::new(2, false, loader(&stats)); + fn reuses_last_workspace() { + let (stats, _) = stats(); + let [a, b, broken] = &manifests(["a", "b", "broken"]); + let mut loaded = LoadedWorkspaces::new(false, loader(&stats)); let mut steps = Vec::new(); - for manifest in [a, b, a, c, b, broken, broken] { - let got = loaded.get(manifest, None, &mut steps).map(|w| w.0.clone()); + for manifest in [a, a, b, a, broken, broken] { + let got = loaded.get(manifest, None, &mut steps); assert_eq!(got.is_some(), manifest != broken); } - // `c` evicts `b`, the least recently used; failed loads are not kept + // failed loads are not kept assert_eq!( *stats.loads.lock().unwrap(), - ["a", "b", "c", "b", "broken", "broken"] + ["a", "b", "a", "broken", "broken"] ); - assert_eq!(steps.len(), 6); - assert!(loaded.contains(c) && loaded.contains(b) && !loaded.contains(a)); + assert_eq!(steps.len(), 5); + assert!(!loaded.contains(a)); + assert_eq!(stats.peak.load(Ordering::SeqCst), 1); } #[test] - fn prefetches_next_workspace_within_bound() { - let stats = Arc::default(); - let all = manifests(&["a", "b", "broken", "c", "d"]); - let mut loaded = LoadedWorkspaces::new(2, true, loader(&stats)); + fn loads_next_workspace_in_background() { + let (stats, release) = stats(); + let all = manifests(["a", "b", "broken", "c", "d"]); + let mut loaded = LoadedWorkspaces::new(true, loader(&stats)); let mut steps = Vec::new(); for (i, manifest) in all.iter().enumerate() { - let got = loaded.get(manifest, all.get(i + 1), &mut steps); + let next = all.get(i + 1); + let got = loaded.get(manifest, next, &mut steps); assert_eq!(got.is_some(), i != 2); + if next.is_some() { + release.send(()).unwrap(); + } } assert_eq!( *stats.loads.lock().unwrap(), @@ -215,7 +223,7 @@ mod tests { ] ); assert_eq!(steps.len(), 5); - assert!(stats.peak.load(Ordering::SeqCst) <= 3); + assert_eq!(stats.peak.load(Ordering::SeqCst), 2); drop(loaded); assert_eq!(stats.live.load(Ordering::SeqCst), 0); } From 27f48159f9668692efecfe46f6b4f917107fba62 Mon Sep 17 00:00:00 2001 From: Paolo Tranquilli Date: Wed, 2 Dec 2026 18:27:39 +0000 Subject: [PATCH 3/6] Rust: Update integration test steps for workspace reuse Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 8d0772f66a6b42c7b59d25b5e8f4073d --- rust/ql/integration-tests/workspace-with-glob/steps.expected | 1 - 1 file changed, 1 deletion(-) diff --git a/rust/ql/integration-tests/workspace-with-glob/steps.expected b/rust/ql/integration-tests/workspace-with-glob/steps.expected index 3ea9ee61bed3..4b0e6ed828b6 100644 --- a/rust/ql/integration-tests/workspace-with-glob/steps.expected +++ b/rust/ql/integration-tests/workspace-with-glob/steps.expected @@ -6,7 +6,6 @@ | lib/src/lib.rs:0:0:0:0 | Extract(lib/src/lib.rs) | | lib/src/lib.rs:0:0:0:0 | Parse(lib/src/lib.rs) | | other/Cargo.toml:0:0:0:0 | LoadManifest(other/Cargo.toml) | -| other/Cargo.toml:0:0:0:0 | LoadManifest(other/Cargo.toml) | | other/src/lib.rs:0:0:0:0 | Extract(other/src/lib.rs) | | other/src/lib.rs:0:0:0:0 | LoadSource(other/src/lib.rs) | | other/src/lib.rs:0:0:0:0 | Parse(other/src/lib.rs) | From 4c9ddfec9e37eb977d92f998d45766baa4fcdb47 Mon Sep 17 00:00:00 2001 From: Paolo Tranquilli Date: Thu, 3 Dec 2026 10:13:12 +0000 Subject: [PATCH 4/6] Rust: Test that dropping loaded workspaces waits for a background load Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 8d0772f66a6b42c7b59d25b5e8f4073d --- rust/extractor/src/workspaces.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/rust/extractor/src/workspaces.rs b/rust/extractor/src/workspaces.rs index 6b9c198d7c5f..56c4e7fea75e 100644 --- a/rust/extractor/src/workspaces.rs +++ b/rust/extractor/src/workspaces.rs @@ -227,4 +227,21 @@ mod tests { drop(loaded); assert_eq!(stats.live.load(Ordering::SeqCst), 0); } + + #[test] + fn drop_waits_for_background_load() { + let (stats, release) = stats(); + let [a, b] = &manifests(["a", "b"]); + let mut loaded = LoadedWorkspaces::new(true, loader(&stats)); + assert!(loaded.get(a, Some(b), &mut Vec::new()).is_some()); + let releaser = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(100)); + release.send(()).unwrap(); + }); + drop(loaded); + assert_eq!(*stats.loads.lock().unwrap(), ["a", "b (background)"]); + assert_eq!(stats.peak.load(Ordering::SeqCst), 2); + assert_eq!(stats.live.load(Ordering::SeqCst), 0); + releaser.join().unwrap(); + } } From b771b4bf8b2452a1db87a4d13891ef78b1a63326 Mon Sep 17 00:00:00 2001 From: Paolo Tranquilli Date: Thu, 3 Dec 2026 10:41:28 +0000 Subject: [PATCH 5/6] Rust: Test proc macros across concurrently loaded workspaces Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 8d0772f66a6b42c7b59d25b5e8f4073d --- .../integration-tests/proc-macro-workspaces/a/Cargo.toml | 8 ++++++++ .../integration-tests/proc-macro-workspaces/a/src/lib.rs | 5 +++++ .../integration-tests/proc-macro-workspaces/b/Cargo.toml | 8 ++++++++ .../integration-tests/proc-macro-workspaces/b/src/lib.rs | 5 +++++ .../proc-macro-workspaces/calls.expected | 2 ++ rust/ql/integration-tests/proc-macro-workspaces/calls.ql | 5 +++++ .../proc-macro-workspaces/macros/Cargo.toml | 8 ++++++++ .../proc-macro-workspaces/macros/src/lib.rs | 6 ++++++ .../proc-macro-workspaces/test_proc_macro_workspaces.py | 6 ++++++ 9 files changed, 53 insertions(+) create mode 100644 rust/ql/integration-tests/proc-macro-workspaces/a/Cargo.toml create mode 100644 rust/ql/integration-tests/proc-macro-workspaces/a/src/lib.rs create mode 100644 rust/ql/integration-tests/proc-macro-workspaces/b/Cargo.toml create mode 100644 rust/ql/integration-tests/proc-macro-workspaces/b/src/lib.rs create mode 100644 rust/ql/integration-tests/proc-macro-workspaces/calls.expected create mode 100644 rust/ql/integration-tests/proc-macro-workspaces/calls.ql create mode 100644 rust/ql/integration-tests/proc-macro-workspaces/macros/Cargo.toml create mode 100644 rust/ql/integration-tests/proc-macro-workspaces/macros/src/lib.rs create mode 100644 rust/ql/integration-tests/proc-macro-workspaces/test_proc_macro_workspaces.py diff --git a/rust/ql/integration-tests/proc-macro-workspaces/a/Cargo.toml b/rust/ql/integration-tests/proc-macro-workspaces/a/Cargo.toml new file mode 100644 index 000000000000..8be3201d8483 --- /dev/null +++ b/rust/ql/integration-tests/proc-macro-workspaces/a/Cargo.toml @@ -0,0 +1,8 @@ +[workspace] +[package] +name = "a" +version = "0.1.0" +edition = "2024" + +[dependencies] +macros = { path = "../macros" } diff --git a/rust/ql/integration-tests/proc-macro-workspaces/a/src/lib.rs b/rust/ql/integration-tests/proc-macro-workspaces/a/src/lib.rs new file mode 100644 index 000000000000..987118f4b777 --- /dev/null +++ b/rust/ql/integration-tests/proc-macro-workspaces/a/src/lib.rs @@ -0,0 +1,5 @@ +macros::generate!(a); + +pub fn call() -> u32 { + from_a() +} diff --git a/rust/ql/integration-tests/proc-macro-workspaces/b/Cargo.toml b/rust/ql/integration-tests/proc-macro-workspaces/b/Cargo.toml new file mode 100644 index 000000000000..f4800e33fb03 --- /dev/null +++ b/rust/ql/integration-tests/proc-macro-workspaces/b/Cargo.toml @@ -0,0 +1,8 @@ +[workspace] +[package] +name = "b" +version = "0.1.0" +edition = "2024" + +[dependencies] +macros = { path = "../macros" } diff --git a/rust/ql/integration-tests/proc-macro-workspaces/b/src/lib.rs b/rust/ql/integration-tests/proc-macro-workspaces/b/src/lib.rs new file mode 100644 index 000000000000..4ddd933d2f0c --- /dev/null +++ b/rust/ql/integration-tests/proc-macro-workspaces/b/src/lib.rs @@ -0,0 +1,5 @@ +macros::generate!(b); + +pub fn call() -> u32 { + from_b() +} diff --git a/rust/ql/integration-tests/proc-macro-workspaces/calls.expected b/rust/ql/integration-tests/proc-macro-workspaces/calls.expected new file mode 100644 index 000000000000..fac9fa604cdf --- /dev/null +++ b/rust/ql/integration-tests/proc-macro-workspaces/calls.expected @@ -0,0 +1,2 @@ +| a/src/lib.rs:4:5:4:12 | from_a(...) | a::from_a | +| b/src/lib.rs:4:5:4:12 | from_b(...) | b::from_b | diff --git a/rust/ql/integration-tests/proc-macro-workspaces/calls.ql b/rust/ql/integration-tests/proc-macro-workspaces/calls.ql new file mode 100644 index 000000000000..242ba6adb6d2 --- /dev/null +++ b/rust/ql/integration-tests/proc-macro-workspaces/calls.ql @@ -0,0 +1,5 @@ +import rust + +from Call c, Function target +where c.fromSource() and target = c.getStaticTarget() and target.getName().getText().matches("from_%") +select c, target.getCanonicalPath() diff --git a/rust/ql/integration-tests/proc-macro-workspaces/macros/Cargo.toml b/rust/ql/integration-tests/proc-macro-workspaces/macros/Cargo.toml new file mode 100644 index 000000000000..4c7ce9065891 --- /dev/null +++ b/rust/ql/integration-tests/proc-macro-workspaces/macros/Cargo.toml @@ -0,0 +1,8 @@ +[workspace] +[package] +name = "macros" +version = "0.1.0" +edition = "2024" + +[lib] +proc-macro = true diff --git a/rust/ql/integration-tests/proc-macro-workspaces/macros/src/lib.rs b/rust/ql/integration-tests/proc-macro-workspaces/macros/src/lib.rs new file mode 100644 index 000000000000..3ad686a8e52b --- /dev/null +++ b/rust/ql/integration-tests/proc-macro-workspaces/macros/src/lib.rs @@ -0,0 +1,6 @@ +extern crate proc_macro; + +#[proc_macro] +pub fn generate(input: proc_macro::TokenStream) -> proc_macro::TokenStream { + format!("pub fn from_{input}() -> u32 {{ 42 }}").parse().unwrap() +} diff --git a/rust/ql/integration-tests/proc-macro-workspaces/test_proc_macro_workspaces.py b/rust/ql/integration-tests/proc-macro-workspaces/test_proc_macro_workspaces.py new file mode 100644 index 000000000000..6f1a1dc7bfcf --- /dev/null +++ b/rust/ql/integration-tests/proc-macro-workspaces/test_proc_macro_workspaces.py @@ -0,0 +1,6 @@ +import pytest + + +@pytest.mark.parametrize("threads", [1, 4]) +def test_proc_macro_workspaces(codeql, rust, threads): + codeql.database.create(threads=threads) From 8f6861cb4c3e94e14064540d5fcd8c93cf4fefe5 Mon Sep 17 00:00:00 2001 From: Paolo Tranquilli Date: Thu, 3 Dec 2026 10:48:29 +0000 Subject: [PATCH 6/6] Rust: Format proc-macro workspaces test query Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 8d0772f66a6b42c7b59d25b5e8f4073d --- rust/ql/integration-tests/proc-macro-workspaces/calls.ql | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/rust/ql/integration-tests/proc-macro-workspaces/calls.ql b/rust/ql/integration-tests/proc-macro-workspaces/calls.ql index 242ba6adb6d2..8cb0f9b4dfd9 100644 --- a/rust/ql/integration-tests/proc-macro-workspaces/calls.ql +++ b/rust/ql/integration-tests/proc-macro-workspaces/calls.ql @@ -1,5 +1,6 @@ import rust from Call c, Function target -where c.fromSource() and target = c.getStaticTarget() and target.getName().getText().matches("from_%") +where + c.fromSource() and target = c.getStaticTarget() and target.getName().getText().matches("from_%") select c, target.getCanonicalPath()