mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 05:34:02 +00:00
feat(mito2): split metadata COUNT from residual scans
Signed-off-by: aumnertic <aumnertic@gmail.com>
This commit is contained in:
@@ -12,8 +12,8 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use async_trait::async_trait;
|
||||
@@ -30,12 +30,13 @@ use datafusion_common::stats::Precision;
|
||||
use datafusion_expr::{col, lit};
|
||||
use datatypes::arrow::datatypes::SchemaRef;
|
||||
use object_store::layers::mock::MockLayerBuilder;
|
||||
use store_api::region_engine::RegionEngine;
|
||||
use store_api::region_engine::{RegionEngine, RegionScannerRef};
|
||||
use store_api::region_request::{RegionDeleteRequest, RegionPutRequest, RegionRequest};
|
||||
use store_api::storage::{RegionId, ScanRequest, TimeSeriesRowSelector};
|
||||
use table::table::scan::RegionScanExec;
|
||||
|
||||
use crate::config::MitoConfig;
|
||||
use crate::engine::MitoEngine;
|
||||
use crate::engine::compaction_test::{compact, delete_and_flush, put_and_flush};
|
||||
use crate::test_util::{self, CreateRequestBuilder, TestEnv};
|
||||
|
||||
@@ -459,11 +460,16 @@ async fn test_metadata_aggr_replacement_with_duplicate_rows_falls_back() {
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let scan = engine
|
||||
let mut scan = engine
|
||||
.handle_query(region_id, request.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(scan.properties().exact_num_rows(), None);
|
||||
let split = scan
|
||||
.take_statistics_split()
|
||||
.expect("the other SST is certified");
|
||||
assert_eq!(split.exact_rows, 3);
|
||||
assert_eq!(scanned_rows(split.residual, request.clone()).await, 2);
|
||||
for request in [request, ScanRequest::default()] {
|
||||
let rows = common_recordbatch::RecordBatches::try_collect(
|
||||
engine.scan_to_stream(region_id, request).await.unwrap(),
|
||||
@@ -666,6 +672,9 @@ async fn test_metadata_aggr_statistics_follow_row_visibility() {
|
||||
.handle_query(region_id, request.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
if append {
|
||||
assert_eq!(scan.properties().exact_num_rows(), None);
|
||||
}
|
||||
let plan = RegionScanExec::new(scan, request.clone(), None).unwrap();
|
||||
let row_count = |plan: &RegionScanExec| {
|
||||
StatisticsContext::new()
|
||||
@@ -788,3 +797,350 @@ async fn test_metadata_aggr_strict_bound_past_max() {
|
||||
}
|
||||
engine.stop().await.unwrap();
|
||||
}
|
||||
|
||||
/// Rows a scanner yields.
|
||||
async fn scanned_rows(scanner: RegionScannerRef, request: ScanRequest) -> usize {
|
||||
let plan = Arc::new(RegionScanExec::new(scanner, request, None).unwrap());
|
||||
datafusion::physical_plan::collect(plan, SessionContext::new().task_ctx())
|
||||
.await
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|batch| batch.num_rows())
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Rows a plain scan of the region yields for `request`.
|
||||
async fn plain_rows(engine: &MitoEngine, region_id: RegionId, request: ScanRequest) -> usize {
|
||||
let request = ScanRequest {
|
||||
metadata_aggr_hint: false,
|
||||
..request
|
||||
};
|
||||
let scanner = engine
|
||||
.handle_query(region_id, request.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
scanned_rows(scanner, request).await
|
||||
}
|
||||
|
||||
/// The rows a hinted scan counts from metadata and the rows its residual scan
|
||||
/// yields, or `None` if it does not split.
|
||||
async fn split_rows(
|
||||
engine: &MitoEngine,
|
||||
region_id: RegionId,
|
||||
request: ScanRequest,
|
||||
) -> Option<(usize, usize)> {
|
||||
let mut scanner = engine
|
||||
.handle_query(region_id, request.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
let split = scanner.take_statistics_split()?;
|
||||
Some((
|
||||
split.exact_rows,
|
||||
scanned_rows(split.residual, request).await,
|
||||
))
|
||||
}
|
||||
|
||||
/// Metadata rows and residual rows of the hinted scans of
|
||||
/// [`test_metadata_aggr_fourteen_day_workload`], in its order.
|
||||
struct FourteenDaySplits {
|
||||
whole: Option<(usize, usize)>,
|
||||
from_day_7: Option<(usize, usize)>,
|
||||
days_5_to_10: Option<(usize, usize)>,
|
||||
after_put: Option<(usize, usize)>,
|
||||
after_delete: Option<(usize, usize)>,
|
||||
}
|
||||
|
||||
/// Days 0..7 are compacted into one file, days 7..13 are separate flushes,
|
||||
/// and day 13 is still in the memtable. The memtable partition follows the
|
||||
/// 7-day compaction window, `[7d, 14d)`.
|
||||
///
|
||||
/// - A time-series memtable range is bounded by that partition, so it keeps
|
||||
/// the files of days 7..13 residual. Only the compacted file is counted
|
||||
/// from metadata.
|
||||
/// - A bulk memtable range is bounded by the part it captured, day 13, so
|
||||
/// every file is counted from metadata.
|
||||
#[rstest::rstest]
|
||||
#[case::time_series("primary_key", "time_series", FourteenDaySplits {
|
||||
whole: Some((7_000, 7_000)),
|
||||
from_day_7: None,
|
||||
// The memtable lies outside the query range, so it is not captured and
|
||||
// bounds nothing; the compacted file is only partly covered.
|
||||
days_5_to_10: Some((3_000, 2_000)),
|
||||
// The put creates partition `[14d, 21d)`, the delete `[0, 7d)`.
|
||||
after_put: Some((7_000, 7_001)),
|
||||
after_delete: None,
|
||||
})]
|
||||
#[case::bulk("flat", "bulk", FourteenDaySplits {
|
||||
whole: Some((13_000, 1_000)),
|
||||
from_day_7: Some((6_000, 1_000)),
|
||||
days_5_to_10: Some((3_000, 2_000)),
|
||||
after_put: Some((13_000, 1_001)),
|
||||
// The deletion's part overlaps the compacted file only.
|
||||
after_delete: Some((6_000, 8_000)),
|
||||
})]
|
||||
#[tokio::test]
|
||||
async fn test_metadata_aggr_fourteen_day_workload(
|
||||
#[case] sst_format: &str,
|
||||
#[case] memtable: &str,
|
||||
#[case] splits: FourteenDaySplits,
|
||||
) {
|
||||
use api::v1::value::ValueData;
|
||||
use store_api::region_request::RegionFlushRequest;
|
||||
|
||||
const DAY_SECONDS: usize = 86_400;
|
||||
let reads = Arc::new(Mutex::new(Vec::<String>::new()));
|
||||
let observed = reads.clone();
|
||||
let layer = MockLayerBuilder::default()
|
||||
.reader_factory(Arc::new(move |path, _, inner| {
|
||||
if path.ends_with(".parquet") {
|
||||
observed.lock().unwrap().push(path.to_string());
|
||||
}
|
||||
inner
|
||||
}))
|
||||
.build()
|
||||
.unwrap();
|
||||
let mut env = TestEnv::new().await.with_mock_layer(layer);
|
||||
let engine = env
|
||||
.create_engine(MitoConfig {
|
||||
experimental_metadata_aggr: true,
|
||||
min_compaction_interval: Duration::from_secs(3600),
|
||||
schedule_compaction_after_edit: false,
|
||||
..Default::default()
|
||||
})
|
||||
.await;
|
||||
let region_id = RegionId::new(2, 1);
|
||||
let create = CreateRequestBuilder::new()
|
||||
.insert_option("compaction.type", "twcs")
|
||||
.insert_option("compaction.twcs.time_window", "7d")
|
||||
.insert_option("compaction.twcs.trigger_file_num", "2")
|
||||
.insert_option("sst_format", sst_format)
|
||||
.insert_option("memtable.type", memtable)
|
||||
.build();
|
||||
let schema = test_util::rows_schema(&create);
|
||||
engine
|
||||
.handle_request(region_id, RegionRequest::Create(create))
|
||||
.await
|
||||
.unwrap();
|
||||
let day_rows = |day: usize| {
|
||||
let mut rows = test_util::build_rows_for_key("a", 0, 1000, 0);
|
||||
for (minute, row) in rows.iter_mut().enumerate() {
|
||||
row.values[2].value_data = Some(ValueData::TimestampMillisecondValue(
|
||||
((day * DAY_SECONDS + minute * 60) * 1000) as i64,
|
||||
));
|
||||
}
|
||||
api::v1::Rows {
|
||||
schema: schema.clone(),
|
||||
rows,
|
||||
}
|
||||
};
|
||||
for day in 0..14 {
|
||||
test_util::put_rows(&engine, region_id, day_rows(day)).await;
|
||||
if day < 13 {
|
||||
engine
|
||||
.handle_request(
|
||||
region_id,
|
||||
RegionRequest::Flush(RegionFlushRequest::default()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
if day == 6 {
|
||||
compact(&engine, region_id).await;
|
||||
}
|
||||
}
|
||||
|
||||
// Ordinary scans are never split, even with the option enabled.
|
||||
let mut scanner = engine
|
||||
.handle_query(region_id, ScanRequest::default())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(scanner.take_statistics_split().is_none());
|
||||
|
||||
// The residual scanner keeps the properties the metric engine sets after
|
||||
// Mito returns the scanner. This hinted scan also loads the files' metadata.
|
||||
let hinted = ScanRequest {
|
||||
metadata_aggr_hint: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut scanner = engine
|
||||
.handle_query(region_id, hinted.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
scanner.set_logical_region(true);
|
||||
scanner.set_query_load_region_id(RegionId::new(2, 7));
|
||||
let split = scanner.take_statistics_split().unwrap();
|
||||
assert_eq!(Some(split.exact_rows), splits.whole.map(|(exact, _)| exact));
|
||||
assert!(split.residual.properties().is_logical_region());
|
||||
assert_eq!(
|
||||
split.residual.properties().query_load_region_id(),
|
||||
Some(RegionId::new(2, 7))
|
||||
);
|
||||
assert_eq!(split.residual.properties().exact_num_rows(), None);
|
||||
drop(split);
|
||||
|
||||
// A dynamic predicate invalidates the prepared split.
|
||||
let mut scanner = engine
|
||||
.handle_query(region_id, hinted.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
scanner.add_dyn_filter_to_predicate(vec![datafusion::physical_plan::expressions::lit(true)]);
|
||||
assert!(scanner.take_statistics_split().is_none());
|
||||
|
||||
let ts = |day: i64| {
|
||||
lit(ScalarValue::TimestampMillisecond(
|
||||
Some(day * 86_400_000),
|
||||
None,
|
||||
))
|
||||
};
|
||||
// (filters, count, exact count, metadata and residual rows of a split)
|
||||
for (filters, expected_count, exact, split) in [
|
||||
(vec![], 14_000, None, splits.whole),
|
||||
// The memtable lies outside the query range, so it is not scanned.
|
||||
(vec![col("ts").lt(ts(7))], 7_000, Some(7_000), None),
|
||||
(vec![col("ts").gt_eq(ts(7))], 7_000, None, splits.from_day_7),
|
||||
(
|
||||
vec![col("ts").gt_eq(ts(5)).and(col("ts").lt(ts(10)))],
|
||||
5_000,
|
||||
None,
|
||||
splits.days_5_to_10,
|
||||
),
|
||||
] {
|
||||
reads.lock().unwrap().clear();
|
||||
let request = ScanRequest {
|
||||
filters,
|
||||
..hinted.clone()
|
||||
};
|
||||
let scanner = engine
|
||||
.handle_query(region_id, request.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(scanner.properties().exact_num_rows(), exact, "{request:?}");
|
||||
// The files' metadata is cached, so neither proof opens an SST.
|
||||
let paths = reads.lock().unwrap().clone();
|
||||
assert!(paths.is_empty(), "COUNT opened SSTs: {paths:?}");
|
||||
assert_eq!(
|
||||
split_rows(&engine, region_id, request.clone()).await,
|
||||
split,
|
||||
"{request:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
plain_rows(&engine, region_id, request).await,
|
||||
expected_count
|
||||
);
|
||||
}
|
||||
|
||||
for (timestamp, delete, expected, split) in [
|
||||
(15 * 86_400_000, false, 14_001, splits.after_put),
|
||||
(86_400_000, true, 14_000, splits.after_delete),
|
||||
] {
|
||||
let mut rows = test_util::build_rows_for_key("a", 0, 1, 0);
|
||||
rows[0].values[2].value_data = Some(ValueData::TimestampMillisecondValue(timestamp));
|
||||
let rows = api::v1::Rows {
|
||||
schema: schema.clone(),
|
||||
rows,
|
||||
};
|
||||
let request = if delete {
|
||||
RegionRequest::Delete(RegionDeleteRequest {
|
||||
rows,
|
||||
hint: None,
|
||||
partition_expr_version: None,
|
||||
})
|
||||
} else {
|
||||
RegionRequest::Put(RegionPutRequest {
|
||||
rows,
|
||||
hint: None,
|
||||
partition_expr_version: None,
|
||||
skip_wal: false,
|
||||
})
|
||||
};
|
||||
engine.handle_request(region_id, request).await.unwrap();
|
||||
assert_eq!(split_rows(&engine, region_id, hinted.clone()).await, split);
|
||||
assert_eq!(
|
||||
plain_rows(&engine, region_id, hinted.clone()).await,
|
||||
expected
|
||||
);
|
||||
}
|
||||
engine.stop().await.unwrap();
|
||||
}
|
||||
|
||||
/// A captured memtable range bounds its rows by its container, not by the
|
||||
/// rows present when it was captured. File A holds `a@100`, file B holds
|
||||
/// `b@0` and `b@200`, and the memtable holds `a@memtable_second` when the
|
||||
/// split is prepared. `a@100` is written again before the split executes.
|
||||
///
|
||||
/// - A time-series range reads its live series set, so it sees the later
|
||||
/// write. In the same daily partition A overlaps the container and stays
|
||||
/// residual, although it is disjoint from the memtable's rows. In another
|
||||
/// partition A is exact, and the later write lands in a partition the scan
|
||||
/// never captured.
|
||||
/// - A bulk range reads the parts captured with it, so A is exact even in the
|
||||
/// same partition, and the later write lands in a part the scan never read.
|
||||
#[rstest::rstest]
|
||||
#[case::time_series_same_partition("primary_key", "time_series", 0, None)]
|
||||
#[case::time_series_other_partition("primary_key", "time_series", 2 * 86_400, Some((1, 1)))]
|
||||
#[case::bulk_same_partition("flat", "bulk", 0, Some((1, 1)))]
|
||||
#[tokio::test]
|
||||
async fn test_metadata_aggr_split_bounds_memtables_by_container(
|
||||
#[case] sst_format: &str,
|
||||
#[case] memtable: &str,
|
||||
#[case] memtable_second: usize,
|
||||
#[case] split: Option<(usize, usize)>,
|
||||
) {
|
||||
let mut env = TestEnv::new().await;
|
||||
let engine = env
|
||||
.create_engine(MitoConfig {
|
||||
experimental_metadata_aggr: true,
|
||||
..Default::default()
|
||||
})
|
||||
.await;
|
||||
let region_id = RegionId::new(1, 1);
|
||||
let create = CreateRequestBuilder::new()
|
||||
.insert_option("sst_format", sst_format)
|
||||
.insert_option("memtable.type", memtable)
|
||||
.build();
|
||||
let schema = test_util::rows_schema(&create);
|
||||
engine
|
||||
.handle_request(region_id, RegionRequest::Create(create))
|
||||
.await
|
||||
.unwrap();
|
||||
let rows = |key: &str, seconds: &[usize]| api::v1::Rows {
|
||||
schema: schema.clone(),
|
||||
rows: seconds
|
||||
.iter()
|
||||
.flat_map(|&second| test_util::build_rows_for_key(key, second, second + 1, 0))
|
||||
.collect(),
|
||||
};
|
||||
put_and_flush_rows(&engine, region_id, rows("a", &[100])).await;
|
||||
put_and_flush_rows(&engine, region_id, rows("b", &[0, 200])).await;
|
||||
test_util::put_rows(&engine, region_id, rows("a", &[memtable_second])).await;
|
||||
|
||||
let request = ScanRequest {
|
||||
filters: vec![col("tag_0").eq(lit("a"))],
|
||||
metadata_aggr_hint: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut scanner = engine
|
||||
.handle_query(region_id, request.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
let prepared = scanner.take_statistics_split();
|
||||
// Written after the split is prepared, before it executes.
|
||||
test_util::put_rows(&engine, region_id, rows("a", &[100])).await;
|
||||
|
||||
let actual = match prepared {
|
||||
Some(prepared) => Some((
|
||||
prepared.exact_rows,
|
||||
scanned_rows(prepared.residual, request.clone()).await,
|
||||
)),
|
||||
None => None,
|
||||
};
|
||||
assert_eq!(actual, split);
|
||||
// Whether or not the scan splits, `a@100` is counted once.
|
||||
assert_eq!(plain_rows(&engine, region_id, request).await, 2);
|
||||
engine.stop().await.unwrap();
|
||||
}
|
||||
|
||||
async fn put_and_flush_rows(engine: &MitoEngine, region_id: RegionId, rows: api::v1::Rows) {
|
||||
test_util::put_rows(engine, region_id, rows).await;
|
||||
test_util::flush_region(engine, region_id, None).await;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
@@ -2460,7 +2460,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()
|
||||
@@ -2864,7 +2864,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 {
|
||||
|
||||
@@ -848,12 +848,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.
|
||||
@@ -861,6 +877,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)]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -532,12 +532,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;
|
||||
|
||||
@@ -514,6 +515,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();
|
||||
@@ -571,7 +575,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.
|
||||
@@ -592,7 +596,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;
|
||||
@@ -612,9 +616,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,
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -716,8 +729,17 @@ 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 {
|
||||
input.exact_num_rows = aggr::prepare(&input, &self.request).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())
|
||||
{
|
||||
match aggr::prepare(&input, &self.request, allow_partial).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)
|
||||
}
|
||||
@@ -1018,6 +1040,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.
|
||||
pub(crate) series_index: Option<SeriesIndexReadContext>,
|
||||
/// Whether to ignore range indexes while retaining series-index candidate discovery.
|
||||
@@ -1101,6 +1125,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>,
|
||||
@@ -1118,6 +1143,63 @@ 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,
|
||||
series_index: self.series_index.clone(),
|
||||
page_index_policy: self.page_index_policy,
|
||||
ignore_range_index: self.ignore_range_index,
|
||||
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,
|
||||
time_pruned_files: self.time_pruned_files.clone(),
|
||||
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(
|
||||
@@ -1128,6 +1210,7 @@ impl ScanInput {
|
||||
input: ScanInput {
|
||||
exact_num_rows: None,
|
||||
row_preserving_request: true,
|
||||
statistics_split: None,
|
||||
series_index: None,
|
||||
page_index_policy: None,
|
||||
ignore_range_index: false,
|
||||
|
||||
@@ -40,19 +40,41 @@ use crate::read::scan_region::{ScanInput, request_preserves_rows};
|
||||
use crate::sst::file::FileHandle;
|
||||
use crate::sst::parquet::metadata::{DEDUPED_SST_KEY, extract_primary_key_range, 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> {
|
||||
if !input.memtables.is_empty() {
|
||||
/// 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),
|
||||
}
|
||||
|
||||
/// 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,
|
||||
/// Other files intersecting the query time range. Memtable ranges always
|
||||
/// stay in the residual scan.
|
||||
pub(crate) remaining_files: Vec<FileHandle>,
|
||||
}
|
||||
|
||||
/// 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, false)?;
|
||||
if !classification.remaining.is_empty() {
|
||||
let classification = classify(input, request, allow_partial)?;
|
||||
if !allow_partial && !classification.remaining.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let evidence = read_file_evidence(input, &classification).await?;
|
||||
resolve(input, classification, &evidence)
|
||||
resolve(input, classification, &evidence, allow_partial)
|
||||
}
|
||||
|
||||
/// Applies the footer evidence of the exact candidates.
|
||||
@@ -60,10 +82,23 @@ fn resolve(
|
||||
input: &ScanInput,
|
||||
mut classification: Classification,
|
||||
evidence: &[bool],
|
||||
) -> Option<usize> {
|
||||
allow_partial: bool,
|
||||
) -> Option<MetadataAggr> {
|
||||
classification.retain_exact(input, evidence);
|
||||
(classification.remaining.is_empty() && input.memtables.is_empty())
|
||||
.then_some(classification.exact_rows)
|
||||
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_files: classification
|
||||
.remaining
|
||||
.iter()
|
||||
.map(|&i| input.files[i].clone())
|
||||
.collect(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Returns whether each candidate yields all of its physical rows once.
|
||||
@@ -295,8 +330,17 @@ fn classify(
|
||||
Some(classification)
|
||||
}
|
||||
|
||||
/// Returns, for each file in `files`, whether another file or a memtable may
|
||||
/// hold a row with the same primary key and timestamp.
|
||||
/// Returns, for each file in `files`, whether another file or a memtable range
|
||||
/// may hold a row with the same primary key and timestamp.
|
||||
///
|
||||
/// 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
|
||||
@@ -309,12 +353,9 @@ fn overlapping_files(input: &ScanInput, files: &[(usize, bool)]) -> Vec<bool> {
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
// Memtable key bounds are unknown.
|
||||
for memtable in &input.memtables {
|
||||
let stats = memtable.stats();
|
||||
match stats.time_range {
|
||||
match memtable.container_time_range() {
|
||||
Some(time) => extents.push(Extent { time, key: None }),
|
||||
None if stats.num_rows == 0 => {}
|
||||
None => return vec![true; files.len()],
|
||||
}
|
||||
}
|
||||
@@ -459,7 +500,12 @@ 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;
|
||||
@@ -535,10 +581,18 @@ mod tests {
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn exact_count(input: &ScanInput, request: &ScanRequest) -> Option<usize> {
|
||||
let classification = classify(input, request, false)?;
|
||||
/// [`prepare`] with the test's footer evidence.
|
||||
fn counted(input: &ScanInput, request: &ScanRequest) -> Option<MetadataAggr> {
|
||||
let classification = classify(input, request, true)?;
|
||||
let no_deletes = evidence(input, &classification);
|
||||
resolve(input, classification, &no_deletes)
|
||||
resolve(input, classification, &no_deletes, 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 {
|
||||
@@ -548,12 +602,67 @@ mod tests {
|
||||
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",
|
||||
@@ -885,4 +994,75 @@ mod tests {
|
||||
assert_eq!(input.scanner_properties().total_rows_is_exact(), fits);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_metadata_aggr_split_plan() {
|
||||
let split = |files| async move {
|
||||
match counted(&input(files, &[]).await, &ScanRequest::default()) {
|
||||
Some(MetadataAggr::Split(plan)) => {
|
||||
Some((plan.exact_rows, plan.remaining_files.len()))
|
||||
}
|
||||
Some(MetadataAggr::Exact(_)) => panic!("unexpected exact count"),
|
||||
None => None,
|
||||
}
|
||||
};
|
||||
// The second file holds a deletion.
|
||||
assert_eq!(
|
||||
split(vec![file(0, 10, 3, true), file(20, 30, 2, false)]).await,
|
||||
Some((3, 1))
|
||||
);
|
||||
// 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, false)]).await,
|
||||
Some((3, 1))
|
||||
);
|
||||
// Without an exact file the scan stays unchanged.
|
||||
assert_eq!(
|
||||
split(vec![file(0, 10, 3, false), file(20, 30, 2, false)]).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_files.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.
|
||||
@@ -86,7 +89,8 @@ pub struct SeqScan {
|
||||
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 {
|
||||
pub(crate) fn new(mut input: ScanInput) -> Self {
|
||||
let statistics_split = input.statistics_split.take();
|
||||
let mut properties = input.scanner_properties();
|
||||
let stream_ctx = Arc::new(StreamContext::seq_scan_ctx(input));
|
||||
properties.partitions = vec![stream_ctx.partition_ranges()];
|
||||
@@ -100,6 +104,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 +112,19 @@ impl SeqScan {
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a scanner over a subset of this scan's sources. It keeps the
|
||||
/// properties callers set after construction, such as the metric engine's
|
||||
/// logical region and query-load attribution.
|
||||
fn split_part(&self, input: ScanInput) -> RegionScannerRef {
|
||||
let mut part = Self::new(input);
|
||||
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);
|
||||
}
|
||||
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 +653,16 @@ impl RegionScanner for SeqScan {
|
||||
"SeqScan"
|
||||
}
|
||||
|
||||
fn take_statistics_split(&mut self) -> Option<StatisticsSplit> {
|
||||
let plan = self.statistics_split.take()?;
|
||||
let input = &self.stream_ctx.input;
|
||||
let residual = input.with_sources(plan.remaining_files, input.memtables.clone())?;
|
||||
Some(StatisticsSplit {
|
||||
exact_rows: plan.exact_rows,
|
||||
residual: self.split_part(residual),
|
||||
})
|
||||
}
|
||||
|
||||
fn properties(&self) -> &ScannerProperties {
|
||||
&self.properties
|
||||
}
|
||||
@@ -661,6 +689,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 +718,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)
|
||||
}
|
||||
|
||||
|
||||
@@ -510,6 +510,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);
|
||||
@@ -682,6 +689,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.
|
||||
@@ -689,6 +709,13 @@ 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.
|
||||
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