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;
22use std::sync::atomic::{AtomicUsize, Ordering};
23use std::sync::{Arc, Mutex};
24use std::time::Instant;
25
26use api::v1::SemanticType;
27use async_stream::try_stream;
28use common_error::ext::BoxedError;
29use common_query::native_histogram::is_native_histogram_value_type;
30use common_recordbatch::util::ChainedRecordBatchStream;
31use common_recordbatch::{RecordBatchStreamWrapper, SendableRecordBatchStream};
32use common_telemetry::tracing::{self, Instrument};
33use common_telemetry::{debug, warn};
34use datafusion::execution::memory_pool::MemoryPool;
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 datatypes::types::TimestampType;
47use futures::{StreamExt, TryStreamExt};
48use smallvec::SmallVec;
49use snafu::{OptionExt, ResultExt, ensure};
50use store_api::metadata::RegionMetadataRef;
51use store_api::metric_engine_consts::is_metric_engine_internal_column;
52use store_api::region_engine::{
53    PartitionRange, PrepareRequest, QueryScanContext, RawLabelSource, RegionScanner,
54    ScannerProperties, SendableRawSeriesStream,
55};
56use store_api::storage::consts::{ReservedColumnId, is_internal_column};
57use table::predicate::Predicate;
58use tokio::sync::Semaphore;
59use tokio::sync::mpsc::error::TrySendError;
60use tokio::sync::mpsc::{self, Receiver, Sender};
61
62use crate::error::{
63    Error, InvalidRecordBatchSnafu, InvalidSenderSnafu, JoinSnafu, PartitionOutOfRangeSnafu,
64    Result, ScanMultiTimesSnafu, ScanSeriesSnafu, TooManyFilesToReadSnafu,
65};
66use crate::metrics::SCAN_MAX_CONCURRENT_FILES;
67use crate::read::ScannerMetrics;
68use crate::read::pruner::{PartitionPruner, Pruner, PrunerOptions};
69use crate::read::scan_region::{ScanInput, StreamContext};
70use crate::read::scan_util::{
71    PartitionMetrics, PartitionMetricsList, SeriesDistributorMetrics, compute_average_batch_size,
72    compute_parallel_channel_size,
73};
74use crate::read::seq_scan::{FlatReadMode, SeqScan};
75use crate::read::series_candidate::{SeriesCandidateScanner, is_sparse_metric_metadata};
76use crate::read::series_reader::{AssignedSeriesBatch, SeriesBatchCollector, SeriesReader};
77use crate::read::stream::{ConvertBatchStream, ScanBatch, ScanBatchStream};
78use crate::sst::parquet::flat_format::primary_key_column_index;
79use crate::sst::parquet::format::PrimaryKeyArray;
80
81/// Maximum number of candidate series retained before distributing assignments.
82const CANDIDATE_SERIES_ASSIGNMENT_THRESHOLD: usize = 1_000_000;
83
84/// Test-only override of [`CANDIDATE_SERIES_ASSIGNMENT_THRESHOLD`], where `0` means "use the
85/// production constant".
86///
87/// The production build compiles this static, the setter below and the private accessor out, so
88/// the shipped threshold is always the constant above.
89#[cfg(test)]
90static CANDIDATE_SERIES_ASSIGNMENT_THRESHOLD_OVERRIDE: AtomicUsize = AtomicUsize::new(0);
91
92/// Test-only number of candidate assignment rounds sent since the override was last set.
93///
94/// A round is one `send_assignments` call, so a partition that received more than one assignment
95/// sees `>= 2` rounds here. Increments are compiled out of production builds.
96#[cfg(test)]
97static CANDIDATE_ASSIGNMENT_ROUNDS: AtomicUsize = AtomicUsize::new(0);
98
99/// Returns the candidate-series assignment threshold, honouring the test-only override.
100fn candidate_series_assignment_threshold() -> usize {
101    #[cfg(test)]
102    {
103        let threshold = CANDIDATE_SERIES_ASSIGNMENT_THRESHOLD_OVERRIDE.load(Ordering::Relaxed);
104        if threshold > 0 {
105            return threshold;
106        }
107    }
108    CANDIDATE_SERIES_ASSIGNMENT_THRESHOLD
109}
110
111/// Test-only: overrides the candidate-series assignment threshold and resets the round counter.
112///
113/// Pass `0` to restore the production threshold. Tests must reset the override before they
114/// return; a scope guard in `engine::scan_test` does that even on panic.
115#[cfg(test)]
116pub(crate) fn set_candidate_series_assignment_threshold(threshold: usize) {
117    CANDIDATE_SERIES_ASSIGNMENT_THRESHOLD_OVERRIDE.store(threshold, Ordering::Relaxed);
118    CANDIDATE_ASSIGNMENT_ROUNDS.store(0, Ordering::Relaxed);
119}
120
121/// Test-only: returns the number of assignment rounds sent since the override was last set.
122#[cfg(test)]
123pub(crate) fn candidate_assignment_rounds() -> usize {
124    CANDIDATE_ASSIGNMENT_ROUNDS.load(Ordering::Relaxed)
125}
126
127/// Legacy data receivers for output partitions.
128type LegacyReceiverList = Vec<Option<Receiver<Result<SeriesBatch>>>>;
129
130/// Candidate assignment receivers for output partitions.
131type CandidateReceiverList = Vec<Option<CandidateReceiver>>;
132
133/// Candidate assignment senders for output partitions.
134type CandidateSenderList = Vec<Option<mpsc::UnboundedSender<Result<SeriesReaderInput>>>>;
135
136#[derive(Clone)]
137pub(crate) struct RawScanPreparation {
138    schema: Arc<SeriesSchema>,
139    fields: Vec<(usize, ConcreteDataType)>,
140    predicates: Vec<Arc<dyn PhysicalExpr>>,
141}
142
143/// Memoized raw-scan preflight: the label binding it was computed for, and its answer.
144///
145/// The answer carries the preparation together with whether its data comes from the columnar
146/// prepared source; `None` means the raw path is unavailable for this scan.
147type PreflightCache = Option<(RawLabelSource, Option<(RawScanPreparation, bool)>)>;
148
149struct CandidateReceiver {
150    receiver: mpsc::UnboundedReceiver<Result<SeriesReaderInput>>,
151    active_receivers: Arc<AtomicUsize>,
152}
153
154impl CandidateReceiver {
155    async fn recv(&mut self) -> Option<Result<SeriesReaderInput>> {
156        self.receiver.recv().await
157    }
158}
159
160impl Drop for CandidateReceiver {
161    fn drop(&mut self) {
162        let previous = self.active_receivers.fetch_sub(1, Ordering::Relaxed);
163        debug_assert!(previous > 0);
164    }
165}
166
167/// Input required by a partition-local series reader.
168struct SeriesReaderInput {
169    assigned_series: AssignedSeriesBatch,
170    partition_pruner: Arc<PartitionPruner>,
171    range_semaphore: Arc<Semaphore>,
172}
173
174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
175enum SeriesScanMode {
176    Prepared,
177    Legacy,
178    TwoPhase,
179}
180
181impl SeriesScanMode {
182    fn as_str(self) -> &'static str {
183        match self {
184            Self::Prepared => "prepared",
185            Self::Legacy => "legacy",
186            Self::TwoPhase => "two_phase",
187        }
188    }
189}
190
191/// Scans a region and returns sorted rows of a series in the same partition.
192///
193/// The output order is always order by `(primary key, time index)` inside every
194/// partition.
195/// Always returns the same series (primary key) to the same partition.
196pub struct SeriesScan {
197    /// Implementation used by this scan.
198    mode: SeriesScanMode,
199    prepared: Arc<prepared::Preparation>,
200    /// Properties of the scanner.
201    properties: ScannerProperties,
202    /// Context of streams.
203    stream_ctx: Arc<StreamContext>,
204    /// Shared pruner for file range building.
205    pruner: Arc<Pruner>,
206    /// Legacy data receivers for each partition.
207    legacy_receivers: Mutex<LegacyReceiverList>,
208    /// Candidate assignment receivers for each partition.
209    candidate_receivers: Mutex<CandidateReceiverList>,
210    /// Metrics for each partition.
211    /// The scanner only sets in query and keeps it empty during compaction.
212    metrics_list: Arc<PartitionMetricsList>,
213    /// Memoized result of [`Self::prepare_raw_scan`] for the label binding it was computed for.
214    ///
215    /// Preflight only reads pinned scanner state, and one execution asks for it once per output
216    /// partition, so the first answer serves the rest. Errors are never stored, and every entry
217    /// that mutates the state the answer depends on clears the entry. The guard is taken and
218    /// released inside a synchronous call, so it never spans an await.
219    preflight: Mutex<PreflightCache>,
220    /// Test-only number of preflight computations performed by this scanner.
221    ///
222    /// A cached answer does not increment it, so a test can prove that a repeated preflight over
223    /// the same pinned state is served from [`Self::preflight`].
224    #[cfg(test)]
225    preflight_runs: AtomicUsize,
226}
227
228impl SeriesScan {
229    /// Creates a new [SeriesScan].
230    pub(crate) fn new(input: ScanInput, experimental_series_scan_v2: bool) -> Self {
231        let mode = if input.requires_narthex_preparation() {
232            SeriesScanMode::Prepared
233        } else if experimental_series_scan_v2 && Self::supports_two_phase(&input) {
234            SeriesScanMode::TwoPhase
235        } else {
236            SeriesScanMode::Legacy
237        };
238        let mut properties = ScannerProperties::default()
239            .with_append_mode(input.append_mode)
240            .with_total_rows(input.total_rows())
241            .with_total_rows_is_exact(input.append_mode && input.total_rows_is_exact());
242        if let Some(counters) = input.query_stat_counters.clone() {
243            properties.set_query_stat_counters(counters);
244        }
245        let stream_ctx = Arc::new(StreamContext::seq_scan_ctx(input));
246        properties.partitions = vec![stream_ctx.partition_ranges()];
247
248        // Create the shared pruner with number of workers equal to CPU cores.
249        let num_workers = common_stat::get_total_cpu_cores().max(1);
250        let pruner = match mode {
251            SeriesScanMode::Legacy | SeriesScanMode::Prepared => {
252                Arc::new(Pruner::new(stream_ctx.clone(), num_workers))
253            }
254            SeriesScanMode::TwoPhase => Arc::new(Pruner::new_with_options(
255                stream_ctx.clone(),
256                num_workers,
257                PrunerOptions {
258                    retain_builders: true,
259                    enable_predicate_prefilter: false,
260                },
261            )),
262        };
263
264        Self {
265            mode,
266            prepared: Arc::new(prepared::Preparation::default()),
267            properties,
268            stream_ctx,
269            pruner,
270            legacy_receivers: Mutex::new(Vec::new()),
271            candidate_receivers: Mutex::new(Vec::new()),
272            metrics_list: Arc::new(PartitionMetricsList::default()),
273            preflight: Mutex::new(None),
274            #[cfg(test)]
275            preflight_runs: AtomicUsize::new(0),
276        }
277    }
278
279    /// Returns the number of preflight computations this scanner has run.
280    ///
281    /// Test-only: a memoized preflight does not count, so a test can distinguish a cache hit from a
282    /// recomputation.
283    #[cfg(test)]
284    pub(crate) fn preflight_runs(&self) -> usize {
285        self.preflight_runs.load(Ordering::Relaxed)
286    }
287
288    /// Drops the memoized preflight.
289    ///
290    /// Every entry point that mutates state the preflight reads calls this, so a stale answer can
291    /// never outlive the state it was derived from.
292    fn clear_preflight_cache(&self) {
293        *self.preflight.lock().unwrap() = None;
294    }
295
296    /// Returns the memoized preflight, if it was computed for the same label binding.
297    ///
298    /// A binding only matches when its immutable identity matches as well: the preflight validates
299    /// the pinned metadata snapshot and the label binding, so an answer for another binding must
300    /// never be reused even when the labels look alike.
301    fn cached_preflight(
302        &self,
303        label_source: &RawLabelSource,
304    ) -> Option<Option<(RawScanPreparation, bool)>> {
305        let cache = self.preflight.lock().unwrap();
306        let (cached_source, cached) = cache.as_ref()?;
307        if !prepared::same_labels(cached_source, label_source) {
308            return None;
309        }
310        Some(cached.clone())
311    }
312
313    fn uses_columnar(&self) -> bool {
314        self.stream_ctx.input.requires_narthex_preparation()
315            || self
316                .stream_ctx
317                .input
318                .series_index
319                .as_ref()
320                .is_some_and(|context| context.format == crate::config::SeriesIndexFormat::Columnar)
321    }
322
323    /// Whether every selected *field* is a `Float64`, which is all the columnar prepared reader
324    /// serves.
325    ///
326    /// Only field columns count: the projection also carries tags and the time index, and those are
327    /// no part of the samples the prepared reader hands over. Checking them here would send an
328    /// ordinary `Float64` query down the ordinary scan just because it projects a timestamp.
329    fn columnar_fields_supported(&self) -> bool {
330        let metadata = self.stream_ctx.input.mapper.metadata();
331        let selected = self.stream_ctx.input.mapper.output_schema();
332        selected
333            .column_schemas()
334            .iter()
335            .filter(|output| {
336                metadata.column_metadatas.iter().any(|column| {
337                    column.column_schema.name == output.name
338                        && column.semantic_type == SemanticType::Field
339                })
340            })
341            .all(|output| output.data_type == ConcreteDataType::float64_datatype())
342    }
343
344    /// Returns whether raw series come from the columnar prepared source.
345    ///
346    /// Derived only from the pinned series index version and every configured partition range, so
347    /// preflight, the partition reader and scanner-wide preparation agree.
348    /// `false` means the stored sources are read by the ordinary scan.
349    fn uses_prepared_columnar(&self) -> Result<bool, BoxedError> {
350        if !self.uses_columnar() {
351            return Ok(false);
352        }
353        let ranges = self
354            .properties
355            .partitions
356            .iter()
357            .flatten()
358            .copied()
359            .collect::<Vec<_>>();
360        prepared::validate_inputs(&self.stream_ctx, &ranges).map_err(BoxedError::new)
361    }
362
363    /// Prepares the raw scan and reports whether its data comes from the columnar prepared source.
364    ///
365    /// The answer only depends on pinned scanner state plus the label binding, and an execution
366    /// asks for it once per output partition, so it is memoized per binding. Only successful
367    /// answers are stored: a rejected binding must fail on every call, not replay a rejection or
368    /// hide a later one.
369    fn prepare_raw_scan(
370        &self,
371        label_source: &RawLabelSource,
372    ) -> Result<Option<(RawScanPreparation, bool)>, BoxedError> {
373        if let Some(cached) = self.cached_preflight(label_source) {
374            return Ok(cached);
375        }
376        let computed = self.prepare_raw_scan_uncached(label_source)?;
377        if self.stream_ctx.input.requires_narthex_preparation()
378            && !matches!(computed, Some((_, true)))
379        {
380            return Err(BoxedError::new(
381                InvalidRecordBatchSnafu {
382                    reason: "Narthex raw scans require prepared-series support",
383                }
384                .build(),
385            ));
386        }
387        // Both sides of the cache are cheap to clone, and callers own their copy: the merge schema
388        // helper rewrites the field indices and predicates of the preparation it is given, which
389        // must never reach the stored answer.
390        *self.preflight.lock().unwrap() = Some((label_source.clone(), computed.clone()));
391        Ok(computed)
392    }
393
394    /// Computes a fresh [`Self::prepare_raw_scan`] answer from the pinned scanner state.
395    fn prepare_raw_scan_uncached(
396        &self,
397        label_source: &RawLabelSource,
398    ) -> Result<Option<(RawScanPreparation, bool)>, BoxedError> {
399        #[cfg(test)]
400        self.preflight_runs.fetch_add(1, Ordering::Relaxed);
401        let input = &self.stream_ctx.input;
402        let metadata = input.mapper.metadata();
403        match label_source {
404            RawLabelSource::PrimaryKey {
405                physical_metadata,
406                logical_tags,
407                ..
408            } => {
409                if !Arc::ptr_eq(metadata, physical_metadata) {
410                    debug!(
411                        "Raw series scan preflight rejected metadata snapshot: region_id={}, physical_region_id={}, schema_version={}, physical_schema_version={}",
412                        metadata.region_id,
413                        physical_metadata.region_id,
414                        metadata.schema_version,
415                        physical_metadata.schema_version,
416                    );
417                    return Err(BoxedError::new(
418                        InvalidRecordBatchSnafu {
419                            reason: "raw label source metadata does not match scanner snapshot"
420                                .to_string(),
421                        }
422                        .build(),
423                    ));
424                }
425                let mut ids = HashSet::new();
426                let mut names = HashSet::new();
427                for tag in logical_tags.iter() {
428                    let column = metadata.column_by_id(tag.column_id).filter(|column| {
429                        column.semantic_type == SemanticType::Tag
430                            && metadata.primary_key.contains(&tag.column_id)
431                    });
432                    let valid = column.is_some_and(|column| {
433                        column.column_schema.name == tag.name.as_ref()
434                            && tag.name.as_ref() != "__name__"
435                            && !is_internal_column(tag.name.as_ref())
436                            && !is_metric_engine_internal_column(tag.name.as_ref())
437                            && !ReservedColumnId::is_reserved(tag.column_id)
438                    });
439                    let unique_id = valid && ids.insert(tag.column_id);
440                    let unique_name = unique_id && names.insert(tag.name.as_ref());
441                    if !valid || !unique_id || !unique_name {
442                        debug!(
443                            "Raw series scan preflight rejected label binding: region_id={}, column_id={}, binding_valid={}, unique_id={}, unique_name={}",
444                            metadata.region_id, tag.column_id, valid, unique_id, unique_name,
445                        );
446                        return Err(BoxedError::new(
447                            InvalidRecordBatchSnafu {
448                                reason: "invalid raw label binding".to_string(),
449                            }
450                            .build(),
451                        ));
452                    }
453                }
454            }
455            RawLabelSource::Explicit => {
456                debug!(
457                    "Raw series scan preflight rejected explicit labels: region_id={}",
458                    metadata.region_id,
459                );
460                return Ok(None);
461            }
462        }
463        // The columnar prepared reader serves sparse metric regions only: another region on a store in
464        // that format has no columnar samples, and its SST rows are the sources the ordinary scan reads
465        // anyway. Missing columnar coverage is not a reason to refuse the raw path - see the
466        // `prepared_columnar` gate below - so such a scan keeps it and is served from the ordinary scan.
467        // Refusing here instead would be an error no caller can turn into a fallback: the logical plan
468        // above this leaf is already the fused node by the time the region is asked.
469        let columnar_region = self.uses_columnar() && is_sparse_metric_metadata(metadata);
470        // Narthex samples exist for sparse metric regions only, so a scan that requires them and is not
471        // one of those has nothing to read them from.
472        if !columnar_region && input.requires_narthex_preparation() {
473            return Ok(None);
474        }
475        let selected = input.mapper.output_schema();
476        let mut fields = Vec::new();
477        let mut specs = Vec::new();
478        // The columnar prepared reader serves `Float64` fields only. A selection carrying another
479        // kind the raw path supports - a native histogram struct, today - is read by the ordinary
480        // scan instead: the columnar samples are an artifact beside the SST rows, so the same
481        // sources are still reachable, and the frame schema and ordering follow the reader that
482        // actually answers.
483        let columnar_fields_supported = self.columnar_fields_supported();
484        for output in selected.column_schemas() {
485            let Some(column) = metadata.column_metadatas.iter().find(|column| {
486                column.column_schema.name == output.name
487                    && column.semantic_type == SemanticType::Field
488            }) else {
489                continue;
490            };
491            let Some((index, (_, data_type))) = input
492                .mapper
493                .batch_schema()
494                .iter()
495                .enumerate()
496                .find(|(_, (id, _))| *id == column.column_id)
497            else {
498                debug!(
499                    "Raw series scan preflight missing mapper field: region_id={}, column_id={}",
500                    metadata.region_id, column.column_id,
501                );
502                return Err(BoxedError::new(
503                    InvalidRecordBatchSnafu {
504                        reason: format!(
505                            "selected field {} is missing from mapper batch schema",
506                            output.name
507                        ),
508                    }
509                    .build(),
510                ));
511            };
512            // The raw converter casts a numeric field to `Float64` and converts a native histogram
513            // struct into histogram samples; nothing else has a raw representation.
514            if !data_type.is_numeric() && !is_native_histogram_value_type(data_type) {
515                debug!(
516                    "Raw series scan preflight rejected field type: region_id={}, column_id={}",
517                    metadata.region_id, column.column_id,
518                );
519                return Ok(None);
520            }
521            fields.push((index, data_type.clone()));
522            specs.push(FieldSpec {
523                name: Arc::from(output.name.as_str()),
524            });
525        }
526        let time_is_millis = matches!(metadata.time_index_type(), TimestampType::Millisecond(_));
527        if fields.is_empty()
528            || (input.append_mode && !input.requires_narthex_preparation())
529            || input.series_row_selector.is_some()
530            || !time_is_millis
531        {
532            debug!(
533                "Raw series scan preflight rejected scan options: region_id={}, selected_fields={}, append_mode={}, row_selector={}, time_is_millis={}",
534                metadata.region_id,
535                fields.len(),
536                input.append_mode,
537                input.series_row_selector.is_some(),
538                time_is_millis,
539            );
540            return Ok(None);
541        }
542        // Structural eligibility errors still reject the raw path; ordinary scans cover sources
543        // without columnar artifacts, so missing coverage is not an error here.
544        let prepared_columnar =
545            columnar_region && self.uses_prepared_columnar()? && columnar_fields_supported;
546        let schema = Arc::new(SeriesSchema {
547            fields: specs.into(),
548            eval_grid: None,
549        });
550        let typed_schema = input.mapper.input_arrow_schema(false);
551        let mut predicates = Vec::new();
552        let predicate = if prepared_columnar {
553            input.predicate_group().predicate()
554        } else {
555            // The ordinary scan applies region predicates before this residual filtering.
556            input.predicate_group().predicate_without_region()
557        };
558        if let Some(predicate) = predicate {
559            if !predicate.dyn_filters().is_empty() {
560                debug!(
561                    "Raw series scan preflight rejected dynamic predicate filters: region_id={}",
562                    metadata.region_id,
563                );
564                return Ok(None);
565            }
566            for expr in predicate.exprs() {
567                // Fresh execution properties cannot preserve Stable or query-dependent semantics.
568                if expr
569                    .exists(|node| {
570                        Ok(matches!(node, Expr::ScalarFunction(function)
571                            if function.func.signature().volatility != Volatility::Immutable)
572                            || matches!(node, Expr::ScalarVariable(..)))
573                    })
574                    .unwrap_or(true)
575                {
576                    debug!(
577                        "Raw series scan preflight rejected predicate volatility or variable: region_id={}",
578                        metadata.region_id,
579                    );
580                    return Ok(None);
581                }
582                // Evaluate residuals with original types before raw conversion to Float64.
583                let Ok(physical) = Predicate::to_physical_expr(expr, &typed_schema) else {
584                    debug!(
585                        "Raw series scan preflight failed predicate compilation: region_id={}",
586                        metadata.region_id,
587                    );
588                    return Ok(None);
589                };
590                if !matches!(
591                    physical.data_type(&typed_schema),
592                    Ok(ArrowDataType::Boolean | ArrowDataType::Null)
593                ) {
594                    debug!(
595                        "Raw series scan preflight rejected predicate type: region_id={}",
596                        metadata.region_id,
597                    );
598                    return Ok(None);
599                }
600                predicates.push(physical);
601            }
602        }
603        Ok(Some((
604            RawScanPreparation {
605                schema,
606                fields,
607                predicates,
608            },
609            prepared_columnar,
610        )))
611    }
612
613    /// Starts scanner-wide preparation from the preflight already performed by the caller.
614    fn prepare_series_with_raw(
615        &self,
616        ctx: &QueryScanContext,
617        metrics_set: &ExecutionPlanMetricsSet,
618        label_source: &RawLabelSource,
619        preparation: Result<Option<(RawScanPreparation, bool)>, BoxedError>,
620    ) -> futures::future::BoxFuture<
621        'static,
622        Result<Option<Arc<dyn store_api::region_engine::PreparedSeriesSource>>, BoxedError>,
623    > {
624        let scan_pool = ctx.memory_pool.clone();
625        let state = self.prepared.clone();
626        let stream_ctx = self.stream_ctx.clone();
627        let ranges = self
628            .properties
629            .partitions
630            .iter()
631            .flatten()
632            .copied()
633            .collect();
634        let labels = label_source.clone();
635        let metrics = new_partition_metrics(
636            &self.stream_ctx,
637            ctx.explain_verbose,
638            metrics_set,
639            0,
640            &self.metrics_list,
641        );
642        Box::pin(async move {
643            let Some((preparation, prepared_columnar)) = preparation? else {
644                return Ok(None);
645            };
646            if !prepared_columnar {
647                // Known unsupported coverage: the caller keeps the ordinary scan instead.
648                return Ok(None);
649            }
650            state
651                .prepare(stream_ctx, ranges, labels, preparation, metrics, scan_pool)
652                .await
653                .map(Some)
654        })
655    }
656
657    fn supports_two_phase(input: &ScanInput) -> bool {
658        if !is_sparse_metric_metadata(input.region_metadata()) {
659            return false;
660        }
661        #[cfg(feature = "enterprise")]
662        if !input.extension_ranges().is_empty() {
663            return false;
664        }
665        true
666    }
667
668    #[tracing::instrument(
669        skip_all,
670        fields(
671            region_id = %self.stream_ctx.input.mapper.metadata().region_id,
672            partition = partition
673        )
674    )]
675    fn scan_partition_impl(
676        &self,
677        ctx: &QueryScanContext,
678        metrics_set: &ExecutionPlanMetricsSet,
679        partition: usize,
680    ) -> Result<SendableRecordBatchStream> {
681        let metrics = new_partition_metrics(
682            &self.stream_ctx,
683            ctx.explain_verbose,
684            metrics_set,
685            partition,
686            &self.metrics_list,
687        );
688
689        let batch_stream =
690            self.scan_batch_in_partition(ctx, partition, metrics.clone(), metrics_set)?;
691
692        let input = &self.stream_ctx.input;
693        let record_batch_stream = ConvertBatchStream::new(
694            batch_stream,
695            input.mapper.clone(),
696            input.cache_strategy.clone(),
697            metrics,
698        );
699
700        Ok(Box::pin(RecordBatchStreamWrapper::new(
701            input.mapper.output_schema(),
702            Box::pin(record_batch_stream),
703        )))
704    }
705
706    #[tracing::instrument(
707        skip_all,
708        fields(
709            region_id = %self.stream_ctx.input.mapper.metadata().region_id,
710            partition = partition
711        )
712    )]
713    fn scan_batch_in_partition(
714        &self,
715        ctx: &QueryScanContext,
716        partition: usize,
717        part_metrics: PartitionMetrics,
718        metrics_set: &ExecutionPlanMetricsSet,
719    ) -> Result<ScanBatchStream> {
720        if ctx.explain_verbose {
721            common_telemetry::info!(
722                "SeriesScan partition {}, region_id: {}",
723                partition,
724                self.stream_ctx.input.region_metadata().region_id
725            );
726        }
727
728        ensure!(
729            partition < self.properties.num_partitions(),
730            PartitionOutOfRangeSnafu {
731                given: partition,
732                all: self.properties.num_partitions(),
733            }
734        );
735
736        match self.mode {
737            SeriesScanMode::Prepared => Ok(prepared::scan_batches(
738                self.prepared.clone(),
739                self.stream_ctx.clone(),
740                self.properties
741                    .partitions
742                    .iter()
743                    .flatten()
744                    .copied()
745                    .collect(),
746                partition,
747                self.properties.num_partitions().max(1),
748                part_metrics,
749                ctx.memory_pool.clone(),
750            )),
751            SeriesScanMode::Legacy => self.scan_legacy_batch_in_partition(
752                partition,
753                part_metrics,
754                metrics_set,
755                ctx.explain_verbose,
756            ),
757            SeriesScanMode::TwoPhase => {
758                self.scan_two_phase_batch_in_partition(ctx, partition, part_metrics, metrics_set)
759            }
760        }
761    }
762
763    fn scan_legacy_batch_in_partition(
764        &self,
765        partition: usize,
766        part_metrics: PartitionMetrics,
767        metrics_set: &ExecutionPlanMetricsSet,
768        explain_verbose: bool,
769    ) -> Result<ScanBatchStream> {
770        self.maybe_start_legacy_distributor(metrics_set, explain_verbose);
771        let mut receiver = self.legacy_receivers.lock().unwrap()[partition]
772            .take()
773            .context(ScanMultiTimesSnafu { partition })?;
774        let stream = try_stream! {
775            part_metrics.on_first_poll();
776
777            let mut fetch_start = Instant::now();
778            let mut metrics = ScannerMetrics::default();
779            while let Some(series) = receiver.recv().await {
780                let series = series?;
781                metrics.scan_cost += fetch_start.elapsed();
782                metrics.num_batches += series.num_batches();
783                metrics.num_rows += series.num_rows();
784
785                let yield_start = Instant::now();
786                yield ScanBatch::Series(series);
787                metrics.yield_cost += yield_start.elapsed();
788                fetch_start = Instant::now();
789            }
790
791            part_metrics.merge_metrics(&metrics);
792            part_metrics.on_finish();
793        };
794        Ok(Box::pin(stream))
795    }
796
797    fn scan_two_phase_batch_in_partition(
798        &self,
799        ctx: &QueryScanContext,
800        partition: usize,
801        part_metrics: PartitionMetrics,
802        metrics_set: &ExecutionPlanMetricsSet,
803    ) -> Result<ScanBatchStream> {
804        self.maybe_start_candidate_distributor(ctx, metrics_set);
805        // Safety: `scan_batch_in_partition` validates the index, and the receiver
806        // list always contains one entry for each output partition.
807        let mut receiver = self.candidate_receivers.lock().unwrap()[partition]
808            .take()
809            .context(ScanMultiTimesSnafu { partition })?;
810        let stream_ctx = self.stream_ctx.clone();
811        let partition_ranges = self
812            .properties
813            .partitions
814            .iter()
815            .flatten()
816            .copied()
817            .collect::<Vec<_>>();
818        let stream = try_stream! {
819            part_metrics.on_first_poll();
820
821            let mut fetch_start = Instant::now();
822            let mut metrics = ScannerMetrics::default();
823            while let Some(input) = receiver.recv().await {
824                let input = input?;
825                metrics.scan_cost += fetch_start.elapsed();
826
827                let build_start = Instant::now();
828                let reader = SeriesReader::try_new(
829                    stream_ctx.clone(),
830                    partition_ranges.clone(),
831                    input.assigned_series,
832                    input.partition_pruner,
833                    input.range_semaphore,
834                    part_metrics.clone(),
835                )?;
836                let mut reader_stream = reader.build_stream().await?;
837                metrics.scan_cost += build_start.elapsed();
838                fetch_start = Instant::now();
839                while let Some(record_batch) = reader_stream.try_next().await? {
840                    metrics.scan_cost += fetch_start.elapsed();
841                    metrics.num_batches += 1;
842                    metrics.num_rows += record_batch.num_rows();
843
844                    let yield_start = Instant::now();
845                    yield ScanBatch::RecordBatch(record_batch);
846                    metrics.yield_cost += yield_start.elapsed();
847                    fetch_start = Instant::now();
848                }
849            }
850            metrics.scan_cost += fetch_start.elapsed();
851
852            part_metrics.merge_metrics(&metrics);
853            part_metrics.on_finish();
854        };
855        Ok(Box::pin(stream))
856    }
857
858    fn maybe_start_legacy_distributor(
859        &self,
860        metrics_set: &ExecutionPlanMetricsSet,
861        explain_verbose: bool,
862    ) {
863        let mut rx_list = self.legacy_receivers.lock().unwrap();
864        if !rx_list.is_empty() {
865            return;
866        }
867
868        let (senders, receivers) = new_legacy_channel_list(self.properties.num_partitions());
869        let mut distributor = SeriesDistributor {
870            stream_ctx: self.stream_ctx.clone(),
871            range_semaphore: Some(Arc::new(Semaphore::new(self.properties.num_partitions()))),
872            final_merge_semaphore: Some(Arc::new(Semaphore::new(self.properties.num_partitions()))),
873            partitions: self.properties.partitions.clone(),
874            pruner: self.pruner.clone(),
875            senders,
876            metrics_set: metrics_set.clone(),
877            metrics_list: self.metrics_list.clone(),
878            explain_verbose,
879        };
880        let region_id = distributor.stream_ctx.input.mapper.metadata().region_id;
881        let span = tracing::info_span!("SeriesScan::distributor", region_id = %region_id);
882        common_runtime::spawn_query(
883            async move {
884                distributor.execute().await;
885            }
886            .instrument(span),
887        );
888
889        *rx_list = receivers;
890    }
891
892    fn maybe_start_candidate_distributor(
893        &self,
894        ctx: &QueryScanContext,
895        metrics_set: &ExecutionPlanMetricsSet,
896    ) {
897        let mut rx_list = self.candidate_receivers.lock().unwrap();
898        if !rx_list.is_empty() {
899            return;
900        }
901
902        let (senders, receivers, active_receivers) =
903            new_candidate_channel_list(self.properties.num_partitions());
904        // Capture the first partition's runtime pool once for the shared distributor.
905        // reset_state clears the receivers so the next execution captures a fresh pool.
906        let mut distributor = SeriesCandidateDistributor {
907            memory_pool: ctx.memory_pool.clone(),
908            stream_ctx: self.stream_ctx.clone(),
909            range_semaphore: Arc::new(Semaphore::new(self.properties.num_partitions())),
910            partitions: self.properties.partitions.clone(),
911            pruner: self.pruner.clone(),
912            senders,
913            active_receivers,
914            metrics_set: metrics_set.clone(),
915            metrics_list: self.metrics_list.clone(),
916            explain_verbose: ctx.explain_verbose,
917        };
918        let region_id = distributor.stream_ctx.input.mapper.metadata().region_id;
919        let span = tracing::info_span!("SeriesScan::candidate_distributor", region_id = %region_id);
920        common_runtime::spawn_query(
921            async move {
922                distributor.execute().await;
923            }
924            .instrument(span),
925        );
926
927        *rx_list = receivers;
928    }
929
930    /// Scans the region and returns a stream.
931    #[tracing::instrument(
932        skip_all,
933        fields(region_id = %self.stream_ctx.input.mapper.metadata().region_id)
934    )]
935    pub(crate) async fn build_stream(&self) -> Result<SendableRecordBatchStream, BoxedError> {
936        let part_num = self.properties.num_partitions();
937        let metrics_set = ExecutionPlanMetricsSet::default();
938        let ctx = QueryScanContext::default();
939        let streams = (0..part_num)
940            .map(|i| self.scan_partition(&ctx, &metrics_set, i))
941            .collect::<Result<Vec<_>, BoxedError>>()?;
942        let chained_stream = ChainedRecordBatchStream::new(streams).map_err(BoxedError::new)?;
943        Ok(Box::pin(chained_stream))
944    }
945
946    /// Scan [`Batch`] in all partitions one by one.
947    pub(crate) fn scan_all_partitions(&self) -> Result<ScanBatchStream> {
948        let metrics_set = ExecutionPlanMetricsSet::new();
949
950        let ctx = QueryScanContext::default();
951        let streams = (0..self.properties.partitions.len())
952            .map(|partition| {
953                let metrics = new_partition_metrics(
954                    &self.stream_ctx,
955                    false,
956                    &metrics_set,
957                    partition,
958                    &self.metrics_list,
959                );
960
961                self.scan_batch_in_partition(&ctx, partition, metrics, &metrics_set)
962            })
963            .collect::<Result<Vec<_>>>()?;
964
965        Ok(Box::pin(futures::stream::iter(streams).flatten()))
966    }
967
968    /// Checks resource limit for the scanner.
969    pub(crate) fn check_scan_limit(&self) -> Result<()> {
970        // Sum the total number of files across all partitions
971        let total_files: usize = self
972            .properties
973            .partitions
974            .iter()
975            .flat_map(|partition| partition.iter())
976            .map(|part_range| {
977                let range_meta = &self.stream_ctx.ranges[part_range.identifier];
978                range_meta.indices.len()
979            })
980            .sum();
981
982        if !self.stream_ctx.input.compaction {
983            SCAN_MAX_CONCURRENT_FILES
984                .with_label_values(&["query"])
985                .observe(total_files as f64);
986        }
987        if self.stream_ctx.input.uses_scan_memory_limit() {
988            return Ok(());
989        }
990
991        let max_concurrent_files = self.stream_ctx.input.max_concurrent_scan_files;
992        if total_files > max_concurrent_files {
993            return TooManyFilesToReadSnafu {
994                actual: total_files,
995                max: max_concurrent_files,
996            }
997            .fail();
998        }
999
1000        Ok(())
1001    }
1002}
1003
1004fn new_legacy_channel_list(num_partitions: usize) -> (SenderList, LegacyReceiverList) {
1005    let (senders, receivers): (Vec<_>, Vec<_>) = (0..num_partitions)
1006        .map(|_| {
1007            let (sender, receiver) = mpsc::channel(1);
1008            (Some(sender), Some(receiver))
1009        })
1010        .unzip();
1011    (SenderList::new(senders), receivers)
1012}
1013
1014fn new_candidate_channel_list(
1015    num_partitions: usize,
1016) -> (CandidateSenderList, CandidateReceiverList, Arc<AtomicUsize>) {
1017    let active_receivers = Arc::new(AtomicUsize::new(num_partitions));
1018    let (senders, receivers) = (0..num_partitions)
1019        .map(|_| {
1020            // Partition streams can be consumed sequentially. A bounded channel for an unpolled
1021            // partition could block the distributor and prevent it from sending more assignments
1022            // to the partition currently being consumed, causing a deadlock.
1023            let (sender, receiver) = mpsc::unbounded_channel();
1024            let receiver = CandidateReceiver {
1025                receiver,
1026                active_receivers: active_receivers.clone(),
1027            };
1028            (Some(sender), Some(receiver))
1029        })
1030        .unzip();
1031    (senders, receivers, active_receivers)
1032}
1033
1034impl RegionScanner for SeriesScan {
1035    fn name(&self) -> &str {
1036        "SeriesScan"
1037    }
1038
1039    fn properties(&self) -> &ScannerProperties {
1040        &self.properties
1041    }
1042
1043    fn schema(&self) -> SchemaRef {
1044        self.stream_ctx.input.mapper.output_schema()
1045    }
1046
1047    fn metadata(&self) -> RegionMetadataRef {
1048        self.stream_ctx.input.mapper.metadata().clone()
1049    }
1050
1051    fn scan_partition(
1052        &self,
1053        ctx: &QueryScanContext,
1054        metrics_set: &ExecutionPlanMetricsSet,
1055        partition: usize,
1056    ) -> Result<SendableRecordBatchStream, BoxedError> {
1057        self.scan_partition_impl(ctx, metrics_set, partition)
1058            .map_err(BoxedError::new)
1059    }
1060
1061    fn raw_series_ordering(&self) -> Result<SeriesOrdering, BoxedError> {
1062        // Both prepared-columnar and ordinary (legacy or two-phase) scans guarantee key/time order.
1063        Ok(SeriesOrdering::KeyThenTime)
1064    }
1065
1066    fn raw_series_schema(
1067        &self,
1068        label_source: &RawLabelSource,
1069    ) -> Result<Option<Arc<SeriesSchema>>, BoxedError> {
1070        Ok(self
1071            .prepare_raw_scan(label_source)?
1072            .map(|(preparation, _)| preparation.schema))
1073    }
1074
1075    fn raw_series_has_explicit_labels(&self, labels: &RawLabelSource) -> Result<bool, BoxedError> {
1076        let Some((mut raw, columnar)) = self.prepare_raw_scan(labels)? else {
1077            return Ok(false);
1078        };
1079        Ok(columnar
1080            && prepared::sample_merge_schema(&self.stream_ctx, &mut raw)
1081                .map_err(BoxedError::new)?
1082                .is_some())
1083    }
1084
1085    fn scan_series_partition(
1086        &self,
1087        ctx: &QueryScanContext,
1088        metrics_set: &ExecutionPlanMetricsSet,
1089        partition: usize,
1090        label_source: &RawLabelSource,
1091    ) -> Result<Option<SendableRawSeriesStream>, BoxedError> {
1092        let Some((preparation, prepared_columnar)) = self.prepare_raw_scan(label_source)? else {
1093            return Ok(None);
1094        };
1095        if prepared_columnar {
1096            let partitions = self.properties.num_partitions().max(1);
1097            if partition >= partitions {
1098                return Err(BoxedError::new(
1099                    PartitionOutOfRangeSnafu {
1100                        given: partition,
1101                        all: partitions,
1102                    }
1103                    .build(),
1104                ));
1105            }
1106            // Preflight needs the declaration before the stream is polled, while preparation
1107            // needs the original field indices and predicates to derive its own merge schema.
1108            let explicit_labels =
1109                prepared::sample_merge_schema(&self.stream_ctx, &mut preparation.clone())
1110                    .map_err(BoxedError::new)?
1111                    .is_some();
1112            let schema = preparation.schema.clone();
1113            let preparation = self
1114                .check_scan_limit()
1115                .map_err(BoxedError::new)
1116                .map(|_| Some((preparation, prepared_columnar)));
1117            let future = self.prepare_series_with_raw(ctx, metrics_set, label_source, preparation);
1118            let labels = label_source.clone();
1119            let stream = async_stream::try_stream! {
1120                let source = future.await?.ok_or_else(|| BoxedError::new(InvalidRecordBatchSnafu { reason: "columnar prepared capability disappeared" }.build()))?;
1121                let n = source.num_series() as u128;
1122                let start = (n * partition as u128 / partitions as u128) as usize;
1123                let end = (n * (partition + 1) as u128 / partitions as u128) as usize;
1124                let mut reader = source.read_series(start..end)?;
1125                while let Some(chunk) = reader.try_next().await? { yield chunk; }
1126            };
1127            return Ok(Some(raw::from_stream(
1128                schema,
1129                labels,
1130                SeriesOrdering::KeyThenTime,
1131                explicit_labels,
1132                Box::pin(stream),
1133            )));
1134        }
1135        // Stored sources without columnar artifacts (memtables, unindexed SSTs) are read by the
1136        // ordinary scan, so the raw path stays available.
1137        let metrics = new_partition_metrics(
1138            &self.stream_ctx,
1139            ctx.explain_verbose,
1140            metrics_set,
1141            partition,
1142            &self.metrics_list,
1143        );
1144        let batches = self
1145            .scan_batch_in_partition(ctx, partition, metrics.clone(), metrics_set)
1146            .map_err(BoxedError::new)?;
1147        Ok(Some(raw::make_stream(
1148            batches,
1149            preparation.schema,
1150            label_source.clone(),
1151            preparation.fields,
1152            metrics,
1153            preparation.predicates,
1154            SeriesOrdering::KeyThenTime,
1155        )))
1156    }
1157
1158    fn prepare_series(
1159        &self,
1160        ctx: &QueryScanContext,
1161        metrics_set: &ExecutionPlanMetricsSet,
1162        label_source: &RawLabelSource,
1163    ) -> futures::future::BoxFuture<
1164        'static,
1165        Result<Option<Arc<dyn store_api::region_engine::PreparedSeriesSource>>, BoxedError>,
1166    > {
1167        if !self.uses_columnar() {
1168            return Box::pin(async { Ok(None) });
1169        }
1170        let preparation = self
1171            .check_scan_limit()
1172            .map_err(BoxedError::new)
1173            .and_then(|_| self.prepare_raw_scan(label_source));
1174        self.prepare_series_with_raw(ctx, metrics_set, label_source, preparation)
1175    }
1176
1177    fn prepare(&mut self, request: PrepareRequest) -> Result<(), BoxedError> {
1178        self.prepared = Arc::new(prepared::Preparation::default());
1179        self.clear_preflight_cache();
1180        self.properties.prepare(request);
1181
1182        self.check_scan_limit().map_err(BoxedError::new)?;
1183
1184        Ok(())
1185    }
1186
1187    fn has_predicate_without_region(&self) -> bool {
1188        let predicate = self
1189            .stream_ctx
1190            .input
1191            .predicate_group()
1192            .predicate_without_region();
1193        predicate.is_some()
1194    }
1195
1196    fn add_dyn_filter_to_predicate(
1197        &mut self,
1198        filter_exprs: Vec<Arc<dyn datafusion::physical_plan::PhysicalExpr>>,
1199    ) -> Vec<bool> {
1200        if self.stream_ctx.input.requires_narthex_preparation() {
1201            return vec![false; filter_exprs.len()];
1202        }
1203        let matched = self.stream_ctx.add_dyn_filter_to_predicate(filter_exprs);
1204        // The added filters change the predicate group the preflight inspects.
1205        self.clear_preflight_cache();
1206        matched
1207    }
1208
1209    fn reset_state(&mut self) {
1210        self.prepared = Arc::new(prepared::Preparation::default());
1211        self.clear_preflight_cache();
1212        self.stream_ctx.input.predicate.clear_dyn_filters();
1213        let num_workers = common_stat::get_total_cpu_cores().max(1);
1214        self.pruner = match self.mode {
1215            SeriesScanMode::Legacy | SeriesScanMode::Prepared => {
1216                Arc::new(Pruner::new(self.stream_ctx.clone(), num_workers))
1217            }
1218            SeriesScanMode::TwoPhase => Arc::new(Pruner::new_with_options(
1219                self.stream_ctx.clone(),
1220                num_workers,
1221                PrunerOptions {
1222                    retain_builders: true,
1223                    enable_predicate_prefilter: false,
1224                },
1225            )),
1226        };
1227        self.legacy_receivers.lock().unwrap().clear();
1228        self.candidate_receivers.lock().unwrap().clear();
1229        self.metrics_list = Arc::new(PartitionMetricsList::default());
1230    }
1231
1232    fn set_logical_region(&mut self, logical_region: bool) {
1233        self.properties.set_logical_region(logical_region);
1234    }
1235
1236    fn set_query_load_region_id(&mut self, region_id: store_api::storage::RegionId) {
1237        self.properties.set_query_load_region_id(region_id);
1238    }
1239
1240    fn snapshot_sequence(&self) -> Option<u64> {
1241        self.stream_ctx.input.snapshot_sequence
1242    }
1243}
1244
1245impl DisplayAs for SeriesScan {
1246    fn fmt_as(&self, t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
1247        write!(
1248            f,
1249            "SeriesScan: region={}, ",
1250            self.stream_ctx.input.mapper.metadata().region_id
1251        )?;
1252        match t {
1253            DisplayFormatType::Default | DisplayFormatType::TreeRender => {
1254                self.stream_ctx.format_for_explain(false, f)?;
1255            }
1256            DisplayFormatType::Verbose => {
1257                self.stream_ctx.format_for_explain(true, f)?;
1258            }
1259        }
1260        write!(f, ", \"mode\":\"{}\"", self.mode.as_str())?;
1261        if matches!(t, DisplayFormatType::Verbose) {
1262            self.metrics_list.format_verbose_metrics(f)?;
1263        }
1264        Ok(())
1265    }
1266}
1267
1268impl fmt::Debug for SeriesScan {
1269    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1270        f.debug_struct("SeriesScan")
1271            .field("mode", &self.mode)
1272            .field("num_ranges", &self.stream_ctx.ranges.len())
1273            .finish()
1274    }
1275}
1276
1277#[cfg(test)]
1278impl SeriesScan {
1279    /// Returns the input.
1280    pub(crate) fn input(&self) -> &ScanInput {
1281        &self.stream_ctx.input
1282    }
1283
1284    /// Returns the scan mode for tests.
1285    pub(crate) fn mode(&self) -> &'static str {
1286        self.mode.as_str()
1287    }
1288}
1289
1290/// The distributor scans series and distributes them to different partitions.
1291struct SeriesDistributor {
1292    /// Context for the scan stream.
1293    stream_ctx: Arc<StreamContext>,
1294    /// Semaphore for file scanning and range-level merging.
1295    range_semaphore: Option<Arc<Semaphore>>,
1296    /// Semaphore for the final merge across all range streams.
1297    /// Must be separate from `range_semaphore` to avoid deadlock: final merge tasks
1298    /// hold a permit while waiting for data from range-level merge tasks, which also
1299    /// need permits to produce data.
1300    final_merge_semaphore: Option<Arc<Semaphore>>,
1301    /// Partition ranges to scan.
1302    partitions: Vec<Vec<PartitionRange>>,
1303    /// Shared pruner for file range building.
1304    pruner: Arc<Pruner>,
1305    /// Senders of all partitions.
1306    senders: SenderList,
1307    /// Metrics set to report.
1308    /// The distributor report the metrics as an additional partition.
1309    /// This may double the scan cost of the [SeriesScan] metrics. We can
1310    /// get per-partition metrics in verbose mode to see the metrics of the
1311    /// distributor.
1312    metrics_set: ExecutionPlanMetricsSet,
1313    metrics_list: Arc<PartitionMetricsList>,
1314    /// Whether to use verbose logging and collect detailed metrics.
1315    explain_verbose: bool,
1316}
1317
1318impl SeriesDistributor {
1319    /// Executes the distributor.
1320    #[tracing::instrument(
1321        skip_all,
1322        fields(region_id = %self.stream_ctx.input.mapper.metadata().region_id)
1323    )]
1324    async fn execute(&mut self) {
1325        if let Err(e) = self.scan_partitions_flat().await {
1326            self.senders.send_error(e).await;
1327        }
1328    }
1329
1330    /// Scans all parts in flat format using FlatSeriesBatchDivider.
1331    #[tracing::instrument(
1332        skip_all,
1333        fields(region_id = %self.stream_ctx.input.mapper.metadata().region_id)
1334    )]
1335    async fn scan_partitions_flat(&mut self) -> Result<()> {
1336        // Initialize reference counts for all partition ranges.
1337        for partition_ranges in &self.partitions {
1338            self.pruner.add_partition_ranges(partition_ranges);
1339        }
1340
1341        // Create PartitionPruner covering all partitions
1342        let all_partition_ranges: Vec<_> = self.partitions.iter().flatten().cloned().collect();
1343        let needs_merge = all_partition_ranges.len() > 1;
1344        let partition_pruner = Arc::new(PartitionPruner::new(
1345            self.pruner.clone(),
1346            &all_partition_ranges,
1347        ));
1348
1349        let part_metrics = new_partition_metrics(
1350            &self.stream_ctx,
1351            self.explain_verbose,
1352            &self.metrics_set,
1353            self.partitions.len(),
1354            &self.metrics_list,
1355        );
1356        part_metrics.on_first_poll();
1357        // Start fetch time before building sources so scan cost contains
1358        // build part cost.
1359        let mut fetch_start = Instant::now();
1360
1361        // Builds one deduped stream per partition range, then merges across ranges.
1362        let build_start = Instant::now();
1363        let mut tasks = Vec::new();
1364        for partition in &self.partitions {
1365            for part_range in partition {
1366                let stream_ctx = self.stream_ctx.clone();
1367                let part_range = *part_range;
1368                let part_metrics = part_metrics.clone();
1369                let partition_pruner = partition_pruner.clone();
1370                let file_scan_semaphore = self.range_semaphore.clone();
1371                let merge_semaphore = self.range_semaphore.clone();
1372                tasks.push(common_runtime::spawn_query(async move {
1373                    SeqScan::build_flat_partition_range_read(
1374                        &stream_ctx,
1375                        &part_range,
1376                        if needs_merge {
1377                            FlatReadMode::CrossRangeMerge
1378                        } else {
1379                            FlatReadMode::Sequential
1380                        },
1381                        &part_metrics,
1382                        partition_pruner,
1383                        file_scan_semaphore,
1384                        merge_semaphore,
1385                    )
1386                    .await
1387                }));
1388            }
1389        }
1390        let mut range_streams = Vec::with_capacity(tasks.len());
1391        let mut estimated_batch_sizes = Vec::with_capacity(tasks.len());
1392        for task in tasks {
1393            let (stream, estimated_batch_size) = task.await.context(JoinSnafu)??;
1394            range_streams.push(stream);
1395            estimated_batch_sizes.push(estimated_batch_size);
1396        }
1397        let channel_size =
1398            compute_parallel_channel_size(compute_average_batch_size(estimated_batch_sizes));
1399        common_telemetry::debug!(
1400            "SeriesDistributor built {} range_streams, region: {}, build cost: {:?}, channel_size: {}",
1401            range_streams.len(),
1402            self.stream_ctx.input.region_metadata().region_id,
1403            build_start.elapsed(),
1404            channel_size,
1405        );
1406
1407        // Each partition range stream is already deduped, so skip dedup here.
1408        // Use a separate semaphore for the final merge to avoid deadlock with
1409        // range-level merge tasks that share the range_semaphore.
1410        let mut reader = SeqScan::build_flat_reader_from_sources(
1411            &self.stream_ctx,
1412            range_streams,
1413            self.final_merge_semaphore.clone(),
1414            Some(&part_metrics),
1415            true,
1416            channel_size,
1417        )
1418        .await?;
1419        let mut metrics = SeriesDistributorMetrics::default();
1420
1421        let mut divider = FlatSeriesBatchDivider::default();
1422        while let Some(record_batch) = reader.try_next().await? {
1423            metrics.scan_cost += fetch_start.elapsed();
1424            metrics.num_batches += 1;
1425            metrics.num_rows += record_batch.num_rows();
1426
1427            debug_assert!(record_batch.num_rows() > 0);
1428            if record_batch.num_rows() == 0 {
1429                fetch_start = Instant::now();
1430                continue;
1431            }
1432
1433            // Use divider to split series
1434            let divider_start = Instant::now();
1435            let series_batch = divider.push(record_batch);
1436            metrics.divider_cost += divider_start.elapsed();
1437            if let Some(series_batch) = series_batch {
1438                let yield_start = Instant::now();
1439                self.senders
1440                    .send_batch(SeriesBatch::Flat(series_batch))
1441                    .await?;
1442                metrics.yield_cost += yield_start.elapsed();
1443            }
1444            fetch_start = Instant::now();
1445        }
1446
1447        // Send any remaining batch in the divider
1448        let divider_start = Instant::now();
1449        let series_batch = divider.finish();
1450        metrics.divider_cost += divider_start.elapsed();
1451        if let Some(series_batch) = series_batch {
1452            let yield_start = Instant::now();
1453            self.senders
1454                .send_batch(SeriesBatch::Flat(series_batch))
1455                .await?;
1456            metrics.yield_cost += yield_start.elapsed();
1457        }
1458
1459        metrics.scan_cost += fetch_start.elapsed();
1460        metrics.num_series_send_full = self.senders.num_full;
1461        part_metrics.set_distributor_metrics(&metrics);
1462
1463        part_metrics.on_finish();
1464
1465        Ok(())
1466    }
1467}
1468
1469/// Discovers metric series and sends one reader assignment to each partition.
1470struct SeriesCandidateDistributor {
1471    memory_pool: Arc<dyn MemoryPool>,
1472    stream_ctx: Arc<StreamContext>,
1473    range_semaphore: Arc<Semaphore>,
1474    partitions: Vec<Vec<PartitionRange>>,
1475    pruner: Arc<Pruner>,
1476    senders: CandidateSenderList,
1477    active_receivers: Arc<AtomicUsize>,
1478    metrics_set: ExecutionPlanMetricsSet,
1479    metrics_list: Arc<PartitionMetricsList>,
1480    explain_verbose: bool,
1481}
1482
1483impl SeriesCandidateDistributor {
1484    async fn execute(&mut self) {
1485        if let Err(e) = self.distribute().await {
1486            self.send_error(e);
1487        }
1488    }
1489
1490    async fn distribute(&mut self) -> Result<()> {
1491        let part_metrics = new_partition_metrics(
1492            &self.stream_ctx,
1493            self.explain_verbose,
1494            &self.metrics_set,
1495            self.partitions.len(),
1496            &self.metrics_list,
1497        );
1498        part_metrics.on_first_poll();
1499
1500        let candidate_scanner = SeriesCandidateScanner::try_new(
1501            self.stream_ctx.clone(),
1502            self.partitions.clone(),
1503            self.pruner.clone(),
1504            self.range_semaphore.clone(),
1505            self.memory_pool.clone(),
1506            self.metrics_set.clone(),
1507            part_metrics.clone(),
1508        )?;
1509        let partition_pruner = candidate_scanner.partition_pruner();
1510        let mut candidates = candidate_scanner.build_stream().await?;
1511        let mut collector =
1512            SeriesBatchCollector::new(self.partitions.len()).context(InvalidSenderSnafu)?;
1513        let mut chunked = false;
1514        while let Some(batch) = candidates.try_next().await? {
1515            if !self.should_fetch_candidates() {
1516                part_metrics.on_finish();
1517                return Ok(());
1518            }
1519            collector.push(batch);
1520            if collector.len() >= candidate_series_assignment_threshold() {
1521                chunked = true;
1522                self.send_assignments(collector.finish(false), &partition_pruner);
1523                if !self.should_fetch_candidates() {
1524                    part_metrics.on_finish();
1525                    return Ok(());
1526                }
1527                collector =
1528                    SeriesBatchCollector::new(self.partitions.len()).context(InvalidSenderSnafu)?;
1529            }
1530        }
1531
1532        if collector.len() > 0 {
1533            self.send_assignments(collector.finish(!chunked), &partition_pruner);
1534        }
1535        part_metrics.on_finish();
1536        Ok(())
1537    }
1538
1539    fn send_assignments(
1540        &mut self,
1541        assignments: Vec<AssignedSeriesBatch>,
1542        partition_pruner: &Arc<PartitionPruner>,
1543    ) {
1544        // One round of candidate collection; a partition that receives two assignments sees two.
1545        #[cfg(test)]
1546        CANDIDATE_ASSIGNMENT_ROUNDS.fetch_add(1, Ordering::Relaxed);
1547        for (partition, assigned_series) in assignments.into_iter().enumerate() {
1548            if assigned_series.series().is_empty() {
1549                continue;
1550            }
1551            let Some(sender) = self.senders[partition].as_ref() else {
1552                continue;
1553            };
1554            let sent = sender
1555                .send(Ok(SeriesReaderInput {
1556                    assigned_series,
1557                    partition_pruner: partition_pruner.clone(),
1558                    range_semaphore: self.range_semaphore.clone(),
1559                }))
1560                .is_ok();
1561            if !sent {
1562                self.senders[partition] = None;
1563            }
1564        }
1565    }
1566
1567    fn should_fetch_candidates(&self) -> bool {
1568        self.active_receivers.load(Ordering::Relaxed) > 0
1569    }
1570
1571    fn send_error(&mut self, error: Error) {
1572        let error = Arc::new(error);
1573        for sender in self.senders.iter_mut().filter_map(Option::take) {
1574            let result = Err(error.clone()).context(ScanSeriesSnafu);
1575            let _ = sender.send(result);
1576        }
1577    }
1578}
1579
1580/// Batches of complete series.
1581///
1582/// A package may hold rows of more than one series, and every series in it is complete: no later
1583/// package of the same stream holds more rows of those series.
1584#[derive(Debug)]
1585pub enum SeriesBatch {
1586    Flat(FlatSeriesBatch),
1587}
1588
1589impl SeriesBatch {
1590    /// Returns the number of batches.
1591    pub fn num_batches(&self) -> usize {
1592        match self {
1593            SeriesBatch::Flat(flat_batch) => flat_batch.batches.len(),
1594        }
1595    }
1596
1597    /// Returns the total number of rows across all batches.
1598    pub fn num_rows(&self) -> usize {
1599        match self {
1600            SeriesBatch::Flat(flat_batch) => flat_batch.batches.iter().map(|x| x.num_rows()).sum(),
1601        }
1602    }
1603}
1604
1605/// Batches of the same series in flat format.
1606#[derive(Default, Debug)]
1607pub struct FlatSeriesBatch {
1608    pub batches: SmallVec<[RecordBatch; 4]>,
1609}
1610
1611/// List of senders.
1612struct SenderList {
1613    senders: Vec<Option<Sender<Result<SeriesBatch>>>>,
1614    /// Number of None senders.
1615    num_nones: usize,
1616    /// Index of the current partition to send.
1617    sender_idx: usize,
1618    /// Number of full senders.
1619    num_full: usize,
1620}
1621
1622impl SenderList {
1623    fn new(senders: Vec<Option<Sender<Result<SeriesBatch>>>>) -> Self {
1624        let num_nones = senders.iter().filter(|sender| sender.is_none()).count();
1625        Self {
1626            senders,
1627            num_nones,
1628            sender_idx: 0,
1629            num_full: 0,
1630        }
1631    }
1632
1633    /// Finds a partition and tries to send the batch to the partition.
1634    /// Returns None if it sends successfully.
1635    fn try_send_batch(&mut self, mut batch: SeriesBatch) -> Result<Option<SeriesBatch>> {
1636        for _ in 0..self.senders.len() {
1637            ensure!(self.num_nones < self.senders.len(), InvalidSenderSnafu);
1638
1639            let sender_idx = self.fetch_add_sender_idx();
1640            let Some(sender) = &self.senders[sender_idx] else {
1641                continue;
1642            };
1643
1644            match sender.try_send(Ok(batch)) {
1645                Ok(()) => return Ok(None),
1646                Err(TrySendError::Full(res)) => {
1647                    self.num_full += 1;
1648                    // Safety: we send Ok.
1649                    batch = res.unwrap();
1650                }
1651                Err(TrySendError::Closed(res)) => {
1652                    self.senders[sender_idx] = None;
1653                    self.num_nones += 1;
1654                    // Safety: we send Ok.
1655                    batch = res.unwrap();
1656                }
1657            }
1658        }
1659
1660        Ok(Some(batch))
1661    }
1662
1663    /// Finds a partition and sends the batch to the partition.
1664    async fn send_batch(&mut self, batch: SeriesBatch) -> Result<()> {
1665        let Some(batch) = self.try_send_batch(batch)? else {
1666            return Ok(());
1667        };
1668
1669        loop {
1670            ensure!(self.num_nones < self.senders.len(), InvalidSenderSnafu);
1671
1672            // Waits on every partition at once and sends to whichever frees a slot first. A
1673            // consumer may leave partitions unpolled for a long time, e.g. one that drains them one
1674            // after another, and waiting on such a partition would stall the scan.
1675            let closed = {
1676                let reservations = self.senders.iter().enumerate().filter_map(|(idx, sender)| {
1677                    sender
1678                        .as_ref()
1679                        .map(|sender| Box::pin(async move { (idx, sender.reserve().await) }))
1680                });
1681                let ((idx, reserved), _, _) = futures::future::select_all(reservations).await;
1682                match reserved {
1683                    Ok(permit) => {
1684                        permit.send(Ok(batch));
1685                        return Ok(());
1686                    }
1687                    Err(_) => idx,
1688                }
1689            };
1690            self.senders[closed] = None;
1691            self.num_nones += 1;
1692        }
1693    }
1694
1695    async fn send_error(&self, error: Error) {
1696        let error = Arc::new(error);
1697        for sender in self.senders.iter().flatten() {
1698            let result = Err(error.clone()).context(ScanSeriesSnafu);
1699            let _ = sender.send(result).await;
1700        }
1701    }
1702
1703    fn fetch_add_sender_idx(&mut self) -> usize {
1704        let sender_idx = self.sender_idx;
1705        self.sender_idx = (self.sender_idx + 1) % self.senders.len();
1706        sender_idx
1707    }
1708}
1709
1710fn new_partition_metrics(
1711    stream_ctx: &StreamContext,
1712    explain_verbose: bool,
1713    metrics_set: &ExecutionPlanMetricsSet,
1714    partition: usize,
1715    metrics_list: &PartitionMetricsList,
1716) -> PartitionMetrics {
1717    let metrics = PartitionMetrics::new(
1718        stream_ctx.input.mapper.metadata().region_id,
1719        partition,
1720        "SeriesScan",
1721        stream_ctx.query_start,
1722        explain_verbose,
1723        metrics_set,
1724    );
1725
1726    metrics_list.set(partition, metrics.clone());
1727    metrics
1728}
1729
1730/// A divider to split flat record batches by time series.
1731///
1732/// It only ensures rows of the same series are returned in the same [FlatSeriesBatch].
1733/// However, a [FlatSeriesBatch] may contain rows from multiple series.
1734#[derive(Default)]
1735struct FlatSeriesBatchDivider {
1736    buffer: FlatSeriesBatch,
1737}
1738
1739impl FlatSeriesBatchDivider {
1740    /// Pushes a record batch into the divider.
1741    ///
1742    /// Returns a [FlatSeriesBatch] if we ensure the batch contains all rows of the series in it.
1743    fn push(&mut self, batch: RecordBatch) -> Option<FlatSeriesBatch> {
1744        // If buffer is empty
1745        if self.buffer.batches.is_empty() {
1746            self.buffer.batches.push(batch);
1747            return None;
1748        }
1749
1750        // Gets the primary key column from the incoming batch.
1751        let pk_column_idx = primary_key_column_index(batch.num_columns());
1752        let batch_pk_column = batch.column(pk_column_idx);
1753        let batch_pk_array = batch_pk_column
1754            .as_any()
1755            .downcast_ref::<PrimaryKeyArray>()
1756            .unwrap();
1757        let batch_pk_values = batch_pk_array
1758            .values()
1759            .as_any()
1760            .downcast_ref::<BinaryArray>()
1761            .unwrap();
1762        // Gets the last primary key of the incoming batch.
1763        let batch_last_pk =
1764            primary_key_at(batch_pk_array, batch_pk_values, batch_pk_array.len() - 1);
1765        // Gets the last primary key of the buffer.
1766        // Safety: the buffer is not empty.
1767        let buffer_last_batch = self.buffer.batches.last().unwrap();
1768        let buffer_pk_column = buffer_last_batch.column(pk_column_idx);
1769        let buffer_pk_array = buffer_pk_column
1770            .as_any()
1771            .downcast_ref::<PrimaryKeyArray>()
1772            .unwrap();
1773        let buffer_pk_values = buffer_pk_array
1774            .values()
1775            .as_any()
1776            .downcast_ref::<BinaryArray>()
1777            .unwrap();
1778        let buffer_last_pk =
1779            primary_key_at(buffer_pk_array, buffer_pk_values, buffer_pk_array.len() - 1);
1780
1781        // If last primary key in the batch is the same as last primary key in the buffer.
1782        if batch_last_pk == buffer_last_pk {
1783            self.buffer.batches.push(batch);
1784            return None;
1785        }
1786        // Otherwise, the batch must have a different primary key, we find the first offset of the
1787        // changed primary key.
1788        let batch_pk_keys = batch_pk_array.keys();
1789        let pk_indices = batch_pk_keys.values();
1790        let mut change_offset = 0;
1791        for (i, &key) in pk_indices.iter().enumerate() {
1792            let batch_pk = batch_pk_values.value(key as usize);
1793
1794            if buffer_last_pk != batch_pk {
1795                change_offset = i;
1796                break;
1797            }
1798        }
1799
1800        // Splits the batch at the change offset
1801        let (first_part, remaining_part) = if change_offset > 0 {
1802            let first_part = batch.slice(0, change_offset);
1803            let remaining_part = batch.slice(change_offset, batch.num_rows() - change_offset);
1804            (Some(first_part), Some(remaining_part))
1805        } else {
1806            (None, Some(batch))
1807        };
1808
1809        // Creates the result from current buffer + first part of new batch
1810        let mut result = std::mem::take(&mut self.buffer);
1811        if let Some(first_part) = first_part {
1812            result.batches.push(first_part);
1813        }
1814
1815        // Pushes remaining part to the buffer if it exists
1816        if let Some(remaining_part) = remaining_part {
1817            self.buffer.batches.push(remaining_part);
1818        }
1819
1820        Some(result)
1821    }
1822
1823    /// Returns the final [FlatSeriesBatch].
1824    fn finish(&mut self) -> Option<FlatSeriesBatch> {
1825        if self.buffer.batches.is_empty() {
1826            None
1827        } else {
1828            Some(std::mem::take(&mut self.buffer))
1829        }
1830    }
1831}
1832
1833/// Helper function to extract primary key bytes at a specific index from [PrimaryKeyArray].
1834fn primary_key_at<'a>(
1835    primary_key: &PrimaryKeyArray,
1836    primary_key_values: &'a BinaryArray,
1837    index: usize,
1838) -> &'a [u8] {
1839    let key = primary_key.keys().value(index);
1840    primary_key_values.value(key as usize)
1841}
1842
1843#[cfg(test)]
1844mod tests {
1845    use std::sync::Arc;
1846
1847    use api::v1::OpType;
1848    use datatypes::arrow::array::{
1849        ArrayRef, BinaryDictionaryBuilder, Int64Array, StringDictionaryBuilder,
1850        TimestampMillisecondArray, UInt8Array, UInt64Array,
1851    };
1852    use datatypes::arrow::datatypes::{DataType, Field, Schema, SchemaRef, TimeUnit, UInt32Type};
1853    use datatypes::arrow::record_batch::RecordBatch;
1854
1855    use super::*;
1856    use crate::read::flat_projection::FlatProjectionMapper;
1857    use crate::read::scan_region::PredicateGroup;
1858    use crate::test_util::scheduler_util::SchedulerEnv;
1859    use crate::test_util::sst_util::sst_region_metadata_with_encoding;
1860
1861    #[tokio::test]
1862    async fn two_phase_eligibility_allows_exact_sequence_range() {
1863        let env = SchedulerEnv::new().await;
1864        let metadata = Arc::new(sst_region_metadata_with_encoding(
1865            store_api::codec::PrimaryKeyEncoding::Sparse,
1866        ));
1867        let predicate = PredicateGroup::default();
1868
1869        let eligible = ScanInput::builder(
1870            env.access_layer.clone(),
1871            FlatProjectionMapper::new(&metadata, [0]).unwrap(),
1872        )
1873        .with_predicate(predicate.clone())
1874        .build();
1875        assert!(SeriesScan::supports_two_phase(&eligible));
1876
1877        let exact_sequence = ScanInput::builder(
1878            env.access_layer.clone(),
1879            FlatProjectionMapper::new(&metadata, [0]).unwrap(),
1880        )
1881        .with_predicate(predicate)
1882        .with_sequence_range(Some(store_api::storage::SequenceRange::GtLtEq {
1883            min: 1,
1884            max: 2,
1885        }))
1886        .build();
1887        assert!(SeriesScan::supports_two_phase(&exact_sequence));
1888    }
1889
1890    #[test]
1891    fn candidate_distributor_stops_after_all_receivers_close() {
1892        let (_senders, mut receivers, active_receivers) = new_candidate_channel_list(2);
1893        assert_eq!(2, active_receivers.load(Ordering::Relaxed));
1894
1895        drop(receivers[0].take());
1896        assert_eq!(1, active_receivers.load(Ordering::Relaxed));
1897
1898        drop(receivers[1].take());
1899        assert_eq!(0, active_receivers.load(Ordering::Relaxed));
1900    }
1901
1902    #[tokio::test]
1903    async fn distributor_does_not_stall_on_partitions_read_one_after_another() {
1904        const NUM_BATCHES: usize = 2000;
1905        let (mut senders, receivers) = new_legacy_channel_list(16);
1906        let producer = tokio::spawn(async move {
1907            for _ in 0..NUM_BATCHES {
1908                senders
1909                    .send_batch(SeriesBatch::Flat(FlatSeriesBatch::default()))
1910                    .await
1911                    .unwrap();
1912            }
1913        });
1914        // Reads partition 0 to its end before touching the next one, so all other partitions stay
1915        // full while the producer still has batches to send.
1916        let consume = async {
1917            let mut received = 0;
1918            for mut receiver in receivers.into_iter().flatten() {
1919                while let Some(batch) = receiver.recv().await {
1920                    batch.unwrap();
1921                    received += 1;
1922                }
1923            }
1924            received
1925        };
1926        let received = tokio::time::timeout(std::time::Duration::from_secs(1), consume)
1927            .await
1928            .expect("the distributor stalled on partitions the consumer was not reading");
1929        producer.await.unwrap();
1930        assert_eq!(NUM_BATCHES, received);
1931    }
1932
1933    fn new_test_record_batch(
1934        primary_keys: &[&[u8]],
1935        timestamps: &[i64],
1936        sequences: &[u64],
1937        op_types: &[OpType],
1938        fields: &[u64],
1939    ) -> RecordBatch {
1940        let num_rows = timestamps.len();
1941        debug_assert_eq!(sequences.len(), num_rows);
1942        debug_assert_eq!(op_types.len(), num_rows);
1943        debug_assert_eq!(fields.len(), num_rows);
1944        debug_assert_eq!(primary_keys.len(), num_rows);
1945
1946        let columns: Vec<ArrayRef> = vec![
1947            build_test_pk_string_dict_array(primary_keys),
1948            Arc::new(Int64Array::from_iter(
1949                fields.iter().map(|v| Some(*v as i64)),
1950            )),
1951            Arc::new(TimestampMillisecondArray::from_iter_values(
1952                timestamps.iter().copied(),
1953            )),
1954            build_test_pk_array(primary_keys),
1955            Arc::new(UInt64Array::from_iter_values(sequences.iter().copied())),
1956            Arc::new(UInt8Array::from_iter_values(
1957                op_types.iter().map(|v| *v as u8),
1958            )),
1959        ];
1960
1961        RecordBatch::try_new(build_test_flat_schema(), columns).unwrap()
1962    }
1963
1964    fn build_test_pk_string_dict_array(primary_keys: &[&[u8]]) -> ArrayRef {
1965        let mut builder = StringDictionaryBuilder::<UInt32Type>::new();
1966        for &pk in primary_keys {
1967            let pk_str = std::str::from_utf8(pk).unwrap();
1968            builder.append(pk_str).unwrap();
1969        }
1970        Arc::new(builder.finish())
1971    }
1972
1973    fn build_test_pk_array(primary_keys: &[&[u8]]) -> ArrayRef {
1974        let mut builder = BinaryDictionaryBuilder::<UInt32Type>::new();
1975        for &pk in primary_keys {
1976            builder.append(pk).unwrap();
1977        }
1978        Arc::new(builder.finish())
1979    }
1980
1981    fn build_test_flat_schema() -> SchemaRef {
1982        let fields = vec![
1983            Field::new(
1984                "k0",
1985                DataType::Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Utf8)),
1986                false,
1987            ),
1988            Field::new("field0", DataType::Int64, true),
1989            Field::new(
1990                "ts",
1991                DataType::Timestamp(TimeUnit::Millisecond, None),
1992                false,
1993            ),
1994            Field::new(
1995                "__primary_key",
1996                DataType::Dictionary(Box::new(DataType::UInt32), Box::new(DataType::Binary)),
1997                false,
1998            ),
1999            Field::new("__sequence", DataType::UInt64, false),
2000            Field::new("__op_type", DataType::UInt8, false),
2001        ];
2002        Arc::new(Schema::new(fields))
2003    }
2004
2005    #[test]
2006    fn test_empty_buffer_first_push() {
2007        let mut divider = FlatSeriesBatchDivider::default();
2008        let result = divider.finish();
2009        assert!(result.is_none());
2010
2011        let mut divider = FlatSeriesBatchDivider::default();
2012        let batch = new_test_record_batch(
2013            &[b"series1", b"series1"],
2014            &[1000, 2000],
2015            &[1, 2],
2016            &[OpType::Put, OpType::Put],
2017            &[10, 20],
2018        );
2019        let result = divider.push(batch);
2020        assert!(result.is_none());
2021        assert_eq!(divider.buffer.batches.len(), 1);
2022    }
2023
2024    #[test]
2025    fn test_same_series_accumulation() {
2026        let mut divider = FlatSeriesBatchDivider::default();
2027
2028        let batch1 = new_test_record_batch(
2029            &[b"series1", b"series1"],
2030            &[1000, 2000],
2031            &[1, 2],
2032            &[OpType::Put, OpType::Put],
2033            &[10, 20],
2034        );
2035
2036        let batch2 = new_test_record_batch(
2037            &[b"series1", b"series1"],
2038            &[3000, 4000],
2039            &[3, 4],
2040            &[OpType::Put, OpType::Put],
2041            &[30, 40],
2042        );
2043
2044        divider.push(batch1);
2045        let result = divider.push(batch2);
2046        assert!(result.is_none());
2047        let series_batch = divider.finish().unwrap();
2048        assert_eq!(series_batch.batches.len(), 2);
2049    }
2050
2051    #[test]
2052    fn test_series_boundary_detection() {
2053        let mut divider = FlatSeriesBatchDivider::default();
2054
2055        let batch1 = new_test_record_batch(
2056            &[b"series1", b"series1"],
2057            &[1000, 2000],
2058            &[1, 2],
2059            &[OpType::Put, OpType::Put],
2060            &[10, 20],
2061        );
2062
2063        let batch2 = new_test_record_batch(
2064            &[b"series2", b"series2"],
2065            &[3000, 4000],
2066            &[3, 4],
2067            &[OpType::Put, OpType::Put],
2068            &[30, 40],
2069        );
2070
2071        divider.push(batch1);
2072        let series_batch = divider.push(batch2).unwrap();
2073        assert_eq!(series_batch.batches.len(), 1);
2074
2075        assert_eq!(divider.buffer.batches.len(), 1);
2076    }
2077
2078    #[test]
2079    fn test_series_boundary_within_batch() {
2080        let mut divider = FlatSeriesBatchDivider::default();
2081
2082        let batch1 = new_test_record_batch(
2083            &[b"series1", b"series1"],
2084            &[1000, 2000],
2085            &[1, 2],
2086            &[OpType::Put, OpType::Put],
2087            &[10, 20],
2088        );
2089
2090        let batch2 = new_test_record_batch(
2091            &[b"series1", b"series2"],
2092            &[3000, 4000],
2093            &[3, 4],
2094            &[OpType::Put, OpType::Put],
2095            &[30, 40],
2096        );
2097
2098        divider.push(batch1);
2099        let series_batch = divider.push(batch2).unwrap();
2100        assert_eq!(series_batch.batches.len(), 2);
2101        assert_eq!(series_batch.batches[0].num_rows(), 2);
2102        assert_eq!(series_batch.batches[1].num_rows(), 1);
2103
2104        assert_eq!(divider.buffer.batches.len(), 1);
2105        assert_eq!(divider.buffer.batches[0].num_rows(), 1);
2106    }
2107
2108    #[test]
2109    fn test_series_splitting() {
2110        let mut divider = FlatSeriesBatchDivider::default();
2111
2112        let batch1 = new_test_record_batch(&[b"series1"], &[1000], &[1], &[OpType::Put], &[10]);
2113
2114        let batch2 = new_test_record_batch(
2115            &[b"series1", b"series2", b"series2", b"series3"],
2116            &[2000, 3000, 4000, 5000],
2117            &[2, 3, 4, 5],
2118            &[OpType::Put, OpType::Put, OpType::Put, OpType::Put],
2119            &[20, 30, 40, 50],
2120        );
2121
2122        divider.push(batch1);
2123        let series_batch = divider.push(batch2).unwrap();
2124        assert_eq!(series_batch.batches.len(), 2);
2125
2126        let total_rows: usize = series_batch.batches.iter().map(|b| b.num_rows()).sum();
2127        assert_eq!(total_rows, 2);
2128
2129        let final_batch = divider.finish().unwrap();
2130        assert_eq!(final_batch.batches.len(), 1);
2131        assert_eq!(final_batch.batches[0].num_rows(), 3);
2132    }
2133}