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