Skip to main content

mito2/cache/
columnar.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Immutable native-reader metadata shares the decoded SST reservation.
16
17use std::any::{Any, TypeId};
18use std::sync::Arc;
19
20use store_api::storage::FileId;
21
22use crate::cache::{CacheStrategy, ColumnarMetaCache};
23use crate::error::Result;
24use crate::metrics::{CACHE_BYTES, CACHE_HIT, CACHE_MISS};
25
26const COLUMNAR_META: &str = "columnar_metadata";
27
28/// Identity of one immutable native-reader structure.
29#[derive(Debug, Clone, Hash, PartialEq, Eq)]
30pub(crate) struct DecodedKey {
31    namespace: FileId,
32    identity: String,
33    representation: TypeId,
34}
35
36#[derive(Clone)]
37pub(crate) struct DecodedValue {
38    value: Arc<dyn Any + Send + Sync>,
39    weight: u32,
40}
41impl DecodedValue {
42    pub(crate) fn label(&self) -> &'static str {
43        COLUMNAR_META
44    }
45}
46/// Weigher for the native-reader metadata tier; the value carries its own admitted weight.
47pub(crate) fn columnar_meta_weight(_key: &DecodedKey, value: &DecodedValue) -> u32 {
48    value.weight
49}
50
51/// Contains no artifact handle or live object-store reader. Loads run independently;
52/// admission uses a synchronous, atomic cache entry after loading.
53#[derive(Clone)]
54pub(crate) struct MetadataCache {
55    cache: ColumnarMetaCache,
56    namespace: FileId,
57}
58impl CacheStrategy {
59    pub(crate) fn columnar_metadata(&self, namespace: FileId) -> Option<MetadataCache> {
60        let Self::EnableAll(manager) = self else {
61            return None;
62        };
63        Some(MetadataCache {
64            cache: manager.columnar_meta_cache.clone()?,
65            namespace,
66        })
67    }
68}
69
70/// Loads only validated immutable structures. Identities include the generation path,
71/// object length, and the complete reference/codec context used to validate the value.
72/// Oversized entries bypass admission; disabled caches perform the same validation.
73pub(crate) async fn load<T: Send + Sync + 'static>(
74    cache: Option<&MetadataCache>,
75    identity: String,
76    weight: impl FnOnce(&T) -> usize,
77    loader: impl Future<Output = Result<T>>,
78) -> Result<Arc<T>> {
79    let Some(context) = cache else {
80        return loader.await.map(Arc::new);
81    };
82    let key = DecodedKey {
83        namespace: context.namespace,
84        identity,
85        representation: TypeId::of::<T>(),
86    };
87    let get = || {
88        context
89            .cache
90            .get(&key)
91            .and_then(|value| value.value.downcast::<T>().ok())
92    };
93    if let Some(value) = get() {
94        CACHE_HIT.with_label_values(&[COLUMNAR_META]).inc();
95        return Ok(value);
96    }
97    CACHE_MISS.with_label_values(&[COLUMNAR_META]).inc();
98    static METRICS: std::sync::LazyLock<Arc<common_cache::metrics::CacheMetrics>> =
99        std::sync::LazyLock::new(|| crate::metrics::cache_loading_metrics(COLUMNAR_META));
100    let value = Arc::new(METRICS.loads.observe(loader).await?);
101    // A caller may flush buffered output while its loader is Pending, then stop
102    // polling it under downstream backpressure. Never hold a shared lock across
103    // that await: another stream may need the lock to finish the current series.
104    let identity_size = key.identity.capacity();
105    let retained = weight(&value).saturating_add(identity_size).saturating_add(
106        std::mem::size_of::<DecodedKey>()
107            + std::mem::size_of::<DecodedValue>()
108            + 2 * std::mem::size_of::<usize>(),
109    );
110    if let Ok(weight) = u32::try_from(retained)
111        && u64::from(weight) <= context.cache.policy().max_capacity().unwrap_or(0)
112    {
113        let entry = context.cache.entry(key).or_insert_with(|| DecodedValue {
114            value: value.clone(),
115            weight,
116        });
117        if entry.is_fresh() {
118            CACHE_BYTES
119                .with_label_values(&[COLUMNAR_META])
120                .add(i64::from(weight));
121        }
122        let admitted = entry.into_value().value;
123        if let Ok(admitted) = admitted.downcast::<T>() {
124            return Ok(admitted);
125        }
126    }
127    Ok(value)
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133    use crate::cache::CacheManager;
134    use std::hash::{DefaultHasher, Hash, Hasher};
135
136    #[rstest::rstest]
137    #[case::same_key(false)]
138    #[case::stripe_collision(true)]
139    #[tokio::test]
140    async fn backpressured_load_does_not_block_other_readers(#[case] different_key: bool) {
141        let manager = CacheManager::builder()
142            .sst_meta_cache_size(8192)
143            .enable_columnar_meta_cache(true)
144            .build();
145        let strategy = CacheStrategy::EnableAll(Arc::new(manager));
146        let cache = strategy.columnar_metadata(FileId::random()).unwrap();
147        let identity = "generation/part/page";
148        // Keep the former stripe collision as a regression case for the old loader.
149        let stripe = |identity: &str| {
150            let key = DecodedKey {
151                namespace: cache.namespace,
152                identity: identity.to_string(),
153                representation: TypeId::of::<Vec<u8>>(),
154            };
155            let mut hash = DefaultHasher::new();
156            key.hash(&mut hash);
157            hash.finish() as usize % 32
158        };
159        let other_identity = if different_key {
160            (0..)
161                .map(|i| format!("other/{i}"))
162                .find(|other| stripe(other) == stripe(identity))
163                .unwrap()
164        } else {
165            identity.to_string()
166        };
167        let (complete, pending) = tokio::sync::oneshot::channel();
168        let mut owner = Box::pin(load(
169            Some(&cache),
170            "generation/part/page".into(),
171            |_| 64,
172            async {
173                pending.await.unwrap();
174                Ok(vec![1u8, 2, 3])
175            },
176        ));
177        assert!(futures::poll!(&mut owner).is_pending());
178        // Deliver the I/O wake, but deliberately never poll its owner again until
179        // the second reader completes. This models a stream paused after a flush.
180        complete.send(()).unwrap();
181        let other = tokio::time::timeout(
182            std::time::Duration::from_secs(1),
183            load(Some(&cache), other_identity, |_| 64, async {
184                Ok(vec![1u8, 2, 3])
185            }),
186        )
187        .await
188        .unwrap()
189        .unwrap();
190        assert_eq!(other.as_slice(), &[1, 2, 3]);
191        let first = owner.await.unwrap();
192        if !different_key {
193            assert!(Arc::ptr_eq(&first, &other));
194        }
195        let cached = load(Some(&cache), "generation/part/page".into(), |_| 64, async {
196            panic!("must reuse the admitted entry")
197        })
198        .await
199        .unwrap();
200        assert!(Arc::ptr_eq(&first, &cached));
201
202        let mut canceled = Box::pin(load(
203            Some(&cache),
204            "canceled".into(),
205            |_| 64,
206            std::future::pending::<Result<Vec<u8>>>(),
207        ));
208        assert!(futures::poll!(&mut canceled).is_pending());
209        drop(canceled);
210        let retry = load(Some(&cache), "canceled".into(), |_| 64, async {
211            Ok(vec![4u8])
212        })
213        .await
214        .unwrap();
215        assert_eq!(&[4], retry.as_slice());
216    }
217    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
218    async fn concurrent_misses_share_the_admitted_value() {
219        let strategy = CacheStrategy::EnableAll(Arc::new(
220            CacheManager::builder()
221                .sst_meta_cache_size(8192)
222                .enable_columnar_meta_cache(true)
223                .build(),
224        ));
225        let cache = strategy.columnar_metadata(FileId::random()).unwrap();
226        let barrier = Arc::new(tokio::sync::Barrier::new(64));
227        let tasks = (0..64)
228            .map(|_| {
229                let cache = cache.clone();
230                let barrier = barrier.clone();
231                tokio::spawn(async move {
232                    load(Some(&cache), "shared-generation".into(), |_| 64, async {
233                        barrier.wait().await;
234                        Ok(vec![1_u8; 64])
235                    })
236                    .await
237                    .unwrap()
238                })
239            })
240            .collect::<Vec<_>>();
241        let values = tokio::time::timeout(
242            std::time::Duration::from_secs(5),
243            futures::future::try_join_all(tasks),
244        )
245        .await
246        .unwrap()
247        .unwrap();
248        assert!(values.iter().all(|value| Arc::ptr_eq(value, &values[0])));
249    }
250}