Skip to main content

commonware_storage/index/
ordered.rs

1//! Implementation of [Ordered] that uses an ordered map internally to map translated keys to
2//! arbitrary values. Beyond the standard [Unordered] implementation, this variant adds the
3//! capability to retrieve values associated with both next and previous translated keys of a given
4//! key. There is no ordering guarantee provided over the values associated with each key. Ordering
5//! applies only to the _translated_ key space.
6
7use crate::{
8    index::{
9        Cursor as CursorTrait, Ordered, Unordered,
10        storage::{Cursor as CursorImpl, IndexEntry, Overflow, Values, push_displaced},
11    },
12    translator::Translator,
13};
14use commonware_runtime::{
15    Metrics,
16    telemetry::metrics::{Counter, Gauge, MetricsExt as _},
17};
18use std::{
19    collections::{
20        BTreeMap, HashMap,
21        btree_map::{
22            Entry as BTreeEntry, OccupiedEntry as BTreeOccupiedEntry,
23            VacantEntry as BTreeVacantEntry,
24        },
25    },
26    ops::Bound::{Excluded, Unbounded},
27};
28
29/// Implementation of [IndexEntry] for [BTreeOccupiedEntry].
30impl<K: Ord + Send + Sync, V: Send + Sync> IndexEntry<V> for BTreeOccupiedEntry<'_, K, V> {
31    type Key = K;
32
33    fn key(&self) -> &K {
34        BTreeOccupiedEntry::key(self)
35    }
36
37    fn get_mut(&mut self) -> &mut V {
38        self.get_mut()
39    }
40
41    fn remove(self) {
42        self.remove_entry();
43    }
44}
45
46/// A [crate::index::Cursor] over the values associated with a translated key.
47pub type Cursor<'a, K, V, S> = CursorImpl<'a, K, V, BTreeOccupiedEntry<'a, K, V>, S>;
48
49/// A memory-efficient index that uses an ordered map internally to map translated keys to arbitrary
50/// values.
51///
52/// Each translated key maps directly to its most recently inserted value. Conflicting values (from
53/// key collisions or repeated insertions) live in a separate overflow map, keeping the common
54/// (collision-free) case compact.
55pub struct Index<T: Translator, V: Send + Sync> {
56    translator: T,
57    map: BTreeMap<T::Key, V>,
58    overflow: Overflow<T::Key, V, T>,
59
60    keys: Gauge,
61    items: Gauge,
62    pruned: Counter,
63}
64
65impl<T: Translator, V: Send + Sync> Index<T, V> {
66    /// Create a new entry in the index.
67    fn create(keys: &Gauge, items: &Gauge, vacant: BTreeVacantEntry<'_, T::Key, V>, v: V) {
68        keys.inc();
69        items.inc();
70        vacant.insert(v);
71    }
72
73    /// Create a new [Index] with the given translator and metrics registry.
74    pub fn new(ctx: impl Metrics, translator: T) -> Self {
75        Self {
76            overflow: HashMap::with_hasher(translator.clone()),
77            translator,
78            map: BTreeMap::new(),
79            keys: ctx.gauge("keys", "Number of translated keys in the index"),
80            items: ctx.gauge("items", "Number of items in the index"),
81            pruned: ctx.counter("pruned", "Number of items pruned"),
82        }
83    }
84
85    /// Returns an iterator over the values associated with the translated key `k`, given that
86    /// key's inline (head) value.
87    fn values<'a>(&'a self, k: &T::Key, head: &'a V) -> Values<'a, T::Key, V, T> {
88        Values::new(Some(head), &self.overflow, *k)
89    }
90
91    /// Returns an iterator over all values associated with an already-translated key.
92    pub(super) fn get_translated(&self, key: T::Key) -> Values<'_, T::Key, V, T> {
93        Values::new(self.map.get(&key), &self.overflow, key)
94    }
95
96    /// Returns an iterator over the values of the translated key that lexicographically follows
97    /// `key`, or None if no such key exists (no cycling).
98    pub(super) fn next_translated_values_no_cycle(
99        &self,
100        key: &[u8],
101    ) -> Option<Values<'_, T::Key, V, T>> {
102        let k = self.translator.transform(key);
103        self.map
104            .range((Excluded(k), Unbounded))
105            .next()
106            .map(|(k, head)| self.values(k, head))
107    }
108
109    /// Returns an iterator over the values of the translated key that lexicographically precedes
110    /// `key`, or None if no such key exists (no cycling).
111    pub(super) fn prev_translated_values_no_cycle(
112        &self,
113        key: &[u8],
114    ) -> Option<Values<'_, T::Key, V, T>> {
115        let k = self.translator.transform(key);
116        self.map
117            .range(..k)
118            .next_back()
119            .map(|(k, head)| self.values(k, head))
120    }
121
122    /// Returns an iterator over the values of the lexicographically first translated key, or
123    /// None if the index is empty.
124    pub(super) fn first_translated_values(&self) -> Option<Values<'_, T::Key, V, T>> {
125        self.map
126            .first_key_value()
127            .map(|(k, head)| self.values(k, head))
128    }
129
130    /// Returns an iterator over the values of the lexicographically last translated key, or
131    /// None if the index is empty.
132    pub(super) fn last_translated_values(&self) -> Option<Values<'_, T::Key, V, T>> {
133        self.map
134            .last_key_value()
135            .map(|(k, head)| self.values(k, head))
136    }
137}
138
139impl<T: Translator, V: Send + Sync> Ordered for Index<T, V> {
140    fn prev_translated_key<'a>(
141        &'a self,
142        key: &[u8],
143    ) -> Option<(impl Iterator<Item = &'a V> + Send + 'a, bool)>
144    where
145        V: 'a,
146    {
147        if let Some(values) = self.prev_translated_values_no_cycle(key) {
148            return Some((values, false));
149        }
150        self.last_translated_values().map(|values| (values, true))
151    }
152
153    fn next_translated_key<'a>(
154        &'a self,
155        key: &[u8],
156    ) -> Option<(impl Iterator<Item = &'a V> + Send + 'a, bool)>
157    where
158        V: 'a,
159    {
160        if let Some(values) = self.next_translated_values_no_cycle(key) {
161            return Some((values, false));
162        }
163        self.first_translated_values().map(|values| (values, true))
164    }
165
166    fn first_translated_key<'a>(&'a self) -> Option<impl Iterator<Item = &'a V> + Send + 'a>
167    where
168        V: 'a,
169    {
170        self.first_translated_values()
171    }
172
173    fn last_translated_key<'a>(&'a self) -> Option<impl Iterator<Item = &'a V> + Send + 'a>
174    where
175        V: 'a,
176    {
177        self.last_translated_values()
178    }
179}
180
181impl<T: Translator, V: Send + Sync> super::Factory for Index<T, V> {
182    type Translator = T;
183
184    fn new(ctx: impl commonware_runtime::Metrics, translator: T) -> Self {
185        Self::new(ctx, translator)
186    }
187}
188
189impl<T: Translator, V: Send + Sync> Unordered for Index<T, V> {
190    type Value = V;
191
192    fn get_many<'a, K: AsRef<[u8]>>(&'a self, keys: &[K], mut visit: impl FnMut(usize, &'a V))
193    where
194        V: 'a,
195    {
196        // Probe in translated-key order: consecutive tree descents share upper node paths,
197        // which stay cache-resident across the batch.
198        let mut order: Vec<(T::Key, usize)> = keys
199            .iter()
200            .enumerate()
201            .map(|(key_idx, key)| (self.translator.transform(key.as_ref()), key_idx))
202            .collect();
203        order.sort_unstable();
204        for (translated, key_idx) in order {
205            for value in self.get_translated(translated) {
206                visit(key_idx, value);
207            }
208        }
209    }
210    type Cursor<'a>
211        = Cursor<'a, T::Key, V, T>
212    where
213        Self: 'a;
214
215    fn get<'a>(&'a self, key: &[u8]) -> impl Iterator<Item = &'a V> + 'a
216    where
217        V: 'a,
218    {
219        self.get_translated(self.translator.transform(key))
220    }
221
222    fn get_mut<'a>(&'a mut self, key: &[u8]) -> Option<Self::Cursor<'a>> {
223        let k = self.translator.transform(key);
224        match self.map.entry(k) {
225            BTreeEntry::Occupied(entry) => Some(Cursor::<'_, T::Key, V, T>::new(
226                entry,
227                &mut self.overflow,
228                &self.keys,
229                &self.items,
230                &self.pruned,
231            )),
232            BTreeEntry::Vacant(_) => None,
233        }
234    }
235
236    fn get_mut_or_insert<'a>(&'a mut self, key: &[u8], value: V) -> Option<Self::Cursor<'a>> {
237        let k = self.translator.transform(key);
238        match self.map.entry(k) {
239            BTreeEntry::Occupied(entry) => Some(Cursor::<'_, T::Key, V, T>::new(
240                entry,
241                &mut self.overflow,
242                &self.keys,
243                &self.items,
244                &self.pruned,
245            )),
246            BTreeEntry::Vacant(entry) => {
247                Self::create(&self.keys, &self.items, entry, value);
248                None
249            }
250        }
251    }
252
253    fn insert(&mut self, key: &[u8], value: V) {
254        let k = self.translator.transform(key);
255        match self.map.entry(k) {
256            BTreeEntry::Occupied(mut entry) => {
257                // The newest value is stored inline; the displaced value joins the end of the
258                // overflow chain.
259                let old = std::mem::replace(entry.get_mut(), value);
260                push_displaced(&mut self.overflow, k, old);
261                self.items.inc();
262            }
263            BTreeEntry::Vacant(entry) => {
264                Self::create(&self.keys, &self.items, entry, value);
265            }
266        }
267    }
268
269    fn insert_and_retain(&mut self, key: &[u8], value: V, should_retain: impl Fn(&V) -> bool) {
270        let k = self.translator.transform(key);
271        match self.map.entry(k) {
272            BTreeEntry::Occupied(mut entry) => {
273                // Optimized fast path for the common case of no overflow chain.
274                #[allow(clippy::map_entry)]
275                if !self.overflow.contains_key(&k) {
276                    match (should_retain(entry.get()), should_retain(&value)) {
277                        // Keep both, with the new value placed at the end of the overflow chain.
278                        (true, true) => {
279                            self.overflow.insert(k, vec![value]);
280                            self.items.inc();
281                        }
282                        // Drop the existing value, keep the new one: replace in place.
283                        (false, true) => {
284                            *entry.get_mut() = value;
285                            self.pruned.inc();
286                        }
287                        // Drop both: remove the key entirely.
288                        (false, false) => {
289                            entry.remove();
290                            self.keys.dec();
291                            self.items.dec();
292                            self.pruned.inc();
293                        }
294                        // Keep the existing value, drop the new one: nothing to do.
295                        (true, false) => {}
296                    }
297                    return;
298                }
299
300                // Slow path: the key has conflicting values; walk them with a cursor.
301                let mut cursor = Cursor::<'_, T::Key, V, T>::new(
302                    entry,
303                    &mut self.overflow,
304                    &self.keys,
305                    &self.items,
306                    &self.pruned,
307                );
308
309                // Drop anything that should not be retained.
310                cursor.retain(&should_retain);
311
312                // Add the new value only if it should be retained.
313                if should_retain(&value) {
314                    cursor.insert(value);
315                }
316            }
317            BTreeEntry::Vacant(entry) => {
318                // Create the entry only if the value should be retained.
319                if should_retain(&value) {
320                    Self::create(&self.keys, &self.items, entry, value);
321                }
322            }
323        }
324    }
325
326    fn remove(&mut self, key: &[u8]) {
327        let k = self.translator.transform(key);
328        if self.map.remove(&k).is_some() {
329            // To ensure metrics are accurate, account for all conflicting values in the chain.
330            self.keys.dec();
331            self.items.dec();
332            self.pruned.inc();
333            if !self.overflow.is_empty()
334                && let Some(chain) = self.overflow.remove(&k)
335            {
336                self.items.dec_by(chain.len() as i64);
337                self.pruned.inc_by(chain.len() as u64);
338            }
339        }
340    }
341
342    #[cfg(test)]
343    fn keys(&self) -> usize {
344        self.keys.get() as usize
345    }
346
347    #[cfg(test)]
348    fn items(&self) -> usize {
349        self.items.get() as usize
350    }
351
352    #[cfg(test)]
353    fn pruned(&self) -> usize {
354        self.pruned.get() as usize
355    }
356}
357
358#[cfg(test)]
359mod tests {
360    use super::*;
361    use crate::translator::OneCap;
362    use commonware_formatting::hex;
363    use commonware_macros::test_traced;
364    use commonware_runtime::{Runner, deterministic};
365
366    #[test_traced]
367    fn test_ordered_empty_index() {
368        let runner = deterministic::Runner::default();
369        runner.start(|context| async move {
370            let index = Index::<_, u64>::new(context, OneCap);
371
372            assert!(index.first_translated_key().is_none());
373            assert!(index.last_translated_key().is_none());
374            assert!(index.prev_translated_key(b"key").is_none());
375            assert!(index.next_translated_key(b"key").is_none());
376        });
377    }
378
379    #[test_traced]
380    fn test_ordered_index_ordering() {
381        let runner = deterministic::Runner::default();
382        runner.start(|context| async move {
383            let mut index = Index::<_, u64>::new(context, OneCap);
384            assert_eq!(index.keys(), 0);
385
386            let k1 = &hex!("0x0b02AA"); // translated key 0b
387            let k2 = &hex!("0x1c04CC"); // translated key 1c
388            let k2_collides = &hex!("0x1c0311");
389            let k3 = &hex!("0x2d06EE"); // translated key 2d
390            index.insert(k1, 1);
391            index.insert(k2, 21);
392            index.insert(k2_collides, 22);
393            index.insert(k3, 3);
394            assert_eq!(index.keys(), 3);
395
396            // First translated key is 0b.
397            let mut next = index.first_translated_key().unwrap();
398            assert_eq!(next.next().unwrap(), &1);
399            assert_eq!(next.next(), None);
400
401            // Next translated key to 0x00 is 0b.
402            let (mut next, wrapped) = index.next_translated_key(&[0x00]).unwrap();
403            assert!(!wrapped);
404            assert_eq!(next.next().unwrap(), &1);
405            assert_eq!(next.next(), None);
406
407            // Next translated key to 0x0b is 1c.
408            let (mut next, wrapped) = index.next_translated_key(&hex!("0x0b0102")).unwrap();
409            assert!(!wrapped);
410            assert_eq!(next.next().unwrap(), &22);
411            assert_eq!(next.next().unwrap(), &21);
412            assert_eq!(next.next(), None);
413
414            // Next translated key to 0x1b is 1c.
415            let (mut next, wrapped) = index.next_translated_key(&hex!("0x1b010203")).unwrap();
416            assert!(!wrapped);
417            assert_eq!(next.next().unwrap(), &22);
418            assert_eq!(next.next().unwrap(), &21);
419            assert_eq!(next.next(), None);
420
421            // Next translated key to 0x2a is 2d.
422            let (mut next, wrapped) = index.next_translated_key(&hex!("0x2a01020304")).unwrap();
423            assert!(!wrapped);
424            assert_eq!(next.next().unwrap(), &3);
425            assert_eq!(next.next(), None);
426
427            // Next translated key to 0x2d cycles around to 0x0b.
428            let (mut next, wrapped) = index.next_translated_key(k3).unwrap();
429            assert!(wrapped);
430            assert_eq!(next.next().unwrap(), &1);
431            assert_eq!(next.next(), None);
432
433            // Another cycle-around case.
434            let (mut next, wrapped) = index.next_translated_key(&hex!("0x2eFF")).unwrap();
435            assert!(wrapped);
436            assert_eq!(next.next().unwrap(), &1);
437            assert_eq!(next.next(), None);
438
439            // Previous translated key of first key is the last key.
440            let (mut prev, wrapped) = index.prev_translated_key(k1).unwrap();
441            assert!(wrapped);
442            assert_eq!(prev.next().unwrap(), &3);
443            assert_eq!(prev.next(), None);
444
445            // Previous translated key is 0b.
446            let (mut prev, wrapped) = index.prev_translated_key(&hex!("0x0c0102")).unwrap();
447            assert!(!wrapped);
448            assert_eq!(prev.next().unwrap(), &1);
449            assert_eq!(prev.next(), None);
450
451            // Previous translated key is 1c.
452            let (mut prev, wrapped) = index.prev_translated_key(&hex!("0x1d0102")).unwrap();
453            assert!(!wrapped);
454            assert_eq!(prev.next().unwrap(), &22);
455            assert_eq!(prev.next().unwrap(), &21);
456            assert_eq!(prev.next(), None);
457
458            // Previous translated key is 2d.
459            let (mut prev, wrapped) = index.prev_translated_key(&hex!("0xCC0102")).unwrap();
460            assert!(!wrapped);
461            assert_eq!(prev.next().unwrap(), &3);
462            assert_eq!(prev.next(), None);
463
464            // Last translated key is 2d.
465            let mut last = index.last_translated_key().unwrap();
466            assert_eq!(last.next().unwrap(), &3);
467            assert_eq!(last.next(), None);
468        });
469    }
470}