Skip to main content

mito2/read/
unordered_scan.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Unordered scanner.
16
17use std::fmt;
18use std::sync::Arc;
19use std::time::Instant;
20
21use async_stream::{stream, try_stream};
22use common_error::ext::BoxedError;
23use common_recordbatch::{RecordBatchStreamWrapper, SendableRecordBatchStream};
24use common_telemetry::{tracing, warn};
25use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet;
26use datafusion::physical_plan::{DisplayAs, DisplayFormatType};
27use datatypes::arrow::record_batch::RecordBatch;
28use datatypes::schema::SchemaRef;
29use futures::{Stream, StreamExt};
30use snafu::ensure;
31use store_api::metadata::RegionMetadataRef;
32use store_api::region_engine::{
33    PrepareRequest, QueryScanContext, RegionScanner, ScannerProperties,
34};
35
36use crate::error::{PartitionOutOfRangeSnafu, Result};
37use crate::read::pruner::{PartitionPruner, Pruner};
38use crate::read::scan_region::{ScanInput, StreamContext};
39use crate::read::scan_util::{
40    PartitionMetrics, PartitionMetricsList, scan_flat_file_ranges, scan_flat_mem_ranges,
41};
42use crate::read::stream::{ConvertBatchStream, ScanBatch, ScanBatchStream};
43use crate::read::{ScannerMetrics, scan_util};
44
45/// Scans a region without providing any output ordering guarantee.
46///
47/// Only an append only table should use this scanner.
48pub struct UnorderedScan {
49    /// Properties of the scanner.
50    properties: ScannerProperties,
51    /// Context of streams.
52    stream_ctx: Arc<StreamContext>,
53    /// Shared pruner for file range building.
54    pruner: Arc<Pruner>,
55    /// Metrics for each partition.
56    metrics_list: PartitionMetricsList,
57}
58
59impl UnorderedScan {
60    /// Creates a new [UnorderedScan].
61    pub(crate) fn new(input: ScanInput) -> Self {
62        let mut properties = ScannerProperties::default()
63            .with_append_mode(input.append_mode)
64            .with_total_rows(input.total_rows())
65            .with_total_rows_is_exact(input.append_mode && input.total_rows_is_exact());
66        if let Some(counters) = input.query_stat_counters.clone() {
67            properties.set_query_stat_counters(counters);
68        }
69        let stream_ctx = Arc::new(StreamContext::unordered_scan_ctx(input));
70        properties.partitions = vec![stream_ctx.partition_ranges()];
71
72        // Create the shared pruner with number of workers equal to CPU cores.
73        let num_workers = common_stat::get_total_cpu_cores().max(1);
74        let pruner = Arc::new(Pruner::new(stream_ctx.clone(), num_workers));
75
76        Self {
77            properties,
78            stream_ctx,
79            pruner,
80            metrics_list: PartitionMetricsList::default(),
81        }
82    }
83
84    /// Scans the region and returns a stream.
85    #[tracing::instrument(
86        skip_all,
87        fields(region_id = %self.stream_ctx.input.mapper.metadata().region_id)
88    )]
89    pub(crate) async fn build_stream(&self) -> Result<SendableRecordBatchStream, BoxedError> {
90        let metrics_set = ExecutionPlanMetricsSet::new();
91        let part_num = self.properties.num_partitions();
92        let streams = (0..part_num)
93            .map(|i| self.scan_partition(&QueryScanContext::default(), &metrics_set, i))
94            .collect::<Result<Vec<_>, BoxedError>>()?;
95        let stream = stream! {
96            for mut stream in streams {
97                while let Some(rb) = stream.next().await {
98                    yield rb;
99                }
100            }
101        };
102        let stream = Box::pin(RecordBatchStreamWrapper::new(
103            self.schema(),
104            Box::pin(stream),
105        ));
106        Ok(stream)
107    }
108
109    /// Scans a [PartitionRange] by its `identifier` and returns a flat stream of RecordBatch.
110    #[tracing::instrument(
111        skip_all,
112        fields(
113            region_id = %stream_ctx.input.region_metadata().region_id,
114            part_range_id = part_range_id
115        )
116    )]
117    fn scan_flat_partition_range(
118        stream_ctx: Arc<StreamContext>,
119        part_range_id: usize,
120        part_metrics: PartitionMetrics,
121        partition_pruner: Arc<PartitionPruner>,
122    ) -> impl Stream<Item = Result<RecordBatch>> {
123        try_stream! {
124            // Gets range meta.
125            let range_meta = &stream_ctx.ranges[part_range_id];
126            let part_range = range_meta.new_partition_range(part_range_id);
127            let pre_filter_mode = stream_ctx.range_pre_filter_mode(&part_range);
128            for index in &range_meta.row_group_indices {
129                if stream_ctx.is_mem_range_index(*index) {
130                    let stream = scan_flat_mem_ranges(
131                        stream_ctx.clone(),
132                        part_metrics.clone(),
133                        *index,
134                        range_meta.time_range,
135                    );
136                    for await record_batch in stream {
137                        yield record_batch?;
138                    }
139                } else if stream_ctx.is_file_range_index(*index) {
140                    // Common manifest-level fast-skip shared by UnorderedScan and SeqScan.
141                    if partition_pruner
142                        .try_skip_manifest_pruned_file_range(*index, &part_metrics)
143                    {
144                        continue;
145                    }
146                    let stream = scan_flat_file_ranges(
147                        stream_ctx.clone(),
148                        part_metrics.clone(),
149                        *index,
150                        "unordered_scan_files",
151                        partition_pruner.clone(),
152                    ).await?;
153                    for await record_batch in stream {
154                        yield record_batch?;
155                    }
156                } else {
157                    let stream = scan_util::maybe_scan_flat_other_ranges(
158                        &stream_ctx,
159                        *index,
160                        &part_metrics,
161                        pre_filter_mode,
162                    ).await?;
163                    for await record_batch in stream {
164                        yield record_batch?;
165                    }
166                }
167            }
168        }
169    }
170
171    /// Scan [`Batch`] in all partitions one by one.
172    pub(crate) fn scan_all_partitions(&self) -> Result<ScanBatchStream> {
173        let metrics_set = ExecutionPlanMetricsSet::new();
174
175        let streams = (0..self.properties.partitions.len())
176            .map(|partition| {
177                let metrics = self.partition_metrics(false, partition, &metrics_set);
178                self.scan_flat_batch_in_partition(partition, metrics)
179            })
180            .collect::<Result<Vec<_>>>()?;
181
182        Ok(Box::pin(futures::stream::iter(streams).flatten()))
183    }
184
185    fn partition_metrics(
186        &self,
187        explain_verbose: bool,
188        partition: usize,
189        metrics_set: &ExecutionPlanMetricsSet,
190    ) -> PartitionMetrics {
191        let part_metrics = PartitionMetrics::new(
192            self.stream_ctx.input.mapper.metadata().region_id,
193            partition,
194            "UnorderedScan",
195            self.stream_ctx.query_start,
196            explain_verbose,
197            metrics_set,
198        );
199        self.metrics_list.set(partition, part_metrics.clone());
200        part_metrics
201    }
202
203    #[tracing::instrument(
204        skip_all,
205        fields(
206            region_id = %self.stream_ctx.input.mapper.metadata().region_id,
207            partition = partition
208        )
209    )]
210    fn scan_partition_impl(
211        &self,
212        ctx: &QueryScanContext,
213        metrics_set: &ExecutionPlanMetricsSet,
214        partition: usize,
215    ) -> Result<SendableRecordBatchStream> {
216        if ctx.explain_verbose {
217            common_telemetry::info!(
218                "UnorderedScan partition {}, region_id: {}",
219                partition,
220                self.stream_ctx.input.region_metadata().region_id
221            );
222        }
223
224        let metrics = self.partition_metrics(ctx.explain_verbose, partition, metrics_set);
225        let input = &self.stream_ctx.input;
226
227        let batch_stream = self.scan_flat_batch_in_partition(partition, metrics.clone())?;
228
229        let record_batch_stream = ConvertBatchStream::new(
230            batch_stream,
231            input.mapper.clone(),
232            input.cache_strategy.clone(),
233            metrics,
234        );
235
236        Ok(Box::pin(RecordBatchStreamWrapper::new(
237            input.mapper.output_schema(),
238            Box::pin(record_batch_stream),
239        )))
240    }
241
242    #[tracing::instrument(
243        skip_all,
244        fields(
245            region_id = %self.stream_ctx.input.mapper.metadata().region_id,
246            partition = partition
247        )
248    )]
249    fn scan_flat_batch_in_partition(
250        &self,
251        partition: usize,
252        part_metrics: PartitionMetrics,
253    ) -> Result<ScanBatchStream> {
254        ensure!(
255            partition < self.properties.partitions.len(),
256            PartitionOutOfRangeSnafu {
257                given: partition,
258                all: self.properties.partitions.len(),
259            }
260        );
261
262        let stream_ctx = self.stream_ctx.clone();
263        let part_ranges = self.properties.partitions[partition].clone();
264        let pruner = self.pruner.clone();
265        // Initializes ref counts for the pruner.
266        // If we call scan_batch_in_partition() multiple times but don't read all batches from the stream,
267        // then the ref count won't be decremented.
268        // This is a rare case and keeping all remaining entries still uses less memory than a per partition cache.
269        pruner.add_partition_ranges(&part_ranges);
270        let partition_pruner = Arc::new(PartitionPruner::new(pruner, &part_ranges));
271
272        let stream = try_stream! {
273            part_metrics.on_first_poll();
274
275            // Scans each part.
276            for part_range in part_ranges {
277                let mut metrics = ScannerMetrics::default();
278                let mut fetch_start = Instant::now();
279
280                let stream = Self::scan_flat_partition_range(
281                    stream_ctx.clone(),
282                    part_range.identifier,
283                    part_metrics.clone(),
284                    partition_pruner.clone(),
285                );
286                for await record_batch in stream {
287                    let record_batch = record_batch?;
288                    metrics.scan_cost += fetch_start.elapsed();
289                    metrics.num_batches += 1;
290                    metrics.num_rows += record_batch.num_rows();
291
292                    debug_assert!(record_batch.num_rows() > 0);
293                    if record_batch.num_rows() == 0 {
294                        continue;
295                    }
296
297                    let yield_start = Instant::now();
298                    yield ScanBatch::RecordBatch(record_batch);
299                    metrics.yield_cost += yield_start.elapsed();
300
301                    fetch_start = Instant::now();
302                }
303
304                metrics.scan_cost += fetch_start.elapsed();
305                part_metrics.merge_metrics(&metrics);
306            }
307
308            part_metrics.on_finish();
309        };
310        Ok(Box::pin(stream))
311    }
312}
313
314impl RegionScanner for UnorderedScan {
315    fn name(&self) -> &str {
316        "UnorderedScan"
317    }
318
319    fn properties(&self) -> &ScannerProperties {
320        &self.properties
321    }
322
323    fn schema(&self) -> SchemaRef {
324        self.stream_ctx.input.mapper.output_schema()
325    }
326
327    fn metadata(&self) -> RegionMetadataRef {
328        self.stream_ctx.input.mapper.metadata().clone()
329    }
330
331    fn prepare(&mut self, request: PrepareRequest) -> Result<(), BoxedError> {
332        self.properties.prepare(request);
333
334        Ok(())
335    }
336
337    fn scan_partition(
338        &self,
339        ctx: &QueryScanContext,
340        metrics_set: &ExecutionPlanMetricsSet,
341        partition: usize,
342    ) -> Result<SendableRecordBatchStream, BoxedError> {
343        self.scan_partition_impl(ctx, metrics_set, partition)
344            .map_err(BoxedError::new)
345    }
346
347    /// If this scanner have predicate other than region partition exprs
348    fn has_predicate_without_region(&self) -> bool {
349        let predicate = self
350            .stream_ctx
351            .input
352            .predicate_group()
353            .predicate_without_region();
354        predicate.is_some()
355    }
356
357    fn add_dyn_filter_to_predicate(
358        &mut self,
359        filter_exprs: Vec<Arc<dyn datafusion::physical_plan::PhysicalExpr>>,
360    ) -> Vec<bool> {
361        self.stream_ctx.add_dyn_filter_to_predicate(filter_exprs)
362    }
363
364    fn reset_state(&mut self) {
365        self.stream_ctx.input.predicate.clear_dyn_filters();
366        let num_workers = common_stat::get_total_cpu_cores().max(1);
367        self.pruner = Arc::new(Pruner::new(self.stream_ctx.clone(), num_workers));
368        self.metrics_list = PartitionMetricsList::default();
369    }
370
371    fn set_logical_region(&mut self, logical_region: bool) {
372        self.properties.set_logical_region(logical_region);
373    }
374
375    fn set_query_load_region_id(&mut self, region_id: store_api::storage::RegionId) {
376        self.properties.set_query_load_region_id(region_id);
377    }
378
379    fn snapshot_sequence(&self) -> Option<u64> {
380        self.stream_ctx.input.snapshot_sequence
381    }
382}
383
384impl DisplayAs for UnorderedScan {
385    fn fmt_as(&self, t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
386        write!(
387            f,
388            "UnorderedScan: region={}, ",
389            self.stream_ctx.input.mapper.metadata().region_id
390        )?;
391        match t {
392            DisplayFormatType::Default | DisplayFormatType::TreeRender => {
393                self.stream_ctx.format_for_explain(false, f)
394            }
395            DisplayFormatType::Verbose => {
396                self.stream_ctx.format_for_explain(true, f)?;
397                self.metrics_list.format_verbose_metrics(f)
398            }
399        }
400    }
401}
402
403impl fmt::Debug for UnorderedScan {
404    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
405        f.debug_struct("UnorderedScan")
406            .field("num_ranges", &self.stream_ctx.ranges.len())
407            .finish()
408    }
409}
410
411#[cfg(test)]
412impl UnorderedScan {
413    /// Returns the input.
414    pub(crate) fn input(&self) -> &ScanInput {
415        &self.stream_ctx.input
416    }
417}