Debian Codegraph @

crates/graph/src/parents_provider.rs

raw symbols SCIP
1 use crate::{ParentMap, Parents};
2 use rustc_hash::{FxHashMap, FxHashSet};
3 use std::collections::{HashMap, HashSet};
4 use std::hash::Hash;
5 use std::sync::Mutex;
6
7 pub trait ParentsProvider<K: PartialEq + Eq + Clone + Hash> {
8 fn get_parent_map(&self, keys: &HashSet<K>) -> ParentMap<K>;
9 }
10
11 pub struct StackedParentsProvider<K> {
12 parent_providers: Vec<Box<dyn ParentsProvider<K>>>,
13 }
14
15 impl<K> StackedParentsProvider<K> {
16 pub fn new(parent_providers: Vec<Box<dyn ParentsProvider<K>>>) -> Self {
17 StackedParentsProvider { parent_providers }
18 }
19 }
20
21 impl<K: Hash + Eq + Clone> ParentsProvider<K> for StackedParentsProvider<K> {
22 fn get_parent_map(&self, keys: &HashSet<K>) -> ParentMap<K> {
23 let mut found = ParentMap::new();
24 let mut remaining = keys.clone();
25
26 for parent_provider in self.parent_providers.iter() {
27 if remaining.is_empty() {
28 break;
29 }
30
31 let new_found = parent_provider.get_parent_map(&remaining);
32 for k in new_found.keys() {
33 remaining.remove(k);
34 }
35 found.extend(new_found);
36 }
37
38 found
39 }
40 }
41
42 pub struct DictParentsProvider<K: Hash + Eq + Clone>(ParentMap<K>);
43
44 impl<K: Hash + Eq + Clone> From<ParentMap<K>> for DictParentsProvider<K> {
45 fn from(parent_map: ParentMap<K>) -> Self {
46 DictParentsProvider(parent_map)
47 }
48 }
49
50 impl<K: Hash + Eq + Clone> From<HashMap<K, Vec<K>>> for DictParentsProvider<K> {
51 fn from(parent_map: HashMap<K, Vec<K>>) -> Self {
52 DictParentsProvider::new(ParentMap(
53 parent_map
54 .into_iter()
55 .map(|(k, v)| (k, Parents::Known(v)))
56 .collect(),
57 ))
58 }
59 }
60
61 impl<K: Hash + Eq + Clone> DictParentsProvider<K> {
62 pub fn new(parent_map: ParentMap<K>) -> Self {
63 DictParentsProvider(parent_map)
64 }
65 }
66
67 impl<K: Hash + Eq + Clone> ParentsProvider<K> for DictParentsProvider<K> {
68 fn get_parent_map(&self, keys: &HashSet<K>) -> ParentMap<K> {
69 ParentMap(
70 keys.iter()
71 .filter_map(|k| self.0.get_key_value(k))
72 .map(|(k, v)| (k.clone(), v.clone()))
73 .collect(),
74 )
75 }
76 }
77
78 /// A parents provider which caches its lookups.
79 ///
80 /// Wraps an inner `ParentsProvider` and memoizes every `(key, parents)`
81 /// pair it returns. When cache-misses-tracking is enabled, keys that were
82 /// requested but not present in the inner provider are also remembered so
83 /// we don't re-request them.
84 ///
85 /// The cache can be disabled and re-enabled at runtime; disabling clears
86 /// the cache entirely.
87 pub struct CachingParentsProvider<K: Hash + Eq + Clone, P: ParentsProvider<K>> {
88 inner: P,
89 // Interior mutability so `get_parent_map(&self, ...)` can populate the
90 // cache. The whole provider is still Sync (via Mutex) which matches the
91 // base trait's `&self` contract.
92 state: Mutex<CacheState<K>>,
93 }
94
95 struct CacheState<K: Hash + Eq + Clone> {
96 /// None when the cache is disabled, Some when enabled.
97 cache: Option<FxHashMap<K, Parents<K>>>,
98 /// Keys known to be missing from the inner provider. Only populated
99 /// when `cache_misses` is true.
100 missing_keys: FxHashSet<K>,
101 /// Whether to remember keys that aren't in the inner provider.
102 cache_misses: bool,
103 }
104
105 impl<K: Hash + Eq + Clone, P: ParentsProvider<K>> CachingParentsProvider<K, P> {
106 /// Create a caching wrapper around `inner`. The cache is enabled by
107 /// default with cache-misses tracking on.
108 pub fn new(inner: P) -> Self {
109 CachingParentsProvider {
110 inner,
111 state: Mutex::new(CacheState {
112 cache: Some(FxHashMap::default()),
113 missing_keys: FxHashSet::default(),
114 cache_misses: true,
115 }),
116 }
117 }
118
119 /// Enable the cache. Matches Python's semantics: calling this when the
120 /// cache is already enabled is an error. `cache_misses` controls
121 /// whether missing keys are remembered between calls.
122 pub fn enable_cache(&self, cache_misses: bool) -> Result<(), &'static str> {
123 let mut state = self.state.lock().unwrap();
124 if state.cache.is_some() {
125 return Err("Cache enabled when already enabled.");
126 }
127 state.cache = Some(FxHashMap::default());
128 state.cache_misses = cache_misses;
129 state.missing_keys = FxHashSet::default();
130 Ok(())
131 }
132
133 /// Disable and clear the cache.
134 pub fn disable_cache(&self) {
135 let mut state = self.state.lock().unwrap();
136 state.cache = None;
137 state.cache_misses = false;
138 state.missing_keys = FxHashSet::default();
139 }
140
141 /// Return a snapshot of the current cache, or `None` if disabled.
142 pub fn get_cached_map(&self) -> Option<FxHashMap<K, Parents<K>>> {
143 let state = self.state.lock().unwrap();
144 state.cache.clone()
145 }
146
147 /// Return entries from the cache without consulting the inner provider.
148 pub fn get_cached_parent_map(&self, keys: &HashSet<K>) -> ParentMap<K> {
149 let state = self.state.lock().unwrap();
150 let Some(cache) = state.cache.as_ref() else {
151 return ParentMap::new();
152 };
153 ParentMap(
154 keys.iter()
155 .filter_map(|k| cache.get_key_value(k))
156 .map(|(k, v)| (k.clone(), v.clone()))
157 .collect(),
158 )
159 }
160
161 /// Note that `key` was missing from the inner provider.
162 pub fn note_missing_key(&self, key: K) {
163 let mut state = self.state.lock().unwrap();
164 if state.cache_misses {
165 state.missing_keys.insert(key);
166 }
167 }
168
169 /// Snapshot of the missing-keys set.
170 pub fn missing_keys(&self) -> FxHashSet<K> {
171 self.state.lock().unwrap().missing_keys.clone()
172 }
173
174 /// Replace the missing-keys set wholesale. Used by the Python bindings to
175 /// sync external mutations of the exposed Python set back into Rust state.
176 pub fn set_missing_keys<I: IntoIterator<Item = K>>(&self, keys: I) {
177 let mut state = self.state.lock().unwrap();
178 state.missing_keys = keys.into_iter().collect();
179 }
180
181 /// Borrow the inner provider.
182 pub fn inner(&self) -> &P {
183 &self.inner
184 }
185 }
186
187 impl<K: Hash + Eq + Clone, P: ParentsProvider<K>> ParentsProvider<K>
188 for CachingParentsProvider<K, P>
189 {
190 fn get_parent_map(&self, keys: &HashSet<K>) -> ParentMap<K> {
191 // Fast path: cache disabled — delegate straight to inner.
192 {
193 let state = self.state.lock().unwrap();
194 if state.cache.is_none() {
195 drop(state);
196 // Note: Python filters the response to only the requested
197 // keys with non-None values; we do the same by filtering
198 // known parents below.
199 let pm = self.inner.get_parent_map(keys);
200 let mut result = ParentMap::new();
201 for k in keys {
202 if let Some(v) = pm.get(k) {
203 if matches!(v, Parents::Known(_)) {
204 result.insert(k.clone(), v.clone());
205 }
206 }
207 }
208 return result;
209 }
210 }
211
212 // Determine which keys we still need to fetch from the inner
213 // provider (not in cache and not known-missing).
214 let needed: HashSet<K> = {
215 let state = self.state.lock().unwrap();
216 let cache = state.cache.as_ref().unwrap();
217 keys.iter()
218 .filter(|k| !cache.contains_key(*k) && !state.missing_keys.contains(*k))
219 .cloned()
220 .collect()
221 };
222
223 if !needed.is_empty() {
224 let fetched = self.inner.get_parent_map(&needed);
225 let mut state = self.state.lock().unwrap();
226 let cache = state.cache.as_mut().unwrap();
227 for (k, v) in fetched.iter() {
228 cache.insert(k.clone(), v.clone());
229 }
230 if state.cache_misses {
231 for k in &needed {
232 if !fetched.contains_key(k) {
233 state.missing_keys.insert(k.clone());
234 }
235 }
236 }
237 }
238
239 // Build the response from the cache, filtering out ghosts/None the
240 // same way Python does.
241 let state = self.state.lock().unwrap();
242 let cache = state.cache.as_ref().unwrap();
243 let mut result = ParentMap::new();
244 for k in keys {
245 if let Some(v) = cache.get(k) {
246 if matches!(v, Parents::Known(_)) {
247 result.insert(k.clone(), v.clone());
248 }
249 }
250 }
251 result
252 }
253 }
254
255 #[cfg(test)]
256 mod tests {
257 use super::*;
258 use std::cell::RefCell;
259
260 /// A ParentsProvider wrapper that counts how many distinct keys were
261 /// requested across all calls to `get_parent_map`. Used to verify the
262 /// caching wrapper avoids redundant lookups.
263 struct CountingProvider<K: Hash + Eq + Clone, P: ParentsProvider<K>> {
264 inner: P,
265 requested: RefCell<Vec<K>>,
266 }
267
268 impl<K: Hash + Eq + Clone, P: ParentsProvider<K>> CountingProvider<K, P> {
269 fn new(inner: P) -> Self {
270 CountingProvider {
271 inner,
272 requested: RefCell::new(Vec::new()),
273 }
274 }
275 }
276
277 impl<K: Hash + Eq + Clone, P: ParentsProvider<K>> ParentsProvider<K> for CountingProvider<K, P> {
278 fn get_parent_map(&self, keys: &HashSet<K>) -> ParentMap<K> {
279 self.requested.borrow_mut().extend(keys.iter().cloned());
280 self.inner.get_parent_map(keys)
281 }
282 }
283
284 fn dict(edges: &[(&'static str, &[&'static str])]) -> DictParentsProvider<&'static str> {
285 let map: HashMap<&'static str, Vec<&'static str>> =
286 edges.iter().map(|(k, ps)| (*k, ps.to_vec())).collect();
287 DictParentsProvider::from(map)
288 }
289
290 fn query(
291 cp: &CachingParentsProvider<
292 &'static str,
293 CountingProvider<&'static str, DictParentsProvider<&'static str>>,
294 >,
295 keys: &[&'static str],
296 ) -> ParentMap<&'static str> {
297 let hs: HashSet<&'static str> = keys.iter().copied().collect();
298 cp.get_parent_map(&hs)
299 }
300
301 #[test]
302 fn caching_returns_known_parents() {
303 let inner = CountingProvider::new(dict(&[("a", &[]), ("b", &["a"])]));
304 let cp = CachingParentsProvider::new(inner);
305 let pm = query(&cp, &["a", "b"]);
306 assert_eq!(pm.get(&"a"), Some(&Parents::Known(vec![])));
307 assert_eq!(pm.get(&"b"), Some(&Parents::Known(vec!["a"])));
308 }
309
310 #[test]
311 fn caching_avoids_refetching_known_keys() {
312 let inner = CountingProvider::new(dict(&[("a", &[]), ("b", &["a"])]));
313 let cp = CachingParentsProvider::new(inner);
314 query(&cp, &["a", "b"]);
315 query(&cp, &["a", "b"]);
316 // Only one round trip for each key.
317 let requested = cp.inner().requested.borrow();
318 let mut seen = FxHashSet::default();
319 for k in requested.iter() {
320 seen.insert(*k);
321 }
322 assert_eq!(seen, ["a", "b"].into_iter().collect::<FxHashSet<_>>());
323 assert_eq!(requested.len(), 2);
324 }
325
326 #[test]
327 fn caching_remembers_missing_keys() {
328 let inner = CountingProvider::new(dict(&[("a", &[])]));
329 let cp = CachingParentsProvider::new(inner);
330 query(&cp, &["a", "missing"]);
331 query(&cp, &["missing"]);
332 // "missing" should have been requested exactly once.
333 let requested = cp.inner().requested.borrow();
334 let count = requested.iter().filter(|k| **k == "missing").count();
335 assert_eq!(count, 1);
336 }
337
338 #[test]
339 fn disable_cache_clears_state() {
340 let inner = CountingProvider::new(dict(&[("a", &[])]));
341 let cp = CachingParentsProvider::new(inner);
342 query(&cp, &["a"]);
343 cp.disable_cache();
344 query(&cp, &["a"]);
345 // With the cache disabled, every call hits the inner provider.
346 let requested = cp.inner().requested.borrow();
347 let count = requested.iter().filter(|k| **k == "a").count();
348 assert_eq!(count, 2);
349 }
350
351 #[test]
352 fn enable_while_enabled_errors() {
353 let cp = CachingParentsProvider::new(dict(&[("a", &[])]));
354 assert!(cp.enable_cache(true).is_err());
355 }
356
357 #[test]
358 fn reenabling_after_disable_works() {
359 let cp = CachingParentsProvider::new(dict(&[("a", &[])]));
360 cp.disable_cache();
361 cp.enable_cache(true).unwrap();
362 let hs: HashSet<&'static str> = ["a"].into_iter().collect();
363 let pm = cp.get_parent_map(&hs);
364 assert_eq!(pm.get(&"a"), Some(&Parents::Known(vec![])));
365 }
366 }