Skip to main content

mito2/cache/
parquet_page.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//! Fixed byte blocks shared across row groups of an immutable Parquet file.
16
17use std::io;
18use std::mem;
19use std::ops::Range;
20use std::sync::Arc;
21use std::time::Duration;
22
23use bytes::Bytes;
24use common_base::range_read::RangeReader;
25use common_cache::paged::{PageFetchStats, PagedCache};
26
27use crate::cache::columnar::MetadataPart;
28use crate::metrics;
29use crate::sst::file::RegionFileId;
30
31/// Default byte blocks, independent of the Parquet format's encoded data-page boundaries.
32pub(crate) const PAGE_SIZE: u64 = 64 * 1024;
33
34/// Internal tuning knob, in bytes; read only when constructing a cache.
35const PAGE_SIZE_ENV: &str = "GREPTIME_PARQUET_PAGE_SIZE";
36/// Expire pages one hour after insertion; physical reclamation uses cache maintenance.
37const PAGE_TTL: Duration = Duration::from_secs(3600);
38
39fn parse_page_size(value: Option<&str>) -> u64 {
40    match value {
41        None => PAGE_SIZE,
42        Some(value) => match value.parse::<u64>() {
43            Ok(size) if (1..=MAX_PAGE_SIZE).contains(&size) => size,
44            _ => {
45                common_telemetry::warn!(
46                    "Invalid {PAGE_SIZE_ENV}: expected bytes in 1..={MAX_PAGE_SIZE}; using {PAGE_SIZE}"
47                );
48                PAGE_SIZE
49            }
50        },
51    }
52}
53
54/// Largest block whose bytes and entry overhead fit the cache's u32 weight.
55pub(crate) const MAX_PAGE_SIZE: u64 = u32::MAX as u64
56    - (mem::size_of::<(PageFile, u64)>() + mem::size_of::<Bytes>() + mem::size_of::<u64>()) as u64;
57
58/// Caches immutable Parquet file bytes in fixed-size blocks shared across row groups.
59#[derive(Clone, Hash, PartialEq, Eq)]
60enum PageFile {
61    Parquet(RegionFileId),
62    Narthex {
63        part: MetadataPart,
64        start: u64,
65        end: u64,
66    },
67}
68
69pub(crate) struct ParquetPageCache {
70    page_size: u64,
71    cache: Arc<PagedCache<PageFile>>,
72}
73
74impl ParquetPageCache {
75    /// Constructs the production cache, resolving the internal block-size override once.
76    pub(crate) fn from_env(capacity: u64) -> Arc<Self> {
77        let value = std::env::var(PAGE_SIZE_ENV).ok();
78        Self::new(capacity, parse_page_size(value.as_deref()))
79    }
80
81    /// Creates a cache with a total byte capacity and a byte-block size.
82    pub(crate) fn new(capacity: u64, page_size: u64) -> Arc<Self> {
83        Self::with_ttl(capacity, page_size, PAGE_TTL)
84    }
85
86    fn with_ttl(capacity: u64, page_size: u64, ttl: Duration) -> Arc<Self> {
87        Arc::new(Self {
88            page_size,
89            cache: Arc::new(PagedCache::new_with_ttl(
90                "parquet_pages",
91                capacity,
92                page_size,
93                |_: &(PageFile, u64), bytes: &Bytes| {
94                    (mem::size_of::<(PageFile, u64)>()
95                        + mem::size_of::<Bytes>()
96                        + mem::size_of::<u64>()
97                        + bytes.len())
98                    .try_into()
99                    .unwrap_or(u32::MAX)
100                },
101                metrics::cache_page_observer("page", "page", |hits, misses| {
102                    (usize::from(hits > 0), usize::from(misses > 0))
103                }),
104                Some(ttl),
105            )),
106        })
107    }
108
109    /// Recovers the immutable file size from a requested block already in memory.
110    pub(crate) async fn known_file_size(
111        &self,
112        file: RegionFileId,
113        ranges: &[Range<u64>],
114    ) -> Option<u64> {
115        self.cache
116            .known_file_size(&PageFile::Parquet(file), ranges)
117            .await
118    }
119
120    /// Fetches ranges in input order, sharing missing blocks and returning [`PageFetchStats`].
121    /// The reader must address the immutable file identified by `file`.
122    pub(crate) async fn fetch<R: RangeReader + ?Sized>(
123        &self,
124        file: RegionFileId,
125        file_size: u64,
126        ranges: &[Range<u64>],
127        reader: &R,
128    ) -> Result<(Vec<Bytes>, PageFetchStats), Arc<io::Error>> {
129        // Also protect internal callers that supply an explicit block size.
130        if self.page_size == 0 || self.page_size > MAX_PAGE_SIZE {
131            return Err(Arc::new(io::Error::new(
132                io::ErrorKind::InvalidInput,
133                format!(
134                    "Parquet cache page size {} is outside 1..={MAX_PAGE_SIZE} bytes",
135                    self.page_size
136                ),
137            )));
138        }
139        let result = self
140            .cache
141            .fetch(PageFile::Parquet(file), file_size, ranges, reader)
142            .await?;
143        metrics::cache_page_fetch_metrics("page", &result.1);
144        Ok(result)
145    }
146
147    pub(crate) fn page_size(&self) -> u64 {
148        self.page_size
149    }
150
151    pub(crate) async fn fetch_narthex<R: RangeReader + 'static>(
152        &self,
153        pool: &common_cache::LoadPool,
154        part: MetadataPart,
155        area: Range<u64>,
156        ranges: &[Range<u64>],
157        reader: Arc<R>,
158    ) -> Result<(Vec<Bytes>, PageFetchStats), Arc<io::Error>> {
159        let size = area.end - area.start;
160        let key = PageFile::Narthex {
161            part,
162            start: area.start,
163            end: area.end,
164        };
165        let result = self
166            .cache
167            .fetch_in_pool(pool, key, size, ranges, reader)
168            .await?;
169        metrics::cache_page_fetch_metrics("page", &result.1);
170        Ok(result)
171    }
172
173    /// Checks whether a completed block is available without recording a lookup event.
174    #[cfg(test)]
175    pub(crate) async fn contains(&self, file: RegionFileId, page_id: u64) -> bool {
176        self.cache.contains(&PageFile::Parquet(file), page_id).await
177    }
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183    use async_trait::async_trait;
184    use common_base::range_read::Metadata;
185    use std::sync::Mutex;
186    use store_api::storage::{FileId, RegionId};
187
188    #[derive(Default)]
189    struct Reader(Mutex<Vec<Range<u64>>>);
190
191    #[async_trait]
192    impl RangeReader for Reader {
193        async fn metadata(&self) -> io::Result<Metadata> {
194            Ok(Metadata {
195                content_length: PAGE_SIZE * 2 + 10,
196            })
197        }
198        async fn read(&self, range: Range<u64>) -> io::Result<Bytes> {
199            self.0.lock().unwrap().push(range.clone());
200            tokio::task::yield_now().await;
201            Ok(Bytes::from(range.map(|n| n as u8).collect::<Vec<_>>()))
202        }
203    }
204
205    #[tokio::test]
206    async fn test_aligns_and_reuses_partial_overlaps_without_merging_reads() {
207        let cache = ParquetPageCache::new(1024 * 1024, PAGE_SIZE);
208        let file = RegionFileId::new(RegionId::new(1, 1), FileId::random());
209        let size = PAGE_SIZE * 2 + 10;
210        let reader = Reader::default();
211        let (result, stats) = cache
212            .fetch(
213                file,
214                size,
215                &[1..4, PAGE_SIZE - 2..PAGE_SIZE + 2, size - 3..size],
216                &reader,
217            )
218            .await
219            .unwrap();
220        assert_eq!(&result[0][..], &[1, 2, 3]);
221        assert_eq!(&result[1][..], &[254, 255, 0, 1]);
222        assert_eq!(&result[2][..], &[7, 8, 9]);
223        assert_eq!(
224            (
225                stats.requested_bytes,
226                stats.unique_requested_bytes,
227                stats.aligned_bytes
228            ),
229            (10, 10, size)
230        );
231        assert_eq!(
232            reader.0.lock().unwrap().as_slice(),
233            &[0..PAGE_SIZE, PAGE_SIZE..PAGE_SIZE * 2, PAGE_SIZE * 2..size]
234        );
235        let (_, stats) = cache
236            .fetch(file, size, &[2..6, 4..8], &reader)
237            .await
238            .unwrap();
239        assert_eq!(
240            (stats.cache_hit, stats.cache_miss, stats.cached_bytes),
241            (1, 0, 8)
242        );
243        assert_eq!(reader.0.lock().unwrap().len(), 3);
244    }
245
246    #[tokio::test]
247    async fn file_identity_includes_region_and_concurrent_reads_share() {
248        let cache = ParquetPageCache::new(1024 * 1024, PAGE_SIZE);
249        let file_id = FileId::random();
250        let first = RegionFileId::new(RegionId::new(1, 1), file_id);
251        let second = RegionFileId::new(RegionId::new(2, 1), file_id);
252        let reader = Reader::default();
253        let ranges = [0..4, 2..6];
254        let (a, b) = tokio::join!(
255            cache.fetch(first, 100, &ranges, &reader),
256            cache.fetch(first, 100, &ranges, &reader)
257        );
258        assert_eq!(a.unwrap().0, b.unwrap().0);
259        assert_eq!(reader.0.lock().unwrap().len(), 1);
260        cache.fetch(second, 100, &ranges, &reader).await.unwrap();
261        assert_eq!(reader.0.lock().unwrap().len(), 2);
262        assert!(cache.contains(first, 0).await);
263        assert!(cache.contains(second, 0).await);
264    }
265
266    #[tokio::test]
267    async fn narthex_pages_are_shared_only_within_the_same_generation_part_and_area() {
268        let cache = ParquetPageCache::new(1024 * 1024, PAGE_SIZE);
269        let pool = common_cache::LoadPool::new(std::num::NonZeroUsize::MIN, tokio::spawn);
270        let reader = Arc::new(Reader::default());
271        let generation = FileId::random();
272        for (id, part, area, misses) in [
273            (generation, 0, 4..12, 1),
274            (generation, 0, 4..12, 0),
275            (FileId::random(), 0, 4..12, 1),
276            (generation, 1, 4..12, 1),
277            (generation, 0, 12..20, 1),
278            (generation, 0, 4..16, 1),
279        ] {
280            let (_, stats) = cache
281                .fetch_narthex(
282                    &pool,
283                    MetadataPart {
284                        generation: id,
285                        part_id: part,
286                        samples_location: None,
287                    },
288                    area,
289                    std::slice::from_ref(&(0..2)),
290                    reader.clone(),
291                )
292                .await
293                .unwrap();
294            assert_eq!(stats.cache_miss, misses);
295        }
296    }
297
298    #[tokio::test]
299    async fn configurable_blocks_preserve_cross_block_and_tail_reads() {
300        let file = RegionFileId::new(RegionId::new(1, 1), FileId::random());
301        let size = PAGE_SIZE * 2 + 10;
302        // Include a non-power-of-two size: the layout only requires a nonzero divisor.
303        for page_size in [1, 37, 4096, PAGE_SIZE, PAGE_SIZE * 4] {
304            let cache = ParquetPageCache::new(16 * 1024 * 1024, page_size);
305            let reader = Reader::default();
306            let boundary = page_size.min(size - 1);
307            let ranges = [
308                0..3,
309                boundary - 1..boundary + 1,
310                PAGE_SIZE - 2..PAGE_SIZE + 2,
311                size - 3..size,
312                size..size,
313            ];
314            let expected: Vec<_> = ranges
315                .iter()
316                .map(|r| Bytes::from(r.clone().map(|n| n as u8).collect::<Vec<_>>()))
317                .collect();
318            let (actual, _) = cache.fetch(file, size, &ranges, &reader).await.unwrap();
319            assert_eq!(actual, expected);
320            let reads = reader.0.lock().unwrap().len();
321            assert!(reader.0.lock().unwrap().iter().all(|r| r.end <= size));
322            let (cached, stats) = cache.fetch(file, size, &ranges, &reader).await.unwrap();
323            assert_eq!(cached, expected);
324            assert_eq!(stats.cache_miss, 0);
325            assert_eq!(reader.0.lock().unwrap().len(), reads);
326        }
327    }
328
329    #[tokio::test]
330    async fn builder_uses_fixed_block_size() {
331        use crate::cache::{CacheManager, CacheStrategy};
332
333        let strategy = CacheStrategy::EnableAll(Arc::new(
334            CacheManager::builder().page_cache_size(1024 * 1024).build(),
335        ));
336        let cache = strategy.parquet_page_cache().unwrap();
337        let reader = Reader::default();
338        let file = RegionFileId::new(RegionId::new(1, 1), FileId::random());
339        cache
340            .fetch(file, PAGE_SIZE * 2, std::slice::from_ref(&(0..1)), &reader)
341            .await
342            .unwrap();
343        assert_eq!(
344            reader.0.lock().unwrap().as_slice(),
345            std::slice::from_ref(&(0..PAGE_SIZE))
346        );
347        let disabled = CacheStrategy::EnableAll(Arc::new(CacheManager::builder().build()));
348        assert!(disabled.parquet_page_cache().is_none());
349    }
350
351    #[test]
352    fn block_size_override_uses_valid_bytes_or_default() {
353        for (value, expected) in [
354            (None, PAGE_SIZE),
355            (Some(""), PAGE_SIZE),
356            (Some("64KiB"), PAGE_SIZE),
357            (Some("0"), PAGE_SIZE),
358            (Some("-1"), PAGE_SIZE),
359            (Some("37"), 37),
360            (Some("131072"), 131072),
361        ] {
362            assert_eq!(parse_page_size(value), expected);
363        }
364        assert_eq!(
365            parse_page_size(Some(&MAX_PAGE_SIZE.to_string())),
366            MAX_PAGE_SIZE
367        );
368        assert_eq!(
369            parse_page_size(Some(&(MAX_PAGE_SIZE + 1).to_string())),
370            PAGE_SIZE
371        );
372    }
373
374    #[tokio::test]
375    async fn expired_pages_reload_without_file_invalidation() {
376        let cache = ParquetPageCache::with_ttl(1024 * 1024, PAGE_SIZE, Duration::from_millis(50));
377        let retained = ParquetPageCache::new(1024 * 1024, PAGE_SIZE);
378        let file = RegionFileId::new(RegionId::new(1, 1), FileId::random());
379        let reader = Reader::default();
380        let ranges = [0..4, 4..8];
381        let expected = cache.fetch(file, 100, &ranges, &reader).await.unwrap().0;
382        retained.fetch(file, 100, &ranges, &reader).await.unwrap();
383        cache.cache.run_pending_tasks().await;
384        retained.cache.run_pending_tasks().await;
385        assert!(retained.contains(file, 0).await);
386        tokio::time::timeout(Duration::from_secs(5), async {
387            while cache.contains(file, 0).await {
388                tokio::time::sleep(Duration::from_millis(5)).await;
389            }
390        })
391        .await
392        .unwrap();
393        assert!(retained.contains(file, 0).await);
394        let (actual, stats) = cache.fetch(file, 100, &ranges, &reader).await.unwrap();
395        assert_eq!(actual, expected);
396        assert_eq!(stats.cache_miss, 1);
397        assert_eq!(reader.0.lock().unwrap().len(), 3);
398    }
399
400    #[tokio::test]
401    async fn invalid_block_size_is_rejected_before_io() {
402        let file = RegionFileId::new(RegionId::new(1, 1), FileId::random());
403        for page_size in [0, MAX_PAGE_SIZE + 1, u64::MAX] {
404            let cache = ParquetPageCache::new(1024, page_size);
405            let reader = Reader::default();
406            let error = cache
407                .fetch(file, 100, std::slice::from_ref(&(0..4)), &reader)
408                .await
409                .unwrap_err();
410            assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
411            assert!(reader.0.lock().unwrap().is_empty());
412        }
413    }
414
415    #[tokio::test]
416    async fn oversized_page_is_returned_without_retention() {
417        let cache = ParquetPageCache::new(1, PAGE_SIZE);
418        let file = RegionFileId::new(RegionId::new(1, 1), FileId::random());
419        let reader = Reader::default();
420        let result = cache
421            .fetch(file, 100, &[0..4, 4..8], &reader)
422            .await
423            .unwrap();
424        assert_eq!(&result.0[0][..], &[0, 1, 2, 3]);
425        cache.cache.run_pending_tasks().await;
426        assert!(!cache.contains(file, 0).await);
427    }
428}