mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-12-04 00:15:29 +00:00
feat: count exact files from metadata in partial COUNT scans (#10140)
* feat(mito2): split metadata counts from residual scans Signed-off-by: aumnertic <aumnertic@gmail.com> * fix(mito2): preserve dedup ranges for metadata count residuals Signed-off-by: aumnertic <aumnertic@gmail.com> * test(mito): set TWCS type for metadata count fixtures Signed-off-by: aumnertic <aumnertic@gmail.com> * fix(mito2): record SST counts once per scan Signed-off-by: aumnertic <aumnertic@gmail.com> --------- Signed-off-by: aumnertic <aumnertic@gmail.com>
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -447,7 +447,7 @@ impl RegionFlushTask {
|
||||
.memtables
|
||||
.immutables()
|
||||
.iter()
|
||||
.map(|m| m.id())
|
||||
.map(|(mem, _)| mem.id())
|
||||
.collect();
|
||||
let flush_finished = FlushFinished {
|
||||
region_id: self.region_id,
|
||||
@@ -773,7 +773,7 @@ impl MemtableSstWriter {
|
||||
let mut flush_metrics = Metrics::new(self.kind.write_type());
|
||||
let partition_expr = parse_partition_expr(self.partition_expr.as_deref())?;
|
||||
let mut all_sst_infos = Vec::new();
|
||||
for mem in memtables {
|
||||
for (mem, _) in memtables {
|
||||
if mem.is_empty() {
|
||||
// Skip empty memtables.
|
||||
continue;
|
||||
@@ -2491,7 +2491,7 @@ mod tests {
|
||||
assert_eq!(1, job_scheduler.num_jobs());
|
||||
// Check the new version.
|
||||
let version_data = version_control.current();
|
||||
assert_eq!(0, version_data.version.memtables.immutables()[0].id());
|
||||
assert_eq!(0, version_data.version.memtables.immutables()[0].0.id());
|
||||
// Schedule remaining tasks.
|
||||
let output_rxs: Vec<_> = tasks
|
||||
.into_iter()
|
||||
@@ -2973,7 +2973,7 @@ mod tests {
|
||||
|
||||
// Check the new version.
|
||||
let version_data = version_control.current();
|
||||
assert_eq!(0, version_data.version.memtables.immutables()[0].id());
|
||||
assert_eq!(0, version_data.version.memtables.immutables()[0].0.id());
|
||||
// Assumes the flush job is finished.
|
||||
version_control.apply_edit(
|
||||
Some(RegionEdit {
|
||||
|
||||
@@ -863,12 +863,28 @@ pub struct MemtableRange {
|
||||
context: MemtableRangeContextRef,
|
||||
/// Statistics for this memtable range.
|
||||
stats: MemtableStats,
|
||||
/// Inclusive time range of every row the range can yield, set only when
|
||||
/// the range reads content captured when it was built.
|
||||
captured_time_range: Option<(Timestamp, Timestamp)>,
|
||||
}
|
||||
|
||||
impl MemtableRange {
|
||||
/// Creates a new range from context and stats.
|
||||
pub fn new(context: MemtableRangeContextRef, stats: MemtableStats) -> Self {
|
||||
Self { context, stats }
|
||||
Self {
|
||||
context,
|
||||
stats,
|
||||
captured_time_range: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Marks the range as reading immutable content captured when it was
|
||||
/// built, whose rows all lie in the inclusive `time_range`. Writes after
|
||||
/// that never reach the range.
|
||||
#[must_use]
|
||||
pub(crate) fn with_captured_time_range(mut self, time_range: (Timestamp, Timestamp)) -> Self {
|
||||
self.captured_time_range = Some(time_range);
|
||||
self
|
||||
}
|
||||
|
||||
/// Returns the statistics for this range.
|
||||
@@ -876,6 +892,12 @@ impl MemtableRange {
|
||||
&self.stats
|
||||
}
|
||||
|
||||
/// Returns the inclusive time range of the captured content, if the range
|
||||
/// reads only content captured when it was built.
|
||||
pub(crate) fn captured_time_range(&self) -> Option<(Timestamp, Timestamp)> {
|
||||
self.captured_time_range
|
||||
}
|
||||
|
||||
/// Returns the id of the memtable to read.
|
||||
pub fn id(&self) -> MemtableId {
|
||||
self.context.id
|
||||
|
||||
@@ -584,6 +584,7 @@ impl Memtable for BulkMemtable {
|
||||
bulk_parts.unordered_part.to_bulk_part(&self.metadata)?
|
||||
{
|
||||
let part_stats = unordered_bulk_part.to_memtable_stats(&self.metadata);
|
||||
let captured = part_stats.time_range;
|
||||
let range = MemtableRange::new(
|
||||
Arc::new(MemtableRangeContext::new(
|
||||
self.id,
|
||||
@@ -598,6 +599,11 @@ impl Memtable for BulkMemtable {
|
||||
)),
|
||||
part_stats,
|
||||
);
|
||||
// The range reads a snapshot of the unordered part.
|
||||
let range = match captured {
|
||||
Some(time_range) => range.with_captured_time_range(time_range),
|
||||
None => range,
|
||||
};
|
||||
ranges.insert(range_id, range);
|
||||
range_id += 1;
|
||||
}
|
||||
@@ -611,6 +617,7 @@ impl Memtable for BulkMemtable {
|
||||
|
||||
let part_stats = part_wrapper.part.to_memtable_stats(&self.metadata);
|
||||
let charges = vec![part_wrapper.charge.clone()];
|
||||
let captured = part_stats.time_range;
|
||||
let iter_builder: Box<dyn IterBuilder> = match &part_wrapper.part {
|
||||
PartToMerge::Bulk { part, .. } => Box::new(BulkRangeIterBuilder {
|
||||
part: part.clone(),
|
||||
@@ -643,6 +650,11 @@ impl Memtable for BulkMemtable {
|
||||
)),
|
||||
part_stats,
|
||||
);
|
||||
// Parts are immutable once added, and the range holds this one.
|
||||
let range = match captured {
|
||||
Some(time_range) => range.with_captured_time_range(time_range),
|
||||
None => range,
|
||||
};
|
||||
ranges.insert(range_id, range);
|
||||
range_id += 1;
|
||||
}
|
||||
|
||||
@@ -38,7 +38,6 @@ use store_api::metadata::RegionMetadataRef;
|
||||
use crate::error;
|
||||
use crate::error::{InvalidRequestSnafu, Result};
|
||||
use crate::memtable::bulk::part::{BulkPart, BulkPartConverter};
|
||||
use crate::memtable::version::SmallMemtableVec;
|
||||
use crate::memtable::{KeyValues, MemtableBuilderRef, MemtableId, MemtableRef};
|
||||
use crate::sst::{FlatSchemaOptions, to_flat_sst_arrow_schema};
|
||||
|
||||
@@ -403,6 +402,20 @@ impl TimePartitions {
|
||||
memtables.extend(inner.parts.iter().map(|part| part.memtable.clone()));
|
||||
}
|
||||
|
||||
/// Appends memtables in partitions with their partition time ranges.
|
||||
pub(crate) fn list_memtables_with_time_ranges(
|
||||
&self,
|
||||
memtables: &mut impl Extend<(MemtableRef, PartTimeRange)>,
|
||||
) {
|
||||
let inner = self.inner.lock().unwrap();
|
||||
memtables.extend(
|
||||
inner
|
||||
.parts
|
||||
.iter()
|
||||
.map(|part| (part.memtable.clone(), part.time_range)),
|
||||
);
|
||||
}
|
||||
|
||||
/// Returns the number of partitions.
|
||||
pub fn num_partitions(&self) -> usize {
|
||||
let inner = self.inner.lock().unwrap();
|
||||
@@ -515,12 +528,6 @@ impl TimePartitions {
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Append memtables in partitions to small vec.
|
||||
pub(crate) fn list_memtables_to_small_vec(&self, memtables: &mut SmallMemtableVec) {
|
||||
let inner = self.inner.lock().unwrap();
|
||||
memtables.extend(inner.parts.iter().map(|part| part.memtable.clone()));
|
||||
}
|
||||
|
||||
/// Returns the next memtable id.
|
||||
pub(crate) fn next_memtable_id(&self) -> MemtableId {
|
||||
let inner = self.inner.lock().unwrap();
|
||||
@@ -789,9 +796,11 @@ impl PartitionsInner {
|
||||
}
|
||||
}
|
||||
|
||||
/// Time range of a partition.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct PartTimeRange {
|
||||
/// Time range of a partition. Writes route every row to the partition whose
|
||||
/// range contains its timestamp, so the range bounds every row the partition's
|
||||
/// memtable can ever hold, including rows written later.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) struct PartTimeRange {
|
||||
/// Inclusive min timestamp of rows in the partition.
|
||||
min_timestamp: Timestamp,
|
||||
/// Exclusive max timestamp of rows in the partition.
|
||||
@@ -815,6 +824,14 @@ impl PartTimeRange {
|
||||
fn contains_timestamp(&self, ts: Timestamp) -> bool {
|
||||
self.min_timestamp <= ts && ts < self.max_timestamp
|
||||
}
|
||||
|
||||
/// Returns the range as inclusive `(min, max)` bounds, or `None` if it
|
||||
/// holds no timestamp.
|
||||
pub(crate) fn to_inclusive(self) -> Option<(Timestamp, Timestamp)> {
|
||||
let max = self.max_timestamp.value().checked_sub(1)?;
|
||||
let max = Timestamp::new(max, self.max_timestamp.unit());
|
||||
(self.min_timestamp <= max).then_some((self.min_timestamp, max))
|
||||
}
|
||||
}
|
||||
|
||||
struct PartitionToWrite<'a> {
|
||||
|
||||
@@ -25,22 +25,20 @@ use store_api::storage::SequenceNumber;
|
||||
|
||||
use crate::error::Result;
|
||||
use crate::memtable::bulk::part::BulkPart;
|
||||
use crate::memtable::time_partition::TimePartitions;
|
||||
use crate::memtable::time_partition::{PartTimeRange, TimePartitions};
|
||||
use crate::memtable::{KeyValues, MemtableBuilderRef, MemtableId, MemtableRef};
|
||||
|
||||
pub(crate) type SmallMemtableVec = SmallVec<[MemtableRef; 2]>;
|
||||
|
||||
/// A version of current memtables in a region.
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct MemtableVersion {
|
||||
/// Mutable memtable.
|
||||
pub(crate) mutable: MutableMemtablesRef,
|
||||
/// Immutable memtables.
|
||||
/// Immutable memtables paired with the time range of their original partition.
|
||||
///
|
||||
/// We only allow one flush job per region but if a flush job failed, then we
|
||||
/// might need to store more than one immutable memtable on the next time we
|
||||
/// flush the region.
|
||||
immutables: SmallMemtableVec,
|
||||
immutables: SmallVec<[(MemtableRef, PartTimeRange); 2]>,
|
||||
/// Whether immutable memtables may contain skip-WAL writes.
|
||||
/// Flushes are serialized per region and cover all immutable memtables.
|
||||
immutable_has_skip_wal_writes: bool,
|
||||
@@ -63,8 +61,8 @@ impl MemtableVersion {
|
||||
self.mutable.has_skip_wal_writes() || self.immutable_has_skip_wal_writes
|
||||
}
|
||||
|
||||
/// Immutable memtables.
|
||||
pub(crate) fn immutables(&self) -> &[MemtableRef] {
|
||||
/// Immutable memtables and their original partition time ranges.
|
||||
pub(crate) fn immutables(&self) -> &[(MemtableRef, PartTimeRange)] {
|
||||
&self.immutables
|
||||
}
|
||||
|
||||
@@ -72,6 +70,18 @@ impl MemtableVersion {
|
||||
pub(crate) fn list_memtables(&self) -> Vec<MemtableRef> {
|
||||
let mut mems = Vec::with_capacity(self.immutables.len() + self.mutable.num_partitions());
|
||||
self.mutable.list_memtables(&mut mems);
|
||||
mems.extend(self.immutables.iter().map(|(mem, _)| mem.clone()));
|
||||
mems
|
||||
}
|
||||
|
||||
/// Lists mutable and immutable memtables with the time range of the
|
||||
/// partition each was created for. A memtable never holds a row outside
|
||||
/// its partition range, even after later writes.
|
||||
pub(crate) fn list_memtables_with_time_ranges(&self) -> Vec<(MemtableRef, PartTimeRange)> {
|
||||
let mut mems = Vec::with_capacity(self.immutables.len() + self.mutable.num_partitions());
|
||||
self.mutable
|
||||
.partitions
|
||||
.list_memtables_with_time_ranges(&mut mems);
|
||||
mems.extend_from_slice(&self.immutables);
|
||||
mems
|
||||
}
|
||||
@@ -142,7 +152,7 @@ impl MemtableVersion {
|
||||
// Pushes the mutable memtable to immutable list.
|
||||
self.mutable
|
||||
.partitions
|
||||
.list_memtables_to_small_vec(&mut immutables);
|
||||
.list_memtables_with_time_ranges(&mut immutables);
|
||||
|
||||
Ok(Some(MemtableVersion {
|
||||
mutable,
|
||||
@@ -154,12 +164,7 @@ impl MemtableVersion {
|
||||
|
||||
/// Removes memtables by ids from immutable memtables.
|
||||
pub(crate) fn remove_memtables(&mut self, ids: &[MemtableId]) {
|
||||
self.immutables = self
|
||||
.immutables
|
||||
.iter()
|
||||
.filter(|mem| !ids.contains(&mem.id()))
|
||||
.cloned()
|
||||
.collect();
|
||||
self.immutables.retain(|(mem, _)| !ids.contains(&mem.id()));
|
||||
if self.immutables.is_empty() {
|
||||
self.immutable_has_skip_wal_writes = false;
|
||||
}
|
||||
@@ -174,7 +179,7 @@ impl MemtableVersion {
|
||||
pub(crate) fn immutables_usage(&self) -> usize {
|
||||
self.immutables
|
||||
.iter()
|
||||
.map(|mem| mem.stats().estimated_bytes)
|
||||
.map(|(mem, _)| mem.stats().estimated_bytes)
|
||||
.sum()
|
||||
}
|
||||
|
||||
@@ -185,7 +190,7 @@ impl MemtableVersion {
|
||||
+ self
|
||||
.immutables
|
||||
.iter()
|
||||
.map(|mem| mem.stats().decoded_bytes())
|
||||
.map(|(mem, _)| mem.stats().decoded_bytes())
|
||||
.sum::<usize>()
|
||||
}
|
||||
|
||||
@@ -193,7 +198,7 @@ impl MemtableVersion {
|
||||
pub(crate) fn num_rows(&self) -> u64 {
|
||||
self.immutables
|
||||
.iter()
|
||||
.map(|mem| mem.stats().num_rows as u64)
|
||||
.map(|(mem, _)| mem.stats().num_rows as u64)
|
||||
.sum::<u64>()
|
||||
+ self.mutable.num_rows()
|
||||
}
|
||||
@@ -204,6 +209,7 @@ impl MemtableVersion {
|
||||
self.mutable.list_memtables(&mut mutables);
|
||||
self.immutables
|
||||
.iter()
|
||||
.map(|(mem, _)| mem)
|
||||
.chain(mutables.iter())
|
||||
.filter_map(|mem| mem.stats().time_range())
|
||||
.reduce(|(min_a, max_a), (min_b, max_b)| (min_a.min(min_b), max_a.max(max_b)))
|
||||
@@ -362,7 +368,11 @@ mod tests {
|
||||
frozen.mutable.mark_skip_wal_writes();
|
||||
}
|
||||
frozen.mutable.write(&kvs).unwrap();
|
||||
let ids: Vec<_> = frozen.immutables().iter().map(|mem| mem.id()).collect();
|
||||
let ids: Vec<_> = frozen
|
||||
.immutables()
|
||||
.iter()
|
||||
.map(|(mem, _)| mem.id())
|
||||
.collect();
|
||||
frozen.remove_memtables(&ids);
|
||||
assert_eq!(new_skip_wal_writes, frozen.has_skip_wal_writes());
|
||||
assert_eq!(
|
||||
@@ -377,7 +387,11 @@ mod tests {
|
||||
.freeze_mutable(&metadata, Some(Duration::from_secs(5)))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let ids: Vec<_> = next_flush.immutables().iter().map(|mem| mem.id()).collect();
|
||||
let ids: Vec<_> = next_flush
|
||||
.immutables()
|
||||
.iter()
|
||||
.map(|(mem, _)| mem.id())
|
||||
.collect();
|
||||
next_flush.remove_memtables(&ids);
|
||||
assert!(!next_flush.has_skip_wal_writes());
|
||||
}
|
||||
@@ -418,7 +432,11 @@ mod tests {
|
||||
.unwrap();
|
||||
assert_eq!(2, retried.immutables().len());
|
||||
assert!(retried.has_skip_wal_writes());
|
||||
let ids: Vec<_> = retried.immutables().iter().map(|mem| mem.id()).collect();
|
||||
let ids: Vec<_> = retried
|
||||
.immutables()
|
||||
.iter()
|
||||
.map(|(mem, _)| mem.id())
|
||||
.collect();
|
||||
retried.remove_memtables(&ids);
|
||||
assert!(!retried.has_skip_wal_writes());
|
||||
|
||||
@@ -431,4 +449,58 @@ mod tests {
|
||||
assert!(!replacement.has_skip_wal_writes());
|
||||
assert!(frozen.has_skip_wal_writes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_partition_time_ranges_follow_memtables() {
|
||||
let metadata = memtable_util::metadata_for_test();
|
||||
let partitions = TimePartitions::new(
|
||||
metadata.clone(),
|
||||
Arc::new(TimeSeriesMemtableBuilder::default()),
|
||||
0,
|
||||
Some(Duration::from_secs(5)),
|
||||
);
|
||||
let version = MemtableVersion::new(partitions);
|
||||
for ts in [1000, 7000] {
|
||||
let kvs = memtable_util::build_key_values(&metadata, "hello".to_string(), 0, &[ts], 1);
|
||||
version.mutable.write(&kvs).unwrap();
|
||||
}
|
||||
let ranges = |version: &MemtableVersion| {
|
||||
let mut ranges: Vec<_> = version
|
||||
.list_memtables_with_time_ranges()
|
||||
.into_iter()
|
||||
.map(|(mem, range)| {
|
||||
let (min, max) = range.to_inclusive().unwrap();
|
||||
(mem.id(), min.value(), max.value())
|
||||
})
|
||||
.collect();
|
||||
ranges.sort_unstable();
|
||||
ranges
|
||||
};
|
||||
// The upper bound of a partition is exclusive.
|
||||
assert_eq!(ranges(&version), [(0, 0, 4999), (1, 5000, 9999)]);
|
||||
|
||||
// Frozen memtables keep their partition ranges. The forked mutable
|
||||
// memtable covers the partition of the latest row.
|
||||
let mut frozen = version
|
||||
.freeze_mutable(&metadata, Some(Duration::from_secs(5)))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
ranges(&frozen),
|
||||
[(0, 0, 4999), (1, 5000, 9999), (2, 5000, 9999)]
|
||||
);
|
||||
let snapshot = frozen.clone();
|
||||
frozen.remove_memtables(&[0]);
|
||||
assert_eq!(ranges(&frozen), [(1, 5000, 9999), (2, 5000, 9999)]);
|
||||
let [(remaining, range)] = frozen.immutables() else {
|
||||
panic!("expected one immutable memtable after removing the first partition");
|
||||
};
|
||||
assert_eq!(remaining.id(), 1);
|
||||
let (min, max) = range.to_inclusive().unwrap();
|
||||
assert_eq!((min.value(), max.value()), (5000, 9999));
|
||||
assert_eq!(
|
||||
ranges(&snapshot),
|
||||
[(0, 0, 4999), (1, 5000, 9999), (2, 5000, 9999)]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -809,11 +809,7 @@ mod tests {
|
||||
.build();
|
||||
let query_start = input.query_start.unwrap_or_else(Instant::now);
|
||||
let ranges = RangeMeta::unordered_scan_ranges(&input).await;
|
||||
let stream_ctx = Arc::new(StreamContext::unordered_scan_ctx(
|
||||
input,
|
||||
ranges,
|
||||
query_start,
|
||||
));
|
||||
let stream_ctx = Arc::new(StreamContext::with_ranges(input, ranges, query_start));
|
||||
let pruner = Arc::new(Pruner::new(stream_ctx, 1));
|
||||
(env, pruner)
|
||||
}
|
||||
@@ -867,11 +863,7 @@ mod tests {
|
||||
.build();
|
||||
let query_start = input.query_start.unwrap_or_else(Instant::now);
|
||||
let ranges = RangeMeta::unordered_scan_ranges(&input).await;
|
||||
let stream_ctx = Arc::new(StreamContext::unordered_scan_ctx(
|
||||
input,
|
||||
ranges,
|
||||
query_start,
|
||||
));
|
||||
let stream_ctx = Arc::new(StreamContext::with_ranges(input, ranges, query_start));
|
||||
let pruner = Arc::new(Pruner::new(stream_ctx, 1));
|
||||
(env, pruner)
|
||||
}
|
||||
|
||||
@@ -71,6 +71,60 @@ pub(crate) struct RangeMeta {
|
||||
}
|
||||
|
||||
impl RangeMeta {
|
||||
/// Retains the sources mapped into `input` and keeps their row groups in
|
||||
/// this range together for deduplication.
|
||||
pub(crate) fn remap_sources(
|
||||
&self,
|
||||
mapping: &[Option<usize>],
|
||||
input: &ScanInput,
|
||||
) -> Option<Self> {
|
||||
let indices: SmallVec<[SourceIndex; 2]> = self
|
||||
.indices
|
||||
.iter()
|
||||
.filter_map(|source| {
|
||||
Some(SourceIndex {
|
||||
index: mapping[source.index]?,
|
||||
..*source
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
if indices.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let row_group_indices = self
|
||||
.row_group_indices
|
||||
.iter()
|
||||
.filter_map(|row_group| {
|
||||
Some(RowGroupIndex {
|
||||
index: mapping[row_group.index]?,
|
||||
..*row_group
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let num_rows = if indices.len() == self.indices.len() {
|
||||
self.num_rows
|
||||
} else {
|
||||
// A multi-source sequential range contains all row groups of each source.
|
||||
indices
|
||||
.iter()
|
||||
.map(|source| {
|
||||
if source.index < input.num_memtables() {
|
||||
input.memtables[source.index].stats().num_rows()
|
||||
} else {
|
||||
input.files[source.index - input.num_memtables()].num_rows()
|
||||
}
|
||||
})
|
||||
.fold(0, usize::saturating_add)
|
||||
};
|
||||
Some(Self {
|
||||
// Keep the original bounds used for time filtering.
|
||||
time_range: self.time_range,
|
||||
indices,
|
||||
row_group_indices,
|
||||
num_rows,
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates a [PartitionRange] with specific identifier.
|
||||
/// It converts the inclusive max timestamp to exclusive end timestamp.
|
||||
pub(crate) fn new_partition_range(&self, identifier: usize) -> PartitionRange {
|
||||
@@ -532,12 +586,33 @@ pub(crate) struct MemRangeBuilder {
|
||||
range: MemtableRange,
|
||||
/// Stats of a memtable.
|
||||
stats: MemtableStats,
|
||||
/// Inclusive time range of every row the range can yield, including rows
|
||||
/// written to its memtable after the range was built. `None` if unknown.
|
||||
/// Unlike `stats`, it never shrinks to the rows present at build time.
|
||||
container_time_range: Option<(Timestamp, Timestamp)>,
|
||||
}
|
||||
|
||||
impl MemRangeBuilder {
|
||||
/// Builds a mem range builder from row groups.
|
||||
pub(crate) fn new(range: MemtableRange, stats: MemtableStats) -> Self {
|
||||
Self { range, stats }
|
||||
Self {
|
||||
range,
|
||||
stats,
|
||||
container_time_range: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the inclusive time range bounding every row the range can yield.
|
||||
#[must_use]
|
||||
pub(crate) fn with_container_time_range(mut self, time_range: (Timestamp, Timestamp)) -> Self {
|
||||
self.container_time_range = Some(time_range);
|
||||
self
|
||||
}
|
||||
|
||||
/// Returns the inclusive time range bounding every row the range can
|
||||
/// yield, or `None` if it is unknown.
|
||||
pub(crate) fn container_time_range(&self) -> Option<(Timestamp, Timestamp)> {
|
||||
self.container_time_range
|
||||
}
|
||||
|
||||
/// Builds mem ranges to read in the memtable.
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
//! Scans a region according to the scan request.
|
||||
|
||||
mod aggr;
|
||||
pub(crate) use aggr::StatisticsSplitPlan;
|
||||
#[cfg(any(test, feature = "test", feature = "testing"))]
|
||||
pub use aggr::overlap as metadata_aggr_overlap;
|
||||
|
||||
@@ -418,7 +419,8 @@ impl ScanRegion {
|
||||
let input = self.scan_input().await?;
|
||||
let query_start = input.query_start.unwrap_or_else(Instant::now);
|
||||
let ranges = RangeMeta::unordered_scan_ranges(&input).await;
|
||||
let stream_ctx = StreamContext::unordered_scan_ctx(input, ranges, query_start);
|
||||
READ_SST_COUNT.observe(input.num_files() as f64);
|
||||
let stream_ctx = StreamContext::with_ranges(input, ranges, query_start);
|
||||
Ok(UnorderedScan::new(stream_ctx))
|
||||
}
|
||||
|
||||
@@ -452,6 +454,9 @@ impl ScanRegion {
|
||||
/// Creates a scan input.
|
||||
#[tracing::instrument(skip_all, fields(region_id = %self.region_id()))]
|
||||
async fn scan_input(mut self) -> Result<ScanInput> {
|
||||
// Only SeqScan consumes a split. Other scanners can still use a
|
||||
// full count when every source is covered.
|
||||
let allow_partial = !self.use_unordered_scan() && !self.use_series_scan();
|
||||
let metadata = &self.version.metadata;
|
||||
let sst_min_sequence = self.request.sst_min_sequence.and_then(NonZeroU64::new);
|
||||
let time_range = self.build_time_range_predicate();
|
||||
@@ -491,7 +496,7 @@ impl ScanRegion {
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
let memtables = self.version.memtables.list_memtables();
|
||||
let memtables = self.version.memtables.list_memtables_with_time_ranges();
|
||||
// Skip empty memtables and memtables out of time range.
|
||||
let mut mem_range_builders = Vec::new();
|
||||
// Narthex may serve raw-series output, which deduplicates append rows.
|
||||
@@ -512,7 +517,7 @@ impl ScanRegion {
|
||||
)
|
||||
};
|
||||
|
||||
for m in memtables {
|
||||
for (m, partition_range) in memtables {
|
||||
// check if memtable is empty by reading stats.
|
||||
let Some((start, end)) = m.stats().time_range() else {
|
||||
continue;
|
||||
@@ -532,9 +537,18 @@ impl ScanRegion {
|
||||
))
|
||||
.with_pre_filter_mode(filter_mode),
|
||||
)?;
|
||||
// A range bounds its rows by its captured content when it has one,
|
||||
// otherwise by its partition: memtables may keep accepting writes
|
||||
// after the range is built, but only inside their partition.
|
||||
let partition_range = partition_range.to_inclusive();
|
||||
mem_range_builders.extend(ranges_in_memtable.ranges.into_values().map(|v| {
|
||||
let stats = v.stats().clone();
|
||||
MemRangeBuilder::new(v, stats)
|
||||
let container = v.captured_time_range().or(partition_range);
|
||||
let builder = MemRangeBuilder::new(v, stats);
|
||||
match container {
|
||||
Some(time_range) => builder.with_container_time_range(time_range),
|
||||
None => builder,
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -633,10 +647,22 @@ impl ScanRegion {
|
||||
};
|
||||
let mut input = input.build();
|
||||
input.row_preserving_request = request_preserves_rows(&self.request);
|
||||
if self.experimental_metadata_aggr && self.request.metadata_aggr_hint {
|
||||
// Reuse the scan's manifest time pruning. Footer checks apply only to
|
||||
// files in the read set, even for manifests from older offline tools.
|
||||
input.exact_num_rows = aggr::prepare(&input, &self.request).boxed().await;
|
||||
if self.experimental_metadata_aggr
|
||||
&& self.request.metadata_aggr_hint
|
||||
&& !(input.append_mode
|
||||
&& input.predicate_group().predicate_without_region().is_none()
|
||||
&& input.source_row_counts_are_exact())
|
||||
{
|
||||
// Reuse the scan's manifest time pruning, even for manifests from
|
||||
// older offline tools.
|
||||
match aggr::prepare(&input, &self.request, allow_partial)
|
||||
.boxed()
|
||||
.await
|
||||
{
|
||||
Some(aggr::MetadataAggr::Exact(rows)) => input.exact_num_rows = Some(rows),
|
||||
Some(aggr::MetadataAggr::Split(plan)) => input.statistics_split = Some(plan),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
Ok(input)
|
||||
}
|
||||
@@ -937,6 +963,8 @@ pub struct ScanInput {
|
||||
pub(crate) exact_num_rows: Option<usize>,
|
||||
/// Whether the request leaves the source rows visible before predicates.
|
||||
row_preserving_request: bool,
|
||||
/// Exact and residual sources of a hinted COUNT, taken by the scanner.
|
||||
pub(crate) statistics_split: Option<StatisticsSplitPlan>,
|
||||
/// Pinned series-index snapshot and its storage, when configured.
|
||||
/// Whether to ignore range indexes while retaining series-index candidate discovery.
|
||||
/// Region SST access layer.
|
||||
@@ -1016,6 +1044,7 @@ pub struct ScanInput {
|
||||
|
||||
/// Cached output of scan request analysis: the optional range-cache fingerprint
|
||||
/// plus the derived implied time range used by range cache and prefilter.
|
||||
#[derive(Clone)]
|
||||
struct ScanAnalysis {
|
||||
/// `None` when the scan is not eligible for range caching.
|
||||
fingerprint: Option<ScanRequestFingerprint>,
|
||||
@@ -1033,6 +1062,60 @@ pub(crate) struct ScanInputBuilder {
|
||||
}
|
||||
|
||||
impl ScanInput {
|
||||
/// Returns this scan restricted to the given sources, sharing the read
|
||||
/// view and every query setting. Opens no SST data.
|
||||
pub(crate) fn with_sources(
|
||||
&self,
|
||||
files: Vec<FileHandle>,
|
||||
memtables: Vec<MemRangeBuilder>,
|
||||
) -> Option<Self> {
|
||||
#[cfg(feature = "enterprise")]
|
||||
if !self.extension_ranges.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(Self {
|
||||
exact_num_rows: None,
|
||||
row_preserving_request: self.row_preserving_request,
|
||||
statistics_split: None,
|
||||
page_index_policy: self.page_index_policy,
|
||||
access_layer: self.access_layer.clone(),
|
||||
mapper: self.mapper.clone(),
|
||||
read_cols: self.read_cols.clone(),
|
||||
time_range: self.time_range,
|
||||
scan_analysis: self.scan_analysis.clone(),
|
||||
predicate: self.predicate.clone(),
|
||||
region_partition_expr: self.region_partition_expr.clone(),
|
||||
memtables,
|
||||
files,
|
||||
narthex_series_indexes: self.narthex_series_indexes.clone(),
|
||||
narthex_format: self.narthex_format,
|
||||
primary_key_mapper: self.primary_key_mapper.clone(),
|
||||
batch_size: self.batch_size,
|
||||
cache_strategy: self.cache_strategy.clone(),
|
||||
ignore_file_not_found: self.ignore_file_not_found,
|
||||
max_concurrent_scan_files: self.max_concurrent_scan_files,
|
||||
scan_memory_tracker: self.scan_memory_tracker.clone(),
|
||||
inverted_index_appliers: self.inverted_index_appliers.clone(),
|
||||
bloom_filter_index_appliers: self.bloom_filter_index_appliers.clone(),
|
||||
fulltext_index_appliers: self.fulltext_index_appliers.clone(),
|
||||
query_start: self.query_start,
|
||||
append_mode: self.append_mode,
|
||||
filter_deleted: self.filter_deleted,
|
||||
merge_mode: self.merge_mode,
|
||||
series_row_selector: self.series_row_selector,
|
||||
distribution: self.distribution,
|
||||
explain_flat_format: self.explain_flat_format,
|
||||
snapshot_sequence: self.snapshot_sequence,
|
||||
sequence_range: self.sequence_range,
|
||||
compaction: self.compaction,
|
||||
compaction_read_parallelism: self.compaction_read_parallelism,
|
||||
json2_rewrite_targets: self.json2_rewrite_targets.clone(),
|
||||
query_stat_counters: self.query_stat_counters.clone(),
|
||||
#[cfg(feature = "enterprise")]
|
||||
extension_ranges: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates a new [ScanInputBuilder].
|
||||
#[must_use]
|
||||
pub(crate) fn builder(
|
||||
@@ -1043,6 +1126,7 @@ impl ScanInput {
|
||||
input: ScanInput {
|
||||
exact_num_rows: None,
|
||||
row_preserving_request: true,
|
||||
statistics_split: None,
|
||||
page_index_policy: None,
|
||||
access_layer,
|
||||
read_cols: mapper.read_columns().clone(),
|
||||
@@ -2187,20 +2271,15 @@ impl StreamContext {
|
||||
let query_start = input.query_start.unwrap_or_else(Instant::now);
|
||||
let ranges = RangeMeta::seq_scan_ranges(&input);
|
||||
READ_SST_COUNT.observe(input.num_files() as f64);
|
||||
Self {
|
||||
input,
|
||||
ranges,
|
||||
query_start,
|
||||
}
|
||||
Self::with_ranges(input, ranges, query_start)
|
||||
}
|
||||
|
||||
/// Creates a new [StreamContext] for [UnorderedScan].
|
||||
pub(crate) fn unordered_scan_ctx(
|
||||
/// Creates a new [StreamContext] with the caller's range layout.
|
||||
pub(crate) fn with_ranges(
|
||||
input: ScanInput,
|
||||
ranges: Vec<RangeMeta>,
|
||||
query_start: Instant,
|
||||
) -> Self {
|
||||
READ_SST_COUNT.observe(input.num_files() as f64);
|
||||
Self {
|
||||
input,
|
||||
ranges,
|
||||
|
||||
@@ -30,7 +30,7 @@ use datatypes::value::Value;
|
||||
use futures::future::BoxFuture;
|
||||
use futures::{FutureExt, StreamExt, TryStreamExt};
|
||||
use mito_codec::row_converter::{PrimaryKeyCodec, build_primary_key_codec};
|
||||
use parquet::file::metadata::ParquetMetaData;
|
||||
use parquet::file::metadata::{PageIndexPolicy, ParquetMetaData};
|
||||
use store_api::codec::PrimaryKeyEncoding;
|
||||
use store_api::metadata::{ColumnMetadata, RegionMetadata};
|
||||
use store_api::storage::{ColumnId, ScanRequest};
|
||||
@@ -43,43 +43,133 @@ use crate::sst::parquet::metadata::{
|
||||
extract_primary_key_range, extract_time_range, has_deduped_sst_marker, has_only_puts,
|
||||
};
|
||||
|
||||
/// Returns the exact number of rows the scan yields, or `None` if it cannot
|
||||
/// be proven. Non-append candidates use cached Parquet footers to prove
|
||||
/// file-local uniqueness and the absence of deletes.
|
||||
pub(crate) async fn prepare(input: &ScanInput, request: &ScanRequest) -> Option<usize> {
|
||||
let classification = classify(input, request)?;
|
||||
if input.append_mode && request.filters.is_empty() {
|
||||
return Some(classification.exact_rows);
|
||||
}
|
||||
let check_keys =
|
||||
classification.key_filter || (!input.append_mode && classification.exact.len() > 1);
|
||||
let check_rows = !input.append_mode;
|
||||
futures::stream::iter(classification.exact)
|
||||
.map(|index| file_evidence(input, input.files[index].clone(), check_keys, check_rows))
|
||||
.buffer_unordered(input.max_concurrent_scan_files.max(1))
|
||||
.try_collect::<()>()
|
||||
.await
|
||||
.ok()?;
|
||||
Some(classification.exact_rows)
|
||||
/// What the manifest and SST statistics prove about the row count of a
|
||||
/// hinted scalar COUNT scan.
|
||||
pub(crate) enum MetadataAggr {
|
||||
/// The whole scan yields exactly this many rows.
|
||||
Exact(usize),
|
||||
/// Some files are exact; the rest of the sources must still be scanned.
|
||||
Split(StatisticsSplitPlan),
|
||||
}
|
||||
|
||||
fn time_bounds_match(file: &FileHandle, sst: &CachedSstMeta, time_id: ColumnId) -> bool {
|
||||
/// Disjoint source sets for an exact part and a residual scan of one read view.
|
||||
pub(crate) struct StatisticsSplitPlan {
|
||||
/// Sum of the manifest row counts of the files whose rows are all yielded
|
||||
/// exactly once, without other sources.
|
||||
pub(crate) exact_rows: usize,
|
||||
/// Indexes into `ScanInput::files` of the other files intersecting the query
|
||||
/// time range. Memtable ranges always stay in the residual scan.
|
||||
pub(crate) remaining_file_indices: Vec<usize>,
|
||||
}
|
||||
|
||||
/// Classifies sources once. Non-append candidates use cached Parquet footers
|
||||
/// to prove file-local uniqueness and the absence of deletes.
|
||||
pub(crate) async fn prepare(
|
||||
input: &ScanInput,
|
||||
request: &ScanRequest,
|
||||
allow_partial: bool,
|
||||
) -> Option<MetadataAggr> {
|
||||
if !allow_partial && !input.memtables.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let classification = classify(input, request, allow_partial)?;
|
||||
if !allow_partial && !classification.remaining.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if classification.exact.is_empty()
|
||||
&& (!classification.remaining.is_empty() || !input.memtables.is_empty())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if input.append_mode && request.filters.is_empty() {
|
||||
return resolve(input, classification, allow_partial);
|
||||
}
|
||||
let mut classification = classification;
|
||||
let check_overlap =
|
||||
!input.append_mode && classification.exact.len() + classification.remaining.len() > 1;
|
||||
if check_overlap {
|
||||
verify_residual_bounds(input, &classification.remaining).await?;
|
||||
}
|
||||
let check_keys = classification.key_filter || check_overlap;
|
||||
let check_rows = !input.append_mode;
|
||||
let proven: Vec<_> = futures::stream::iter(classification.exact.iter().copied())
|
||||
.map(|index| file_evidence(input, input.files[index].clone(), check_keys, check_rows))
|
||||
.buffered(input.max_concurrent_scan_files.max(1))
|
||||
.try_collect()
|
||||
.await
|
||||
.ok()?;
|
||||
classification.retain_exact(input, &proven);
|
||||
resolve(input, classification, allow_partial)
|
||||
}
|
||||
|
||||
/// Applies the footer evidence of the exact candidates.
|
||||
fn resolve(
|
||||
input: &ScanInput,
|
||||
classification: Classification,
|
||||
allow_partial: bool,
|
||||
) -> Option<MetadataAggr> {
|
||||
if classification.remaining.is_empty() && input.memtables.is_empty() {
|
||||
return Some(MetadataAggr::Exact(classification.exact_rows));
|
||||
}
|
||||
if !allow_partial || classification.exact.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(MetadataAggr::Split(StatisticsSplitPlan {
|
||||
exact_rows: classification.exact_rows,
|
||||
remaining_file_indices: classification.remaining,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Reuses ordinary scan pruning for files the residual cannot read. For files
|
||||
/// it can read, a stale bound (e.g. from older offline replacement) could
|
||||
/// hide an overlap with an exact candidate. Only consult memory for these
|
||||
/// bounds and let the ordinary scan handle a cache miss.
|
||||
async fn verify_residual_bounds(input: &ScanInput, remaining: &[usize]) -> Option<()> {
|
||||
let time_id = input.region_metadata().time_index_column().column_id;
|
||||
for &index in remaining {
|
||||
let file = &input.files[index];
|
||||
if input.can_manifest_prune_file(file) {
|
||||
continue;
|
||||
}
|
||||
let sst = input
|
||||
.cache_strategy
|
||||
.get_sst_meta_data_from_mem_cache(file.file_id(), PageIndexPolicy::Skip)
|
||||
.await?;
|
||||
if !bounds_match(file, &sst, time_id, true) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
fn bounds_match(
|
||||
file: &FileHandle,
|
||||
sst: &CachedSstMeta,
|
||||
time_id: ColumnId,
|
||||
check_keys: bool,
|
||||
) -> bool {
|
||||
let region = sst.region_metadata();
|
||||
let time_index = region.time_index_column();
|
||||
let (start, end) = file.time_range();
|
||||
let metadata = sst.parquet_metadata();
|
||||
time_index.column_id == time_id
|
||||
&& extract_time_range(&sst.parquet_metadata(), time_index).is_some_and(|(min, max)| {
|
||||
&& extract_time_range(&metadata, time_index).is_some_and(|(min, max)| {
|
||||
start.unit() == min.unit() && end.unit() == max.unit() && (start, end) == (min, max)
|
||||
})
|
||||
&& (!check_keys
|
||||
|| file
|
||||
.raw_primary_key_range()
|
||||
.is_none_or(|range| extract_primary_key_range(&metadata, ®ion) == Some(range)))
|
||||
}
|
||||
|
||||
/// Proves the bounds and visible rows required for this exact candidate.
|
||||
/// A bounds mismatch invalidates the classification. An unproven row count
|
||||
/// can still be left to the residual scan when partial counts are supported.
|
||||
fn file_evidence(
|
||||
input: &ScanInput,
|
||||
file: FileHandle,
|
||||
check_keys: bool,
|
||||
check_rows: bool,
|
||||
) -> BoxFuture<'static, Result<(), ()>> {
|
||||
) -> BoxFuture<'static, Result<bool, ()>> {
|
||||
let time_id = input.region_metadata().time_index_column().column_id;
|
||||
let reader = input
|
||||
.access_layer
|
||||
@@ -92,19 +182,10 @@ fn file_evidence(
|
||||
file.file_id()
|
||||
);
|
||||
})?;
|
||||
let metadata = sst.parquet_metadata();
|
||||
if !time_bounds_match(&file, &sst, time_id) {
|
||||
if !bounds_match(&file, &sst, time_id, check_keys) {
|
||||
return Err(());
|
||||
}
|
||||
if check_keys
|
||||
&& let Some(range) = file.raw_primary_key_range()
|
||||
&& extract_primary_key_range(&metadata, &sst.region_metadata()) != Some(range)
|
||||
{
|
||||
return Err(());
|
||||
}
|
||||
(!check_rows || footer_proves_visible_rows(&metadata, file.num_rows()))
|
||||
.then_some(())
|
||||
.ok_or(())
|
||||
Ok(!check_rows || footer_proves_visible_rows(&sst.parquet_metadata(), file.num_rows()))
|
||||
}
|
||||
.boxed()
|
||||
}
|
||||
@@ -130,12 +211,32 @@ fn footer_proves_visible_rows(metadata: &ParquetMetaData, manifest_rows: usize)
|
||||
struct Classification {
|
||||
/// Indexes into `ScanInput::files` whose rows are all yielded exactly once.
|
||||
exact: Vec<usize>,
|
||||
/// Indexes of the other files intersecting the query time range.
|
||||
remaining: Vec<usize>,
|
||||
/// Sum of the manifest row counts of `exact`.
|
||||
exact_rows: usize,
|
||||
/// Whether the filter proof depends on key bounds.
|
||||
key_filter: bool,
|
||||
}
|
||||
|
||||
impl Classification {
|
||||
/// Moves the exact files without proof to `remaining`.
|
||||
fn retain_exact(&mut self, input: &ScanInput, proven: &[bool]) {
|
||||
debug_assert_eq!(self.exact.len(), proven.len());
|
||||
let mut exact = Vec::with_capacity(self.exact.len());
|
||||
for (&index, &proven) in self.exact.iter().zip(proven) {
|
||||
if proven {
|
||||
exact.push(index);
|
||||
} else {
|
||||
self.exact_rows -= input.files[index].num_rows();
|
||||
self.remaining.push(index);
|
||||
}
|
||||
}
|
||||
self.exact = exact;
|
||||
self.remaining.sort_unstable();
|
||||
}
|
||||
}
|
||||
|
||||
/// A file is an exact candidate if all of the following hold:
|
||||
/// - The query time range covers it and every other static filter holds for
|
||||
/// all of its rows (see [`AggrFilters`]).
|
||||
@@ -146,11 +247,12 @@ struct Classification {
|
||||
///
|
||||
/// Returns `None` for scans whose visible rows can differ from the sources'
|
||||
/// rows for reasons other than the files themselves.
|
||||
fn classify(input: &ScanInput, request: &ScanRequest) -> Option<Classification> {
|
||||
if !input.memtables.is_empty()
|
||||
|| !input.allows_exact_row_count()
|
||||
|| !request_preserves_rows(request)
|
||||
{
|
||||
fn classify(
|
||||
input: &ScanInput,
|
||||
request: &ScanRequest,
|
||||
allow_partial: bool,
|
||||
) -> Option<Classification> {
|
||||
if !input.allows_exact_row_count() || !request_preserves_rows(request) {
|
||||
return None;
|
||||
}
|
||||
let filters = AggrFilters::new(input.region_metadata(), &request.filters)?;
|
||||
@@ -173,36 +275,73 @@ fn classify(input: &ScanInput, request: &ScanRequest) -> Option<Classification>
|
||||
&& input.file_time_bounds_fit(file)
|
||||
&& (input.region_partition_expr.is_none() || input.should_skip_region_partition(file))
|
||||
&& filters.covers(file);
|
||||
if !candidate {
|
||||
if !candidate && !allow_partial {
|
||||
return None;
|
||||
}
|
||||
intersecting.push(index);
|
||||
intersecting.push((index, candidate));
|
||||
}
|
||||
if !input.append_mode && intersecting.len() > 1 {
|
||||
let mapper = input.primary_key_mapper();
|
||||
let extents: Vec<_> = intersecting
|
||||
.iter()
|
||||
.map(|&index| {
|
||||
let file = &input.files[index];
|
||||
Extent {
|
||||
time: file.time_range(),
|
||||
key: file.primary_key_range(mapper),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
if find_overlaps(&extents).contains(&true) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let exact_rows = intersecting.iter().try_fold(0usize, |rows, &index| {
|
||||
rows.checked_add(input.files[index].num_rows())
|
||||
})?;
|
||||
i64::try_from(exact_rows).ok()?;
|
||||
Some(Classification {
|
||||
exact: intersecting,
|
||||
exact_rows,
|
||||
// Append mode never merges rows, so sources cannot hide each other's rows.
|
||||
let overlaps = if !input.append_mode && intersecting.iter().any(|&(_, candidate)| candidate) {
|
||||
overlapping_files(input, &intersecting)
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
|
||||
let mut classification = Classification {
|
||||
exact: Vec::new(),
|
||||
remaining: Vec::new(),
|
||||
exact_rows: 0,
|
||||
key_filter: filters.codec.is_some(),
|
||||
})
|
||||
};
|
||||
for (position, (index, candidate)) in intersecting.into_iter().enumerate() {
|
||||
let file = &input.files[index];
|
||||
if candidate && !overlaps.get(position).copied().unwrap_or(false) {
|
||||
classification.exact_rows = classification.exact_rows.checked_add(file.num_rows())?;
|
||||
classification.exact.push(index);
|
||||
} else {
|
||||
classification.remaining.push(index);
|
||||
}
|
||||
}
|
||||
i64::try_from(classification.exact_rows).ok()?;
|
||||
Some(classification)
|
||||
}
|
||||
|
||||
/// Returns, for each file in `files`, whether another file or a memtable range
|
||||
/// may hold a row with the same primary key and timestamp.
|
||||
///
|
||||
/// Uses manifest bounds for the overlap check. Preparation verifies the bounds
|
||||
/// of files that can affect the count. Files pruned by the ordinary scan use
|
||||
/// the same manifest bounds without rechecking their footers.
|
||||
///
|
||||
/// A memtable range is bounded by its container, the time range of every row
|
||||
/// it can ever yield (see [`MemRangeBuilder::container_time_range`]), not by
|
||||
/// the rows it held when it was captured: a time-series memtable keeps
|
||||
/// accepting writes into its partition and its ranges read them. A range
|
||||
/// without a known container overlaps every file. Containers carry no key
|
||||
/// bounds, so a file overlapping one in time stays residual.
|
||||
///
|
||||
/// [`MemRangeBuilder::container_time_range`]: crate::read::range::MemRangeBuilder::container_time_range
|
||||
fn overlapping_files(input: &ScanInput, files: &[(usize, bool)]) -> Vec<bool> {
|
||||
let mapper = input.primary_key_mapper();
|
||||
let mut extents: Vec<_> = files
|
||||
.iter()
|
||||
.map(|&(index, _)| {
|
||||
let file = &input.files[index];
|
||||
Extent {
|
||||
time: file.time_range(),
|
||||
key: file.primary_key_range(mapper),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
for memtable in &input.memtables {
|
||||
match memtable.container_time_range() {
|
||||
Some(time) => extents.push(Extent { time, key: None }),
|
||||
None => return vec![true; files.len()],
|
||||
}
|
||||
}
|
||||
let mut overlaps = find_overlaps(&extents);
|
||||
overlaps.truncate(files.len());
|
||||
overlaps
|
||||
}
|
||||
|
||||
/// Static scan predicates a metadata count can absorb.
|
||||
@@ -341,15 +480,19 @@ mod tests {
|
||||
use table::predicate::build_time_range_predicate;
|
||||
|
||||
use super::*;
|
||||
use crate::memtable::{
|
||||
BoxedBatchIterator, BoxedRecordBatchIterator, IterBuilder, MemScanMetrics, MemtableRange,
|
||||
MemtableRangeContext, MemtableStats,
|
||||
};
|
||||
use crate::read::flat_projection::FlatProjectionMapper;
|
||||
use crate::read::range::MemRangeBuilder;
|
||||
use crate::read::scan_region::PredicateGroup;
|
||||
use crate::sst::file::FileMeta;
|
||||
use crate::test_util::memtable_util::metadata_with_primary_key;
|
||||
use crate::test_util::new_noop_file_purger;
|
||||
use crate::test_util::scheduler_util::SchedulerEnv;
|
||||
|
||||
/// Files whose `__op_type` statistics would show deletions. Unit tests
|
||||
/// have no Parquet files; engine tests cover reading the statistics.
|
||||
/// Synthetic delete evidence for tests that only exercise classification.
|
||||
static WITH_DELETES: LazyLock<Mutex<HashSet<FileId>>> = LazyLock::new(Default::default);
|
||||
|
||||
fn file(start: i64, end: i64, rows: u64, no_deletes: bool) -> FileHandle {
|
||||
@@ -407,22 +550,101 @@ mod tests {
|
||||
)
|
||||
}
|
||||
|
||||
fn exact_count(input: &ScanInput, request: &ScanRequest) -> Option<usize> {
|
||||
let classification = classify(input, request)?;
|
||||
let deletes = WITH_DELETES.lock().unwrap();
|
||||
/// Footer evidence for the synthetic files in these classification tests.
|
||||
fn evidence(input: &ScanInput, classification: &Classification) -> Vec<bool> {
|
||||
let with_deletes = WITH_DELETES.lock().unwrap();
|
||||
classification
|
||||
.exact
|
||||
.iter()
|
||||
.all(|&i| input.append_mode || !deletes.contains(&input.files[i].meta_ref().file_id))
|
||||
.then_some(classification.exact_rows)
|
||||
.map(|&index| {
|
||||
input.append_mode || !with_deletes.contains(&input.files[index].meta_ref().file_id)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// [`prepare`] with the test's footer evidence.
|
||||
fn counted(input: &ScanInput, request: &ScanRequest) -> Option<MetadataAggr> {
|
||||
let mut classification = classify(input, request, true)?;
|
||||
let no_deletes = evidence(input, &classification);
|
||||
classification.retain_exact(input, &no_deletes);
|
||||
resolve(input, classification, true)
|
||||
}
|
||||
|
||||
fn exact_count(input: &ScanInput, request: &ScanRequest) -> Option<usize> {
|
||||
match counted(input, request)? {
|
||||
MetadataAggr::Exact(rows) => Some(rows),
|
||||
MetadataAggr::Split(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn classified(input: &ScanInput, request: &ScanRequest) -> Classification {
|
||||
let mut classification = classify(input, request, true).unwrap();
|
||||
let no_deletes = evidence(input, &classification);
|
||||
classification.retain_exact(input, &no_deletes);
|
||||
classification
|
||||
}
|
||||
|
||||
struct EmptyIterBuilder;
|
||||
|
||||
impl IterBuilder for EmptyIterBuilder {
|
||||
fn build(&self, _: Option<MemScanMetrics>) -> crate::error::Result<BoxedBatchIterator> {
|
||||
Ok(Box::new(std::iter::empty()))
|
||||
}
|
||||
|
||||
fn is_record_batch(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn build_record_batch(
|
||||
&self,
|
||||
_: Option<(Timestamp, Timestamp)>,
|
||||
_: Option<MemScanMetrics>,
|
||||
) -> crate::error::Result<BoxedRecordBatchIterator> {
|
||||
Ok(Box::new(std::iter::empty()))
|
||||
}
|
||||
}
|
||||
|
||||
/// A memtable range holding `rows` rows within `data`, inside `container`.
|
||||
fn memtable(data: (i64, i64), container: Option<(i64, i64)>, rows: usize) -> MemRangeBuilder {
|
||||
let ms = |(start, end): (i64, i64)| {
|
||||
(
|
||||
Timestamp::new_millisecond(start),
|
||||
Timestamp::new_millisecond(end),
|
||||
)
|
||||
};
|
||||
let stats = MemtableStats {
|
||||
time_range: Some(ms(data)),
|
||||
num_rows: rows,
|
||||
num_ranges: 1,
|
||||
..Default::default()
|
||||
};
|
||||
let context = Arc::new(MemtableRangeContext::new(
|
||||
0,
|
||||
Box::new(EmptyIterBuilder),
|
||||
Default::default(),
|
||||
));
|
||||
let builder = MemRangeBuilder::new(MemtableRange::new(context, stats.clone()), stats);
|
||||
match container {
|
||||
Some(container) => builder.with_container_time_range(ms(container)),
|
||||
None => builder,
|
||||
}
|
||||
}
|
||||
|
||||
async fn input(files: Vec<FileHandle>, filters: &[Expr]) -> ScanInput {
|
||||
input_with_memtables(files, filters, Vec::new()).await
|
||||
}
|
||||
|
||||
async fn input_with_memtables(
|
||||
files: Vec<FileHandle>,
|
||||
filters: &[Expr],
|
||||
memtables: Vec<MemRangeBuilder>,
|
||||
) -> ScanInput {
|
||||
let env = SchedulerEnv::new().await;
|
||||
let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false));
|
||||
let mapper = FlatProjectionMapper::new(&metadata, [0, 2, 3]).unwrap();
|
||||
ScanInput::builder(env.access_layer.clone(), mapper)
|
||||
.with_files(files)
|
||||
.with_memtables(memtables)
|
||||
.with_predicate(PredicateGroup::new(&metadata, filters).unwrap())
|
||||
.with_time_range(Some(build_time_range_predicate(
|
||||
"ts",
|
||||
@@ -522,6 +744,18 @@ mod tests {
|
||||
};
|
||||
assert_eq!(exact_count(&input, &request), expected, "{request:?}");
|
||||
}
|
||||
|
||||
let filters = vec![k0("x")];
|
||||
let input = input(vec![x(0, 10, 3), mixed()], &filters).await;
|
||||
let request = ScanRequest {
|
||||
filters,
|
||||
..Default::default()
|
||||
};
|
||||
let classification = classified(&input, &request);
|
||||
assert_eq!(
|
||||
(classification.exact_rows, classification.remaining.len()),
|
||||
(3, 1)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -571,6 +805,52 @@ mod tests {
|
||||
input.append_mode = true;
|
||||
assert_eq!(exact_count(&input, &ScanRequest::default()), None);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn test_metadata_aggr_classifies_files() {
|
||||
for (files, exact_rows, exact, remaining) in [
|
||||
(
|
||||
vec![file(0, 10, 3, true), file(20, 30, 2, false)],
|
||||
3,
|
||||
vec![0],
|
||||
vec![1],
|
||||
),
|
||||
// Without key bounds, the wide file overlaps both others in time.
|
||||
(
|
||||
vec![
|
||||
file(0, 100, 3, true),
|
||||
file(5, 8, 2, false),
|
||||
file(20, 30, 4, true),
|
||||
],
|
||||
0,
|
||||
vec![],
|
||||
vec![0, 1, 2],
|
||||
),
|
||||
(
|
||||
vec![file(0, 10, 3, true), file(20, 30, 0, true)],
|
||||
3,
|
||||
vec![0],
|
||||
vec![1],
|
||||
),
|
||||
// Disjoint keys keep time-overlapping files independent.
|
||||
(
|
||||
vec![
|
||||
keyed_file(0, 10, 3, ("a", 0), ("a", 9)),
|
||||
keyed_file(5, 15, 4, ("b", 0), ("b", 9)),
|
||||
keyed_file(8, 9, 1, ("a", 5), ("a", 5)),
|
||||
],
|
||||
4,
|
||||
vec![1],
|
||||
vec![0, 2],
|
||||
),
|
||||
] {
|
||||
let input = input(files, &[]).await;
|
||||
let classification = classified(&input, &ScanRequest::default());
|
||||
assert_eq!(classification.exact_rows, exact_rows);
|
||||
assert_eq!(classification.exact, exact);
|
||||
assert_eq!(classification.remaining, remaining);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_metadata_aggr_reads_op_type_statistics() {
|
||||
use api::v1::OpType;
|
||||
@@ -717,4 +997,247 @@ mod tests {
|
||||
assert_eq!(input.scanner_properties().total_rows_is_exact(), fits);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_metadata_aggr_split_plan() {
|
||||
use api::v1::OpType;
|
||||
use datatypes::arrow::array::{TimestampMillisecondArray, UInt8Array};
|
||||
use datatypes::arrow::record_batch::RecordBatch;
|
||||
use parquet::file::statistics::Statistics;
|
||||
use store_api::storage::consts::OP_TYPE_COLUMN_NAME;
|
||||
|
||||
use crate::access_layer::{Metrics, OperationType, SstWriteRequest, WriteType};
|
||||
use crate::cache::{CacheManager, CacheStrategy};
|
||||
use crate::region::options::MergeMode;
|
||||
use crate::sst::FormatType;
|
||||
use crate::sst::parquet::WriteOptions;
|
||||
use crate::test_util::sst_util::{
|
||||
new_flat_source_from_record_batches, new_record_batch_by_range, sst_region_metadata,
|
||||
};
|
||||
|
||||
let env = SchedulerEnv::new().await;
|
||||
let metadata = Arc::new(sst_region_metadata());
|
||||
let cache = Arc::new(
|
||||
CacheManager::builder()
|
||||
.sst_meta_cache_size(1024 * 1024)
|
||||
.disable_sst_meta_cache_on_write()
|
||||
.build(),
|
||||
);
|
||||
let cache_strategy = CacheStrategy::EnableAll(cache.clone());
|
||||
let put = OpType::Put as u8;
|
||||
let delete = OpType::Delete as u8;
|
||||
let mut files = Vec::new();
|
||||
for (timestamps, operations) in [
|
||||
(vec![10_000, 15_000, 20_000], vec![put; 3]),
|
||||
(vec![0, 8_000], vec![put, delete]),
|
||||
] {
|
||||
let batch = new_record_batch_by_range(&["a", "b"], 0, timestamps.len());
|
||||
let schema = batch.schema();
|
||||
let mut columns = batch.columns().to_vec();
|
||||
columns[schema.index_of("ts").unwrap()] =
|
||||
Arc::new(TimestampMillisecondArray::from(timestamps));
|
||||
let has_delete = operations.contains(&delete);
|
||||
columns[schema.index_of(OP_TYPE_COLUMN_NAME).unwrap()] =
|
||||
Arc::new(UInt8Array::from(operations));
|
||||
let batch = RecordBatch::try_new(schema, columns).unwrap();
|
||||
let source = new_flat_source_from_record_batches(vec![batch])
|
||||
.with_dedup_mode(Some(MergeMode::LastRow));
|
||||
let output = env
|
||||
.access_layer
|
||||
.write_sst(
|
||||
SstWriteRequest {
|
||||
index_build_inputs: None,
|
||||
op_type: OperationType::Flush,
|
||||
metadata: metadata.clone(),
|
||||
source,
|
||||
cache_manager: cache.clone(),
|
||||
max_sequence: None,
|
||||
sst_write_format: FormatType::Flat,
|
||||
preserve_row_sequence: false,
|
||||
index_options: Default::default(),
|
||||
index_config: Default::default(),
|
||||
inverted_index_config: Default::default(),
|
||||
fulltext_index_config: Default::default(),
|
||||
bloom_filter_index_config: Default::default(),
|
||||
},
|
||||
&WriteOptions::default(),
|
||||
&mut Metrics::new(WriteType::Flush),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(output.len(), 1);
|
||||
let info = &output[0];
|
||||
let footer = info.file_metadata.as_ref().unwrap();
|
||||
assert!(has_deduped_sst_marker(footer));
|
||||
assert_eq!(has_only_puts(footer.row_groups()), !has_delete);
|
||||
if has_delete {
|
||||
let op_column = footer
|
||||
.row_group(0)
|
||||
.columns()
|
||||
.iter()
|
||||
.find(|column| column.column_path().string() == OP_TYPE_COLUMN_NAME)
|
||||
.unwrap();
|
||||
let Some(Statistics::Int32(stats)) = op_column.statistics() else {
|
||||
panic!("expected op-type statistics");
|
||||
};
|
||||
assert_eq!(stats.min_opt().copied(), Some(i32::from(put.min(delete))));
|
||||
assert_eq!(stats.max_opt().copied(), Some(i32::from(put.max(delete))));
|
||||
}
|
||||
let (min, max) = extract_primary_key_range(footer, &metadata).unwrap();
|
||||
let file = FileHandle::new(
|
||||
FileMeta {
|
||||
region_id: metadata.region_id,
|
||||
file_id: info.file_id,
|
||||
file_size: info.file_size,
|
||||
time_range: info.time_range,
|
||||
num_rows: info.num_rows as u64,
|
||||
num_row_groups: info.num_row_groups,
|
||||
primary_key_min: Some(min),
|
||||
primary_key_max: Some(max),
|
||||
dedup_marker_trusted: true,
|
||||
format: info.format.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
new_noop_file_purger(),
|
||||
);
|
||||
assert!(file.dedup_marker_trusted());
|
||||
files.push(file);
|
||||
}
|
||||
let residual = &files[1];
|
||||
let build_input = |request: &ScanRequest| {
|
||||
let mapper = FlatProjectionMapper::new(&metadata, [0, 1, 2, 3]).unwrap();
|
||||
ScanInput::builder(env.access_layer.clone(), mapper)
|
||||
.with_files(files.clone())
|
||||
.with_cache(cache_strategy.clone())
|
||||
.with_predicate(PredicateGroup::new(&metadata, &request.filters).unwrap())
|
||||
.with_time_range(Some(build_time_range_predicate(
|
||||
"ts",
|
||||
TimeUnit::Millisecond,
|
||||
&request.filters,
|
||||
)))
|
||||
.build()
|
||||
};
|
||||
let assert_split = |result| {
|
||||
let Some(MetadataAggr::Split(plan)) = result else {
|
||||
panic!("expected metadata and residual sources");
|
||||
};
|
||||
assert_eq!(plan.exact_rows, 3);
|
||||
let [index] = plan.remaining_file_indices.as_slice() else {
|
||||
panic!("expected one residual file");
|
||||
};
|
||||
assert_eq!(files[*index].file_id(), residual.file_id());
|
||||
};
|
||||
let request = ScanRequest {
|
||||
metadata_aggr_hint: true,
|
||||
..Default::default()
|
||||
};
|
||||
let input = build_input(&request);
|
||||
assert_eq!(classify(&input, &request, true).unwrap().exact.len(), 2);
|
||||
assert_split(prepare(&input, &request, true).await);
|
||||
|
||||
let request = ScanRequest {
|
||||
filters: vec![
|
||||
col("ts").gt_eq(lit(ScalarValue::TimestampMillisecond(Some(5_000), None))),
|
||||
],
|
||||
..request
|
||||
};
|
||||
let input = build_input(&request);
|
||||
assert_eq!(classify(&input, &request, true).unwrap().remaining, vec![1]);
|
||||
assert!(!input.can_manifest_prune_file(residual));
|
||||
let footer = env
|
||||
.access_layer
|
||||
.read_sst(residual.clone())
|
||||
.cache(cache_strategy.clone())
|
||||
.read_statistics()
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(bounds_match(
|
||||
residual,
|
||||
&footer,
|
||||
metadata.time_index_column().column_id,
|
||||
true
|
||||
));
|
||||
assert!(
|
||||
cache
|
||||
.get_parquet_meta_data_from_mem_cache(residual.file_id())
|
||||
.await
|
||||
.is_some()
|
||||
);
|
||||
assert_split(prepare(&input, &request, true).await);
|
||||
|
||||
cache.remove_parquet_meta_data(residual.file_id()).await;
|
||||
assert!(
|
||||
cache
|
||||
.get_parquet_meta_data_from_mem_cache(residual.file_id())
|
||||
.await
|
||||
.is_none()
|
||||
);
|
||||
assert!(prepare(&input, &request, true).await.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_metadata_aggr_split_plan_unknown_and_no_exact() {
|
||||
let split = |files| async move {
|
||||
match counted(&input(files, &[]).await, &ScanRequest::default()) {
|
||||
Some(MetadataAggr::Split(plan)) => {
|
||||
Some((plan.exact_rows, plan.remaining_file_indices.len()))
|
||||
}
|
||||
Some(MetadataAggr::Exact(_)) => panic!("unexpected exact count"),
|
||||
None => None,
|
||||
}
|
||||
};
|
||||
// A residual file with an unknown row count is scanned as usual.
|
||||
assert_eq!(
|
||||
split(vec![file(0, 10, 3, true), file(20, 30, 0, true)]).await,
|
||||
Some((3, 1))
|
||||
);
|
||||
// Without an exact file the scan stays unchanged.
|
||||
assert_eq!(
|
||||
split(vec![file(0, 10, 3, true), file(5, 15, 2, true)]).await,
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
/// Memtable ranges are bounded by their containers, never by the rows
|
||||
/// they held when captured.
|
||||
#[tokio::test]
|
||||
async fn test_metadata_aggr_memtable_containers() {
|
||||
let split = |memtables: Vec<MemRangeBuilder>| async move {
|
||||
let files = vec![file(0, 10, 3, true), file(20, 30, 2, true)];
|
||||
let input = input_with_memtables(files, &[], memtables).await;
|
||||
match counted(&input, &ScanRequest::default()) {
|
||||
Some(MetadataAggr::Split(plan)) => {
|
||||
Some((plan.exact_rows, plan.remaining_file_indices.len()))
|
||||
}
|
||||
Some(MetadataAggr::Exact(_)) => panic!("memtables must stay residual"),
|
||||
None => None,
|
||||
}
|
||||
};
|
||||
// The memtable only holds a row at 0, but its container reaches 15,
|
||||
// so a later write may land in the first file's range.
|
||||
assert_eq!(
|
||||
split(vec![memtable((0, 0), Some((0, 15)), 1)]).await,
|
||||
Some((2, 1))
|
||||
);
|
||||
// A container disjoint from both files leaves them exact.
|
||||
assert_eq!(
|
||||
split(vec![memtable((40, 40), Some((40, 49)), 1)]).await,
|
||||
Some((5, 0))
|
||||
);
|
||||
// Touching endpoints overlap; both bounds are inclusive.
|
||||
assert_eq!(
|
||||
split(vec![memtable((31, 31), Some((30, 39)), 1)]).await,
|
||||
Some((3, 1))
|
||||
);
|
||||
// Without a known container no file is exact, whatever the data range.
|
||||
assert_eq!(split(vec![memtable((40, 40), None, 1)]).await, None);
|
||||
assert_eq!(
|
||||
split(vec![
|
||||
memtable((40, 40), Some((40, 49)), 1),
|
||||
memtable((50, 50), None, 1),
|
||||
])
|
||||
.await,
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,7 +30,8 @@ use futures::{StreamExt, TryStreamExt};
|
||||
use snafu::ensure;
|
||||
use store_api::metadata::RegionMetadataRef;
|
||||
use store_api::region_engine::{
|
||||
PartitionRange, PrepareRequest, QueryScanContext, RegionScanner, ScannerProperties,
|
||||
PartitionRange, PrepareRequest, QueryScanContext, RegionScanner, RegionScannerRef,
|
||||
ScannerProperties, StatisticsSplit,
|
||||
};
|
||||
use store_api::storage::TimeSeriesRowSelector;
|
||||
use tokio::sync::Semaphore;
|
||||
@@ -43,7 +44,7 @@ use crate::read::last_row::FlatLastRowReader;
|
||||
use crate::read::pruner::{PartitionPruner, Pruner};
|
||||
use crate::read::range::RangeMeta;
|
||||
use crate::read::range_cache::{CachedRangeReader, build_range_cache_key};
|
||||
use crate::read::scan_region::{ScanInput, StreamContext};
|
||||
use crate::read::scan_region::{ScanInput, StatisticsSplitPlan, StreamContext};
|
||||
use crate::read::scan_util::{
|
||||
BATCH_SIZE_THRESHOLD, MIN_COMPACTION_SPLIT_ROWS, PartitionMetrics, PartitionMetricsList,
|
||||
SplitRecordBatchStream, compute_parallel_channel_size, prepare_flat_mem_stream,
|
||||
@@ -72,6 +73,8 @@ pub(crate) enum FlatReadMode {
|
||||
pub struct SeqScan {
|
||||
/// Shares narthex candidate discovery across batch-output partitions.
|
||||
narthex_preparation: Option<Arc<crate::read::series_scan::prepared::Preparation>>,
|
||||
/// Exact and residual sources prepared for a scalar COUNT, if any.
|
||||
statistics_split: Option<StatisticsSplitPlan>,
|
||||
/// Properties of the scanner.
|
||||
properties: ScannerProperties,
|
||||
/// Context of streams.
|
||||
@@ -87,8 +90,13 @@ impl SeqScan {
|
||||
/// Creates a new [SeqScan] with the given input.
|
||||
/// If `input.compaction` is true, the scanner will not attempt to split ranges.
|
||||
pub(crate) fn new(input: ScanInput) -> Self {
|
||||
let mut properties = input.scanner_properties();
|
||||
let stream_ctx = Arc::new(StreamContext::seq_scan_ctx(input));
|
||||
Self::with_stream_ctx(StreamContext::seq_scan_ctx(input))
|
||||
}
|
||||
|
||||
fn with_stream_ctx(mut stream_ctx: StreamContext) -> Self {
|
||||
let statistics_split = stream_ctx.input.statistics_split.take();
|
||||
let mut properties = stream_ctx.input.scanner_properties();
|
||||
let stream_ctx = Arc::new(stream_ctx);
|
||||
properties.partitions = vec![stream_ctx.partition_ranges()];
|
||||
|
||||
// Create the shared pruner with number of workers equal to CPU cores.
|
||||
@@ -100,6 +108,7 @@ impl SeqScan {
|
||||
.input
|
||||
.requires_narthex_preparation()
|
||||
.then(|| Arc::new(crate::read::series_scan::prepared::Preparation::default())),
|
||||
statistics_split,
|
||||
properties,
|
||||
stream_ctx,
|
||||
pruner,
|
||||
@@ -107,6 +116,40 @@ impl SeqScan {
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps the original deduplication groups when removing exact files.
|
||||
fn residual_scanner(&self, remaining_file_indices: &[usize]) -> Option<RegionScannerRef> {
|
||||
let input = &self.stream_ctx.input;
|
||||
let num_memtables = input.num_memtables();
|
||||
let mut mapping: Vec<_> = (0..num_memtables).map(Some).collect();
|
||||
mapping.resize(num_memtables + input.num_files(), None);
|
||||
let files = remaining_file_indices
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(new, &old)| {
|
||||
mapping[num_memtables + old] = Some(num_memtables + new);
|
||||
input.files[old].clone()
|
||||
})
|
||||
.collect();
|
||||
let residual = input.with_sources(files, input.memtables.clone())?;
|
||||
let ranges = self
|
||||
.stream_ctx
|
||||
.ranges
|
||||
.iter()
|
||||
.filter_map(|range| range.remap_sources(&mapping, &residual))
|
||||
.collect();
|
||||
let mut part = Self::with_stream_ctx(StreamContext::with_ranges(
|
||||
residual,
|
||||
ranges,
|
||||
self.stream_ctx.query_start,
|
||||
));
|
||||
part.properties
|
||||
.set_logical_region(self.properties.is_logical_region());
|
||||
if let Some(region_id) = self.properties.query_load_region_id() {
|
||||
part.properties.set_query_load_region_id(region_id);
|
||||
}
|
||||
Some(Box::new(part))
|
||||
}
|
||||
|
||||
/// Builds a stream for the query.
|
||||
///
|
||||
/// The returned stream is not partitioned and will contains all the data. If want
|
||||
@@ -635,6 +678,17 @@ impl RegionScanner for SeqScan {
|
||||
"SeqScan"
|
||||
}
|
||||
|
||||
fn take_statistics_split(&mut self) -> Option<StatisticsSplit> {
|
||||
if self.properties.distinguish_partition_range {
|
||||
return None;
|
||||
}
|
||||
let plan = self.statistics_split.take()?;
|
||||
Some(StatisticsSplit {
|
||||
exact_rows: plan.exact_rows,
|
||||
residual: self.residual_scanner(&plan.remaining_file_indices)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn properties(&self) -> &ScannerProperties {
|
||||
&self.properties
|
||||
}
|
||||
@@ -661,6 +715,10 @@ impl RegionScanner for SeqScan {
|
||||
if let Some(preparation) = &mut self.narthex_preparation {
|
||||
*preparation = Arc::new(crate::read::series_scan::prepared::Preparation::default());
|
||||
}
|
||||
if self.statistics_split.is_some() && !request.preserves_ranges(&self.properties.partitions)
|
||||
{
|
||||
self.statistics_split = None;
|
||||
}
|
||||
self.properties.prepare(request);
|
||||
|
||||
self.check_scan_limit().map_err(BoxedError::new)?;
|
||||
@@ -686,7 +744,9 @@ impl RegionScanner for SeqScan {
|
||||
// rather than claiming pushdown that discovery cannot honor.
|
||||
return vec![false; filter_exprs.len()];
|
||||
}
|
||||
// Prepared counts did not see the dynamic predicate.
|
||||
self.properties.clear_exact_num_rows();
|
||||
self.statistics_split = None;
|
||||
self.stream_ctx.add_dyn_filter_to_predicate(filter_exprs)
|
||||
}
|
||||
|
||||
|
||||
@@ -511,6 +511,13 @@ pub struct PrepareRequest {
|
||||
}
|
||||
|
||||
impl PrepareRequest {
|
||||
/// Returns whether this request preserves all ranges of the given layout.
|
||||
pub fn preserves_ranges(&self, current: &[Vec<PartitionRange>]) -> bool {
|
||||
self.ranges
|
||||
.as_ref()
|
||||
.is_none_or(|replacement| same_partition_ranges(current, replacement))
|
||||
}
|
||||
|
||||
/// Sets the ranges.
|
||||
pub fn with_ranges(mut self, ranges: Vec<Vec<PartitionRange>>) -> Self {
|
||||
self.ranges = Some(ranges);
|
||||
@@ -683,6 +690,19 @@ pub trait PreparedSeriesSource: Send + Sync {
|
||||
) -> Result<SendableRawSeriesStream, BoxedError>;
|
||||
}
|
||||
|
||||
/// A scan split into sources counted from metadata and a residual scan.
|
||||
///
|
||||
/// The two parts are source-disjoint: no row the residual scan yields is
|
||||
/// counted in `exact_rows`, so a scalar COUNT of the original scan is
|
||||
/// `exact_rows` plus the COUNT of the residual scan.
|
||||
#[derive(Debug)]
|
||||
pub struct StatisticsSplit {
|
||||
/// Query-visible rows of the sources answered from metadata.
|
||||
pub exact_rows: usize,
|
||||
/// All remaining sources, merged and deduplicated together.
|
||||
pub residual: RegionScannerRef,
|
||||
}
|
||||
|
||||
/// A scanner that provides a way to scan the region concurrently.
|
||||
///
|
||||
/// The scanner splits the region into partitions so that each partition can be scanned concurrently.
|
||||
@@ -690,6 +710,14 @@ pub trait PreparedSeriesSource: Send + Sync {
|
||||
pub trait RegionScanner: Debug + DisplayAs + Send {
|
||||
fn name(&self) -> &str;
|
||||
|
||||
/// Takes the source split an engine prepared for a scalar COUNT of a scan
|
||||
/// hinted with `metadata_aggr_hint`. On success the caller must replace
|
||||
/// this scanner with the residual scan and add the exact rows once.
|
||||
/// Partition assignments must use the residual scanner's ranges.
|
||||
fn take_statistics_split(&mut self) -> Option<StatisticsSplit> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Returns the properties of the scanner.
|
||||
fn properties(&self) -> &ScannerProperties;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user