diff --git a/src/promql/src/extension_plan/planner.rs b/src/promql/src/extension_plan/planner.rs index f2d86b76862..701ca4be01d 100644 --- a/src/promql/src/extension_plan/planner.rs +++ b/src/promql/src/extension_plan/planner.rs @@ -67,7 +67,11 @@ impl ExtensionPlanner for PromExtensionPlanner { } else if let Some(node) = node.as_any().downcast_ref::() { Ok(Some(node.to_execution_plan(physical_inputs[0].clone()))) } else if let Some(node) = node.as_any().downcast_ref::() { - plan_fused_series(node, physical_inputs) + plan_fused_series( + node, + physical_inputs, + session.config_options().execution.target_partitions, + ) } else { Ok(None) } @@ -90,9 +94,13 @@ const METRIC_NAME: &str = "__name__"; /// found but refuses the raw path is a different case — the logical route chose this node for this /// scan and nothing here can undo that choice, because the logical plan is not available — so it is /// reported as an error that names the reason instead of silently producing no plan. +/// The fused leaf needs a prepared scan: range assignment runs after physical planning and cannot +/// see a `SeriesScanExec`. Preparation keeps the scan's parallel layout, and the series-producer +/// contract guarantees that one series stays in one scan partition. fn plan_fused_series( fused: &FusedSeries, physical_inputs: &[Arc], + target_partitions: usize, ) -> DfResult>> { let Some(input) = physical_inputs.first() else { return Ok(None); @@ -124,7 +132,18 @@ fn plan_fused_series( .map(|field| field.name.to_string()) .collect::>(); - let scan = single_partition_scan(scan)?; + let scan = if scan.is_partition_set() { + Arc::new(scan.clone()) + } else { + let partitions = table::table::scan::assign_partition_ranges( + scan.get_partition_ranges(), + target_partitions.max(1), + ); + Arc::new( + scan.with_new_partitions(partitions, target_partitions.max(1)) + .map_err(|error| DataFusionError::External(error.into_inner()))?, + ) + }; // The scan resolves the label source and the ordering it will declare itself, against its own // metadata snapshot, and hands both back through the leaf it builds. Naming them here instead // would be a second copy of a binding only the scanner can make: the physical metadata and @@ -146,24 +165,3 @@ fn plan_fused_series( .to_execution_plan(series_scan, label_source, ordering) .map(Some) } - -/// The scan as one partition holding every range it already has. -/// -/// A raw-series binding is resolvable only once the scan holds exactly one partition: the label -/// source is decoded against the scanner's own metadata snapshot and the frames it produces carry -/// whole series, so a scan spread over several partitions has no single binding to name. The rule -/// that assigns partition ranges (`ParallelizeScan`) runs *after* physical planning, i.e. after -/// this node is built, so a scan reaching here is unprepared; preparing it here keeps the node from -/// reading one partition of the series it was bound to. A scan that is already prepared — several -/// partitions, assigned by whatever ran before — is passed through as it is, and the binding below -/// declines it if it cannot name one partition. -fn single_partition_scan(scan: &RegionScanExec) -> DfResult> { - if scan.is_partition_set() { - return Ok(Arc::new(scan.clone())); - } - let ranges = scan.get_partition_ranges(); - let prepared = scan - .with_new_partitions(vec![ranges], 1) - .map_err(|error| DataFusionError::External(error.into_inner()))?; - Ok(Arc::new(prepared)) -} diff --git a/src/query/src/optimizer/parallelize_scan.rs b/src/query/src/optimizer/parallelize_scan.rs index 8e0113e69df..1bc07e34a93 100644 --- a/src/query/src/optimizer/parallelize_scan.rs +++ b/src/query/src/optimizer/parallelize_scan.rs @@ -12,7 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::collections::BinaryHeap; use std::sync::Arc; use common_telemetry::debug; @@ -22,7 +21,6 @@ use datafusion::physical_plan::ExecutionPlan; use datafusion::physical_plan::sorts::sort::SortExec; use datafusion_common::tree_node::{Transformed, TreeNode}; use datafusion_common::{DataFusionError, Result}; -use store_api::region_engine::PartitionRange; use table::table::scan::RegionScanExec; #[derive(Debug)] @@ -71,7 +69,7 @@ impl ParallelizeScan { // assign ranges to each partition let mut partition_ranges = - Self::assign_partition_range(ranges, expected_partition_num); + table::table::scan::assign_partition_ranges(ranges, expected_partition_num); debug!( "Assign {total_range_num} ranges to {expected_partition_num} partitions" ); @@ -116,176 +114,13 @@ impl ParallelizeScan { Ok(result) } - - /// Distribute [`PartitionRange`]s to each partition. - /// - /// Currently we assign ranges to partitions according to their rows so each partition - /// has similar number of rows. This method always return `expected_partition_num` partitions. - pub fn assign_partition_range( - mut ranges: Vec, - expected_partition_num: usize, - ) -> Vec> { - if ranges.is_empty() { - // Returns a single partition with no range. - return vec![vec![]; expected_partition_num]; - } - - if ranges.len() == 1 { - let mut vec = vec![vec![]; expected_partition_num]; - vec[0] = ranges; - return vec; - } - - // Sort ranges by number of rows in descending order. - ranges.sort_by_key(|b| std::cmp::Reverse(b.num_rows)); - let mut partition_ranges = vec![vec![]; expected_partition_num]; - - #[derive(Eq, PartialEq)] - struct HeapNode { - num_rows: usize, - partition_idx: usize, - } - - impl Ord for HeapNode { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { - // Reverse for min-heap. - self.num_rows.cmp(&other.num_rows).reverse() - } - } - - impl PartialOrd for HeapNode { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } - } - - let mut part_heap = - BinaryHeap::from_iter((0..expected_partition_num).map(|partition_idx| HeapNode { - num_rows: 0, - partition_idx, - })); - - // Assigns the range to the partition with the smallest number of rows. - for range in ranges { - let mut node = part_heap.pop().unwrap(); - let partition_idx = node.partition_idx; - node.num_rows += range.num_rows; - partition_ranges[partition_idx].push(range); - part_heap.push(node); - } - - partition_ranges - } } #[cfg(test)] mod test { use common_time::Timestamp; use common_time::timestamp::TimeUnit; - - use super::*; - - #[test] - fn test_assign_partition_range() { - let ranges = vec![ - PartitionRange { - start: Timestamp::new(0, TimeUnit::Second), - end: Timestamp::new(10, TimeUnit::Second), - num_rows: 100, - identifier: 1, - }, - PartitionRange { - start: Timestamp::new(10, TimeUnit::Second), - end: Timestamp::new(20, TimeUnit::Second), - num_rows: 200, - identifier: 2, - }, - PartitionRange { - start: Timestamp::new(20, TimeUnit::Second), - end: Timestamp::new(30, TimeUnit::Second), - num_rows: 150, - identifier: 3, - }, - PartitionRange { - start: Timestamp::new(30, TimeUnit::Second), - end: Timestamp::new(40, TimeUnit::Second), - num_rows: 250, - identifier: 4, - }, - ]; - - // assign to 2 partitions - let expected_partition_num = 2; - let result = - ParallelizeScan::assign_partition_range(ranges.clone(), expected_partition_num); - let expected = vec![ - vec![ - PartitionRange { - start: Timestamp::new(30, TimeUnit::Second), - end: Timestamp::new(40, TimeUnit::Second), - num_rows: 250, - identifier: 4, - }, - PartitionRange { - start: Timestamp::new(0, TimeUnit::Second), - end: Timestamp::new(10, TimeUnit::Second), - num_rows: 100, - identifier: 1, - }, - ], - vec![ - PartitionRange { - start: Timestamp::new(10, TimeUnit::Second), - end: Timestamp::new(20, TimeUnit::Second), - num_rows: 200, - identifier: 2, - }, - PartitionRange { - start: Timestamp::new(20, TimeUnit::Second), - end: Timestamp::new(30, TimeUnit::Second), - num_rows: 150, - identifier: 3, - }, - ], - ]; - assert_eq!(result, expected); - - // assign 4 ranges to 5 partitions. - let expected_partition_num = 5; - let result = ParallelizeScan::assign_partition_range(ranges, expected_partition_num); - let expected = vec![ - vec![PartitionRange { - start: Timestamp::new(30, TimeUnit::Second), - end: Timestamp::new(40, TimeUnit::Second), - num_rows: 250, - identifier: 4, - }], - vec![PartitionRange { - start: Timestamp::new(0, TimeUnit::Second), - end: Timestamp::new(10, TimeUnit::Second), - num_rows: 100, - identifier: 1, - }], - vec![PartitionRange { - start: Timestamp::new(10, TimeUnit::Second), - end: Timestamp::new(20, TimeUnit::Second), - num_rows: 200, - identifier: 2, - }], - vec![], - vec![PartitionRange { - start: Timestamp::new(20, TimeUnit::Second), - end: Timestamp::new(30, TimeUnit::Second), - num_rows: 150, - identifier: 3, - }], - ]; - assert_eq!(result, expected); - - // assign 0 ranges to 5 partitions. Should return 5 empty ranges. - let result = ParallelizeScan::assign_partition_range(vec![], 5); - assert_eq!(result.len(), 5); - } + use store_api::region_engine::PartitionRange; #[test] fn test_assign_unbalance_partition_range() { @@ -319,7 +154,7 @@ mod test { // assign to 2 partitions let expected_partition_num = 2; let result = - ParallelizeScan::assign_partition_range(ranges.clone(), expected_partition_num); + table::table::scan::assign_partition_ranges(ranges.clone(), expected_partition_num); let expected = vec![ vec![PartitionRange { start: Timestamp::new(30, TimeUnit::Second), diff --git a/src/table/src/table/scan.rs b/src/table/src/table/scan.rs index 486b1e8d6da..38548fa0853 100644 --- a/src/table/src/table/scan.rs +++ b/src/table/src/table/scan.rs @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::collections::HashSet; +use std::collections::{BinaryHeap, HashSet}; use std::pin::Pin; use std::sync::{Arc, Mutex}; use std::task::{Context, Poll}; @@ -109,6 +109,66 @@ impl std::fmt::Debug for RegionScanExec { } } +/// Distribute [`PartitionRange`]s to each partition. +/// +/// Currently we assign ranges to partitions according to their rows so each partition +/// has similar number of rows. This method always return `expected_partition_num` partitions. +pub fn assign_partition_ranges( + mut ranges: Vec, + expected_partition_num: usize, +) -> Vec> { + if ranges.is_empty() { + // Returns a single partition with no range. + return vec![vec![]; expected_partition_num]; + } + + if ranges.len() == 1 { + let mut vec = vec![vec![]; expected_partition_num]; + vec[0] = ranges; + return vec; + } + + // Sort ranges by number of rows in descending order. + ranges.sort_by_key(|b| std::cmp::Reverse(b.num_rows)); + let mut partition_ranges = vec![vec![]; expected_partition_num]; + + #[derive(Eq, PartialEq)] + struct HeapNode { + num_rows: usize, + partition_idx: usize, + } + + impl Ord for HeapNode { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + // Reverse for min-heap. + self.num_rows.cmp(&other.num_rows).reverse() + } + } + + impl PartialOrd for HeapNode { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } + } + + let mut part_heap = + BinaryHeap::from_iter((0..expected_partition_num).map(|partition_idx| HeapNode { + num_rows: 0, + partition_idx, + })); + + // Assigns the range to the partition with the smallest number of rows. + for range in ranges { + let mut node = part_heap.pop().unwrap(); + let partition_idx = node.partition_idx; + node.num_rows += range.num_rows; + partition_ranges[partition_idx].push(range); + part_heap.push(node); + } + + partition_ranges +} + impl RegionScanExec { pub fn new( scanner: RegionScannerRef, @@ -434,6 +494,7 @@ impl RegionScanExec { /// Resolves authorized logical names against this prepared scanner's physical metadata, /// then selects a native raw-series leaf and returns the binding it was validated against. + /// Prepared scans may contain multiple partitions; the producer keeps each series in one partition. /// /// Approval must be based on the returned [`RawSeriesRequest`], because that binding, not the /// requested names, describes the approved output. See [`Self::try_to_named_series_scan`] @@ -474,10 +535,6 @@ impl RegionScanExec { } let scanner = self.scanner.lock().unwrap(); let metadata = scanner.metadata(); - if scanner.properties().num_partitions().max(1) != 1 { - return None; - } - let primary_key_ids = metadata .primary_key_columns() .map(|column| column.column_id) @@ -1302,6 +1359,39 @@ mod test { ) } + #[test] + fn assign_partition_ranges_preserves_requested_partition_count() { + let ranges = (0..4) + .map(|identifier| PartitionRange { + start: common_time::Timestamp::new( + identifier as i64, + common_time::timestamp::TimeUnit::Second, + ), + end: common_time::Timestamp::new( + identifier as i64 + 1, + common_time::timestamp::TimeUnit::Second, + ), + num_rows: 1, + identifier, + }) + .collect(); + assert_eq!(assign_partition_ranges(ranges, 4).len(), 4); + } + + #[test] + fn named_series_binding_accepts_multiple_prepared_partitions() { + let (_, plan) = dynamic_filter_fixture(5687); + let prepared = plan + .with_new_partitions(vec![vec![], vec![]], 2) + .expect("prepare two scanner partitions"); + assert!(prepared.is_partition_set()); + assert!( + prepared + .resolve_named_series_binding("cpu", &[], &["a".to_string()]) + .is_some() + ); + } + #[test] fn named_series_scan_requires_prepared_single_partition() { let (_, plan) = dynamic_filter_fixture(5686);