From 0521b3058288a816e5b999a0553cdff84ae4effc Mon Sep 17 00:00:00 2001 From: Paolo Tranquilli Date: Wed, 2 Dec 2026 13:05:02 +0000 Subject: [PATCH 1/4] Rust: Prime crate def maps in dependency order before parallel extraction With more than one extraction thread, compute all crate def maps of a freshly loaded workspace in dependency order on that many threads. Otherwise extraction workers compute them lazily and mostly serialize on them. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 5d1bdb3a2b3c43ce80bf533edd8fc893 --- rust/extractor/src/main.rs | 42 ++++- rust/extractor/src/parallel.rs | 269 ++++++++++++++++++++++++++++++--- 2 files changed, 285 insertions(+), 26 deletions(-) diff --git a/rust/extractor/src/main.rs b/rust/extractor/src/main.rs index 4324dd28712c..8dc6db8a289f 100644 --- a/rust/extractor/src/main.rs +++ b/rust/extractor/src/main.rs @@ -15,7 +15,7 @@ use ra_ap_paths::{AbsPathBuf, Utf8PathBuf}; use ra_ap_project_model::{CargoConfig, ProjectManifest}; use ra_ap_vfs::Vfs; use rust_analyzer::{ParseResult, RustAnalyzer}; -use std::collections::{BTreeMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::fs::File; use std::io::{self, BufRead, BufReader}; use std::path::{Path, PathBuf}; @@ -259,6 +259,45 @@ impl<'a> Extractor<'a> { } } +/// Computes the def maps of all crates in dependency order on `threads` threads. +/// +/// Otherwise extraction workers compute them lazily, recursively including dependencies, which +/// mostly serializes the workers on them. +fn prime_def_maps(db: &RootDatabase, threads: usize) { + if threads <= 1 { + return; + } + let before = Instant::now(); + let crates = ra_ap_hir::Crate::all(db); + let index: HashMap<_, _> = crates.iter().enumerate().map(|(i, c)| (*c, i)).collect(); + let deps: Vec> = crates + .iter() + .map(|krate| { + krate + .dependencies(db) + .iter() + .filter_map(|dep| index.get(&dep.krate).copied()) + .collect() + }) + .collect(); + parallel::for_each_in_dependency_order( + threads, + &deps, + || db.clone(), + |db, i| { + // a failure resurfaces (and is handled) when extraction needs the same def map + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + crates[i].root_module(db); + })); + }, + ); + info!( + "computed def maps of {} crates in {:?}", + crates.len(), + before.elapsed() + ); +} + fn cwd() -> anyhow::Result { let path = std::env::current_dir().context("current directory")?; let utf8_path = Utf8PathBuf::from_path_buf(path) @@ -354,6 +393,7 @@ fn main() -> anyhow::Result<()> { extractor .steps .push(ExtractionStep::crate_graph(before_crate_graph)); + prime_def_maps(&db, threads); 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 { diff --git a/rust/extractor/src/parallel.rs b/rust/extractor/src/parallel.rs index a71eb4bba780..865c4bc88dd8 100644 --- a/rust/extractor/src/parallel.rs +++ b/rust/extractor/src/parallel.rs @@ -1,6 +1,7 @@ use codeql_extractor::options::parse_codeql_threads; use std::num::NonZero; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Condvar, Mutex}; use tracing::warn; /// Number of extraction threads, from `CODEQL_THREADS` (set by the CLI from `--threads`). @@ -35,6 +36,42 @@ impl Drop for AbortOnPanic<'_> { } } +/// Calls `run` on `threads` threads, each with its own result of `init` (called on the current +/// thread), returning the results. If `inline`, a single state runs on the current thread instead. +/// If a thread panics, the panic is propagated once all threads have finished. If a thread cannot +/// be spawned, `stop` is called to make the already spawned ones finish early before panicking. +fn run_on_threads( + inline: bool, + threads: usize, + mut init: impl FnMut() -> I, + run: impl Fn(I) -> O + Sync, + stop: impl Fn(), +) -> Vec { + if inline { + return vec![run(init())]; + } + let states: Vec<_> = (0..threads).map(|_| init()).collect(); + std::thread::scope(|scope| { + let handles: Vec<_> = states + .into_iter() + .map(|state| { + std::thread::Builder::new() + .stack_size(WORKER_STACK_SIZE) + .spawn_scoped(scope, || run(state)) + .unwrap_or_else(|e| { + stop(); + panic!("spawning extraction thread: {e}") + }) + }) + .collect(); + let joined: Vec<_> = handles.into_iter().map(|h| h.join()).collect(); + joined + .into_iter() + .map(|r| r.unwrap_or_else(|e| std::panic::resume_unwind(e))) + .collect() + }) +} + /// Processes `items` on up to `threads` threads pulling from a shared queue. /// /// For each thread, `init` is called on the current thread and its result is moved to that @@ -48,7 +85,7 @@ impl Drop for AbortOnPanic<'_> { pub fn parallel_map( threads: usize, items: &[T], - mut init: impl FnMut() -> I, + init: impl FnMut() -> I, worker: impl Fn(I, &mut dyn FnMut(&mut dyn FnMut(&T) -> R)) -> S + Sync, ) -> (Vec, Vec) where @@ -73,30 +110,9 @@ where }); (ret, results) }; - let outputs = if inline { - vec![run(init())] - } else { - let states: Vec<_> = (0..threads).map(|_| init()).collect(); - std::thread::scope(|scope| { - let handles: Vec<_> = states - .into_iter() - .map(|state| { - std::thread::Builder::new() - .stack_size(WORKER_STACK_SIZE) - .spawn_scoped(scope, || run(state)) - .unwrap_or_else(|e| { - abort.store(true, Ordering::Relaxed); - panic!("spawning extraction thread: {e}") - }) - }) - .collect(); - let joined: Vec<_> = handles.into_iter().map(|h| h.join()).collect(); - joined - .into_iter() - .map(|r| r.unwrap_or_else(|e| std::panic::resume_unwind(e))) - .collect::>() - }) - }; + let outputs = run_on_threads(inline, threads, init, run, || { + abort.store(true, Ordering::Relaxed); + }); let mut states = Vec::with_capacity(outputs.len()); let mut results = Vec::with_capacity(items.len()); for (state, worker_results) in outputs { @@ -108,6 +124,105 @@ where (states, results.into_iter().map(|(_, r)| r).collect()) } +struct Schedule { + ready: Vec, + missing_deps: Vec, + running: usize, + abort: bool, +} + +/// Marks a node as finished when dropped, releasing its dependents unless unwinding. +struct Finish<'a> { + node: usize, + schedule: &'a Mutex, + wakeup: &'a Condvar, + dependents: &'a [Vec], +} + +impl Drop for Finish<'_> { + fn drop(&mut self) { + let mut schedule = self.schedule.lock().unwrap(); + schedule.running -= 1; + if std::thread::panicking() { + schedule.abort = true; + } else { + for &dependent in &self.dependents[self.node] { + schedule.missing_deps[dependent] -= 1; + if schedule.missing_deps[dependent] == 0 { + schedule.ready.push(dependent); + } + } + } + self.wakeup.notify_all(); + } +} + +/// Calls `work` on each node of a dependency graph on up to `threads` threads, only once all +/// dependencies of that node have completed. `deps[i]` lists the nodes `i` depends on, and nodes +/// on or depending on a cycle are skipped. `init` is called on the current thread for each thread. +/// +/// If `work` panics, the other threads stop starting nodes and the panic is propagated once they +/// finish. +pub fn for_each_in_dependency_order( + threads: usize, + deps: &[Vec], + init: impl FnMut() -> I, + work: impl Fn(&mut I, usize) + Sync, +) { + let mut dependents = vec![Vec::new(); deps.len()]; + for (node, node_deps) in deps.iter().enumerate() { + for &dep in node_deps { + dependents[dep].push(node); + } + } + let missing_deps: Vec<_> = deps.iter().map(Vec::len).collect(); + let ready = (0..deps.len()).filter(|&i| missing_deps[i] == 0).collect(); + let schedule = Mutex::new(Schedule { + ready, + missing_deps, + running: 0, + abort: false, + }); + let wakeup = Condvar::new(); + let run = |mut state: I| { + loop { + let node = { + let mut schedule = schedule.lock().unwrap(); + loop { + if schedule.abort { + return; + } + if let Some(node) = schedule.ready.pop() { + schedule.running += 1; + break node; + } + if schedule.running == 0 { + return; + } + schedule = wakeup.wait(schedule).unwrap(); + } + }; + let _finish = Finish { + node, + schedule: &schedule, + wakeup: &wakeup, + dependents: &dependents, + }; + work(&mut state, node); + } + }; + run_on_threads( + threads <= 1, + threads.clamp(1, deps.len().max(1)), + init, + run, + || { + schedule.lock().unwrap().abort = true; + wakeup.notify_all(); + }, + ); +} + #[cfg(test)] mod tests { use super::*; @@ -225,4 +340,108 @@ mod tests { assert_eq!(results.len(), items.len()); } } + + fn run_graph(threads: usize, deps: &[Vec]) -> Vec { + let done: Vec<_> = deps.iter().map(|_| AtomicBool::new(false)).collect(); + let order = Mutex::new(Vec::new()); + let (running, max_running) = (AtomicUsize::new(0), AtomicUsize::new(0)); + for_each_in_dependency_order( + threads, + deps, + || (), + |(), node| { + let now = running.fetch_add(1, Ordering::SeqCst) + 1; + max_running.fetch_max(now, Ordering::SeqCst); + assert!(deps[node].iter().all(|&d| done[d].load(Ordering::SeqCst))); + std::thread::sleep(std::time::Duration::from_millis(1)); + done[node].store(true, Ordering::SeqCst); + order.lock().unwrap().push(node); + running.fetch_sub(1, Ordering::SeqCst); + }, + ); + assert!(max_running.into_inner() <= threads.max(1)); + order.into_inner().unwrap() + } + + #[test] + fn dependency_order_is_respected() { + // a diamond on top of independent chains + let mut deps = vec![vec![], vec![0], vec![0], vec![1, 2]]; + for i in 4..40 { + deps.push(if i % 4 == 0 { vec![] } else { vec![i - 1, 3] }); + } + for threads in [1, 2, 8] { + let mut order = run_graph(threads, &deps); + order.sort_unstable(); + assert_eq!(order, (0..deps.len()).collect::>()); + } + } + + #[test] + fn empty_graph_terminates() { + assert_eq!(run_graph(4, &[]), Vec::::new()); + } + + #[test] + fn cycles_are_skipped() { + let deps = [vec![1], vec![0], vec![1], vec![], vec![3], vec![5]]; + for threads in [1, 4] { + let mut order = run_graph(threads, &deps); + order.sort_unstable(); + assert_eq!(order, [3, 4]); + } + } + + #[test] + fn dependency_order_panic_propagates() { + // `49` is started first, and the other ready nodes are queued behind it + let deps: Vec<_> = (0..100) + .map(|i| if i < 50 { vec![] } else { vec![49] }) + .collect(); + let started = AtomicUsize::new(0); + let panicking = AtomicBool::new(false); + let result = std::panic::catch_unwind(|| { + for_each_in_dependency_order( + 2, + &deps, + || (), + |(), node| { + started.fetch_add(1, Ordering::SeqCst); + if node == 49 { + panicking.store(true, Ordering::SeqCst); + std::panic::panic_any(node); + } + // give the panic time to reach the scheduler + while !panicking.load(Ordering::SeqCst) { + std::thread::yield_now(); + } + std::thread::sleep(std::time::Duration::from_millis(200)); + }, + ); + }); + assert_eq!(*result.unwrap_err().downcast::().unwrap(), 49); + // after the panic no queued node or dependent is started + assert!(started.into_inner() <= 2); + } + + #[test] + fn dependency_order_runs_in_parallel() { + let arrived = AtomicUsize::new(0); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + for_each_in_dependency_order( + 2, + &[vec![], vec![]], + || (), + |(), _| { + arrived.fetch_add(1, Ordering::SeqCst); + while arrived.load(Ordering::SeqCst) < 2 { + assert!( + std::time::Instant::now() < deadline, + "nodes did not overlap" + ); + std::thread::yield_now(); + } + }, + ); + } } From 32bb6c540e5f1961b49caef495e599f7038eb7cc Mon Sep 17 00:00:00 2001 From: Paolo Tranquilli Date: Wed, 2 Dec 2026 14:12:50 +0000 Subject: [PATCH 2/4] Rust: Prime only def maps needed by extracted files Also synchronize the panic test on worker unwinding instead of a sleep. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 5d1bdb3a2b3c43ce80bf533edd8fc893 --- rust/extractor/src/main.rs | 44 +++++++++++++++++++++++----------- rust/extractor/src/parallel.rs | 21 ++++++++++------ 2 files changed, 44 insertions(+), 21 deletions(-) diff --git a/rust/extractor/src/main.rs b/rust/extractor/src/main.rs index 8dc6db8a289f..04c8eafd9e0c 100644 --- a/rust/extractor/src/main.rs +++ b/rust/extractor/src/main.rs @@ -259,27 +259,43 @@ impl<'a> Extractor<'a> { } } -/// Computes the def maps of all crates in dependency order on `threads` threads. +/// Computes the def maps of the crates of `files` and their dependencies in dependency order on +/// `threads` threads. /// /// Otherwise extraction workers compute them lazily, recursively including dependencies, which /// mostly serializes the workers on them. -fn prime_def_maps(db: &RootDatabase, threads: usize) { +fn prime_def_maps<'a>( + db: &RootDatabase, + vfs: &Vfs, + files: impl IntoIterator, + threads: usize, +) { if threads <= 1 { return; } let before = Instant::now(); - let crates = ra_ap_hir::Crate::all(db); - let index: HashMap<_, _> = crates.iter().enumerate().map(|(i, c)| (*c, i)).collect(); - let deps: Vec> = crates - .iter() - .map(|krate| { - krate - .dependencies(db) - .iter() - .filter_map(|dep| index.get(&dep.krate).copied()) - .collect() - }) + let mut crates: Vec = files + .into_iter() + .filter_map(|file| path_to_file_id(file, vfs)) + .flat_map(|file_id| ra_ap_base_db::relevant_crates(db, file_id)) + .map(|&krate| krate.into()) + .unique() .collect(); + let mut index: HashMap<_, _> = crates.iter().enumerate().map(|(i, c)| (*c, i)).collect(); + let mut deps: Vec> = Vec::new(); + while deps.len() < crates.len() { + let krate_deps = crates[deps.len()] + .dependencies(db) + .into_iter() + .map(|dep| { + *index.entry(dep.krate).or_insert_with(|| { + crates.push(dep.krate); + crates.len() - 1 + }) + }) + .collect(); + deps.push(krate_deps); + } parallel::for_each_in_dependency_order( threads, &deps, @@ -393,12 +409,12 @@ fn main() -> anyhow::Result<()> { extractor .steps .push(ExtractionStep::crate_graph(before_crate_graph)); - prime_def_maps(&db, threads); 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))); } + prime_def_maps(&db, &vfs, items.iter().map(|(f, _)| *f), threads); debug_assert!(items.iter().map(|(f, _)| f).all_unique()); extractor.run_parallel( &db, diff --git a/rust/extractor/src/parallel.rs b/rust/extractor/src/parallel.rs index 865c4bc88dd8..141f5509310e 100644 --- a/rust/extractor/src/parallel.rs +++ b/rust/extractor/src/parallel.rs @@ -394,28 +394,35 @@ mod tests { #[test] fn dependency_order_panic_propagates() { + /// Flags when a worker's state is dropped by unwinding, which happens after the + /// scheduler has recorded the panic. + struct OnUnwind<'a>(&'a AtomicBool); + impl Drop for OnUnwind<'_> { + fn drop(&mut self) { + if std::thread::panicking() { + self.0.store(true, Ordering::SeqCst); + } + } + } // `49` is started first, and the other ready nodes are queued behind it let deps: Vec<_> = (0..100) .map(|i| if i < 50 { vec![] } else { vec![49] }) .collect(); let started = AtomicUsize::new(0); - let panicking = AtomicBool::new(false); + let unwound = AtomicBool::new(false); let result = std::panic::catch_unwind(|| { for_each_in_dependency_order( 2, &deps, - || (), - |(), node| { + || OnUnwind(&unwound), + |_, node| { started.fetch_add(1, Ordering::SeqCst); if node == 49 { - panicking.store(true, Ordering::SeqCst); std::panic::panic_any(node); } - // give the panic time to reach the scheduler - while !panicking.load(Ordering::SeqCst) { + while !unwound.load(Ordering::SeqCst) { std::thread::yield_now(); } - std::thread::sleep(std::time::Duration::from_millis(200)); }, ); }); From 82550886e5f6f0338c6095b3d9eaf539d97a1641 Mon Sep 17 00:00:00 2001 From: Paolo Tranquilli Date: Wed, 2 Dec 2026 14:45:53 +0000 Subject: [PATCH 3/4] Rust: Test dependency closure used for def map priming Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 5d1bdb3a2b3c43ce80bf533edd8fc893 --- rust/extractor/src/main.rs | 26 +++++----------------- rust/extractor/src/parallel.rs | 40 ++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 20 deletions(-) diff --git a/rust/extractor/src/main.rs b/rust/extractor/src/main.rs index 04c8eafd9e0c..86719891077c 100644 --- a/rust/extractor/src/main.rs +++ b/rust/extractor/src/main.rs @@ -15,7 +15,7 @@ use ra_ap_paths::{AbsPathBuf, Utf8PathBuf}; use ra_ap_project_model::{CargoConfig, ProjectManifest}; use ra_ap_vfs::Vfs; use rust_analyzer::{ParseResult, RustAnalyzer}; -use std::collections::{BTreeMap, HashMap, HashSet}; +use std::collections::{BTreeMap, HashSet}; use std::fs::File; use std::io::{self, BufRead, BufReader}; use std::path::{Path, PathBuf}; @@ -274,28 +274,14 @@ fn prime_def_maps<'a>( return; } let before = Instant::now(); - let mut crates: Vec = files + let roots = files .into_iter() .filter_map(|file| path_to_file_id(file, vfs)) .flat_map(|file_id| ra_ap_base_db::relevant_crates(db, file_id)) - .map(|&krate| krate.into()) - .unique() - .collect(); - let mut index: HashMap<_, _> = crates.iter().enumerate().map(|(i, c)| (*c, i)).collect(); - let mut deps: Vec> = Vec::new(); - while deps.len() < crates.len() { - let krate_deps = crates[deps.len()] - .dependencies(db) - .into_iter() - .map(|dep| { - *index.entry(dep.krate).or_insert_with(|| { - crates.push(dep.krate); - crates.len() - 1 - }) - }) - .collect(); - deps.push(krate_deps); - } + .map(|&krate| ra_ap_hir::Crate::from(krate)); + let (crates, deps) = parallel::dependency_closure(roots, |krate| { + krate.dependencies(db).into_iter().map(|dep| dep.krate) + }); parallel::for_each_in_dependency_order( threads, &deps, diff --git a/rust/extractor/src/parallel.rs b/rust/extractor/src/parallel.rs index 141f5509310e..c38490a761ab 100644 --- a/rust/extractor/src/parallel.rs +++ b/rust/extractor/src/parallel.rs @@ -1,4 +1,6 @@ use codeql_extractor::options::parse_codeql_threads; +use std::collections::HashMap; +use std::hash::Hash; use std::num::NonZero; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Condvar, Mutex}; @@ -124,6 +126,35 @@ where (states, results.into_iter().map(|(_, r)| r).collect()) } +/// Collects `roots` and everything they transitively depend on according to `deps_of`, returning +/// those nodes and, for each of them, the indexes of its dependencies, as expected by +/// [`for_each_in_dependency_order`]. +pub fn dependency_closure>( + roots: impl IntoIterator, + deps_of: impl Fn(T) -> D, +) -> (Vec, Vec>) { + let mut nodes = Vec::new(); + let mut index = HashMap::new(); + let mut add = |nodes: &mut Vec, node| { + *index.entry(node).or_insert_with(|| { + nodes.push(node); + nodes.len() - 1 + }) + }; + for root in roots { + add(&mut nodes, root); + } + let mut deps = Vec::new(); + while deps.len() < nodes.len() { + let node_deps = deps_of(nodes[deps.len()]) + .into_iter() + .map(|dep| add(&mut nodes, dep)) + .collect(); + deps.push(node_deps); + } + (nodes, deps) +} + struct Schedule { ready: Vec, missing_deps: Vec, @@ -363,6 +394,15 @@ mod tests { order.into_inner().unwrap() } + #[test] + fn dependency_closure_excludes_unrelated_nodes() { + // 0 -> 1 -> 2, 3 -> 2, 4 -> 0 and 5 are unrelated to the root 0 + let graph = [vec![1], vec![2], vec![], vec![2], vec![0], vec![]]; + let (nodes, deps) = dependency_closure([0, 0], |node: usize| graph[node].clone()); + assert_eq!(nodes, [0, 1, 2]); + assert_eq!(deps, [vec![1], vec![2], vec![]]); + } + #[test] fn dependency_order_is_respected() { // a diamond on top of independent chains From 4d971dc48efe73338ce9a423533166d6d0d603a4 Mon Sep 17 00:00:00 2001 From: Paolo Tranquilli Date: Thu, 3 Dec 2026 10:17:09 +0000 Subject: [PATCH 4/4] Rust: Clarify def-map priming log The count includes crates whose def map failed or was skipped in a cycle. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 5d1bdb3a2b3c43ce80bf533edd8fc893 --- rust/extractor/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/extractor/src/main.rs b/rust/extractor/src/main.rs index 86719891077c..30a78611b9b2 100644 --- a/rust/extractor/src/main.rs +++ b/rust/extractor/src/main.rs @@ -294,7 +294,7 @@ fn prime_def_maps<'a>( }, ); info!( - "computed def maps of {} crates in {:?}", + "considered {} crates for def-map priming in {:?}", crates.len(), before.elapsed() );