Skip to main content

mito2/read/series_scan/
prepared.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//! Scanner-wide columnar candidates and independent, lazy sample reads.
16
17mod narthex;
18#[cfg(test)]
19mod tests;
20
21use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
22use std::ops::Range;
23use std::sync::Arc;
24use std::time::Instant;
25
26use api::v1::SemanticType;
27use common_error::ext::BoxedError;
28use common_recordbatch::filter::SimpleFilterEvaluator;
29use datafusion::execution::memory_pool::{MemoryConsumer, MemoryPool, MemoryReservation};
30use datafusion_expr::{Expr, utils::split_conjunction};
31use datatypes::arrow::array::{
32    Array, ArrayRef, BinaryArray, BooleanArray, DictionaryArray, StringArray, UInt32Array,
33    UInt64Array,
34};
35use datatypes::arrow::buffer::{Buffer, OffsetBuffer};
36use datatypes::arrow::compute::{cast, filter_record_batch, max, min, take_record_batch};
37use datatypes::arrow::datatypes::{Schema, SchemaRef, UInt32Type};
38use datatypes::arrow::record_batch::RecordBatch;
39use datatypes::series::{SeriesLabelBatch, SeriesLabels, SeriesOrdering};
40use datatypes::value::{Value, ValueRef};
41use futures::TryStreamExt;
42use mito_codec::row_converter::SparsePrimaryKeyCodec;
43use snafu::{IntoError, ResultExt};
44use store_api::metric_engine_consts::{
45    DATA_SCHEMA_TABLE_ID_COLUMN_NAME, DATA_SCHEMA_TSID_COLUMN_NAME,
46};
47use store_api::region_engine::{
48    PartitionRange, PreparedSeriesSource, RawLabelSource, SendableRawSeriesStream, SeriesInfo,
49};
50use store_api::storage::SequenceRange;
51use store_api::storage::consts::{ReservedColumnId, SEQUENCE_COLUMN_NAME};
52use table::predicate::Predicate;
53use tokio::sync::OnceCell;
54
55use crate::error::{
56    ComputeArrowSnafu, Error, InvalidRecordBatchSnafu, NewRecordBatchSnafu, Result,
57};
58use crate::read::BoxedRecordBatchStream;
59use crate::read::scan_region::StreamContext;
60use crate::read::scan_util::PartitionMetrics;
61use crate::read::seq_scan::SeqScan;
62use crate::read::series_scan::{RawScanPreparation, raw};
63use crate::read::stream::ScanBatch;
64use crate::series_index::format::{
65    self, FormatReader, SamplesBatch, SamplesFormatReader, SamplesReadRequest, SeriesReadRequest,
66};
67use crate::series_index::identity::ExactSeriesKey;
68use crate::series_index::{MetricSeriesId, ROW_COUNT_COLUMN};
69use crate::sst::file::{FileTimeRange, WindowSequence};
70
71fn invalid(reason: impl Into<String>) -> Error {
72    InvalidRecordBatchSnafu {
73        reason: reason.into(),
74    }
75    .build()
76}
77
78/// Errors are shared too: a failed execution must not restart discovery in another partition.
79#[derive(Default)]
80pub(crate) struct Preparation {
81    source: OnceCell<std::result::Result<Arc<ColumnarPreparedSource>, Arc<Error>>>,
82}
83
84impl Preparation {
85    pub(crate) async fn prepare_batches(
86        &self,
87        context: Arc<StreamContext>,
88        ranges: Vec<PartitionRange>,
89        metrics: PartitionMetrics,
90        scan_pool: Arc<dyn MemoryPool>,
91    ) -> Result<Arc<ColumnarPreparedSource>> {
92        let result = self
93            .source
94            .get_or_init(|| async {
95                let raw = RawScanPreparation {
96                    schema: Arc::new(datatypes::series::samples::SeriesSchema {
97                        fields: Vec::new().into(),
98                        eval_grid: None,
99                    }),
100                    fields: Vec::new(),
101                    predicates: Vec::new(),
102                };
103                ColumnarPreparedSource::prepare(
104                    context,
105                    ranges,
106                    RawLabelSource::Explicit,
107                    raw,
108                    metrics,
109                    scan_pool,
110                )
111                .await
112                .map(Arc::new)
113                .map_err(Arc::new)
114            })
115            .await;
116        let source = result
117            .as_ref()
118            .map_err(|error| crate::error::ScanSeriesSnafu.into_error(error.clone()))?;
119        if !matches!(source.labels, RawLabelSource::Explicit) {
120            return Err(invalid("cannot change prepared output representation"));
121        }
122        Ok(source.clone())
123    }
124
125    pub(crate) async fn prepare(
126        &self,
127        context: Arc<StreamContext>,
128        ranges: Vec<PartitionRange>,
129        labels: RawLabelSource,
130        raw: RawScanPreparation,
131        metrics: PartitionMetrics,
132        scan_pool: Arc<dyn MemoryPool>,
133    ) -> std::result::Result<Arc<dyn PreparedSeriesSource>, BoxedError> {
134        // Per caller, including time awaiting another partition's shared preparation.
135        // This overlaps prepare_wall and must not be added to its component timings.
136        let acquire_timer = crate::metrics::READ_STAGE_ELAPSED
137            .with_label_values(&["columnar_prepare_acquire_wall"])
138            .start_timer();
139        let expected = labels.clone();
140        let result = self
141            .source
142            .get_or_init(|| async {
143                ColumnarPreparedSource::prepare(context, ranges, labels, raw, metrics, scan_pool)
144                    .await
145                    .map(Arc::new)
146                    .map_err(Arc::new)
147            })
148            .await;
149        drop(acquire_timer);
150        let source = result.as_ref().map_err(|error| {
151            BoxedError::new(crate::error::ScanSeriesSnafu.into_error(error.clone()))
152        })?;
153        if !same_labels(&source.labels, &expected) {
154            return Err(BoxedError::new(invalid(
155                "label binding changed after series preparation",
156            )));
157        }
158        Ok(source.clone())
159    }
160}
161
162pub(super) fn same_labels(left: &RawLabelSource, right: &RawLabelSource) -> bool {
163    match (left, right) {
164        (
165            RawLabelSource::PrimaryKey {
166                metric_name: a,
167                physical_metadata: am,
168                logical_tags: at,
169            },
170            RawLabelSource::PrimaryKey {
171                metric_name: b,
172                physical_metadata: bm,
173                logical_tags: bt,
174            },
175        ) => {
176            a == b
177                && Arc::ptr_eq(am, bm)
178                && at.len() == bt.len()
179                && at
180                    .iter()
181                    .zip(bt.iter())
182                    .all(|(a, b)| a.column_id == b.column_id && a.name == b.name)
183        }
184        _ => false,
185    }
186}
187
188/// Pushes the supported conjuncts into the request.
189///
190/// The second element reports, for every input conjunct, whether `ColumnarReader`
191/// applies it exactly, so callers must not evaluate those conjuncts again.
192fn series_read_request(schema: &Schema, conjuncts: &[&Expr]) -> (SeriesReadRequest, Vec<bool>) {
193    let mut request = SeriesReadRequest {
194        projection: schema
195            .fields()
196            .iter()
197            .filter(|field| field.name() != ROW_COUNT_COLUMN)
198            .map(|field| field.name().clone())
199            .collect(),
200        ..Default::default()
201    };
202    let mut accepted = Vec::with_capacity(conjuncts.len());
203    let mut predicates = Vec::new();
204    for expr in conjuncts {
205        let Some(filter) = SimpleFilterEvaluator::try_new_with_column_type(expr, &|name| {
206            schema
207                .field_with_name(name)
208                .ok()
209                .map(|field| field.data_type().clone())
210        }) else {
211            accepted.push(false);
212            continue;
213        };
214        if !request
215            .projection
216            .iter()
217            .any(|name| name == filter.column_name())
218        {
219            accepted.push(false);
220            continue;
221        }
222        if filter.column_name() == DATA_SCHEMA_TABLE_ID_COLUMN_NAME
223            && filter.is_eq()
224            && let Some(Value::UInt32(table_id)) = filter.literal_value()
225        {
226            // Keep all equality filters, including contradictory ones, for exact evaluation.
227            request.table_id = Some(table_id);
228        }
229        predicates.push((*expr).clone());
230        request.filters.push(filter);
231        accepted.push(true);
232    }
233    request.filter_exprs = predicates.into();
234    (request, accepted)
235}
236
237/// Flattens the scanner predicate into the conjuncts shared by pushdown and residual filters.
238fn predicate_conjuncts(predicate: Option<&Predicate>) -> Vec<&Expr> {
239    predicate
240        .into_iter()
241        .flat_map(|predicate| predicate.exprs())
242        .flat_map(split_conjunction)
243        .collect()
244}
245
246struct Candidate {
247    /// Coarse prefix of the exact key; only a hash, never identity.
248    id: MetricSeriesId,
249    /// The canonical sparse key: the identity every comparison, sample attribution and output
250    /// chunk uses. It must not be qualified by region: every region holding a fragment of one
251    /// series has to report the same identity, or the fragments never meet in one owner above
252    /// the regions.
253    key: Buffer,
254    tags: HashMap<u32, Option<String>>,
255    metric: Option<SeriesLabels>,
256}
257
258pub(crate) struct ColumnarPreparedSource {
259    context: Arc<StreamContext>,
260    labels: RawLabelSource,
261    raw: Arc<RawScanPreparation>,
262    sample_schema: Option<SchemaRef>,
263    merge_field_start: usize,
264    // Append-mode Narthex raw reads still require one row per series/timestamp.
265    dedup_append_raw: bool,
266    sample_partition: Option<Arc<SamplePartitionFilter>>,
267    candidates: Arc<Vec<Candidate>>,
268    samples: Arc<Vec<Arc<dyn SamplesFormatReader>>>,
269    metrics: PartitionMetrics,
270    scan_pool: Arc<dyn MemoryPool>,
271    // Readers retain this reservation with the candidate set.
272    reservation: Arc<MemoryReservation>,
273}
274
275/// Only Narthex index readers carry a coverage window. A failed index read can
276/// schedule discovery from the corresponding pinned samples once per scan.
277#[derive(Default)]
278pub(crate) struct SeriesDiscovery {
279    readers: VecDeque<(Box<dyn FormatReader>, Option<WindowSequence>)>,
280    covered_samples: Vec<(FileTimeRange, usize)>,
281}
282
283impl ColumnarPreparedSource {
284    async fn prepare(
285        context: Arc<StreamContext>,
286        ranges: Vec<PartitionRange>,
287        labels: RawLabelSource,
288        raw: RawScanPreparation,
289        metrics: PartitionMetrics,
290        scan_pool: Arc<dyn MemoryPool>,
291    ) -> Result<Self> {
292        let _prepare_timer = crate::metrics::READ_STAGE_ELAPSED
293            .with_label_values(&["columnar_prepare_wall"])
294            .start_timer();
295        let mut preparation_metrics = crate::metrics::ColumnarReadMetrics::default();
296        preparation_metrics.counts.insert("prepare_executions", 1);
297        let started = Instant::now();
298        let input = &context.input;
299        let metadata = input.region_metadata();
300        let (samples, mut series) = narthex::open_sources(&context, &ranges, &scan_pool).await?;
301        preparation_metrics.add_elapsed("columnar_prepare_coverage", started.elapsed());
302        preparation_metrics
303            .counts
304            .insert("prepare_sample_readers", samples.len() as u64);
305        preparation_metrics
306            .counts
307            .insert("prepare_series_indexes", series.readers.len() as u64);
308        let reservation = MemoryConsumer::new("ColumnarPreparedSource").register(&scan_pool);
309        let started = Instant::now();
310        let mut raw = raw;
311        let batch_output = matches!(labels, RawLabelSource::Explicit);
312        let dedup_append_raw = input.append_mode && !batch_output;
313        let sample_schema = if batch_output {
314            Some(input.mapper.input_arrow_schema(input.compaction))
315        } else {
316            sample_merge_schema(&context, &mut raw)?
317        };
318        // Sparse compaction omits tag columns, unlike the mapper's query batch.
319        // Derive the offset from the schema that actually reaches the dedup reader.
320        let merge_field_start = sample_schema.as_ref().map_or_else(
321            || input.mapper.field_column_start(),
322            |schema| {
323                schema
324                    .fields()
325                    .iter()
326                    .position(|field| {
327                        metadata
328                            .column_by_name(field.name())
329                            .is_some_and(|column| column.semantic_type == SemanticType::Field)
330                    })
331                    .unwrap_or(0)
332            },
333        );
334        preparation_metrics.add_elapsed("columnar_prepare_schema", started.elapsed());
335        preparation_metrics.bytes.insert("prepare_encoded_keys", 0);
336        preparation_metrics.counts.insert("prepare_batch_series", 0);
337        let direct_labels = !batch_output && sample_schema.is_some();
338        let conjuncts = predicate_conjuncts(input.predicate_group().predicate());
339        let partition = narthex_partition_filter(metadata.partition_expr.as_deref(), None)?;
340        // Series rows carry tags only, so a rule over any other column, such as the time index,
341        // filters sample rows instead.
342        let (series_partition, sample_partition) = match partition {
343            Some(rule) if partition_on_tags_only(&rule, metadata) => (Some(rule), None),
344            Some(rule) => (None, Some(SamplePartitionFilter::try_new(&rule, metadata)?)),
345            None => (None, None),
346        };
347        let mut retained_rows = 0_usize;
348        let mut candidates = BTreeMap::<ExactSeriesKey, Candidate>::new();
349        while let Some((reader, window)) = series.readers.pop_front() {
350            let started = Instant::now();
351            let schema = reader.schema();
352            format::validate_series_schema(&schema, metadata)?;
353            let mut tags = schema
354                .fields()
355                .iter()
356                .skip(3)
357                .map(|field| {
358                    let id = format::field_id(field)?;
359                    Ok((id, field.name().clone()))
360                })
361                .collect::<Result<Vec<_>>>()?;
362            tags.sort_unstable_by(|a, b| a.1.cmp(&b.1));
363            let (request, accepted) = series_read_request(&schema, &conjuncts);
364            let projection = request
365                .projection
366                .iter()
367                .map(|name| schema.index_of(name).map_err(|e| invalid(e.to_string())))
368                .collect::<Result<Vec<_>>>()?;
369            let projected_schema = Arc::new(
370                schema
371                    .project(&projection)
372                    .map_err(|e| invalid(e.to_string()))?,
373            );
374            let mut filters = Vec::new();
375            for (expr, accepted) in conjuncts.iter().zip(&accepted) {
376                // The reader already applied accepted conjuncts exactly.
377                if *accepted
378                    || !expr
379                        .column_refs()
380                        .iter()
381                        .all(|column| projected_schema.index_of(&column.name).is_ok())
382                {
383                    continue;
384                }
385                filters.push(
386                    Predicate::to_physical_expr(expr, &projected_schema)
387                        .map_err(|e| invalid(e.to_string()))?,
388                );
389            }
390            if let Some(partition) = &series_partition {
391                filters.push(
392                    partition
393                        .try_as_physical_expr(&projected_schema)
394                        .map_err(|error| invalid(error.to_string()))?,
395                );
396            }
397            preparation_metrics.add_elapsed("columnar_prepare_compile", started.elapsed());
398            let mut batches = reader.read(request)?;
399            loop {
400                let timer = preparation_metrics.timer("columnar_prepare_discovery_wall");
401                let batch = batches.try_next().await;
402                drop(timer);
403                let batch = match (batch, window) {
404                    (Ok(batch), _) => batch,
405                    (Err(error), Some(window)) => {
406                        common_telemetry::warn!(
407                            ?error,
408                            ?window,
409                            "Series index read failed, discovering keys from samples"
410                        );
411                        series.fallback_to_samples(window, &samples, metadata, &scan_pool)?;
412                        break;
413                    }
414                    (Err(error), None) => return Err(error),
415                };
416                let Some(mut batch) = batch else {
417                    break;
418                };
419                *preparation_metrics
420                    .counts
421                    .entry("prepare_discovered_rows")
422                    .or_default() += batch.num_rows() as u64;
423                *preparation_metrics
424                    .counts
425                    .entry("prepare_discovery_batches")
426                    .or_default() += 1;
427                let started = Instant::now();
428                for filter in &filters {
429                    batch = common_recordbatch::filter::batch_filter(&batch, filter)
430                        .map_err(|e| invalid(e.to_string()))?;
431                }
432                preparation_metrics.add_elapsed("columnar_prepare_residual", started.elapsed());
433                *preparation_metrics
434                    .counts
435                    .entry("prepare_selected_rows")
436                    .or_default() += batch.num_rows() as u64;
437                let started = Instant::now();
438                let mut duplicate_rows = 0_u64;
439                let table = batch
440                    .column_by_name(DATA_SCHEMA_TABLE_ID_COLUMN_NAME)
441                    .ok_or_else(|| invalid("missing table ID column"))?
442                    .as_any()
443                    .downcast_ref::<UInt32Array>()
444                    .ok_or_else(|| invalid("invalid table ID column"))?;
445                let tsid = batch
446                    .column_by_name(DATA_SCHEMA_TSID_COLUMN_NAME)
447                    .ok_or_else(|| invalid("missing TSID column"))?
448                    .as_any()
449                    .downcast_ref::<UInt64Array>()
450                    .ok_or_else(|| invalid("invalid TSID column"))?;
451                let tag_arrays = tags
452                    .iter()
453                    .map(|(id, name)| {
454                        let strings = batch
455                            .column_by_name(name)
456                            .ok_or_else(|| invalid("missing series tag column"))?
457                            .as_any()
458                            .downcast_ref::<StringArray>()
459                            .ok_or_else(|| invalid("invalid series tag array"))?;
460                        Ok((*id, strings))
461                    })
462                    .collect::<Result<Vec<_>>>()?;
463                // Identity is the exact canonical sparse key. `tsid` is a hash, so rows
464                // that differ only in labels are different series and must both survive:
465                // re-encoding the artifact's own tags reproduces the SST key byte for byte.
466                let codec = SparsePrimaryKeyCodec::schemaless();
467                let mut offsets = mito_codec::row_converter::SparseOffsetsCache::new();
468                let mut identity = Vec::new();
469                let mut previous: Option<Vec<u8>> = None;
470                let mut fresh = Vec::<(ExactSeriesKey, usize)>::new();
471                let mut encoded_key_bytes = 0_u64;
472                for row in 0..batch.num_rows() {
473                    identity.clear();
474                    codec
475                        .encode_internal(table.value(row), tsid.value(row), &mut identity)
476                        .map_err(|e| invalid(e.to_string()))?;
477                    codec
478                        .encode_to_vec(
479                            tag_arrays.iter().map(|(id, strings)| {
480                                (
481                                    *id,
482                                    if strings.is_null(row) {
483                                        ValueRef::Null
484                                    } else {
485                                        ValueRef::String(strings.value(row))
486                                    },
487                                )
488                            }),
489                            &mut identity,
490                        )
491                        .map_err(|e| invalid(e.to_string()))?;
492                    encoded_key_bytes += identity.len() as u64;
493                    // Adjacent duplicates are the common case and never allocate a key.
494                    if previous.as_deref() == Some(identity.as_slice())
495                        || candidates.contains_key(identity.as_slice())
496                    {
497                        duplicate_rows += 1;
498                        continue;
499                    }
500                    let key = ExactSeriesKey::from_sparse_key(&identity, &mut offsets)?;
501                    previous = Some(identity.clone());
502                    fresh.push((key, row));
503                }
504                // Retain only rows that introduce a new identity; the retained batch backs
505                // both explicit labels and the metadata rows of direct-label candidates.
506                let retained = if fresh.len() == batch.num_rows() {
507                    batch.clone()
508                } else {
509                    let selected: Vec<u64> = fresh.iter().map(|(_, row)| *row as u64).collect();
510                    take_record_batch(&batch, &UInt64Array::from(selected))
511                        .context(ComputeArrowSnafu)?
512                };
513                if direct_labels {
514                    // Only explicit-label chunks retain a batch to resolve labels from.
515                    retained_rows += retained.num_rows();
516                }
517                let label_batch = if direct_labels {
518                    let RawLabelSource::PrimaryKey { logical_tags, .. } = &labels else {
519                        return Err(invalid("expected bound labels"));
520                    };
521                    let columns = logical_tags
522                        .iter()
523                        .map(|tag| {
524                            let name = tags
525                                .iter()
526                                .find(|(id, _)| *id == tag.column_id)
527                                .ok_or_else(|| invalid("missing bound tag"))?;
528                            Ok((
529                                tag.name.clone(),
530                                retained
531                                    .schema()
532                                    .index_of(&name.1)
533                                    .map_err(|e| invalid(e.to_string()))?,
534                            ))
535                        })
536                        .collect::<Result<Vec<_>>>()?;
537                    let owner = Arc::new(
538                        MemoryConsumer::new("ColumnarSeriesLabelBatch").register(&scan_pool),
539                    );
540                    let label_batch =
541                        SeriesLabelBatch::try_new(retained.clone(), columns, owner.clone())
542                            .map_err(|e| invalid(e.to_string()))?;
543                    owner
544                        .try_grow(label_batch.estimated_size())
545                        .context(crate::error::ScanMemoryExhaustedSnafu)?;
546                    Some(Arc::new(label_batch))
547                } else {
548                    None
549                };
550                let mut tag_values = 0_u64;
551                let mut batch_series = 0_u64;
552                for (retained_row, (exact, row)) in fresh.into_iter().enumerate() {
553                    let mut values = HashMap::new();
554                    if !direct_labels && (!batch_output || !input.compaction) {
555                        values.reserve(tag_arrays.len());
556                        for (column_id, strings) in &tag_arrays {
557                            values.insert(
558                                *column_id,
559                                (!strings.is_null(row)).then(|| strings.value(row).to_owned()),
560                            );
561                        }
562                    } else if let Some(filter) = &sample_partition {
563                        for column_id in filter.tag_ids() {
564                            let (_, strings) =
565                                tag_arrays
566                                    .iter()
567                                    .find(|(id, _)| *id == column_id)
568                                    .ok_or_else(|| invalid("missing partition tag column"))?;
569                            values.insert(
570                                column_id,
571                                (!strings.is_null(row)).then(|| strings.value(row).to_owned()),
572                            );
573                        }
574                    }
575                    tag_values += values.len() as u64;
576                    let key = Buffer::from(exact.bytes().to_vec());
577                    let bytes = key.len()
578                        + values.values().flatten().map(String::len).sum::<usize>()
579                        + values.capacity() * (std::mem::size_of::<(u32, Option<String>)>() + 16)
580                        + std::mem::size_of::<Candidate>()
581                        + 64;
582                    reservation
583                        .try_grow(bytes)
584                        .context(crate::error::ScanMemoryExhaustedSnafu)?;
585                    let metric = if let Some(label_batch) = &label_batch {
586                        batch_series += 1;
587                        let RawLabelSource::PrimaryKey { metric_name, .. } = &labels else {
588                            return Err(invalid("expected bound labels"));
589                        };
590                        Some(
591                            SeriesLabels::from_batch(
592                                Some(metric_name.clone()),
593                                label_batch.clone(),
594                                retained_row,
595                            )
596                            .map_err(|e| invalid(e.to_string()))?,
597                        )
598                    } else {
599                        None
600                    };
601                    let id = exact.id();
602                    candidates.insert(
603                        exact,
604                        Candidate {
605                            id,
606                            key,
607                            tags: values,
608                            metric,
609                        },
610                    );
611                }
612                *preparation_metrics
613                    .bytes
614                    .entry("prepare_encoded_keys")
615                    .or_default() += encoded_key_bytes;
616                *preparation_metrics
617                    .counts
618                    .entry("prepare_tag_values")
619                    .or_default() += tag_values;
620                *preparation_metrics
621                    .counts
622                    .entry("prepare_duplicate_rows")
623                    .or_default() += duplicate_rows;
624                *preparation_metrics
625                    .counts
626                    .entry("prepare_batch_series")
627                    .or_default() += batch_series;
628                preparation_metrics.add_elapsed("columnar_prepare_candidates", started.elapsed());
629            }
630        }
631        let started = Instant::now();
632        preparation_metrics
633            .counts
634            .insert("prepare_unique_series", candidates.len() as u64);
635        preparation_metrics
636            .counts
637            .insert("prepare_retained_rows", retained_rows as u64);
638        let mut candidates: Vec<_> = candidates.into_values().collect();
639        candidates.sort_unstable_by(|a, b| a.key.as_slice().cmp(b.key.as_slice()));
640        preparation_metrics.add_elapsed("columnar_prepare_sort", started.elapsed());
641        Ok(Self {
642            context,
643            labels,
644            raw: Arc::new(raw),
645            sample_schema,
646            merge_field_start,
647            dedup_append_raw,
648            sample_partition: sample_partition.map(Arc::new),
649            candidates: Arc::new(candidates),
650            samples: Arc::new(samples),
651            metrics,
652            scan_pool,
653            reservation: Arc::new(reservation),
654        })
655    }
656}
657
658impl ColumnarPreparedSource {
659    pub(crate) fn read_batches(&self, range: Range<usize>) -> Result<BoxedRecordBatchStream> {
660        if range.start > range.end || range.end > self.candidates.len() {
661            return Err(invalid("series range out of bounds"));
662        }
663        let context = self.context.clone();
664        let sample_schema = self.sample_schema.clone();
665        let candidates = self.candidates.clone();
666        let samples = self.samples.clone();
667        let metrics = self.metrics.clone();
668        let reservation = self.reservation.clone();
669        let scan_pool = self.scan_pool.clone();
670        let field_column_start = self.merge_field_start;
671        let dedup_append_raw = self.dedup_append_raw;
672        let sample_partition = self.sample_partition.clone();
673        // Time-only conjuncts drop every version of a (series, time) key alike, so they
674        // commute with dedup and must run before the merge: a row selector inside the
675        // merge would otherwise pick a row they reject. Other conjuncts may depend on
676        // which version dedup keeps and stay after the merge. Volatile conjuncts never get
677        // here: DataFusion's `PushDownFilter` keeps them in the `Filter` above the scan.
678        let mut time_filters = Vec::new();
679        let mut filters = Vec::new();
680        if matches!(self.labels, RawLabelSource::Explicit) && !context.input.compaction {
681            // Batch output keeps this schema before and after the merge.
682            let schema = context.input.mapper.input_arrow_schema(false);
683            let time_index = &context
684                .input
685                .region_metadata()
686                .time_index_column()
687                .column_schema
688                .name;
689            for expr in predicate_conjuncts(context.input.predicate_group().predicate()) {
690                let filter = Predicate::to_physical_expr(expr, &schema)
691                    .map_err(|error| invalid(error.to_string()))?;
692                if expr
693                    .column_refs()
694                    .iter()
695                    .all(|column| &column.name == time_index)
696                {
697                    time_filters.push(filter);
698                } else {
699                    filters.push(filter);
700                }
701            }
702        }
703        let time_filters = Arc::new(time_filters);
704        let stream = async_stream::try_stream! {
705            let _reservation = reservation;
706            if range.is_empty() { return; }
707            let mut sources = Vec::<BoxedRecordBatchStream>::new();
708            for reader in samples.iter() {
709                let candidates = candidates.clone();
710                let range = range.clone();
711                let context = context.clone();
712                let reader = reader.clone();
713                let sample_schema = sample_schema.clone();
714                let scan_pool = scan_pool.clone();
715                let sample_partition = sample_partition.clone();
716                let time_filters = time_filters.clone();
717                sources.push(Box::pin(async_stream::try_stream! {
718                    let reservation = MemoryConsumer::new("ColumnarSamplesRead").register(&scan_pool);
719                    // Account for the selection retained by the samples reader, including
720                    // B-tree node overhead, before allocating it. The exact-key selection and
721                    // the coarse identifiers the reader derives from it both live for the
722                    // lifetime of the sample stream.
723                    let selection_bytes = candidates[range.clone()]
724                        .iter()
725                        .map(|candidate| {
726                            std::mem::size_of::<ExactSeriesKey>()
727                                + candidate.key.len()
728                                + std::mem::size_of::<MetricSeriesId>()
729                                + 64
730                        })
731                        .sum::<usize>();
732                    reservation.try_grow(selection_bytes).context(crate::error::ScanMemoryExhaustedSnafu)?;
733                    // Exact ownership: a block is read only when its own key is selected,
734                    // never because a colliding partner shares the identifier. Coarse
735                    // pruning bounds are derived from these keys inside the reader.
736                    // The keys are built from the one key the candidate retains, so the
737                    // selection costs one owned copy per series rather than a second copy
738                    // alongside every candidate.
739                    let mut offsets = mito_codec::row_converter::SparseOffsetsCache::new();
740                    let keys = candidates[range.clone()]
741                        .iter()
742                        .map(|c| ExactSeriesKey::from_sparse_key(c.key.as_slice(), &mut offsets))
743                        .collect::<Result<BTreeSet<_>>>()?;
744                    let mut stage_metrics = crate::metrics::ColumnarReadMetrics::default();
745                    let schema = reader.schema();
746                    let metadata = context.input.region_metadata();
747                    let name = &metadata.time_index_column().column_schema.name;
748                    let field = schema.field_with_name(name).map_err(|err| invalid(err.to_string()))?;
749                    let unit = match field.data_type() {
750                        datatypes::arrow::datatypes::DataType::Timestamp(unit, _) => Ok(common_time::timestamp::TimeUnit::from(unit)),
751                        _ => Err(invalid(format!("sample time index {name} must be a timestamp"))),
752                    }?;
753                    let bounds = context.input.time_range.as_ref();
754                    let start = bounds.and_then(|r| *r.start()).and_then(|t| t.convert_to_ceil(unit)).map(|t| t.value());
755                    let end = bounds.and_then(|r| *r.end()).and_then(|t| t.convert_to_ceil(unit)).map(|t| t.value());
756                    let mut batches = reader.read(SamplesReadRequest {
757                        projection: sample_projection(&schema, &context),
758                        memory_pool: Some(scan_pool.clone()),
759                        keys: Some(keys),
760                        start,
761                        end,
762                        ..Default::default()
763                    })?;
764                    while let Some(samples) = batches.try_next().await? {
765                        // A block belongs to exactly one series, so the reader returns its
766                        // exact key once and the whole batch is attributed at once.
767                        let SamplesBatch { batch, key } = samples;
768                        let ordinal = candidates[range.clone()]
769                            .binary_search_by(|candidate| {
770                                candidate.key.as_slice().cmp(key.bytes())
771                            })
772                            .map_err(|_| invalid("sample contains an unselected series"))?
773                            + range.start;
774                        let started = std::time::Instant::now();
775                        let flat = sample_to_flat(batch, &candidates[ordinal], &context, sample_schema.as_ref())?;
776                        let flat = match &sample_partition {
777                            Some(filter) => filter.filter(flat, &candidates[ordinal])?,
778                            None => flat,
779                        };
780                        let mut flat = filter_visibility(flat, &context)?;
781                        for filter in time_filters.iter() {
782                            flat = common_recordbatch::filter::batch_filter(&flat, filter)
783                                .map_err(|error| invalid(error.to_string()))?;
784                        }
785                        stage_metrics.add_elapsed("columnar_sample_adapt", started.elapsed());
786                        if flat.num_rows() == 0 { continue; }
787                        let bytes = flat.get_array_memory_size();
788                        reservation.try_grow(bytes).context(crate::error::ScanMemoryExhaustedSnafu)?;
789                        yield flat;
790                        reservation.shrink(bytes);
791                    }
792                }));
793            }
794            let mut merged = if let Some(schema) = sample_schema {
795                SeqScan::merge_flat_sources(&context, sources, Some(&metrics), false, schema, field_column_start).await?
796            } else {
797                SeqScan::build_flat_reader_from_sources(&context, sources, None, Some(&metrics), false, 1).await?
798            };
799            // Append mode skips dedup in the merge reader, but raw series reads
800            // require unique timestamps. Non-append reads use the configured merge
801            // mode above; batch reads retain append semantics.
802            if dedup_append_raw {
803                merged = Box::pin(crate::read::flat_dedup::FlatDedupReader::new(
804                    merged,
805                    crate::read::flat_dedup::FlatLastRow::new(context.input.filter_deleted),
806                    Some(metrics.dedup_metrics_reporter()),
807                ).into_stream());
808            }
809            while let Some(mut batch) = merged.try_next().await? {
810                for filter in &filters {
811                    batch = common_recordbatch::filter::batch_filter(&batch, filter)
812                        .map_err(|error| invalid(error.to_string()))?;
813                }
814                if batch.num_rows() > 0 {
815                    yield batch;
816                }
817            }
818        };
819        Ok(Box::pin(stream))
820    }
821}
822
823impl PreparedSeriesSource for ColumnarPreparedSource {
824    fn num_series(&self) -> usize {
825        self.candidates.len()
826    }
827    fn label_source(&self) -> &RawLabelSource {
828        &self.labels
829    }
830    fn series_info(&self, ordinal: usize) -> std::result::Result<SeriesInfo, BoxedError> {
831        let candidate = self
832            .candidates
833            .get(ordinal)
834            .ok_or_else(|| BoxedError::new(invalid("series ordinal out of bounds")))?;
835        Ok(SeriesInfo {
836            primary_key: candidate.key.clone(),
837            metric: candidate.metric.clone(),
838        })
839    }
840    fn read_series(
841        &self,
842        range: Range<usize>,
843    ) -> std::result::Result<SendableRawSeriesStream, BoxedError> {
844        let mut batches = self.read_batches(range).map_err(BoxedError::new)?;
845        let stream = async_stream::try_stream! {
846            while let Some(batch) = batches.try_next().await? {
847                yield ScanBatch::RecordBatch(batch);
848            }
849        };
850        let stream = raw::make_stream(
851            Box::pin(stream),
852            self.raw.schema.clone(),
853            self.labels.clone(),
854            self.raw.fields.clone(),
855            self.metrics.clone(),
856            self.raw.predicates.clone(),
857            SeriesOrdering::KeyThenTime,
858            // The narthex preparation already collapsed an append-mode tie, and a sidecar
859            // preparation is served without that step, so the raw stream repeats the collapse
860            // for whichever source answered.
861            self.context.input.append_mode,
862        );
863        if self.sample_schema.is_none() {
864            return Ok(stream);
865        }
866        let candidates = self.candidates.clone();
867        let reservation = self.reservation.clone();
868        Ok(raw::with_series_labels(stream, move |key| {
869            // The resolver can outlive the exhausted sample stream.
870            let _reservation = &reservation;
871            let ordinal = candidates
872                .binary_search_by(|candidate| candidate.key.as_slice().cmp(key.as_slice()))
873                .map_err(|_| BoxedError::new(invalid("unknown merged series identity")))?;
874            Ok((
875                candidates[ordinal].key.clone(),
876                candidates[ordinal]
877                    .metric
878                    .clone()
879                    .ok_or_else(|| BoxedError::new(invalid("identity merge is missing labels")))?,
880            ))
881        }))
882    }
883}
884
885/// Omits tags only when every predicate is enforced either on the series index
886/// or on sample columns. Conjunctions can be separated; mixed disjunctions
887/// retain the ordinary flat adapter.
888pub(crate) fn sample_merge_schema(
889    context: &StreamContext,
890    raw: &mut RawScanPreparation,
891) -> Result<Option<SchemaRef>> {
892    let metadata = context.input.region_metadata();
893    let full = context.input.mapper.input_arrow_schema(false);
894    let projection: Vec<_> = full
895        .fields()
896        .iter()
897        .enumerate()
898        .filter_map(|(i, field)| {
899            let tag = metadata
900                .column_by_name(field.name())
901                .is_some_and(|column| column.semantic_type == SemanticType::Tag);
902            (!tag).then_some(i)
903        })
904        .collect();
905    let schema = Arc::new(full.project(&projection).context(ComputeArrowSnafu)?);
906    let mut predicates = Vec::new();
907    if let Some(predicate) = context.input.predicate_group().predicate() {
908        for expr in predicate.exprs().iter().flat_map(split_conjunction) {
909            let columns = expr.column_refs();
910            if columns.iter().all(|column| {
911                metadata
912                    .column_by_name(&column.name)
913                    .is_some_and(|column| column.semantic_type == SemanticType::Tag)
914            }) {
915                // prepare() applies this complete expression to every series-index batch.
916                continue;
917            }
918            if !columns
919                .iter()
920                .all(|column| schema.index_of(&column.name).is_ok())
921            {
922                return Ok(None);
923            }
924            predicates.push(
925                Predicate::to_physical_expr(expr, &schema).map_err(|e| invalid(e.to_string()))?,
926            );
927        }
928    }
929    let fields = raw
930        .fields
931        .iter()
932        .map(|(index, data_type)| {
933            projection
934                .iter()
935                .position(|old| old == index)
936                .map(|index| (index, data_type.clone()))
937                .ok_or_else(|| invalid("sample merge is missing a selected field"))
938        })
939        .collect::<Result<Vec<_>>>()?;
940    raw.fields = fields;
941    raw.predicates = predicates;
942    Ok(Some(schema))
943}
944
945fn sample_to_flat(
946    batch: RecordBatch,
947    candidate: &Candidate,
948    context: &StreamContext,
949    sample_schema: Option<&SchemaRef>,
950) -> Result<RecordBatch> {
951    let schema = sample_schema
952        .cloned()
953        .unwrap_or_else(|| context.input.mapper.input_arrow_schema(false));
954    let key = &candidate.key;
955    let metadata = context.input.region_metadata();
956    let mut arrays = Vec::<ArrayRef>::new();
957    for field in schema.fields() {
958        let array: ArrayRef = match field.name().as_str() {
959            "__primary_key" => Arc::new(
960                DictionaryArray::<UInt32Type>::try_new(
961                    UInt32Array::from(vec![0; batch.num_rows()]),
962                    Arc::new(BinaryArray::new(
963                        OffsetBuffer::new(
964                            vec![
965                                0,
966                                i32::try_from(key.len()).map_err(|_| {
967                                    invalid("series key exceeds Arrow offset limit")
968                                })?,
969                            ]
970                            .into(),
971                        ),
972                        key.clone(),
973                        None,
974                    )),
975                )
976                .context(ComputeArrowSnafu)?,
977            ),
978            "__sequence" | "__op_type" => batch
979                .column_by_name(field.name())
980                .ok_or_else(|| invalid("missing sample internal column"))?
981                .clone(),
982            name => {
983                let column = metadata
984                    .column_by_name(name)
985                    .ok_or_else(|| invalid("unknown flat column"))?;
986                if column.semantic_type == SemanticType::Tag {
987                    if column.column_id == ReservedColumnId::table_id() {
988                        Arc::new(UInt32Array::from(vec![
989                            candidate.id.table_id;
990                            batch.num_rows()
991                        ]))
992                    } else if column.column_id == ReservedColumnId::tsid() {
993                        Arc::new(UInt64Array::from(vec![candidate.id.tsid; batch.num_rows()]))
994                    } else {
995                        let value = candidate
996                            .tags
997                            .get(&column.column_id)
998                            .ok_or_else(|| invalid("missing series tag"))?;
999                        Arc::new(StringArray::from(vec![value.as_deref(); batch.num_rows()]))
1000                    }
1001                } else {
1002                    match batch.column_by_name(name) {
1003                        Some(array) => array.clone(),
1004                        None if field.is_nullable() => datatypes::arrow::array::new_null_array(
1005                            field.data_type(),
1006                            batch.num_rows(),
1007                        ),
1008                        None => return Err(invalid("missing non-null sample field")),
1009                    }
1010                }
1011            }
1012        };
1013        arrays.push(if array.data_type() == field.data_type() {
1014            array
1015        } else {
1016            cast(&array, field.data_type()).context(ComputeArrowSnafu)?
1017        });
1018    }
1019    RecordBatch::try_new(schema, arrays).context(NewRecordBatchSnafu)
1020}
1021
1022fn filter_visibility(batch: RecordBatch, context: &StreamContext) -> Result<RecordBatch> {
1023    let sequence_column = batch
1024        .column_by_name(SEQUENCE_COLUMN_NAME)
1025        .ok_or_else(|| invalid("missing sequence column __sequence"))?;
1026    let sequence = sequence_column
1027        .as_any()
1028        .downcast_ref::<UInt64Array>()
1029        .ok_or_else(|| invalid("sequence column __sequence must be UInt64"))?;
1030    let metadata = context.input.region_metadata();
1031    let timestamp = &metadata.time_index_column().column_schema;
1032    let time_column = batch
1033        .column_by_name(&timestamp.name)
1034        .ok_or_else(|| invalid(format!("missing time index column {}", timestamp.name)))?;
1035    let unit = metadata.time_index_type().unit();
1036    let (time, actual_unit) = datatypes::timestamp::timestamp_array_to_primitive(time_column)
1037        .ok_or_else(|| {
1038            invalid(format!(
1039                "time index column {} must be a timestamp",
1040                timestamp.name
1041            ))
1042        })?;
1043    if common_time::timestamp::TimeUnit::from(actual_unit) != unit {
1044        return Err(invalid(format!(
1045            "time index column {} has unit {actual_unit:?}, expected {unit:?}",
1046            timestamp.name
1047        )));
1048    }
1049    // Bounds are computed from the actual arrays: sample metadata does not expose
1050    // sequence bounds here, and format-reader timestamps need not be sorted.
1051    if sequence.null_count() == 0 && time.null_count() == 0 {
1052        let needs_sequence_max = context.input.snapshot_sequence.is_some()
1053            || matches!(
1054                context.input.sequence_range,
1055                Some(SequenceRange::LtEq { .. } | SequenceRange::GtLtEq { .. })
1056            );
1057        let sequence_max = needs_sequence_max.then(|| max(sequence)).flatten();
1058        let snapshot_visible = context
1059            .input
1060            .snapshot_sequence
1061            .is_none_or(|bound| sequence_max.is_some_and(|value| value <= bound));
1062        let range_visible = context
1063            .input
1064            .sequence_range
1065            .is_none_or(|range| match range {
1066                SequenceRange::Gt { min: bound } => {
1067                    min(sequence).is_some_and(|value| value > bound)
1068                }
1069                SequenceRange::LtEq { max: bound } => {
1070                    sequence_max.is_some_and(|value| value <= bound)
1071                }
1072                SequenceRange::GtLtEq {
1073                    min: lower,
1074                    max: upper,
1075                } => {
1076                    sequence_max.is_some_and(|value| value <= upper)
1077                        && min(sequence).is_some_and(|value| value > lower)
1078                }
1079            });
1080        let time_visible = context.input.time_range.as_ref().is_none_or(|range| {
1081            min(&time).zip(max(&time)).is_some_and(|(lower, upper)| {
1082                range.contains(&common_time::Timestamp::new(lower, unit))
1083                    && range.contains(&common_time::Timestamp::new(upper, unit))
1084            })
1085        });
1086        if snapshot_visible && range_visible && time_visible {
1087            return Ok(batch);
1088        }
1089    }
1090    let sequence_filter = context
1091        .input
1092        .sequence_range
1093        .map(|range| range.filter(sequence_column))
1094        .transpose()
1095        .context(ComputeArrowSnafu)?;
1096    let filter = BooleanArray::from(
1097        (0..batch.num_rows())
1098            .map(|i| {
1099                !sequence.is_null(i)
1100                    && !time.is_null(i)
1101                    && context
1102                        .input
1103                        .snapshot_sequence
1104                        .is_none_or(|max| sequence.value(i) <= max)
1105                    && sequence_filter
1106                        .as_ref()
1107                        .is_none_or(|filter| filter.value(i))
1108                    && context.input.time_range.as_ref().is_none_or(|range| {
1109                        range.contains(&common_time::Timestamp::new(time.value(i), unit))
1110                    })
1111            })
1112            .collect::<Vec<_>>(),
1113    );
1114    filter_record_batch(&batch, &filter).context(ComputeArrowSnafu)
1115}
1116
1117/// The mapper includes projected and residual-filter columns. Identity/time and
1118/// merge visibility columns are always needed by the narthex source adapter. The exact
1119/// series key is not projected: the samples reader returns it once per batch.
1120fn sample_projection(
1121    schema: &datatypes::arrow::datatypes::Schema,
1122    context: &StreamContext,
1123) -> Vec<String> {
1124    let input = context.input.mapper.input_arrow_schema(false);
1125    schema
1126        .fields()
1127        .iter()
1128        .enumerate()
1129        .filter(|(index, field)| {
1130            field.name() != store_api::storage::consts::PRIMARY_KEY_COLUMN_NAME
1131                && (*index < 5 || input.index_of(field.name()).is_ok())
1132        })
1133        .map(|(_, field)| field.name().clone())
1134        .collect()
1135}
1136
1137/// Returns a partition rule only when metrics rows need filtering for this owner.
1138fn narthex_partition_filter(
1139    region_partition: Option<&str>,
1140    file_partition: Option<&partition::expr::PartitionExpr>,
1141) -> Result<Option<partition::expr::PartitionExpr>> {
1142    Ok(region_partition
1143        .map(|json| {
1144            partition::expr::PartitionExpr::from_json_str(json)
1145                .map_err(|error| invalid(error.to_string()))
1146        })
1147        .transpose()?
1148        .flatten()
1149        .filter(|partition| file_partition != Some(partition)))
1150}
1151
1152fn partition_on_tags_only(
1153    rule: &partition::expr::PartitionExpr,
1154    metadata: &store_api::metadata::RegionMetadata,
1155) -> bool {
1156    let mut columns = HashSet::new();
1157    rule.collect_column_names(&mut columns);
1158    columns.iter().all(|name| {
1159        metadata
1160            .column_by_name(name)
1161            .is_some_and(|column| column.semantic_type == SemanticType::Tag)
1162    })
1163}
1164
1165/// A region partition rule that references a column other than a tag, applied to sample rows.
1166///
1167/// Files shared after repartition can hold rows of other partitions, so the rule has to drop them
1168/// row by row; a series may own rows on both sides of the rule.
1169struct SamplePartitionFilter {
1170    /// The columns the rule references, typed as the region declares them.
1171    schema: SchemaRef,
1172    /// Where each schema field's values come from.
1173    inputs: Vec<PartitionInput>,
1174    expr: Arc<dyn datafusion::physical_plan::PhysicalExpr>,
1175}
1176
1177enum PartitionInput {
1178    /// Logical table ID of the series. Repartitioning a metric table may route on it, and the
1179    /// series index keeps it outside the tag columns.
1180    TableId,
1181    /// A tag column, by column ID, valued from the series.
1182    Tag(u32),
1183    /// A column the sample rows carry.
1184    Sample,
1185}
1186
1187impl SamplePartitionFilter {
1188    fn try_new(
1189        rule: &partition::expr::PartitionExpr,
1190        metadata: &store_api::metadata::RegionMetadata,
1191    ) -> Result<Self> {
1192        let mut names = HashSet::new();
1193        rule.collect_column_names(&mut names);
1194        let mut names = names.into_iter().collect::<Vec<_>>();
1195        names.sort_unstable();
1196        let mut fields = Vec::with_capacity(names.len());
1197        let mut inputs = Vec::with_capacity(names.len());
1198        for name in names {
1199            let column = metadata
1200                .column_by_name(&name)
1201                .ok_or_else(|| invalid(format!("unknown partition column {name}")))?;
1202            fields.push(datatypes::arrow::datatypes::Field::new(
1203                name,
1204                datatypes::data_type::DataType::as_arrow_type(&column.column_schema.data_type),
1205                true,
1206            ));
1207            inputs.push(if column.column_id == ReservedColumnId::table_id() {
1208                PartitionInput::TableId
1209            } else if column.semantic_type == SemanticType::Tag {
1210                PartitionInput::Tag(column.column_id)
1211            } else {
1212                PartitionInput::Sample
1213            });
1214        }
1215        let schema = Arc::new(Schema::new(fields));
1216        let expr = rule
1217            .try_as_physical_expr(&schema)
1218            .map_err(|error| invalid(error.to_string()))?;
1219        Ok(Self {
1220            schema,
1221            inputs,
1222            expr,
1223        })
1224    }
1225
1226    fn tag_ids(&self) -> impl Iterator<Item = u32> + '_ {
1227        self.inputs.iter().filter_map(|input| match input {
1228            PartitionInput::Tag(column_id) => Some(*column_id),
1229            _ => None,
1230        })
1231    }
1232
1233    /// Keeps the rows of `flat`, all of `candidate`, that the rule assigns to this region.
1234    fn filter(&self, flat: RecordBatch, candidate: &Candidate) -> Result<RecordBatch> {
1235        let rows = flat.num_rows();
1236        let columns = self
1237            .schema
1238            .fields()
1239            .iter()
1240            .zip(&self.inputs)
1241            .map(|(field, input)| match input {
1242                PartitionInput::TableId => {
1243                    Ok(Arc::new(UInt32Array::from(vec![candidate.id.table_id; rows])) as ArrayRef)
1244                }
1245                PartitionInput::Tag(column_id) => {
1246                    let value = candidate
1247                        .tags
1248                        .get(column_id)
1249                        .ok_or_else(|| invalid("missing partition tag"))?;
1250                    Ok(Arc::new(StringArray::from(vec![value.as_deref(); rows])) as ArrayRef)
1251                }
1252                PartitionInput::Sample => {
1253                    let array = flat
1254                        .column_by_name(field.name())
1255                        .ok_or_else(|| invalid("missing partition column in samples"))?;
1256                    if array.data_type() == field.data_type() {
1257                        Ok(array.clone())
1258                    } else {
1259                        cast(array, field.data_type()).context(ComputeArrowSnafu)
1260                    }
1261                }
1262            })
1263            .collect::<Result<Vec<_>>>()?;
1264        let columns = RecordBatch::try_new_with_options(
1265            self.schema.clone(),
1266            columns,
1267            &datatypes::arrow::record_batch::RecordBatchOptions::new().with_row_count(Some(rows)),
1268        )
1269        .context(NewRecordBatchSnafu)?;
1270        let mask = self
1271            .expr
1272            .evaluate(&columns)
1273            .and_then(|value| value.into_array(rows))
1274            .map_err(|error| invalid(error.to_string()))?;
1275        let mask = mask
1276            .as_any()
1277            .downcast_ref::<BooleanArray>()
1278            .ok_or_else(|| invalid("partition rule must evaluate to booleans"))?;
1279        filter_record_batch(&flat, mask).context(ComputeArrowSnafu)
1280    }
1281}
1282
1283/// Shares narthex discovery across partitions and assigns disjoint exact-series ranges.
1284pub(crate) fn scan_batches(
1285    preparation: Arc<Preparation>,
1286    context: Arc<StreamContext>,
1287    ranges: Vec<PartitionRange>,
1288    partition: usize,
1289    partitions: usize,
1290    metrics: PartitionMetrics,
1291    scan_pool: Arc<dyn MemoryPool>,
1292) -> crate::read::stream::ScanBatchStream {
1293    Box::pin(async_stream::try_stream! {
1294        let source = preparation.prepare_batches(context, ranges, metrics, scan_pool).await?;
1295        let n = source.candidates.len() as u128;
1296        let start = (n * partition as u128 / partitions as u128) as usize;
1297        let end = (n * (partition + 1) as u128 / partitions as u128) as usize;
1298        let mut stream = source.read_batches(start..end)?;
1299        while let Some(batch) = stream.try_next().await? {
1300            yield ScanBatch::RecordBatch(batch);
1301        }
1302    })
1303}