Skip to main content

itzma_core/
decoded.rs

1//! The decoded-structure cache.
2//!
3//! [`CacheStore`](crate::CacheStore) keeps bytes, so a warm query still parses
4//! every head, partition, block and directory it touches. This keeps what the
5//! parse produced, keyed by the object's path and the structure, so a warm
6//! query reads nothing from the store and decodes nothing. It needs no
7//! invalidation: an object's bytes never change while it exists, and index
8//! generations are never reused.
9//!
10//! Loads are single-flight. The first caller of a missing key marks it pending
11//! and runs its own load. Callers that find it pending wait, then look again:
12//! a value is a hit, and a load that failed or was dropped leaves nothing
13//! behind, so the next caller loads it itself with its own read budget. No
14//! error is ever shared between callers, so [`ItzmaError`] needs no `Clone`.
15//!
16//! One LRU bounded by weight in bytes, not shards: a decoded `Layer` of a whole
17//! segment can be larger than any fixed share of the limit would be.
18
19use std::any::Any;
20use std::collections::HashMap;
21use std::future::Future;
22use std::sync::{Arc, Mutex, PoisonError, Weak};
23
24use futures::channel::oneshot;
25use futures::future::{FutureExt, Shared};
26use lru::LruCache;
27use object_store::ObjectStore;
28use object_store::path::Path;
29
30use crate::error::{ItzmaError, Result};
31
32/// The limit a [`DecodedCache`] has when the caller does not say: 256 MiB.
33pub const DEFAULT_DECODED_MAX_BYTES: u64 = 256 * 1024 * 1024;
34
35/// How a [`DecodedCache`] is sized.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37#[non_exhaustive]
38pub struct DecodedCacheOptions {
39    /// The most bytes of decoded structures kept, by each structure's own
40    /// estimate of its size. A structure bigger than this is used and not
41    /// kept. Default [`DEFAULT_DECODED_MAX_BYTES`].
42    pub max_bytes: u64,
43}
44
45impl Default for DecodedCacheOptions {
46    fn default() -> Self {
47        Self {
48            max_bytes: DEFAULT_DECODED_MAX_BYTES,
49        }
50    }
51}
52
53impl DecodedCacheOptions {
54    /// Set [`max_bytes`](Self::max_bytes).
55    #[must_use]
56    pub fn max_bytes(mut self, max_bytes: u64) -> Self {
57        self.max_bytes = max_bytes;
58        self
59    }
60}
61
62/// Which structure of an object a cache entry holds.
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
64pub(crate) enum What {
65    /// A segment's header, trailer and directory (`RangedSegment::open`).
66    SegmentMeta,
67    /// A segment's Bloom filter.
68    Bloom,
69    /// A segment's zone statistics, every field of every block.
70    Zones,
71    /// One block of a segment's ids, attributes or tombstones.
72    IdBlock(usize),
73    AttrBlock(usize),
74    TombstoneBlock(usize),
75    /// An index object's prefix and head bytes (`index::open`), any kind.
76    IndexHead,
77    /// An SQ8 head, parsed.
78    Sq8Head,
79    /// One SQ8 partition, parsed.
80    Partition(u32),
81    /// A sparse index's term directory.
82    SparseDirectory,
83    /// A whole segment for the query's flat path, as a `SegmentView`.
84    View,
85}
86
87#[derive(Debug, Clone, PartialEq, Eq, Hash)]
88struct Key {
89    store: usize,
90    path: Path,
91    what: What,
92}
93
94type Value = Arc<dyn Any + Send + Sync>;
95type Pending = Shared<oneshot::Receiver<()>>;
96
97struct Inner {
98    ready: LruCache<Key, (Value, u64)>,
99    pending: HashMap<Key, Pending>,
100    used: u64,
101    /// The stores whose handles have used this cache, by address, so a store
102    /// dropped and another allocated at the same address cannot see its
103    /// entries.
104    stores: HashMap<usize, Weak<dyn ObjectStore>>,
105}
106
107/// Parsed index heads, partitions, segment directories, blocks and decoded
108/// segments, shared by every handle given it with
109/// [`Namespace::with_decoded_cache`](crate::Namespace::with_decoded_cache).
110///
111/// A hit costs no store call and is not charged to the read budget; a miss is
112/// read and charged as it would be without the cache. Only the query path uses
113/// it: `index`, `compact`, `gc`, `inspect` and `recover` never do. Entries are
114/// keyed by store as well as path, so one cache can serve handles over several
115/// stores.
116pub struct DecodedCache {
117    max_bytes: u64,
118    inner: Mutex<Inner>,
119}
120
121impl std::fmt::Debug for DecodedCache {
122    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123        let inner = self.lock();
124        f.debug_struct("DecodedCache")
125            .field("max_bytes", &self.max_bytes)
126            .field("used", &inner.used)
127            .field("entries", &inner.ready.len())
128            .finish()
129    }
130}
131
132impl DecodedCache {
133    /// An empty cache.
134    #[must_use]
135    pub fn new(options: DecodedCacheOptions) -> Arc<Self> {
136        Arc::new(Self {
137            max_bytes: options.max_bytes,
138            inner: Mutex::new(Inner {
139                ready: LruCache::unbounded(),
140                pending: HashMap::new(),
141                used: 0,
142                stores: HashMap::new(),
143            }),
144        })
145    }
146
147    fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
148        self.inner.lock().unwrap_or_else(PoisonError::into_inner)
149    }
150
151    /// A store's identity while it lives: the address of its data.
152    pub(crate) fn store_id(store: &Arc<dyn ObjectStore>) -> usize {
153        Arc::as_ptr(store).cast::<()>() as usize
154    }
155
156    /// A handle for reads from `store`.
157    pub(crate) fn handle(self: &Arc<Self>, store: &Arc<dyn ObjectStore>) -> DecodedRef {
158        let id = Self::store_id(store);
159        let mut inner = self.lock();
160        let known = inner.stores.get(&id).map(|weak| weak.strong_count() > 0);
161        if known == Some(false) {
162            Self::purge(&mut inner, id);
163        }
164        inner.stores.insert(id, Arc::downgrade(store));
165        DecodedRef {
166            cache: self.clone(),
167            store: id,
168        }
169    }
170
171    /// Drop the entries of the store at `id` if it is gone.
172    #[cfg(test)]
173    pub(crate) fn forget_dead(&self, id: usize) {
174        let mut inner = self.lock();
175        if inner.stores.get(&id).is_some_and(|w| w.strong_count() == 0) {
176            Self::purge(&mut inner, id);
177        }
178    }
179
180    #[cfg(test)]
181    pub(crate) fn entries_of(&self, id: usize) -> usize {
182        self.lock()
183            .ready
184            .iter()
185            .filter(|(k, _)| k.store == id)
186            .count()
187    }
188
189    fn purge(inner: &mut Inner, id: usize) {
190        let dead: Vec<Key> = inner
191            .ready
192            .iter()
193            .filter(|(key, _)| key.store == id)
194            .map(|(key, _)| key.clone())
195            .collect();
196        for key in dead {
197            if let Some((_, weight)) = inner.ready.pop(&key) {
198                inner.used -= weight;
199            }
200        }
201        inner.stores.remove(&id);
202    }
203
204    fn insert(&self, inner: &mut Inner, key: Key, value: Value, weight: u64) {
205        if weight > self.max_bytes {
206            return;
207        }
208        if let Some((_, old)) = inner.ready.put(key, (value, weight)) {
209            inner.used -= old;
210        }
211        inner.used += weight;
212        while inner.used > self.max_bytes {
213            match inner.ready.pop_lru() {
214                Some((_, (_, w))) => inner.used -= w,
215                None => break,
216            }
217        }
218    }
219}
220
221/// Removes the keys a caller claimed but did not fill, and wakes their
222/// waiters, however the load ended: an error, success, or a dropped future.
223struct Claim {
224    cache: Arc<DecodedCache>,
225    keys: Vec<Key>,
226    _wake: Vec<oneshot::Sender<()>>,
227}
228
229impl Drop for Claim {
230    fn drop(&mut self) {
231        let mut inner = self.cache.lock();
232        for key in &self.keys {
233            inner.pending.remove(key);
234        }
235    }
236}
237
238/// A [`DecodedCache`] bound to one store, as a query holds it.
239#[derive(Clone)]
240pub(crate) struct DecodedRef {
241    cache: Arc<DecodedCache>,
242    store: usize,
243}
244
245impl std::fmt::Debug for DecodedRef {
246    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
247        f.debug_struct("DecodedRef")
248            .field("store", &self.store)
249            .finish()
250    }
251}
252
253impl DecodedRef {
254    fn key(&self, path: &Path, what: What) -> Key {
255        Key {
256            store: self.store,
257            path: path.clone(),
258            what,
259        }
260    }
261
262    /// The structure `what` of `path`, from the cache or from `load`, which
263    /// gives the value and its weight in bytes and runs at most once per call.
264    pub(crate) async fn get_or_load<T, F, Fut>(
265        &self,
266        path: &Path,
267        what: What,
268        load: F,
269    ) -> Result<Arc<T>>
270    where
271        T: Send + Sync + 'static,
272        F: FnOnce() -> Fut,
273        Fut: Future<Output = Result<(T, u64)>>,
274    {
275        let mut load = Some(load);
276        let mut got = self
277            .get_or_load_many(path, &[what], |_| {
278                let load = load.take();
279                async move {
280                    match load {
281                        Some(load) => Ok(vec![load().await?]),
282                        // Only the first claim loads: a second would mean the
283                        // first one's value vanished, which `get_or_load_many`
284                        // never lets happen within one call.
285                        None => Err(ItzmaError::InvalidQuery("a cache load ran twice")),
286                    }
287                }
288            })
289            .await?;
290        got.pop()
291            .ok_or(ItzmaError::InvalidQuery("a cache load gave no value"))
292    }
293
294    /// The structures `whats` of `path`, in order. `load` is given the
295    /// positions in `whats` that are neither cached nor being loaded by another
296    /// caller, and returns their values and weights in that order, so it can
297    /// fetch them together. It runs once per round that finds such positions.
298    pub(crate) async fn get_or_load_many<T, F, Fut>(
299        &self,
300        path: &Path,
301        whats: &[What],
302        mut load: F,
303    ) -> Result<Vec<Arc<T>>>
304    where
305        T: Send + Sync + 'static,
306        F: FnMut(Vec<usize>) -> Fut,
307        Fut: Future<Output = Result<Vec<(T, u64)>>>,
308    {
309        let keys: Vec<Key> = whats.iter().map(|w| self.key(path, *w)).collect();
310        let mut out: Vec<Option<Arc<T>>> = vec![None; keys.len()];
311        loop {
312            let mut claimed = Vec::new();
313            let mut senders = Vec::new();
314            let mut waits = Vec::new();
315            {
316                let mut inner = self.cache.lock();
317                for (at, key) in keys.iter().enumerate() {
318                    if out[at].is_some() {
319                        continue;
320                    }
321                    let hit = inner.ready.get(key).map(|(value, _)| value.clone());
322                    if let Some(typed) = hit.and_then(|value| value.downcast::<T>().ok()) {
323                        out[at] = Some(typed);
324                    } else if let Some(pending) = inner.pending.get(key) {
325                        waits.push(pending.clone());
326                    } else {
327                        let (tx, rx) = oneshot::channel();
328                        inner.pending.insert(key.clone(), rx.shared());
329                        senders.push(tx);
330                        claimed.push(at);
331                    }
332                }
333            }
334            if claimed.is_empty() && waits.is_empty() {
335                break;
336            }
337            if !claimed.is_empty() {
338                let claim = Claim {
339                    cache: self.cache.clone(),
340                    keys: claimed.iter().map(|at| keys[*at].clone()).collect(),
341                    _wake: senders,
342                };
343                let values = load(claimed.clone()).await?;
344                if values.len() != claimed.len() {
345                    return Err(ItzmaError::InvalidQuery(
346                        "a cache load gave the wrong number of values",
347                    ));
348                }
349                let mut inner = self.cache.lock();
350                for (at, (value, weight)) in claimed.iter().zip(values) {
351                    let value = Arc::new(value);
352                    let shared: Value = value.clone();
353                    self.cache
354                        .insert(&mut inner, keys[*at].clone(), shared, weight);
355                    out[*at] = Some(value);
356                }
357                drop(inner);
358                drop(claim);
359            }
360            for wait in waits {
361                let _ = wait.await;
362            }
363        }
364        Ok(out.into_iter().flatten().collect())
365    }
366}
367
368#[cfg(test)]
369mod tests {
370    use std::sync::Arc;
371    use std::sync::atomic::{AtomicUsize, Ordering};
372
373    use futures::channel::oneshot;
374    use futures::future::FutureExt;
375    use object_store::ObjectStore;
376    use object_store::memory::InMemory;
377    use object_store::path::Path;
378
379    use super::*;
380    use crate::error::ItzmaError;
381
382    fn store() -> Arc<dyn ObjectStore> {
383        Arc::new(InMemory::new())
384    }
385
386    fn cache(max_bytes: u64) -> Arc<DecodedCache> {
387        DecodedCache::new(DecodedCacheOptions::default().max_bytes(max_bytes))
388    }
389
390    fn path(name: &str) -> Path {
391        Path::from(name)
392    }
393
394    /// A load that counts its calls and gives `value` with weight `weight`.
395    async fn counted(
396        calls: &AtomicUsize,
397        value: u64,
398        weight: u64,
399    ) -> crate::error::Result<(u64, u64)> {
400        calls.fetch_add(1, Ordering::SeqCst);
401        Ok((value, weight))
402    }
403
404    #[tokio::test]
405    async fn two_concurrent_gets_of_one_key_load_once() {
406        let s = store();
407        let handle = cache(1 << 20).handle(&s);
408        let calls = AtomicUsize::new(0);
409        let (open, gate) = oneshot::channel::<()>();
410        let gate = gate.shared();
411        let a = path("a");
412
413        let first = handle.get_or_load(&a, What::IndexHead, || async {
414            calls.fetch_add(1, Ordering::SeqCst);
415            let _ = gate.clone().await;
416            Ok::<_, ItzmaError>((7u64, 8))
417        });
418        let second = handle.get_or_load(&a, What::IndexHead, || async {
419            calls.fetch_add(1, Ordering::SeqCst);
420            Ok::<_, ItzmaError>((9u64, 8))
421        });
422        let release = async {
423            tokio::task::yield_now().await;
424            let _ = open.send(());
425        };
426        let (a, b, ()) = futures::join!(first, second, release);
427        assert_eq!(calls.load(Ordering::SeqCst), 1, "the waiter must not load");
428        assert!(Arc::ptr_eq(&a.unwrap(), &b.unwrap()));
429    }
430
431    #[tokio::test]
432    async fn a_hit_does_not_load_and_moves_the_entry_to_the_front() {
433        let s = store();
434        let handle = cache(100).handle(&s);
435        let calls = AtomicUsize::new(0);
436        let get = |name: &'static str, weight: u64| {
437            let handle = handle.clone();
438            let calls = &calls;
439            async move {
440                handle
441                    .get_or_load(&path(name), What::IndexHead, || counted(calls, 1, weight))
442                    .await
443                    .unwrap()
444            }
445        };
446        get("a", 60).await;
447        get("b", 30).await;
448        get("a", 60).await;
449        assert_eq!(calls.load(Ordering::SeqCst), 2, "the third get is a hit");
450
451        // 60 + 30 + 30 is over 100: the least recently used, `b`, goes.
452        get("c", 30).await;
453        get("a", 60).await;
454        assert_eq!(calls.load(Ordering::SeqCst), 3, "a stayed");
455        get("b", 30).await;
456        assert_eq!(calls.load(Ordering::SeqCst), 4, "b was evicted");
457    }
458
459    #[tokio::test]
460    async fn a_value_bigger_than_the_cache_is_returned_and_not_kept() {
461        let s = store();
462        let handle = cache(10).handle(&s);
463        let calls = AtomicUsize::new(0);
464        for _ in 0..2 {
465            let got = handle
466                .get_or_load(&path("big"), What::View, || counted(&calls, 5, 11))
467                .await
468                .unwrap();
469            assert_eq!(*got, 5);
470        }
471        assert_eq!(calls.load(Ordering::SeqCst), 2);
472    }
473
474    #[tokio::test]
475    async fn a_failed_load_is_not_kept_and_the_next_caller_loads_again() {
476        let s = store();
477        let handle = cache(1 << 20).handle(&s);
478        let failed = handle
479            .get_or_load(&path("a"), What::Bloom, || async {
480                Err::<(u64, u64), _>(ItzmaError::EmptyBatch)
481            })
482            .await;
483        assert!(matches!(failed, Err(ItzmaError::EmptyBatch)), "{failed:?}");
484        let calls = AtomicUsize::new(0);
485        let got = handle
486            .get_or_load(&path("a"), What::Bloom, || counted(&calls, 3, 1))
487            .await
488            .unwrap();
489        assert_eq!((*got, calls.load(Ordering::SeqCst)), (3, 1));
490    }
491
492    /// A waiter whose loader fails, or is dropped mid-load, loads itself.
493    #[tokio::test]
494    async fn a_waiter_loads_itself_when_the_loader_fails_or_is_dropped() {
495        for drop_the_loader in [false, true] {
496            let s = store();
497            let handle = cache(1 << 20).handle(&s);
498            let (open, gate) = oneshot::channel::<()>();
499            let gate = gate.shared();
500            let a = path("a");
501            let mut first = handle
502                .get_or_load(&a, What::IndexHead, || async {
503                    let _ = gate.clone().await;
504                    Err::<(u64, u64), _>(ItzmaError::EmptyBatch)
505                })
506                .boxed();
507            // The first caller claims the key and stops at the gate.
508            assert!(futures::poll!(&mut first).is_pending());
509            let calls = AtomicUsize::new(0);
510            let second = handle.get_or_load(&a, What::IndexHead, || counted(&calls, 4, 1));
511
512            // `second` is polled first and waits; then the loader fails or
513            // goes away.
514            let driver = async move {
515                if drop_the_loader {
516                    drop(first);
517                } else {
518                    let _ = open.send(());
519                    assert!(first.await.is_err());
520                }
521            };
522            let (got, ()) = futures::join!(second, driver);
523            assert_eq!(*got.unwrap(), 4, "drop: {drop_the_loader}");
524            assert_eq!(calls.load(Ordering::SeqCst), 1);
525        }
526    }
527
528    #[tokio::test]
529    async fn many_loads_only_the_missing_keys_in_one_call() {
530        let s = store();
531        let handle = cache(1 << 20).handle(&s);
532        let p = path("idx");
533        handle
534            .get_or_load(&p, What::Partition(1), || async {
535                Ok::<_, ItzmaError>((10u64, 1))
536            })
537            .await
538            .unwrap();
539        let asked = std::sync::Mutex::new(Vec::new());
540        let got = handle
541            .get_or_load_many(
542                &p,
543                &[What::Partition(0), What::Partition(1), What::Partition(2)],
544                |missing: Vec<usize>| {
545                    asked.lock().unwrap().push(missing.clone());
546                    async move { Ok(missing.iter().map(|i| (*i as u64 * 100, 1)).collect()) }
547                },
548            )
549            .await
550            .unwrap();
551        let values: Vec<u64> = got.iter().map(|v| **v).collect();
552        assert_eq!(values, [0, 10, 200]);
553        assert_eq!(*asked.lock().unwrap(), [vec![0, 2]]);
554    }
555
556    #[tokio::test]
557    async fn two_stores_never_share_an_entry() {
558        let (s1, s2) = (store(), store());
559        let shared = cache(1 << 20);
560        let (h1, h2) = (shared.handle(&s1), shared.handle(&s2));
561        let calls = AtomicUsize::new(0);
562        let a = h1
563            .get_or_load(&path("x"), What::IndexHead, || counted(&calls, 1, 1))
564            .await
565            .unwrap();
566        let b = h2
567            .get_or_load(&path("x"), What::IndexHead, || counted(&calls, 2, 1))
568            .await
569            .unwrap();
570        assert_eq!((*a, *b), (1, 2));
571    }
572
573    /// A store dropped and a new one allocated at the same address must not see
574    /// the old store's entries.
575    #[tokio::test]
576    async fn a_dead_stores_entries_are_dropped_when_its_address_comes_back() {
577        let shared = cache(1 << 20);
578        let s1 = store();
579        let id = DecodedCache::store_id(&s1);
580        shared
581            .handle(&s1)
582            .get_or_load(&path("x"), What::IndexHead, || async {
583                Ok::<_, ItzmaError>((1u64, 1))
584            })
585            .await
586            .unwrap();
587        drop(s1);
588        shared.forget_dead(id);
589        assert_eq!(shared.entries_of(id), 0);
590    }
591
592    #[test]
593    fn options_default_to_256_mib() {
594        assert_eq!(DecodedCacheOptions::default().max_bytes, 256 << 20);
595        assert_eq!(DecodedCacheOptions::default().max_bytes(5).max_bytes, 5);
596    }
597}