perf(mito2): cache decoded series indexes and prefetch discovery (#10836)

* perf(mito2): cache decoded series index blocks and prefetch discovery

Port decoded columns, bounded projection fills, and caller-side cache fills from 58562b0, c41dd0c, 5f9a1c6, and 9c171c1. Overlap the first batch of the next covered index as in ddbb64a.

Signed-off-by: evenyag <realevenyag@gmail.com>

* fix(mito2): account decoded cache fills in scan metrics

Signed-off-by: evenyag <realevenyag@gmail.com>

* test(mito2): verify decoded cache hits skip scan accounting

Signed-off-by: evenyag <realevenyag@gmail.com>

* fix(mito2): pass scan metrics to the decoded projection loader

Signed-off-by: evenyag <realevenyag@gmail.com>

* perf(mito2): share the index result cache with decoded series indexes

Signed-off-by: evenyag <realevenyag@gmail.com>

* refactor(mito2): bind series load metrics in the index result cache

Signed-off-by: evenyag <realevenyag@gmail.com>

---------

Signed-off-by: evenyag <realevenyag@gmail.com>
This commit is contained in:
Yingwen authored and GitHub committed 2026-12-04 10:32:11 +00:00
1 parent 4b205bc0f0
commit 3a1d0d110f
8 files changed
+787 -387

No files matched your search

+29 -10
View File
@@ -3302,7 +3302,7 @@ mod tests {
.index_metadata_size(index_metadata_size as u64)
.index_content_size(128)
.index_content_page_size(64)
.index_result_cache_size(128)
.index_result_cache_size(1024)
.puffin_metadata_size(puffin_metadata_size as u64)
.build(),
);
@@ -3325,7 +3325,9 @@ mod tests {
.await;
let predicate = PredicateKey::new_bloom(Arc::new(BTreeMap::new()));
let selection = Arc::new(RowGroupSelection::default());
result_cache.put(predicate.clone(), index_id.file_id(), selection);
result_cache
.put(predicate.clone(), index_id.file_id(), selection)
.await;
let metadata = Arc::new(FileMetadata {
blobs: Vec::new(),
properties: HashMap::new(),
@@ -3341,7 +3343,12 @@ mod tests {
.await
.is_some()
);
assert!(result_cache.get(&predicate, index_id.file_id()).is_some());
assert!(
result_cache
.get(&predicate, index_id.file_id())
.await
.is_some()
);
assert!(
puffin_metadata_cache
.get_metadata(&metadata_key)
@@ -3384,7 +3391,12 @@ mod tests {
.await
.is_none()
);
assert!(result_cache.get(&predicate, index_id.file_id()).is_none());
assert!(
result_cache
.get(&predicate, index_id.file_id())
.await
.is_none()
);
assert!(
puffin_metadata_cache
.get_metadata(&metadata_key)
@@ -3399,11 +3411,13 @@ mod tests {
inverted_cache
.put_metadata(file_key.clone(), Arc::new(InvertedIndexMetas::default()))
.await;
result_cache.put(
predicate.clone(),
index_id.file_id(),
Arc::new(RowGroupSelection::default()),
);
result_cache
.put(
predicate.clone(),
index_id.file_id(),
Arc::new(RowGroupSelection::default()),
)
.await;
puffin_metadata_cache
.put_metadata(
metadata_key.clone(),
@@ -3424,7 +3438,12 @@ mod tests {
.await
.is_none()
);
assert!(result_cache.get(&predicate, index_id.file_id()).is_none());
assert!(
result_cache
.get(&predicate, index_id.file_id())
.await
.is_none()
);
assert!(
puffin_metadata_cache
.get_metadata(&metadata_key)
+159 -40
View File
@@ -21,10 +21,11 @@ use snafu::IntoError;
use store_api::storage::FileId;
use crate::cache::file_cache::{FileCacheRef, FileType, IndexKey};
use crate::cache::index::result_cache::{IndexResultCache, SeriesIndexKey};
use crate::cache::write_cache::WriteCacheRef;
use crate::cache::{
CacheManagerRef, CacheStrategy, MetaValue, NarthexPrefilterBlock, PrefilterKey,
SstDecodedMetaKey,
SstDecodedMetaCache, SstDecodedMetaKey,
};
use crate::error::Result;
use crate::metrics::{CACHE_HIT, CACHE_MISS};
@@ -307,6 +308,19 @@ impl PartArea {
Some((manager, key))
}
/// Returns the index result cache and the location of a series payload.
pub(crate) fn series_index(&self, offset: u64) -> Option<(&IndexResultCache, SeriesIndexKey)> {
let cache = self.cache.as_ref()?.memory.as_ref()?.index_result_cache()?;
Some((
cache,
SeriesIndexKey {
generation: self.part.generation,
part_id: self.part.part_id,
offset,
},
))
}
/// Peak temporary bytes for aligned pages and the requested slices.
pub(crate) fn page_fetch_bytes(&self, ranges: &[std::ops::Range<u64>]) -> Option<usize> {
let pages = self.cache.as_ref()?.memory.as_ref()?.page_cache.as_ref()?;
@@ -437,47 +451,18 @@ where
return loader().await.map(Arc::new);
};
let key = SstDecodedMetaKey::Narthex(identity);
if let Some(MetaValue::Narthex(hit)) = decoded.get(&key).await {
CACHE_HIT.with_label_values(&[COLUMNAR_META]).inc();
return Ok(T::extract(hit.value));
if let Some(hit) = lookup(decoded, &key).await {
return Ok(hit);
}
CACHE_MISS.with_label_values(&[COLUMNAR_META]).inc();
let overhead = size_of::<SstDecodedMetaKey>() + size_of::<MetaValue>() + 2 * size_of::<usize>();
let cache = decoded.clone();
let worker_metrics = metrics.clone();
let worker_load = loader.clone();
let job = async move {
let result = cache
.try_get_with_unobserved(key, async {
let value = Arc::new(
worker_metrics
.loads
.observe(worker_load())
.await
.map_err(|e| Uncached::Error(Arc::new(e)))?,
);
let retained = weight(&value).saturating_add(overhead);
if let Ok(weight) = u32::try_from(retained)
&& u64::from(weight) <= cache.capacity()
{
Ok(MetaValue::Narthex(DecodedValue {
value: T::wrap(value),
weight,
}))
} else {
Err(Uncached::Value(value))
}
let job = {
let decoded = decoded.clone();
let metrics = metrics.clone();
let worker_load = loader.clone();
async move {
load_cached(&decoded, &metrics, key, weight, async move {
worker_load().await
})
.await;
match result {
Ok(MetaValue::Narthex(entry)) => Ok(T::extract(entry.value)),
Ok(MetaValue::Parquet(_)) => unreachable!("Narthex key contains Parquet metadata"),
Err(result) => match result.as_ref() {
Uncached::Value(value) => Ok(value.clone()),
Uncached::Error(error) => {
Err(crate::error::LoadSstMetaSnafu.into_error(error.clone()))
}
},
.await
}
};
match manager.narthex_load_pool().run(job).await {
@@ -486,11 +471,145 @@ where
}
}
async fn lookup<T: MetadataValue>(
cache: &SstDecodedMetaCache,
key: &SstDecodedMetaKey,
) -> Option<Arc<T>> {
if let Some(MetaValue::Narthex(hit)) = cache.get(key).await {
CACHE_HIT.with_label_values(&[COLUMNAR_META]).inc();
Some(T::extract(hit.value))
} else {
CACHE_MISS.with_label_values(&[COLUMNAR_META]).inc();
None
}
}
async fn load_cached<T>(
cache: &SstDecodedMetaCache,
metrics: &common_cache::metrics::CacheMetrics,
key: SstDecodedMetaKey,
weight: impl FnOnce(&T) -> usize + Send,
loader: impl Future<Output = Result<T>> + Send,
) -> Result<Arc<T>>
where
T: MetadataValue + Send + Sync + 'static,
{
let overhead = size_of::<SstDecodedMetaKey>() + size_of::<MetaValue>() + 2 * size_of::<usize>();
let result = cache
.try_get_with_unobserved(key, async {
let value = Arc::new(
metrics
.loads
.observe(loader)
.await
.map_err(|e| Uncached::Error(Arc::new(e)))?,
);
let retained = weight(&value).saturating_add(overhead);
if let Ok(weight) = u32::try_from(retained)
&& u64::from(weight) <= cache.capacity()
{
Ok(MetaValue::Narthex(DecodedValue {
value: T::wrap(value),
weight,
}))
} else {
Err(Uncached::Value(value))
}
})
.await;
match result {
Ok(MetaValue::Narthex(entry)) => Ok(T::extract(entry.value)),
Ok(MetaValue::Parquet(_)) => unreachable!("Narthex key contains Parquet metadata"),
Err(result) => match result.as_ref() {
Uncached::Value(value) => Ok(value.clone()),
Uncached::Error(error) => Err(crate::error::LoadSstMetaSnafu.into_error(error.clone())),
},
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::cache::CacheManager;
#[tokio::test]
async fn decoded_series_can_use_the_only_page_load_worker() {
let manager = CacheManager::builder()
.index_result_cache_size(8192)
.build();
manager
.narthex_load_pool
.get_or_init(|| common_cache::LoadPool::new(std::num::NonZeroUsize::MIN, tokio::spawn));
let cache = manager.index_result_cache().unwrap();
let key = SeriesIndexKey {
generation: FileId::random(),
part_id: 0,
offset: 0,
};
let value = tokio::time::timeout(
std::time::Duration::from_secs(2),
cache.load_series_column(key, async {
Ok(series::reader::Decoded::Null(
manager
.narthex_load_pool()
.run(async { 42_usize })
.await
.unwrap(),
))
}),
)
.await
.expect("decoded series load must leave a worker free for the page")
.unwrap();
assert!(matches!(*value, series::reader::Decoded::Null(42)));
}
#[tokio::test]
async fn decoded_series_keys_distinguish_generation_and_representation() {
use series::reader::{Decoded, DecodedProjection};
let cache = IndexResultCache::new(8192);
let key = SeriesIndexKey {
generation: FileId::random(),
part_id: 0,
offset: 32,
};
let mut metrics = crate::metrics::ColumnarReadMetrics::default();
for (key, rows) in [
(key, 3),
(
SeriesIndexKey {
generation: FileId::random(),
..key
},
4,
),
(SeriesIndexKey { part_id: 1, ..key }, 5),
(SeriesIndexKey { offset: 64, ..key }, 6),
(key, 3),
] {
let value = cache
.load_series_column(key, async {
*metrics.counts.entry("series_column_reads").or_default() += 1;
Ok(Decoded::Null(rows))
})
.await
.unwrap();
assert!(matches!(*value, Decoded::Null(n) if n == rows));
}
assert_eq!(metrics.counts["series_column_reads"], 4);
let block = cache
.load_series_block(key, async {
Ok(DecodedProjection::from([(
"tag".to_owned(),
Arc::new(Decoded::Null(7)),
)]))
})
.await
.unwrap();
assert!(matches!(block["tag"].as_ref(), Decoded::Null(7)));
}
#[tokio::test]
async fn oversized_metadata_is_returned_without_retention() {
let strategy = CacheStrategy::EnableAll(Arc::new(
+268 -264
View File
@@ -15,97 +15,257 @@
use std::collections::BTreeMap;
use std::sync::Arc;
use common_cache::Cache;
use common_cache::metrics::CacheMetrics;
use index::bloom_filter::applier::InListPredicate;
use index::inverted_index::search::predicate::{Predicate, RangePredicate};
use index::target::IndexTarget;
use moka::notification::RemovalCause;
use moka::sync::Cache;
use prometheus::IntGauge;
use snafu::IntoError;
use store_api::storage::FileId;
use crate::metrics::{CACHE_BYTES, CACHE_EVICTION, CACHE_HIT, CACHE_MISS};
use crate::error::{Error, Result, ScanSeriesSnafu};
use crate::metrics::{CACHE_BYTES, CACHE_EVICTION, CACHE_HIT, CACHE_MISS, cache_loading_metrics};
use crate::series_index::columnar::reader::{Decoded, DecodedProjection};
use crate::sst::index::fulltext_index::applier::builder::{
FulltextLike, FulltextQuery, FulltextRequest, FulltextTerm,
};
use crate::sst::parquet::row_selection::RowGroupSelection;
const INDEX_RESULT_TYPE: &str = "index_result";
const SERIES_COLUMN_TYPE: &str = "index_result_series_column";
const SERIES_BLOCK_TYPE: &str = "index_result_series_block";
/// Cache for storing index query results.
///
/// The `RowGroupSelection` is a collection of row groups that match the predicate.
///
/// Row groups can be partially searched. Row groups that not contained in `RowGroupSelection` are not searched.
/// User can retrieve the partial results and handle uncontained row groups required by the predicate subsequently.
/// The location of an immutable payload within a published series index.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) struct SeriesIndexKey {
pub(crate) generation: FileId,
pub(crate) part_id: u32,
pub(crate) offset: u64,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum IndexResultKey {
Parquet(PredicateKey, FileId),
SeriesColumn(SeriesIndexKey),
SeriesBlock(SeriesIndexKey),
}
impl IndexResultKey {
fn metric_type(&self) -> &'static str {
match self {
Self::Parquet(..) => INDEX_RESULT_TYPE,
Self::SeriesColumn(_) => SERIES_COLUMN_TYPE,
Self::SeriesBlock(_) => SERIES_BLOCK_TYPE,
}
}
}
enum IndexResultValue {
Parquet(Arc<RowGroupSelection>),
SeriesColumn(Arc<Decoded>),
SeriesBlock(Arc<DecodedProjection>),
}
struct IndexResultEntry {
value: IndexResultValue,
weight: u32,
bytes: IntGauge,
}
impl IndexResultEntry {
fn new(key: &IndexResultKey, value: IndexResultValue, weight: u32) -> Arc<Self> {
let bytes = CACHE_BYTES.with_label_values(&[key.metric_type()]);
bytes.add(weight.into());
Arc::new(Self {
value,
weight,
bytes,
})
}
}
impl Drop for IndexResultEntry {
fn drop(&mut self) {
// Each cache entry owns its charge, including during replacement or cancelled insertion.
self.bytes.sub(self.weight.into());
}
}
const ENTRY_OVERHEAD: usize =
size_of::<IndexResultKey>() + size_of::<IndexResultEntry>() + 2 * size_of::<usize>();
enum Uncached<T> {
Oversized(Arc<T>),
Error(Arc<Error>),
}
/// A shared cache for Parquet predicate results and immutable decoded series index payloads.
pub struct IndexResultCache {
cache: Cache<(PredicateKey, FileId), Arc<RowGroupSelection>>,
cache: Cache<IndexResultKey, Arc<IndexResultEntry>>,
series_column_metrics: Arc<CacheMetrics>,
series_block_metrics: Arc<CacheMetrics>,
}
impl IndexResultCache {
/// Creates a new cache with the given capacity.
pub fn new(capacity: u64) -> Self {
fn to_str(cause: RemovalCause) -> &'static str {
match cause {
RemovalCause::Expired => "expired",
RemovalCause::Explicit => "explicit",
RemovalCause::Replaced => "replaced",
RemovalCause::Size => "size",
}
}
let cache = Cache::builder()
.max_capacity(capacity)
.weigher(Self::index_result_cache_weight)
.eviction_listener(|k, v, cause| {
let size = Self::index_result_cache_weight(&k, &v);
CACHE_BYTES
.with_label_values(&[INDEX_RESULT_TYPE])
.sub(size.into());
let cache = Cache::new(
INDEX_RESULT_TYPE,
capacity,
|_, entry: &Arc<IndexResultEntry>| entry.weight,
|key: Arc<IndexResultKey>, _, cause| {
CACHE_EVICTION
.with_label_values(&[INDEX_RESULT_TYPE, to_str(cause)])
.with_label_values(&[key.metric_type(), cause.as_str()])
.inc();
})
.support_invalidation_closures()
.build();
Self { cache }
}
/// Puts a query result into the cache.
///
/// Allow user to put a partial result (not containing all row groups) into the cache.
pub fn put(&self, key: PredicateKey, file_id: FileId, result: Arc<RowGroupSelection>) {
let key = (key, file_id);
let size = Self::index_result_cache_weight(&key, &result);
CACHE_BYTES
.with_label_values(&[INDEX_RESULT_TYPE])
.add(size.into());
self.cache.insert(key, result);
}
/// Gets a query result from the cache.
///
/// Note: the returned `RowGroupSelection` only contains the row groups that are searched.
/// Caller should handle the uncontained row groups required by the predicate subsequently.
pub fn get(&self, key: &PredicateKey, file_id: FileId) -> Option<Arc<RowGroupSelection>> {
let res = self.cache.get(&(key.clone(), file_id));
if res.is_some() {
CACHE_HIT.with_label_values(&[INDEX_RESULT_TYPE]).inc();
} else {
CACHE_MISS.with_label_values(&[INDEX_RESULT_TYPE]).inc()
},
);
Self {
cache,
series_column_metrics: cache_loading_metrics(SERIES_COLUMN_TYPE),
series_block_metrics: cache_loading_metrics(SERIES_BLOCK_TYPE),
}
res
}
/// Calculates the memory usage of a cache entry.
fn index_result_cache_weight(k: &(PredicateKey, FileId), v: &Arc<RowGroupSelection>) -> u32 {
k.0.mem_usage() as u32 + v.mem_usage() as u32
/// Puts a query result into the cache. It may cover only some row groups.
pub async fn put(
&self,
predicate: PredicateKey,
file_id: FileId,
result: Arc<RowGroupSelection>,
) {
let retained = ENTRY_OVERHEAD
.saturating_add(predicate.mem_usage())
.saturating_add(result.mem_usage());
let Ok(weight) = u32::try_from(retained) else {
return;
};
let key = IndexResultKey::Parquet(predicate, file_id);
let entry = IndexResultEntry::new(&key, IndexResultValue::Parquet(result), weight);
self.cache.insert(key, entry).await;
}
/// Removes cached results for the given file.
/// Gets a query result. Callers must handle any row groups it does not cover.
pub async fn get(&self, key: &PredicateKey, file_id: FileId) -> Option<Arc<RowGroupSelection>> {
let entry = self
.lookup(&IndexResultKey::Parquet(key.clone(), file_id))
.await?;
let IndexResultValue::Parquet(result) = &entry.value else {
unreachable!("Parquet key contains a series index payload");
};
Some(result.clone())
}
/// Loads a decoded column in the calling scan and shares it with concurrent readers.
pub(crate) async fn load_series_column(
&self,
key: SeriesIndexKey,
loader: impl Future<Output = Result<Decoded>> + Send,
) -> Result<Arc<Decoded>> {
self.load_series(
IndexResultKey::SeriesColumn(key),
&self.series_column_metrics,
Decoded::retained_size,
IndexResultValue::SeriesColumn,
|value| match value {
IndexResultValue::SeriesColumn(column) => column.clone(),
_ => unreachable!("series column key contains a different payload"),
},
loader,
)
.await
}
/// Loads a predicate-independent block projection in the calling scan.
pub(crate) async fn load_series_block(
&self,
key: SeriesIndexKey,
loader: impl Future<Output = Result<DecodedProjection>> + Send,
) -> Result<Arc<DecodedProjection>> {
self.load_series(
IndexResultKey::SeriesBlock(key),
&self.series_block_metrics,
|columns: &DecodedProjection| {
// The block can outlive separately cached entries for these columns.
columns.capacity() * size_of::<(String, Arc<Decoded>)>()
+ columns
.iter()
.map(|(name, column)| {
name.capacity() + column.retained_size() + 2 * size_of::<usize>()
})
.sum::<usize>()
},
IndexResultValue::SeriesBlock,
|value| match value {
IndexResultValue::SeriesBlock(block) => block.clone(),
_ => unreachable!("series block key contains a different payload"),
},
loader,
)
.await
}
/// Removes cached Parquet results for the given file.
pub fn invalidate_file(&self, file_id: FileId) {
self.cache
.invalidate_entries_if(move |(_, cached_file_id), _| *cached_file_id == file_id)
.invalidate_if(move |key, _| {
matches!(key, IndexResultKey::Parquet(_, cached) if *cached == file_id)
})
.expect("cache should support invalidation closures");
}
async fn lookup(&self, key: &IndexResultKey) -> Option<Arc<IndexResultEntry>> {
let result = self.cache.get(key).await;
if result.is_some() {
CACHE_HIT.with_label_values(&[key.metric_type()]).inc();
} else {
CACHE_MISS.with_label_values(&[key.metric_type()]).inc();
}
result
}
async fn load_series<T: Send + Sync + 'static>(
&self,
key: IndexResultKey,
metrics: &CacheMetrics,
retained_size: fn(&T) -> usize,
wrap: fn(Arc<T>) -> IndexResultValue,
extract: fn(&IndexResultValue) -> Arc<T>,
loader: impl Future<Output = Result<T>> + Send,
) -> Result<Arc<T>> {
if let Some(entry) = self.lookup(&key).await {
return Ok(extract(&entry.value));
}
let result = self
.cache
.try_get_with_unobserved(key.clone(), async {
let value = Arc::new(
metrics
.loads
.observe(loader)
.await
.map_err(|error| Uncached::Error(Arc::new(error)))?,
);
let retained = retained_size(&value).saturating_add(ENTRY_OVERHEAD);
if let Ok(weight) = u32::try_from(retained)
&& u64::from(weight) <= self.cache.capacity()
{
Ok(IndexResultEntry::new(&key, wrap(value), weight))
} else {
Err(Uncached::Oversized(value))
}
})
.await;
match result {
Ok(entry) => Ok(extract(&entry.value)),
Err(outcome) => match outcome.as_ref() {
Uncached::Oversized(value) => Ok(value.clone()),
Uncached::Error(error) => Err(ScanSeriesSnafu.into_error(error.clone())),
},
}
}
}
/// Key for different types of index predicates.
@@ -283,22 +443,13 @@ impl MinMaxKey {
}
#[cfg(test)]
#[allow(clippy::single_range_in_vec_init)]
mod tests {
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use index::bloom_filter::applier::InListPredicate as BloomInListPredicate;
use index::inverted_index::search::predicate::{Predicate, Range, RangePredicate};
use index::inverted_index::search::predicate::Range;
use super::*;
use crate::sst::index::fulltext_index::applier::builder::{
FulltextQuery, FulltextRequest, FulltextTerm,
};
use crate::sst::parquet::row_selection::RowGroupSelection;
#[test]
fn test_inverted_cache_separates_json_paths() {
#[tokio::test]
async fn test_inverted_cache_separates_json_paths() {
let key = |path: &str| {
PredicateKey::new_inverted(Arc::new(BTreeMap::from([(
IndexTarget::new_json_path(1, vec![path.into()]).unwrap(),
@@ -314,207 +465,60 @@ mod tests {
let b = key("b");
let cache = IndexResultCache::new(10000);
let file = FileId::random();
cache.put(a.clone(), file, Arc::new(RowGroupSelection::new(10, 10)));
assert!(cache.get(&a, file).is_some());
assert!(cache.get(&b, file).is_none());
}
#[test]
fn test_cache_basic_operations() {
let cache = IndexResultCache::new(1000);
let file_id = FileId::random();
// Create a test key and value
let predicates = BTreeMap::new();
let key = PredicateKey::new_fulltext(Arc::new(predicates));
let selection = Arc::new(RowGroupSelection::from_row_ids(
[1, 2, 3].into_iter().collect(),
1,
10,
));
// Test put and get
cache.put(key.clone(), file_id, selection.clone());
let retrieved = cache.get(&key, file_id);
assert!(retrieved.is_some());
assert_eq!(
retrieved.unwrap().as_ref().row_count(),
selection.as_ref().row_count()
);
// Test get non-existent key
let non_existent_file_id = FileId::random();
assert!(cache.get(&key, non_existent_file_id).is_none());
cache
.put(a.clone(), file, Arc::new(RowGroupSelection::new(10, 10)))
.await;
assert!(cache.get(&a, file).await.is_some());
assert!(cache.get(&b, file).await.is_none());
}
#[test]
fn test_minmax_key_should_distinguish_schema_version_and_skip_fields() {
let exprs = Arc::new(vec!["col > 1".to_string()]);
let key1 = PredicateKey::new_minmax(exprs.clone(), 1, false);
let key2 = PredicateKey::new_minmax(exprs.clone(), 2, false);
assert_ne!(key1, key2);
let key3 = PredicateKey::new_minmax(exprs, 1, true);
assert_ne!(key1, key3);
let key = PredicateKey::new_minmax(exprs.clone(), 1, false);
assert_ne!(key, PredicateKey::new_minmax(exprs.clone(), 1, true));
assert_ne!(key, PredicateKey::new_minmax(exprs, 2, false));
}
#[test]
fn test_cache_capacity_limit() {
// Create a cache with small capacity (100 bytes)
let cache = IndexResultCache::new(100);
let file_id1 = FileId::random();
let file_id2 = FileId::random();
// Create two large keys that will exceed capacity
let mut predicates1 = BTreeMap::new();
let request1 = FulltextRequest {
queries: vec![
FulltextQuery(
"test query 1 with a very long string to ensure large weight".to_string(),
),
FulltextQuery("another long query string".to_string()),
],
terms: vec![],
likes: vec![],
#[tokio::test]
async fn test_cache_capacity_limit() {
let cache = IndexResultCache::new((ENTRY_OVERHEAD + 256) as u64);
let file = FileId::random();
let predicate = PredicateKey::new_minmax(Arc::new(vec!["tag = 'foo'".into()]), 1, false);
let selection = Arc::new(RowGroupSelection::new(10, 10));
let block_key = SeriesIndexKey {
generation: file,
part_id: 0,
offset: 0,
};
predicates1.insert(IndexTarget::ColumnId(1), request1);
let key1 = PredicateKey::new_fulltext(Arc::new(predicates1));
let selection1 = Arc::new(RowGroupSelection::default());
let block = IndexResultKey::SeriesBlock(block_key);
let mut predicates2 = BTreeMap::new();
let request2 = FulltextRequest {
queries: vec![
FulltextQuery(
"test query 2 with a very long string to ensure large weight".to_string(),
),
FulltextQuery("another long query string".to_string()),
],
terms: vec![],
likes: vec![],
};
predicates2.insert(IndexTarget::ColumnId(1), request2);
let key2 = PredicateKey::new_fulltext(Arc::new(predicates2));
let selection2 = Arc::new(RowGroupSelection::default());
let parquet_only = IndexResultCache::new(cache.cache.capacity());
parquet_only
.put(predicate.clone(), file, selection.clone())
.await;
parquet_only.cache.run_pending_tasks().await;
assert!(parquet_only.get(&predicate, file).await.is_some());
// Calculate weights
let weight1 =
IndexResultCache::index_result_cache_weight(&(key1.clone(), file_id1), &selection1);
let weight2 =
IndexResultCache::index_result_cache_weight(&(key2.clone(), file_id2), &selection2);
assert!(weight1 > 100);
assert!(weight2 > 100);
cache
.load_series_block(block_key, async {
Ok(DecodedProjection::from([(
"tag".into(),
Arc::new(Decoded::Null(10)),
)]))
})
.await
.unwrap();
cache.cache.run_pending_tasks().await;
assert!(cache.cache.get(&block).await.is_some());
// Put first key-value pair
cache.put(key1.clone(), file_id1, selection1.clone());
// Verify first key is in cache
let retrieved1 = cache.get(&key1, file_id1);
assert!(retrieved1.is_some());
assert_eq!(
retrieved1.unwrap().as_ref().row_count(),
selection1.as_ref().row_count()
);
// Put second key-value pair, which should trigger eviction
cache.put(key2.clone(), file_id2, selection2.clone());
// Verify second key is in cache
let retrieved2 = cache.get(&key2, file_id2);
assert!(retrieved2.is_some());
assert_eq!(
retrieved2.unwrap().as_ref().row_count(),
selection2.as_ref().row_count()
);
// Verify first key was evicted
cache.cache.run_pending_tasks();
let retrieved1_after_eviction = cache.get(&key1, file_id1);
assert!(
retrieved1_after_eviction.is_none(),
"First key should have been evicted"
);
}
#[test]
fn test_index_result_cache_weight() {
let file_id = FileId::random();
// Test empty values
let empty_predicates = BTreeMap::new();
let empty_key = PredicateKey::new_fulltext(Arc::new(empty_predicates));
let empty_selection = Arc::new(RowGroupSelection::default());
let empty_weight = IndexResultCache::index_result_cache_weight(
&(empty_key.clone(), file_id),
&empty_selection,
);
assert_eq!(empty_weight, 0);
assert_eq!(
empty_weight,
empty_key.mem_usage() as u32 + empty_selection.mem_usage() as u32
);
// Test 1: FulltextIndexKey
let mut predicates1 = BTreeMap::new();
let request1 = FulltextRequest {
queries: vec![FulltextQuery("test query".to_string())],
terms: vec![FulltextTerm {
col_lowered: false,
term: "test term".to_string(),
}],
likes: vec![],
};
predicates1.insert(IndexTarget::ColumnId(1), request1);
let key1 = PredicateKey::new_fulltext(Arc::new(predicates1));
let selection1 = Arc::new(RowGroupSelection::new(100, 250));
let weight1 =
IndexResultCache::index_result_cache_weight(&(key1.clone(), file_id), &selection1);
assert!(weight1 > 0);
assert_eq!(
weight1,
key1.mem_usage() as u32 + selection1.mem_usage() as u32
);
// Test 2: BloomFilterKey
let mut predicates2 = BTreeMap::new();
let predicate2 = BloomInListPredicate {
list: BTreeSet::from([b"test1".to_vec(), b"test2".to_vec()]),
};
predicates2.insert(IndexTarget::ColumnId(1), vec![predicate2]);
let key2 = PredicateKey::new_bloom(Arc::new(predicates2));
let selection2 = Arc::new(RowGroupSelection::from_row_ids(
[1, 2, 3].into_iter().collect(),
100,
1,
));
let weight2 =
IndexResultCache::index_result_cache_weight(&(key2.clone(), file_id), &selection2);
assert!(weight2 > 0);
assert_eq!(
weight2,
key2.mem_usage() as u32 + selection2.mem_usage() as u32
);
// Test 3: InvertedIndexKey
let mut predicates3 = BTreeMap::new();
let predicate3 = Predicate::Range(RangePredicate {
range: Range {
lower: None,
upper: None,
},
});
predicates3.insert(IndexTarget::ColumnId(1), vec![predicate3]);
let key3 = PredicateKey::new_inverted(Arc::new(predicates3));
let selection3 = Arc::new(RowGroupSelection::from_row_ranges(
vec![(0, vec![5..15])],
20,
));
let weight3 =
IndexResultCache::index_result_cache_weight(&(key3.clone(), file_id), &selection3);
assert!(weight3 > 0);
assert_eq!(
weight3,
key3.mem_usage() as u32 + selection3.mem_usage() as u32
cache.put(predicate.clone(), file, selection).await;
cache.cache.run_pending_tasks().await;
assert_eq!(cache.cache.entry_count(), 1);
assert!(cache.cache.weighted_size() <= cache.cache.capacity());
assert_ne!(
cache.get(&predicate, file).await.is_some(),
cache.cache.get(&block).await.is_some()
);
}
}
+47 -4
View File
@@ -350,7 +350,7 @@ impl ColumnarPreparedSource {
};
let mut retained_rows = 0_usize;
let mut candidates = BTreeMap::<ExactSeriesKey, Candidate>::new();
while let Some((reader, window)) = series.readers.pop_front() {
let prepare_reader = |reader: &dyn FormatReader| -> Result<_> {
let started = Instant::now();
let schema = reader.schema();
format::validate_series_schema(&schema, metadata)?;
@@ -398,11 +398,53 @@ impl ColumnarPreparedSource {
.map_err(|error| invalid(error.to_string()))?,
);
}
preparation_metrics.add_elapsed("columnar_prepare_compile", started.elapsed());
let mut batches = reader.read(request)?;
let elapsed = started.elapsed();
Ok((tags, filters, reader.read(request)?, elapsed))
};
let mut prefetched = None;
while let Some((reader, window)) = series.readers.pop_front() {
let ((tags, filters, mut batches, elapsed), mut head) = match prefetched.take() {
Some((prepared, task)) => (prepared?, task),
None => {
let (tags, filters, stream, elapsed) = prepare_reader(reader.as_ref())?;
((tags, filters, Some(stream), elapsed), None)
}
};
preparation_metrics.add_elapsed("columnar_prepare_compile", elapsed);
if window.is_some()
&& let Some((next, Some(_))) = series.readers.front()
{
let (prepared, task) = match prepare_reader(next.as_ref()) {
Ok((next_tags, next_filters, mut next_batches, elapsed)) => {
// The worker reads the next index's first batch while this index is
// consumed. It retains only one prefetched batch.
let task = common_runtime::spawn_query(async move {
let batch = next_batches.try_next().await;
(batch, next_batches)
});
let abort = crate::read::stream::AbortOnDrop(task.abort_handle());
(
Ok((next_tags, next_filters, None, elapsed)),
Some((task, abort)),
)
}
Err(error) => (Err(error), None),
};
prefetched = Some((prepared, task));
}
loop {
let timer = preparation_metrics.timer("columnar_prepare_discovery_wall");
let batch = batches.try_next().await;
let batch = if let Some((task, _abort)) = head.take() {
let (batch, stream) = task.await.context(crate::error::JoinSnafu)?;
batches = Some(stream);
batch
} else {
batches
.as_mut()
.ok_or_else(|| invalid("missing prepared series stream"))?
.try_next()
.await
};
drop(timer);
let batch = match (batch, window) {
(Ok(batch), _) => batch,
@@ -412,6 +454,7 @@ impl ColumnarPreparedSource {
?window,
"Series index read failed, discovering keys from samples"
);
prefetched = None;
series.fallback_to_samples(window, &samples, metadata, &scan_pool)?;
break;
}
+1 -1
View File
@@ -178,7 +178,7 @@ pub(crate) fn spawn_compact_stream(
}
/// Aborts a task when its consumer is dropped before the end.
struct AbortOnDrop(AbortHandle);
pub(crate) struct AbortOnDrop(pub(crate) AbortHandle);
impl Drop for AbortOnDrop {
fn drop(&mut self) {
+229 -27
View File
@@ -498,13 +498,31 @@ async fn load_metadata_page(
}
#[derive(Debug)]
enum Decoded {
pub(crate) enum Decoded {
Integers(Vec<u64>),
Strings(Dictionary),
Table(u32, usize),
Null(usize),
}
impl Decoded {
pub(crate) fn retained_size(&self) -> usize {
let data = match self {
Self::Integers(values) => values.capacity() * size_of::<u64>(),
Self::Strings(dictionary) => {
dictionary.codes.capacity() * size_of::<u32>()
+ dictionary.values.capacity() * size_of::<Option<String>>()
+ dictionary
.values
.iter()
.flatten()
.map(String::capacity)
.sum::<usize>()
}
Self::Table(..) | Self::Null(_) => 0,
};
size_of::<Self>() + data
}
fn value_bytes(&self, index: usize) -> usize {
match self {
Self::Integers(_) => 8,
@@ -560,18 +578,25 @@ async fn load_column_chunk(
block: &Block,
metrics: &mut ColumnarReadMetrics,
) -> Result<Decoded> {
let integer = column.name == TSID_COLUMN || column.name == ROW_COUNT_COLUMN;
let expected = if integer {
codec::INTEGER
} else {
codec::DICTIONARY
};
if column.payload.encoding != expected {
return Err(unsupported(format!(
"series column encoding {} for {}",
column.payload.encoding, column.name
)));
}
decode_column_chunk(
area,
column,
block.rows as usize,
block.first,
block.last,
metrics,
)
.await
}
async fn decode_column_chunk(
area: &PartArea,
column: &Column,
rows: usize,
first: u64,
last: u64,
metrics: &mut ColumnarReadMetrics,
) -> Result<Decoded> {
let timer = metrics.timer("columnar_series_fetch_wall");
let range = column.payload.offset..column.payload.end()?;
let (bytes, reads, fetched) = if let Some((mut bytes, stats)) = area
@@ -591,12 +616,33 @@ async fn load_column_chunk(
drop(timer);
*metrics.counts.entry("series_column_reads").or_default() += reads;
*metrics.bytes.entry("series_payload_fetched").or_default() += fetched;
let started = Instant::now();
let rows = block.rows as usize;
let first = block.first;
let last = block.last;
let bytes = column.payload.unpack(&bytes)?;
let result = if integer {
let timer = metrics.timer("columnar_series_decode");
let decoded = decode_column_bytes(column, rows, first, last, &bytes);
drop(timer);
decoded
}
fn decode_column_bytes(
column: &Column,
rows: usize,
first: u64,
last: u64,
bytes: &[u8],
) -> Result<Decoded> {
let integer = column.name == TSID_COLUMN || column.name == ROW_COUNT_COLUMN;
let expected = if integer {
codec::INTEGER
} else {
codec::DICTIONARY
};
if column.payload.encoding != expected {
return Err(unsupported(format!(
"series column encoding {} for {}",
column.payload.encoding, column.name
)));
}
let bytes = column.payload.unpack(bytes)?;
if integer {
let values = codec::decode_integers(&bytes, rows)?;
if column.name == TSID_COLUMN {
// Rows are ordered by exact key, so their coarse TSIDs are non-decreasing:
@@ -633,9 +679,7 @@ async fn load_column_chunk(
"series dictionary bounds mismatch",
)?;
Ok(Decoded::Strings(dictionary))
};
metrics.add_elapsed("columnar_series_decode", started.elapsed());
result
}
}
async fn read_integers(
@@ -665,6 +709,161 @@ async fn get_column(
}
}
pub(crate) type DecodedProjection = HashMap<String, Arc<Decoded>>;
async fn get_query_column(
area: &PartArea,
block: &Block,
name: &str,
metrics: &mut ColumnarReadMetrics,
) -> Result<Arc<Decoded>> {
if let Some(column) = block.columns.iter().find(|column| column.name == name)
&& let Some((cache, key)) = area.series_index(column.payload.offset)
{
let (rows, first, last) = (block.rows as usize, block.first, block.last);
return cache
.load_series_column(
key,
decode_column_chunk(area, column, rows, first, last, metrics),
)
.await;
}
get_column(area, block, name, metrics).await.map(Arc::new)
}
const SERIES_PROJECTION_CHUNKS: usize = 64;
const SERIES_PROJECTION_BYTES: u64 = 512 * 1024;
/// Fetches the projected chunks of one selected block together. Filter columns are
/// still evaluated before this I/O, so a nonmatching block reads no projected tags.
async fn prefetch_projection(
area: &PartArea,
block: &Block,
projection: &[String],
decoded: &mut HashMap<String, Arc<Decoded>>,
metrics: &mut ColumnarReadMetrics,
) -> Result<()> {
let mut columns = Vec::new();
let mut ranges = Vec::new();
let mut bytes = 0_u64;
for column in &block.columns {
if decoded.contains_key(&column.name)
|| !projection.contains(&column.name)
|| column.name == TABLE_ID_COLUMN
{
continue;
}
let range = column.payload.offset..column.payload.end()?;
bytes += range.end - range.start;
if bytes > SERIES_PROJECTION_BYTES || columns.len() == SERIES_PROJECTION_CHUNKS {
break;
}
columns.push(column);
ranges.push(range);
}
if columns.len() <= 1 {
return Ok(());
}
let timer = metrics.timer("columnar_series_fetch_wall");
let (payloads, read_count, fetched) = match area.cached_ranges(&ranges, None).await? {
Some((payloads, stats)) => (
payloads,
u64::from(stats.loaded_bytes > 0),
stats.loaded_bytes,
),
None => {
let payloads = area.reader.fetch(ranges).await.context(OpenDalSnafu)?;
let fetched = payloads.iter().map(|bytes| bytes.len() as u64).sum();
(payloads, 1, fetched)
}
};
drop(timer);
require(
payloads.len() == columns.len(),
"series projection range count mismatch",
)?;
*metrics.counts.entry("series_column_reads").or_default() += read_count;
*metrics.bytes.entry("series_payload_fetched").or_default() += fetched;
*metrics
.counts
.entry("series_projection_columns")
.or_default() += columns.len() as u64;
let timer = metrics.timer("columnar_series_decode");
for (column, payload) in columns.into_iter().zip(payloads) {
let decoded_column = decode_column_bytes(
column,
block.rows as usize,
block.first,
block.last,
&payload,
)?;
decoded.insert(column.name.clone(), Arc::new(decoded_column));
}
drop(timer);
Ok(())
}
/// A complete projection is reusable across predicates because it contains the
/// original immutable dictionaries and codes, before row selection.
async fn cached_block_projection(
area: &PartArea,
block: &Block,
projection: &[String],
decoded: &mut HashMap<String, Arc<Decoded>>,
metrics: &mut ColumnarReadMetrics,
) -> Result<bool> {
// Discovery projects the TSID and all tags, leaving row counts to their
// own cache entry. This fixed set is independent of the caller's filters.
let columns = || {
block
.columns
.iter()
.filter(|column| column.name != ROW_COUNT_COLUMN && column.name != TABLE_ID_COLUMN)
};
let Some(first) = columns().next() else {
return Ok(false);
};
let count = columns().count();
if !(2..=SERIES_PROJECTION_CHUNKS).contains(&count)
|| columns().map(|c| u64::from(c.payload.stored)).sum::<u64>() > SERIES_PROJECTION_BYTES
|| columns().map(|c| u64::from(c.payload.decoded)).sum::<u64>() > 4 * 1024 * 1024
|| !columns().all(|column| projection.contains(&column.name))
{
return Ok(false);
}
let Some((cache, key)) = area.series_index(first.payload.offset) else {
return Ok(false);
};
let loaded = cache
.load_series_block(key, async {
let mut seeded: DecodedProjection = columns()
.filter_map(|column| {
decoded
.get(&column.name)
.map(|value| (column.name.clone(), value.clone()))
})
.collect();
let projection = columns()
.map(|column| column.name.clone())
.collect::<Vec<_>>();
prefetch_projection(area, block, &projection, &mut seeded, metrics).await?;
for column in columns() {
if !seeded.contains_key(&column.name) {
let value = load_column_chunk(area, column, block, metrics).await?;
seeded.insert(column.name.clone(), Arc::new(value));
}
}
Ok(seeded)
})
.await?;
decoded.extend(
loaded
.iter()
.map(|(name, values)| (name.clone(), values.clone())),
);
Ok(true)
}
async fn read_block(
area: &PartArea,
block: &Block,
@@ -675,8 +874,8 @@ async fn read_block(
let mut decoded = HashMap::new();
let mut selected: Vec<_> = (0..block.rows as usize).collect();
if let Some(ids) = &request.ids {
let column = get_column(area, block, TSID_COLUMN, metrics).await?;
if let Decoded::Integers(values) = &column {
let column = get_query_column(area, block, TSID_COLUMN, metrics).await?;
if let Decoded::Integers(values) = column.as_ref() {
selected.retain(|&i| {
ids.contains(&MetricSeriesId {
table_id: block.table_id,
@@ -684,7 +883,7 @@ async fn read_block(
})
});
}
decoded.insert(TSID_COLUMN.to_owned(), Arc::new(column));
decoded.insert(TSID_COLUMN.to_owned(), column);
}
// A complete block mask can be reused without hashing an arbitrary ID selection.
let prefilter = if request.ids.is_none()
@@ -713,7 +912,7 @@ async fn read_block(
*metrics.counts.entry("series_filter_columns").or_default() += 1;
decoded.insert(
name.to_owned(),
Arc::new(get_column(area, block, name, metrics).await?),
get_query_column(area, block, name, metrics).await?,
);
}
let started = Instant::now();
@@ -735,6 +934,9 @@ async fn read_block(
if selected.is_empty() {
return Ok(None);
}
let used =
cached_block_projection(area, block, &request.projection, &mut decoded, metrics).await?;
*metrics.counts.entry("series_block_projection").or_default() += u64::from(used);
let mut columns = Vec::with_capacity(request.projection.len());
for name in &request.projection {
if !decoded.contains_key(name) {
@@ -744,7 +946,7 @@ async fn read_block(
.or_default() += 1;
decoded.insert(
name.clone(),
Arc::new(get_column(area, block, name, metrics).await?),
get_query_column(area, block, name, metrics).await?,
);
}
columns.push(
+3
View File
@@ -2409,6 +2409,7 @@ mod tests {
.unwrap();
let cached = index_result_cache
.get(&plan.predicate_key, handle.file_id().file_id())
.await
.unwrap();
// inverted index will search all row groups
assert!(cached.contains_row_group(0));
@@ -2465,6 +2466,7 @@ mod tests {
let bloom_predicate_key = PredicateKey::new_bloom(bloom_predicates);
let cached = index_result_cache
.get(&bloom_predicate_key, handle.file_id().file_id())
.await
.unwrap();
assert!(cached.contains_row_group(2));
assert!(cached.contains_row_group(3));
@@ -2538,6 +2540,7 @@ mod tests {
let bloom_predicate_key = PredicateKey::new_bloom(bloom_predicates);
let cached = index_result_cache
.get(&bloom_predicate_key, handle.file_id().file_id())
.await
.unwrap();
assert!(cached.contains_row_group(0));
assert!(cached.contains_row_group(1));
+51 -41
View File
@@ -924,14 +924,16 @@ impl ParquetReaderBuilder {
// Compute skip_fields once for all pruning operations
let skip_fields = self.pre_filter_mode.skip_fields();
let mut output = self.row_groups_by_minmax(
read_format,
parquet_meta,
row_group_size,
num_rows as usize,
metrics,
skip_fields,
);
let mut output = self
.row_groups_by_minmax(
read_format,
parquet_meta,
row_group_size,
num_rows as usize,
metrics,
skip_fields,
)
.await;
if output.is_empty() {
return output;
}
@@ -1018,10 +1020,7 @@ impl ParquetReaderBuilder {
};
let predicate_key = PredicateKey::new_fulltext(requests.clone());
// Fast path: return early if the result is in the cache.
let cached = self
.cache_strategy
.index_result_cache()
.and_then(|cache| cache.get(&predicate_key, self.file_handle.file_id().file_id()));
let cached = self.get_cached_index_result(&predicate_key).await;
if let Some(result) = cached.as_ref()
&& all_required_row_groups_searched(output, result)
{
@@ -1060,7 +1059,8 @@ impl ParquetReaderBuilder {
output,
metrics,
INDEX_TYPE_FULLTEXT,
);
)
.await;
pruned = true;
}
pruned
@@ -1102,10 +1102,7 @@ impl ParquetReaderBuilder {
};
// Fast path: return early if the result is in the cache.
let cached = self.cache_strategy.index_result_cache().and_then(|cache| {
let file_id = self.file_handle.file_id().file_id();
cache.get(&plan.predicate_key, file_id)
});
let cached = self.get_cached_index_result(&plan.predicate_key).await;
if let Some(result) = cached.as_ref()
&& all_required_row_groups_searched(output, result)
@@ -1160,7 +1157,8 @@ impl ParquetReaderBuilder {
output,
metrics,
INDEX_TYPE_INVERTED,
);
)
.await;
pruned = true;
}
pruned
@@ -1194,10 +1192,7 @@ impl ParquetReaderBuilder {
};
let predicate_key = PredicateKey::new_bloom(compatible_predicates.clone());
// Fast path: return early if the result is in the cache.
let cached = self.cache_strategy.index_result_cache().and_then(|cache| {
let file_id = self.file_handle.file_id().file_id();
cache.get(&predicate_key, file_id)
});
let cached = self.get_cached_index_result(&predicate_key).await;
if let Some(result) = cached.as_ref()
&& all_required_row_groups_searched(output, result)
{
@@ -1252,7 +1247,8 @@ impl ParquetReaderBuilder {
output,
metrics,
INDEX_TYPE_BLOOM,
);
)
.await;
pruned = true;
}
pruned
@@ -1285,10 +1281,7 @@ impl ParquetReaderBuilder {
};
let predicate_key = PredicateKey::new_fulltext(requests.clone());
// Fast path: return early if the result is in the cache.
let cached = self
.cache_strategy
.index_result_cache()
.and_then(|cache| cache.get(&predicate_key, self.file_handle.file_id().file_id()));
let cached = self.get_cached_index_result(&predicate_key).await;
if let Some(result) = cached.as_ref()
&& all_required_row_groups_searched(output, result)
{
@@ -1344,14 +1337,15 @@ impl ParquetReaderBuilder {
output,
metrics,
INDEX_TYPE_FULLTEXT,
);
)
.await;
pruned = true;
}
pruned
}
/// Computes row groups selection after min-max pruning.
fn row_groups_by_minmax(
async fn row_groups_by_minmax(
&self,
read_format: &FlatReadFormat,
parquet_meta: &ParquetMetaData,
@@ -1393,7 +1387,7 @@ impl ParquetReaderBuilder {
if let Some(index_result_cache) = index_result_cache
&& let Some(predicate_key) = cached_minmax_key.as_ref()
{
if let Some(result) = index_result_cache.get(predicate_key, file_id) {
if let Some(result) = index_result_cache.get(predicate_key, file_id).await {
metrics.minmax_cache_hit += 1;
let num_row_groups = parquet_meta.num_row_groups();
metrics.rg_minmax_filtered +=
@@ -1437,13 +1431,25 @@ impl ParquetReaderBuilder {
if let Some(index_result_cache) = index_result_cache
&& let Some(predicate_key) = cached_minmax_key
{
index_result_cache.put(predicate_key, file_id, Arc::new(output.clone()));
index_result_cache
.put(predicate_key, file_id, Arc::new(output.clone()))
.await;
}
output
}
fn apply_index_result_and_update_cache(
async fn get_cached_index_result(
&self,
predicate_key: &PredicateKey,
) -> Option<Arc<RowGroupSelection>> {
self.cache_strategy
.index_result_cache()?
.get(predicate_key, self.file_handle.file_id().file_id())
.await
}
async fn apply_index_result_and_update_cache(
&self,
predicate_key: &PredicateKey,
file_id: FileId,
@@ -1455,7 +1461,9 @@ impl ParquetReaderBuilder {
apply_selection_and_update_metrics(output, &result, metrics, index_type);
if let Some(index_result_cache) = &self.cache_strategy.index_result_cache() {
index_result_cache.put(predicate_key.clone(), file_id, Arc::new(result));
index_result_cache
.put(predicate_key.clone(), file_id, Arc::new(result))
.await;
}
}
}
@@ -4034,14 +4042,16 @@ mod tests {
let row_group_size = parquet_meta.row_group(0).num_rows() as usize;
let total_row_count = parquet_meta.file_metadata().num_rows() as usize;
let mut metrics = ReaderFilterMetrics::default();
let selection = builder.row_groups_by_minmax(
&read_format,
&parquet_meta,
row_group_size,
total_row_count,
&mut metrics,
false,
);
let selection = builder
.row_groups_by_minmax(
&read_format,
&parquet_meta,
row_group_size,
total_row_count,
&mut metrics,
false,
)
.await;
assert!(!selection.is_empty());
}