From fd4e7afc7087fd8b35dddef53019d0ec6ce304f8 Mon Sep 17 00:00:00 2001 From: Paolo Tranquilli Date: Wed, 2 Dec 2026 12:09:45 +0000 Subject: [PATCH 1/8] Rust: Extract files in parallel following `CODEQL_THREADS` Each worker uses its own `Semantics` over a clone of the loaded database. Extraction stays sequential when `CODEQL_THREADS` is unset or invalid. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- rust/extractor/src/main.rs | 118 ++++++++++++++++----- rust/extractor/src/parallel.rs | 182 +++++++++++++++++++++++++++++++++ 2 files changed, 274 insertions(+), 26 deletions(-) create mode 100644 rust/extractor/src/parallel.rs 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..e85b4d77d250 --- /dev/null +++ b/rust/extractor/src/parallel.rs @@ -0,0 +1,182 @@ +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 + }) +} + +/// 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`. +/// +/// With a single thread everything runs on the current thread. 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 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 threads == 1 { + vec![run(init())] + } else { + let states: Vec<_> = (0..threads).map(|_| init()).collect(); + std::thread::scope(|scope| { + let handles: Vec<_> = states + .into_iter() + .map(|state| scope.spawn(|| run(state))) + .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::sync::Mutex; + 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![])); + } + + #[test] + fn panic_stops_other_workers_and_propagates() { + let items: Vec = (0..10_000).collect(); + let processed = Mutex::new(0); + let result = std::panic::catch_unwind(|| { + parallel_map( + 4, + &items, + || (), + |(), drive| { + drive(&mut |&item| { + if item == 10 { + std::panic::panic_any(item); + } + *processed.lock().unwrap() += 1; + std::thread::yield_now(); + }); + }, + ) + }); + assert_eq!(*result.unwrap_err().downcast::().unwrap(), 10); + assert!(*processed.lock().unwrap() < items.len() - 1); + } +} From a9b7fdd267a37b5e37d8dba226d61d17bf4361fd Mon Sep 17 00:00:00 2001 From: Paolo Tranquilli Date: Wed, 2 Dec 2026 13:25:24 +0000 Subject: [PATCH 2/8] Rust: Give extraction worker threads a 16 MiB stack The default 2 MiB stack overflowed on deeply nested expressions that extract fine on the main thread. Also test dependency features and a deep expression with multiple threads, and make the panic test schedule-proof. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- rust/extractor/src/diagnostics.rs | 1 + rust/extractor/src/parallel.rs | 52 ++++++++++++++++--- .../deep-expression/Cargo.toml | 7 +++ .../deep-expression/src/.gitignore | 1 + .../deep-expression/src/lib.rs | 2 + .../deep-expression/src/shallow.rs | 3 ++ .../deep-expression/test_deep_expression.py | 9 ++++ .../test_dependency_features.py | 5 +- 8 files changed, 70 insertions(+), 10 deletions(-) create mode 100644 rust/ql/integration-tests/deep-expression/Cargo.toml create mode 100644 rust/ql/integration-tests/deep-expression/src/.gitignore create mode 100644 rust/ql/integration-tests/deep-expression/src/lib.rs create mode 100644 rust/ql/integration-tests/deep-expression/src/shallow.rs create mode 100644 rust/ql/integration-tests/deep-expression/test_deep_expression.py 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/parallel.rs b/rust/extractor/src/parallel.rs index e85b4d77d250..e7784d15ac70 100644 --- a/rust/extractor/src/parallel.rs +++ b/rust/extractor/src/parallel.rs @@ -20,6 +20,10 @@ 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; + /// Sets the flag if the current thread unwinds while this is alive. struct AbortOnPanic<'a>(&'a AtomicBool); @@ -74,7 +78,12 @@ where std::thread::scope(|scope| { let handles: Vec<_> = states .into_iter() - .map(|state| scope.spawn(|| run(state))) + .map(|state| { + std::thread::Builder::new() + .stack_size(WORKER_STACK_SIZE) + .spawn_scoped(scope, || run(state)) + .expect("spawning extraction thread") + }) .collect(); let joined: Vec<_> = handles.into_iter().map(|h| h.join()).collect(); joined @@ -97,7 +106,6 @@ where #[cfg(test)] mod tests { use super::*; - use std::sync::Mutex; use std::thread::ThreadId; #[test] @@ -157,9 +165,8 @@ mod tests { } #[test] - fn panic_stops_other_workers_and_propagates() { - let items: Vec = (0..10_000).collect(); - let processed = Mutex::new(0); + fn panic_propagates() { + let items: Vec = (0..100).collect(); let result = std::panic::catch_unwind(|| { parallel_map( 4, @@ -170,13 +177,42 @@ mod tests { if item == 10 { std::panic::panic_any(item); } - *processed.lock().unwrap() += 1; - std::thread::yield_now(); }); }, ) }); assert_eq!(*result.unwrap_err().downcast::().unwrap(), 10); - assert!(*processed.lock().unwrap() < items.len() - 1); + } + + #[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 + let (_, results) = parallel_map( + 2, + &[6000, 6000], + || (), + |(), drive| drive(&mut |&depth| recurse(depth)), + ); + assert_eq!(results.len(), 2); } } 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/test_deep_expression.py b/rust/ql/integration-tests/deep-expression/test_deep_expression.py new file mode 100644 index 000000000000..a83f0a371204 --- /dev/null +++ b/rust/ql/integration-tests/deep-expression/test_deep_expression.py @@ -0,0 +1,9 @@ +import pytest + + +@pytest.mark.ql_test(None) +def test_deep_expression_in_parallel(codeql, rust, cwd): + # extraction recurses on this, so it overflows a default-sized worker thread stack + 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) From 87d0e8a61ea434b8160293a45da1c9564538c2c3 Mon Sep 17 00:00:00 2001 From: Paolo Tranquilli Date: Wed, 2 Dec 2026 13:44:02 +0000 Subject: [PATCH 3/8] Rust: Stop started workers if spawning another fails Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- rust/extractor/src/parallel.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/rust/extractor/src/parallel.rs b/rust/extractor/src/parallel.rs index e7784d15ac70..3647080ff75e 100644 --- a/rust/extractor/src/parallel.rs +++ b/rust/extractor/src/parallel.rs @@ -82,7 +82,10 @@ where std::thread::Builder::new() .stack_size(WORKER_STACK_SIZE) .spawn_scoped(scope, || run(state)) - .expect("spawning extraction thread") + .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(); From 647625cc93499a25aac3d04714ff4b651a787e64 Mon Sep 17 00:00:00 2001 From: Paolo Tranquilli Date: Thu, 3 Dec 2026 08:32:02 +0000 Subject: [PATCH 4/8] Rust: Check multi-file extraction results across thread counts Replace the deep-expression test with a workspace whose files call each other and use a macro, comparing calls and extraction steps at 1 and 4 threads. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../integration-tests/deep-expression/src/lib.rs | 2 -- .../deep-expression/src/shallow.rs | 3 --- .../Cargo.toml | 2 +- .../parallel-extraction/calls.expected | 5 +++++ .../integration-tests/parallel-extraction/calls.ql | 5 +++++ .../src/.gitignore | 0 .../parallel-extraction/src/caller.rs | 9 +++++++++ .../parallel-extraction/src/helpers.rs | 14 ++++++++++++++ .../parallel-extraction/src/lib.rs | 3 +++ .../parallel-extraction/steps.expected | 12 ++++++++++++ .../integration-tests/parallel-extraction/steps.ql | 5 +++++ .../test_parallel_extraction.py} | 6 +++--- 12 files changed, 57 insertions(+), 9 deletions(-) delete mode 100644 rust/ql/integration-tests/deep-expression/src/lib.rs delete mode 100644 rust/ql/integration-tests/deep-expression/src/shallow.rs rename rust/ql/integration-tests/{deep-expression => parallel-extraction}/Cargo.toml (71%) create mode 100644 rust/ql/integration-tests/parallel-extraction/calls.expected create mode 100644 rust/ql/integration-tests/parallel-extraction/calls.ql rename rust/ql/integration-tests/{deep-expression => parallel-extraction}/src/.gitignore (100%) create mode 100644 rust/ql/integration-tests/parallel-extraction/src/caller.rs create mode 100644 rust/ql/integration-tests/parallel-extraction/src/helpers.rs create mode 100644 rust/ql/integration-tests/parallel-extraction/src/lib.rs create mode 100644 rust/ql/integration-tests/parallel-extraction/steps.expected create mode 100644 rust/ql/integration-tests/parallel-extraction/steps.ql rename rust/ql/integration-tests/{deep-expression/test_deep_expression.py => parallel-extraction/test_parallel_extraction.py} (61%) diff --git a/rust/ql/integration-tests/deep-expression/src/lib.rs b/rust/ql/integration-tests/deep-expression/src/lib.rs deleted file mode 100644 index f4c9b954f9e0..000000000000 --- a/rust/ql/integration-tests/deep-expression/src/lib.rs +++ /dev/null @@ -1,2 +0,0 @@ -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 deleted file mode 100644 index 541e5bd47198..000000000000 --- a/rust/ql/integration-tests/deep-expression/src/shallow.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub fn shallow() -> i32 { - 1 -} diff --git a/rust/ql/integration-tests/deep-expression/Cargo.toml b/rust/ql/integration-tests/parallel-extraction/Cargo.toml similarity index 71% rename from rust/ql/integration-tests/deep-expression/Cargo.toml rename to rust/ql/integration-tests/parallel-extraction/Cargo.toml index 0d385afff3ad..3f2716385bd2 100644 --- a/rust/ql/integration-tests/deep-expression/Cargo.toml +++ b/rust/ql/integration-tests/parallel-extraction/Cargo.toml @@ -1,6 +1,6 @@ [workspace] [package] -name = "deep_expression" +name = "parallel_extraction" version = "0.1.0" edition = "2021" 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..7c7a7ffe3012 --- /dev/null +++ b/rust/ql/integration-tests/parallel-extraction/calls.ql @@ -0,0 +1,5 @@ +import rust + +from Call c +where c.fromSource() and not c.getFile().getBaseName() = "deep.rs" +select c, c.getStaticTarget().getCanonicalPath() diff --git a/rust/ql/integration-tests/deep-expression/src/.gitignore b/rust/ql/integration-tests/parallel-extraction/src/.gitignore similarity index 100% rename from rust/ql/integration-tests/deep-expression/src/.gitignore rename to rust/ql/integration-tests/parallel-extraction/src/.gitignore 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..36c091376b00 --- /dev/null +++ b/rust/ql/integration-tests/parallel-extraction/src/lib.rs @@ -0,0 +1,3 @@ +mod caller; +mod deep; +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..e88335bb45fb --- /dev/null +++ b/rust/ql/integration-tests/parallel-extraction/steps.expected @@ -0,0 +1,12 @@ +| 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/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/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/deep-expression/test_deep_expression.py b/rust/ql/integration-tests/parallel-extraction/test_parallel_extraction.py similarity index 61% rename from rust/ql/integration-tests/deep-expression/test_deep_expression.py rename to rust/ql/integration-tests/parallel-extraction/test_parallel_extraction.py index a83f0a371204..8f9ad0c86baa 100644 --- a/rust/ql/integration-tests/deep-expression/test_deep_expression.py +++ b/rust/ql/integration-tests/parallel-extraction/test_parallel_extraction.py @@ -1,9 +1,9 @@ import pytest -@pytest.mark.ql_test(None) -def test_deep_expression_in_parallel(codeql, rust, cwd): +@pytest.mark.parametrize("threads", [1, 4]) +def test_parallel_extraction(codeql, rust, cwd, threads): # extraction recurses on this, so it overflows a default-sized worker thread stack 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) + codeql.database.create(threads=threads) From 304172fe702cf6a7aa043d5f7a5ee6119fcee3f1 Mon Sep 17 00:00:00 2001 From: Paolo Tranquilli Date: Thu, 3 Dec 2026 09:05:43 +0000 Subject: [PATCH 5/8] Rust: Keep deep extraction input off the main thread Run the deep-expression check in its own test at two threads, so it never runs on the main thread (1 MiB on Windows), and so the call-parity query no longer type-checks 10,000 additions. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../integration-tests/parallel-extraction/calls.ql | 2 +- .../parallel-extraction/src/lib.rs | 1 - .../parallel-extraction/steps.deep.expected | 12 ++++++++++++ .../parallel-extraction/steps.expected | 3 --- .../parallel-extraction/test_parallel_extraction.py | 13 ++++++++++--- 5 files changed, 23 insertions(+), 8 deletions(-) create mode 100644 rust/ql/integration-tests/parallel-extraction/steps.deep.expected diff --git a/rust/ql/integration-tests/parallel-extraction/calls.ql b/rust/ql/integration-tests/parallel-extraction/calls.ql index 7c7a7ffe3012..cf1af6d37f5e 100644 --- a/rust/ql/integration-tests/parallel-extraction/calls.ql +++ b/rust/ql/integration-tests/parallel-extraction/calls.ql @@ -1,5 +1,5 @@ import rust from Call c -where c.fromSource() and not c.getFile().getBaseName() = "deep.rs" +where c.fromSource() select c, c.getStaticTarget().getCanonicalPath() diff --git a/rust/ql/integration-tests/parallel-extraction/src/lib.rs b/rust/ql/integration-tests/parallel-extraction/src/lib.rs index 36c091376b00..6e0a50fad56e 100644 --- a/rust/ql/integration-tests/parallel-extraction/src/lib.rs +++ b/rust/ql/integration-tests/parallel-extraction/src/lib.rs @@ -1,3 +1,2 @@ mod caller; -mod deep; mod helpers; diff --git a/rust/ql/integration-tests/parallel-extraction/steps.deep.expected b/rust/ql/integration-tests/parallel-extraction/steps.deep.expected new file mode 100644 index 000000000000..e88335bb45fb --- /dev/null +++ b/rust/ql/integration-tests/parallel-extraction/steps.deep.expected @@ -0,0 +1,12 @@ +| 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/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/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.expected b/rust/ql/integration-tests/parallel-extraction/steps.expected index e88335bb45fb..9a40cf51deaf 100644 --- a/rust/ql/integration-tests/parallel-extraction/steps.expected +++ b/rust/ql/integration-tests/parallel-extraction/steps.expected @@ -1,9 +1,6 @@ | 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/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/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) | diff --git a/rust/ql/integration-tests/parallel-extraction/test_parallel_extraction.py b/rust/ql/integration-tests/parallel-extraction/test_parallel_extraction.py index 8f9ad0c86baa..6c17a48abc03 100644 --- a/rust/ql/integration-tests/parallel-extraction/test_parallel_extraction.py +++ b/rust/ql/integration-tests/parallel-extraction/test_parallel_extraction.py @@ -2,8 +2,15 @@ @pytest.mark.parametrize("threads", [1, 4]) -def test_parallel_extraction(codeql, rust, cwd, threads): - # extraction recurses on this, so it overflows a default-sized worker thread stack +def test_parallel_extraction(codeql, rust, threads): + codeql.database.create(threads=threads) + + +@pytest.mark.ql_test("steps.ql", expected=".deep.expected") +def test_deep_expression(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=threads) + (cwd / "src" / "lib.rs").write_text("mod caller;\nmod deep;\nmod helpers;\n") + codeql.database.create(threads=2) From d8728999d3c92723ace35c405ccf8c6b1025af25 Mon Sep 17 00:00:00 2001 From: Paolo Tranquilli Date: Thu, 3 Dec 2026 09:32:52 +0000 Subject: [PATCH 6/8] Rust: Move the deep extraction test to its own directory Every query in a test directory runs for each test there, so the deep input also went through the call query. Give it a directory with just the extraction step query. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- rust/ql/integration-tests/deep-expression/Cargo.toml | 7 +++++++ .../src/.gitignore | 0 rust/ql/integration-tests/deep-expression/src/lib.rs | 2 ++ .../integration-tests/deep-expression/src/shallow.rs | 3 +++ .../integration-tests/deep-expression/steps.expected | 9 +++++++++ rust/ql/integration-tests/deep-expression/steps.ql | 5 +++++ .../deep-expression/test_deep_expression.py | 6 ++++++ .../parallel-extraction/steps.deep.expected | 12 ------------ .../parallel-extraction/test_parallel_extraction.py | 9 --------- 9 files changed, 32 insertions(+), 21 deletions(-) create mode 100644 rust/ql/integration-tests/deep-expression/Cargo.toml rename rust/ql/integration-tests/{parallel-extraction => deep-expression}/src/.gitignore (100%) create mode 100644 rust/ql/integration-tests/deep-expression/src/lib.rs create mode 100644 rust/ql/integration-tests/deep-expression/src/shallow.rs create mode 100644 rust/ql/integration-tests/deep-expression/steps.expected create mode 100644 rust/ql/integration-tests/deep-expression/steps.ql create mode 100644 rust/ql/integration-tests/deep-expression/test_deep_expression.py delete mode 100644 rust/ql/integration-tests/parallel-extraction/steps.deep.expected 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/parallel-extraction/src/.gitignore b/rust/ql/integration-tests/deep-expression/src/.gitignore similarity index 100% rename from rust/ql/integration-tests/parallel-extraction/src/.gitignore rename to rust/ql/integration-tests/deep-expression/src/.gitignore 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/parallel-extraction/steps.deep.expected b/rust/ql/integration-tests/parallel-extraction/steps.deep.expected deleted file mode 100644 index e88335bb45fb..000000000000 --- a/rust/ql/integration-tests/parallel-extraction/steps.deep.expected +++ /dev/null @@ -1,12 +0,0 @@ -| 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/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/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/test_parallel_extraction.py b/rust/ql/integration-tests/parallel-extraction/test_parallel_extraction.py index 6c17a48abc03..747fd94d849d 100644 --- a/rust/ql/integration-tests/parallel-extraction/test_parallel_extraction.py +++ b/rust/ql/integration-tests/parallel-extraction/test_parallel_extraction.py @@ -5,12 +5,3 @@ def test_parallel_extraction(codeql, rust, threads): codeql.database.create(threads=threads) - -@pytest.mark.ql_test("steps.ql", expected=".deep.expected") -def test_deep_expression(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") - (cwd / "src" / "lib.rs").write_text("mod caller;\nmod deep;\nmod helpers;\n") - codeql.database.create(threads=2) From b2ac40c87621dbc7a3b1557c3e4ee0a84e682b10 Mon Sep 17 00:00:00 2001 From: Paolo Tranquilli Date: Thu, 3 Dec 2026 09:50:15 +0000 Subject: [PATCH 7/8] Rust: Use a worker thread for single-item multi-thread batches A one-item batch was clamped to one thread and ran inline, missing the large worker stack. Only run inline when one thread is requested. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- rust/extractor/src/parallel.rs | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/rust/extractor/src/parallel.rs b/rust/extractor/src/parallel.rs index 3647080ff75e..a71eb4bba780 100644 --- a/rust/extractor/src/parallel.rs +++ b/rust/extractor/src/parallel.rs @@ -42,7 +42,8 @@ impl Drop for AbortOnPanic<'_> { /// 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`. /// -/// With a single thread everything runs on the current thread. If a thread panics, the others +/// 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, @@ -56,6 +57,7 @@ where 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); @@ -71,7 +73,7 @@ where }); (ret, results) }; - let outputs = if threads == 1 { + let outputs = if inline { vec![run(init())] } else { let states: Vec<_> = (0..threads).map(|_| init()).collect(); @@ -165,6 +167,9 @@ mod tests { 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] @@ -210,12 +215,14 @@ mod tests { } } // needs well over the default 2 MiB thread stack - let (_, results) = parallel_map( - 2, - &[6000, 6000], - || (), - |(), drive| drive(&mut |&depth| recurse(depth)), - ); - assert_eq!(results.len(), 2); + for items in [&[6000, 6000][..], &[6000]] { + let (_, results) = parallel_map( + 2, + items, + || (), + |(), drive| drive(&mut |&depth| recurse(depth)), + ); + assert_eq!(results.len(), items.len()); + } } } From 592a6fb66a9f43655b98d91ba97c12422dc597e3 Mon Sep 17 00:00:00 2001 From: Paolo Tranquilli Date: Thu, 3 Dec 2026 10:09:12 +0000 Subject: [PATCH 8/8] Rust: Run extractor unit tests in CI Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/workflows/rust.yml | 3 +++ 1 file changed, 3 insertions(+) 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: