Skip to main content

mito2/read/scan_region/
aggr.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//! Answers aggregates of a scan from manifest and SST statistics instead of
16//! scanning SST rows. The preparation result, an exact answer or a split into
17//! exact and residual sources, does not depend on the aggregate; scalar COUNT
18//! is the only aggregate served so far.
19
20pub mod overlap;
21
22use std::sync::Arc;
23
24use common_telemetry::debug;
25use common_time::range::TimestampRange;
26use datafusion_common::ScalarValue;
27use datafusion_expr::{Expr, Operator};
28use datatypes::data_type::DataType;
29use datatypes::value::Value;
30use futures::future::BoxFuture;
31use futures::{FutureExt, StreamExt, TryStreamExt};
32use mito_codec::row_converter::{PrimaryKeyCodec, build_primary_key_codec};
33use parquet::file::metadata::ParquetMetaData;
34use store_api::codec::PrimaryKeyEncoding;
35use store_api::metadata::{ColumnMetadata, RegionMetadata};
36use store_api::storage::{ColumnId, ScanRequest};
37
38use crate::cache::CachedSstMeta;
39use crate::read::scan_region::aggr::overlap::{Extent, find_overlaps};
40use crate::read::scan_region::{ScanInput, request_preserves_rows};
41use crate::sst::file::FileHandle;
42use crate::sst::parquet::metadata::{
43    extract_primary_key_range, extract_time_range, has_deduped_sst_marker, has_only_puts,
44};
45
46/// Returns the exact number of rows the scan yields, or `None` if it cannot
47/// be proven. Non-append candidates use cached Parquet footers to prove
48/// file-local uniqueness and the absence of deletes.
49pub(crate) async fn prepare(input: &ScanInput, request: &ScanRequest) -> Option<usize> {
50    let classification = classify(input, request)?;
51    if input.append_mode && request.filters.is_empty() {
52        return Some(classification.exact_rows);
53    }
54    let check_keys =
55        classification.key_filter || (!input.append_mode && classification.exact.len() > 1);
56    let check_rows = !input.append_mode;
57    futures::stream::iter(classification.exact)
58        .map(|index| file_evidence(input, input.files[index].clone(), check_keys, check_rows))
59        .buffer_unordered(input.max_concurrent_scan_files.max(1))
60        .try_collect::<()>()
61        .await
62        .ok()?;
63    Some(classification.exact_rows)
64}
65
66fn time_bounds_match(file: &FileHandle, sst: &CachedSstMeta, time_id: ColumnId) -> bool {
67    let region = sst.region_metadata();
68    let time_index = region.time_index_column();
69    let (start, end) = file.time_range();
70    time_index.column_id == time_id
71        && extract_time_range(&sst.parquet_metadata(), time_index).is_some_and(|(min, max)| {
72            start.unit() == min.unit() && end.unit() == max.unit() && (start, end) == (min, max)
73        })
74}
75
76/// Proves the bounds and visible rows required for this exact candidate.
77fn file_evidence(
78    input: &ScanInput,
79    file: FileHandle,
80    check_keys: bool,
81    check_rows: bool,
82) -> BoxFuture<'static, Result<(), ()>> {
83    let time_id = input.region_metadata().time_index_column().column_id;
84    let reader = input
85        .access_layer
86        .read_sst(file.clone())
87        .cache(input.cache_strategy.clone());
88    async move {
89        let sst = reader.read_statistics().await.map_err(|e| {
90            debug!(
91                "Metadata count could not read footer of {}: {e:?}",
92                file.file_id()
93            );
94        })?;
95        let metadata = sst.parquet_metadata();
96        if !time_bounds_match(&file, &sst, time_id) {
97            return Err(());
98        }
99        if check_keys
100            && let Some(range) = file.raw_primary_key_range()
101            && extract_primary_key_range(&metadata, &sst.region_metadata()) != Some(range)
102        {
103            return Err(());
104        }
105        (!check_rows || footer_proves_visible_rows(&metadata, file.num_rows()))
106            .then_some(())
107            .ok_or(())
108    }
109    .boxed()
110}
111
112/// The footer and manifest must agree. Without the writer's uniqueness claim,
113/// only a single physical row is independently known to be unique.
114fn footer_proves_visible_rows(metadata: &ParquetMetaData, manifest_rows: usize) -> bool {
115    let footer = metadata.file_metadata();
116    let unique = manifest_rows == 1 || has_deduped_sst_marker(metadata);
117    unique
118        && usize::try_from(footer.num_rows()) == Ok(manifest_rows)
119        && metadata
120            .row_groups()
121            .iter()
122            .try_fold(0usize, |total, group| {
123                total.checked_add(usize::try_from(group.num_rows()).ok()?)
124            })
125            == Some(manifest_rows)
126        && has_only_puts(metadata.row_groups())
127}
128
129/// Files of one scan classified against its pinned read view.
130struct Classification {
131    /// Indexes into `ScanInput::files` whose rows are all yielded exactly once.
132    exact: Vec<usize>,
133    /// Sum of the manifest row counts of `exact`.
134    exact_rows: usize,
135    /// Whether the filter proof depends on key bounds.
136    key_filter: bool,
137}
138
139/// A file is an exact candidate if all of the following hold:
140/// - The query time range covers it and every other static filter holds for
141///   all of its rows (see [`AggrFilters`]).
142/// - Its manifest row count is known.
143/// - In a deduplicating region, no other file or memtable may hold a row with
144///   the same primary key and timestamp. A multi-row file needs a trusted
145///   dedup marker. The footer must still prove uniqueness and all-Put rows.
146///
147/// Returns `None` for scans whose visible rows can differ from the sources'
148/// rows for reasons other than the files themselves.
149fn classify(input: &ScanInput, request: &ScanRequest) -> Option<Classification> {
150    if !input.memtables.is_empty()
151        || !input.allows_exact_row_count()
152        || !request_preserves_rows(request)
153    {
154        return None;
155    }
156    let filters = AggrFilters::new(input.region_metadata(), &request.filters)?;
157    let range = input.time_range.as_ref()?;
158
159    let mut intersecting = Vec::new();
160    for (index, file) in input.files.iter().enumerate() {
161        let (start, end) = file.time_range();
162        if start > end {
163            return None;
164        }
165        if !range.intersects(&TimestampRange::new_inclusive(Some(start), Some(end))) {
166            continue;
167        }
168        let candidate = range.contains(&start)
169            && range.contains(&end)
170            // Zero is unknown in legacy manifests.
171            && file.num_rows() > 0
172            && (input.append_mode || file.num_rows() == 1 || file.dedup_marker_trusted())
173            && input.file_time_bounds_fit(file)
174            && (input.region_partition_expr.is_none() || input.should_skip_region_partition(file))
175            && filters.covers(file);
176        if !candidate {
177            return None;
178        }
179        intersecting.push(index);
180    }
181    if !input.append_mode && intersecting.len() > 1 {
182        let mapper = input.primary_key_mapper();
183        let extents: Vec<_> = intersecting
184            .iter()
185            .map(|&index| {
186                let file = &input.files[index];
187                Extent {
188                    time: file.time_range(),
189                    key: file.primary_key_range(mapper),
190                }
191            })
192            .collect();
193        if find_overlaps(&extents).contains(&true) {
194            return None;
195        }
196    }
197    let exact_rows = intersecting.iter().try_fold(0usize, |rows, &index| {
198        rows.checked_add(input.files[index].num_rows())
199    })?;
200    i64::try_from(exact_rows).ok()?;
201    Some(Classification {
202        exact: intersecting,
203        exact_rows,
204        key_filter: filters.codec.is_some(),
205    })
206}
207
208/// Static scan predicates a metadata count can absorb.
209struct AggrFilters {
210    /// Values the leftmost primary key column must equal.
211    leftmost_values: Vec<Value>,
212    codec: Option<Arc<dyn PrimaryKeyCodec>>,
213}
214
215impl AggrFilters {
216    /// Returns `None` if any conjunct is neither a time-index comparison nor an
217    /// equality between the leftmost primary key column and a literal.
218    fn new(metadata: &RegionMetadata, filters: &[Expr]) -> Option<Self> {
219        let time_index = &metadata.time_index_column().column_schema;
220        let time_type = time_index.data_type.as_arrow_type();
221        let mut conjuncts = Vec::new();
222        for expr in filters {
223            split_and(expr, &mut conjuncts);
224        }
225        let mut leftmost_values = Vec::new();
226        for expr in conjuncts {
227            if time_filter(expr, &time_index.name, &time_type) {
228                continue;
229            }
230            let column = &leftmost_primary_key(metadata)?.column_schema;
231            let value = eq_literal(expr, &column.name, &column.data_type.as_arrow_type())?;
232            leftmost_values.push(Value::try_from(value.clone()).ok()?);
233        }
234        let codec = (!leftmost_values.is_empty()).then(|| build_primary_key_codec(metadata));
235        Some(Self {
236            leftmost_values,
237            codec,
238        })
239    }
240
241    /// Whether the leftmost key equalities hold for every row of the file.
242    /// Keys are sorted memcomparable bytes, so when both bounds decode to the
243    /// same leftmost value, every key between them shares it.
244    fn covers(&self, file: &FileHandle) -> bool {
245        let Some(codec) = &self.codec else {
246            return true;
247        };
248        let Some((min, max)) = file.raw_primary_key_range() else {
249            return false;
250        };
251        match (codec.decode_leftmost(&min), codec.decode_leftmost(&max)) {
252            (Ok(Some(low)), Ok(Some(high))) => {
253                low == high && self.leftmost_values.iter().all(|value| *value == low)
254            }
255            _ => false,
256        }
257    }
258}
259
260/// The leftmost primary key column. Sparse keys are not supported yet.
261fn leftmost_primary_key(metadata: &RegionMetadata) -> Option<&ColumnMetadata> {
262    match metadata.primary_key_encoding {
263        PrimaryKeyEncoding::Sparse => None,
264        PrimaryKeyEncoding::Dense => metadata.primary_key_columns().next(),
265    }
266}
267
268fn split_and<'a>(expr: &'a Expr, out: &mut Vec<&'a Expr>) {
269    match expr {
270        Expr::BinaryExpr(binary) if binary.op == Operator::And => {
271            split_and(&binary.left, out);
272            split_and(&binary.right, out);
273        }
274        _ => out.push(expr),
275    }
276}
277
278/// Returns the literal of a non-null, same-type `column = literal` equality.
279fn eq_literal<'a>(
280    expr: &'a Expr,
281    name: &str,
282    data_type: &datatypes::arrow::datatypes::DataType,
283) -> Option<&'a ScalarValue> {
284    let Expr::BinaryExpr(binary) = expr else {
285        return None;
286    };
287    if binary.op != Operator::Eq {
288        return None;
289    }
290    let (column, value) = match (binary.left.as_ref(), binary.right.as_ref()) {
291        (Expr::Column(column), Expr::Literal(value, _))
292        | (Expr::Literal(value, _), Expr::Column(column)) => (column, value),
293        _ => return None,
294    };
295    // Arrow uses total ordering for floats. Decoded Values equate NaNs and
296    // both signs of zero, so those equalities cannot prove Arrow coverage.
297    if match value {
298        ScalarValue::Float32(Some(value)) => value.is_nan() || *value == 0.0,
299        ScalarValue::Float64(Some(value)) => value.is_nan() || *value == 0.0,
300        _ => false,
301    } {
302        return None;
303    }
304    (column.name == name && !value.is_null() && &value.data_type() == data_type).then_some(value)
305}
306
307fn time_filter(expr: &Expr, name: &str, data_type: &datatypes::arrow::datatypes::DataType) -> bool {
308    let Expr::BinaryExpr(binary) = expr else {
309        return false;
310    };
311    if binary.op == Operator::And {
312        return time_filter(&binary.left, name, data_type)
313            && time_filter(&binary.right, name, data_type);
314    }
315    if !matches!(
316        binary.op,
317        Operator::Eq | Operator::Lt | Operator::LtEq | Operator::Gt | Operator::GtEq
318    ) {
319        return false;
320    }
321    let (column, value) = match (binary.left.as_ref(), binary.right.as_ref()) {
322        (Expr::Column(column), Expr::Literal(value, _))
323        | (Expr::Literal(value, _), Expr::Column(column)) => (column, value),
324        _ => return false,
325    };
326    column.name == name && !value.is_null() && &value.data_type() == data_type
327}
328
329#[cfg(test)]
330mod tests {
331    use std::collections::HashSet;
332    use std::sync::{Arc, LazyLock, Mutex};
333
334    use bytes::Bytes;
335    use common_time::Timestamp;
336    use common_time::timestamp::TimeUnit;
337    use datafusion_expr::{col, lit};
338    use datatypes::value::ValueRef;
339    use mito_codec::row_converter::{DensePrimaryKeyCodec, PrimaryKeyCodecExt};
340    use store_api::storage::{FileId, RegionId};
341    use table::predicate::build_time_range_predicate;
342
343    use super::*;
344    use crate::read::flat_projection::FlatProjectionMapper;
345    use crate::read::scan_region::PredicateGroup;
346    use crate::sst::file::FileMeta;
347    use crate::test_util::memtable_util::metadata_with_primary_key;
348    use crate::test_util::new_noop_file_purger;
349    use crate::test_util::scheduler_util::SchedulerEnv;
350
351    /// Files whose `__op_type` statistics would show deletions. Unit tests
352    /// have no Parquet files; engine tests cover reading the statistics.
353    static WITH_DELETES: LazyLock<Mutex<HashSet<FileId>>> = LazyLock::new(Default::default);
354
355    fn file(start: i64, end: i64, rows: u64, no_deletes: bool) -> FileHandle {
356        let file_id = FileId::random();
357        if !no_deletes {
358            WITH_DELETES.lock().unwrap().insert(file_id);
359        }
360        FileHandle::new(
361            FileMeta {
362                region_id: RegionId::new(123, 456),
363                file_id,
364                num_rows: rows,
365                dedup_marker_trusted: true,
366                time_range: (
367                    Timestamp::new_millisecond(start),
368                    Timestamp::new_millisecond(end),
369                ),
370                ..Default::default()
371            },
372            new_noop_file_purger(),
373        )
374    }
375
376    /// A file without deletions whose primary keys span `min..=max` over `(k0, k1)`.
377    fn keyed_file(
378        start: i64,
379        end: i64,
380        rows: u64,
381        min: (&str, u32),
382        max: (&str, u32),
383    ) -> FileHandle {
384        let codec = DensePrimaryKeyCodec::new(&metadata_with_primary_key(vec![0, 1], false));
385        let encode = |(k0, k1): (&str, u32)| {
386            Bytes::from(
387                codec
388                    .encode([ValueRef::String(k0), ValueRef::UInt32(k1)].into_iter())
389                    .unwrap(),
390            )
391        };
392        FileHandle::new(
393            FileMeta {
394                region_id: RegionId::new(123, 456),
395                file_id: FileId::random(),
396                num_rows: rows,
397                dedup_marker_trusted: true,
398                time_range: (
399                    Timestamp::new_millisecond(start),
400                    Timestamp::new_millisecond(end),
401                ),
402                primary_key_min: Some(encode(min)),
403                primary_key_max: Some(encode(max)),
404                ..Default::default()
405            },
406            new_noop_file_purger(),
407        )
408    }
409
410    fn exact_count(input: &ScanInput, request: &ScanRequest) -> Option<usize> {
411        let classification = classify(input, request)?;
412        let deletes = WITH_DELETES.lock().unwrap();
413        classification
414            .exact
415            .iter()
416            .all(|&i| input.append_mode || !deletes.contains(&input.files[i].meta_ref().file_id))
417            .then_some(classification.exact_rows)
418    }
419
420    async fn input(files: Vec<FileHandle>, filters: &[Expr]) -> ScanInput {
421        let env = SchedulerEnv::new().await;
422        let metadata = Arc::new(metadata_with_primary_key(vec![0, 1], false));
423        let mapper = FlatProjectionMapper::new(&metadata, [0, 2, 3]).unwrap();
424        ScanInput::builder(env.access_layer.clone(), mapper)
425            .with_files(files)
426            .with_predicate(PredicateGroup::new(&metadata, filters).unwrap())
427            .with_time_range(Some(build_time_range_predicate(
428                "ts",
429                TimeUnit::Millisecond,
430                filters,
431            )))
432            .build()
433    }
434
435    #[tokio::test]
436    async fn test_metadata_aggr_requires_trusted_marker_for_non_append_multi_row_files() {
437        for (num_rows, append_mode, expected) in
438            [(2, false, None), (1, false, Some(1)), (2, true, Some(2))]
439        {
440            let file = FileHandle::new(
441                FileMeta {
442                    num_rows,
443                    dedup_marker_trusted: false,
444                    ..file(0, 0, num_rows, true).meta_ref().clone()
445                },
446                new_noop_file_purger(),
447            );
448            let mut input = input(vec![file], &[]).await;
449            input.append_mode = append_mode;
450            assert_eq!(exact_count(&input, &ScanRequest::default()), expected);
451        }
452    }
453
454    #[tokio::test]
455    async fn test_metadata_aggr_coverage_and_overlap() {
456        let ts = |v| lit(ScalarValue::TimestampMillisecond(Some(v), None));
457        for (filters, expected) in [
458            (vec![], Some(5)),
459            (vec![col("ts").lt(ts(20))], Some(3)),
460            (vec![col("ts").gt_eq(ts(20))], Some(2)),
461            (vec![col("ts").lt(ts(5))], None),
462            (vec![col("ts").gt(ts(30))], Some(0)),
463            (vec![col("ts").eq(ts(0)).or(col("ts").eq(ts(30)))], None),
464            (vec![col("ts").not_eq(ts(5))], None),
465            (vec![col("k0").eq(lit("x"))], None),
466        ] {
467            let input = input(vec![file(0, 10, 3, true), file(20, 30, 2, true)], &filters).await;
468            let request = ScanRequest {
469                filters,
470                metadata_aggr_hint: true,
471                ..Default::default()
472            };
473            // Deletion evidence comes from the test, see `WITH_DELETES`.
474            assert_eq!(exact_count(&input, &request), expected, "{request:?}");
475        }
476        for files in [
477            vec![file(0, 10, 3, true), file(10, 20, 2, true)],
478            vec![file(0, 10, 3, true), file(5, 8, 2, true)],
479            vec![file(0, 10, 3, false)],
480            vec![file(0, 10, 0, false)],
481        ] {
482            assert_eq!(
483                exact_count(&input(files, &[]).await, &ScanRequest::default()),
484                None
485            );
486        }
487    }
488
489    #[tokio::test]
490    async fn test_metadata_aggr_leftmost_key_filter() {
491        let ts = |v| lit(ScalarValue::TimestampMillisecond(Some(v), None));
492        let x = |start, end, rows| keyed_file(start, end, rows, ("x", 1), ("x", 9));
493        let mixed = || keyed_file(20, 30, 2, ("x", 1), ("y", 1));
494        let k0 = |v: &str| col("k0").eq(lit(v));
495        for (files, filters, expected) in [
496            // Both bounds prove the equality, so it holds for every row.
497            (
498                vec![x(0, 10, 3), x(20, 30, 2)],
499                vec![col("ts").gt_eq(ts(0)).and(col("ts").lt(ts(40))), k0("x")],
500                Some(5),
501            ),
502            (
503                vec![x(0, 10, 3), x(20, 30, 2)],
504                vec![lit("x").eq(col("k0"))],
505                Some(5),
506            ),
507            // A file spanning several leftmost values may hold other rows.
508            (vec![x(0, 10, 3), mixed()], vec![k0("x")], None),
509            // A disproved equality is not used to exclude files.
510            (vec![x(0, 10, 3)], vec![k0("y")], None),
511            // Only the leftmost column is decodable from the bounds.
512            (vec![x(0, 10, 3)], vec![col("k1").eq(lit(1u32))], None),
513            (vec![x(0, 10, 3)], vec![col("k0").not_eq(lit("y"))], None),
514            // Missing key statistics cannot prove anything.
515            (vec![file(0, 10, 3, true)], vec![k0("x")], None),
516        ] {
517            let input = input(files, &filters).await;
518            let request = ScanRequest {
519                filters,
520                metadata_aggr_hint: true,
521                ..Default::default()
522            };
523            assert_eq!(exact_count(&input, &request), expected, "{request:?}");
524        }
525    }
526
527    #[tokio::test]
528    async fn test_metadata_aggr_fences_and_limits() {
529        let input = input(vec![file(0, 10, 3, true)], &[]).await;
530        for request in [
531            ScanRequest {
532                limit: Some(1),
533                ..Default::default()
534            },
535            ScanRequest {
536                memtable_max_sequence: Some(10),
537                ..Default::default()
538            },
539            ScanRequest {
540                memtable_min_sequence: Some(10),
541                ..Default::default()
542            },
543            ScanRequest {
544                snapshot_on_scan: true,
545                ..Default::default()
546            },
547            ScanRequest {
548                sst_min_sequence: Some(10),
549                ..Default::default()
550            },
551            ScanRequest {
552                exact_sequence_range: true,
553                ..Default::default()
554            },
555            ScanRequest {
556                skip_sst_files: true,
557                ..Default::default()
558            },
559        ] {
560            assert_eq!(exact_count(&input, &request), None);
561        }
562        let mut input = input;
563        input.files.clear();
564        assert_eq!(exact_count(&input, &ScanRequest::default()), Some(0));
565    }
566
567    #[tokio::test]
568    async fn test_metadata_aggr_unknown_manifest_count_falls_back() {
569        let mut input = input(vec![file(0, 10, 0, true)], &[]).await;
570        assert_eq!(exact_count(&input, &ScanRequest::default()), None);
571        input.append_mode = true;
572        assert_eq!(exact_count(&input, &ScanRequest::default()), None);
573    }
574    #[test]
575    fn test_metadata_aggr_reads_op_type_statistics() {
576        use api::v1::OpType;
577        use datatypes::arrow::array::{ArrayRef, StructArray, UInt8Array};
578        use datatypes::arrow::datatypes::{DataType as ArrowType, Field};
579        use datatypes::arrow::record_batch::RecordBatch;
580        use parquet::arrow::ArrowWriter;
581        use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
582        use parquet::file::metadata::KeyValue;
583        use parquet::file::properties::{EnabledStatistics, WriterProperties};
584        use store_api::storage::consts::OP_TYPE_COLUMN_NAME;
585
586        use crate::sst::parquet::metadata::DEDUPED_SST_KEY;
587
588        let put = OpType::Put as u8;
589        let del = OpType::Delete as u8;
590        let metadata = |name: &str, ops: Vec<Option<u8>>, stats, marker: bool| {
591            let nested = StructArray::from(vec![(
592                Arc::new(Field::new(OP_TYPE_COLUMN_NAME, ArrowType::UInt8, false)),
593                Arc::new(UInt8Array::from_value(put, ops.len())) as ArrayRef,
594            )]);
595            let batch = RecordBatch::try_from_iter([
596                ("payload", Arc::new(nested) as ArrayRef),
597                (name, Arc::new(UInt8Array::from(ops)) as ArrayRef),
598            ])
599            .unwrap();
600            let mut buffer = Vec::new();
601            // Two rows per row group, so a delete in a later row group counts.
602            let props = WriterProperties::builder()
603                .set_max_row_group_row_count(Some(2))
604                .set_statistics_enabled(stats)
605                .set_key_value_metadata(
606                    marker.then(|| vec![KeyValue::new(DEDUPED_SST_KEY.to_owned(), None)]),
607                )
608                .build();
609            let mut writer =
610                ArrowWriter::try_new(&mut buffer, batch.schema(), Some(props)).unwrap();
611            writer.write(&batch).unwrap();
612            writer.close().unwrap();
613            ParquetRecordBatchReaderBuilder::try_new(Bytes::from(buffer))
614                .unwrap()
615                .metadata()
616                .clone()
617        };
618        let ops = vec![Some(put); 4];
619        let stats = EnabledStatistics::Page;
620        for (name, ops, statistics, certified, expected) in [
621            (OP_TYPE_COLUMN_NAME, ops.clone(), stats, true, true),
622            (OP_TYPE_COLUMN_NAME, ops.clone(), stats, false, false),
623            (OP_TYPE_COLUMN_NAME, vec![Some(put)], stats, false, true),
624            ("other", ops.clone(), stats, true, false),
625            (
626                OP_TYPE_COLUMN_NAME,
627                ops,
628                EnabledStatistics::None,
629                true,
630                false,
631            ),
632            (OP_TYPE_COLUMN_NAME, vec![None; 4], stats, true, false),
633            (
634                OP_TYPE_COLUMN_NAME,
635                vec![Some(put), None],
636                stats,
637                true,
638                false,
639            ),
640            (
641                OP_TYPE_COLUMN_NAME,
642                vec![Some(put), Some(put), Some(put), Some(del)],
643                stats,
644                true,
645                false,
646            ),
647        ] {
648            let rows = ops.len();
649            let footer = metadata(name, ops, statistics, certified);
650            assert_eq!(
651                footer_proves_visible_rows(&footer, rows),
652                expected,
653                "{footer:?}"
654            );
655            assert!(!footer_proves_visible_rows(&footer, rows + 1));
656        }
657    }
658
659    #[test]
660    fn test_metadata_aggr_rejects_non_arrow_float_equalities() {
661        use datatypes::arrow::datatypes::DataType as ArrowType;
662
663        for (value, data_type) in [
664            (
665                ScalarValue::Float32(Some(f32::from_bits(0x7fc0_0001))),
666                ArrowType::Float32,
667            ),
668            (
669                ScalarValue::Float64(Some(f64::from_bits(0x7ff8_0000_0000_0001))),
670                ArrowType::Float64,
671            ),
672            (ScalarValue::Float64(Some(-0.0)), ArrowType::Float64),
673        ] {
674            let filter = col("k0").eq(lit(value));
675            assert!(eq_literal(&filter, "k0", &data_type).is_none());
676        }
677        let ordinary = col("k0").eq(lit(1.5f64));
678        assert!(eq_literal(&ordinary, "k0", &ArrowType::Float64).is_some());
679    }
680
681    #[tokio::test]
682    async fn test_metadata_aggr_narrowed_partition_falls_back() {
683        use partition::expr::col as partition_col;
684
685        let original_scope = partition_col("k0").gt_eq(Value::String("a".into()));
686        let file = FileHandle::new(
687            FileMeta {
688                partition_expr: Some(original_scope.clone().into()),
689                ..file(0, 10, 3, true).meta_ref().clone()
690            },
691            new_noop_file_purger(),
692        );
693        let mut input = input(vec![file], &[]).await;
694        input.region_partition_expr = Some(original_scope);
695        assert_eq!(exact_count(&input, &ScanRequest::default()), Some(3));
696        input.region_partition_expr = Some(partition_col("k0").gt_eq(Value::String("x".into())));
697        assert_eq!(exact_count(&input, &ScanRequest::default()), None);
698    }
699
700    #[tokio::test]
701    async fn test_metadata_aggr_file_timestamp_unit_overflow() {
702        for (start, end) in [(i64::MIN / 1000 - 1, 0), (0, i64::MAX / 1000 + 1), (-1, 1)] {
703            let file = FileHandle::new(
704                FileMeta {
705                    time_range: (Timestamp::new_second(start), Timestamp::new_second(end)),
706                    ..file(0, 0, 2, true).meta_ref().clone()
707                },
708                new_noop_file_purger(),
709            );
710            let mut input = input(vec![file], &[]).await;
711            let fits = start == -1;
712            assert_eq!(
713                exact_count(&input, &ScanRequest::default()),
714                fits.then_some(2),
715            );
716            input.append_mode = true;
717            assert_eq!(input.scanner_properties().total_rows_is_exact(), fits);
718        }
719    }
720}