Skip to content

Commit f4c3833

Browse files
Paolo TranquilliCopilot
andcommitted
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
1 parent d484168 commit f4c3833

3 files changed

Lines changed: 255 additions & 34 deletions

File tree

‎rust/extractor/src/main.rs‎

Lines changed: 32 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,8 @@ use itertools::Itertools;
1010
use ra_ap_hir::Semantics;
1111
use ra_ap_ide_db::RootDatabase;
1212
use ra_ap_ide_db::line_index::{LineCol, LineIndex};
13-
use ra_ap_load_cargo::LoadCargoConfig;
1413
use ra_ap_paths::{AbsPathBuf, Utf8PathBuf};
15-
use ra_ap_project_model::{CargoConfig, ProjectManifest};
14+
use ra_ap_project_model::ProjectManifest;
1615
use ra_ap_vfs::Vfs;
1716
use rust_analyzer::{ParseResult, RustAnalyzer};
1817
use std::collections::{BTreeMap, HashSet};
@@ -24,6 +23,7 @@ use std::{env, fs};
2423
use tracing::{error, info, warn};
2524
use tracing_subscriber::layer::SubscriberExt;
2625
use tracing_subscriber::util::SubscriberInitExt;
26+
use workspaces::LoadedWorkspaces;
2727

2828
mod archive;
2929
mod config;
@@ -38,6 +38,10 @@ mod toolchain;
3838
mod translate;
3939
pub mod trap;
4040
mod util;
41+
mod workspaces;
42+
43+
/// How many loaded workspaces are kept for reuse, besides the one loading in the background.
44+
const MAX_LOADED_WORKSPACES: usize = 2;
4145

4246
struct Extractor<'a> {
4347
archiver: &'a Archiver,
@@ -128,19 +132,6 @@ impl<'a> Extractor<'a> {
128132
self.extract(&RustAnalyzer::from(err), file, source_kind);
129133
}
130134

