Skip to main content

datafusion_common/
stats.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! This module provides data structures to represent statistics
6
7use std::fmt::{self, Debug, Display};
8
9use crate::{Result, ScalarValue};
10
11use crate::error::_plan_err;
12use crate::utils::aggregate::precision_add;
13use arrow::datatypes::{DataType, Schema};
14
15/// Represents a value with a degree of certainty. `Precision` is used to
16/// propagate information the precision of statistical values.
17#[derive(Clone, PartialEq, Eq, Default, Copy)]
18pub enum Precision<T: Debug + Clone + PartialEq + Eq + PartialOrd> {
19    /// The exact value is known. Used for guaranteeing correctness.
20    ///
21    /// Comes from definitive sources such as:
22    /// - Parquet file metadata (row counts, byte sizes)
23    /// - In-memory RecordBatch data (actual row counts, byte sizes, null counts)
24    /// - and more...
25    Exact(T),
26    /// The value is not known exactly, but is likely close to this value.
27    /// Used for cost-based optimizations.
28    ///
29    /// Some operations that would result in `Inexact(T)` would be:
30    /// - Applying a filter (selectivity is unknown)
31    /// - Mixing exact and inexact values in arithmetic
32    /// - and more...
33    Inexact(T),
34    /// Nothing is known about the value. This is the default state.
35    ///
36    /// Acts as an absorbing element in arithmetic -> any operation
37    /// involving `Absent` yields `Absent`. [`Precision::to_inexact`]
38    /// on `Absent` returns `Absent`, not `Inexact` — it represents
39    /// a fundamentally different state.
40    ///
41    /// Common sources include:
42    /// - Data sources without statistics
43    /// - Parquet columns missing from file metadata
44    /// - Statistics that cannot be derived for an operation (e.g.,
45    ///   `distinct_count` after a union, `total_byte_size` for joins)
46    #[default]
47    Absent,
48}
49
50impl<T: Debug + Clone + PartialEq + Eq + PartialOrd> Precision<T> {
51    /// If we have some value (exact or inexact), it returns that value.
52    /// Otherwise, it returns `None`.
53    pub fn get_value(&self) -> Option<&T> {
54        match self {
55            Precision::Exact(value) | Precision::Inexact(value) => Some(value),
56            Precision::Absent => None,
57        }
58    }
59
60    /// Transform the value in this [`Precision`] object, if one exists, using
61    /// the given function. Preserves the exactness state.
62    pub fn map<U, F>(self, f: F) -> Precision<U>
63    where
64        F: Fn(T) -> U,
65        U: Debug + Clone + PartialEq + Eq + PartialOrd,
66    {
67        match self {
68            Precision::Exact(val) => Precision::Exact(f(val)),
69            Precision::Inexact(val) => Precision::Inexact(f(val)),
70            _ => Precision::<U>::Absent,
71        }
72    }
73
74    /// Returns `Some(true)` if we have an exact value, `Some(false)` if we
75    /// have an inexact value, and `None` if there is no value.
76    pub fn is_exact(&self) -> Option<bool> {
77        match self {
78            Precision::Exact(_) => Some(true),
79            Precision::Inexact(_) => Some(false),
80            _ => None,
81        }
82    }
83
84    /// Returns the maximum of two (possibly inexact) values, conservatively
85    /// propagating exactness information. If one of the input values is
86    /// [`Precision::Absent`], the result is `Absent` too.
87    pub fn max(&self, other: &Precision<T>) -> Precision<T> {
88        match (self, other) {
89            (Precision::Exact(a), Precision::Exact(b)) => {
90                Precision::Exact(if a >= b { a.clone() } else { b.clone() })
91            }
92            (Precision::Inexact(a), Precision::Exact(b))
93            | (Precision::Exact(a), Precision::Inexact(b))
94            | (Precision::Inexact(a), Precision::Inexact(b)) => {
95                Precision::Inexact(if a >= b { a.clone() } else { b.clone() })
96            }
97            (_, _) => Precision::Absent,
98        }
99    }
100
101    /// Returns the minimum of two (possibly inexact) values, conservatively
102    /// propagating exactness information. If one of the input values is
103    /// [`Precision::Absent`], the result is `Absent` too.
104    pub fn min(&self, other: &Precision<T>) -> Precision<T> {
105        match (self, other) {
106            (Precision::Exact(a), Precision::Exact(b)) => {
107                Precision::Exact(if a >= b { b.clone() } else { a.clone() })
108            }
109            (Precision::Inexact(a), Precision::Exact(b))
110            | (Precision::Exact(a), Precision::Inexact(b))
111            | (Precision::Inexact(a), Precision::Inexact(b)) => {
112                Precision::Inexact(if a >= b { b.clone() } else { a.clone() })
113            }
114            (_, _) => Precision::Absent,
115        }
116    }
117
118    /// Demotes the precision state from exact to inexact (if present).
119    pub fn to_inexact(self) -> Self {
120        match self {
121            Precision::Exact(value) => Precision::Inexact(value),
122            _ => self,
123        }
124    }
125}
126
127impl Precision<usize> {
128    /// Calculates the sum of two (possibly inexact) [`usize`] values,
129    /// conservatively propagating exactness information. If one of the input
130    /// values is [`Precision::Absent`], the result is `Absent` too.
131    pub fn add(&self, other: &Precision<usize>) -> Precision<usize> {
132        match (self, other) {
133            (Precision::Exact(a), Precision::Exact(b)) => a.checked_add(*b).map_or_else(
134                || Precision::Inexact(a.saturating_add(*b)),
135                Precision::Exact,
136            ),
137            (Precision::Inexact(a), Precision::Exact(b))
138            | (Precision::Exact(a), Precision::Inexact(b))
139            | (Precision::Inexact(a), Precision::Inexact(b)) => {
140                Precision::Inexact(a.saturating_add(*b))
141            }
142            (_, _) => Precision::Absent,
143        }
144    }
145
146    /// Calculates the difference of two (possibly inexact) [`usize`] values,
147    /// conservatively propagating exactness information. If one of the input
148    /// values is [`Precision::Absent`], the result is `Absent` too.
149    pub fn sub(&self, other: &Precision<usize>) -> Precision<usize> {
150        match (self, other) {
151            (Precision::Exact(a), Precision::Exact(b)) => a.checked_sub(*b).map_or_else(
152                || Precision::Inexact(a.saturating_sub(*b)),
153                Precision::Exact,
154            ),
155            (Precision::Inexact(a), Precision::Exact(b))
156            | (Precision::Exact(a), Precision::Inexact(b))
157            | (Precision::Inexact(a), Precision::Inexact(b)) => {
158                Precision::Inexact(a.saturating_sub(*b))
159            }
160            (_, _) => Precision::Absent,
161        }
162    }
163
164    /// Calculates the multiplication of two (possibly inexact) [`usize`] values,
165    /// conservatively propagating exactness information. If one of the input
166    /// values is [`Precision::Absent`], the result is `Absent` too.
167    pub fn multiply(&self, other: &Precision<usize>) -> Precision<usize> {
168        match (self, other) {
169            (Precision::Exact(a), Precision::Exact(b)) => a.checked_mul(*b).map_or_else(
170                || Precision::Inexact(a.saturating_mul(*b)),
171                Precision::Exact,
172            ),
173            (Precision::Inexact(a), Precision::Exact(b))
174            | (Precision::Exact(a), Precision::Inexact(b))
175            | (Precision::Inexact(a), Precision::Inexact(b)) => {
176                Precision::Inexact(a.saturating_mul(*b))
177            }
178            (_, _) => Precision::Absent,
179        }
180    }
181
182    /// Return the estimate of applying a filter with estimated selectivity
183    /// `selectivity` to this Precision. A selectivity of `1.0` means that all
184    /// rows are selected. A selectivity of `0.5` means half the rows are
185    /// selected. An exact zero is preserved, since filtering an empty input
186    /// cannot produce rows; any other known value is demoted to inexact.
187    pub fn with_estimated_selectivity(self, selectivity: f64) -> Self {
188        if self == Precision::Exact(0) {
189            return self;
190        }
191        self.map(|v| ((v as f64 * selectivity).ceil()) as usize)
192            .to_inexact()
193    }
194}
195
196impl Precision<ScalarValue> {
197    fn sum_data_type(data_type: &DataType) -> DataType {
198        match data_type {
199            DataType::Int8 | DataType::Int16 | DataType::Int32 => DataType::Int64,
200            DataType::UInt8 | DataType::UInt16 | DataType::UInt32 => DataType::UInt64,
201            _ => data_type.clone(),
202        }
203    }
204
205    fn cast_scalar_to_sum_type(value: &ScalarValue) -> Result<ScalarValue> {
206        let source_type = value.data_type();
207        let target_type = Self::sum_data_type(&source_type);
208        if source_type == target_type {
209            Ok(value.clone())
210        } else {
211            value.cast_to(&target_type)
212        }
213    }
214
215    /// Calculates the sum of two (possibly inexact) [`ScalarValue`] values,
216    /// conservatively propagating exactness information. If one of the input
217    /// values is [`Precision::Absent`], the result is `Absent` too.
218    ///
219    /// Uses [`ScalarValue::add_checked`] so that integer overflow returns
220    /// an error (mapped to `Absent`) instead of silently wrapping.
221    ///
222    /// For performance-sensitive paths prefer `precision_add` which
223    /// avoids the Arrow array round-trip.
224    pub fn add(&self, other: &Precision<ScalarValue>) -> Precision<ScalarValue> {
225        match (self, other) {
226            (Precision::Exact(a), Precision::Exact(b)) => a
227                .add_checked(b)
228                .map(Precision::Exact)
229                .unwrap_or(Precision::Absent),
230            (Precision::Inexact(a), Precision::Exact(b))
231            | (Precision::Exact(a), Precision::Inexact(b))
232            | (Precision::Inexact(a), Precision::Inexact(b)) => a
233                .add_checked(b)
234                .map(Precision::Inexact)
235                .unwrap_or(Precision::Absent),
236            (_, _) => Precision::Absent,
237        }
238    }
239
240    /// Casts integer values to the wider SQL `SUM` return type.
241    ///
242    /// This narrows overflow risk when `sum_value` statistics are merged:
243    /// `Int8/Int16/Int32 -> Int64` and `UInt8/UInt16/UInt32 -> UInt64`.
244    pub fn cast_to_sum_type(&self) -> Precision<ScalarValue> {
245        match (self.is_exact(), self.get_value()) {
246            (Some(true), Some(value)) => Self::cast_scalar_to_sum_type(value)
247                .map(Precision::Exact)
248                .unwrap_or(Precision::Absent),
249            (Some(false), Some(value)) => Self::cast_scalar_to_sum_type(value)
250                .map(Precision::Inexact)
251                .unwrap_or(Precision::Absent),
252            (_, _) => Precision::Absent,
253        }
254    }
255
256    /// SUM-style addition with integer widening to match SQL `SUM` return
257    /// types for smaller integral inputs.
258    pub fn add_for_sum(&self, other: &Precision<ScalarValue>) -> Precision<ScalarValue> {
259        let mut lhs = self.cast_to_sum_type();
260        let rhs = other.cast_to_sum_type();
261        precision_add(&mut lhs, &rhs);
262        lhs
263    }
264
265    /// Calculates the difference of two (possibly inexact) [`ScalarValue`] values,
266    /// conservatively propagating exactness information. If one of the input
267    /// values is [`Precision::Absent`], the result is `Absent` too.
268    pub fn sub(&self, other: &Precision<ScalarValue>) -> Precision<ScalarValue> {
269        match (self, other) {
270            (Precision::Exact(a), Precision::Exact(b)) => {
271                a.sub(b).map(Precision::Exact).unwrap_or(Precision::Absent)
272            }
273            (Precision::Inexact(a), Precision::Exact(b))
274            | (Precision::Exact(a), Precision::Inexact(b))
275            | (Precision::Inexact(a), Precision::Inexact(b)) => a
276                .sub(b)
277                .map(Precision::Inexact)
278                .unwrap_or(Precision::Absent),
279            (_, _) => Precision::Absent,
280        }
281    }
282
283    /// Calculates the multiplication of two (possibly inexact) [`ScalarValue`] values,
284    /// conservatively propagating exactness information. If one of the input
285    /// values is [`Precision::Absent`], the result is `Absent` too.
286    pub fn multiply(&self, other: &Precision<ScalarValue>) -> Precision<ScalarValue> {
287        match (self, other) {
288            (Precision::Exact(a), Precision::Exact(b)) => a
289                .mul_checked(b)
290                .map(Precision::Exact)
291                .unwrap_or(Precision::Absent),
292            (Precision::Inexact(a), Precision::Exact(b))
293            | (Precision::Exact(a), Precision::Inexact(b))
294            | (Precision::Inexact(a), Precision::Inexact(b)) => a
295                .mul_checked(b)
296                .map(Precision::Inexact)
297                .unwrap_or(Precision::Absent),
298            (_, _) => Precision::Absent,
299        }
300    }
301
302    /// Casts the value to the given data type, propagating exactness information.
303    pub fn cast_to(&self, data_type: &DataType) -> Result<Precision<ScalarValue>> {
304        match self {
305            Precision::Exact(value) => value.cast_to(data_type).map(Precision::Exact),
306            Precision::Inexact(value) => value.cast_to(data_type).map(Precision::Inexact),
307            Precision::Absent => Ok(Precision::Absent),
308        }
309    }
310}
311
312impl<T: Debug + Clone + PartialEq + Eq + PartialOrd> From<Option<T>> for Precision<T> {
313    fn from(option: Option<T>) -> Self {
314        option.map_or(Precision::Absent, Precision::Exact)
315    }
316}
317
318impl<T: Debug + Clone + PartialEq + Eq + PartialOrd> Debug for Precision<T> {
319    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
320        match self {
321            Precision::Exact(inner) => write!(f, "Exact({inner:?})"),
322            Precision::Inexact(inner) => write!(f, "Inexact({inner:?})"),
323            Precision::Absent => write!(f, "Absent"),
324        }
325    }
326}
327
328impl<T: Debug + Clone + PartialEq + Eq + PartialOrd> Display for Precision<T> {
329    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
330        match self {
331            Precision::Exact(inner) => write!(f, "Exact({inner:?})"),
332            Precision::Inexact(inner) => write!(f, "Inexact({inner:?})"),
333            Precision::Absent => write!(f, "Absent"),
334        }
335    }
336}
337
338impl From<Precision<usize>> for Precision<ScalarValue> {
339    fn from(value: Precision<usize>) -> Self {
340        match value {
341            Precision::Exact(v) => Precision::Exact(ScalarValue::UInt64(Some(v as u64))),
342            Precision::Inexact(v) => {
343                Precision::Inexact(ScalarValue::UInt64(Some(v as u64)))
344            }
345            Precision::Absent => Precision::Absent,
346        }
347    }
348}
349
350/// Statistics for a relation
351/// Fields are optional and can be inexact because the sources
352/// sometimes provide approximate estimates for performance reasons
353/// and the transformations output are not always predictable.
354#[derive(Debug, Clone, PartialEq, Eq)]
355pub struct Statistics {
356    /// The number of rows estimated to be scanned.
357    pub num_rows: Precision<usize>,
358    /// The total bytes of the output data.
359    ///
360    /// Note that this is not the same as the total bytes that may be scanned,
361    /// processed, etc.
362    /// E.g. we may read 1GB of data from a Parquet file but the Arrow data
363    /// the node produces may be 2GB; it's this 2GB that is tracked here.
364    pub total_byte_size: Precision<usize>,
365    /// Statistics on a column level.
366    ///
367    /// It must contains a [`ColumnStatistics`] for each field in the schema of
368    /// the table to which the [`Statistics`] refer.
369    pub column_statistics: Vec<ColumnStatistics>,
370}
371
372/// Returns `true` when the statistics prove that the input contains no rows.
373///
374/// Inexact or absent row counts are not sufficient to treat an input as empty.
375pub fn is_known_empty(statistics: &Statistics) -> bool {
376    statistics.num_rows == Precision::Exact(0)
377}
378
379/// Fallback to use when NDV overlap can not be estimated from column bounds.
380#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
381pub enum NdvFallback {
382    /// Use the larger input NDV. This is the conservative default for
383    /// related fragments such as files from the same table.
384    #[default]
385    Max,
386    /// Sum the input NDVs. This is a conservative upper bound for
387    /// independent inputs such as `UNION ALL`.
388    Sum,
389}
390
391impl NdvFallback {
392    fn merge(self, left: usize, right: usize) -> usize {
393        match self {
394            Self::Max => usize::max(left, right),
395            Self::Sum => left.saturating_add(right),
396        }
397    }
398}
399
400impl Default for Statistics {
401    /// Returns a new [`Statistics`] instance with all fields set to unknown
402    /// and no columns.
403    fn default() -> Self {
404        Self {
405            num_rows: Precision::Absent,
406            total_byte_size: Precision::Absent,
407            column_statistics: vec![],
408        }
409    }
410}
411
412impl Statistics {
413    /// Returns a [`Statistics`] instance for the given schema by assigning
414    /// unknown statistics to each column in the schema.
415    pub fn new_unknown(schema: &Schema) -> Self {
416        Self {
417            num_rows: Precision::Absent,
418            total_byte_size: Precision::Absent,
419            column_statistics: Statistics::unknown_column(schema),
420        }
421    }
422
423    /// Calculates `total_byte_size` based on the schema and `num_rows`.
424    /// If any of the columns has non-primitive width, or `num_rows` is unknown,
425    /// the previous `total_byte_size` is kept but downgraded to inexact rather
426    /// than discarded.
427    pub fn calculate_total_byte_size(&mut self, schema: &Schema) {
428        let mut row_size = Some(0);
429        for field in schema.fields() {
430            match field.data_type().primitive_width() {
431                Some(width) => {
432                    row_size = row_size.map(|s| s + width);
433                }
434                None => {
435                    row_size = None;
436                    break;
437                }
438            }
439        }
440        match (row_size, &self.num_rows) {
441            (None, _) | (Some(_), Precision::Absent) => {
442                self.total_byte_size = self.total_byte_size.to_inexact();
443            }
444            (Some(size), _) => {
445                self.total_byte_size = self.num_rows.multiply(&Precision::Exact(size));
446            }
447        }
448    }
449
450    /// Returns an unbounded `ColumnStatistics` for each field in the schema.
451    pub fn unknown_column(schema: &Schema) -> Vec<ColumnStatistics> {
452        schema
453            .fields()
454            .iter()
455            .map(|_| ColumnStatistics::new_unknown())
456            .collect()
457    }
458
459    /// Set the number of rows
460    pub fn with_num_rows(mut self, num_rows: Precision<usize>) -> Self {
461        self.num_rows = num_rows;
462        self
463    }
464
465    /// Set the total size, in bytes
466    pub fn with_total_byte_size(mut self, total_byte_size: Precision<usize>) -> Self {
467        self.total_byte_size = total_byte_size;
468        self
469    }
470
471    /// Add a column to the column statistics
472    pub fn add_column_statistics(mut self, column_stats: ColumnStatistics) -> Self {
473        self.column_statistics.push(column_stats);
474        self
475    }
476
477    /// If the exactness of a [`Statistics`] instance is lost, this function relaxes
478    /// the exactness of all information by converting them [`Precision::Inexact`].
479    pub fn to_inexact(mut self) -> Self {
480        self.num_rows = self.num_rows.to_inexact();
481        self.total_byte_size = self.total_byte_size.to_inexact();
482        self.column_statistics = self
483            .column_statistics
484            .into_iter()
485            .map(|s| s.to_inexact())
486            .collect();
487        self
488    }
489
490    /// Project the statistics to the given column indices.
491    ///
492    /// For example, if we had statistics for columns `{"a", "b", "c"}`,
493    /// projecting to `vec![2, 1]` would return statistics for columns `{"c",
494    /// "b"}`.
495    pub fn project(self, projection: Option<&impl AsRef<[usize]>>) -> Self {
496        let projection = projection.map(AsRef::as_ref);
497        self.project_impl(projection)
498    }
499
500    fn project_impl(mut self, projection: Option<&[usize]>) -> Self {
501        let Some(projection) = projection.map(AsRef::as_ref) else {
502            return self;
503        };
504
505        #[expect(clippy::large_enum_variant)]
506        enum Slot {
507            /// The column is taken and put into the specified statistics location
508            Taken(usize),
509            /// The original columns is present
510            Present(ColumnStatistics),
511        }
512
513        // Convert to Vec<Slot> so we can avoid copying the statistics
514        let mut columns: Vec<_> = std::mem::replace(
515            &mut self.column_statistics,
516            Vec::with_capacity(projection.len()),
517        )
518        .into_iter()
519        .map(Slot::Present)
520        .collect();
521
522        for idx in projection.iter() {
523            let next_idx = self.column_statistics.len();
524            let slot = std::mem::replace(
525                columns.get_mut(*idx).expect("projection out of bounds"),
526                Slot::Taken(next_idx),
527            );
528            match slot {
529                // The column was there, so just move it
530                Slot::Present(col) => self.column_statistics.push(col),
531                // The column was taken, so copy from the previous location
532                Slot::Taken(prev_idx) => self
533                    .column_statistics
534                    .push(self.column_statistics[prev_idx].clone()),
535            }
536        }
537
538        self
539    }
540
541    /// Calculates the statistics after applying `fetch` and `skip` operations.
542    ///
543    /// Here, `self` denotes per-partition statistics. Use the `n_partitions`
544    /// parameter to compute global statistics in a multi-partition setting.
545    pub fn with_fetch(
546        mut self,
547        fetch: Option<usize>,
548        skip: usize,
549        n_partitions: usize,
550    ) -> Result<Self> {
551        if fetch.is_none() && skip == 0 {
552            return Ok(self);
553        }
554
555        let fetch_val = fetch.unwrap_or(usize::MAX);
556
557        // Get the ratio of rows after / rows before on a per-partition basis
558        let num_rows_before = self.num_rows;
559
560        self.num_rows = match self {
561            Statistics {
562                num_rows: Precision::Exact(nr),
563                ..
564            }
565            | Statistics {
566                num_rows: Precision::Inexact(nr),
567                ..
568            } => {
569                // Here, the inexact case gives us an estimate of the number of rows.
570                if nr <= skip {
571                    // All input data will be skipped. Preserve the exactness of
572                    // the input estimate: if the input was inexact, the
573                    // resulting zero is also inexact.
574                    check_num_rows(Some(0), self.num_rows.is_exact().unwrap())
575                } else if nr <= fetch_val && skip == 0 {
576                    // If the input does not reach the `fetch` globally, and `skip`
577                    // is zero (meaning the input and output are identical), return
578                    // input stats as is.
579                    // TODO: Can input stats still be used, but adjusted, when `skip`
580                    //       is non-zero?
581                    return Ok(self);
582                } else if nr - skip <= fetch_val {
583                    // After `skip` input rows are skipped, the remaining rows are
584                    // less than or equal to the `fetch` values, so `num_rows` must
585                    // equal the remaining rows.
586                    check_num_rows(
587                        (nr - skip).checked_mul(n_partitions),
588                        // We know that we have an estimate for the number of rows:
589                        self.num_rows.is_exact().unwrap(),
590                    )
591                } else {
592                    // At this point we know that we were given a `fetch` value
593                    // as the `None` case would go into the branch above. Since
594                    // the input has more rows than `fetch + skip`, the number
595                    // of rows will be the `fetch`, other statistics will have to be downgraded to inexact.
596                    check_num_rows(
597                        fetch_val.checked_mul(n_partitions),
598                        // We know that we have an estimate for the number of rows:
599                        self.num_rows.is_exact().unwrap(),
600                    )
601                }
602            }
603            Statistics {
604                num_rows: Precision::Absent,
605                ..
606            } => check_num_rows(fetch.and_then(|v| v.checked_mul(n_partitions)), false),
607        };
608        let ratio: Option<f64> = match (num_rows_before, self.num_rows) {
609            (
610                Precision::Exact(nr_before) | Precision::Inexact(nr_before),
611                Precision::Exact(nr_after) | Precision::Inexact(nr_after),
612            ) => {
613                if nr_before == 0 {
614                    Some(0.0)
615                } else {
616                    Some(nr_after as f64 / nr_before as f64)
617                }
618            }
619            _ => None,
620        };
621        self.column_statistics = self
622            .column_statistics
623            .into_iter()
624            .map(|cs| {
625                let mut cs = cs.to_inexact();
626                // Scale byte_size by the row ratio
627                cs.byte_size = match (cs.byte_size, ratio) {
628                    (Precision::Exact(n) | Precision::Inexact(n), Some(ratio)) => {
629                        Precision::Inexact((n as f64 * ratio) as usize)
630                    }
631                    _ => Precision::Absent,
632                };
633                // NDV can never exceed the number of rows
634                if let Some(&rows) = self.num_rows.get_value() {
635                    cs.distinct_count = cs.distinct_count.min(&Precision::Inexact(rows));
636                }
637                cs
638            })
639            .collect();
640
641        // Compute total_byte_size as sum of column byte_size values if all are present,
642        // otherwise fall back to scaling the original total_byte_size
643        let sum_scan_bytes: Option<usize> = self
644            .column_statistics
645            .iter()
646            .map(|cs| cs.byte_size.get_value().copied())
647            .try_fold(0usize, |acc, val| val.map(|v| acc + v));
648
649        self.total_byte_size = match sum_scan_bytes {
650            Some(sum) => Precision::Inexact(sum),
651            None => {
652                // Fall back to scaling original total_byte_size if not all columns have byte_size
653                match (&self.total_byte_size, ratio) {
654                    (Precision::Exact(n) | Precision::Inexact(n), Some(ratio)) => {
655                        Precision::Inexact((*n as f64 * ratio) as usize)
656                    }
657                    _ => Precision::Absent,
658                }
659            }
660        };
661        Ok(self)
662    }
663
664    /// Summarize zero or more statistics into a single `Statistics` instance.
665    ///
666    /// The method assumes that all statistics are for the same schema.
667    /// If not, maybe you can call `SchemaMapper::map_column_statistics` to make them consistent.
668    ///
669    /// This method uses [`NdvFallback::Max`] when `distinct_count` overlap
670    /// can not be estimated from column bounds.
671    ///
672    /// Returns an error if the statistics do not match the specified schemas.
673    ///
674    /// # Example
675    /// ```
676    /// # use datafusion_common::{ColumnStatistics, ScalarValue, Statistics};
677    /// # use arrow::datatypes::{Field, Schema, DataType};
678    /// # use datafusion_common::stats::Precision;
679    /// let stats1 = Statistics::default()
680    ///     .with_num_rows(Precision::Exact(10))
681    ///     .add_column_statistics(
682    ///         ColumnStatistics::new_unknown()
683    ///             .with_min_value(Precision::Exact(ScalarValue::from(1)))
684    ///             .with_max_value(Precision::Exact(ScalarValue::from(100)))
685    ///             .with_sum_value(Precision::Exact(ScalarValue::from(500))),
686    ///     );
687    ///
688    /// let stats2 = Statistics::default()
689    ///     .with_num_rows(Precision::Exact(20))
690    ///     .add_column_statistics(
691    ///         ColumnStatistics::new_unknown()
692    ///             .with_min_value(Precision::Exact(ScalarValue::from(5)))
693    ///             .with_max_value(Precision::Exact(ScalarValue::from(200)))
694    ///             .with_sum_value(Precision::Exact(ScalarValue::from(1000))),
695    ///     );
696    ///
697    /// let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
698    /// let merged = Statistics::try_merge_iter(
699    ///     &[stats1, stats2],
700    ///     &schema,
701    /// ).unwrap();
702    ///
703    /// assert_eq!(merged.num_rows, Precision::Exact(30));
704    /// assert_eq!(merged.column_statistics[0].min_value,
705    ///     Precision::Exact(ScalarValue::from(1)));
706    /// assert_eq!(merged.column_statistics[0].max_value,
707    ///     Precision::Exact(ScalarValue::from(200)));
708    /// assert_eq!(merged.column_statistics[0].sum_value,
709    ///     Precision::Exact(ScalarValue::Int64(Some(1500))));
710    /// ```
711    pub fn try_merge_iter<'a, I>(items: I, schema: &Schema) -> Result<Statistics>
712    where
713        I: IntoIterator<Item = &'a Statistics>,
714    {
715        Self::try_merge_iter_with_ndv_fallback(items, schema, NdvFallback::Max)
716    }
717
718    /// Same as [`Statistics::try_merge_iter`], but lets callers choose the
719    /// fallback used when `distinct_count` overlap can not be estimated.
720    pub fn try_merge_iter_with_ndv_fallback<'a, I>(
721        items: I,
722        schema: &Schema,
723        ndv_fallback: NdvFallback,
724    ) -> Result<Statistics>
725    where
726        I: IntoIterator<Item = &'a Statistics>,
727    {
728        let mut items = items.into_iter();
729        let Some(first) = items.next() else {
730            return Ok(Statistics::new_unknown(schema));
731        };
732        let Some(second) = items.next() else {
733            return Ok(first.clone());
734        };
735
736        let num_cols = first.column_statistics.len();
737        let mut num_rows = first.num_rows;
738        let mut total_byte_size = first.total_byte_size;
739        let mut column_statistics = first.column_statistics.clone();
740        for col_stats in &mut column_statistics {
741            cast_sum_value_to_sum_type_in_place(&mut col_stats.sum_value);
742        }
743
744        // Merge the remaining items in a single pass.
745        for (i, stat) in std::iter::once(second).chain(items).enumerate() {
746            if stat.column_statistics.len() != num_cols {
747                return _plan_err!(
748                    "Cannot merge statistics with different number of columns: {} vs {} (item {})",
749                    num_cols,
750                    stat.column_statistics.len(),
751                    i + 1
752                );
753            }
754            num_rows = num_rows.add(&stat.num_rows);
755            total_byte_size = total_byte_size.add(&stat.total_byte_size);
756
757            // Uses precision_add for sum (reuses the lhs accumulator for
758            // direct numeric addition), while preserving the NDV update
759            // ordering required by estimate_ndv_with_overlap.
760            for (col_stats, item_cs) in
761                column_statistics.iter_mut().zip(&stat.column_statistics)
762            {
763                col_stats.null_count = col_stats.null_count.add(&item_cs.null_count);
764
765                // NDV must be computed before min/max update (needs pre-merge ranges)
766                col_stats.distinct_count = match (
767                    col_stats.distinct_count.get_value(),
768                    item_cs.distinct_count.get_value(),
769                ) {
770                    (Some(&l), Some(&r)) => Precision::Inexact(
771                        estimate_ndv_with_overlap(col_stats, item_cs, l, r)
772                            .unwrap_or_else(|| ndv_fallback.merge(l, r)),
773                    ),
774                    _ => Precision::Absent,
775                };
776                precision_min(&mut col_stats.min_value, &item_cs.min_value);
777                precision_max(&mut col_stats.max_value, &item_cs.max_value);
778                precision_add_for_sum_in_place(
779                    &mut col_stats.sum_value,
780                    &item_cs.sum_value,
781                );
782                col_stats.byte_size = col_stats.byte_size.add(&item_cs.byte_size);
783            }
784        }
785
786        Ok(Statistics {
787            num_rows,
788            total_byte_size,
789            column_statistics,
790        })
791    }
792}
793
794/// Estimates the combined number of distinct values (NDV) when merging two
795/// column statistics, using range overlap to avoid double-counting shared values.
796///
797/// Assumes values are distributed uniformly within each input's
798/// `[min, max]` range (the standard assumption when only summary
799/// statistics are available). Under uniformity the fraction of an input's
800/// distinct values that land in a sub-range equals the fraction of
801/// the range that sub-range covers.
802///
803/// The combined value space is split into three disjoint regions:
804///
805/// ```text
806///   |-- only A --|-- overlap --|-- only B --|
807/// ```
808///
809/// * **Only in A/B** - values outside the other input's range
810///   contribute `(1 - overlap_a) * NDV_a` and `(1 - overlap_b) * NDV_b`.
811/// * **Overlap** - both inputs may produce values here. We take
812///   `max(overlap_a * NDV_a, overlap_b * NDV_b)` rather than the
813///   sum because values in the same sub-range are likely shared
814///   (the smaller set is assumed to be a subset of the larger).
815///
816/// The formula ranges between `[max(NDV_a, NDV_b), NDV_a + NDV_b]`,
817/// from full overlap to no overlap.
818///
819/// ```text
820/// NDV = max(overlap_a * NDV_a, overlap_b * NDV_b)   [intersection]
821///     + (1 - overlap_a) * NDV_a                      [only in A]
822///     + (1 - overlap_b) * NDV_b                      [only in B]
823/// ```
824///
825/// Returns `None` when min/max are absent or distance is unsupported
826/// (e.g. strings), in which case the caller should fall back to a simpler
827/// estimate.
828pub fn estimate_ndv_with_overlap(
829    left: &ColumnStatistics,
830    right: &ColumnStatistics,
831    ndv_left: usize,
832    ndv_right: usize,
833) -> Option<usize> {
834    let left_min = left.min_value.get_value()?;
835    let left_max = left.max_value.get_value()?;
836    let right_min = right.min_value.get_value()?;
837    let right_max = right.max_value.get_value()?;
838
839    let range_left = left_max.distance_u64(left_min)?;
840    let range_right = right_max.distance_u64(right_min)?;
841
842    // Constant columns (range == 0) can't use the proportional overlap
843    // formula below, so check interval overlap directly instead.
844    if range_left == 0 || range_right == 0 {
845        let overlaps = left_min <= right_max && right_min <= left_max;
846        return Some(if overlaps {
847            usize::max(ndv_left, ndv_right)
848        } else {
849            ndv_left + ndv_right
850        });
851    }
852
853    let overlap_min = if left_min >= right_min {
854        left_min
855    } else {
856        right_min
857    };
858    let overlap_max = if left_max <= right_max {
859        left_max
860    } else {
861        right_max
862    };
863
864    // Disjoint ranges: no overlap, NDVs are additive
865    if overlap_min > overlap_max {
866        return Some(ndv_left + ndv_right);
867    }
868
869    let overlap_range = overlap_max.distance_u64(overlap_min)? as f64;
870
871    let overlap_left = overlap_range / range_left as f64;
872    let overlap_right = overlap_range / range_right as f64;
873
874    let intersection = f64::max(
875        overlap_left * ndv_left as f64,
876        overlap_right * ndv_right as f64,
877    );
878    let only_left = (1.0 - overlap_left) * ndv_left as f64;
879    let only_right = (1.0 - overlap_right) * ndv_right as f64;
880
881    Some((intersection + only_left + only_right).round() as usize)
882}
883
884/// Returns the minimum precision while not allocating a new value,
885/// mirrors the semantics of `PartialOrd`.
886#[inline]
887fn precision_min<T>(lhs: &mut Precision<T>, rhs: &Precision<T>)
888where
889    T: Debug + Clone + PartialEq + Eq + PartialOrd,
890{
891    *lhs = match (std::mem::take(lhs), rhs) {
892        (Precision::Exact(left), Precision::Exact(right)) => {
893            if left <= *right {
894                Precision::Exact(left)
895            } else {
896                Precision::Exact(right.clone())
897            }
898        }
899        (Precision::Exact(left), Precision::Inexact(right))
900        | (Precision::Inexact(left), Precision::Exact(right))
901        | (Precision::Inexact(left), Precision::Inexact(right)) => {
902            if left <= *right {
903                Precision::Inexact(left)
904            } else {
905                Precision::Inexact(right.clone())
906            }
907        }
908        (_, _) => Precision::Absent,
909    };
910}
911
912/// Returns the maximum precision while not allocating a new value,
913/// mirrors the semantics of `PartialOrd`.
914#[inline]
915fn precision_max<T>(lhs: &mut Precision<T>, rhs: &Precision<T>)
916where
917    T: Debug + Clone + PartialEq + Eq + PartialOrd,
918{
919    *lhs = match (std::mem::take(lhs), rhs) {
920        (Precision::Exact(left), Precision::Exact(right)) => {
921            if left >= *right {
922                Precision::Exact(left)
923            } else {
924                Precision::Exact(right.clone())
925            }
926        }
927        (Precision::Exact(left), Precision::Inexact(right))
928        | (Precision::Inexact(left), Precision::Exact(right))
929        | (Precision::Inexact(left), Precision::Inexact(right)) => {
930            if left >= *right {
931                Precision::Inexact(left)
932            } else {
933                Precision::Inexact(right.clone())
934            }
935        }
936        (_, _) => Precision::Absent,
937    };
938}
939
940#[inline]
941fn cast_sum_value_to_sum_type_in_place(value: &mut Precision<ScalarValue>) {
942    let (is_exact, inner) = match std::mem::take(value) {
943        Precision::Exact(v) => (true, v),
944        Precision::Inexact(v) => (false, v),
945        Precision::Absent => return,
946    };
947    let source_type = inner.data_type();
948    let target_type = Precision::<ScalarValue>::sum_data_type(&source_type);
949
950    let wrap_precision_fn: fn(ScalarValue) -> Precision<ScalarValue> = if is_exact {
951        Precision::Exact
952    } else {
953        Precision::Inexact
954    };
955
956    *value = if source_type == target_type {
957        wrap_precision_fn(inner)
958    } else {
959        inner
960            .cast_to(&target_type)
961            .map(wrap_precision_fn)
962            .unwrap_or(Precision::Absent)
963    };
964}
965
966#[inline]
967fn precision_add_for_sum_in_place(
968    lhs: &mut Precision<ScalarValue>,
969    rhs: &Precision<ScalarValue>,
970) {
971    let (value, wrap_fn): (&ScalarValue, fn(ScalarValue) -> Precision<ScalarValue>) =
972        match rhs {
973            Precision::Exact(v) => (v, Precision::Exact),
974            Precision::Inexact(v) => (v, Precision::Inexact),
975            Precision::Absent => {
976                *lhs = Precision::Absent;
977                return;
978            }
979        };
980    let source_type = value.data_type();
981    let target_type = Precision::<ScalarValue>::sum_data_type(&source_type);
982    if source_type == target_type {
983        precision_add(lhs, rhs);
984    } else {
985        let rhs = value
986            .cast_to(&target_type)
987            .map(wrap_fn)
988            .unwrap_or(Precision::Absent);
989        precision_add(lhs, &rhs);
990    }
991}
992
993/// Creates an estimate of the number of rows in the output using the given
994/// optional value and exactness flag.
995fn check_num_rows(value: Option<usize>, is_exact: bool) -> Precision<usize> {
996    if let Some(value) = value {
997        if is_exact {
998            Precision::Exact(value)
999        } else {
1000            // If the input stats are inexact, so are the output stats.
1001            Precision::Inexact(value)
1002        }
1003    } else {
1004        // If the estimate is not available (e.g. due to an overflow), we can
1005        // not produce a reliable estimate.
1006        Precision::Absent
1007    }
1008}
1009
1010impl Display for Statistics {
1011    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1012        // string of column statistics
1013        let column_stats = self
1014            .column_statistics
1015            .iter()
1016            .enumerate()
1017            .map(|(i, cs)| {
1018                let s = format!("(Col[{i}]:");
1019                let s = if cs.min_value != Precision::Absent {
1020                    format!("{} Min={}", s, cs.min_value)
1021                } else {
1022                    s
1023                };
1024                let s = if cs.max_value != Precision::Absent {
1025                    format!("{} Max={}", s, cs.max_value)
1026                } else {
1027                    s
1028                };
1029                let s = if cs.sum_value != Precision::Absent {
1030                    format!("{} Sum={}", s, cs.sum_value)
1031                } else {
1032                    s
1033                };
1034                let s = if cs.null_count != Precision::Absent {
1035                    format!("{} Null={}", s, cs.null_count)
1036                } else {
1037                    s
1038                };
1039                let s = if cs.distinct_count != Precision::Absent {
1040                    format!("{} Distinct={}", s, cs.distinct_count)
1041                } else {
1042                    s
1043                };
1044                let s = if cs.byte_size != Precision::Absent {
1045                    format!("{} ScanBytes={}", s, cs.byte_size)
1046                } else {
1047                    s
1048                };
1049
1050                s + ")"
1051            })
1052            .collect::<Vec<_>>()
1053            .join(",");
1054
1055        write!(
1056            f,
1057            "Rows={}, Bytes={}, [{}]",
1058            self.num_rows, self.total_byte_size, column_stats
1059        )?;
1060
1061        Ok(())
1062    }
1063}
1064
1065/// Statistics for a column within a relation
1066#[derive(Clone, Debug, PartialEq, Eq, Default)]
1067pub struct ColumnStatistics {
1068    /// Number of null values on column
1069    pub null_count: Precision<usize>,
1070    /// Maximum value of column
1071    pub max_value: Precision<ScalarValue>,
1072    /// Minimum value of column
1073    pub min_value: Precision<ScalarValue>,
1074    /// Sum value of a column.
1075    ///
1076    /// For integral columns, values should be kept in SUM-compatible widened
1077    /// types (`Int8/Int16/Int32 -> Int64`, `UInt8/UInt16/UInt32 -> UInt64`) to
1078    /// reduce overflow risk during statistics propagation.
1079    ///
1080    /// Callers should prefer [`ColumnStatistics::with_sum_value`] for setting
1081    /// this field and [`Precision<ScalarValue>::add_for_sum`] /
1082    /// [`Precision<ScalarValue>::cast_to_sum_type`] for sum arithmetic.
1083    pub sum_value: Precision<ScalarValue>,
1084    /// Number of distinct values
1085    pub distinct_count: Precision<usize>,
1086    /// Estimated size of this column's data in bytes for the output.
1087    ///
1088    /// Note that this is not the same as the total bytes that may be scanned,
1089    /// processed, etc.
1090    ///
1091    /// E.g. we may read 1GB of data from a Parquet file but the Arrow data
1092    /// the node produces may be 2GB; it's this 2GB that is tracked here.
1093    ///
1094    /// Currently this is accurately calculated for primitive types only.
1095    /// For complex types (like Utf8, List, Struct, etc), this value may be
1096    /// absent or inexact (e.g. estimated from the size of the data in the source Parquet files).
1097    ///
1098    /// This value is automatically scaled when operations like limits or
1099    /// filters reduce the number of rows (see [`Statistics::with_fetch`]).
1100    pub byte_size: Precision<usize>,
1101}
1102
1103impl ColumnStatistics {
1104    /// Column contains a single non null value (e.g constant).
1105    pub fn is_singleton(&self) -> bool {
1106        match (&self.min_value, &self.max_value) {
1107            // Min and max values are the same and not infinity.
1108            (Precision::Exact(min), Precision::Exact(max)) => {
1109                !min.is_null() && !max.is_null() && (min == max)
1110            }
1111            (_, _) => false,
1112        }
1113    }
1114
1115    /// Returns a [`ColumnStatistics`] instance having all [`Precision::Absent`] parameters.
1116    pub fn new_unknown() -> Self {
1117        Self {
1118            null_count: Precision::Absent,
1119            max_value: Precision::Absent,
1120            min_value: Precision::Absent,
1121            sum_value: Precision::Absent,
1122            distinct_count: Precision::Absent,
1123            byte_size: Precision::Absent,
1124        }
1125    }
1126
1127    /// Set the null count
1128    pub fn with_null_count(mut self, null_count: Precision<usize>) -> Self {
1129        self.null_count = null_count;
1130        self
1131    }
1132
1133    /// Set the max value
1134    pub fn with_max_value(mut self, max_value: Precision<ScalarValue>) -> Self {
1135        self.max_value = max_value;
1136        self
1137    }
1138
1139    /// Set the min value
1140    pub fn with_min_value(mut self, min_value: Precision<ScalarValue>) -> Self {
1141        self.min_value = min_value;
1142        self
1143    }
1144
1145    /// Set the sum value
1146    pub fn with_sum_value(mut self, sum_value: Precision<ScalarValue>) -> Self {
1147        self.sum_value = match sum_value {
1148            Precision::Exact(value) => {
1149                Precision::<ScalarValue>::cast_scalar_to_sum_type(&value)
1150                    .map(Precision::Exact)
1151                    .unwrap_or(Precision::Absent)
1152            }
1153            Precision::Inexact(value) => {
1154                Precision::<ScalarValue>::cast_scalar_to_sum_type(&value)
1155                    .map(Precision::Inexact)
1156                    .unwrap_or(Precision::Absent)
1157            }
1158            Precision::Absent => Precision::Absent,
1159        };
1160        self
1161    }
1162
1163    /// Set the distinct count
1164    pub fn with_distinct_count(mut self, distinct_count: Precision<usize>) -> Self {
1165        self.distinct_count = distinct_count;
1166        self
1167    }
1168
1169    /// Set the scan byte size
1170    /// This should initially be set to the total size of the column.
1171    pub fn with_byte_size(mut self, byte_size: Precision<usize>) -> Self {
1172        self.byte_size = byte_size;
1173        self
1174    }
1175
1176    /// If the exactness of a [`ColumnStatistics`] instance is lost, this
1177    /// function relaxes the exactness of all information by converting them
1178    /// [`Precision::Inexact`].
1179    pub fn to_inexact(mut self) -> Self {
1180        self.null_count = self.null_count.to_inexact();
1181        self.max_value = self.max_value.to_inexact();
1182        self.min_value = self.min_value.to_inexact();
1183        self.sum_value = self.sum_value.to_inexact();
1184        self.distinct_count = self.distinct_count.to_inexact();
1185        self.byte_size = self.byte_size.to_inexact();
1186        self
1187    }
1188}
1189
1190#[cfg(test)]
1191mod tests {
1192    use super::*;
1193    use crate::assert_contains;
1194    use arrow::datatypes::Field;
1195    use std::sync::Arc;
1196
1197    #[test]
1198    fn test_get_value() {
1199        let exact_precision = Precision::Exact(42);
1200        let inexact_precision = Precision::Inexact(23);
1201        let absent_precision = Precision::<i32>::Absent;
1202
1203        assert_eq!(*exact_precision.get_value().unwrap(), 42);
1204        assert_eq!(*inexact_precision.get_value().unwrap(), 23);
1205        assert_eq!(absent_precision.get_value(), None);
1206    }
1207
1208    #[test]
1209    fn test_with_estimated_selectivity() {
1210        // Filtering an empty input cannot produce rows, so the zero stays exact.
1211        assert_eq!(
1212            Precision::Exact(0).with_estimated_selectivity(0.5),
1213            Precision::Exact(0)
1214        );
1215        assert_eq!(
1216            Precision::Exact(0).with_estimated_selectivity(1.0),
1217            Precision::Exact(0)
1218        );
1219
1220        // Any other known value is scaled and demoted, since the selectivity is
1221        // itself an estimate.
1222        assert_eq!(
1223            Precision::Exact(100).with_estimated_selectivity(0.5),
1224            Precision::Inexact(50)
1225        );
1226        assert_eq!(
1227            Precision::Exact(100).with_estimated_selectivity(1.0),
1228            Precision::Inexact(100)
1229        );
1230        assert_eq!(
1231            Precision::Exact(3).with_estimated_selectivity(0.5),
1232            Precision::Inexact(2)
1233        );
1234
1235        // An inexact zero is an estimate, not a proof, and stays inexact.
1236        assert_eq!(
1237            Precision::Inexact(0).with_estimated_selectivity(0.5),
1238            Precision::Inexact(0)
1239        );
1240        assert_eq!(
1241            Precision::<usize>::Absent.with_estimated_selectivity(0.5),
1242            Precision::Absent
1243        );
1244    }
1245
1246    #[test]
1247    fn test_map() {
1248        let exact_precision = Precision::Exact(42);
1249        let inexact_precision = Precision::Inexact(23);
1250        let absent_precision = Precision::Absent;
1251
1252        let squared = |x| x * x;
1253
1254        assert_eq!(exact_precision.map(squared), Precision::Exact(1764));
1255        assert_eq!(inexact_precision.map(squared), Precision::Inexact(529));
1256        assert_eq!(absent_precision.map(squared), Precision::Absent);
1257    }
1258
1259    #[test]
1260    fn test_is_exact() {
1261        let exact_precision = Precision::Exact(42);
1262        let inexact_precision = Precision::Inexact(23);
1263        let absent_precision = Precision::<i32>::Absent;
1264
1265        assert_eq!(exact_precision.is_exact(), Some(true));
1266        assert_eq!(inexact_precision.is_exact(), Some(false));
1267        assert_eq!(absent_precision.is_exact(), None);
1268    }
1269
1270    #[test]
1271    fn test_max() {
1272        let precision1 = Precision::Exact(42);
1273        let precision2 = Precision::Inexact(23);
1274        let precision3 = Precision::Exact(30);
1275        let absent_precision = Precision::Absent;
1276
1277        assert_eq!(precision1.max(&precision2), Precision::Inexact(42));
1278        assert_eq!(precision1.max(&precision3), Precision::Exact(42));
1279        assert_eq!(precision2.max(&precision3), Precision::Inexact(30));
1280        assert_eq!(precision1.max(&absent_precision), Precision::Absent);
1281    }
1282
1283    #[test]
1284    fn test_min() {
1285        let precision1 = Precision::Exact(42);
1286        let precision2 = Precision::Inexact(23);
1287        let precision3 = Precision::Exact(30);
1288        let absent_precision = Precision::Absent;
1289
1290        assert_eq!(precision1.min(&precision2), Precision::Inexact(23));
1291        assert_eq!(precision1.min(&precision3), Precision::Exact(30));
1292        assert_eq!(precision2.min(&precision3), Precision::Inexact(23));
1293        assert_eq!(precision1.min(&absent_precision), Precision::Absent);
1294    }
1295
1296    #[test]
1297    fn test_to_inexact() {
1298        let exact_precision = Precision::Exact(42);
1299        let inexact_precision = Precision::Inexact(42);
1300        let absent_precision = Precision::<i32>::Absent;
1301
1302        assert_eq!(exact_precision.to_inexact(), inexact_precision);
1303        assert_eq!(inexact_precision.to_inexact(), inexact_precision);
1304        assert_eq!(absent_precision.to_inexact(), absent_precision);
1305    }
1306
1307    #[test]
1308    fn test_add() {
1309        let precision1 = Precision::Exact(42);
1310        let precision2 = Precision::Inexact(23);
1311        let precision3 = Precision::Exact(30);
1312        let absent_precision = Precision::Absent;
1313        let precision_max_exact = Precision::Exact(usize::MAX);
1314        let precision_max_inexact = Precision::Exact(usize::MAX);
1315
1316        assert_eq!(precision1.add(&precision2), Precision::Inexact(65));
1317        assert_eq!(precision1.add(&precision3), Precision::Exact(72));
1318        assert_eq!(precision2.add(&precision3), Precision::Inexact(53));
1319        assert_eq!(precision1.add(&absent_precision), Precision::Absent);
1320        assert_eq!(
1321            precision_max_exact.add(&precision1),
1322            Precision::Inexact(usize::MAX)
1323        );
1324        assert_eq!(
1325            precision_max_inexact.add(&precision1),
1326            Precision::Inexact(usize::MAX)
1327        );
1328    }
1329
1330    #[test]
1331    fn test_add_scalar() {
1332        let precision = Precision::Exact(ScalarValue::Int32(Some(42)));
1333
1334        assert_eq!(
1335            precision.add(&Precision::Exact(ScalarValue::Int32(Some(23)))),
1336            Precision::Exact(ScalarValue::Int32(Some(65))),
1337        );
1338        assert_eq!(
1339            precision.add(&Precision::Inexact(ScalarValue::Int32(Some(23)))),
1340            Precision::Inexact(ScalarValue::Int32(Some(65))),
1341        );
1342        assert_eq!(
1343            precision.add(&Precision::Exact(ScalarValue::Int32(None))),
1344            // As per behavior of ScalarValue::add
1345            Precision::Exact(ScalarValue::Int32(None)),
1346        );
1347        assert_eq!(precision.add(&Precision::Absent), Precision::Absent);
1348    }
1349
1350    #[test]
1351    fn test_add_for_sum_scalar_integer_widening() {
1352        let precision = Precision::Exact(ScalarValue::Int32(Some(42)));
1353
1354        assert_eq!(
1355            precision.add_for_sum(&Precision::Exact(ScalarValue::Int32(Some(23)))),
1356            Precision::Exact(ScalarValue::Int64(Some(65))),
1357        );
1358        assert_eq!(
1359            precision.add_for_sum(&Precision::Inexact(ScalarValue::Int32(Some(23)))),
1360            Precision::Inexact(ScalarValue::Int64(Some(65))),
1361        );
1362    }
1363
1364    #[test]
1365    fn test_add_for_sum_prevents_int32_overflow() {
1366        let lhs = Precision::Exact(ScalarValue::Int32(Some(i32::MAX)));
1367        let rhs = Precision::Exact(ScalarValue::Int32(Some(1)));
1368
1369        assert_eq!(
1370            lhs.add_for_sum(&rhs),
1371            Precision::Exact(ScalarValue::Int64(Some(i64::from(i32::MAX) + 1))),
1372        );
1373    }
1374
1375    #[test]
1376    fn test_add_for_sum_scalar_unsigned_integer_widening() {
1377        let precision = Precision::Exact(ScalarValue::UInt32(Some(42)));
1378
1379        assert_eq!(
1380            precision.add_for_sum(&Precision::Exact(ScalarValue::UInt32(Some(23)))),
1381            Precision::Exact(ScalarValue::UInt64(Some(65))),
1382        );
1383        assert_eq!(
1384            precision.add_for_sum(&Precision::Inexact(ScalarValue::UInt32(Some(23)))),
1385            Precision::Inexact(ScalarValue::UInt64(Some(65))),
1386        );
1387    }
1388
1389    #[test]
1390    fn test_sub() {
1391        let precision1 = Precision::Exact(42);
1392        let precision2 = Precision::Inexact(23);
1393        let precision3 = Precision::Exact(30);
1394        let absent_precision = Precision::Absent;
1395
1396        assert_eq!(precision1.sub(&precision2), Precision::Inexact(19));
1397        assert_eq!(precision1.sub(&precision3), Precision::Exact(12));
1398        assert_eq!(precision2.sub(&precision1), Precision::Inexact(0));
1399        assert_eq!(precision3.sub(&precision1), Precision::Inexact(0));
1400        assert_eq!(precision1.sub(&absent_precision), Precision::Absent);
1401    }
1402
1403    #[test]
1404    fn test_sub_scalar() {
1405        let precision = Precision::Exact(ScalarValue::Int32(Some(42)));
1406
1407        assert_eq!(
1408            precision.sub(&Precision::Exact(ScalarValue::Int32(Some(23)))),
1409            Precision::Exact(ScalarValue::Int32(Some(19))),
1410        );
1411        assert_eq!(
1412            precision.sub(&Precision::Inexact(ScalarValue::Int32(Some(23)))),
1413            Precision::Inexact(ScalarValue::Int32(Some(19))),
1414        );
1415        assert_eq!(
1416            precision.sub(&Precision::Exact(ScalarValue::Int32(None))),
1417            // As per behavior of ScalarValue::sub
1418            Precision::Exact(ScalarValue::Int32(None)),
1419        );
1420        assert_eq!(precision.sub(&Precision::Absent), Precision::Absent);
1421    }
1422
1423    #[test]
1424    fn test_multiply() {
1425        let precision1 = Precision::Exact(6);
1426        let precision2 = Precision::Inexact(3);
1427        let precision3 = Precision::Exact(5);
1428        let precision_max_exact = Precision::Exact(usize::MAX);
1429        let precision_max_inexact = Precision::Exact(usize::MAX);
1430        let absent_precision = Precision::Absent;
1431
1432        assert_eq!(precision1.multiply(&precision2), Precision::Inexact(18));
1433        assert_eq!(precision1.multiply(&precision3), Precision::Exact(30));
1434        assert_eq!(precision2.multiply(&precision3), Precision::Inexact(15));
1435        assert_eq!(precision1.multiply(&absent_precision), Precision::Absent);
1436        assert_eq!(
1437            precision_max_exact.multiply(&precision1),
1438            Precision::Inexact(usize::MAX)
1439        );
1440        assert_eq!(
1441            precision_max_inexact.multiply(&precision1),
1442            Precision::Inexact(usize::MAX)
1443        );
1444    }
1445
1446    #[test]
1447    fn test_multiply_scalar() {
1448        let precision = Precision::Exact(ScalarValue::Int32(Some(6)));
1449
1450        assert_eq!(
1451            precision.multiply(&Precision::Exact(ScalarValue::Int32(Some(5)))),
1452            Precision::Exact(ScalarValue::Int32(Some(30))),
1453        );
1454        assert_eq!(
1455            precision.multiply(&Precision::Inexact(ScalarValue::Int32(Some(5)))),
1456            Precision::Inexact(ScalarValue::Int32(Some(30))),
1457        );
1458        assert_eq!(
1459            precision.multiply(&Precision::Exact(ScalarValue::Int32(None))),
1460            // As per behavior of ScalarValue::mul_checked
1461            Precision::Exact(ScalarValue::Int32(None)),
1462        );
1463        assert_eq!(precision.multiply(&Precision::Absent), Precision::Absent);
1464    }
1465
1466    #[test]
1467    fn test_cast_to() {
1468        // Valid
1469        assert_eq!(
1470            Precision::Exact(ScalarValue::Int32(Some(42)))
1471                .cast_to(&DataType::Int64)
1472                .unwrap(),
1473            Precision::Exact(ScalarValue::Int64(Some(42))),
1474        );
1475        assert_eq!(
1476            Precision::Inexact(ScalarValue::Int32(Some(42)))
1477                .cast_to(&DataType::Int64)
1478                .unwrap(),
1479            Precision::Inexact(ScalarValue::Int64(Some(42))),
1480        );
1481        // Null
1482        assert_eq!(
1483            Precision::Exact(ScalarValue::Int32(None))
1484                .cast_to(&DataType::Int64)
1485                .unwrap(),
1486            Precision::Exact(ScalarValue::Int64(None)),
1487        );
1488        // Overflow returns error
1489        assert!(
1490            Precision::Exact(ScalarValue::Int32(Some(256)))
1491                .cast_to(&DataType::Int8)
1492                .is_err()
1493        );
1494    }
1495
1496    #[test]
1497    fn test_precision_cloning() {
1498        // Precision<usize> is copy
1499        let precision: Precision<usize> = Precision::Exact(42);
1500        let p2 = precision;
1501        assert_eq!(precision, p2);
1502
1503        // Precision<ScalarValue> is not copy (requires .clone())
1504        let precision: Precision<ScalarValue> =
1505            Precision::Exact(ScalarValue::Int64(Some(42)));
1506        let p2 = precision.clone();
1507        assert_eq!(precision, p2);
1508    }
1509
1510    #[test]
1511    fn test_project_none() {
1512        let projection: Option<Vec<usize>> = None;
1513        let stats = make_stats(vec![10, 20, 30]).project(projection.as_ref());
1514        assert_eq!(stats, make_stats(vec![10, 20, 30]));
1515    }
1516
1517    #[test]
1518    fn test_project_empty() {
1519        let projection = Some(vec![]);
1520        let stats = make_stats(vec![10, 20, 30]).project(projection.as_ref());
1521        assert_eq!(stats, make_stats(vec![]));
1522    }
1523
1524    #[test]
1525    fn test_project_swap() {
1526        let projection = Some(vec![2, 1]);
1527        let stats = make_stats(vec![10, 20, 30]).project(projection.as_ref());
1528        assert_eq!(stats, make_stats(vec![30, 20]));
1529    }
1530
1531    #[test]
1532    fn test_project_repeated() {
1533        let projection = Some(vec![1, 2, 1, 1, 0, 2]);
1534        let stats = make_stats(vec![10, 20, 30]).project(projection.as_ref());
1535        assert_eq!(stats, make_stats(vec![20, 30, 20, 20, 10, 30]));
1536    }
1537
1538    // Make a Statistics structure with the specified null counts for each column
1539    fn make_stats(counts: impl IntoIterator<Item = usize>) -> Statistics {
1540        Statistics {
1541            num_rows: Precision::Exact(42),
1542            total_byte_size: Precision::Exact(500),
1543            column_statistics: counts.into_iter().map(col_stats_i64).collect(),
1544        }
1545    }
1546
1547    fn col_stats_i64(null_count: usize) -> ColumnStatistics {
1548        ColumnStatistics {
1549            null_count: Precision::Exact(null_count),
1550            max_value: Precision::Exact(ScalarValue::Int64(Some(42))),
1551            min_value: Precision::Exact(ScalarValue::Int64(Some(64))),
1552            sum_value: Precision::Exact(ScalarValue::Int64(Some(4600))),
1553            distinct_count: Precision::Exact(100),
1554            byte_size: Precision::Exact(800),
1555        }
1556    }
1557
1558    fn make_single_i64_ndv_stats(
1559        distinct_count: Precision<usize>,
1560        min_value: Option<i64>,
1561        max_value: Option<i64>,
1562    ) -> Statistics {
1563        let to_precision = |value| Precision::Exact(ScalarValue::Int64(Some(value)));
1564
1565        Statistics::default()
1566            .with_num_rows(Precision::Exact(10))
1567            .add_column_statistics(
1568                ColumnStatistics::new_unknown()
1569                    .with_distinct_count(distinct_count)
1570                    .with_min_value(
1571                        min_value.map(to_precision).unwrap_or(Precision::Absent),
1572                    )
1573                    .with_max_value(
1574                        max_value.map(to_precision).unwrap_or(Precision::Absent),
1575                    ),
1576            )
1577    }
1578
1579    fn merge_single_i64_ndv_distinct_count(
1580        left: Statistics,
1581        right: Statistics,
1582        ndv_fallback: NdvFallback,
1583    ) -> Precision<usize> {
1584        let schema = Schema::new(vec![Field::new("a", DataType::Int64, true)]);
1585
1586        Statistics::try_merge_iter_with_ndv_fallback(
1587            [&left, &right],
1588            &schema,
1589            ndv_fallback,
1590        )
1591        .unwrap()
1592        .column_statistics[0]
1593            .distinct_count
1594    }
1595
1596    #[test]
1597    fn test_try_merge() {
1598        // Create a schema with two columns
1599        let schema = Arc::new(Schema::new(vec![
1600            Field::new("col1", DataType::Int32, false),
1601            Field::new("col2", DataType::Int32, false),
1602        ]));
1603
1604        // Create items with statistics
1605        let stats1 = Statistics {
1606            num_rows: Precision::Exact(10),
1607            total_byte_size: Precision::Exact(100),
1608            column_statistics: vec![
1609                ColumnStatistics {
1610                    null_count: Precision::Exact(1),
1611                    max_value: Precision::Exact(ScalarValue::Int32(Some(100))),
1612                    min_value: Precision::Exact(ScalarValue::Int32(Some(1))),
1613                    sum_value: Precision::Exact(ScalarValue::Int32(Some(500))),
1614                    distinct_count: Precision::Absent,
1615                    byte_size: Precision::Exact(40),
1616                },
1617                ColumnStatistics {
1618                    null_count: Precision::Exact(2),
1619                    max_value: Precision::Exact(ScalarValue::Int32(Some(200))),
1620                    min_value: Precision::Exact(ScalarValue::Int32(Some(10))),
1621                    sum_value: Precision::Exact(ScalarValue::Int32(Some(1000))),
1622                    distinct_count: Precision::Absent,
1623                    byte_size: Precision::Exact(40),
1624                },
1625            ],
1626        };
1627
1628        let stats2 = Statistics {
1629            num_rows: Precision::Exact(15),
1630            total_byte_size: Precision::Exact(150),
1631            column_statistics: vec![
1632                ColumnStatistics {
1633                    null_count: Precision::Exact(2),
1634                    max_value: Precision::Exact(ScalarValue::Int32(Some(120))),
1635                    min_value: Precision::Exact(ScalarValue::Int32(Some(-10))),
1636                    sum_value: Precision::Exact(ScalarValue::Int32(Some(600))),
1637                    distinct_count: Precision::Absent,
1638                    byte_size: Precision::Exact(60),
1639                },
1640                ColumnStatistics {
1641                    null_count: Precision::Exact(3),
1642                    max_value: Precision::Exact(ScalarValue::Int32(Some(180))),
1643                    min_value: Precision::Exact(ScalarValue::Int32(Some(5))),
1644                    sum_value: Precision::Exact(ScalarValue::Int32(Some(1200))),
1645                    distinct_count: Precision::Absent,
1646                    byte_size: Precision::Exact(60),
1647                },
1648            ],
1649        };
1650
1651        let items = vec![stats1, stats2];
1652
1653        let summary_stats = Statistics::try_merge_iter(&items, &schema).unwrap();
1654
1655        // Verify the results
1656        assert_eq!(summary_stats.num_rows, Precision::Exact(25)); // 10 + 15
1657        assert_eq!(summary_stats.total_byte_size, Precision::Exact(250)); // 100 + 150
1658
1659        // Verify column statistics
1660        let col1_stats = &summary_stats.column_statistics[0];
1661        assert_eq!(col1_stats.null_count, Precision::Exact(3)); // 1 + 2
1662        assert_eq!(
1663            col1_stats.max_value,
1664            Precision::Exact(ScalarValue::Int32(Some(120)))
1665        );
1666        assert_eq!(
1667            col1_stats.min_value,
1668            Precision::Exact(ScalarValue::Int32(Some(-10)))
1669        );
1670        assert_eq!(
1671            col1_stats.sum_value,
1672            Precision::Exact(ScalarValue::Int64(Some(1100)))
1673        ); // 500 + 600
1674
1675        let col2_stats = &summary_stats.column_statistics[1];
1676        assert_eq!(col2_stats.null_count, Precision::Exact(5)); // 2 + 3
1677        assert_eq!(
1678            col2_stats.max_value,
1679            Precision::Exact(ScalarValue::Int32(Some(200)))
1680        );
1681        assert_eq!(
1682            col2_stats.min_value,
1683            Precision::Exact(ScalarValue::Int32(Some(5)))
1684        );
1685        assert_eq!(
1686            col2_stats.sum_value,
1687            Precision::Exact(ScalarValue::Int64(Some(2200)))
1688        ); // 1000 + 1200
1689    }
1690
1691    #[test]
1692    fn test_try_merge_mixed_precision() {
1693        // Create a schema with one column
1694        let schema = Arc::new(Schema::new(vec![Field::new(
1695            "col1",
1696            DataType::Int32,
1697            false,
1698        )]));
1699
1700        // Create items with different precision levels
1701        let stats1 = Statistics {
1702            num_rows: Precision::Exact(10),
1703            total_byte_size: Precision::Inexact(100),
1704            column_statistics: vec![ColumnStatistics {
1705                null_count: Precision::Exact(1),
1706                max_value: Precision::Exact(ScalarValue::Int32(Some(100))),
1707                min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
1708                sum_value: Precision::Exact(ScalarValue::Int32(Some(500))),
1709                distinct_count: Precision::Absent,
1710                byte_size: Precision::Exact(40),
1711            }],
1712        };
1713
1714        let stats2 = Statistics {
1715            num_rows: Precision::Inexact(15),
1716            total_byte_size: Precision::Exact(150),
1717            column_statistics: vec![ColumnStatistics {
1718                null_count: Precision::Inexact(2),
1719                max_value: Precision::Inexact(ScalarValue::Int32(Some(120))),
1720                min_value: Precision::Exact(ScalarValue::Int32(Some(-10))),
1721                sum_value: Precision::Absent,
1722                distinct_count: Precision::Absent,
1723                byte_size: Precision::Inexact(60),
1724            }],
1725        };
1726
1727        let items = vec![stats1, stats2];
1728
1729        let summary_stats = Statistics::try_merge_iter(&items, &schema).unwrap();
1730
1731        assert_eq!(summary_stats.num_rows, Precision::Inexact(25));
1732        assert_eq!(summary_stats.total_byte_size, Precision::Inexact(250));
1733
1734        let col_stats = &summary_stats.column_statistics[0];
1735        assert_eq!(col_stats.null_count, Precision::Inexact(3));
1736        assert_eq!(
1737            col_stats.max_value,
1738            Precision::Inexact(ScalarValue::Int32(Some(120)))
1739        );
1740        assert_eq!(
1741            col_stats.min_value,
1742            Precision::Inexact(ScalarValue::Int32(Some(-10)))
1743        );
1744        assert_eq!(col_stats.sum_value, Precision::Absent);
1745    }
1746
1747    #[test]
1748    fn test_try_merge_empty() {
1749        let schema = Arc::new(Schema::new(vec![Field::new(
1750            "col1",
1751            DataType::Int32,
1752            false,
1753        )]));
1754
1755        // Empty collection
1756        let items: Vec<Statistics> = vec![];
1757
1758        let summary_stats = Statistics::try_merge_iter(&items, &schema).unwrap();
1759
1760        // Verify default values for empty collection
1761        assert_eq!(summary_stats.num_rows, Precision::Absent);
1762        assert_eq!(summary_stats.total_byte_size, Precision::Absent);
1763        assert_eq!(summary_stats.column_statistics.len(), 1);
1764        assert_eq!(
1765            summary_stats.column_statistics[0].null_count,
1766            Precision::Absent
1767        );
1768    }
1769
1770    #[test]
1771    fn test_try_merge_mismatched_size() {
1772        // Create a schema with one column
1773        let schema = Arc::new(Schema::new(vec![Field::new(
1774            "col1",
1775            DataType::Int32,
1776            false,
1777        )]));
1778
1779        // No column statistics
1780        let stats1 = Statistics::default();
1781
1782        let stats2 =
1783            Statistics::default().add_column_statistics(ColumnStatistics::new_unknown());
1784
1785        let items = vec![stats1, stats2];
1786
1787        let e = Statistics::try_merge_iter(&items, &schema).unwrap_err();
1788        assert_contains!(
1789            e.to_string(),
1790            "Error during planning: Cannot merge statistics with different number of columns: 0 vs 1"
1791        );
1792    }
1793
1794    #[test]
1795    fn test_try_merge_distinct_count_absent() {
1796        // Create statistics with known distinct counts
1797        let stats1 = Statistics::default()
1798            .with_num_rows(Precision::Exact(10))
1799            .with_total_byte_size(Precision::Exact(100))
1800            .add_column_statistics(
1801                ColumnStatistics::new_unknown()
1802                    .with_null_count(Precision::Exact(0))
1803                    .with_min_value(Precision::Exact(ScalarValue::Int32(Some(1))))
1804                    .with_max_value(Precision::Exact(ScalarValue::Int32(Some(10))))
1805                    .with_distinct_count(Precision::Exact(5)),
1806            );
1807
1808        let stats2 = Statistics::default()
1809            .with_num_rows(Precision::Exact(15))
1810            .with_total_byte_size(Precision::Exact(150))
1811            .add_column_statistics(
1812                ColumnStatistics::new_unknown()
1813                    .with_null_count(Precision::Exact(0))
1814                    .with_min_value(Precision::Exact(ScalarValue::Int32(Some(5))))
1815                    .with_max_value(Precision::Exact(ScalarValue::Int32(Some(20))))
1816                    .with_distinct_count(Precision::Exact(7)),
1817            );
1818
1819        // Merge statistics
1820        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
1821        let merged_stats =
1822            Statistics::try_merge_iter([&stats1, &stats2], &schema).unwrap();
1823
1824        // Verify the results
1825        assert_eq!(merged_stats.num_rows, Precision::Exact(25));
1826        assert_eq!(merged_stats.total_byte_size, Precision::Exact(250));
1827
1828        let col_stats = &merged_stats.column_statistics[0];
1829        assert_eq!(col_stats.null_count, Precision::Exact(0));
1830        assert_eq!(
1831            col_stats.min_value,
1832            Precision::Exact(ScalarValue::Int32(Some(1)))
1833        );
1834        assert_eq!(
1835            col_stats.max_value,
1836            Precision::Exact(ScalarValue::Int32(Some(20)))
1837        );
1838        // Overlap-based NDV: ranges [1,10] and [5,20], overlap [5,10]
1839        // range_left=9, range_right=15, overlap=5
1840        // overlap_left=5*(5/9)=2.78, overlap_right=7*(5/15)=2.33
1841        // result = max(2.78, 2.33) + (5-2.78) + (7-2.33) = 9.67 -> 10
1842        assert_eq!(col_stats.distinct_count, Precision::Inexact(10));
1843    }
1844
1845    #[test]
1846    fn test_try_merge_ndv_disjoint_ranges() {
1847        let stats1 = Statistics::default()
1848            .with_num_rows(Precision::Exact(10))
1849            .add_column_statistics(
1850                ColumnStatistics::new_unknown()
1851                    .with_min_value(Precision::Exact(ScalarValue::Int32(Some(0))))
1852                    .with_max_value(Precision::Exact(ScalarValue::Int32(Some(10))))
1853                    .with_distinct_count(Precision::Exact(5)),
1854            );
1855        let stats2 = Statistics::default()
1856            .with_num_rows(Precision::Exact(10))
1857            .add_column_statistics(
1858                ColumnStatistics::new_unknown()
1859                    .with_min_value(Precision::Exact(ScalarValue::Int32(Some(20))))
1860                    .with_max_value(Precision::Exact(ScalarValue::Int32(Some(30))))
1861                    .with_distinct_count(Precision::Exact(8)),
1862            );
1863
1864        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
1865        let merged = Statistics::try_merge_iter([&stats1, &stats2], &schema).unwrap();
1866        // No overlap -> sum of NDVs
1867        assert_eq!(
1868            merged.column_statistics[0].distinct_count,
1869            Precision::Inexact(13)
1870        );
1871    }
1872
1873    #[test]
1874    fn test_try_merge_ndv_identical_ranges() {
1875        let stats1 = Statistics::default()
1876            .with_num_rows(Precision::Exact(100))
1877            .add_column_statistics(
1878                ColumnStatistics::new_unknown()
1879                    .with_min_value(Precision::Exact(ScalarValue::Int32(Some(0))))
1880                    .with_max_value(Precision::Exact(ScalarValue::Int32(Some(100))))
1881                    .with_distinct_count(Precision::Exact(50)),
1882            );
1883        let stats2 = Statistics::default()
1884            .with_num_rows(Precision::Exact(100))
1885            .add_column_statistics(
1886                ColumnStatistics::new_unknown()
1887                    .with_min_value(Precision::Exact(ScalarValue::Int32(Some(0))))
1888                    .with_max_value(Precision::Exact(ScalarValue::Int32(Some(100))))
1889                    .with_distinct_count(Precision::Exact(30)),
1890            );
1891
1892        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
1893        let merged = Statistics::try_merge_iter([&stats1, &stats2], &schema).unwrap();
1894        // Full overlap -> max(50, 30) = 50
1895        assert_eq!(
1896            merged.column_statistics[0].distinct_count,
1897            Precision::Inexact(50)
1898        );
1899    }
1900
1901    #[test]
1902    fn test_try_merge_ndv_partial_overlap() {
1903        let stats1 = Statistics::default()
1904            .with_num_rows(Precision::Exact(100))
1905            .add_column_statistics(
1906                ColumnStatistics::new_unknown()
1907                    .with_min_value(Precision::Exact(ScalarValue::Int32(Some(0))))
1908                    .with_max_value(Precision::Exact(ScalarValue::Int32(Some(100))))
1909                    .with_distinct_count(Precision::Exact(80)),
1910            );
1911        let stats2 = Statistics::default()
1912            .with_num_rows(Precision::Exact(100))
1913            .add_column_statistics(
1914                ColumnStatistics::new_unknown()
1915                    .with_min_value(Precision::Exact(ScalarValue::Int32(Some(50))))
1916                    .with_max_value(Precision::Exact(ScalarValue::Int32(Some(150))))
1917                    .with_distinct_count(Precision::Exact(60)),
1918            );
1919
1920        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
1921        let merged = Statistics::try_merge_iter([&stats1, &stats2], &schema).unwrap();
1922        // overlap=[50,100], range_left=100, range_right=100, overlap_range=50
1923        // overlap_left=80*(50/100)=40, overlap_right=60*(50/100)=30
1924        // result = max(40,30) + (80-40) + (60-30) = 40 + 40 + 30 = 110
1925        assert_eq!(
1926            merged.column_statistics[0].distinct_count,
1927            Precision::Inexact(110)
1928        );
1929    }
1930
1931    #[test]
1932    fn test_try_merge_ndv_missing_min_max() {
1933        let stats1 = Statistics::default()
1934            .with_num_rows(Precision::Exact(10))
1935            .add_column_statistics(
1936                ColumnStatistics::new_unknown().with_distinct_count(Precision::Exact(5)),
1937            );
1938        let stats2 = Statistics::default()
1939            .with_num_rows(Precision::Exact(10))
1940            .add_column_statistics(
1941                ColumnStatistics::new_unknown().with_distinct_count(Precision::Exact(8)),
1942            );
1943
1944        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
1945        let merged = Statistics::try_merge_iter([&stats1, &stats2], &schema).unwrap();
1946        // No min/max -> default fallback is max
1947        assert_eq!(
1948            merged.column_statistics[0].distinct_count,
1949            Precision::Inexact(8)
1950        );
1951    }
1952
1953    #[test]
1954    fn test_try_merge_ndv_non_numeric_types() {
1955        let stats1 = Statistics::default()
1956            .with_num_rows(Precision::Exact(10))
1957            .add_column_statistics(
1958                ColumnStatistics::new_unknown()
1959                    .with_min_value(Precision::Exact(ScalarValue::Utf8(Some(
1960                        "aaa".to_string(),
1961                    ))))
1962                    .with_max_value(Precision::Exact(ScalarValue::Utf8(Some(
1963                        "zzz".to_string(),
1964                    ))))
1965                    .with_distinct_count(Precision::Exact(5)),
1966            );
1967        let stats2 = Statistics::default()
1968            .with_num_rows(Precision::Exact(10))
1969            .add_column_statistics(
1970                ColumnStatistics::new_unknown()
1971                    .with_min_value(Precision::Exact(ScalarValue::Utf8(Some(
1972                        "bbb".to_string(),
1973                    ))))
1974                    .with_max_value(Precision::Exact(ScalarValue::Utf8(Some(
1975                        "yyy".to_string(),
1976                    ))))
1977                    .with_distinct_count(Precision::Exact(8)),
1978            );
1979
1980        let schema = Schema::new(vec![Field::new("a", DataType::Utf8, true)]);
1981        let merged = Statistics::try_merge_iter([&stats1, &stats2], &schema).unwrap();
1982        // distance() unsupported for strings -> default fallback is max
1983        assert_eq!(
1984            merged.column_statistics[0].distinct_count,
1985            Precision::Inexact(8)
1986        );
1987    }
1988
1989    #[test]
1990    fn test_try_merge_ndv_non_numeric_types_sum_fallback() {
1991        let stats1 = Statistics::default()
1992            .with_num_rows(Precision::Exact(10))
1993            .add_column_statistics(
1994                ColumnStatistics::new_unknown()
1995                    .with_min_value(Precision::Exact(ScalarValue::Utf8(Some(
1996                        "aaa".to_string(),
1997                    ))))
1998                    .with_max_value(Precision::Exact(ScalarValue::Utf8(Some(
1999                        "zzz".to_string(),
2000                    ))))
2001                    .with_distinct_count(Precision::Exact(5)),
2002            );
2003        let stats2 = Statistics::default()
2004            .with_num_rows(Precision::Exact(10))
2005            .add_column_statistics(
2006                ColumnStatistics::new_unknown()
2007                    .with_min_value(Precision::Exact(ScalarValue::Utf8(Some(
2008                        "bbb".to_string(),
2009                    ))))
2010                    .with_max_value(Precision::Exact(ScalarValue::Utf8(Some(
2011                        "yyy".to_string(),
2012                    ))))
2013                    .with_distinct_count(Precision::Exact(8)),
2014            );
2015
2016        let schema = Schema::new(vec![Field::new("a", DataType::Utf8, true)]);
2017        let merged = Statistics::try_merge_iter_with_ndv_fallback(
2018            [&stats1, &stats2],
2019            &schema,
2020            NdvFallback::Sum,
2021        )
2022        .unwrap();
2023
2024        // distance() unsupported for strings -> sum fallback is caller-selected
2025        assert_eq!(
2026            merged.column_statistics[0].distinct_count,
2027            Precision::Inexact(13)
2028        );
2029    }
2030
2031    #[test]
2032    fn test_try_merge_ndv_constant_columns() {
2033        // Same constant: [5,5]+[5,5] -> max
2034        let stats1 = Statistics::default()
2035            .with_num_rows(Precision::Exact(10))
2036            .add_column_statistics(
2037                ColumnStatistics::new_unknown()
2038                    .with_min_value(Precision::Exact(ScalarValue::Int32(Some(5))))
2039                    .with_max_value(Precision::Exact(ScalarValue::Int32(Some(5))))
2040                    .with_distinct_count(Precision::Exact(1)),
2041            );
2042        let stats2 = Statistics::default()
2043            .with_num_rows(Precision::Exact(10))
2044            .add_column_statistics(
2045                ColumnStatistics::new_unknown()
2046                    .with_min_value(Precision::Exact(ScalarValue::Int32(Some(5))))
2047                    .with_max_value(Precision::Exact(ScalarValue::Int32(Some(5))))
2048                    .with_distinct_count(Precision::Exact(1)),
2049            );
2050
2051        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
2052        let merged = Statistics::try_merge_iter([&stats1, &stats2], &schema).unwrap();
2053        assert_eq!(
2054            merged.column_statistics[0].distinct_count,
2055            Precision::Inexact(1)
2056        );
2057
2058        // Different constants: [5,5]+[10,10] -> sum
2059        let stats3 = Statistics::default()
2060            .with_num_rows(Precision::Exact(10))
2061            .add_column_statistics(
2062                ColumnStatistics::new_unknown()
2063                    .with_min_value(Precision::Exact(ScalarValue::Int32(Some(5))))
2064                    .with_max_value(Precision::Exact(ScalarValue::Int32(Some(5))))
2065                    .with_distinct_count(Precision::Exact(1)),
2066            );
2067        let stats4 = Statistics::default()
2068            .with_num_rows(Precision::Exact(10))
2069            .add_column_statistics(
2070                ColumnStatistics::new_unknown()
2071                    .with_min_value(Precision::Exact(ScalarValue::Int32(Some(10))))
2072                    .with_max_value(Precision::Exact(ScalarValue::Int32(Some(10))))
2073                    .with_distinct_count(Precision::Exact(1)),
2074            );
2075
2076        let merged = Statistics::try_merge_iter([&stats3, &stats4], &schema).unwrap();
2077        assert_eq!(
2078            merged.column_statistics[0].distinct_count,
2079            Precision::Inexact(2)
2080        );
2081    }
2082
2083    #[test]
2084    fn test_try_merge_ndv_original_union_edge_cases() {
2085        struct NdvTestCase {
2086            name: &'static str,
2087            left_ndv: Precision<usize>,
2088            left_min: Option<i64>,
2089            left_max: Option<i64>,
2090            right_ndv: Precision<usize>,
2091            right_min: Option<i64>,
2092            right_max: Option<i64>,
2093            expected: Precision<usize>,
2094        }
2095
2096        let cases = vec![
2097            NdvTestCase {
2098                name: "disjoint ranges",
2099                left_ndv: Precision::Exact(5),
2100                left_min: Some(0),
2101                left_max: Some(10),
2102                right_ndv: Precision::Exact(3),
2103                right_min: Some(20),
2104                right_max: Some(30),
2105                expected: Precision::Inexact(8),
2106            },
2107            NdvTestCase {
2108                name: "identical ranges",
2109                left_ndv: Precision::Exact(10),
2110                left_min: Some(0),
2111                left_max: Some(100),
2112                right_ndv: Precision::Exact(8),
2113                right_min: Some(0),
2114                right_max: Some(100),
2115                expected: Precision::Inexact(10),
2116            },
2117            NdvTestCase {
2118                name: "partial overlap",
2119                left_ndv: Precision::Exact(100),
2120                left_min: Some(0),
2121                left_max: Some(100),
2122                right_ndv: Precision::Exact(50),
2123                right_min: Some(50),
2124                right_max: Some(150),
2125                expected: Precision::Inexact(125),
2126            },
2127            NdvTestCase {
2128                name: "right contained in left",
2129                left_ndv: Precision::Exact(100),
2130                left_min: Some(0),
2131                left_max: Some(100),
2132                right_ndv: Precision::Exact(50),
2133                right_min: Some(25),
2134                right_max: Some(75),
2135                expected: Precision::Inexact(100),
2136            },
2137            NdvTestCase {
2138                name: "same constant value",
2139                left_ndv: Precision::Exact(1),
2140                left_min: Some(5),
2141                left_max: Some(5),
2142                right_ndv: Precision::Exact(1),
2143                right_min: Some(5),
2144                right_max: Some(5),
2145                expected: Precision::Inexact(1),
2146            },
2147            NdvTestCase {
2148                name: "different constant values",
2149                left_ndv: Precision::Exact(1),
2150                left_min: Some(5),
2151                left_max: Some(5),
2152                right_ndv: Precision::Exact(1),
2153                right_min: Some(10),
2154                right_max: Some(10),
2155                expected: Precision::Inexact(2),
2156            },
2157            NdvTestCase {
2158                name: "left constant within right range",
2159                left_ndv: Precision::Exact(1),
2160                left_min: Some(5),
2161                left_max: Some(5),
2162                right_ndv: Precision::Exact(10),
2163                right_min: Some(0),
2164                right_max: Some(10),
2165                expected: Precision::Inexact(10),
2166            },
2167            NdvTestCase {
2168                name: "left constant outside right range",
2169                left_ndv: Precision::Exact(1),
2170                left_min: Some(20),
2171                left_max: Some(20),
2172                right_ndv: Precision::Exact(10),
2173                right_min: Some(0),
2174                right_max: Some(10),
2175                expected: Precision::Inexact(11),
2176            },
2177            NdvTestCase {
2178                name: "right constant within left range",
2179                left_ndv: Precision::Exact(10),
2180                left_min: Some(0),
2181                left_max: Some(10),
2182                right_ndv: Precision::Exact(1),
2183                right_min: Some(5),
2184                right_max: Some(5),
2185                expected: Precision::Inexact(10),
2186            },
2187            NdvTestCase {
2188                name: "right constant outside left range",
2189                left_ndv: Precision::Exact(10),
2190                left_min: Some(0),
2191                left_max: Some(10),
2192                right_ndv: Precision::Exact(1),
2193                right_min: Some(20),
2194                right_max: Some(20),
2195                expected: Precision::Inexact(11),
2196            },
2197            NdvTestCase {
2198                name: "missing bounds exact plus exact",
2199                left_ndv: Precision::Exact(10),
2200                left_min: None,
2201                left_max: None,
2202                right_ndv: Precision::Exact(5),
2203                right_min: None,
2204                right_max: None,
2205                expected: Precision::Inexact(15),
2206            },
2207            NdvTestCase {
2208                name: "missing bounds exact plus inexact",
2209                left_ndv: Precision::Exact(10),
2210                left_min: None,
2211                left_max: None,
2212                right_ndv: Precision::Inexact(5),
2213                right_min: None,
2214                right_max: None,
2215                expected: Precision::Inexact(15),
2216            },
2217            NdvTestCase {
2218                name: "missing bounds inexact plus inexact",
2219                left_ndv: Precision::Inexact(7),
2220                left_min: None,
2221                left_max: None,
2222                right_ndv: Precision::Inexact(3),
2223                right_min: None,
2224                right_max: None,
2225                expected: Precision::Inexact(10),
2226            },
2227            NdvTestCase {
2228                name: "exact plus absent",
2229                left_ndv: Precision::Exact(10),
2230                left_min: None,
2231                left_max: None,
2232                right_ndv: Precision::Absent,
2233                right_min: None,
2234                right_max: None,
2235                expected: Precision::Absent,
2236            },
2237            NdvTestCase {
2238                name: "inexact plus absent",
2239                left_ndv: Precision::Inexact(4),
2240                left_min: None,
2241                left_max: None,
2242                right_ndv: Precision::Absent,
2243                right_min: None,
2244                right_max: None,
2245                expected: Precision::Absent,
2246            },
2247        ];
2248
2249        for case in cases {
2250            let actual = merge_single_i64_ndv_distinct_count(
2251                make_single_i64_ndv_stats(case.left_ndv, case.left_min, case.left_max),
2252                make_single_i64_ndv_stats(case.right_ndv, case.right_min, case.right_max),
2253                NdvFallback::Sum,
2254            );
2255
2256            assert_eq!(actual, case.expected, "case {} failed", case.name);
2257        }
2258    }
2259
2260    #[test]
2261    fn test_with_fetch_basic_preservation() {
2262        // Test that column statistics and byte size are preserved (as inexact) when applying fetch
2263        let original_stats = Statistics {
2264            num_rows: Precision::Exact(1000),
2265            total_byte_size: Precision::Exact(8000),
2266            column_statistics: vec![
2267                ColumnStatistics {
2268                    null_count: Precision::Exact(10),
2269                    max_value: Precision::Exact(ScalarValue::Int32(Some(100))),
2270                    min_value: Precision::Exact(ScalarValue::Int32(Some(0))),
2271                    sum_value: Precision::Exact(ScalarValue::Int32(Some(5050))),
2272                    distinct_count: Precision::Exact(50),
2273                    byte_size: Precision::Exact(4000),
2274                },
2275                ColumnStatistics {
2276                    null_count: Precision::Exact(20),
2277                    max_value: Precision::Exact(ScalarValue::Int64(Some(200))),
2278                    min_value: Precision::Exact(ScalarValue::Int64(Some(10))),
2279                    sum_value: Precision::Exact(ScalarValue::Int64(Some(10100))),
2280                    distinct_count: Precision::Exact(75),
2281                    byte_size: Precision::Exact(8000),
2282                },
2283            ],
2284        };
2285
2286        // Apply fetch of 100 rows (10% of original)
2287        let result = original_stats.clone().with_fetch(Some(100), 0, 1).unwrap();
2288
2289        // Check num_rows
2290        assert_eq!(result.num_rows, Precision::Exact(100));
2291
2292        // Check total_byte_size is computed as sum of scaled column byte_size values
2293        // Column 1: 4000 * 0.1 = 400, Column 2: 8000 * 0.1 = 800, Sum = 1200
2294        assert_eq!(result.total_byte_size, Precision::Inexact(1200));
2295
2296        // Check column statistics are preserved but marked as inexact
2297        assert_eq!(result.column_statistics.len(), 2);
2298
2299        // First column
2300        assert_eq!(
2301            result.column_statistics[0].null_count,
2302            Precision::Inexact(10)
2303        );
2304        assert_eq!(
2305            result.column_statistics[0].max_value,
2306            Precision::Inexact(ScalarValue::Int32(Some(100)))
2307        );
2308        assert_eq!(
2309            result.column_statistics[0].min_value,
2310            Precision::Inexact(ScalarValue::Int32(Some(0)))
2311        );
2312        assert_eq!(
2313            result.column_statistics[0].sum_value,
2314            Precision::Inexact(ScalarValue::Int32(Some(5050)))
2315        );
2316        assert_eq!(
2317            result.column_statistics[0].distinct_count,
2318            Precision::Inexact(50)
2319        );
2320
2321        // Second column
2322        assert_eq!(
2323            result.column_statistics[1].null_count,
2324            Precision::Inexact(20)
2325        );
2326        assert_eq!(
2327            result.column_statistics[1].max_value,
2328            Precision::Inexact(ScalarValue::Int64(Some(200)))
2329        );
2330        assert_eq!(
2331            result.column_statistics[1].min_value,
2332            Precision::Inexact(ScalarValue::Int64(Some(10)))
2333        );
2334        assert_eq!(
2335            result.column_statistics[1].sum_value,
2336            Precision::Inexact(ScalarValue::Int64(Some(10100)))
2337        );
2338        assert_eq!(
2339            result.column_statistics[1].distinct_count,
2340            Precision::Inexact(75)
2341        );
2342    }
2343
2344    #[test]
2345    fn test_with_fetch_inexact_input() {
2346        // Test that inexact input statistics remain inexact
2347        let original_stats = Statistics {
2348            num_rows: Precision::Inexact(1000),
2349            total_byte_size: Precision::Inexact(8000),
2350            column_statistics: vec![ColumnStatistics {
2351                null_count: Precision::Inexact(10),
2352                max_value: Precision::Inexact(ScalarValue::Int32(Some(100))),
2353                min_value: Precision::Inexact(ScalarValue::Int32(Some(0))),
2354                sum_value: Precision::Inexact(ScalarValue::Int32(Some(5050))),
2355                distinct_count: Precision::Inexact(50),
2356                byte_size: Precision::Inexact(4000),
2357            }],
2358        };
2359
2360        let result = original_stats.clone().with_fetch(Some(500), 0, 1).unwrap();
2361
2362        // Check num_rows is inexact
2363        assert_eq!(result.num_rows, Precision::Inexact(500));
2364
2365        // Check total_byte_size is computed as sum of scaled column byte_size values
2366        // Column 1: 4000 * 0.5 = 2000, Sum = 2000
2367        assert_eq!(result.total_byte_size, Precision::Inexact(2000));
2368
2369        // Column stats remain inexact
2370        assert_eq!(
2371            result.column_statistics[0].null_count,
2372            Precision::Inexact(10)
2373        );
2374    }
2375
2376    #[test]
2377    fn test_with_fetch_skip_all_rows() {
2378        // Test when skip >= num_rows (all rows are skipped)
2379        let original_stats = Statistics {
2380            num_rows: Precision::Exact(100),
2381            total_byte_size: Precision::Exact(800),
2382            column_statistics: vec![col_stats_i64(10)],
2383        };
2384
2385        let result = original_stats.clone().with_fetch(Some(50), 100, 1).unwrap();
2386
2387        assert_eq!(result.num_rows, Precision::Exact(0));
2388        // When ratio is 0/100 = 0, byte size should be 0
2389        assert_eq!(result.total_byte_size, Precision::Inexact(0));
2390    }
2391
2392    #[test]
2393    fn test_with_fetch_skip_all_rows_inexact() {
2394        // When the input num_rows is Inexact (an upper-bound estimate), an
2395        // `nr <= skip` outcome must remain Inexact: the estimate could be
2396        // wrong, so we cannot promote 0 to Exact.
2397        let original_stats = Statistics {
2398            num_rows: Precision::Inexact(0),
2399            total_byte_size: Precision::Inexact(0),
2400            column_statistics: vec![col_stats_i64(10)],
2401        };
2402
2403        let result = original_stats.clone().with_fetch(None, 0, 1).unwrap();
2404
2405        assert_eq!(result.num_rows, Precision::Inexact(0));
2406    }
2407
2408    #[test]
2409    fn test_with_fetch_no_limit() {
2410        // Test when fetch is None and skip is 0 (no limit applied)
2411        let original_stats = Statistics {
2412            num_rows: Precision::Exact(100),
2413            total_byte_size: Precision::Exact(800),
2414            column_statistics: vec![col_stats_i64(10)],
2415        };
2416
2417        let result = original_stats.clone().with_fetch(None, 0, 1).unwrap();
2418
2419        // Stats should be unchanged when no fetch and no skip
2420        assert_eq!(result.num_rows, Precision::Exact(100));
2421        assert_eq!(result.total_byte_size, Precision::Exact(800));
2422    }
2423
2424    #[test]
2425    fn test_with_fetch_no_limit_preserves_absent_num_rows() {
2426        let original_stats = Statistics {
2427            num_rows: Precision::Absent,
2428            total_byte_size: Precision::Exact(800),
2429            column_statistics: vec![col_stats_i64(10)],
2430        };
2431
2432        let result = original_stats.clone().with_fetch(None, 0, 1).unwrap();
2433
2434        assert_eq!(result, original_stats);
2435    }
2436
2437    #[test]
2438    fn test_with_fetch_absent_num_rows_does_not_zero_byte_size() {
2439        let original_stats = Statistics {
2440            num_rows: Precision::Absent,
2441            total_byte_size: Precision::Exact(800),
2442            column_statistics: vec![col_stats_i64(10)],
2443        };
2444
2445        let result = original_stats.with_fetch(Some(1), 0, 1).unwrap();
2446
2447        assert_eq!(result.num_rows, Precision::Inexact(1));
2448        assert_eq!(result.total_byte_size, Precision::Absent);
2449        assert_eq!(result.column_statistics[0].byte_size, Precision::Absent);
2450        assert_eq!(
2451            result.column_statistics[0].distinct_count,
2452            Precision::Inexact(1)
2453        );
2454    }
2455
2456    #[test]
2457    fn test_with_fetch_with_skip() {
2458        // Test with both skip and fetch
2459        let original_stats = Statistics {
2460            num_rows: Precision::Exact(1000),
2461            total_byte_size: Precision::Exact(8000),
2462            column_statistics: vec![col_stats_i64(10)],
2463        };
2464
2465        // Skip 200, fetch 300, so we get rows 200-500
2466        let result = original_stats
2467            .clone()
2468            .with_fetch(Some(300), 200, 1)
2469            .unwrap();
2470
2471        assert_eq!(result.num_rows, Precision::Exact(300));
2472        // Column 1: byte_size 800 * (300/500) = 240, Sum = 240
2473        assert_eq!(result.total_byte_size, Precision::Inexact(240));
2474    }
2475
2476    #[test]
2477    fn test_with_fetch_multi_partition() {
2478        // Test with multiple partitions
2479        let original_stats = Statistics {
2480            num_rows: Precision::Exact(1000), // per partition
2481            total_byte_size: Precision::Exact(8000),
2482            column_statistics: vec![col_stats_i64(10)],
2483        };
2484
2485        // Fetch 100 per partition, 4 partitions = 400 total
2486        let result = original_stats.clone().with_fetch(Some(100), 0, 4).unwrap();
2487
2488        assert_eq!(result.num_rows, Precision::Exact(400));
2489        // Column 1: byte_size 800 * 0.4 = 320, Sum = 320
2490        assert_eq!(result.total_byte_size, Precision::Inexact(320));
2491    }
2492
2493    #[test]
2494    fn test_with_fetch_absent_stats() {
2495        // Test with absent statistics
2496        let original_stats = Statistics {
2497            num_rows: Precision::Absent,
2498            total_byte_size: Precision::Absent,
2499            column_statistics: vec![ColumnStatistics {
2500                null_count: Precision::Absent,
2501                max_value: Precision::Absent,
2502                min_value: Precision::Absent,
2503                sum_value: Precision::Absent,
2504                distinct_count: Precision::Absent,
2505                byte_size: Precision::Absent,
2506            }],
2507        };
2508
2509        let result = original_stats.clone().with_fetch(Some(100), 0, 1).unwrap();
2510
2511        // With absent input stats, output should be inexact estimate
2512        assert_eq!(result.num_rows, Precision::Inexact(100));
2513        assert_eq!(result.total_byte_size, Precision::Absent);
2514        // Column stats should remain absent
2515        assert_eq!(result.column_statistics[0].null_count, Precision::Absent);
2516    }
2517
2518    #[test]
2519    fn test_with_fetch_fetch_exceeds_rows() {
2520        // Test when fetch is larger than available rows after skip
2521        let original_stats = Statistics {
2522            num_rows: Precision::Exact(100),
2523            total_byte_size: Precision::Exact(800),
2524            column_statistics: vec![col_stats_i64(10)],
2525        };
2526
2527        // Skip 50, fetch 100, but only 50 rows remain
2528        let result = original_stats.clone().with_fetch(Some(100), 50, 1).unwrap();
2529
2530        assert_eq!(result.num_rows, Precision::Exact(50));
2531        // 50/100 = 0.5, so 800 * 0.5 = 400
2532        assert_eq!(result.total_byte_size, Precision::Inexact(400));
2533    }
2534
2535    #[test]
2536    fn test_with_fetch_preserves_all_column_stats() {
2537        // Comprehensive test that all column statistic fields are preserved
2538        let original_col_stats = ColumnStatistics {
2539            null_count: Precision::Exact(42),
2540            max_value: Precision::Exact(ScalarValue::Int32(Some(999))),
2541            min_value: Precision::Exact(ScalarValue::Int32(Some(-100))),
2542            sum_value: Precision::Exact(ScalarValue::Int32(Some(123456))),
2543            distinct_count: Precision::Exact(789),
2544            byte_size: Precision::Exact(4000),
2545        };
2546
2547        let original_stats = Statistics {
2548            num_rows: Precision::Exact(1000),
2549            total_byte_size: Precision::Exact(8000),
2550            column_statistics: vec![original_col_stats.clone()],
2551        };
2552
2553        let result = original_stats.with_fetch(Some(250), 0, 1).unwrap();
2554
2555        let result_col_stats = &result.column_statistics[0];
2556
2557        // All values should be preserved but marked as inexact
2558        assert_eq!(result_col_stats.null_count, Precision::Inexact(42));
2559        assert_eq!(
2560            result_col_stats.max_value,
2561            Precision::Inexact(ScalarValue::Int32(Some(999)))
2562        );
2563        assert_eq!(
2564            result_col_stats.min_value,
2565            Precision::Inexact(ScalarValue::Int32(Some(-100)))
2566        );
2567        assert_eq!(
2568            result_col_stats.sum_value,
2569            Precision::Inexact(ScalarValue::Int32(Some(123456)))
2570        );
2571        // NDV is capped at the new row count (250) since 789 > 250
2572        assert_eq!(result_col_stats.distinct_count, Precision::Inexact(250));
2573    }
2574
2575    #[test]
2576    fn test_byte_size_to_inexact() {
2577        let col_stats = ColumnStatistics {
2578            null_count: Precision::Exact(10),
2579            max_value: Precision::Absent,
2580            min_value: Precision::Absent,
2581            sum_value: Precision::Absent,
2582            distinct_count: Precision::Absent,
2583            byte_size: Precision::Exact(5000),
2584        };
2585
2586        let inexact = col_stats.to_inexact();
2587        assert_eq!(inexact.byte_size, Precision::Inexact(5000));
2588    }
2589
2590    #[test]
2591    fn test_with_byte_size_builder() {
2592        let col_stats =
2593            ColumnStatistics::new_unknown().with_byte_size(Precision::Exact(8192));
2594        assert_eq!(col_stats.byte_size, Precision::Exact(8192));
2595    }
2596
2597    #[test]
2598    fn test_with_sum_value_builder_widens_small_integers() {
2599        let col_stats = ColumnStatistics::new_unknown()
2600            .with_sum_value(Precision::Exact(ScalarValue::UInt32(Some(123))));
2601        assert_eq!(
2602            col_stats.sum_value,
2603            Precision::Exact(ScalarValue::UInt64(Some(123)))
2604        );
2605    }
2606
2607    #[test]
2608    fn test_with_fetch_scales_byte_size() {
2609        // Test that byte_size is scaled by the row ratio in with_fetch
2610        let original_stats = Statistics {
2611            num_rows: Precision::Exact(1000),
2612            total_byte_size: Precision::Exact(8000),
2613            column_statistics: vec![
2614                ColumnStatistics {
2615                    null_count: Precision::Exact(10),
2616                    max_value: Precision::Absent,
2617                    min_value: Precision::Absent,
2618                    sum_value: Precision::Absent,
2619                    distinct_count: Precision::Absent,
2620                    byte_size: Precision::Exact(4000),
2621                },
2622                ColumnStatistics {
2623                    null_count: Precision::Exact(20),
2624                    max_value: Precision::Absent,
2625                    min_value: Precision::Absent,
2626                    sum_value: Precision::Absent,
2627                    distinct_count: Precision::Absent,
2628                    byte_size: Precision::Exact(8000),
2629                },
2630            ],
2631        };
2632
2633        // Apply fetch of 100 rows (10% of original)
2634        let result = original_stats.with_fetch(Some(100), 0, 1).unwrap();
2635
2636        // byte_size should be scaled: 4000 * 0.1 = 400, 8000 * 0.1 = 800
2637        assert_eq!(
2638            result.column_statistics[0].byte_size,
2639            Precision::Inexact(400)
2640        );
2641        assert_eq!(
2642            result.column_statistics[1].byte_size,
2643            Precision::Inexact(800)
2644        );
2645
2646        // total_byte_size should be computed as sum of byte_size values: 400 + 800 = 1200
2647        assert_eq!(result.total_byte_size, Precision::Inexact(1200));
2648    }
2649
2650    #[test]
2651    fn test_with_fetch_total_byte_size_fallback() {
2652        // Test that total_byte_size falls back to scaling when not all columns have byte_size
2653        let original_stats = Statistics {
2654            num_rows: Precision::Exact(1000),
2655            total_byte_size: Precision::Exact(8000),
2656            column_statistics: vec![
2657                ColumnStatistics {
2658                    null_count: Precision::Exact(10),
2659                    max_value: Precision::Absent,
2660                    min_value: Precision::Absent,
2661                    sum_value: Precision::Absent,
2662                    distinct_count: Precision::Absent,
2663                    byte_size: Precision::Exact(4000),
2664                },
2665                ColumnStatistics {
2666                    null_count: Precision::Exact(20),
2667                    max_value: Precision::Absent,
2668                    min_value: Precision::Absent,
2669                    sum_value: Precision::Absent,
2670                    distinct_count: Precision::Absent,
2671                    byte_size: Precision::Absent, // One column has no byte_size
2672                },
2673            ],
2674        };
2675
2676        // Apply fetch of 100 rows (10% of original)
2677        let result = original_stats.with_fetch(Some(100), 0, 1).unwrap();
2678
2679        // total_byte_size should fall back to scaling: 8000 * 0.1 = 800
2680        assert_eq!(result.total_byte_size, Precision::Inexact(800));
2681    }
2682
2683    #[test]
2684    fn test_with_fetch_caps_ndv_at_row_count() {
2685        // NDV=500 but after LIMIT 10, NDV should be capped at 10
2686        let stats = Statistics {
2687            num_rows: Precision::Exact(1000),
2688            total_byte_size: Precision::Exact(8000),
2689            column_statistics: vec![ColumnStatistics {
2690                distinct_count: Precision::Inexact(500),
2691                ..Default::default()
2692            }],
2693        };
2694
2695        let result = stats.with_fetch(Some(10), 0, 1).unwrap();
2696        assert_eq!(result.num_rows, Precision::Exact(10));
2697        assert_eq!(
2698            result.column_statistics[0].distinct_count,
2699            Precision::Inexact(10)
2700        );
2701    }
2702
2703    #[test]
2704    fn test_with_fetch_caps_ndv_with_skip() {
2705        // 1000 rows, NDV=500, OFFSET 5 LIMIT 10
2706        // with_fetch computes num_rows = min(1000 - 5, 10) = 10
2707        // NDV should be capped at 10
2708        let stats = Statistics {
2709            num_rows: Precision::Exact(1000),
2710            total_byte_size: Precision::Exact(8000),
2711            column_statistics: vec![ColumnStatistics {
2712                distinct_count: Precision::Inexact(500),
2713                ..Default::default()
2714            }],
2715        };
2716
2717        let result = stats.with_fetch(Some(10), 5, 1).unwrap();
2718        assert_eq!(result.num_rows, Precision::Exact(10));
2719        assert_eq!(
2720            result.column_statistics[0].distinct_count,
2721            Precision::Inexact(10)
2722        );
2723    }
2724
2725    #[test]
2726    fn test_with_fetch_caps_ndv_with_large_skip() {
2727        // 1000 rows, NDV=500, OFFSET 995 LIMIT 100
2728        // with_fetch computes num_rows = min(1000 - 995, 100) = 5
2729        // NDV should be capped at 5
2730        let stats = Statistics {
2731            num_rows: Precision::Exact(1000),
2732            total_byte_size: Precision::Exact(8000),
2733            column_statistics: vec![ColumnStatistics {
2734                distinct_count: Precision::Inexact(500),
2735                ..Default::default()
2736            }],
2737        };
2738
2739        let result = stats.with_fetch(Some(100), 995, 1).unwrap();
2740        assert_eq!(result.num_rows, Precision::Exact(5));
2741        assert_eq!(
2742            result.column_statistics[0].distinct_count,
2743            Precision::Inexact(5)
2744        );
2745    }
2746
2747    #[test]
2748    fn test_with_fetch_ndv_below_row_count_unchanged() {
2749        // NDV=5 and LIMIT 10: NDV should stay at 5
2750        let stats = Statistics {
2751            num_rows: Precision::Exact(1000),
2752            total_byte_size: Precision::Exact(8000),
2753            column_statistics: vec![ColumnStatistics {
2754                distinct_count: Precision::Inexact(5),
2755                ..Default::default()
2756            }],
2757        };
2758
2759        let result = stats.with_fetch(Some(10), 0, 1).unwrap();
2760        assert_eq!(result.num_rows, Precision::Exact(10));
2761        assert_eq!(
2762            result.column_statistics[0].distinct_count,
2763            Precision::Inexact(5)
2764        );
2765    }
2766
2767    #[test]
2768    fn test_try_merge_iter_basic() {
2769        let schema = Arc::new(Schema::new(vec![
2770            Field::new("col1", DataType::Int32, false),
2771            Field::new("col2", DataType::Int32, false),
2772        ]));
2773
2774        let stats1 = Statistics {
2775            num_rows: Precision::Exact(10),
2776            total_byte_size: Precision::Exact(100),
2777            column_statistics: vec![
2778                ColumnStatistics {
2779                    null_count: Precision::Exact(1),
2780                    max_value: Precision::Exact(ScalarValue::Int32(Some(100))),
2781                    min_value: Precision::Exact(ScalarValue::Int32(Some(1))),
2782                    sum_value: Precision::Exact(ScalarValue::Int32(Some(500))),
2783                    distinct_count: Precision::Absent,
2784                    byte_size: Precision::Exact(40),
2785                },
2786                ColumnStatistics {
2787                    null_count: Precision::Exact(2),
2788                    max_value: Precision::Exact(ScalarValue::Int32(Some(200))),
2789                    min_value: Precision::Exact(ScalarValue::Int32(Some(10))),
2790                    sum_value: Precision::Exact(ScalarValue::Int32(Some(1000))),
2791                    distinct_count: Precision::Absent,
2792                    byte_size: Precision::Exact(40),
2793                },
2794            ],
2795        };
2796
2797        let stats2 = Statistics {
2798            num_rows: Precision::Exact(15),
2799            total_byte_size: Precision::Exact(150),
2800            column_statistics: vec![
2801                ColumnStatistics {
2802                    null_count: Precision::Exact(2),
2803                    max_value: Precision::Exact(ScalarValue::Int32(Some(120))),
2804                    min_value: Precision::Exact(ScalarValue::Int32(Some(-10))),
2805                    sum_value: Precision::Exact(ScalarValue::Int32(Some(600))),
2806                    distinct_count: Precision::Absent,
2807                    byte_size: Precision::Exact(60),
2808                },
2809                ColumnStatistics {
2810                    null_count: Precision::Exact(3),
2811                    max_value: Precision::Exact(ScalarValue::Int32(Some(180))),
2812                    min_value: Precision::Exact(ScalarValue::Int32(Some(5))),
2813                    sum_value: Precision::Exact(ScalarValue::Int32(Some(1200))),
2814                    distinct_count: Precision::Absent,
2815                    byte_size: Precision::Exact(60),
2816                },
2817            ],
2818        };
2819
2820        let items = vec![&stats1, &stats2];
2821        let summary_stats = Statistics::try_merge_iter(items, &schema).unwrap();
2822
2823        assert_eq!(summary_stats.num_rows, Precision::Exact(25));
2824        assert_eq!(summary_stats.total_byte_size, Precision::Exact(250));
2825
2826        let col1_stats = &summary_stats.column_statistics[0];
2827        assert_eq!(col1_stats.null_count, Precision::Exact(3));
2828        assert_eq!(
2829            col1_stats.max_value,
2830            Precision::Exact(ScalarValue::Int32(Some(120)))
2831        );
2832        assert_eq!(
2833            col1_stats.min_value,
2834            Precision::Exact(ScalarValue::Int32(Some(-10)))
2835        );
2836        assert_eq!(
2837            col1_stats.sum_value,
2838            Precision::Exact(ScalarValue::Int64(Some(1100)))
2839        );
2840
2841        let col2_stats = &summary_stats.column_statistics[1];
2842        assert_eq!(col2_stats.null_count, Precision::Exact(5));
2843        assert_eq!(
2844            col2_stats.max_value,
2845            Precision::Exact(ScalarValue::Int32(Some(200)))
2846        );
2847        assert_eq!(
2848            col2_stats.min_value,
2849            Precision::Exact(ScalarValue::Int32(Some(5)))
2850        );
2851        assert_eq!(
2852            col2_stats.sum_value,
2853            Precision::Exact(ScalarValue::Int64(Some(2200)))
2854        );
2855    }
2856
2857    #[test]
2858    fn test_try_merge_iter_mixed_precision() {
2859        let schema = Arc::new(Schema::new(vec![Field::new(
2860            "col1",
2861            DataType::Int32,
2862            false,
2863        )]));
2864
2865        let stats1 = Statistics {
2866            num_rows: Precision::Exact(10),
2867            total_byte_size: Precision::Inexact(100),
2868            column_statistics: vec![ColumnStatistics {
2869                null_count: Precision::Exact(1),
2870                max_value: Precision::Exact(ScalarValue::Int32(Some(100))),
2871                min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
2872                sum_value: Precision::Exact(ScalarValue::Int32(Some(500))),
2873                distinct_count: Precision::Absent,
2874                byte_size: Precision::Exact(40),
2875            }],
2876        };
2877
2878        let stats2 = Statistics {
2879            num_rows: Precision::Inexact(15),
2880            total_byte_size: Precision::Exact(150),
2881            column_statistics: vec![ColumnStatistics {
2882                null_count: Precision::Inexact(2),
2883                max_value: Precision::Inexact(ScalarValue::Int32(Some(120))),
2884                min_value: Precision::Exact(ScalarValue::Int32(Some(-10))),
2885                sum_value: Precision::Absent,
2886                distinct_count: Precision::Absent,
2887                byte_size: Precision::Inexact(60),
2888            }],
2889        };
2890
2891        let items = vec![&stats1, &stats2];
2892        let summary_stats = Statistics::try_merge_iter(items, &schema).unwrap();
2893
2894        assert_eq!(summary_stats.num_rows, Precision::Inexact(25));
2895        assert_eq!(summary_stats.total_byte_size, Precision::Inexact(250));
2896
2897        let col_stats = &summary_stats.column_statistics[0];
2898        assert_eq!(col_stats.null_count, Precision::Inexact(3));
2899        assert_eq!(
2900            col_stats.max_value,
2901            Precision::Inexact(ScalarValue::Int32(Some(120)))
2902        );
2903        assert_eq!(
2904            col_stats.min_value,
2905            Precision::Inexact(ScalarValue::Int32(Some(-10)))
2906        );
2907        // sum_value becomes Absent because stats2 has Absent sum
2908        assert_eq!(col_stats.sum_value, Precision::Absent);
2909    }
2910
2911    #[test]
2912    fn test_try_merge_iter_empty() {
2913        let schema = Arc::new(Schema::new(vec![Field::new(
2914            "col1",
2915            DataType::Int32,
2916            false,
2917        )]));
2918
2919        let items: Vec<&Statistics> = vec![];
2920        let summary_stats = Statistics::try_merge_iter(items, &schema).unwrap();
2921
2922        assert_eq!(summary_stats.num_rows, Precision::Absent);
2923        assert_eq!(summary_stats.total_byte_size, Precision::Absent);
2924        assert_eq!(summary_stats.column_statistics.len(), 1);
2925        assert_eq!(
2926            summary_stats.column_statistics[0].null_count,
2927            Precision::Absent
2928        );
2929    }
2930
2931    #[test]
2932    fn test_try_merge_iter_single_item() {
2933        let schema = Arc::new(Schema::new(vec![Field::new(
2934            "col1",
2935            DataType::Int32,
2936            false,
2937        )]));
2938
2939        let stats = Statistics {
2940            num_rows: Precision::Exact(10),
2941            total_byte_size: Precision::Exact(100),
2942            column_statistics: vec![ColumnStatistics {
2943                null_count: Precision::Exact(1),
2944                max_value: Precision::Exact(ScalarValue::Int32(Some(100))),
2945                min_value: Precision::Exact(ScalarValue::Int32(Some(1))),
2946                sum_value: Precision::Exact(ScalarValue::Int32(Some(500))),
2947                distinct_count: Precision::Exact(10),
2948                byte_size: Precision::Exact(40),
2949            }],
2950        };
2951
2952        let items = vec![&stats];
2953        let summary_stats = Statistics::try_merge_iter(items, &schema).unwrap();
2954
2955        assert_eq!(summary_stats, stats);
2956    }
2957
2958    #[test]
2959    fn test_try_merge_iter_mismatched_columns() {
2960        let schema = Arc::new(Schema::new(vec![Field::new(
2961            "col1",
2962            DataType::Int32,
2963            false,
2964        )]));
2965
2966        let stats1 = Statistics::default();
2967        let stats2 =
2968            Statistics::default().add_column_statistics(ColumnStatistics::new_unknown());
2969
2970        let items = vec![&stats1, &stats2];
2971        let e = Statistics::try_merge_iter(items, &schema).unwrap_err();
2972        assert_contains!(
2973            e.to_string(),
2974            "Cannot merge statistics with different number of columns: 0 vs 1"
2975        );
2976    }
2977
2978    #[test]
2979    fn test_try_merge_iter_three_items() {
2980        // Verify that merging three items works correctly
2981        let schema = Arc::new(Schema::new(vec![Field::new(
2982            "col1",
2983            DataType::Int64,
2984            false,
2985        )]));
2986
2987        let stats1 = Statistics {
2988            num_rows: Precision::Exact(10),
2989            total_byte_size: Precision::Exact(100),
2990            column_statistics: vec![ColumnStatistics {
2991                null_count: Precision::Exact(1),
2992                max_value: Precision::Exact(ScalarValue::Int64(Some(100))),
2993                min_value: Precision::Exact(ScalarValue::Int64(Some(10))),
2994                sum_value: Precision::Exact(ScalarValue::Int64(Some(500))),
2995                distinct_count: Precision::Exact(8),
2996                byte_size: Precision::Exact(80),
2997            }],
2998        };
2999
3000        let stats2 = Statistics {
3001            num_rows: Precision::Exact(20),
3002            total_byte_size: Precision::Exact(200),
3003            column_statistics: vec![ColumnStatistics {
3004                null_count: Precision::Exact(2),
3005                max_value: Precision::Exact(ScalarValue::Int64(Some(200))),
3006                min_value: Precision::Exact(ScalarValue::Int64(Some(5))),
3007                sum_value: Precision::Exact(ScalarValue::Int64(Some(1000))),
3008                distinct_count: Precision::Exact(15),
3009                byte_size: Precision::Exact(160),
3010            }],
3011        };
3012
3013        let stats3 = Statistics {
3014            num_rows: Precision::Exact(30),
3015            total_byte_size: Precision::Exact(300),
3016            column_statistics: vec![ColumnStatistics {
3017                null_count: Precision::Exact(3),
3018                max_value: Precision::Exact(ScalarValue::Int64(Some(150))),
3019                min_value: Precision::Exact(ScalarValue::Int64(Some(1))),
3020                sum_value: Precision::Exact(ScalarValue::Int64(Some(2000))),
3021                distinct_count: Precision::Exact(25),
3022                byte_size: Precision::Exact(240),
3023            }],
3024        };
3025
3026        let items = vec![&stats1, &stats2, &stats3];
3027        let summary_stats = Statistics::try_merge_iter(items, &schema).unwrap();
3028
3029        assert_eq!(summary_stats.num_rows, Precision::Exact(60));
3030        assert_eq!(summary_stats.total_byte_size, Precision::Exact(600));
3031
3032        let col_stats = &summary_stats.column_statistics[0];
3033        assert_eq!(col_stats.null_count, Precision::Exact(6));
3034        assert_eq!(
3035            col_stats.max_value,
3036            Precision::Exact(ScalarValue::Int64(Some(200)))
3037        );
3038        assert_eq!(
3039            col_stats.min_value,
3040            Precision::Exact(ScalarValue::Int64(Some(1)))
3041        );
3042        assert_eq!(
3043            col_stats.sum_value,
3044            Precision::Exact(ScalarValue::Int64(Some(3500)))
3045        );
3046        assert_eq!(col_stats.byte_size, Precision::Exact(480));
3047        // Overlap-based NDV merge (pairwise left-to-right):
3048        // stats1+stats2: [10,100]+[5,200] -> NDV=16, then +stats3: [5,200]+[1,150] -> NDV=29
3049        assert_eq!(col_stats.distinct_count, Precision::Inexact(29));
3050    }
3051
3052    #[test]
3053    fn test_try_merge_iter_float_types() {
3054        let schema = Arc::new(Schema::new(vec![Field::new(
3055            "col1",
3056            DataType::Float64,
3057            false,
3058        )]));
3059
3060        let stats1 = Statistics {
3061            num_rows: Precision::Exact(10),
3062            total_byte_size: Precision::Exact(80),
3063            column_statistics: vec![ColumnStatistics {
3064                null_count: Precision::Exact(0),
3065                max_value: Precision::Exact(ScalarValue::Float64(Some(99.9))),
3066                min_value: Precision::Exact(ScalarValue::Float64(Some(1.1))),
3067                sum_value: Precision::Exact(ScalarValue::Float64(Some(500.5))),
3068                distinct_count: Precision::Absent,
3069                byte_size: Precision::Exact(80),
3070            }],
3071        };
3072
3073        let stats2 = Statistics {
3074            num_rows: Precision::Exact(10),
3075            total_byte_size: Precision::Exact(80),
3076            column_statistics: vec![ColumnStatistics {
3077                null_count: Precision::Exact(0),
3078                max_value: Precision::Exact(ScalarValue::Float64(Some(200.0))),
3079                min_value: Precision::Exact(ScalarValue::Float64(Some(0.5))),
3080                sum_value: Precision::Exact(ScalarValue::Float64(Some(1000.0))),
3081                distinct_count: Precision::Absent,
3082                byte_size: Precision::Exact(80),
3083            }],
3084        };
3085
3086        let items = vec![&stats1, &stats2];
3087        let summary_stats = Statistics::try_merge_iter(items, &schema).unwrap();
3088
3089        let col_stats = &summary_stats.column_statistics[0];
3090        assert_eq!(
3091            col_stats.max_value,
3092            Precision::Exact(ScalarValue::Float64(Some(200.0)))
3093        );
3094        assert_eq!(
3095            col_stats.min_value,
3096            Precision::Exact(ScalarValue::Float64(Some(0.5)))
3097        );
3098        assert_eq!(
3099            col_stats.sum_value,
3100            Precision::Exact(ScalarValue::Float64(Some(1500.5)))
3101        );
3102    }
3103
3104    #[test]
3105    fn test_try_merge_iter_string_types() {
3106        let schema =
3107            Arc::new(Schema::new(vec![Field::new("col1", DataType::Utf8, false)]));
3108
3109        let stats1 = Statistics {
3110            num_rows: Precision::Exact(10),
3111            total_byte_size: Precision::Exact(100),
3112            column_statistics: vec![ColumnStatistics {
3113                null_count: Precision::Exact(0),
3114                max_value: Precision::Exact(ScalarValue::Utf8(Some("dog".to_string()))),
3115                min_value: Precision::Exact(ScalarValue::Utf8(Some("ant".to_string()))),
3116                sum_value: Precision::Absent,
3117                distinct_count: Precision::Absent,
3118                byte_size: Precision::Exact(100),
3119            }],
3120        };
3121
3122        let stats2 = Statistics {
3123            num_rows: Precision::Exact(10),
3124            total_byte_size: Precision::Exact(100),
3125            column_statistics: vec![ColumnStatistics {
3126                null_count: Precision::Exact(0),
3127                max_value: Precision::Exact(ScalarValue::Utf8(Some("zebra".to_string()))),
3128                min_value: Precision::Exact(ScalarValue::Utf8(Some("bat".to_string()))),
3129                sum_value: Precision::Absent,
3130                distinct_count: Precision::Absent,
3131                byte_size: Precision::Exact(100),
3132            }],
3133        };
3134
3135        let items = vec![&stats1, &stats2];
3136        let summary_stats = Statistics::try_merge_iter(items, &schema).unwrap();
3137
3138        let col_stats = &summary_stats.column_statistics[0];
3139        assert_eq!(
3140            col_stats.max_value,
3141            Precision::Exact(ScalarValue::Utf8(Some("zebra".to_string())))
3142        );
3143        assert_eq!(
3144            col_stats.min_value,
3145            Precision::Exact(ScalarValue::Utf8(Some("ant".to_string())))
3146        );
3147        assert_eq!(col_stats.sum_value, Precision::Absent);
3148    }
3149
3150    #[test]
3151    fn test_try_merge_iter_all_inexact() {
3152        let schema = Arc::new(Schema::new(vec![Field::new(
3153            "col1",
3154            DataType::Int32,
3155            false,
3156        )]));
3157
3158        let stats1 = Statistics {
3159            num_rows: Precision::Inexact(10),
3160            total_byte_size: Precision::Inexact(100),
3161            column_statistics: vec![ColumnStatistics {
3162                null_count: Precision::Inexact(1),
3163                max_value: Precision::Inexact(ScalarValue::Int32(Some(100))),
3164                min_value: Precision::Inexact(ScalarValue::Int32(Some(1))),
3165                sum_value: Precision::Inexact(ScalarValue::Int32(Some(500))),
3166                distinct_count: Precision::Absent,
3167                byte_size: Precision::Inexact(40),
3168            }],
3169        };
3170
3171        let stats2 = Statistics {
3172            num_rows: Precision::Inexact(20),
3173            total_byte_size: Precision::Inexact(200),
3174            column_statistics: vec![ColumnStatistics {
3175                null_count: Precision::Inexact(2),
3176                max_value: Precision::Inexact(ScalarValue::Int32(Some(200))),
3177                min_value: Precision::Inexact(ScalarValue::Int32(Some(-5))),
3178                sum_value: Precision::Inexact(ScalarValue::Int32(Some(1000))),
3179                distinct_count: Precision::Absent,
3180                byte_size: Precision::Inexact(60),
3181            }],
3182        };
3183
3184        let items = vec![&stats1, &stats2];
3185        let summary_stats = Statistics::try_merge_iter(items, &schema).unwrap();
3186
3187        assert_eq!(summary_stats.num_rows, Precision::Inexact(30));
3188        assert_eq!(summary_stats.total_byte_size, Precision::Inexact(300));
3189
3190        let col_stats = &summary_stats.column_statistics[0];
3191        assert_eq!(col_stats.null_count, Precision::Inexact(3));
3192        assert_eq!(
3193            col_stats.max_value,
3194            Precision::Inexact(ScalarValue::Int32(Some(200)))
3195        );
3196        assert_eq!(
3197            col_stats.min_value,
3198            Precision::Inexact(ScalarValue::Int32(Some(-5)))
3199        );
3200        assert_eq!(
3201            col_stats.sum_value,
3202            Precision::Inexact(ScalarValue::Int64(Some(1500)))
3203        );
3204    }
3205
3206    #[test]
3207    fn test_precision_min_in_place() {
3208        // Exact vs Exact: keeps the smaller
3209        let mut lhs = Precision::Exact(10);
3210        precision_min(&mut lhs, &Precision::Exact(20));
3211        assert_eq!(lhs, Precision::Exact(10));
3212
3213        let mut lhs = Precision::Exact(20);
3214        precision_min(&mut lhs, &Precision::Exact(10));
3215        assert_eq!(lhs, Precision::Exact(10));
3216
3217        // Equal exact values
3218        let mut lhs = Precision::Exact(5);
3219        precision_min(&mut lhs, &Precision::Exact(5));
3220        assert_eq!(lhs, Precision::Exact(5));
3221
3222        // Mixed exact/inexact: result is Inexact with smaller value
3223        let mut lhs = Precision::Exact(10);
3224        precision_min(&mut lhs, &Precision::Inexact(20));
3225        assert_eq!(lhs, Precision::Inexact(10));
3226
3227        let mut lhs = Precision::Inexact(10);
3228        precision_min(&mut lhs, &Precision::Exact(5));
3229        assert_eq!(lhs, Precision::Inexact(5));
3230
3231        // Inexact vs Inexact
3232        let mut lhs = Precision::Inexact(30);
3233        precision_min(&mut lhs, &Precision::Inexact(20));
3234        assert_eq!(lhs, Precision::Inexact(20));
3235
3236        // Absent makes result Absent
3237        let mut lhs = Precision::Exact(10);
3238        precision_min(&mut lhs, &Precision::Absent);
3239        assert_eq!(lhs, Precision::Absent);
3240
3241        let mut lhs = Precision::<i32>::Absent;
3242        precision_min(&mut lhs, &Precision::Exact(10));
3243        assert_eq!(lhs, Precision::Absent);
3244    }
3245
3246    #[test]
3247    fn test_precision_max_in_place() {
3248        // Exact vs Exact: keeps the larger
3249        let mut lhs = Precision::Exact(10);
3250        precision_max(&mut lhs, &Precision::Exact(20));
3251        assert_eq!(lhs, Precision::Exact(20));
3252
3253        let mut lhs = Precision::Exact(20);
3254        precision_max(&mut lhs, &Precision::Exact(10));
3255        assert_eq!(lhs, Precision::Exact(20));
3256
3257        // Equal exact values
3258        let mut lhs = Precision::Exact(5);
3259        precision_max(&mut lhs, &Precision::Exact(5));
3260        assert_eq!(lhs, Precision::Exact(5));
3261
3262        // Mixed exact/inexact: result is Inexact with larger value
3263        let mut lhs = Precision::Exact(10);
3264        precision_max(&mut lhs, &Precision::Inexact(20));
3265        assert_eq!(lhs, Precision::Inexact(20));
3266
3267        let mut lhs = Precision::Inexact(10);
3268        precision_max(&mut lhs, &Precision::Exact(5));
3269        assert_eq!(lhs, Precision::Inexact(10));
3270
3271        // Inexact vs Inexact
3272        let mut lhs = Precision::Inexact(20);
3273        precision_max(&mut lhs, &Precision::Inexact(30));
3274        assert_eq!(lhs, Precision::Inexact(30));
3275
3276        // Absent makes result Absent
3277        let mut lhs = Precision::Exact(10);
3278        precision_max(&mut lhs, &Precision::Absent);
3279        assert_eq!(lhs, Precision::Absent);
3280
3281        let mut lhs = Precision::<i32>::Absent;
3282        precision_max(&mut lhs, &Precision::Exact(10));
3283        assert_eq!(lhs, Precision::Absent);
3284    }
3285
3286    #[test]
3287    fn test_cast_sum_value_to_sum_type_in_place_widens_int32() {
3288        let mut value = Precision::Exact(ScalarValue::Int32(Some(42)));
3289        cast_sum_value_to_sum_type_in_place(&mut value);
3290        assert_eq!(value, Precision::Exact(ScalarValue::Int64(Some(42))));
3291    }
3292
3293    #[test]
3294    fn test_cast_sum_value_to_sum_type_in_place_preserves_int64() {
3295        // Int64 is already the sum type for Int64, no widening needed
3296        let mut value = Precision::Exact(ScalarValue::Int64(Some(100)));
3297        cast_sum_value_to_sum_type_in_place(&mut value);
3298        assert_eq!(value, Precision::Exact(ScalarValue::Int64(Some(100))));
3299    }
3300
3301    #[test]
3302    fn test_cast_sum_value_to_sum_type_in_place_inexact() {
3303        let mut value = Precision::Inexact(ScalarValue::Int32(Some(42)));
3304        cast_sum_value_to_sum_type_in_place(&mut value);
3305        assert_eq!(value, Precision::Inexact(ScalarValue::Int64(Some(42))));
3306    }
3307
3308    #[test]
3309    fn test_cast_sum_value_to_sum_type_in_place_absent() {
3310        let mut value = Precision::<ScalarValue>::Absent;
3311        cast_sum_value_to_sum_type_in_place(&mut value);
3312        assert_eq!(value, Precision::Absent);
3313    }
3314
3315    #[test]
3316    fn test_precision_add_for_sum_in_place_same_type() {
3317        // Int64 + Int64: no widening needed, straight add
3318        let mut lhs = Precision::Exact(ScalarValue::Int64(Some(10)));
3319        let rhs = Precision::Exact(ScalarValue::Int64(Some(20)));
3320        precision_add_for_sum_in_place(&mut lhs, &rhs);
3321        assert_eq!(lhs, Precision::Exact(ScalarValue::Int64(Some(30))));
3322    }
3323
3324    #[test]
3325    fn test_precision_add_for_sum_in_place_widens_rhs() {
3326        // lhs is already Int64 (widened), rhs is Int32 -> gets cast to Int64
3327        let mut lhs = Precision::Exact(ScalarValue::Int64(Some(10)));
3328        let rhs = Precision::Exact(ScalarValue::Int32(Some(5)));
3329        precision_add_for_sum_in_place(&mut lhs, &rhs);
3330        assert_eq!(lhs, Precision::Exact(ScalarValue::Int64(Some(15))));
3331    }
3332
3333    #[test]
3334    fn test_precision_add_for_sum_in_place_inexact() {
3335        let mut lhs = Precision::Inexact(ScalarValue::Int64(Some(10)));
3336        let rhs = Precision::Inexact(ScalarValue::Int32(Some(5)));
3337        precision_add_for_sum_in_place(&mut lhs, &rhs);
3338        assert_eq!(lhs, Precision::Inexact(ScalarValue::Int64(Some(15))));
3339    }
3340
3341    #[test]
3342    fn test_precision_add_for_sum_in_place_absent_rhs() {
3343        let mut lhs = Precision::Exact(ScalarValue::Int64(Some(10)));
3344        precision_add_for_sum_in_place(&mut lhs, &Precision::Absent);
3345        assert_eq!(lhs, Precision::Absent);
3346    }
3347
3348    #[test]
3349    fn test_calculate_total_byte_size() {
3350        let primitive_schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]);
3351        let non_primitive_schema =
3352            Schema::new(vec![Field::new("a", DataType::Utf8, false)]);
3353
3354        // All-primitive schema with a known row count computes an exact size.
3355        let mut stats = Statistics::new_unknown(&primitive_schema);
3356        stats.num_rows = Precision::Exact(10);
3357        stats.calculate_total_byte_size(&primitive_schema);
3358        assert_eq!(stats.total_byte_size, Precision::Exact(40));
3359
3360        // All-primitive schema with an unknown row count keeps a previously
3361        // known `total_byte_size`, downgraded to inexact, instead of
3362        // discarding it to `Absent`.
3363        let mut stats = Statistics::new_unknown(&primitive_schema);
3364        stats.total_byte_size = Precision::Exact(1234);
3365        stats.calculate_total_byte_size(&primitive_schema);
3366        assert_eq!(stats.total_byte_size, Precision::Inexact(1234));
3367
3368        // Non-primitive schema always downgrades any existing
3369        // `total_byte_size` to inexact, regardless of `num_rows`.
3370        let mut stats = Statistics::new_unknown(&non_primitive_schema);
3371        stats.num_rows = Precision::Exact(10);
3372        stats.total_byte_size = Precision::Exact(999);
3373        stats.calculate_total_byte_size(&non_primitive_schema);
3374        assert_eq!(stats.total_byte_size, Precision::Inexact(999));
3375    }
3376
3377    #[test]
3378    fn test_is_known_empty() {
3379        let statistics = |num_rows| Statistics {
3380            num_rows,
3381            ..Default::default()
3382        };
3383
3384        assert!(is_known_empty(&statistics(Precision::Exact(0))));
3385        assert!(!is_known_empty(&statistics(Precision::Inexact(0))));
3386        assert!(!is_known_empty(&statistics(Precision::Exact(1))));
3387        assert!(!is_known_empty(&statistics(Precision::Absent)));
3388    }
3389}