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