Skip to main content

mito2/read/
series_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//! Per-series scan implementation.
16
17pub(crate) mod prepared;
18mod raw;
19
20use std::collections::HashSet;
21use std::fmt;
22#[cfg(test)]
23use std::sync::atomic::{AtomicUsize, Ordering};
24use std::sync::{Arc, Mutex};
25use std::time::Instant;
26
27use api::v1::SemanticType;
28use async_stream::try_stream;
29use common_error::ext::BoxedError;
30use common_query::native_histogram::is_native_histogram_value_type;
31use common_recordbatch::util::ChainedRecordBatchStream;
32use common_recordbatch::{RecordBatchStreamWrapper, SendableRecordBatchStream};
33use common_telemetry::tracing::{self, Instrument};
34use common_telemetry::{debug, warn};
35use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet;
36use datafusion::physical_plan::{DisplayAs, DisplayFormatType, PhysicalExpr};
37use datafusion_common::tree_node::TreeNode;
38use datafusion_expr::{Expr, Volatility};
39use datatypes::arrow::array::BinaryArray;
40use datatypes::arrow::datatypes::DataType as ArrowDataType;
41use datatypes::arrow::record_batch::RecordBatch;
42use datatypes::prelude::ConcreteDataType;
43use datatypes::schema::SchemaRef;
44use datatypes::series::SeriesOrdering;
45use datatypes::series::samples::{FieldSpec, SeriesSchema};
46use futures::{StreamExt, TryStreamExt};
47use smallvec::SmallVec;
48use snafu::{OptionExt, ResultExt, ensure};
49use store_api::metadata::RegionMetadataRef;
50use store_api::metric_engine_consts::is_metric_engine_internal_column;
51use store_api::region_engine::{
52    PartitionRange, PrepareRequest, QueryScanContext, RawLabelSource, RegionScanner,
53    ScannerProperties, SendableRawSeriesStream,
54};
55use store_api::storage::consts::{ReservedColumnId, is_internal_column};
56use table::predicate::Predicate;
57use tokio::sync::Semaphore;
58use tokio::sync::mpsc::error::TrySendError;
59use tokio::sync::mpsc::{self, Receiver, Sender};
60
61use crate::error::{
62    Error, InvalidRecordBatchSnafu, InvalidSenderSnafu, JoinSnafu, PartitionOutOfRangeSnafu,
63    Result, ScanMultiTimesSnafu, ScanSeriesSnafu, TooManyFilesToReadSnafu,
64};
65use crate::metrics::SCAN_MAX_CONCURRENT_FILES;
66use crate::read::ScannerMetrics;
67use crate::read::pruner::{PartitionPruner, Pruner};
68use crate::read::scan_region::{ScanInput, StreamContext};
69use crate::read::scan_util::{
70    PartitionMetrics, PartitionMetricsList, SeriesDistributorMetrics, compute_average_batch_size,
71    compute_parallel_channel_size,
72};
73use crate::read::seq_scan::{FlatReadMode, SeqScan};
74use crate::read::stream::{ConvertBatchStream, ScanBatch, ScanBatchStream};
75use crate::series_index::is_sparse_metric_metadata;
76use crate::sst::parquet::flat_format::primary_key_column_index;
77use crate::sst::parquet::format::PrimaryKeyArray;
78
79/// Legacy data receivers for output partitions.
80type LegacyReceiverList = Vec<Option<Receiver<Result<SeriesBatch>>>>;
81
82#[derive(Clone)]
83pub(crate) struct RawScanPreparation {
84    schema: Arc<SeriesSchema>,
85    fields: Vec<(usize, ConcreteDataType)>,
86    predicates: Vec<Arc<dyn PhysicalExpr>>,
87}
88
89/// Memoized raw-scan preflight: the label binding it was computed for, and its answer.
90///
91/// A cached `None` means the scan cannot serve this label binding.
92type PreflightCache = Option<(RawLabelSource, Option<RawScanPreparation>)>;
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95enum SeriesScanMode {
96    Prepared,
97    Legacy,
98}
99
100impl SeriesScanMode {
101    fn as_str(self) -> &'static str {
102        match self {
103            Self::Prepared => "prepared",
104            Self::Legacy => "legacy",
105        }
106    }
107}
108
109/// Scans a region and returns sorted rows of a series in the same partition.
110///
111/// The output order is always order by `(primary key, time index)` inside every
112/// partition.
113/// Always returns the same series (primary key) to the same partition.
114pub struct SeriesScan {
115    /// Implementation used by this scan.
116    mode: SeriesScanMode,
117    prepared: Arc<prepared::Preparation>,
118    /// Properties of the scanner.
119    properties: ScannerProperties,
120    /// Context of streams.
121    stream_ctx: Arc<StreamContext>,
122    /// Shared pruner for file range building.
123    pruner: Arc<Pruner>,
124    /// Legacy data receivers for each partition.
125    legacy_receivers: Mutex<LegacyReceiverList>,
126    /// Metrics for each partition.
127    /// The scanner only sets in query and keeps it empty during compaction.
128    metrics_list: Arc<PartitionMetricsList>,
129    /// Memoized result of [`Self::prepare_raw_scan`] for the label binding it was computed for.
130    ///
131    /// Preflight only reads pinned scanner state, and one execution asks for it once per output
132    /// partition, so the first answer serves the rest. Errors are never stored, and every entry
133    /// that mutates the state the answer depends on clears the entry. The guard is taken and
134    /// released inside a synchronous call, so it never spans an await.
135    preflight: Mutex<PreflightCache>,
136    /// Test-only number of preflight computations performed by this scanner.
137    ///
138    /// A cached answer does not increment it, so a test can prove that a repeated preflight over
139    /// the same pinned state is served from [`Self::preflight`].
140    #[cfg(test)]
141    preflight_runs: AtomicUsize,
142}
143
144impl SeriesScan {
145    /// Creates a new [SeriesScan].
146    pub(crate) fn new(input: ScanInput) -> Self {
147        let mode = if input.requires_narthex_preparation() {
148            SeriesScanMode::Prepared
149        } else {
150            SeriesScanMode::Legacy
151        };
152        let mut properties = input.scanner_properties();
153        let stream_ctx = Arc::new(StreamContext::seq_scan_ctx(input));
154        properties.partitions = vec![stream_ctx.partition_ranges()];
155
156        // Create the shared pruner with number of workers equal to CPU cores.
157        let num_workers = common_stat::get_total_cpu_cores().max(1);
158        let pruner = Arc::new(Pruner::new(stream_ctx.clone(), num_workers));
159
160        Self {
161            mode,
162            prepared: Arc::new(prepared::Preparation::default()),
163            properties,
164            stream_ctx,
165            pruner,
166            legacy_receivers: Mutex::new(Vec::new()),
167            metrics_list: Arc::new(PartitionMetricsList::default()),
168            preflight: Mutex::new(None),
169            #[cfg(test)]
170            preflight_runs: AtomicUsize::new(0),
171        }
172    }
173
174    /// Returns the number of preflight computations this scanner has run.
175    ///
176    /// Test-only: a memoized preflight does not count, so a test can distinguish a cache hit from a
177    /// recomputation.
178    #[cfg(test)]
179    pub(crate) fn preflight_runs(&self) -> usize {
180        self.preflight_runs.load(Ordering::Relaxed)
181    }
182
183    /// Drops the memoized preflight.
184    ///
185    /// Every entry point that mutates state the preflight reads calls this, so a stale answer can
186    /// never outlive the state it was derived from.
187    fn clear_preflight_cache(&self) {
188        *self.preflight.lock().unwrap() = None;
189    }
190
191    /// Returns the memoized preflight, if it was computed for the same label binding.
192    ///
193    /// A binding only matches when its immutable identity matches as well: the preflight validates
194    /// the pinned metadata snapshot and the label binding, so an answer for another binding must
195    /// never be reused even when the labels look alike.
196    fn cached_preflight(
197        &self,
198        label_source: &RawLabelSource,
199    ) -> Option<Option<RawScanPreparation>> {
200        let cache = self.preflight.lock().unwrap();
201        let (cached_source, cached) = cache.as_ref()?;
202        if !prepared::same_labels(cached_source, label_source) {
203            return None;
204        }
205        Some(cached.clone())
206    }
207
208    /// Prepares the raw scan for the supplied label binding.
209    ///
210    /// The answer only depends on pinned scanner state plus the label binding, and an execution
211    /// asks for it once per output partition, so it is memoized per binding. Only successful
212    /// answers are stored: a rejected binding must fail on every call, not replay a rejection or
213    /// hide a later one.
214    fn prepare_raw_scan(
215        &self,
216        label_source: &RawLabelSource,
217    ) -> Result<Option<RawScanPreparation>, BoxedError> {
218        if let Some(cached) = self.cached_preflight(label_source) {
219            return Ok(cached);
220        }
221        let computed = self.prepare_raw_scan_uncached(label_source)?;
222        if self.stream_ctx.input.requires_narthex_preparation() && computed.is_none() {
223            return Err(BoxedError::new(
224                InvalidRecordBatchSnafu {
225                    reason: "Narthex raw scans require prepared-series support",
226                }
227                .build(),
228            ));
229        }
230        // Both sides of the cache are cheap to clone, and callers own their copy: the merge schema
231        // helper rewrites the field indices and predicates of the preparation it is given, which
232        // must never reach the stored answer.
233        *self.preflight.lock().unwrap() = Some((label_source.clone(), computed.clone()));
234        Ok(computed)
235    }
236
237    /// Computes a fresh [`Self::prepare_raw_scan`] answer from the pinned scanner state.
238    fn prepare_raw_scan_uncached(
239        &self,
240        label_source: &RawLabelSource,
241    ) -> Result<Option<RawScanPreparation>, BoxedError> {
242        #[cfg(test)]
243        self.preflight_runs.fetch_add(1, Ordering::Relaxed);
244        let input = &self.stream_ctx.input;
245        let metadata = input.mapper.metadata();
246        match label_source {
247            RawLabelSource::PrimaryKey {
248                physical_metadata,
249                logical_tags,
250                ..
251            } => {
252                if !Arc::ptr_eq(metadata, physical_metadata) {
253                    debug!(
254                        "Raw series scan preflight rejected metadata snapshot: region_id={}, physical_region_id={}, schema_version={}, physical_schema_version={}",
255                        metadata.region_id,
256                        physical_metadata.region_id,
257                        metadata.schema_version,
258                        physical_metadata.schema_version,
259                    );
260                    return Err(BoxedError::new(
261                        InvalidRecordBatchSnafu {
262                            reason: "raw label source metadata does not match scanner snapshot"
263                                .to_string(),
264                        }
265                        .build(),
266                    ));
267                }
268                let mut ids = HashSet::new();
269                let mut names = HashSet::new();
270                for tag in logical_tags.iter() {
271                    let column = metadata.column_by_id(tag.column_id).filter(|column| {
272                        column.semantic_type == SemanticType::Tag
273                            && metadata.primary_key.contains(&tag.column_id)
274                    });
275                    let valid = column.is_some_and(|column| {
276                        column.column_schema.name == tag.name.as_ref()
277                            && tag.name.as_ref() != "__name__"
278                            && !is_internal_column(tag.name.as_ref())
279                            && !is_metric_engine_internal_column(tag.name.as_ref())
280                            && !ReservedColumnId::is_reserved(tag.column_id)
281                    });
282                    let unique_id = valid && ids.insert(tag.column_id);
283                    let unique_name = unique_id && names.insert(tag.name.as_ref());
284                    if !valid || !unique_id || !unique_name {
285                        debug!(
286                            "Raw series scan preflight rejected label binding: region_id={}, column_id={}, binding_valid={}, unique_id={}, unique_name={}",
287                            metadata.region_id, tag.column_id, valid, unique_id, unique_name,
288                        );
289                        return Err(BoxedError::new(
290                            InvalidRecordBatchSnafu {
291                                reason: "invalid raw label binding".to_string(),
292                            }
293                            .build(),
294                        ));
295                    }
296                }
297            }
298            RawLabelSource::Explicit => {
299                debug!(
300                    "Raw series scan preflight rejected explicit labels: region_id={}",
301                    metadata.region_id,
302                );
303                return Ok(None);
304            }
305        }
306        let narthex = input.requires_narthex_preparation();
307        if narthex && !is_sparse_metric_metadata(metadata) {
308            return Ok(None);
309        }
310        let selected = input.mapper.output_schema();
311        let mut fields = Vec::new();
312        let mut specs = Vec::new();
313        for output in selected.column_schemas() {
314            let Some(column) = metadata.column_metadatas.iter().find(|column| {
315                column.column_schema.name == output.name
316                    && column.semantic_type == SemanticType::Field
317            }) else {
318                continue;
319            };
320            let Some((index, (_, data_type))) = input
321                .mapper
322                .batch_schema()
323                .iter()
324                .enumerate()
325                .find(|(_, (id, _))| *id == column.column_id)
326            else {
327                debug!(
328                    "Raw series scan preflight missing mapper field: region_id={}, column_id={}",
329                    metadata.region_id, column.column_id,
330                );
331                return Err(BoxedError::new(
332                    InvalidRecordBatchSnafu {
333                        reason: format!(
334                            "selected field {} is missing from mapper batch schema",
335                            output.name
336                        ),
337                    }
338                    .build(),
339                ));
340            };
341            // The raw converter casts a numeric field to `Float64` and converts a native histogram
342            // struct into histogram samples; nothing else has a raw representation.
343            let numeric = if narthex {
344                *data_type == ConcreteDataType::float64_datatype()
345            } else {
346                data_type.is_numeric()
347            };
348            if !numeric && !is_native_histogram_value_type(data_type) {
349                debug!(
350                    "Raw series scan preflight rejected field type: region_id={}, column_id={}",
351                    metadata.region_id, column.column_id,
352                );
353                return Ok(None);
354            }
355            fields.push((index, data_type.clone()));
356            specs.push(FieldSpec {
357                name: Arc::from(output.name.as_str()),
358            });
359        }
360        if fields.is_empty() || input.series_row_selector.is_some() {
361            debug!(
362                "Raw series scan preflight rejected scan options: region_id={}, selected_fields={}, append_mode={}, row_selector={}",
363                metadata.region_id,
364                fields.len(),
365                input.append_mode,
366                input.series_row_selector.is_some(),
367            );
368            return Ok(None);
369        }
370        let schema = Arc::new(SeriesSchema {
371            fields: specs.into(),
372            eval_grid: None,
373        });
374        let typed_schema = input.mapper.input_arrow_schema(false);
375        let mut predicates = Vec::new();
376        let predicate = if narthex {
377            input.predicate_group().predicate()
378        } else {
379            // The ordinary scan applies region predicates before this residual filtering.
380            input.predicate_group().predicate_without_region()
381        };
382        if let Some(predicate) = predicate {
383            if !predicate.dyn_filters().is_empty() {
384                debug!(
385                    "Raw series scan preflight rejected dynamic predicate filters: region_id={}",
386                    metadata.region_id,
387                );
388                return Ok(None);
389            }
390            for expr in predicate.exprs() {
391                // Fresh execution properties cannot preserve Stable or query-dependent semantics.
392                if expr
393                    .exists(|node| {
394                        Ok(matches!(node, Expr::ScalarFunction(function)
395                            if function.func.signature().volatility != Volatility::Immutable)
396                            || matches!(node, Expr::ScalarVariable(..)))
397                    })
398                    .unwrap_or(true)
399                {
400                    debug!(
401                        "Raw series scan preflight rejected predicate volatility or variable: region_id={}",
402                        metadata.region_id,
403                    );
404                    return Ok(None);
405                }
406                // Evaluate residuals with original types before raw conversion to Float64.
407                let Ok(physical) = Predicate::to_physical_expr(expr, &typed_schema) else {
408                    debug!(
409                        "Raw series scan preflight failed predicate compilation: region_id={}",
410                        metadata.region_id,
411                    );
412                    return Ok(None);
413                };
414                if !matches!(
415                    physical.data_type(&typed_schema),
416                    Ok(ArrowDataType::Boolean | ArrowDataType::Null)
417                ) {
418                    debug!(
419                        "Raw series scan preflight rejected predicate type: region_id={}",
420                        metadata.region_id,
421                    );
422                    return Ok(None);
423                }
424                predicates.push(physical);
425            }
426        }
427        Ok(Some(RawScanPreparation {
428            schema,
429            fields,
430            predicates,
431        }))
432    }
433
434    /// Starts scanner-wide preparation from the preflight already performed by the caller.
435    fn prepare_series_with_raw(
436        &self,
437        ctx: &QueryScanContext,
438        metrics_set: &ExecutionPlanMetricsSet,
439        label_source: &RawLabelSource,
440        preparation: Result<Option<RawScanPreparation>, BoxedError>,
441    ) -> futures::future::BoxFuture<
442        'static,
443        Result<Option<Arc<dyn store_api::region_engine::PreparedSeriesSource>>, BoxedError>,
444    > {
445        let scan_pool = ctx.memory_pool.clone();
446        let state = self.prepared.clone();
447        let stream_ctx = self.stream_ctx.clone();
448        let ranges = self
449            .properties
450            .partitions
451            .iter()
452            .flatten()
453            .copied()
454            .collect();
455        let labels = label_source.clone();
456        let metrics = new_partition_metrics(
457            &self.stream_ctx,
458            ctx.explain_verbose,
459            metrics_set,
460            0,
461            &self.metrics_list,
462        );
463        Box::pin(async move {
464            let Some(preparation) = preparation? else {
465                return Ok(None);
466            };
467            state
468                .prepare(stream_ctx, ranges, labels, preparation, metrics, scan_pool)
469                .await
470                .map(Some)
471        })
472    }
473
474    #[tracing::instrument(
475        skip_all,
476        fields(
477            region_id = %self.stream_ctx.input.mapper.metadata().region_id,
478            partition = partition
479        )
480    )]
481    fn scan_partition_impl(
482        &self,
483        ctx: &QueryScanContext,
484        metrics_set: &ExecutionPlanMetricsSet,
485        partition: usize,
486    ) -> Result<SendableRecordBatchStream> {
487        let metrics = new_partition_metrics(
488            &self.stream_ctx,
489            ctx.explain_verbose,
490            metrics_set,
491            partition,
492            &self.metrics_list,
493        );
494
495        let batch_stream =
496            self.scan_batch_in_partition(ctx, partition, metrics.clone(), metrics_set)?;
497
498        let input = &self.stream_ctx.input;
499        let record_batch_stream = ConvertBatchStream::new(
500            batch_stream,
501            input.mapper.clone(),
502            input.cache_strategy.clone(),
503            metrics,
504        );
505
506        Ok(Box::pin(RecordBatchStreamWrapper::new(
507            input.mapper.output_schema(),
508            Box::pin(record_batch_stream),
509        )))
510    }
511
512    #[tracing::instrument(
513        skip_all,
514        fields(
515            region_id = %self.stream_ctx.input.mapper.metadata().region_id,
516            partition = partition
517        )
518    )]
519    fn scan_batch_in_partition(
520        &self,
521        ctx: &QueryScanContext,
522        partition: usize,
523        part_metrics: PartitionMetrics,
524        metrics_set: &ExecutionPlanMetricsSet,
525    ) -> Result<ScanBatchStream> {
526        if ctx.explain_verbose {
527            common_telemetry::info!(
528                "SeriesScan partition {}, region_id: {}",
529                partition,
530                self.stream_ctx.input.region_metadata().region_id
531            );
532        }
533
534        ensure!(
535            partition < self.properties.num_partitions(),
536            PartitionOutOfRangeSnafu {
537                given: partition,
538                all: self.properties.num_partitions(),
539            }
540        );
541
542        match self.mode {
543            SeriesScanMode::Prepared => Ok(prepared::scan_batches(
544                self.prepared.clone(),
545                self.stream_ctx.clone(),
546                self.properties
547                    .partitions
548                    .iter()
549                    .flatten()
550                    .copied()
551                    .collect(),
552                partition,
553                self.properties.num_partitions().max(1),
554                part_metrics,
555                ctx.memory_pool.clone(),
556            )),
557            SeriesScanMode::Legacy => self.scan_legacy_batch_in_partition(
558                partition,
559                part_metrics,
560                metrics_set,
561                ctx.explain_verbose,
562            ),
563        }
564    }
565
566    fn scan_legacy_batch_in_partition(
567        &self,
568        partition: usize,
569        part_metrics: PartitionMetrics,
570        metrics_set: &ExecutionPlanMetricsSet,
571        explain_verbose: bool,
572    ) -> Result<ScanBatchStream> {
573        self.maybe_start_legacy_distributor(metrics_set, explain_verbose);
574        let mut receiver = self.legacy_receivers.lock().unwrap()[partition]
575            .take()
576            .context(ScanMultiTimesSnafu { partition })?;
577        let stream = try_stream! {
578            part_metrics.on_first_poll();
579
580            let mut fetch_start = Instant::now();
581            let mut metrics = ScannerMetrics::default();
582            while let Some(series) = receiver.recv().await {
583                let series = series?;
584                metrics.scan_cost += fetch_start.elapsed();
585                metrics.num_batches += series.num_batches();
586                metrics.num_rows += series.num_rows();
587
588                let yield_start = Instant::now();
589                yield ScanBatch::Series(series);
590                metrics.yield_cost += yield_start.elapsed();
591                fetch_start = Instant::now();
592            }
593
594            part_metrics.merge_metrics(&metrics);
595            part_metrics.on_finish();
596        };
597        Ok(Box::pin(stream))
598    }
599
600    fn maybe_start_legacy_distributor(
601        &self,
602        metrics_set: &ExecutionPlanMetricsSet,
603        explain_verbose: bool,
604    ) {
605        let mut rx_list = self.legacy_receivers.lock().unwrap();
606        if !rx_list.is_empty() {
607            return;
608        }
609
610        let (senders, receivers) = new_legacy_channel_list(self.properties.num_partitions());
611        let mut distributor = SeriesDistributor {
612            stream_ctx: self.stream_ctx.clone(),
613            range_semaphore: Some(Arc::new(Semaphore::new(self.properties.num_partitions()))),
614            final_merge_semaphore: Some(Arc::new(Semaphore::new(self.properties.num_partitions()))),
615            partitions: self.properties.partitions.clone(),
616            pruner: self.pruner.clone(),
617            senders,
618            metrics_set: metrics_set.clone(),
619            metrics_list: self.metrics_list.clone(),
620            explain_verbose,
621        };
622        let region_id = distributor.stream_ctx.input.mapper.metadata().region_id;
623        let span = tracing::info_span!("SeriesScan::distributor", region_id = %region_id);
624        common_runtime::spawn_query(
625            async move {
626                distributor.execute().await;
627            }
628            .instrument(span),
629        );
630
631        *rx_list = receivers;
632    }
633
634    /// Scans the region and returns a stream.
635    #[tracing::instrument(
636        skip_all,
637        fields(region_id = %self.stream_ctx.input.mapper.metadata().region_id)
638    )]
639    pub(crate) async fn build_stream(&self) -> Result<SendableRecordBatchStream, BoxedError> {
640        let part_num = self.properties.num_partitions();
641        let metrics_set = ExecutionPlanMetricsSet::default();
642        let ctx = QueryScanContext::default();
643        let streams = (0..part_num)
644            .map(|i| self.scan_partition(&ctx, &metrics_set, i))
645            .collect::<Result<Vec<_>, BoxedError>>()?;
646        let chained_stream = ChainedRecordBatchStream::new(streams).map_err(BoxedError::new)?;
647        Ok(Box::pin(chained_stream))
648    }
649
650    /// Scan [`Batch`] in all partitions one by one.
651    pub(crate) fn scan_all_partitions(&self) -> Result<ScanBatchStream> {
652        let metrics_set = ExecutionPlanMetricsSet::new();
653
654        let ctx = QueryScanContext::default();
655        let streams = (0..self.properties.partitions.len())
656            .map(|partition| {
657                let metrics = new_partition_metrics(
658                    &self.stream_ctx,
659                    false,
660                    &metrics_set,
661                    partition,
662                    &self.metrics_list,
663                );
664
665                self.scan_batch_in_partition(&ctx, partition, metrics, &metrics_set)
666            })
667            .collect::<Result<Vec<_>>>()?;
668
669        Ok(Box::pin(futures::stream::iter(streams).flatten()))
670    }
671
672    /// Checks resource limit for the scanner.
673    pub(crate) fn check_scan_limit(&self) -> Result<()> {
674        // Sum the total number of files across all partitions
675        let total_files: usize = self
676            .properties
677            .partitions
678            .iter()
679            .flat_map(|partition| partition.iter())
680            .map(|part_range| {
681                let range_meta = &self.stream_ctx.ranges[part_range.identifier];
682                range_meta.indices.len()
683            })
684            .sum();
685
686        if !self.stream_ctx.input.compaction {
687            SCAN_MAX_CONCURRENT_FILES
688                .with_label_values(&["query"])
689                .observe(total_files as f64);
690        }
691        if self.stream_ctx.input.uses_scan_memory_limit() {
692            return Ok(());
693        }
694
695        let max_concurrent_files = self.stream_ctx.input.max_concurrent_scan_files;
696        if total_files > max_concurrent_files {
697            return TooManyFilesToReadSnafu {
698                actual: total_files,
699                max: max_concurrent_files,
700            }
701            .fail();
702        }
703
704        Ok(())
705    }
706}
707
708fn new_legacy_channel_list(num_partitions: usize) -> (SenderList, LegacyReceiverList) {
709    let (senders, receivers): (Vec<_>, Vec<_>) = (0..num_partitions)
710        .map(|_| {
711            let (sender, receiver) = mpsc::channel(1);
712            (Some(sender), Some(receiver))
713        })
714        .unzip();
715    (SenderList::new(senders), receivers)
716}
717
718impl RegionScanner for SeriesScan {
719    fn name(&self) -> &str {
720        "SeriesScan"
721    }
722
723    fn properties(&self) -> &ScannerProperties {
724        &self.properties
725    }
726
727    fn schema(&self) -> SchemaRef {
728        self.stream_ctx.input.mapper.output_schema()
729    }
730
731    fn metadata(&self) -> RegionMetadataRef {
732        self.stream_ctx.input.mapper.metadata().clone()
733    }
734
735    fn scan_partition(
736        &self,
737        ctx: &QueryScanContext,
738        metrics_set: &ExecutionPlanMetricsSet,
739        partition: usize,
740    ) -> Result<SendableRecordBatchStream, BoxedError> {
741        self.scan_partition_impl(ctx, metrics_set, partition)
742            .map_err(BoxedError::new)
743    }
744
745    fn raw_series_ordering(&self) -> Result<SeriesOrdering, BoxedError> {
746        // Both prepared-columnar and ordinary scans guarantee key/time order.
747        Ok(SeriesOrdering::KeyThenTime)
748    }
749
750    fn raw_series_schema(
751        &self,
752        label_source: &RawLabelSource,
753    ) -> Result<Option<Arc<SeriesSchema>>, BoxedError> {
754        Ok(self
755            .prepare_raw_scan(label_source)?
756            .map(|preparation| preparation.schema))
757    }
758
759    fn raw_series_has_explicit_labels(&self, labels: &RawLabelSource) -> Result<bool, BoxedError> {
760        let Some(mut raw) = self.prepare_raw_scan(labels)? else {
761            return Ok(false);
762        };
763        Ok(self.mode == SeriesScanMode::Prepared
764            && prepared::sample_merge_schema(&self.stream_ctx, &mut raw)
765                .map_err(BoxedError::new)?
766                .is_some())
767    }
768
769    fn scan_series_partition(
770        &self,
771        ctx: &QueryScanContext,
772        metrics_set: &ExecutionPlanMetricsSet,
773        partition: usize,
774        label_source: &RawLabelSource,
775    ) -> Result<Option<SendableRawSeriesStream>, BoxedError> {
776        let Some(preparation) = self.prepare_raw_scan(label_source)? else {
777            return Ok(None);
778        };
779        if self.mode == SeriesScanMode::Prepared {
780            let partitions = self.properties.num_partitions().max(1);
781            if partition >= partitions {
782                return Err(BoxedError::new(
783                    PartitionOutOfRangeSnafu {
784                        given: partition,
785                        all: partitions,
786                    }
787                    .build(),
788                ));
789            }
790            // Preflight needs the declaration before the stream is polled, while preparation
791            // needs the original field indices and predicates to derive its own merge schema.
792            let explicit_labels =
793                prepared::sample_merge_schema(&self.stream_ctx, &mut preparation.clone())
794                    .map_err(BoxedError::new)?
795                    .is_some();
796            let schema = preparation.schema.clone();
797            let preparation = self
798                .check_scan_limit()
799                .map_err(BoxedError::new)
800                .map(|_| Some(preparation));
801            let future = self.prepare_series_with_raw(ctx, metrics_set, label_source, preparation);
802            let labels = label_source.clone();
803            let stream = async_stream::try_stream! {
804                let source = future.await?.ok_or_else(|| BoxedError::new(InvalidRecordBatchSnafu { reason: "columnar prepared capability disappeared" }.build()))?;
805                let n = source.num_series() as u128;
806                let start = (n * partition as u128 / partitions as u128) as usize;
807                let end = (n * (partition + 1) as u128 / partitions as u128) as usize;
808                let mut reader = source.read_series(start..end)?;
809                while let Some(chunk) = reader.try_next().await? { yield chunk; }
810            };
811            return Ok(Some(raw::from_stream(
812                schema,
813                labels,
814                SeriesOrdering::KeyThenTime,
815                explicit_labels,
816                Box::pin(stream),
817            )));
818        }
819        // Read Parquet regions through the ordinary per-series scan.
820        let metrics = new_partition_metrics(
821            &self.stream_ctx,
822            ctx.explain_verbose,
823            metrics_set,
824            partition,
825            &self.metrics_list,
826        );
827        let batches = self
828            .scan_batch_in_partition(ctx, partition, metrics.clone(), metrics_set)
829            .map_err(BoxedError::new)?;
830        Ok(Some(raw::make_stream(
831            batches,
832            preparation.schema,
833            label_source.clone(),
834            preparation.fields,
835            metrics,
836            preparation.predicates,
837            SeriesOrdering::KeyThenTime,
838            self.stream_ctx.input.append_mode,
839        )))
840    }
841
842    fn prepare_series(
843        &self,
844        ctx: &QueryScanContext,
845        metrics_set: &ExecutionPlanMetricsSet,
846        label_source: &RawLabelSource,
847    ) -> futures::future::BoxFuture<
848        'static,
849        Result<Option<Arc<dyn store_api::region_engine::PreparedSeriesSource>>, BoxedError>,
850    > {
851        if !self.stream_ctx.input.requires_narthex_preparation() {
852            return Box::pin(async { Ok(None) });
853        }
854        let preparation = self
855            .check_scan_limit()
856            .map_err(BoxedError::new)
857            .and_then(|_| self.prepare_raw_scan(label_source));
858        self.prepare_series_with_raw(ctx, metrics_set, label_source, preparation)
859    }
860
861    fn prepare(&mut self, request: PrepareRequest) -> Result<(), BoxedError> {
862        self.prepared = Arc::new(prepared::Preparation::default());
863        self.clear_preflight_cache();
864        self.properties.prepare(request);
865
866        self.check_scan_limit().map_err(BoxedError::new)?;
867
868        Ok(())
869    }
870
871    fn has_predicate_without_region(&self) -> bool {
872        let predicate = self
873            .stream_ctx
874            .input
875            .predicate_group()
876            .predicate_without_region();
877        predicate.is_some()
878    }
879
880    fn add_dyn_filter_to_predicate(
881        &mut self,
882        filter_exprs: Vec<Arc<dyn datafusion::physical_plan::PhysicalExpr>>,
883    ) -> Vec<bool> {
884        if self.stream_ctx.input.requires_narthex_preparation() {
885            return vec![false; filter_exprs.len()];
886        }
887        self.properties.clear_exact_num_rows();
888        let matched = self.stream_ctx.add_dyn_filter_to_predicate(filter_exprs);
889        // The added filters change the predicate group the preflight inspects.
890        self.clear_preflight_cache();
891        matched
892    }
893
894    fn reset_state(&mut self) {
895        self.prepared = Arc::new(prepared::Preparation::default());
896        self.clear_preflight_cache();
897        self.stream_ctx.input.predicate.clear_dyn_filters();
898        let num_workers = common_stat::get_total_cpu_cores().max(1);
899        self.pruner = Arc::new(Pruner::new(self.stream_ctx.clone(), num_workers));
900        self.legacy_receivers.lock().unwrap().clear();
901        self.metrics_list = Arc::new(PartitionMetricsList::default());
902    }
903
904    fn set_logical_region(&mut self, logical_region: bool) {
905        self.properties.set_logical_region(logical_region);
906    }
907
908    fn set_query_load_region_id(&mut self, region_id: store_api::storage::RegionId) {
909        self.properties.set_query_load_region_id(region_id);
910    }
911
912    fn snapshot_sequence(&self) -> Option<u64> {
913        self.stream_ctx.input.snapshot_sequence
914    }
915}
916
917impl DisplayAs for SeriesScan {
918    fn fmt_as(&self, t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
919        write!(
920            f,
921            "SeriesScan: region={}, ",
922            self.stream_ctx.input.mapper.metadata().region_id
923        )?;
924        match t {
925            DisplayFormatType::Default | DisplayFormatType::TreeRender => {
926                self.stream_ctx.format_for_explain(false, f)?;
927            }
928            DisplayFormatType::Verbose => {
929                self.stream_ctx.format_for_explain(true, f)?;
930            }
931        }
932        write!(f, ", \"mode\":\"{}\"", self.mode.as_str())?;
933        if matches!(t, DisplayFormatType::Verbose) {
934            self.metrics_list.format_verbose_metrics(f)?;
935        }
936        Ok(())
937    }
938}
939
940impl fmt::Debug for SeriesScan {
941    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
942        f.debug_struct("SeriesScan")
943            .field("mode", &self.mode)
944            .field("num_ranges", &self.stream_ctx.ranges.len())
945            .finish()
946    }
947}
948
949#[cfg(test)]
950impl SeriesScan {
951    /// Returns the input.
952    pub(crate) fn input(&self) -> &ScanInput {
953        &self.stream_ctx.input
954    }
955
956    /// Returns the scan mode for tests.
957    pub(crate) fn mode(&self) -> &'static str {
958        self.mode.as_str()
959    }
960}
961
962/// The distributor scans series and distributes them to different partitions.
963struct SeriesDistributor {
964    /// Context for the scan stream.
965    stream_ctx: Arc<StreamContext>,
966    /// Semaphore for file scanning and range-level merging.
967    range_semaphore: Option<Arc<Semaphore>>,
968    /// Semaphore for the final merge across all range streams.
969    /// Must be separate from `range_semaphore` to avoid deadlock: final merge tasks
970    /// hold a permit while waiting for data from range-level merge tasks, which also
971    /// need permits to produce data.
972    final_merge_semaphore: Option<Arc<Semaphore>>,
973    /// Partition ranges to scan.
974    partitions: Vec<Vec<PartitionRange>>,
975    /// Shared pruner for file range building.
976    pruner: Arc<Pruner>,
977    /// Senders of all partitions.
978    senders: SenderList,
979    /// Metrics set to report.
980    /// The distributor report the metrics as an additional partition.
981    /// This may double the scan cost of the [SeriesScan] metrics. We can
982    /// get per-partition metrics in verbose mode to see the metrics of the
983    /// distributor.
984    metrics_set: ExecutionPlanMetricsSet,
985    metrics_list: Arc<PartitionMetricsList>,
986    /// Whether to use verbose logging and collect detailed metrics.
987    explain_verbose: bool,
988}
989
990impl SeriesDistributor {
991    /// Executes the distributor.
992    #[tracing::instrument(
993        skip_all,
994        fields(region_id = %self.stream_ctx.input.mapper.metadata().region_id)
995    )]
996    async fn execute(&mut self) {
997        if let Err(e) = self.scan_partitions_flat().await {
998            self.senders.send_error(e).await;
999        }
1000    }
1001
1002    /// Scans all parts in flat format using FlatSeriesBatchDivider.
1003    #[tracing::instrument(
1004        skip_all,
1005        fields(region_id = %self.stream_ctx.input.mapper.metadata().region_id)
1006    )]
1007    async fn scan_partitions_flat(&mut self) -> Result<()> {
1008        // Initialize reference counts for all partition ranges.
1009        for partition_ranges in &self.partitions {
1010            self.pruner.add_partition_ranges(partition_ranges);
1011        }
1012
1013        // Create PartitionPruner covering all partitions
1014        let all_partition_ranges: Vec<_> = self.partitions.iter().flatten().cloned().collect();
1015        let needs_merge = all_partition_ranges.len() > 1;
1016        let partition_pruner = Arc::new(PartitionPruner::new(
1017            self.pruner.clone(),
1018            &all_partition_ranges,
1019        ));
1020
1021        let part_metrics = new_partition_metrics(
1022            &self.stream_ctx,
1023            self.explain_verbose,
1024            &self.metrics_set,
1025            self.partitions.len(),
1026            &self.metrics_list,
1027        );
1028        part_metrics.on_first_poll();
1029        // Start fetch time before building sources so scan cost contains
1030        // build part cost.
1031        let mut fetch_start = Instant::now();
1032
1033        // Builds one deduped stream per partition range, then merges across ranges.
1034        let build_start = Instant::now();
1035        let mut tasks = Vec::new();
1036        for partition in &self.partitions {
1037            for part_range in partition {
1038                let stream_ctx = self.stream_ctx.clone();
1039                let part_range = *part_range;
1040                let part_metrics = part_metrics.clone();
1041                let partition_pruner = partition_pruner.clone();
1042                let file_scan_semaphore = self.range_semaphore.clone();
1043                let merge_semaphore = self.range_semaphore.clone();
1044                tasks.push(common_runtime::spawn_query(async move {
1045                    SeqScan::build_flat_partition_range_read(
1046                        &stream_ctx,
1047                        &part_range,
1048                        if needs_merge {
1049                            FlatReadMode::CrossRangeMerge
1050                        } else {
1051                            FlatReadMode::Sequential
1052                        },
1053                        &part_metrics,
1054                        partition_pruner,
1055                        file_scan_semaphore,
1056                        merge_semaphore,
1057                    )
1058                    .await
1059                }));
1060            }
1061        }
1062        let mut range_streams = Vec::with_capacity(tasks.len());
1063        let mut estimated_batch_sizes = Vec::with_capacity(tasks.len());
1064        for task in tasks {
1065            let (stream, estimated_batch_size) = task.await.context(JoinSnafu)??;
1066            range_streams.push(stream);
1067            estimated_batch_sizes.push(estimated_batch_size);
1068        }
1069        let channel_size =
1070            compute_parallel_channel_size(compute_average_batch_size(estimated_batch_sizes));
1071        common_telemetry::debug!(
1072            "SeriesDistributor built {} range_streams, region: {}, build cost: {:?}, channel_size: {}",
1073            range_streams.len(),
1074            self.stream_ctx.input.region_metadata().region_id,
1075            build_start.elapsed(),
1076            channel_size,
1077        );
1078
1079        // Each partition range stream is already deduped, so skip dedup here.
1080        // Use a separate semaphore for the final merge to avoid deadlock with
1081        // range-level merge tasks that share the range_semaphore.
1082        let mut reader = SeqScan::build_flat_reader_from_sources(
1083            &self.stream_ctx,
1084            range_streams,
1085            self.final_merge_semaphore.clone(),
1086            Some(&part_metrics),
1087            true,
1088            channel_size,
1089        )
1090        .await?;
1091        let mut metrics = SeriesDistributorMetrics::default();
1092
1093        let mut divider = FlatSeriesBatchDivider::default();
1094        while let Some(record_batch) = reader.try_next().await? {
1095            metrics.scan_cost += fetch_start.elapsed();
1096            metrics.num_batches += 1;
1097            metrics.num_rows += record_batch.num_rows();
1098
1099            debug_assert!(record_batch.num_rows() > 0);
1100            if record_batch.num_rows() == 0 {
1101                fetch_start = Instant::now();
1102                continue;
1103            }
1104
1105            // Use divider to split series
1106            let divider_start = Instant::now();
1107            let series_batch = divider.push(record_batch);
1108            metrics.divider_cost += divider_start.elapsed();
1109            if let Some(series_batch) = series_batch {
1110                let yield_start = Instant::now();
1111                self.senders
1112                    .send_batch(SeriesBatch::Flat(series_batch))
1113                    .await?;
1114                metrics.yield_cost += yield_start.elapsed();
1115            }
1116            fetch_start = Instant::now();
1117        }
1118
1119        // Send any remaining batch in the divider
1120        let divider_start = Instant::now();
1121        let series_batch = divider.finish();
1122        metrics.divider_cost += divider_start.elapsed();
1123        if let Some(series_batch) = series_batch {
1124            let yield_start = Instant::now();
1125            self.senders
1126                .send_batch(SeriesBatch::Flat(series_batch))
1127                .await?;
1128            metrics.yield_cost += yield_start.elapsed();
1129        }
1130
1131        metrics.scan_cost += fetch_start.elapsed();
1132        metrics.num_series_send_full = self.senders.num_full;
1133        part_metrics.set_distributor_metrics(&metrics);
1134
1135        part_metrics.on_finish();
1136
1137        Ok(())
1138    }
1139}
1140
1141/// Batches of complete series.
1142///
1143/// A package may hold rows of more than one series, and every series in it is complete: no later
1144/// package of the same stream holds more rows of those series.
1145#[derive(Debug)]
1146pub enum SeriesBatch {
1147    Flat(FlatSeriesBatch),
1148}
1149
1150impl SeriesBatch {
1151    /// Returns the number of batches.
1152    pub fn num_batches(&self) -> usize {
1153        match self {
1154            SeriesBatch::Flat(flat_batch) => flat_batch.batches.len(),
1155        }
1156    }
1157
1158    /// Returns the total number of rows across all batches.
1159    pub fn num_rows(&self) -> usize {
1160        match self {
1161            SeriesBatch::Flat(flat_batch) => flat_batch.batches.iter().map(|x| x.num_rows()).sum(),
1162        }
1163    }
1164}
1165
1166/// Batches of the same series in flat format.
1167#[derive(Default, Debug)]
1168pub struct FlatSeriesBatch {
1169    pub batches: SmallVec<[RecordBatch; 4]>,
1170}
1171
1172/// List of senders.
1173struct SenderList {
1174    senders: Vec<Option<Sender<Result<SeriesBatch>>>>,
1175    /// Number of None senders.
1176    num_nones: usize,
1177    /// Index of the current partition to send.
1178    sender_idx: usize,
1179    /// Number of full senders.
1180    num_full: usize,
1181}
1182
1183impl SenderList {
1184    fn new(senders: Vec<Option<Sender<Result<SeriesBatch>>>>) -> Self {
1185        let num_nones = senders.iter().filter(|sender| sender.is_none()).count();
1186        Self {
1187            senders,
1188            num_nones,
1189            sender_idx: 0,
1190            num_full: 0,
1191        }
1192    }
1193
1194    /// Finds a partition and tries to send the batch to the partition.
1195    /// Returns None if it sends successfully.
1196    fn try_send_batch(&mut self, mut batch: SeriesBatch) -> Result<Option<SeriesBatch>> {
1197        for _ in 0..self.senders.len() {
1198            ensure!(self.num_nones < self.senders.len(), InvalidSenderSnafu);
1199
1200            let sender_idx = self.fetch_add_sender_idx();
1201            let Some(sender) = &self.senders[sender_idx] else {
1202                continue;
1203            };
1204
1205            match sender.try_send(Ok(batch)) {
1206                Ok(()) => return Ok(None),
1207                Err(TrySendError::Full(res)) => {
1208                    self.num_full += 1;
1209                    // Safety: we send Ok.
1210                    batch = res.unwrap();
1211                }
1212                Err(TrySendError::Closed(res)) => {
1213                    self.senders[sender_idx] = None;
1214                    self.num_nones += 1;
1215                    // Safety: we send Ok.
1216                    batch = res.unwrap();
1217                }
1218            }
1219        }
1220
1221        Ok(Some(batch))
1222    }
1223
1224    /// Finds a partition and sends the batch to the partition.
1225    async fn send_batch(&mut self, batch: SeriesBatch) -> Result<()> {
1226        let Some(batch) = self.try_send_batch(batch)? else {
1227            return Ok(());
1228        };
1229
1230        loop {
1231            ensure!(self.num_nones < self.senders.len(), InvalidSenderSnafu);
1232
1233            // Waits on every partition at once and sends to whichever frees a slot first. A
1234            // consumer may leave partitions unpolled for a long time, e.g. one that drains them one
1235            // after another, and waiting on such a partition would stall the scan.
1236            let closed = {
1237                let reservations = self.senders.iter().enumerate().filter_map(|(idx, sender)| {
1238                    sender
1239                        .as_ref()
1240                        .map(|sender| Box::pin(async move { (idx, sender.reserve().await) }))
1241                });
1242                let ((idx, reserved), _, _) = futures::future::select_all(reservations).await;
1243                match reserved {
1244                    Ok(permit) => {
1245                        permit.send(Ok(batch));
1246                        return Ok(());
1247                    }
1248                    Err(_) => idx,
1249                }
1250            };
1251            self.senders[closed] = None;
1252            self.num_nones += 1;
1253        }
1254    }
1255
1256    async fn send_error(&self, error: Error) {
1257        let error = Arc::new(error);
1258        for sender in self.senders.iter().flatten() {
1259            let result = Err(error.clone()).context(ScanSeriesSnafu);
1260            let _ = sender.send(result).await;
1261        }
1262    }
1263
1264    fn fetch_add_sender_idx(&mut self) -> usize {
1265        let sender_idx = self.sender_idx;
1266        self.sender_idx = (self.sender_idx + 1) % self.senders.len();
1267        sender_idx
1268    }
1269}
1270
1271fn new_partition_metrics(
1272    stream_ctx: &StreamContext,
1273    explain_verbose: bool,
1274    metrics_set: &ExecutionPlanMetricsSet,
1275    partition: usize,
1276    metrics_list: &PartitionMetricsList,
1277) -> PartitionMetrics {
1278    let metrics = PartitionMetrics::new(
1279        stream_ctx.input.mapper.metadata().region_id,
1280        partition,
1281        "SeriesScan",
1282        stream_ctx.query_start,
1283        explain_verbose,
1284        metrics_set,
1285    );
1286
1287    metrics_list.set(partition, metrics.clone());
1288    metrics
1289}
1290
1291/// A divider to split flat record batches by time series.
1292///
1293/// It only ensures rows of the same series are returned in the same [FlatSeriesBatch].
1294/// However, a [FlatSeriesBatch] may contain rows from multiple series.
1295#[derive(Default)]
1296struct FlatSeriesBatchDivider {
1297    buffer: FlatSeriesBatch,
1298}
1299
1300impl FlatSeriesBatchDivider {
1301    /// Pushes a record batch into the divider.
1302    ///
1303    /// Returns a [FlatSeriesBatch] if we ensure the batch contains all rows of the series in it.
1304    fn push(&mut self, batch: RecordBatch) -> Option<FlatSeriesBatch> {
1305        // If buffer is empty
1306        if self.buffer.batches.is_empty() {
1307            self.buffer.batches.push(batch);
1308            return None;
1309        }
1310
1311        // Gets the primary key column from the incoming batch.
1312        let pk_column_idx = primary_key_column_index(batch.num_columns());
1313        let batch_pk_column = batch.column(pk_column_idx);
1314        let batch_pk_array = batch_pk_column
1315            .as_any()
1316            .downcast_ref::<PrimaryKeyArray>()
1317            .unwrap();
1318        let batch_pk_values = batch_pk_array
1319            .values()
1320            .as_any()
1321            .downcast_ref::<BinaryArray>()
1322            .unwrap();
1323        // Gets the last primary key of the incoming batch.
1324        let batch_last_pk =
1325            primary_key_at(batch_pk_array, batch_pk_values, batch_pk_array.len() - 1);
1326        // Gets the last primary key of the buffer.
1327        // Safety: the buffer is not empty.
1328        let buffer_last_batch = self.buffer.batches.last().unwrap();
1329        let buffer_pk_column = buffer_last_batch.column(pk_column_idx);
1330        let buffer_pk_array = buffer_pk_column
1331            .as_any()
1332            .downcast_ref::<PrimaryKeyArray>()
1333            .unwrap();
1334        let buffer_pk_values = buffer_pk_array
1335            .values()
1336            .as_any()
1337            .downcast_ref::<BinaryArray>()
1338            .unwrap();
1339        let buffer_last_pk =
1340            primary_key_at(buffer_pk_array, buffer_pk_values, buffer_pk_array.len() - 1);
1341
1342        // If last primary key in the batch is the same as last primary key in the buffer.
1343        if batch_last_pk == buffer_last_pk {
1344            self.buffer.batches.push(batch);
1345            return None;
1346        }
1347        // Otherwise, the batch must have a different primary key, we find the first offset of the
1348        // changed primary key.
1349        let batch_pk_keys = batch_pk_array.keys();
1350        let pk_indices = batch_pk_keys.values();
1351        let mut change_offset = 0;
1352        for (i, &key) in pk_indices.iter().enumerate() {
1353            let batch_pk = batch_pk_values.value(key as usize);
1354
1355            if buffer_last_pk != batch_pk {
1356                change_offset = i;
1357                break;
1358            }
1359        }
1360
1361        // Splits the batch at the change offset
1362        let (first_part, remaining_part) = if change_offset > 0 {
1363            let first_part = batch.slice(0, change_offset);
1364            let remaining_part = batch.slice(change_offset, batch.num_rows() - change_offset);
1365            (Some(first_part), Some(remaining_part))
1366        } else {
1367            (None, Some(batch))
1368        };
1369
1370        // Creates the result from current buffer + first part of new batch
1371        let mut result = std::mem::take(&mut self.buffer);
1372        if let Some(first_part) = first_part {
1373            result.batches.push(first_part);
1374        }
1375
1376        // Pushes remaining part to the buffer if it exists
1377        if let Some(remaining_part) = remaining_part {
1378            self.buffer.batches.push(remaining_part);
1379        }
1380
1381        Some(result)
1382    }
1383
1384    /// Returns the final [FlatSeriesBatch].
1385    fn finish(&mut self) -> Option<FlatSeriesBatch> {
1386        if self.buffer.batches.is_empty() {
1387            None
1388        } else {
1389            Some(std::mem::take(&mut self.buffer))
1390        }
1391    }
1392}
1393
1394/// Helper function to extract primary key bytes at a specific index from [PrimaryKeyArray].
1395fn primary_key_at<'a>(
1396    primary_key: &PrimaryKeyArray,
1397    primary_key_values: &'a BinaryArray,
1398    index: usize,
1399) -> &'a [u8] {
1400    let key = primary_key.keys().value(index);
1401    primary_key_values.value(key as usize)
1402}
1403
1404#[cfg(test)]
1405mod tests {
1406    use std::sync::Arc;
1407
1408    use api::v1::OpType;
1409    use datatypes::arrow::array::{
1410        ArrayRef, BinaryDictionaryBuilder, Int64Array, StringDictionaryBuilder,
1411        TimestampMillisecondArray, UInt8Array, UInt64Array,
1412    };
1413    use datatypes::arrow::datatypes::{DataType, Field, Schema, SchemaRef, TimeUnit, UInt32Type};
1414    use datatypes::arrow::record_batch::RecordBatch;
1415
1416    use super::*;
1417
1418    #[tokio::test]
1419    async fn distributor_does_not_stall_on_partitions_read_one_after_another() {
1420        const NUM_BATCHES: usize = 2000;
1421        let (mut senders, receivers) = new_legacy_channel_list(16);
1422        let producer = tokio::spawn(async move {
1423            for _ in 0..NUM_BATCHES {
1424                senders
1425                    .send_batch(SeriesBatch::Flat(FlatSeriesBatch::default()))
1426                    .await
1427                    .unwrap();
1428            }
1429        });
1430        // Reads partition 0 to its end before touching the next one, so all other partitions stay
1431        // full while the producer still has batches to send.
1432        let consume = async {
1433            let mut received = 0;
1434            for mut receiver in receivers.into_iter().flatten() {
1435                while let Some(batch) = receiver.recv().await {
1436                    batch.unwrap();
1437                    received += 1;
1438                }
1439            }
1440            received
1441        };
1442        let received = tokio::time::timeout(std::time::Duration::from_secs(1), consume)
1443            .await
1444            .expect("the distributor stalled on partitions the consumer was not reading");
1445        producer.await.unwrap();
1446        assert_eq!(NUM_BATCHES, received);
1447    }
1448
1449    fn new_test_record_batch(
1450        primary_keys: &[&[u8]],
1451        timestamps: &[i64],
1452        sequences: &[u64],
1453        op_types: &[OpType],
1454        fields: &[u64],
1455    ) -> RecordBatch {
1456        let num_rows = timestamps.len();
1457        debug_assert_eq!(sequences.len(), num_rows);
1458        debug_assert_eq!(op_types.len(), num_rows);
1459        debug_assert_eq!(fields.len(), num_rows);
1460        debug_assert_eq!(primary_keys.len(), num_rows);
1461
1462        let columns: Vec<ArrayRef> = vec![
1463            build_test_pk_string_dict_array(primary_keys),
1464            Arc::new(Int64Array::from_iter(
1465                fields.iter().map(|v| Some(*v as i64)),
1466            )),
1467            Arc::new(TimestampMillisecondArray::from_iter_values(
1468                timestamps.iter().copied(),
1469            )),
1470            build_test_pk_array(primary_keys),
1471            Arc::new(UInt64Array::from_iter_values(sequences.iter().copied())),
1472            Arc::new(UInt8Array::from_iter_values(
1473                op_types.iter().map(|v| *v as u8),
1474            )),
1475        ];
1476
1477        RecordBatch::try_new(build_test_flat_schema(), columns).unwrap()
1478    }
1479
1480    fn build_test_pk_string_dict_array(primary_keys: &[&[u8]]) -> ArrayRef {
1481        let mut builder = StringDictionaryBuilder::<UInt32Type>::new();
1482        for &pk in primary_keys {
1483            let pk_str = std::str::from_utf8(pk).unwrap();
1484            builder.append(pk_str).unwrap();
1485        }
1486        Arc::new(builder.finish())
1487    }
1488
1489    fn build_test_pk_array(primary_keys: &[&[u8]]) -> ArrayRef {
1490        let mut builder = BinaryDictionaryBuilder::<UInt32Type>::new();
1491        for &pk in primary_keys {
1492            builder.append(pk).unwrap();
1493        }
1494        Arc::new(builder.finish())
1495    }
1496
1497    fn build_test_flat_schema() -> SchemaRef {
1498        let fields = vec![
1499            Field::new(
1500                "k0",
1501                DataType::Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Utf8)),
1502                false,
1503            ),
1504            Field::new("field0", DataType::Int64, true),
1505            Field::new(
1506                "ts",
1507                DataType::Timestamp(TimeUnit::Millisecond, None),
1508                false,
1509            ),
1510            Field::new(
1511                "__primary_key",
1512                DataType::Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Binary)),
1513                false,
1514            ),
1515            Field::new("__sequence", DataType::UInt64, false),
1516            Field::new("__op_type", DataType::UInt8, false),
1517        ];
1518        Arc::new(Schema::new(fields))
1519    }
1520
1521    #[test]
1522    fn test_empty_buffer_first_push() {
1523        let mut divider = FlatSeriesBatchDivider::default();
1524        let result = divider.finish();
1525        assert!(result.is_none());
1526
1527        let mut divider = FlatSeriesBatchDivider::default();
1528        let batch = new_test_record_batch(
1529            &[b"series1", b"series1"],
1530            &[1000, 2000],
1531            &[1, 2],
1532            &[OpType::Put, OpType::Put],
1533            &[10, 20],
1534        );
1535        let result = divider.push(batch);
1536        assert!(result.is_none());
1537        assert_eq!(divider.buffer.batches.len(), 1);
1538    }
1539
1540    #[test]
1541    fn test_same_series_accumulation() {
1542        let mut divider = FlatSeriesBatchDivider::default();
1543
1544        let batch1 = new_test_record_batch(
1545            &[b"series1", b"series1"],
1546            &[1000, 2000],
1547            &[1, 2],
1548            &[OpType::Put, OpType::Put],
1549            &[10, 20],
1550        );
1551
1552        let batch2 = new_test_record_batch(
1553            &[b"series1", b"series1"],
1554            &[3000, 4000],
1555            &[3, 4],
1556            &[OpType::Put, OpType::Put],
1557            &[30, 40],
1558        );
1559
1560        divider.push(batch1);
1561        let result = divider.push(batch2);
1562        assert!(result.is_none());
1563        let series_batch = divider.finish().unwrap();
1564        assert_eq!(series_batch.batches.len(), 2);
1565    }
1566
1567    #[test]
1568    fn test_series_boundary_detection() {
1569        let mut divider = FlatSeriesBatchDivider::default();
1570
1571        let batch1 = new_test_record_batch(
1572            &[b"series1", b"series1"],
1573            &[1000, 2000],
1574            &[1, 2],
1575            &[OpType::Put, OpType::Put],
1576            &[10, 20],
1577        );
1578
1579        let batch2 = new_test_record_batch(
1580            &[b"series2", b"series2"],
1581            &[3000, 4000],
1582            &[3, 4],
1583            &[OpType::Put, OpType::Put],
1584            &[30, 40],
1585        );
1586
1587        divider.push(batch1);
1588        let series_batch = divider.push(batch2).unwrap();
1589        assert_eq!(series_batch.batches.len(), 1);
1590
1591        assert_eq!(divider.buffer.batches.len(), 1);
1592    }
1593
1594    #[test]
1595    fn test_series_boundary_within_batch() {
1596        let mut divider = FlatSeriesBatchDivider::default();
1597
1598        let batch1 = new_test_record_batch(
1599            &[b"series1", b"series1"],
1600            &[1000, 2000],
1601            &[1, 2],
1602            &[OpType::Put, OpType::Put],
1603            &[10, 20],
1604        );
1605
1606        let batch2 = new_test_record_batch(
1607            &[b"series1", b"series2"],
1608            &[3000, 4000],
1609            &[3, 4],
1610            &[OpType::Put, OpType::Put],
1611            &[30, 40],
1612        );
1613
1614        divider.push(batch1);
1615        let series_batch = divider.push(batch2).unwrap();
1616        assert_eq!(series_batch.batches.len(), 2);
1617        assert_eq!(series_batch.batches[0].num_rows(), 2);
1618        assert_eq!(series_batch.batches[1].num_rows(), 1);
1619
1620        assert_eq!(divider.buffer.batches.len(), 1);
1621        assert_eq!(divider.buffer.batches[0].num_rows(), 1);
1622    }
1623
1624    #[test]
1625    fn test_series_splitting() {
1626        let mut divider = FlatSeriesBatchDivider::default();
1627
1628        let batch1 = new_test_record_batch(&[b"series1"], &[1000], &[1], &[OpType::Put], &[10]);
1629
1630        let batch2 = new_test_record_batch(
1631            &[b"series1", b"series2", b"series2", b"series3"],
1632            &[2000, 3000, 4000, 5000],
1633            &[2, 3, 4, 5],
1634            &[OpType::Put, OpType::Put, OpType::Put, OpType::Put],
1635            &[20, 30, 40, 50],
1636        );
1637
1638        divider.push(batch1);
1639        let series_batch = divider.push(batch2).unwrap();
1640        assert_eq!(series_batch.batches.len(), 2);
1641
1642        let total_rows: usize = series_batch.batches.iter().map(|b| b.num_rows()).sum();
1643        assert_eq!(total_rows, 2);
1644
1645        let final_batch = divider.finish().unwrap();
1646        assert_eq!(final_batch.batches.len(), 1);
1647        assert_eq!(final_batch.batches[0].num_rows(), 3);
1648    }
1649}