Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions crates/paimon/src/btree/reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,31 @@ pub struct BTreeIndexReader<F: Fn(&[u8], &[u8]) -> crate::Result<Ordering>> {
}

impl<F: Fn(&[u8], &[u8]) -> crate::Result<Ordering>> BTreeIndexReader<F> {
/// Approximate retained heap bytes when the reader is parked between scans.
/// Data blocks have a separate bounded cache and are excluded here.
pub(crate) fn cache_weight(&self) -> usize {
let null_bytes = self
.null_bitmap
.get()
.map_or(0, |bitmap| bitmap.serialized_size().saturating_mul(4));
let bloom_bytes = self
.bloom_filter
.as_ref()
.and_then(|bloom| bloom.filter.get())
.map_or(0, |filter| filter.bytes().len());
std::mem::size_of::<Self>()
.saturating_add(self.sst_reader.index_block().retained_bytes())
.saturating_add(self.min_key.as_ref().map_or(0, Vec::capacity))
.saturating_add(self.max_key.as_ref().map_or(0, Vec::capacity))
.saturating_add(null_bytes)
.saturating_add(bloom_bytes)
.saturating_add(self.data_block_cache_file.len())
}

pub(crate) fn set_data_block_cache(&mut self, cache: Arc<BTreeDataBlockCache>) {
self.data_block_cache = cache;
}

/// Open a BTree index reader from a FileRead and file metadata.
/// Only reads the footer and index block on open.
/// Data blocks, the Bloom filter, and the null bitmap are read on demand.
Expand Down
23 changes: 23 additions & 0 deletions crates/paimon/src/catalog/rest/rest_token_file_io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ const OSS_ENDPOINT: &str = "fs.oss.endpoint";
struct TokenState {
token: RESTToken,
file_io: FileIO,
generation: u64,
}

pub struct RESTTokenFileIO {
Expand Down Expand Up @@ -121,9 +122,16 @@ impl RESTTokenFileIO {
_ => self.refresh_token().await?,
};
let file_io = self.build_static_file_io(&token)?;
let generation = self
.state
.read()
.await
.as_ref()
.map_or(1, |state| state.generation.saturating_add(1));
*self.state.write().await = Some(TokenState {
token,
file_io: file_io.clone(),
generation,
});
Ok(file_io)
}
Expand Down Expand Up @@ -186,6 +194,16 @@ impl RESTTokenFileIO {

#[async_trait::async_trait]
impl FileIOProvider for RESTTokenFileIO {
async fn reader_cache_epoch(&self) -> Result<Option<u64>> {
self.current_file_io().await?;
Ok(self
.state
.read()
.await
.as_ref()
.map(|state| state.generation))
}

async fn create(&self, path: &str) -> Result<(opendal::Operator, String)> {
self.current_file_io().await?.create_static(path)
}
Expand Down Expand Up @@ -358,6 +376,7 @@ mod tests {

let file_io = token_file_io.build_file_io().await.unwrap();
assert_eq!(requests.load(Ordering::SeqCst), 0);
assert_eq!(file_io.reader_cache_epoch().await.unwrap(), Some(1));
assert!(!file_io
.exists(file_path.to_string_lossy().as_ref())
.await
Expand All @@ -377,6 +396,10 @@ mod tests {
.await
.unwrap());
assert_eq!(requests.load(Ordering::SeqCst), 1);
// The first refreshed test token is deliberately shorter than the
// safety margin, so checking the epoch refreshes it once more.
assert_eq!(file_io.reader_cache_epoch().await.unwrap(), Some(3));
assert_eq!(requests.load(Ordering::SeqCst), 2);
server.abort();
}

Expand Down
14 changes: 14 additions & 0 deletions crates/paimon/src/io/file_io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,13 @@ pub trait FileIOProvider: std::fmt::Debug + Send + Sync + 'static {
/// Rename requires both paths to resolve to the same shared service instance.
async fn create(&self, path: &str) -> crate::Result<(Operator, String)>;

/// Return the current generation of reader credentials, refreshing them
/// first if needed. `None` disables cross-scan reader reuse for providers
/// that cannot identify when their existing file handles become stale.
async fn reader_cache_epoch(&self) -> crate::Result<Option<u64>> {
Ok(None)
}

/// Optionally publish a complete immutable file without replacing an existing file.
///
/// Return `Some(true)` on success or `Some(false)` for a definite conflict.
Expand Down Expand Up @@ -438,6 +445,13 @@ impl std::fmt::Debug for FileIO {
}

impl FileIO {
pub(crate) async fn reader_cache_epoch(&self) -> crate::Result<Option<u64>> {
match &self.backend {
FileIOBackend::Storage(_) => Ok(Some(0)),
FileIOBackend::Provider(provider) => provider.reader_cache_epoch().await,
}
}

/// Attach an externally managed block cache.
///
/// `block_size` controls the aligned ranges presented to the cache.
Expand Down
144 changes: 136 additions & 8 deletions crates/paimon/src/table/global_index_scanner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,12 @@ use super::global_index_types::{
use crate::btree::{BTreeDataBlockCache, BTreeIndexMeta, BTreeIndexReader};
use crate::fm_index::{manifest_row_range, FMReadContext, FMReadOptions};
use crate::io::FileIO;
use crate::spec::{DataField, FileKind, GlobalIndexSearchMode, IndexManifestEntry, Predicate};
use crate::spec::{
DataField, DataType, FileKind, GlobalIndexSearchMode, IndexManifestEntry, Predicate,
};
use crate::table::RowRange;
use crate::{Error, Result};
use lru::LruCache;
use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex};
Expand All @@ -60,6 +63,101 @@ use std::sync::atomic::{

type BoxedCmp = Box<dyn Fn(&[u8], &[u8]) -> Result<Ordering> + Send + Sync>;

type ReaderKey = (String, DataType);
type CachedReader = (BTreeIndexReader<BoxedCmp>, usize);

pub(super) const DEFAULT_BTREE_READER_CACHE_BYTES: usize = 128 * 1024 * 1024;

/// Reuses immutable BTree index metadata between scans of a table handle.
/// Readers are exclusive while in use. A storage credential generation change
/// drops idle readers, and in-flight scans cannot return older readers.
pub(super) struct SharedBTreeReaderCache {
readers: Mutex<(LruCache<ReaderKey, CachedReader>, usize, u64)>,
max_bytes: usize,
data_blocks: Mutex<Option<(usize, Arc<BTreeDataBlockCache>)>>,
}

impl std::fmt::Debug for SharedBTreeReaderCache {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SharedBTreeReaderCache")
.field("max_bytes", &self.max_bytes)
.finish()
}
}

impl SharedBTreeReaderCache {
pub(super) fn new(max_bytes: usize) -> Self {
Self {
readers: Mutex::new((LruCache::unbounded(), 0, 0)),
max_bytes,
data_blocks: Mutex::new(None),
}
}

fn data_block_cache(&self, max_bytes: usize) -> Arc<BTreeDataBlockCache> {
let mut slot = self.data_blocks.lock().unwrap();
if let Some((size, cache)) = slot.as_ref() {
if *size == max_bytes {
return Arc::clone(cache);
}
// Parked readers retain the previous data cache. Drop them before
// switching budgets so old caches cannot accumulate on a table.
let mut readers = self.readers.lock().unwrap();
readers.0.clear();
readers.1 = 0;
}
let cache = Arc::new(BTreeDataBlockCache::new(max_bytes));
*slot = Some((max_bytes, Arc::clone(&cache)));
cache
}

fn set_epoch(&self, epoch: u64) {
let mut state = self.readers.lock().unwrap();
if state.2 != epoch {
state.0.clear();
state.1 = 0;
state.2 = epoch;
}
}

fn take(&self, key: &ReaderKey, epoch: u64) -> Option<BTreeIndexReader<BoxedCmp>> {
let mut state = self.readers.lock().unwrap();
if state.2 != epoch {
return None;
}
let (reader, weight) = state.0.pop(key)?;
state.1 = state.1.saturating_sub(weight);
Some(reader)
}

fn put(&self, key: ReaderKey, mut reader: BTreeIndexReader<BoxedCmp>, epoch: u64) {
let data_blocks = self.data_blocks.lock().unwrap();
if let Some((_, cache)) = data_blocks.as_ref() {
// Never retain one scan-scoped block cache per parked reader.
reader.set_data_block_cache(Arc::clone(cache));
}
let weight = reader.cache_weight().saturating_add(key.0.capacity());
if weight > self.max_bytes {
return;
}
let mut state = self.readers.lock().unwrap();
if state.2 != epoch {
return;
}
if let Some((_, old_weight)) = state.0.pop(&key) {
state.1 = state.1.saturating_sub(old_weight);
}
state.1 = state.1.saturating_add(weight);
state.0.put(key, (reader, weight));
while state.1 > self.max_bytes {
let Some((_, (_, old_weight))) = state.0.pop_lru() else {
break;
};
state.1 = state.1.saturating_sub(old_weight);
}
}
}

const DELETION_VECTORS_INDEX_TYPE: &str = "DELETION_VECTORS";

#[cfg(test)]
Expand Down Expand Up @@ -137,8 +235,9 @@ pub(crate) struct GlobalIndexScanner {
coverage_by_field: HashMap<i32, Vec<RowRange>>,
/// Schema fields for field_id lookup.
schema_fields: Vec<DataField>,
/// Cache of opened BTree readers, keyed by resolved path.
reader_cache: Mutex<HashMap<String, BTreeIndexReader<BoxedCmp>>>,
/// Cache of opened BTree readers, keyed by resolved path and key type.
reader_cache: Arc<SharedBTreeReaderCache>,
reader_cache_epoch: u64,
/// Serialize use of each BTree reader across concurrent predicate branches.
btree_file_locks: Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
#[cfg(test)]
Expand Down Expand Up @@ -359,13 +458,22 @@ impl GlobalIndexScanner {
#[cfg(test)]
coverage_by_field,
schema_fields: schema_fields.to_vec(),
reader_cache: Mutex::new(HashMap::new()),
reader_cache: Arc::new(SharedBTreeReaderCache::new(usize::MAX)),
reader_cache_epoch: 0,
btree_file_locks: Mutex::new(HashMap::new()),
#[cfg(test)]
query_io_probe: None,
}))
}

fn with_reader_cache(mut self, cache: Arc<SharedBTreeReaderCache>, epoch: u64) -> Self {
cache.set_epoch(epoch);
self.btree_data_block_cache = cache.data_block_cache(self.btree_data_block_cache_size);
self.reader_cache = cache;
self.reader_cache_epoch = epoch;
self
}

/// Bootstrap shared reader resources from effective field settings. An
/// overridden invalid table default must not fail before field resolution.
pub(super) fn read_defaults(
Expand Down Expand Up @@ -651,19 +759,34 @@ pub(crate) struct GlobalIndexEvaluation<'a> {
pub(crate) async fn evaluate_global_index(
evaluation: GlobalIndexEvaluation<'_>,
) -> Result<Option<Vec<RowRange>>> {
evaluate_global_index_impl(evaluation, None).await
evaluate_global_index_impl(evaluation, None, None).await
}

pub(crate) async fn evaluate_global_index_with_options(
evaluation: GlobalIndexEvaluation<'_>,
options: &HashMap<String, String>,
) -> Result<Option<Vec<RowRange>>> {
evaluate_global_index_impl(evaluation, Some(options)).await
evaluate_global_index_impl(evaluation, Some(options), None).await
}

pub(super) async fn evaluate_global_index_with_options_cached(
evaluation: GlobalIndexEvaluation<'_>,
options: &HashMap<String, String>,
reader_cache: Arc<SharedBTreeReaderCache>,
reader_cache_epoch: u64,
) -> Result<Option<Vec<RowRange>>> {
evaluate_global_index_impl(
evaluation,
Some(options),
Some((reader_cache, reader_cache_epoch)),
)
.await
}

async fn evaluate_global_index_impl(
evaluation: GlobalIndexEvaluation<'_>,
options: Option<&HashMap<String, String>>,
reader_cache: Option<(Arc<SharedBTreeReaderCache>, u64)>,
) -> Result<Option<Vec<RowRange>>> {
let scanner = match GlobalIndexScanner::create_with_fm_options(
evaluation.file_io,
Expand All @@ -677,10 +800,15 @@ async fn evaluate_global_index_impl(
evaluation.fm_read_options,
)? {
Some(s) => {
if let Some(options) = options {
s.with_field_options(options, evaluation.index_entries)?
let scanner = if let Some((cache, epoch)) = reader_cache {
s.with_reader_cache(cache, epoch)
} else {
s
};
if let Some(options) = options {
scanner.with_field_options(options, evaluation.index_entries)?
} else {
scanner
}
}
None => return Ok(None),
Expand Down
6 changes: 5 additions & 1 deletion crates/paimon/src/table/global_index_scanner/composite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,11 @@ impl GlobalIndexScanner {
unreachable!()
};
let queried = reader.query_composite(plan).await;
self.return_reader(entry.resolved_path(&self.table_path), reader);
self.return_reader(
entry.resolved_path(&self.table_path),
key_type.clone(),
reader,
);
match queried {
Ok(bitmap) => Ok(Some(
bitmap_to_ranges(&bitmap)
Expand Down
Loading
Loading