Skip to main content

datafusion_execution/cache/
lru_queue.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use std::{
6    collections::HashMap,
7    hash::Hash,
8    sync::{Arc, Weak},
9};
10
11use parking_lot::Mutex;
12
13#[derive(Default)]
14/// Provides a Least Recently Used queue with unbounded capacity.
15///
16/// # Examples
17///
18/// ```
19/// use datafusion_execution::cache::lru_queue::LruQueue;
20///
21/// let mut lru_queue: LruQueue<i32, i32> = LruQueue::new();
22/// lru_queue.put(1, 10);
23/// lru_queue.put(2, 20);
24/// lru_queue.put(3, 30);
25/// assert_eq!(lru_queue.get(&2), Some(&20));
26/// assert_eq!(lru_queue.pop(), Some((1, 10)));
27/// assert_eq!(lru_queue.pop(), Some((3, 30)));
28/// assert_eq!(lru_queue.pop(), Some((2, 20)));
29/// assert_eq!(lru_queue.pop(), None);
30/// ```
31pub struct LruQueue<K: Eq + Hash + Clone, V> {
32    data: LruData<K, V>,
33    queue: LruList<K>,
34}
35
36/// Maps the key to the [`LruNode`] in queue and the value.
37type LruData<K, V> = HashMap<K, (Arc<Mutex<LruNode<K>>>, V)>;
38
39#[derive(Default)]
40/// Doubly-linked list that maintains the LRU order
41struct LruList<K> {
42    head: Link<K>,
43    tail: Link<K>,
44}
45
46/// Doubly-linked list node.
47struct LruNode<K> {
48    key: K,
49    prev: Link<K>,
50    next: Link<K>,
51}
52
53/// Weak pointer to a [`LruNode`], used to connect nodes in the doubly-linked list.
54/// The strong reference is guaranteed to be stored in the `data` map of the [`LruQueue`].
55type Link<K> = Option<Weak<Mutex<LruNode<K>>>>;
56
57impl<K: Eq + Hash + Clone, V> LruQueue<K, V> {
58    pub fn new() -> Self {
59        Self {
60            data: HashMap::new(),
61            queue: LruList {
62                head: None,
63                tail: None,
64            },
65        }
66    }
67
68    /// Returns a reference to value mapped by `key`, if it exists.
69    /// If the entry exists, it becomes the most recently used.
70    pub fn get(&mut self, key: &K) -> Option<&V> {
71        if let Some(value) = self.remove(key) {
72            self.put(key.clone(), value);
73        }
74        self.data.get(key).map(|(_, value)| value)
75    }
76
77    /// Returns a reference to value mapped by `key`, if it exists.
78    /// Does not affect the queue order.
79    pub fn peek(&self, key: &K) -> Option<&V> {
80        self.data.get(key).map(|(_, value)| value)
81    }
82
83    /// Checks whether there is an entry with key `key` in the queue.
84    /// Does not affect the queue order.
85    pub fn contains_key(&self, key: &K) -> bool {
86        self.data.contains_key(key)
87    }
88
89    /// Inserts an entry in the queue, becoming the most recently used.
90    /// If the entry already exists, returns the previous value.
91    pub fn put(&mut self, key: K, value: V) -> Option<V> {
92        let old_value = self.remove(&key);
93
94        let node = Arc::new(Mutex::new(LruNode {
95            key: key.clone(),
96            prev: None,
97            next: None,
98        }));
99
100        match self.queue.head {
101            // queue is not empty
102            Some(ref old_head) => {
103                old_head
104                    .upgrade()
105                    .expect("value has been unexpectedly dropped")
106                    .lock()
107                    .prev = Some(Arc::downgrade(&node));
108                node.lock().next = Some(Weak::clone(old_head));
109                self.queue.head = Some(Arc::downgrade(&node));
110            }
111            // queue is empty
112            _ => {
113                self.queue.head = Some(Arc::downgrade(&node));
114                self.queue.tail = Some(Arc::downgrade(&node));
115            }
116        }
117
118        self.data.insert(key, (node, value));
119
120        old_value
121    }
122
123    /// Removes and returns the least recently used value.
124    /// Returns `None` if the queue is empty.
125    pub fn pop(&mut self) -> Option<(K, V)> {
126        let key_to_remove = self.queue.tail.as_ref().map(|n| {
127            n.upgrade()
128                .expect("value has been unexpectedly dropped")
129                .lock()
130                .key
131                .clone()
132        });
133        if let Some(k) = key_to_remove {
134            let value = self.remove(&k).unwrap(); // confirmed above that the entry exists
135            Some((k, value))
136        } else {
137            None
138        }
139    }
140
141    /// Removes a specific entry from the queue, if it exists.
142    pub fn remove(&mut self, key: &K) -> Option<V> {
143        if let Some((old_node, old_value)) = self.data.remove(key) {
144            let LruNode { key: _, prev, next } = &*old_node.lock();
145            match (prev, next) {
146                // single node in the queue
147                (None, None) => {
148                    self.queue.head = None;
149                    self.queue.tail = None;
150                }
151                // removed the head node
152                (None, Some(n)) => {
153                    let n_strong =
154                        n.upgrade().expect("value has been unexpectedly dropped");
155                    n_strong.lock().prev = None;
156                    self.queue.head = Some(Weak::clone(n));
157                }
158                // removed the tail node
159                (Some(p), None) => {
160                    let p_strong =
161                        p.upgrade().expect("value has been unexpectedly dropped");
162                    p_strong.lock().next = None;
163                    self.queue.tail = Some(Weak::clone(p));
164                }
165                // removed a middle node
166                (Some(p), Some(n)) => {
167                    let n_strong =
168                        n.upgrade().expect("value has been unexpectedly dropped");
169                    let p_strong =
170                        p.upgrade().expect("value has been unexpectedly dropped");
171                    n_strong.lock().prev = Some(Weak::clone(p));
172                    p_strong.lock().next = Some(Weak::clone(n));
173                }
174            }
175            Some(old_value)
176        } else {
177            None
178        }
179    }
180
181    /// Returns the number of entries in the queue.
182    pub fn len(&self) -> usize {
183        self.data.len()
184    }
185
186    /// Checks whether the queue has no items.
187    pub fn is_empty(&self) -> bool {
188        self.data.is_empty()
189    }
190
191    /// Removes all entries from the queue.
192    pub fn clear(&mut self) {
193        self.queue.head = None;
194        self.queue.tail = None;
195        self.data.clear();
196    }
197
198    /// Returns a reference to the entries currently in the queue.
199    pub fn list_entries(&self) -> HashMap<&K, &V> {
200        self.data.iter().map(|(k, (_, v))| (k, v)).collect()
201    }
202
203    /// Returns an iterator over references to the keys currently in the queue.
204    /// The order is unspecified and does not reflect the LRU order.
205    pub fn keys(&self) -> impl Iterator<Item = &K> {
206        self.data.keys()
207    }
208}
209
210#[cfg(test)]
211mod tests {
212    use std::collections::HashMap;
213
214    use rand::seq::IndexedRandom;
215
216    use crate::cache::lru_queue::LruQueue;
217
218    #[test]
219    fn test_get() {
220        let mut lru_queue: LruQueue<i32, i32> = LruQueue::new();
221
222        // value does not exist
223        assert_eq!(lru_queue.get(&1), None);
224
225        // value exists
226        lru_queue.put(1, 10);
227        assert_eq!(lru_queue.get(&1), Some(&10));
228        assert_eq!(lru_queue.get(&1), Some(&10));
229
230        // value is removed
231        lru_queue.remove(&1);
232        assert_eq!(lru_queue.get(&1), None);
233    }
234
235    #[test]
236    fn test_peek() {
237        let mut lru_queue: LruQueue<i32, i32> = LruQueue::new();
238
239        // value does not exist
240        assert_eq!(lru_queue.peek(&1), None);
241
242        // value exists
243        lru_queue.put(1, 10);
244        assert_eq!(lru_queue.peek(&1), Some(&10));
245        assert_eq!(lru_queue.peek(&1), Some(&10));
246
247        // value is removed
248        lru_queue.remove(&1);
249        assert_eq!(lru_queue.peek(&1), None);
250    }
251
252    #[test]
253    fn test_put() {
254        let mut lru_queue: LruQueue<i32, i32> = LruQueue::new();
255
256        // no previous value
257        assert_eq!(lru_queue.put(1, 10), None);
258
259        // update, the previous value is returned
260        assert_eq!(lru_queue.put(1, 11), Some(10));
261        assert_eq!(lru_queue.put(1, 12), Some(11));
262        assert_eq!(lru_queue.put(1, 13), Some(12));
263    }
264
265    #[test]
266    fn test_remove() {
267        let mut lru_queue: LruQueue<i32, i32> = LruQueue::new();
268
269        // value does not exist
270        assert_eq!(lru_queue.remove(&1), None);
271
272        // value exists and is returned
273        lru_queue.put(1, 10);
274        assert_eq!(lru_queue.remove(&1), Some(10));
275
276        // value does not exist
277        assert_eq!(lru_queue.remove(&1), None);
278    }
279
280    #[test]
281    fn test_contains_key() {
282        let mut lru_queue: LruQueue<i32, i32> = LruQueue::new();
283
284        // value does not exist
285        assert!(!lru_queue.contains_key(&1));
286
287        // value exists
288        lru_queue.put(1, 10);
289        assert!(lru_queue.contains_key(&1));
290
291        // value is removed
292        lru_queue.remove(&1);
293        assert!(!lru_queue.contains_key(&1));
294    }
295
296    #[test]
297    fn test_len() {
298        let mut lru_queue: LruQueue<i32, i32> = LruQueue::new();
299
300        // empty
301        assert_eq!(lru_queue.len(), 0);
302
303        // puts
304        lru_queue.put(1, 10);
305        assert_eq!(lru_queue.len(), 1);
306        lru_queue.put(2, 20);
307        assert_eq!(lru_queue.len(), 2);
308        lru_queue.put(3, 30);
309        assert_eq!(lru_queue.len(), 3);
310        lru_queue.put(1, 11);
311        lru_queue.put(3, 31);
312        assert_eq!(lru_queue.len(), 3);
313
314        // removes
315        lru_queue.remove(&1);
316        assert_eq!(lru_queue.len(), 2);
317        lru_queue.remove(&1);
318        assert_eq!(lru_queue.len(), 2);
319        lru_queue.remove(&4);
320        assert_eq!(lru_queue.len(), 2);
321        lru_queue.remove(&3);
322        assert_eq!(lru_queue.len(), 1);
323        lru_queue.remove(&2);
324        assert_eq!(lru_queue.len(), 0);
325        lru_queue.remove(&2);
326        assert_eq!(lru_queue.len(), 0);
327
328        // clear
329        lru_queue.put(1, 10);
330        lru_queue.put(2, 20);
331        lru_queue.put(3, 30);
332        assert_eq!(lru_queue.len(), 3);
333        lru_queue.clear();
334        assert_eq!(lru_queue.len(), 0);
335    }
336
337    #[test]
338    fn test_is_empty() {
339        let mut lru_queue: LruQueue<i32, i32> = LruQueue::new();
340
341        // empty
342        assert!(lru_queue.is_empty());
343
344        // puts
345        lru_queue.put(1, 10);
346        assert!(!lru_queue.is_empty());
347        lru_queue.put(2, 20);
348        assert!(!lru_queue.is_empty());
349
350        // removes
351        lru_queue.remove(&1);
352        assert!(!lru_queue.is_empty());
353        lru_queue.remove(&1);
354        assert!(!lru_queue.is_empty());
355        lru_queue.remove(&2);
356        assert!(lru_queue.is_empty());
357
358        // clear
359        lru_queue.put(1, 10);
360        lru_queue.put(2, 20);
361        lru_queue.put(3, 30);
362        assert!(!lru_queue.is_empty());
363        lru_queue.clear();
364        assert!(lru_queue.is_empty());
365    }
366
367    #[test]
368    fn test_clear() {
369        let mut lru_queue: LruQueue<i32, i32> = LruQueue::new();
370
371        // empty
372        lru_queue.clear();
373
374        // filled
375        lru_queue.put(1, 10);
376        lru_queue.put(2, 20);
377        lru_queue.put(3, 30);
378        assert_eq!(lru_queue.get(&1), Some(&10));
379        assert_eq!(lru_queue.get(&2), Some(&20));
380        assert_eq!(lru_queue.get(&3), Some(&30));
381        lru_queue.clear();
382        assert_eq!(lru_queue.get(&1), None);
383        assert_eq!(lru_queue.get(&2), None);
384        assert_eq!(lru_queue.get(&3), None);
385        assert_eq!(lru_queue.len(), 0);
386    }
387
388    #[test]
389    fn test_pop() {
390        let mut lru_queue: LruQueue<i32, i32> = LruQueue::new();
391
392        // empty queue
393        assert_eq!(lru_queue.pop(), None);
394
395        // simplest case
396        lru_queue.put(1, 10);
397        lru_queue.put(2, 20);
398        lru_queue.put(3, 30);
399        assert_eq!(lru_queue.pop(), Some((1, 10)));
400        assert_eq!(lru_queue.pop(), Some((2, 20)));
401        assert_eq!(lru_queue.pop(), Some((3, 30)));
402        assert_eq!(lru_queue.pop(), None);
403
404        // 'get' changes the order
405        lru_queue.put(1, 10);
406        lru_queue.put(2, 20);
407        lru_queue.put(3, 30);
408        lru_queue.get(&2);
409        assert_eq!(lru_queue.pop(), Some((1, 10)));
410        assert_eq!(lru_queue.pop(), Some((3, 30)));
411        assert_eq!(lru_queue.pop(), Some((2, 20)));
412        assert_eq!(lru_queue.pop(), None);
413
414        // multiple 'gets'
415        lru_queue.put(1, 10);
416        lru_queue.put(2, 20);
417        lru_queue.put(3, 30);
418        lru_queue.get(&2);
419        lru_queue.get(&3);
420        lru_queue.get(&1);
421        assert_eq!(lru_queue.pop(), Some((2, 20)));
422        assert_eq!(lru_queue.pop(), Some((3, 30)));
423        assert_eq!(lru_queue.pop(), Some((1, 10)));
424        assert_eq!(lru_queue.pop(), None);
425
426        // 'peak' does not change the order
427        lru_queue.put(1, 10);
428        lru_queue.put(2, 20);
429        lru_queue.put(3, 30);
430        lru_queue.peek(&2);
431        assert_eq!(lru_queue.pop(), Some((1, 10)));
432        assert_eq!(lru_queue.pop(), Some((2, 20)));
433        assert_eq!(lru_queue.pop(), Some((3, 30)));
434        assert_eq!(lru_queue.pop(), None);
435
436        // 'contains' does not change the order
437        lru_queue.put(1, 10);
438        lru_queue.put(2, 20);
439        lru_queue.put(3, 30);
440        lru_queue.contains_key(&2);
441        assert_eq!(lru_queue.pop(), Some((1, 10)));
442        assert_eq!(lru_queue.pop(), Some((2, 20)));
443        assert_eq!(lru_queue.pop(), Some((3, 30)));
444        assert_eq!(lru_queue.pop(), None);
445
446        // 'put' on the same key promotes it
447        lru_queue.put(1, 10);
448        lru_queue.put(2, 20);
449        lru_queue.put(3, 30);
450        lru_queue.put(2, 21);
451        assert_eq!(lru_queue.pop(), Some((1, 10)));
452        assert_eq!(lru_queue.pop(), Some((3, 30)));
453        assert_eq!(lru_queue.pop(), Some((2, 21)));
454        assert_eq!(lru_queue.pop(), None);
455
456        // multiple 'puts'
457        lru_queue.put(1, 10);
458        lru_queue.put(2, 20);
459        lru_queue.put(3, 30);
460        lru_queue.put(2, 21);
461        lru_queue.put(3, 31);
462        lru_queue.put(1, 11);
463        assert_eq!(lru_queue.pop(), Some((2, 21)));
464        assert_eq!(lru_queue.pop(), Some((3, 31)));
465        assert_eq!(lru_queue.pop(), Some((1, 11)));
466        assert_eq!(lru_queue.pop(), None);
467
468        // 'remove' an element in the middle of the queue
469        lru_queue.put(1, 10);
470        lru_queue.put(2, 20);
471        lru_queue.put(3, 30);
472        lru_queue.remove(&2);
473        assert_eq!(lru_queue.pop(), Some((1, 10)));
474        assert_eq!(lru_queue.pop(), Some((3, 30)));
475        assert_eq!(lru_queue.pop(), None);
476
477        // 'remove' the LRU
478        lru_queue.put(1, 10);
479        lru_queue.put(2, 20);
480        lru_queue.put(3, 30);
481        lru_queue.remove(&1);
482        assert_eq!(lru_queue.pop(), Some((2, 20)));
483        assert_eq!(lru_queue.pop(), Some((3, 30)));
484        assert_eq!(lru_queue.pop(), None);
485
486        // 'remove' the MRU
487        lru_queue.put(1, 10);
488        lru_queue.put(2, 20);
489        lru_queue.put(3, 30);
490        lru_queue.remove(&3);
491        assert_eq!(lru_queue.pop(), Some((1, 10)));
492        assert_eq!(lru_queue.pop(), Some((2, 20)));
493        assert_eq!(lru_queue.pop(), None);
494    }
495
496    #[test]
497    /// Fuzzy test using an hashmap as the base to check the methods.
498    fn test_fuzzy() {
499        let mut lru_queue: LruQueue<i32, i32> = LruQueue::new();
500        let mut map: HashMap<i32, i32> = HashMap::new();
501        let max_keys = 1_000;
502        let methods = ["get", "put", "remove", "pop", "contains", "len"];
503        let mut rng = rand::rng();
504
505        for i in 0..1_000_000 {
506            match *methods.choose(&mut rng).unwrap() {
507                "get" => {
508                    assert_eq!(lru_queue.get(&(i % max_keys)), map.get(&(i % max_keys)))
509                }
510                "put" => assert_eq!(
511                    lru_queue.put(i % max_keys, i),
512                    map.insert(i % max_keys, i)
513                ),
514                "remove" => assert_eq!(
515                    lru_queue.remove(&(i % max_keys)),
516                    map.remove(&(i % max_keys))
517                ),
518                "pop" => {
519                    let removed = lru_queue.pop();
520                    if let Some((k, v)) = removed {
521                        assert_eq!(Some(v), map.remove(&k))
522                    }
523                }
524                "contains" => {
525                    assert_eq!(
526                        lru_queue.contains_key(&(i % max_keys)),
527                        map.contains_key(&(i % max_keys))
528                    )
529                }
530                "len" => assert_eq!(lru_queue.len(), map.len()),
531                _ => unreachable!(),
532            }
533        }
534    }
535}