131-
pub fn load_manifest(
132-
&mut self,
133-
project: &ProjectManifest,
134-
config: &CargoConfig,
135-
load_config: &LoadCargoConfig,
136-
) -> Option<(RootDatabase, Vfs)> {
137-
let before = Instant::now();
138-
let ret = RustAnalyzer::load_workspace(project, config, load_config);
139-
self.steps
140-
.push(ExtractionStep::load_manifest(before, project));
141-
ret
142-
}
143-
144135
pub fn load_source(
145136
&mut self,
146137
file: &Path,
@@ -422,25 +413,29 @@ fn main() -> anyhow::Result<()> {
422413
// workspace a dependency file should be extracted.
423414
let dependency_extraction_ambiguity = workspaces.len() == 1;
424415

425-
for (manifest, files) in workspaces.values() {
426-
if let Some((db, vfs)) =
427-
extractor.load_manifest(manifest, &cargo_config, &load_cargo_config)
428-
{
416+
// loading in the background needs a thread beyond the sequential extraction one
417+
let mut loaded = LoadedWorkspaces::new(MAX_LOADED_WORKSPACES, threads > 1, move |manifest| {
418+
RustAnalyzer::load_workspace(manifest, &cargo_config, &load_cargo_config)
419+
});
420+
let mut workspaces = workspaces.values().peekable();
421+
while let Some((manifest, files)) = workspaces.next() {
422+
let next = workspaces.peek().map(|(next, _)| *next);
423+
if let Some((db, vfs)) = loaded.get(manifest, next, &mut extractor.steps) {
429424
let before_crate_graph = Instant::now();
430-
crate_graph::extract_crate_graph(extractor.traps, &db, &vfs);
425+
crate_graph::extract_crate_graph(extractor.traps, db, vfs);
431426
extractor
432427
.steps
433428
.push(ExtractionStep::crate_graph(before_crate_graph));
434429
let mut items: Vec<(&Path, bool)> = files.iter().map(|f| (*f, true)).collect();
435430
// Fast path when there is no ambiguity in dependency extraction.
436431
if dependency_extraction_ambiguity {
437-
items.extend(dependency_files(&db, &vfs, &source_files).map(|(_, f)| (f, false)));
432+
items.extend(dependency_files(db, vfs, &source_files).map(|(_, f)| (f, false)));
438433
}
439-
prime_def_maps(&db, &vfs, items.iter().map(|(f, _)| *f), threads);
434+
prime_def_maps(db, vfs, items.iter().map(|(f, _)| *f), threads);
440435
debug_assert!(items.iter().map(|(f, _)| f).all_unique());
441436
extractor.run_parallel(
442-
&db,
443-
&vfs,
437+
db,
438+
vfs,
444439
threads,
445440
&items,
446441
|extractor, semantics, vfs, &(file, is_source)| {
@@ -457,8 +452,8 @@ fn main() -> anyhow::Result<()> {
457452
},
458453
);
459454
if !dependency_extraction_ambiguity {
460-
let semantics = Semantics::new(&db);
461-
dependencies.add_manifest(manifest, &semantics, &vfs, &source_files);
455+
let semantics = Semantics::new(db);
456+
dependencies.add_manifest(manifest, &semantics, vfs, &source_files);
462457
}
463458
} else {
464459
extractor.extract_without_semantics_parallel(
@@ -474,14 +469,17 @@ fn main() -> anyhow::Result<()> {
474469
// preferred. Note that when `dependency_extraction_ambiguity` is true then
475470
// `selected` below is empty.
476471
loop {
477-
let selected = dependencies.by_manifests();
472+
let mut selected = dependencies.by_manifests().into_iter().collect_vec();
478473
if selected.is_empty() {
479474
break;
480475
}
481-
for (manifest, files) in selected {
482-
if let Some((db, vfs)) =
483-
extractor.load_manifest(manifest, &cargo_config, &load_cargo_config)
484-
{
476+
// The order does not affect what is extracted: start with the workspaces still loaded.
477+
selected
478+
.sort_by_key(|&(manifest, _)| (!loaded.contains(manifest), manifest_parent(manifest)));
479+
let mut selected = selected.into_iter().peekable();
480+
while let Some((manifest, files)) = selected.next() {
481+
let next = selected.peek().map(|(next, _)| *next);
482+
if let Some((db, vfs)) = loaded.get(manifest, next, &mut extractor.steps) {
485483
// `has_alternative` is evaluated upfront, which is equivalent to evaluating it
486484
// just before each extraction as each file occurs at most once in `selected`.
487485
let items: Vec<_> = files
@@ -493,8 +491,8 @@ fn main() -> anyhow::Result<()> {
493491
.collect();
494492
debug_assert!(items.iter().map(|(f, _)| f).all_unique());
495493
let extracted = extractor.run_parallel(
496-
&db,
497-
&vfs,
494+
db,
495+
vfs,
498496
threads,
499497
&items,
500498
|extractor, semantics, vfs, (file, has_alternative)| {
@@ -532,6 +530,7 @@ fn main() -> anyhow::Result<()> {
532530
}
533531
}
534532
}
533+
drop(loaded);
535534

536535
let builtins_dir = env::var("CODEQL_EXTRACTOR_RUST_ROOT")
537536
.map(|path| Path::new(&path).join("tools").join("builtins"))?;

‎rust/extractor/src/parallel.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ fn threads_from(value: Option<&str>, cores: usize) -> usize {
2929

3030
/// Extraction recurses deeply on nested code, so workers need more than the default 2 MiB stack.
3131
/// This matches what rust-analyzer uses for its own threads.
32-
const WORKER_STACK_SIZE: usize = 16 << 20;
32+
pub const WORKER_STACK_SIZE: usize = 16 << 20;
3333

3434
/// Sets the flag if the current thread unwinds while this is alive.
3535
struct AbortOnPanic<'a>(&'a AtomicBool);

‎rust/extractor/src/workspaces.rs‎

Lines changed: 222 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,222 @@
1+
use crate::diagnostics::ExtractionStep;
2+
use crate::parallel::WORKER_STACK_SIZE;
3+
use ra_ap_project_model::ProjectManifest;
4+
use std::sync::Arc;
5+
use std::thread::JoinHandle;
6+
use std::time::Instant;
7+
use tracing::{error, warn};
8+
9+
type Loaded<W> = (Option<W>, ExtractionStep);
10+
11+
/// Workspaces loaded from manifests, keeping the `capacity` most recently used ones so that they
12+
/// need not be reloaded when extracting dependencies. Optionally, the manifest that is going to be
13+
/// requested next is loaded in the background meanwhile. At most `capacity + 1` workspaces are
14+
/// held at any time.
15+
pub struct LoadedWorkspaces<'m, W, L> {
16+
/// Most recently used last.
17+
loaded: Vec<(&'m ProjectManifest, W)>,
18+
prefetched: Option<(&'m ProjectManifest, JoinHandle<Loaded<W>>)>,
19+
load: Arc<L>,
20+
capacity: usize,
21+
prefetch: bool,
22+
}
23+
24+
impl<'m, W, L> LoadedWorkspaces<'m, W, L>
25+
where
26+
W: Send + 'static,
27+
L: Fn(&ProjectManifest) -> Option<W> + Send + Sync + 'static,
28+
{
29+
pub fn new(capacity: usize, prefetch: bool, load: L) -> Self {
30+
assert!(capacity > 0);
31+
Self {
32+
loaded: Vec::with_capacity(capacity),
33+
prefetched: None,
34+
load: Arc::new(load),
35+
capacity,
36+
prefetch,
37+
}
38+
}
39+
40+
pub fn contains(&self, manifest: &ProjectManifest) -> bool {
41+
self.loaded.iter().any(|(m, _)| *m == manifest)
42+
}
43+
44+
/// Returns the workspace of `manifest`, loading it unless still loaded, or `None` if it cannot
45+
/// be loaded. Then starts loading `next` in the background, if prefetching is enabled.
46+
pub fn get(
47+
&mut self,
48+
manifest: &'m ProjectManifest,
49+
next: Option<&'m ProjectManifest>,
50+
steps: &mut Vec<ExtractionStep>,
51+
) -> Option<&W> {
52+
let found = if let Some(index) = self.loaded.iter().position(|(m, _)| *m == manifest) {
53+
let entry = self.loaded.remove(index);
54+
self.loaded.push(entry);
55+
true
56+
} else {
57+
let prefetched = self.take_prefetched(manifest, steps);
58+
let (workspace, step) = prefetched.unwrap_or_else(|| load_timed(&*self.load, manifest));
59+
steps.push(step);
60+
workspace.is_some_and(|workspace| {
61+
// evict before starting the next prefetch to bound the number of workspaces held
62+
if self.loaded.len() == self.capacity {
63+
self.loaded.remove(0);
64+
}
65+
self.loaded.push((manifest, workspace));
66+
true
67+
})
68+
};
69+
if let Some(next) = next {
70+
self.start_prefetch(next);
71+
}
72+
let (_, workspace) = self.loaded.last().filter(|_| found)?;
73+
Some(workspace)
74+
}
75+
76+
fn take_prefetched(
77+
&mut self,
78+
manifest: &ProjectManifest,
79+
steps: &mut Vec<ExtractionStep>,
80+
) -> Option<Loaded<W>> {
81+
let (prefetched, handle) = self.prefetched.take()?;
82+
let loaded = handle
83+
.join()
84+
.unwrap_or_else(|e| std::panic::resume_unwind(e));
85+
if prefetched == manifest {
86+
return Some(loaded);
87+
}
88+
warn!("discarding {prefetched}, loaded in the background instead of {manifest}");
89+
steps.push(loaded.1);
90+
None
91+
}
92+
93+
fn start_prefetch(&mut self, next: &'m ProjectManifest) {
94+
if !self.prefetch || self.prefetched.is_some() || self.contains(next) {
95+
return;
96+
}
97+
let load = Arc::clone(&self.load);
98+
let manifest = next.clone();
99+
match std::thread::Builder::new()
100+
.stack_size(WORKER_STACK_SIZE)
101+
.spawn(move || load_timed(&*load, &manifest))
102+
{
103+
Ok(handle) => self.prefetched = Some((next, handle)),
104+
// `next` is then loaded when requested
105+
Err(e) => warn!("cannot load {next} in the background: {e}"),
106+
}
107+
}
108+
}
109+
110+
impl<W, L> Drop for LoadedWorkspaces<'_, W, L> {
111+
fn drop(&mut self) {
112+
// do not leave cargo or proc-macro server processes behind
113+
if let Some((manifest, handle)) = self.prefetched.take()
114+
&& handle.join().is_err()
115+
{
116+
error!("loading {manifest} in the background panicked");
117+
}
118+
}
119+
}
120+
121+
fn load_timed<W>(
122+
load: &impl Fn(&ProjectManifest) -> Option<W>,
123+
manifest: &ProjectManifest,
124+
) -> Loaded<W> {
125+
let before = Instant::now();
126+
let ret = load(manifest);
127+
(ret, ExtractionStep::load_manifest(before, manifest))
128+
}
129+
130+
#[cfg(test)]
131+
mod tests {
132+
use super::*;
133+
use std::sync::Mutex;
134+
use std::sync::atomic::{AtomicUsize, Ordering};
135+
136+
#[derive(Default)]
137+
struct Stats {
138+
loads: Mutex<Vec<String>>,
139+
live: AtomicUsize,
140+
peak: AtomicUsize,
141+
}
142+
143+
struct Workspace(String, Arc<Stats>);
144+
145+
impl Drop for Workspace {
146+
fn drop(&mut self) {
147+
self.1.live.fetch_sub(1, Ordering::SeqCst);
148+
}
149+
}
150+
151+
fn manifests(names: &[&str]) -> Vec<ProjectManifest> {
152+
let root = crate::cwd().unwrap();
153+
names
154+
.iter()
155+
.map(|name| ProjectManifest::from_manifest_file(root.join(name).join("Cargo.toml")))
156+
.collect::<Result<_, _>>()
157+
.unwrap()
158+
}
159+
160+
/// Loads workspaces named after their directory, failing for `broken`.
161+
fn loader(stats: &Arc<Stats>) -> impl Fn(&ProjectManifest) -> Option<Workspace> + use<> {
162+
let stats = Arc::clone(stats);
163+
move |manifest| {
164+
let name = manifest.manifest_path().parent().file_name()?.to_owned();
165+
// test threads are named, background loading ones are not
166+
let background = std::thread::current().name().is_none();
167+
let entry = format!("{name}{}", if background { " (background)" } else { "" });
168+
stats.loads.lock().unwrap().push(entry);
169+
if name == "broken" {
170+
return None;
171+
}
172+
let live = stats.live.fetch_add(1, Ordering::SeqCst) + 1;
173+
stats.peak.fetch_max(live, Ordering::SeqCst);
174+
Some(Workspace(name, Arc::clone(&stats)))
175+
}
176+
}
177+
178+
#[test]
179+
fn reuses_most_recently_used_workspaces() {
180+
let stats = Arc::default();
181+
let [a, b, c, broken]: &[_; 4] = &manifests(&["a", "b", "c", "broken"]).try_into().unwrap();
182+
let mut loaded = LoadedWorkspaces::new(2, false, loader(&stats));
183+
let mut steps = Vec::new();
184+
for manifest in [a, b, a, c, b, broken, broken] {
185+
let got = loaded.get(manifest, None, &mut steps).map(|w| w.0.clone());
186+
assert_eq!(got.is_some(), manifest != broken);
187+
}
188+
// `c` evicts `b`, the least recently used; failed loads are not kept
189+
assert_eq!(
190+
*stats.loads.lock().unwrap(),
191+
["a", "b", "c", "b", "broken", "broken"]
192+
);
193+
assert_eq!(steps.len(), 6);
194+
assert!(loaded.contains(c) && loaded.contains(b) && !loaded.contains(a));
195+
}
196+
197+
#[test]
198+
fn prefetches_next_workspace_within_bound() {
199+
let stats = Arc::default();
200+
let all = manifests(&["a", "b", "broken", "c", "d"]);
201+
let mut loaded = LoadedWorkspaces::new(2, true, loader(&stats));
202+
let mut steps = Vec::new();
203+
for (i, manifest) in all.iter().enumerate() {
204+
let got = loaded.get(manifest, all.get(i + 1), &mut steps);
205+
assert_eq!(got.is_some(), i != 2);
206+
}
207+
assert_eq!(
208+
*stats.loads.lock().unwrap(),
209+
[
210+
"a",
211+
"b (background)",
212+
"broken (background)",
213+
"c (background)",
214+
"d (background)"
215+
]
216+
);
217+
assert_eq!(steps.len(), 5);
218+
assert!(stats.peak.load(Ordering::SeqCst) <= 3);
219+
drop(loaded);
220+
assert_eq!(stats.live.load(Ordering::SeqCst), 0);
221+
}
222+
}

0 commit comments

Comments
 (0)