diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 89d4d91f561c..5d0aeae3c5cc 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -63,6 +63,9 @@ jobs: - name: Compilation shell: bash run: cargo check + - name: Unit tests + shell: bash + run: cargo test rust-codegen: runs-on: ubuntu-latest steps: diff --git a/rust/extractor/src/diagnostics.rs b/rust/extractor/src/diagnostics.rs index 8b84f6074351..937973d08f57 100644 --- a/rust/extractor/src/diagnostics.rs +++ b/rust/extractor/src/diagnostics.rs @@ -204,6 +204,7 @@ impl Display for HumanReadableDuration { #[derive(Debug, Default, Clone, Serialize)] #[serde(rename_all = "camelCase")] struct DurationsSummary { + /// Summed over all extraction threads, so with more than one thread these may exceed `total`. #[serde(flatten)] durations: HashMap, total: HumanReadableDuration, diff --git a/rust/extractor/src/main.rs b/rust/extractor/src/main.rs index 92f119b68777..4324dd28712c 100644 --- a/rust/extractor/src/main.rs +++ b/rust/extractor/src/main.rs @@ -6,6 +6,7 @@ use crate::trap::TrapId; use anyhow::Context; use archive::Archiver; use configuration::{DependencyFiles, dependency_files, manifest_parent}; +use itertools::Itertools; use ra_ap_hir::Semantics; use ra_ap_ide_db::RootDatabase; use ra_ap_ide_db::line_index::{LineCol, LineIndex}; @@ -30,6 +31,7 @@ mod configuration; mod crate_graph; mod diagnostics; pub mod generated; +mod parallel; mod qltest; mod rust_analyzer; mod toolchain; @@ -194,6 +196,33 @@ impl<'a> Extractor<'a> { Ok(()) } + /// Runs `work` on `items` using up to `threads` workers, each with its own `Extractor` and + /// `Semantics` over a clone of `db` (sharing its query storage). Returns results in item order. + fn run_parallel( + &mut self, + db: &RootDatabase, + vfs: &Vfs, + threads: usize, + items: &[T], + work: impl for<'s> Fn(&mut Extractor<'a>, &'s Semantics<'s, RootDatabase>, &'s Vfs, &T) -> R + + Sync, + ) -> Vec { + let (archiver, traps) = (self.archiver, self.traps); + let (steps, results) = parallel::parallel_map( + threads, + items, + || db.clone(), + |db, drive| { + let semantics = Semantics::new(&db); + let mut extractor = Extractor::new(archiver, traps); + drive(&mut |item| work(&mut extractor, &semantics, vfs, item)); + extractor.steps + }, + ); + self.steps.extend(steps.into_iter().flatten()); + results + } + pub fn find_manifests(&mut self, files: &[PathBuf]) -> anyhow::Result> { let before = Instant::now(); let ret = rust_analyzer::find_project_manifests(files); @@ -288,6 +317,8 @@ fn main() -> anyhow::Result<()> { // [1]: https://github.com/rust-lang/rust-analyzer/issues/18894#issuecomment-2580014730 dunce::canonicalize(&file).unwrap_or(file) }) + // each file must be extracted at most once at a time, as trap and archive writes are not atomic + .unique() .collect::>(); let manifests = extractor.find_manifests(&files)?; let workspaces = extractor.group_files(&manifests, &files); @@ -305,6 +336,8 @@ fn main() -> anyhow::Result<()> { SourceKind::Source }; let source_files = HashSet::from_iter(files.iter().cloned()); + let threads = parallel::extraction_threads(); + info!("extraction threads: {threads}"); let mut dependencies = DependencyFiles::default(); @@ -321,19 +354,32 @@ fn main() -> anyhow::Result<()> { extractor .steps .push(ExtractionStep::crate_graph(before_crate_graph)); - let semantics = Semantics::new(&db); - for file in files { - match extractor.load_source(file, &semantics, &vfs) { - Ok(()) => extractor.extract_with_semantics(file, &semantics, &vfs, source_mode), - Err(e) => extractor.extract_without_semantics(file, source_mode, e), - } - } + 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 { - for (_, file) in dependency_files(&db, &vfs, &source_files) { - extractor.extract_with_semantics(file, &semantics, &vfs, library_mode); - } - } else { + items.extend(dependency_files(&db, &vfs, &source_files).map(|(_, f)| (f, false))); + } + debug_assert!(items.iter().map(|(f, _)| f).all_unique()); + extractor.run_parallel( + &db, + &vfs, + threads, + &items, + |extractor, semantics, vfs, &(file, is_source)| { + if !is_source { + extractor.extract_with_semantics(file, semantics, vfs, library_mode); + return; + } + match extractor.load_source(file, semantics, vfs) { + Ok(()) => { + extractor.extract_with_semantics(file, semantics, vfs, source_mode); + } + Err(e) => extractor.extract_without_semantics(file, source_mode, e), + } + }, + ); + if !dependency_extraction_ambiguity { + let semantics = Semantics::new(&db); dependencies.add_manifest(manifest, &semantics, &vfs, &source_files); } } else { @@ -359,21 +405,41 @@ fn main() -> anyhow::Result<()> { if let Some((db, vfs)) = extractor.load_manifest(manifest, &cargo_config, &load_cargo_config) { - let semantics = Semantics::new(&db); - for file in files { - // A richer configuration can disable a file when using cfg - // options like `#[cfg(not(feature = "foo"))]`. When this is - // the case `file_to_module_def` will return `None` for the - // file. When this is the case and there are alternatives we - // do not extract the file yet. Instead the file will be - // considered again in the next iteration of the loop. - if !dependencies.has_alternative(&file) - || path_to_file_id(&file, &vfs) - .and_then(|id| semantics.file_to_module_def(id)) - .is_some() - { - extractor.extract_with_semantics(&file, &semantics, &vfs, library_mode); - dependencies.extracted(&file); + // `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 + .into_iter() + .map(|file| { + let has_alternative = dependencies.has_alternative(&file); + (file, has_alternative) + }) + .collect(); + debug_assert!(items.iter().map(|(f, _)| f).all_unique()); + let extracted = extractor.run_parallel( + &db, + &vfs, + threads, + &items, + |extractor, semantics, vfs, (file, has_alternative)| { + // A richer configuration can disable a file when using cfg + // options like `#[cfg(not(feature = "foo"))]`. When this is + // the case `file_to_module_def` will return `None` for the + // file. When this is the case and there are alternatives we + // do not extract the file yet. Instead the file will be + // considered again in the next iteration of the loop. + let extract = !has_alternative + || path_to_file_id(file, vfs) + .and_then(|id| semantics.file_to_module_def(id)) + .is_some(); + if extract { + extractor.extract_with_semantics(file, semantics, vfs, library_mode); + } + extract + }, + ); + for ((file, _), extracted) in items.iter().zip(extracted) { + if extracted { + dependencies.extracted(file); } } } else { diff --git a/rust/extractor/src/parallel.rs b/rust/extractor/src/parallel.rs new file mode 100644 index 000000000000..a71eb4bba780 --- /dev/null +++ b/rust/extractor/src/parallel.rs @@ -0,0 +1,228 @@ +use codeql_extractor::options::parse_codeql_threads; +use std::num::NonZero; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use tracing::warn; + +/// Number of extraction threads, from `CODEQL_THREADS` (set by the CLI from `--threads`). +/// +/// Unlike the extractor spec default of `-1`, extraction stays sequential when the variable is +/// unset or invalid. +pub fn extraction_threads() -> usize { + let cores = std::thread::available_parallelism().map_or(1, NonZero::get); + threads_from(std::env::var("CODEQL_THREADS").ok().as_deref(), cores) +} + +fn threads_from(value: Option<&str>, cores: usize) -> usize { + let Some(value) = value else { return 1 }; + parse_codeql_threads(value.trim(), cores).unwrap_or_else(|| { + warn!("ignoring invalid CODEQL_THREADS value '{value}'"); + 1 + }) +} + +/// 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; + +/// Sets the flag if the current thread unwinds while this is alive. +struct AbortOnPanic<'a>(&'a AtomicBool); + +impl Drop for AbortOnPanic<'_> { + fn drop(&mut self) { + if std::thread::panicking() { + self.0.store(true, Ordering::Relaxed); + } + } +} + +/// 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 +/// thread's `worker`, which must call the given `drive` callback once with the per-item function. +/// This allows per-thread state borrowing from values owned by the thread. Returns the `worker` +/// results and the per-item results, the latter in the order of `items`. +/// +/// If `threads` is 1, everything runs on the current thread; otherwise, even a single item is +/// processed on a spawned thread with a large stack. If a thread panics, the others +/// stop claiming items and the panic is propagated once they finish. +pub fn parallel_map( + threads: usize, + items: &[T], + mut init: impl FnMut() -> I, + worker: impl Fn(I, &mut dyn FnMut(&mut dyn FnMut(&T) -> R)) -> S + Sync, +) -> (Vec, Vec) +where + T: Sync, + I: Send, + S: Send, + R: Send, +{ + let inline = threads <= 1; + let threads = threads.clamp(1, items.len().max(1)); + let next = AtomicUsize::new(0); + let abort = AtomicBool::new(false); + let run = |state: I| { + let _guard = AbortOnPanic(&abort); + let mut results = Vec::new(); + let ret = worker(state, &mut |f| { + while !abort.load(Ordering::Relaxed) { + let i = next.fetch_add(1, Ordering::Relaxed); + let Some(item) = items.get(i) else { break }; + results.push((i, f(item))); + } + }); + (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 mut states = Vec::with_capacity(outputs.len()); + let mut results = Vec::with_capacity(items.len()); + for (state, worker_results) in outputs { + states.push(state); + results.extend(worker_results); + } + results.sort_unstable_by_key(|(i, _)| *i); + debug_assert_eq!(results.len(), items.len()); + (states, results.into_iter().map(|(_, r)| r).collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::thread::ThreadId; + + #[test] + fn threads_from_env() { + assert_eq!(threads_from(None, 8), 1); + assert_eq!(threads_from(Some(""), 8), 1); + assert_eq!(threads_from(Some("many"), 8), 1); + assert_eq!(threads_from(Some("1"), 8), 1); + assert_eq!(threads_from(Some(" 4\n"), 8), 4); + assert_eq!(threads_from(Some("16"), 8), 16); + assert_eq!(threads_from(Some("0"), 8), 8); + assert_eq!(threads_from(Some("-2"), 8), 6); + assert_eq!(threads_from(Some("-8"), 8), 1); + assert_eq!(threads_from(Some("-100"), 8), 1); + } + + fn map_threads(threads: usize, items: &[usize]) -> (Vec, Vec<(usize, ThreadId)>) { + parallel_map( + threads, + items, + || (), + |(), drive| { + let mut count = 0; + drive(&mut |&item| { + count += 1; + (item * 2, std::thread::current().id()) + }); + count + }, + ) + } + + #[test] + fn results_follow_item_order() { + let items: Vec = (0..1000).collect(); + for threads in [1, 3, 8] { + let (counts, results) = map_threads(threads, &items); + assert_eq!(counts.len(), threads); + assert_eq!(counts.iter().sum::(), items.len()); + let doubled: Vec<_> = results.iter().map(|(r, _)| *r).collect(); + assert_eq!(doubled, items.iter().map(|i| i * 2).collect::>()); + } + } + + #[test] + fn single_thread_runs_inline() { + let (counts, results) = map_threads(1, &[1, 2, 3]); + assert_eq!(counts, [3]); + let current = std::thread::current().id(); + assert!(results.iter().all(|(_, id)| *id == current)); + } + + #[test] + fn threads_are_capped_by_items() { + assert_eq!(map_threads(8, &[1, 2]).0.len(), 2); + assert_eq!(map_threads(8, &[]), (vec![0], vec![])); + let (counts, results) = map_threads(8, &[1]); + assert_eq!(counts, [1]); + assert_ne!(results[0].1, std::thread::current().id()); + } + + #[test] + fn panic_propagates() { + let items: Vec = (0..100).collect(); + let result = std::panic::catch_unwind(|| { + parallel_map( + 4, + &items, + || (), + |(), drive| { + drive(&mut |&item| { + if item == 10 { + std::panic::panic_any(item); + } + }); + }, + ) + }); + assert_eq!(*result.unwrap_err().downcast::().unwrap(), 10); + } + + #[test] + fn abort_guard_flags_only_on_panic() { + let abort = AtomicBool::new(false); + drop(AbortOnPanic(&abort)); + assert!(!abort.load(Ordering::Relaxed)); + let _ = std::panic::catch_unwind(|| { + let _guard = AbortOnPanic(&abort); + panic!("boom"); + }); + assert!(abort.load(Ordering::Relaxed)); + } + + #[test] + fn workers_have_large_stacks() { + fn recurse(depth: usize) -> usize { + let buf = std::hint::black_box([depth as u8; 1024]); + if depth == 0 { + buf[0] as usize + } else { + recurse(depth - 1) + buf[1] as usize + } + } + // needs well over the default 2 MiB thread stack + for items in [&[6000, 6000][..], &[6000]] { + let (_, results) = parallel_map( + 2, + items, + || (), + |(), drive| drive(&mut |&depth| recurse(depth)), + ); + assert_eq!(results.len(), items.len()); + } + } +} diff --git a/rust/ql/integration-tests/deep-expression/Cargo.toml b/rust/ql/integration-tests/deep-expression/Cargo.toml new file mode 100644 index 000000000000..0d385afff3ad --- /dev/null +++ b/rust/ql/integration-tests/deep-expression/Cargo.toml @@ -0,0 +1,7 @@ +[workspace] +[package] +name = "deep_expression" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/rust/ql/integration-tests/deep-expression/src/.gitignore b/rust/ql/integration-tests/deep-expression/src/.gitignore new file mode 100644 index 000000000000..0a1d0eb22ded --- /dev/null +++ b/rust/ql/integration-tests/deep-expression/src/.gitignore @@ -0,0 +1 @@ +deep.rs diff --git a/rust/ql/integration-tests/deep-expression/src/lib.rs b/rust/ql/integration-tests/deep-expression/src/lib.rs new file mode 100644 index 000000000000..f4c9b954f9e0 --- /dev/null +++ b/rust/ql/integration-tests/deep-expression/src/lib.rs @@ -0,0 +1,2 @@ +mod deep; +mod shallow; diff --git a/rust/ql/integration-tests/deep-expression/src/shallow.rs b/rust/ql/integration-tests/deep-expression/src/shallow.rs new file mode 100644 index 000000000000..541e5bd47198 --- /dev/null +++ b/rust/ql/integration-tests/deep-expression/src/shallow.rs @@ -0,0 +1,3 @@ +pub fn shallow() -> i32 { + 1 +} diff --git a/rust/ql/integration-tests/deep-expression/steps.expected b/rust/ql/integration-tests/deep-expression/steps.expected new file mode 100644 index 000000000000..58a01cf5cd12 --- /dev/null +++ b/rust/ql/integration-tests/deep-expression/steps.expected @@ -0,0 +1,9 @@ +| src/deep.rs:0:0:0:0 | Extract(src/deep.rs) | +| src/deep.rs:0:0:0:0 | LoadSource(src/deep.rs) | +| src/deep.rs:0:0:0:0 | Parse(src/deep.rs) | +| src/lib.rs:0:0:0:0 | Extract(src/lib.rs) | +| src/lib.rs:0:0:0:0 | LoadSource(src/lib.rs) | +| src/lib.rs:0:0:0:0 | Parse(src/lib.rs) | +| src/shallow.rs:0:0:0:0 | Extract(src/shallow.rs) | +| src/shallow.rs:0:0:0:0 | LoadSource(src/shallow.rs) | +| src/shallow.rs:0:0:0:0 | Parse(src/shallow.rs) | diff --git a/rust/ql/integration-tests/deep-expression/steps.ql b/rust/ql/integration-tests/deep-expression/steps.ql new file mode 100644 index 000000000000..3465f67608a8 --- /dev/null +++ b/rust/ql/integration-tests/deep-expression/steps.ql @@ -0,0 +1,5 @@ +import codeql.rust.elements.internal.ExtractorStep + +from ExtractorStep step +where step.getAction() = ["LoadSource", "Parse", "Extract"] +select step diff --git a/rust/ql/integration-tests/deep-expression/test_deep_expression.py b/rust/ql/integration-tests/deep-expression/test_deep_expression.py new file mode 100644 index 000000000000..6c6d4206a085 --- /dev/null +++ b/rust/ql/integration-tests/deep-expression/test_deep_expression.py @@ -0,0 +1,6 @@ +def test_deep_expression_in_parallel(codeql, rust, cwd): + # Extraction recurses on this, overflowing a default-sized thread stack. Only workers get a + # large stack (the main thread has 1 MiB on Windows), so use more than one thread. + terms = " + ".join(["1"] * 10_000) + (cwd / "src" / "deep.rs").write_text(f"pub fn deep() -> i32 {{\n {terms}\n}}\n") + codeql.database.create(threads=2) diff --git a/rust/ql/integration-tests/dependency-features/test_dependency_features.py b/rust/ql/integration-tests/dependency-features/test_dependency_features.py index a7da594e6908..cddddf1af509 100644 --- a/rust/ql/integration-tests/dependency-features/test_dependency_features.py +++ b/rust/ql/integration-tests/dependency-features/test_dependency_features.py @@ -23,7 +23,8 @@ for reverse in [False, True] ], ) -def test_dependency_features(codeql, rust, cwd, configurations, reverse): +@pytest.mark.parametrize("threads", [1, 4]) +def test_dependency_features(codeql, rust, cwd, configurations, reverse, threads): """ Two independent workspaces, `source/first` and `source/second`, share the local dependencies `alpha` and `beta`, but enable different Cargo features @@ -79,4 +80,4 @@ def test_dependency_features(codeql, rust, cwd, configurations, reverse): + "\n" ) commands.run(f'cargo check --quiet --manifest-path "{manifest}"') - codeql.database.create(source_root="source") + codeql.database.create(source_root="source", threads=threads) diff --git a/rust/ql/integration-tests/parallel-extraction/Cargo.toml b/rust/ql/integration-tests/parallel-extraction/Cargo.toml new file mode 100644 index 000000000000..3f2716385bd2 --- /dev/null +++ b/rust/ql/integration-tests/parallel-extraction/Cargo.toml @@ -0,0 +1,7 @@ +[workspace] +[package] +name = "parallel_extraction" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/rust/ql/integration-tests/parallel-extraction/calls.expected b/rust/ql/integration-tests/parallel-extraction/calls.expected new file mode 100644 index 000000000000..9d0f441265ca --- /dev/null +++ b/rust/ql/integration-tests/parallel-extraction/calls.expected @@ -0,0 +1,5 @@ +| src/caller.rs:4:5:4:9 | one(...) | parallel_extraction::helpers::one | +| src/caller.rs:8:24:8:42 | ... + ... | ::add | +| src/caller.rs:8:24:8:42 | ...::two(...) | parallel_extraction::helpers::two | +| src/caller.rs:8:24:8:42 | ...::two(...) | parallel_extraction::helpers::two | +| src/helpers.rs:13:5:13:29 | ...::call_one(...) | parallel_extraction::caller::call_one | diff --git a/rust/ql/integration-tests/parallel-extraction/calls.ql b/rust/ql/integration-tests/parallel-extraction/calls.ql new file mode 100644 index 000000000000..cf1af6d37f5e --- /dev/null +++ b/rust/ql/integration-tests/parallel-extraction/calls.ql @@ -0,0 +1,5 @@ +import rust + +from Call c +where c.fromSource() +select c, c.getStaticTarget().getCanonicalPath() diff --git a/rust/ql/integration-tests/parallel-extraction/src/caller.rs b/rust/ql/integration-tests/parallel-extraction/src/caller.rs new file mode 100644 index 000000000000..1a34a2913caf --- /dev/null +++ b/rust/ql/integration-tests/parallel-extraction/src/caller.rs @@ -0,0 +1,9 @@ +use crate::helpers::one; + +pub fn call_one() -> i32 { + one() +} + +pub fn call_macro() -> i32 { + crate::call_twice!(crate::helpers::two) +} diff --git a/rust/ql/integration-tests/parallel-extraction/src/helpers.rs b/rust/ql/integration-tests/parallel-extraction/src/helpers.rs new file mode 100644 index 000000000000..2174165e470c --- /dev/null +++ b/rust/ql/integration-tests/parallel-extraction/src/helpers.rs @@ -0,0 +1,14 @@ +#[macro_export] +macro_rules! call_twice { + ($f:path) => { + $f() + $f() + }; +} + +pub fn one() -> i32 { + 1 +} + +pub fn two() -> i32 { + crate::caller::call_one() +} diff --git a/rust/ql/integration-tests/parallel-extraction/src/lib.rs b/rust/ql/integration-tests/parallel-extraction/src/lib.rs new file mode 100644 index 000000000000..6e0a50fad56e --- /dev/null +++ b/rust/ql/integration-tests/parallel-extraction/src/lib.rs @@ -0,0 +1,2 @@ +mod caller; +mod helpers; diff --git a/rust/ql/integration-tests/parallel-extraction/steps.expected b/rust/ql/integration-tests/parallel-extraction/steps.expected new file mode 100644 index 000000000000..9a40cf51deaf --- /dev/null +++ b/rust/ql/integration-tests/parallel-extraction/steps.expected @@ -0,0 +1,9 @@ +| src/caller.rs:0:0:0:0 | Extract(src/caller.rs) | +| src/caller.rs:0:0:0:0 | LoadSource(src/caller.rs) | +| src/caller.rs:0:0:0:0 | Parse(src/caller.rs) | +| src/helpers.rs:0:0:0:0 | Extract(src/helpers.rs) | +| src/helpers.rs:0:0:0:0 | LoadSource(src/helpers.rs) | +| src/helpers.rs:0:0:0:0 | Parse(src/helpers.rs) | +| src/lib.rs:0:0:0:0 | Extract(src/lib.rs) | +| src/lib.rs:0:0:0:0 | LoadSource(src/lib.rs) | +| src/lib.rs:0:0:0:0 | Parse(src/lib.rs) | diff --git a/rust/ql/integration-tests/parallel-extraction/steps.ql b/rust/ql/integration-tests/parallel-extraction/steps.ql new file mode 100644 index 000000000000..3465f67608a8 --- /dev/null +++ b/rust/ql/integration-tests/parallel-extraction/steps.ql @@ -0,0 +1,5 @@ +import codeql.rust.elements.internal.ExtractorStep + +from ExtractorStep step +where step.getAction() = ["LoadSource", "Parse", "Extract"] +select step diff --git a/rust/ql/integration-tests/parallel-extraction/test_parallel_extraction.py b/rust/ql/integration-tests/parallel-extraction/test_parallel_extraction.py new file mode 100644 index 000000000000..747fd94d849d --- /dev/null +++ b/rust/ql/integration-tests/parallel-extraction/test_parallel_extraction.py @@ -0,0 +1,7 @@ +import pytest + + +@pytest.mark.parametrize("threads", [1, 4]) +def test_parallel_extraction(codeql, rust, threads): + codeql.database.create(threads=threads) +