diff --git a/src/query/src/optimizer.rs b/src/query/src/optimizer.rs index 289b07ce748..8864ab22617 100644 --- a/src/query/src/optimizer.rs +++ b/src/query/src/optimizer.rs @@ -19,6 +19,7 @@ pub mod count_wildcard; pub mod enforce_sorting; pub(crate) mod expr_depth; pub mod global_limit; +pub mod global_topk; pub(crate) mod infer_aggregate_input_bounds; pub(crate) mod insert_assignment; pub(crate) mod json_schema_concretize; @@ -33,6 +34,7 @@ pub(crate) mod sst_manifest_aggregate; pub mod string_normalization; #[cfg(test)] pub(crate) mod test_util; +pub mod topk_filter_batch; pub mod transcribe_atat; pub mod type_conversion; pub mod windowed_sort; diff --git a/src/query/src/optimizer/global_topk.rs b/src/query/src/optimizer/global_topk.rs new file mode 100644 index 00000000000..939a560a881 --- /dev/null +++ b/src/query/src/optimizer/global_topk.rs @@ -0,0 +1,287 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::sync::Arc; + +use datafusion::config::ConfigOptions; +use datafusion::physical_optimizer::PhysicalOptimizerRule; +use datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec; +use datafusion::physical_plan::coop::CooperativeExec; +use datafusion::physical_plan::filter::FilterExec; +use datafusion::physical_plan::projection::ProjectionExec; +use datafusion::physical_plan::sorts::sort::SortExec; +use datafusion::physical_plan::sorts::sort_preserving_merge::SortPreservingMergeExec; +use datafusion::physical_plan::{ + ChildrenPropertiesMode, ExecutionPlan, ExecutionPlanProperties, ReplaceChildrenOptions, +}; +use datafusion_common::Result; +use datafusion_common::tree_node::{Transformed, TreeNode}; +use table::table::scan::RegionScanExec; + +use crate::optimizer::windowed_sort::is_time_index_expr; + +/// Keeps one TopK heap for all partitions of a filtered region scan. +/// +/// A partitioned TopK publishes its dynamic filter threshold only after one partition +/// alone has collected `fetch` rows. Under a selective filter every partition has to read +/// `fetch / selectivity` rows before that happens. A single heap fed by all partitions +/// fills after `fetch` matching rows in total, so the scan starts skipping older ranges +/// about `partitions` times earlier. Only the filtered rows go through the heap. +#[derive(Debug)] +pub struct GlobalTopKOverFilteredScan; + +/// Largest fetch that gets one heap. The heap runs on one thread: with a filter passing +/// 90% of 24M rows, it took about 1.6x as long as per-partition heaps at fetch 100000. +/// Below that, fetch does not decide the outcome: with files split by time one heap wins +/// or ties at fetch 1000 to 10000, and with files overlapping in time it loses up to 12% +/// at each of them when the filter passes most rows. +const MAX_GLOBAL_TOPK_FETCH: usize = 10_000; + +impl PhysicalOptimizerRule for GlobalTopKOverFilteredScan { + fn optimize( + &self, + plan: Arc, + _config: &ConfigOptions, + ) -> Result> { + plan.transform_up(|plan| { + let Some(merge_fetch) = plan + .downcast_ref::() + .and_then(|merge| merge.fetch()) + else { + return Ok(Transformed::no(plan)); + }; + match one_heap_below_merge(plan.children()[0], merge_fetch)? { + Some(input) => Ok(Transformed::yes(plan.clone().replace_children( + vec![input], + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + )?)), + None => Ok(Transformed::no(plan)), + } + }) + .map(|t| t.data) + } + + fn name(&self) -> &str { + "GlobalTopKOverFilteredScan" + } + + fn schema_check(&self) -> bool { + true + } +} + +/// Rewrites the partitioned TopK that a `SortPreservingMergeExec` with `merge_fetch` reads +/// through projections into one TopK over all partitions. +/// +/// The partitioned TopK keeps up to `fetch` rows per partition, which equals the global +/// result only because the merge above it takes the first `merge_fetch` rows of all +/// partitions. One heap with `fetch >= merge_fetch` keeps every row the merge can return. +fn one_heap_below_merge( + plan: &Arc, + merge_fetch: usize, +) -> Result>> { + if plan.is::() { + let Some(input) = one_heap_below_merge(plan.children()[0], merge_fetch)? else { + return Ok(None); + }; + return plan + .clone() + .replace_children( + vec![input], + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + ) + .map(Some); + } + let Some(sort) = plan.downcast_ref::() else { + return Ok(None); + }; + let partitions = sort.input().output_partitioning().partition_count(); + if !sort.preserve_partitioning() + || sort.fetch().is_none_or(|fetch| fetch < merge_fetch) + || partitions <= 1 + || filtered_scan_below_topk(sort, partitions)?.is_none() + { + return Ok(None); + } + let coalesced: Arc = + Arc::new(CoalescePartitionsExec::new(sort.input().clone())); + // Both calls keep the dynamic filter expression already pushed into the scan. + // `with_preserve_partitioning` rebuilds its wrapper for one emitter, so the + // threshold is published as soon as the single heap fills. + let resorted = plan.clone().replace_children( + vec![coalesced], + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + )?; + let global = resorted + .downcast_ref::() + .expect("replace_children keeps the SortExec") + .clone() + .with_preserve_partitioning(false); + Ok(Some(Arc::new(global))) +} + +/// Returns the region scan that `sort` reads if `sort` is a TopK on the time index with +/// a fetch up to [`MAX_GLOBAL_TOPK_FETCH`], reading the scan through row-wise operators +/// that include at least one filter, and if the scan has more ranges than `partitions`. +/// +/// Without a filter every scanned row reaches the heaps, so each fills at once. On another +/// sort key the scan cannot skip ranges by time, so one heap only serializes the work. A +/// filter with a fetch keeps the first rows that pass, so reading ranges in another order +/// would change which rows it keeps. With at most one range per partition the threshold +/// leaves no later range to skip, so one heap only adds a single consumer. +pub(crate) fn filtered_scan_below_topk( + sort: &SortExec, + partitions: usize, +) -> Result> { + if !sort + .fetch() + .is_some_and(|fetch| fetch <= MAX_GLOBAL_TOPK_FETCH) + || !is_time_index_expr(sort.input(), &sort.expr().first().expr)? + { + return Ok(None); + } + let mut node = sort.input(); + let mut seen_filter = false; + loop { + if let Some(scan) = node.downcast_ref::() { + let has_ranges_to_skip = scan.get_partition_ranges().len() > partitions; + return Ok((seen_filter && has_ranges_to_skip).then_some(scan)); + } + let is_filter = match node.downcast_ref::() { + Some(filter) if filter.fetch().is_some() => return Ok(None), + Some(_) => true, + None => false, + }; + seen_filter |= is_filter; + if !(is_filter || node.is::() || node.is::()) { + return Ok(None); + } + let Some(child) = node.children().into_iter().next() else { + return Ok(None); + }; + node = child; + } +} + +#[cfg(test)] +mod tests { + use datafusion_physical_expr::expressions::Column; + + use super::*; + use crate::optimizer::test_util::{body_is_not_null as filter, log_region_scan, sort_by}; + + fn partitioned_topk( + input: Arc, + sort_key: Column, + fetch: usize, + ) -> Arc { + Arc::new( + sort_by(input, sort_key, false) + .with_fetch(Some(fetch)) + .with_preserve_partitioning(true), + ) + } + + fn ts() -> Column { + Column::new("ts", 1) + } + + fn merged(topk: Arc, fetch: usize) -> Arc { + let ordering = topk.output_ordering().unwrap().clone(); + Arc::new(SortPreservingMergeExec::new(ordering, topk).with_fetch(Some(fetch))) + } + + fn optimize(plan: Arc) -> Arc { + GlobalTopKOverFilteredScan + .optimize(plan, &ConfigOptions::default()) + .unwrap() + } + + /// Optimizes `topk` under a merge with the same fetch and returns the merge's input. + fn optimize_merged(topk: Arc) -> Arc { + let fetch = topk.fetch().unwrap(); + optimize(merged(topk, fetch)).children()[0].clone() + } + + fn is_partitioned_topk(plan: &Arc) -> bool { + plan.downcast_ref::() + .unwrap() + .preserve_partitioning() + } + + #[test] + fn test_filtered_scan_gets_one_heap() { + let topk = partitioned_topk(filter(log_region_scan(4, 2)), ts(), 100); + let pushed_filter = topk.dynamic_expressions_produced()[0].clone(); + let projection = Arc::new( + ProjectionExec::try_new(vec![(Arc::new(ts()) as _, "ts".to_string())], topk).unwrap(), + ); + let plan = optimize(merged(projection, 100)); + + let projection = plan.children()[0]; + assert!(projection.is::()); + let sort = projection.children()[0].downcast_ref::().unwrap(); + assert!(!sort.preserve_partitioning()); + assert_eq!(Some(100), sort.fetch()); + // The scan holds the filter the old TopK produced; the new one must update it. + assert!(Arc::ptr_eq( + &pushed_filter, + &sort.dynamic_expressions_produced()[0] + )); + let coalesce = sort.input(); + assert!(coalesce.is::()); + assert_eq!( + 4, + coalesce.children()[0] + .output_partitioning() + .partition_count() + ); + } + + #[test] + fn test_topk_keeps_partitions_without_a_merge_bounding_it() { + // Without a merge each partition's rows are part of the result. + let plan = partitioned_topk(filter(log_region_scan(4, 2)), ts(), 100); + assert!(is_partitioned_topk(&optimize(plan))); + // A merge returning more rows than one heap keeps needs every partition's rows. + let plan = merged( + partitioned_topk(filter(log_region_scan(4, 2)), ts(), 100), + 200, + ); + assert!(is_partitioned_topk(optimize(plan).children()[0])); + } + + #[test] + fn test_topk_keeps_partitions_when_one_heap_does_not_help() { + // One thread would merge every filtered row of a weak filter. + let plan = partitioned_topk( + filter(log_region_scan(4, 2)), + ts(), + MAX_GLOBAL_TOPK_FETCH + 1, + ); + assert!(is_partitioned_topk(&optimize_merged(plan))); + // Without a filter every scanned row reaches the heaps, so each fills at once. + let plan = partitioned_topk(log_region_scan(4, 2), ts(), 100); + assert!(is_partitioned_topk(&optimize_merged(plan))); + // The scan cannot skip ranges on another sort key. + let plan = partitioned_topk(filter(log_region_scan(4, 2)), Column::new("body", 0), 100); + assert!(is_partitioned_topk(&optimize_merged(plan))); + // Each partition reads one range, so there is no later range to skip. + let plan = partitioned_topk(filter(log_region_scan(4, 1)), ts(), 100); + assert!(is_partitioned_topk(&optimize_merged(plan))); + let limited = filter(log_region_scan(4, 2)).with_fetch(Some(2)).unwrap(); + let plan = partitioned_topk(limited, ts(), 100); + assert!(is_partitioned_topk(&optimize_merged(plan))); + } +} diff --git a/src/query/src/optimizer/parallelize_scan.rs b/src/query/src/optimizer/parallelize_scan.rs index a0b0545d4e0..e69a86cffe4 100644 --- a/src/query/src/optimizer/parallelize_scan.rs +++ b/src/query/src/optimizer/parallelize_scan.rs @@ -19,12 +19,14 @@ use datafusion::config::ConfigOptions; use datafusion::physical_optimizer::PhysicalOptimizerRule; use datafusion::physical_plan::ExecutionPlan; use datafusion::physical_plan::sorts::sort::SortExec; -use datafusion_common::tree_node::{Transformed, TreeNode}; +use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRecursion}; use datafusion_common::{DataFusionError, Result}; +use store_api::region_engine::PartitionRange; use table::table::scan::RegionScanExec; - pub use table::table::scan::assign_partition_ranges; +use crate::optimizer::global_topk::filtered_scan_below_topk; + #[derive(Debug)] pub struct ParallelizeScan; @@ -52,6 +54,20 @@ impl ParallelizeScan { config: &ConfigOptions, ) -> Result> { let mut first_order_expr = None; + // Scans read by a TopK that keeps one heap, with whether the TopK is descending. + let mut global_topk_scans = Vec::new(); + plan.apply(|node| { + if let Some(sort) = node.downcast_ref::() + && let Some(scan) = + filtered_scan_below_topk(sort, config.execution.target_partitions)? + { + global_topk_scans.push(( + scan as *const RegionScanExec, + sort.expr().first().options.descending, + )); + } + Ok(TreeNodeRecursion::Continue) + })?; let result = plan .transform_down(|plan| { @@ -70,8 +86,22 @@ impl ParallelizeScan { let total_range_num = ranges.len(); // assign ranges to each partition - let mut partition_ranges = - assign_partition_ranges(ranges, expected_partition_num); + let global_topk_descending = global_topk_scans + .iter() + .find(|(scan, _)| std::ptr::eq(*scan, region_scan_exec)) + .map(|(_, descending)| *descending); + let mut partition_ranges = match global_topk_descending { + // The scan skips a range once the TopK threshold excludes the + // range's time span. Dealing ranges in time order makes the first + // range of every partition one of the newest (or oldest), so the + // threshold forms before older ranges are read. + Some(descending) => assign_partition_ranges_by_time( + ranges, + expected_partition_num, + descending, + ), + None => assign_partition_ranges(ranges, expected_partition_num), + }; debug!( "Assign {total_range_num} ranges to {expected_partition_num} partitions" ); @@ -118,13 +148,137 @@ impl ParallelizeScan { } } +/// Assigns ranges in time order, newest first when `descending`, each to the partition +/// with the fewest rows so far, then the fewest ranges. Every partition starts with one +/// of the newest ranges, and the rows stay balanced when range sizes vary. Ranges of +/// old files may report 0 rows, meaning unknown; the range count spreads those. +fn assign_partition_ranges_by_time( + mut ranges: Vec, + expected_partition_num: usize, + descending: bool, +) -> Vec> { + if descending { + ranges.sort_by(|a, b| b.end.cmp(&a.end).then_with(|| b.start.cmp(&a.start))); + } else { + ranges.sort_by(|a, b| a.start.cmp(&b.start).then_with(|| a.end.cmp(&b.end))); + } + let mut partition_ranges = vec![vec![]; expected_partition_num]; + let mut partition_rows = vec![0; expected_partition_num]; + for range in ranges { + let target = (0..expected_partition_num) + .min_by_key(|&i| (partition_rows[i], partition_ranges[i].len(), i)) + .unwrap(); + partition_rows[target] += range.num_rows; + partition_ranges[target].push(range); + } + partition_ranges +} + #[cfg(test)] mod test { use common_time::Timestamp; use common_time::timestamp::TimeUnit; + use datafusion::physical_plan::union::UnionExec; + use datafusion_physical_expr::expressions::Column; use store_api::region_engine::PartitionRange; - use super::assign_partition_ranges; + use super::*; + use crate::optimizer::test_util::{body_is_not_null, sort_by, unassigned_log_region_scan}; + + /// Consecutive ten-millisecond ranges with the given row counts, oldest first. + fn time_ranges(rows: &[usize]) -> Vec { + rows.iter() + .enumerate() + .map(|(i, &num_rows)| PartitionRange { + start: Timestamp::new(i as i64 * 10, TimeUnit::Millisecond), + end: Timestamp::new(i as i64 * 10 + 10, TimeUnit::Millisecond), + num_rows, + identifier: i, + }) + .collect() + } + + /// Older ranges are larger, as compacted files usually are, so assigning by rows + /// alone starts a partition with an old range. + const SHRINKING: [usize; 8] = [800, 700, 600, 500, 400, 300, 200, 100]; + + #[test] + fn test_assign_by_time() { + let firsts = |partitions: Vec>| { + let mut ids: Vec<_> = partitions.iter().map(|p| p[0].identifier).collect(); + ids.sort(); + ids + }; + let assign = |rows: &[usize], partitions, descending| { + assign_partition_ranges_by_time(time_ranges(rows), partitions, descending) + }; + // Every partition starts with one of the newest (or oldest) ranges. + assert_eq!(vec![5, 6, 7], firsts(assign(&SHRINKING, 3, true))); + assert_eq!(vec![0, 1, 2], firsts(assign(&SHRINKING, 3, false))); + // Rows stay balanced: when fewer than `fetch` rows match, every range is read. + let rows: Vec = assign(&[1000, 1, 1000, 1], 2, false) + .iter() + .map(|p| p.iter().map(|r| r.num_rows).sum()) + .collect(); + assert_eq!(vec![1001, 1001], rows); + // Ranges of old files report 0 rows, meaning unknown, and are spread by count. + let counts: Vec<_> = assign(&[0, 0, 0, 0], 2, true) + .iter() + .map(Vec::len) + .collect(); + assert_eq!(vec![2, 2], counts); + } + + #[test] + fn test_only_filtered_time_topk_scans_get_time_ordered_ranges() { + let filter = body_is_not_null(unassigned_log_region_scan(time_ranges(&SHRINKING))); + let topk = Arc::new(sort_by(filter, Column::new("ts", 1), true).with_fetch(Some(100))); + // A sibling scan that no TopK reads must keep the row-balanced assignment. + let plan = UnionExec::try_new(vec![ + topk, + unassigned_log_region_scan(time_ranges(&SHRINKING)), + ]) + .unwrap(); + + let mut config = ConfigOptions::default(); + config.execution.target_partitions = 3; + let plan = ParallelizeScan.optimize(plan, &config).unwrap(); + + let mut assignments = vec![]; + plan.apply(|node| { + if let Some(scan) = node.downcast_ref::() { + assignments.push(members(&scan.get_uncollapsed_partition_ranges())); + } + Ok(TreeNodeRecursion::Continue) + }) + .unwrap(); + assert_eq!( + vec![ + members(&assign_partition_ranges_by_time( + time_ranges(&SHRINKING), + 3, + true + )), + members(&assign_partition_ranges(time_ranges(&SHRINKING), 3)), + ], + assignments + ); + } + + /// The range identifiers of each partition, ignoring order within and across + /// partitions. + fn members(partitions: &[Vec]) -> Vec> { + let mut members: Vec> = partitions + .iter() + .map(|p| { + let mut ids: Vec<_> = p.iter().map(|r| r.identifier).collect(); + ids.sort(); + ids + }) + .collect(); + members.sort(); + members + } #[test] fn test_assign_unbalance_partition_range() { diff --git a/src/query/src/optimizer/test_util.rs b/src/query/src/optimizer/test_util.rs index befaa62daad..6cee4a6841c 100644 --- a/src/query/src/optimizer/test_util.rs +++ b/src/query/src/optimizer/test_util.rs @@ -23,18 +23,30 @@ use api::v1::SemanticType; use async_trait::async_trait; use common_error::ext::{BoxedError, PlainError}; use common_error::status_code::StatusCode; -use datatypes::schema::ColumnSchema; +use common_recordbatch::{RecordBatches, SendableRecordBatchStream}; +use common_time::Timestamp; +use datafusion::physical_plan::display::{DisplayAs, DisplayFormatType}; +use datafusion::physical_plan::filter::FilterExec; +use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet; +use datafusion::physical_plan::sorts::sort::SortExec; +use datafusion::physical_plan::{ExecutionPlan, PhysicalExpr}; +use datafusion_physical_expr::expressions::{Column, IsNotNullExpr}; +use datafusion_physical_expr::{LexOrdering, PhysicalSortExpr}; +use datatypes::arrow::compute::SortOptions; +use datatypes::schema::{ColumnSchema, SchemaRef}; use store_api::metadata::{ ColumnMetadata, RegionMetadata, RegionMetadataBuilder, RegionMetadataRef, }; use store_api::metric_engine_consts::DATA_SCHEMA_TSID_COLUMN_NAME; use store_api::region_engine::{ - RegionEngine, RegionRole, RegionScannerRef, RegionStatistic, RemapManifestsRequest, - RemapManifestsResponse, SetRegionRoleStateResponse, SettableRegionRoleState, + PartitionRange, PrepareRequest, QueryScanContext, RegionEngine, RegionRole, RegionScanner, + RegionScannerRef, RegionStatistic, RemapManifestsRequest, RemapManifestsResponse, + ScannerProperties, SetRegionRoleStateResponse, SettableRegionRoleState, SinglePartitionScanner, SyncRegionFromRequest, SyncRegionFromResponse, }; use store_api::region_request::RegionRequest; use store_api::storage::{ConcreteDataType, RegionId, ScanRequest, SequenceNumber}; +use table::table::scan::RegionScanExec; use crate::dummy_catalog::DummyTableProvider; @@ -226,3 +238,146 @@ fn mock_region_metadata_with_tsid(region_id: RegionId) -> RegionMetadata { .primary_key(vec![1, 2]); builder.build().unwrap() } + +fn log_region_metadata() -> RegionMetadataRef { + let mut builder = RegionMetadataBuilder::new(RegionId::new(1, 1)); + builder + .push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new("body", ConcreteDataType::string_datatype(), true), + semantic_type: SemanticType::Field, + column_id: 1, + }) + .push_column_metadata(ColumnMetadata { + column_schema: ColumnSchema::new( + "ts", + ConcreteDataType::timestamp_millisecond_datatype(), + false, + ), + semantic_type: SemanticType::Timestamp, + column_id: 2, + }); + Arc::new(builder.build().unwrap()) +} + +/// A region scan over an empty `(body STRING, ts TIMESTAMP TIME INDEX)` table split +/// into `partitions` partitions of `ranges_per_partition` ranges, each range reporting +/// one row. +pub(crate) fn log_region_scan( + partitions: usize, + ranges_per_partition: usize, +) -> Arc { + let metadata = log_region_metadata(); + let stream = RecordBatches::try_new(metadata.schema.clone(), vec![]) + .unwrap() + .as_stream(); + let scanner = Box::new(SinglePartitionScanner::new(stream, false, metadata, None)); + let scan = RegionScanExec::new(scanner, ScanRequest::default(), None).unwrap(); + let ranges = (0..partitions) + .map(|partition| { + (0..ranges_per_partition) + .map(|i| { + let id = partition * ranges_per_partition + i; + PartitionRange { + start: Timestamp::new_millisecond(id as i64 * 10), + end: Timestamp::new_millisecond(id as i64 * 10 + 10), + num_rows: 1, + identifier: id, + } + }) + .collect() + }) + .collect(); + Arc::new(scan.with_new_partitions(ranges, partitions).unwrap()) +} + +/// Filters the output of a [`log_region_scan`] by `body IS NOT NULL`. +pub(crate) fn body_is_not_null(input: Arc) -> Arc { + let predicate = Arc::new(IsNotNullExpr::new(Arc::new(Column::new("body", 0)))); + Arc::new(FilterExec::try_new(predicate, input).unwrap()) +} + +pub(crate) fn sort_by(input: Arc, key: Column, descending: bool) -> SortExec { + let options = SortOptions { + descending, + nulls_first: true, + }; + let ordering = LexOrdering::new(vec![PhysicalSortExpr::new(Arc::new(key), options)]).unwrap(); + SortExec::new(ordering, input) +} + +/// A region scan over the same table as [`log_region_scan`] whose ranges are not yet +/// assigned to partitions, as `ParallelizeScan` sees it. +pub(crate) fn unassigned_log_region_scan(ranges: Vec) -> Arc { + let scanner = Box::new(RangesScanner { + metadata: log_region_metadata(), + properties: ScannerProperties::new(vec![ranges], false, 0), + }); + Arc::new(RegionScanExec::new(scanner, ScanRequest::default(), None).unwrap()) +} + +#[derive(Debug)] +struct RangesScanner { + metadata: RegionMetadataRef, + properties: ScannerProperties, +} + +impl DisplayAs for RangesScanner { + fn fmt_as( + &self, + _format: DisplayFormatType, + f: &mut std::fmt::Formatter<'_>, + ) -> std::fmt::Result { + write!(f, "RangesScanner") + } +} + +impl RegionScanner for RangesScanner { + fn name(&self) -> &str { + "RangesScanner" + } + + fn properties(&self) -> &ScannerProperties { + &self.properties + } + + fn schema(&self) -> SchemaRef { + self.metadata.schema.clone() + } + + fn metadata(&self) -> RegionMetadataRef { + self.metadata.clone() + } + + fn prepare(&mut self, request: PrepareRequest) -> Result<(), BoxedError> { + self.properties.prepare(request); + Ok(()) + } + + fn scan_partition( + &self, + _ctx: &QueryScanContext, + _metrics: &ExecutionPlanMetricsSet, + _partition: usize, + ) -> Result { + unreachable!("planning only") + } + + fn has_predicate_without_region(&self) -> bool { + false + } + + fn add_dyn_filter_to_predicate( + &mut self, + filter_exprs: Vec>, + ) -> Vec { + vec![false; filter_exprs.len()] + } + + fn set_logical_region(&mut self, logical_region: bool) { + self.properties.set_logical_region(logical_region); + } + + fn set_query_load_region_id(&mut self, region_id: RegionId) { + self.properties.set_query_load_region_id(region_id); + } +} diff --git a/src/query/src/optimizer/topk_filter_batch.rs b/src/query/src/optimizer/topk_filter_batch.rs new file mode 100644 index 00000000000..ad539e03c79 --- /dev/null +++ b/src/query/src/optimizer/topk_filter_batch.rs @@ -0,0 +1,233 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::sync::Arc; + +use datafusion::config::ConfigOptions; +use datafusion::physical_optimizer::PhysicalOptimizerRule; +use datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec; +use datafusion::physical_plan::coop::CooperativeExec; +use datafusion::physical_plan::filter::FilterExec; +use datafusion::physical_plan::projection::ProjectionExec; +use datafusion::physical_plan::repartition::RepartitionExec; +use datafusion::physical_plan::sorts::sort::SortExec; +use datafusion::physical_plan::{ChildrenPropertiesMode, ExecutionPlan, ReplaceChildrenOptions}; +use datafusion_common::Result; + +use crate::optimizer::windowed_sort::is_time_index_expr; + +/// Lets a TopK see filtered rows as soon as it can use them. +/// +/// `FilterExec` buffers its output until `batch_size` rows pass. Under a selective +/// filter a TopK above it receives nothing until 8192 rows match or the input +/// partition ends, so its heap fills too late to publish the dynamic filter +/// threshold that lets the scan skip older files and row groups. For a TopK on the +/// time index, this rule sets the batch size of such filters to 1, which passes each +/// filtered input batch on whole: the coalescer never splits a batch into pieces of the +/// target size or holds rows back. Other sort keys are left alone, since file and row +/// group ranges rarely let the scan skip anything by them. +/// +/// Batch size 1 passes batches through only because `LimitedBatchCoalescer` caps the +/// biggest batch it coalesces at half the target, so every non-empty batch takes arrow's +/// large-batch bypass. `test_filter_with_batch_size_one_keeps_batches_whole` fails if a +/// DataFusion or arrow upgrade changes that. +#[derive(Debug)] +pub struct TopKFilterBatchSize; + +impl PhysicalOptimizerRule for TopKFilterBatchSize { + fn optimize( + &self, + plan: Arc, + _config: &ConfigOptions, + ) -> Result> { + rewrite(plan, false) + } + + fn name(&self) -> &str { + "TopKFilterBatchSize" + } + + fn schema_check(&self) -> bool { + true + } +} + +/// `under_topk` is true if a TopK on the time index reads `plan`'s output through +/// operators that neither combine rows nor reorder them by anything but the sort key. +fn rewrite(plan: Arc, under_topk: bool) -> Result> { + let (plan, child_under_topk) = if let Some(sort) = plan.downcast_ref::() { + let is_time_topk = + sort.fetch().is_some() && is_time_index_expr(sort.input(), &sort.expr().first().expr)?; + (plan, is_time_topk) + } else if let Some(filter) = plan.downcast_ref::() { + if filter.fetch().is_some() { + // It keeps the first rows that pass, so when the threshold arrives decides which. + (plan, false) + } else if under_topk && filter.batch_size() > 1 { + ( + Arc::new(filter.with_batch_size(1)?) as Arc, + true, + ) + } else { + (plan, under_topk) + } + } else if plan.is::() + || plan.is::() + || plan.is::() + || plan.is::() + { + (plan, under_topk) + } else { + (plan, false) + }; + + let children = plan.children(); + if children.is_empty() { + return Ok(plan); + } + let mut changed = false; + let new_children = children + .into_iter() + .map(|child| { + let new_child = rewrite(child.clone(), child_under_topk)?; + changed |= !Arc::ptr_eq(&new_child, child); + Ok(new_child) + }) + .collect::>>()?; + if !changed { + return Ok(plan); + } + plan.replace_children( + new_children, + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + ) +} + +#[cfg(test)] +mod tests { + use datafusion::datasource::memory::MemorySourceConfig; + use datafusion::datasource::source::DataSourceExec; + use datafusion::execution::TaskContext; + use datafusion::physical_plan::aggregates::{AggregateExec, AggregateMode, PhysicalGroupBy}; + use datafusion::physical_plan::collect; + use datafusion_physical_expr::expressions::{Column, IsNotNullExpr}; + use datatypes::arrow::array::{ArrayRef, StringArray}; + use datatypes::arrow::record_batch::RecordBatch; + + use super::*; + use crate::optimizer::test_util::{body_is_not_null, log_region_scan, sort_by}; + + fn filter_over_scan() -> Arc { + body_is_not_null(log_region_scan(1, 1)) + } + + fn sort( + input: Arc, + key: Column, + fetch: Option, + ) -> Arc { + Arc::new(sort_by(input, key, false).with_fetch(fetch)) + } + + fn filter_batch_size(plan: &Arc) -> usize { + if let Some(filter) = plan.downcast_ref::() { + return filter.batch_size(); + } + filter_batch_size(plan.children()[0]) + } + + fn optimize(plan: Arc) -> Arc { + TopKFilterBatchSize + .optimize(plan, &ConfigOptions::default()) + .unwrap() + } + + #[test] + fn test_topk_flushes_filter_per_batch() { + let filter = filter_over_scan(); + let default_size = filter_batch_size(&filter); + let projection = Arc::new( + ProjectionExec::try_new( + vec![(Arc::new(Column::new("ts", 1)) as _, "ts".to_string())], + filter.clone(), + ) + .unwrap(), + ); + + let plan = optimize(sort(projection, Column::new("ts", 0), Some(100))); + assert_eq!(1, filter_batch_size(&plan)); + + // A full sort needs every row; batching does not delay any decision. + let plan = optimize(sort(filter.clone(), Column::new("ts", 1), None)); + assert_eq!(default_size, filter_batch_size(&plan)); + } + + #[test] + fn test_filter_batch_size_kept_when_topk_cannot_prune() { + let filter = filter_over_scan(); + let default_size = filter_batch_size(&filter); + + // The scan cannot skip ranges on a sort key other than the time index. + let plan = optimize(sort(filter.clone(), Column::new("body", 0), Some(100))); + assert_eq!(default_size, filter_batch_size(&plan)); + + // An aggregate combines rows, so its input order does not decide the TopK. + let aggregate = Arc::new( + AggregateExec::try_new( + AggregateMode::Single, + PhysicalGroupBy::new_single(vec![( + Arc::new(Column::new("ts", 1)) as _, + "ts".to_string(), + )]), + vec![], + vec![], + filter.clone(), + filter.schema(), + ) + .unwrap(), + ); + let plan = optimize(sort(aggregate, Column::new("ts", 0), Some(100))); + assert_eq!(default_size, filter_batch_size(&plan)); + + let limited = filter.with_fetch(Some(2)).unwrap(); + let plan = optimize(sort(limited, Column::new("ts", 1), Some(1))); + assert_eq!(default_size, filter_batch_size(&plan)); + } + + #[tokio::test] + async fn test_filter_with_batch_size_one_keeps_batches_whole() { + // The rule relies on the coalescer passing batches through at a target of 1; + // splitting them into single rows would multiply the per-batch cost. + let batch = |rows: usize| { + let body: ArrayRef = Arc::new(StringArray::from(vec!["a"; rows])); + RecordBatch::try_from_iter([("body", body)]).unwrap() + }; + let schema = batch(0).schema(); + let input = DataSourceExec::from_data_source( + MemorySourceConfig::try_new(&[vec![batch(3), batch(100), batch(100)]], schema, None) + .unwrap(), + ); + let predicate = Arc::new(IsNotNullExpr::new(Arc::new(Column::new("body", 0)))); + let filter = FilterExec::try_new(predicate, input) + .unwrap() + .with_batch_size(1) + .unwrap(); + + let output = collect(Arc::new(filter), Arc::new(TaskContext::default())) + .await + .unwrap(); + let sizes: Vec<_> = output.iter().map(|b| b.num_rows()).collect(); + assert_eq!(vec![3, 100, 100], sizes); + } +} diff --git a/src/query/src/optimizer/windowed_sort.rs b/src/query/src/optimizer/windowed_sort.rs index d1ec687c6cf..d6f2720efa4 100644 --- a/src/query/src/optimizer/windowed_sort.rs +++ b/src/query/src/optimizer/windowed_sort.rs @@ -213,7 +213,7 @@ fn fetch_partition_range(input: Arc) -> DataFusionResult, expr: &Arc, ) -> DataFusionResult { diff --git a/src/query/src/query_engine/state.rs b/src/query/src/query_engine/state.rs index c9540682a13..fbba7ae9098 100644 --- a/src/query/src/query_engine/state.rs +++ b/src/query/src/query_engine/state.rs @@ -70,6 +70,7 @@ use crate::optimizer::count_wildcard::CountWildcardToTimeIndexRule; use crate::optimizer::enforce_sorting::EnforceSorting; use crate::optimizer::expr_depth; use crate::optimizer::global_limit::EnsureGlobalLimitForFetch; +use crate::optimizer::global_topk::GlobalTopKOverFilteredScan; use crate::optimizer::infer_aggregate_input_bounds::InferAggregateInputBoundsRule; use crate::optimizer::json_schema_concretize::JsonSchemaConcretizeRule; use crate::optimizer::json_type_concretize::JsonTypeConcretizeRule; @@ -83,6 +84,7 @@ use crate::optimizer::sst_manifest_aggregate::{ SstManifestAggregatePlanner, SstManifestAggregateRule, }; use crate::optimizer::string_normalization::StringNormalizationRule; +use crate::optimizer::topk_filter_batch::TopKFilterBatchSize; use crate::optimizer::transcribe_atat::TranscribeAtatRule; use crate::optimizer::type_conversion::TypeConversionRule; use crate::optimizer::windowed_sort::WindowedSortPhysicalRule; @@ -290,6 +292,10 @@ impl QueryEngineState { physical_optimizer .rules .push(Arc::new(EnsureGlobalLimitForFetch)); + physical_optimizer.rules.push(Arc::new(TopKFilterBatchSize)); + physical_optimizer + .rules + .push(Arc::new(GlobalTopKOverFilteredScan)); // Add rule to remove duplicate nodes generated by other rules. Run this in the last. physical_optimizer.rules.push(Arc::new(RemoveDuplicate)); // Place SanityCheckPlan at the end of the list to ensure that it runs after all other rules. diff --git a/tests/cases/standalone/common/order/windowed_sort.result b/tests/cases/standalone/common/order/windowed_sort.result index a80ff6714ad..9bcbe94f763 100644 --- a/tests/cases/standalone/common/order/windowed_sort.result +++ b/tests/cases/standalone/common/order/windowed_sort.result @@ -417,3 +417,119 @@ DROP TABLE test_pk; Affected Rows: 0 +-- More ranges (6 files) than sqlness partitions (4): the TopK on the time index +-- reads all partitions through one heap and publishes its threshold. +CREATE TABLE test_one_heap(i INTEGER, t TIMESTAMP TIME INDEX) WITH('compaction.type'='twcs', 'compaction.twcs.trigger_file_num'='16'); + +Affected Rows: 0 + +INSERT INTO test_one_heap VALUES (1, 1), (2, 2); + +Affected Rows: 2 + +ADMIN FLUSH_TABLE('test_one_heap'); + ++------------------------------------+ +| ADMIN FLUSH_TABLE('test_one_heap') | ++------------------------------------+ +| 0 | ++------------------------------------+ + +INSERT INTO test_one_heap VALUES (3, 3), (4, 4); + +Affected Rows: 2 + +ADMIN FLUSH_TABLE('test_one_heap'); + ++------------------------------------+ +| ADMIN FLUSH_TABLE('test_one_heap') | ++------------------------------------+ +| 0 | ++------------------------------------+ + +INSERT INTO test_one_heap VALUES (5, 5), (6, 6); + +Affected Rows: 2 + +ADMIN FLUSH_TABLE('test_one_heap'); + ++------------------------------------+ +| ADMIN FLUSH_TABLE('test_one_heap') | ++------------------------------------+ +| 0 | ++------------------------------------+ + +INSERT INTO test_one_heap VALUES (7, 7), (8, 8); + +Affected Rows: 2 + +ADMIN FLUSH_TABLE('test_one_heap'); + ++------------------------------------+ +| ADMIN FLUSH_TABLE('test_one_heap') | ++------------------------------------+ +| 0 | ++------------------------------------+ + +INSERT INTO test_one_heap VALUES (9, 9), (10, 10); + +Affected Rows: 2 + +ADMIN FLUSH_TABLE('test_one_heap'); + ++------------------------------------+ +| ADMIN FLUSH_TABLE('test_one_heap') | ++------------------------------------+ +| 0 | ++------------------------------------+ + +INSERT INTO test_one_heap VALUES (11, 11), (12, 12); + +Affected Rows: 2 + +ADMIN FLUSH_TABLE('test_one_heap'); + ++------------------------------------+ +| ADMIN FLUSH_TABLE('test_one_heap') | ++------------------------------------+ +| 0 | ++------------------------------------+ + +SELECT * FROM test_one_heap WHERE i > 2 ORDER BY t DESC LIMIT 3; + ++----+-------------------------+ +| i | t | ++----+-------------------------+ +| 12 | 1970-01-01T00:00:00.012 | +| 11 | 1970-01-01T00:00:00.011 | +| 10 | 1970-01-01T00:00:00.010 | ++----+-------------------------+ + +-- SQLNESS REPLACE (-+) - +-- SQLNESS REPLACE (\s\s+) _ +-- SQLNESS REPLACE (peers.*) REDACTED +-- SQLNESS REPLACE (metrics.*) REDACTED +-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED +-- SQLNESS REPLACE num_ranges=\d+ num_ranges=REDACTED +-- SQLNESS REPLACE \\?"(dyn_filters|time_range|file_summary|max_part_range)\\?":.* "$1":REDACTED +EXPLAIN ANALYZE SELECT * FROM test_one_heap WHERE i > 2 ORDER BY t DESC LIMIT 3; + ++-+-+-+ +| stage | node | plan_| ++-+-+-+ +| 0_| 0_|_CooperativeExec REDACTED +|_|_|_MergeScanExec: REDACTED +|_|_|_| +| 1_| 0_|_SortPreservingMergeExec: [t@1 DESC], fetch=3 REDACTED +|_|_|_SortExec: TopK(fetch=3), expr=[t@1 DESC], preserve_partitioning=[false], filter=[t@1 IS NULL OR t@1 > 10] REDACTED +|_|_|_CoalescePartitionsExec REDACTED +|_|_|_FilterExec: i@0 > 2 REDACTED +|_|_|_SeqScan: region=REDACTED, "partition_count":{"count":6, "mem_ranges":0, "files":6, "file_ranges":6}, "projection": ["i", "t"], "filters": ["i > Int32(2)"], "dyn_filters":REDACTED +|_|_|_| +|_|_| Total rows: 3_| ++-+-+-+ + +DROP TABLE test_one_heap; + +Affected Rows: 0 + diff --git a/tests/cases/standalone/common/order/windowed_sort.sql b/tests/cases/standalone/common/order/windowed_sort.sql index 7815693e237..055429ea07c 100644 --- a/tests/cases/standalone/common/order/windowed_sort.sql +++ b/tests/cases/standalone/common/order/windowed_sort.sql @@ -147,3 +147,44 @@ EXPLAIN ANALYZE SELECT * FROM test_pk where pk > 7 ORDER BY t LIMIT 5; EXPLAIN ANALYZE VERBOSE SELECT * FROM test_pk where pk > 7 ORDER BY t LIMIT 5; DROP TABLE test_pk; + +-- More ranges (6 files) than sqlness partitions (4): the TopK on the time index +-- reads all partitions through one heap and publishes its threshold. +CREATE TABLE test_one_heap(i INTEGER, t TIMESTAMP TIME INDEX) WITH('compaction.type'='twcs', 'compaction.twcs.trigger_file_num'='16'); + +INSERT INTO test_one_heap VALUES (1, 1), (2, 2); + +ADMIN FLUSH_TABLE('test_one_heap'); + +INSERT INTO test_one_heap VALUES (3, 3), (4, 4); + +ADMIN FLUSH_TABLE('test_one_heap'); + +INSERT INTO test_one_heap VALUES (5, 5), (6, 6); + +ADMIN FLUSH_TABLE('test_one_heap'); + +INSERT INTO test_one_heap VALUES (7, 7), (8, 8); + +ADMIN FLUSH_TABLE('test_one_heap'); + +INSERT INTO test_one_heap VALUES (9, 9), (10, 10); + +ADMIN FLUSH_TABLE('test_one_heap'); + +INSERT INTO test_one_heap VALUES (11, 11), (12, 12); + +ADMIN FLUSH_TABLE('test_one_heap'); + +SELECT * FROM test_one_heap WHERE i > 2 ORDER BY t DESC LIMIT 3; + +-- SQLNESS REPLACE (-+) - +-- SQLNESS REPLACE (\s\s+) _ +-- SQLNESS REPLACE (peers.*) REDACTED +-- SQLNESS REPLACE (metrics.*) REDACTED +-- SQLNESS REPLACE region=\d+\(\d+,\s+\d+\) region=REDACTED +-- SQLNESS REPLACE num_ranges=\d+ num_ranges=REDACTED +-- SQLNESS REPLACE \\?"(dyn_filters|time_range|file_summary|max_part_range)\\?":.* "$1":REDACTED +EXPLAIN ANALYZE SELECT * FROM test_one_heap WHERE i > 2 ORDER BY t DESC LIMIT 3; + +DROP TABLE test_one_heap; diff --git a/tests/cases/standalone/common/tql-explain-analyze/explain.result b/tests/cases/standalone/common/tql-explain-analyze/explain.result index 6d7f2b142a6..16930d8ccef 100644 --- a/tests/cases/standalone/common/tql-explain-analyze/explain.result +++ b/tests/cases/standalone/common/tql-explain-analyze/explain.result @@ -214,6 +214,8 @@ TQL EXPLAIN VERBOSE (0, 10, '5s') test; | physical_plan after WindowedSortRule_| SAME TEXT AS ABOVE_| | physical_plan after MatchesConstantTerm_| SAME TEXT AS ABOVE_| | physical_plan after EnsureGlobalLimitForFetch_| SAME TEXT AS ABOVE_| +| physical_plan after TopKFilterBatchSize_| SAME TEXT AS ABOVE_| +| physical_plan after GlobalTopKOverFilteredScan_| SAME TEXT AS ABOVE_| | physical_plan after RemoveDuplicateRule_| SAME TEXT AS ABOVE_| | physical_plan after SeriesFrameOutput_| SAME TEXT AS ABOVE_| | physical_plan after SanityCheckPlan_| SAME TEXT AS ABOVE_| @@ -377,6 +379,8 @@ TQL EXPLAIN VERBOSE (0, 10, '5s') test AS series; | physical_plan after WindowedSortRule_| SAME TEXT AS ABOVE_| | physical_plan after MatchesConstantTerm_| SAME TEXT AS ABOVE_| | physical_plan after EnsureGlobalLimitForFetch_| SAME TEXT AS ABOVE_| +| physical_plan after TopKFilterBatchSize_| SAME TEXT AS ABOVE_| +| physical_plan after GlobalTopKOverFilteredScan_| SAME TEXT AS ABOVE_| | physical_plan after RemoveDuplicateRule_| SAME TEXT AS ABOVE_| | physical_plan after SeriesFrameOutput_| SAME TEXT AS ABOVE_| | physical_plan after SanityCheckPlan_| SAME TEXT AS ABOVE_| @@ -570,6 +574,8 @@ TQL EXPLAIN VERBOSE (0, 10, '5s') test_nano; | physical_plan after WindowedSortRule_| SAME TEXT AS ABOVE_| | physical_plan after MatchesConstantTerm_| SAME TEXT AS ABOVE_| | physical_plan after EnsureGlobalLimitForFetch_| SAME TEXT AS ABOVE_| +| physical_plan after TopKFilterBatchSize_| SAME TEXT AS ABOVE_| +| physical_plan after GlobalTopKOverFilteredScan_| SAME TEXT AS ABOVE_| | physical_plan after RemoveDuplicateRule_| SAME TEXT AS ABOVE_| | physical_plan after SeriesFrameOutput_| SAME TEXT AS ABOVE_| | physical_plan after SanityCheckPlan_| SAME TEXT AS ABOVE_| diff --git a/tests/perf/README.md b/tests/perf/README.md index a7e698fe047..74dcb0016b7 100644 --- a/tests/perf/README.md +++ b/tests/perf/README.md @@ -611,6 +611,9 @@ Additional SQL optimizer cases: - `sql_topk_order_by`: single-table TopK / `ORDER BY` on a DOUBLE field with time and tag predicates. +- `sql_topk_time_index_selective_filter`: `ORDER BY ts DESC LIMIT 100` with a + 1-in-1000 filter over 64 time-split SSTs; the TopK dynamic filter should let + the scan skip older SSTs. - `sql_aggregate_order_by`: grouped aggregate ordered by aggregate value with a `LIMIT`. - `sql_join_filter_order`: two direct-SST tables joined on a shared tag with diff --git a/tests/perf/query_cases/sql_topk_time_index_selective_filter/case.toml b/tests/perf/query_cases/sql_topk_time_index_selective_filter/case.toml new file mode 100644 index 00000000000..5911072e5be --- /dev/null +++ b/tests/perf/query_cases/sql_topk_time_index_selective_filter/case.toml @@ -0,0 +1,57 @@ +# A selective filter under ORDER BY ts DESC LIMIT. The TopK fills from the newest +# matching rows and its dynamic filter lets the scan skip older SSTs; a change that +# delays the threshold makes the scan read every SST. + +[case] +name = "sql_topk_time_index_selective_filter" +description = "ORDER BY time index DESC LIMIT with a 1-in-1000 filter over 64 time-split SSTs" + +[scenario] +kind = "direct_readable_sst" +seed = 10515 + +[[scenario.tables]] +database = "public" +name = "sql_topk_time_index_selective_filter" +engine = "mito" +append_mode = true +sst_format = "flat" +primary_key = ["host"] +time_index = "ts" + +[[scenario.tables.columns]] +name = "host" +type = "STRING" +semantic = "tag" +distribution = { kind = "cardinality", values = 16, prefix = "host" } + +[[scenario.tables.columns]] +name = "num" +type = "UINT64" +semantic = "field" + +[[scenario.tables.columns]] +name = "ts" +type = "TIMESTAMP(9)" +semantic = "timestamp" + +[scenario.layout] +regions = 1 +sst_count = 64 +rows_per_sst = 131072 +row_group_size = 16384 +series_count = 16 +start_unix_nanos = 1704067200000000000 +step_nanos = 1000000000 +time_range_layout = "non_overlapping_per_sst" +series_layout = "round_robin" + +[[scenario.queries]] +name = "topk_ts_desc_selective_filter" +kind = "sql" +query = "SELECT ts, host, num FROM sql_topk_time_index_selective_filter WHERE num % 1000 = 7 ORDER BY ts DESC LIMIT 100" +warmup = 2 +iterations = 10 + +[scenario.queries.thresholds] +max_candidate_latency_regression_pct = 30